repo
stringlengths
1
191
file
stringlengths
23
351
code
stringlengths
0
5.32M
file_length
int64
0
5.32M
avg_line_length
float64
0
2.9k
max_line_length
int64
0
288k
extension_type
stringclasses
1 value
null
wildfly-main/jpa/hibernate6/src/main/java/org/jboss/as/jpa/hibernate/service/WildFlyCustomJtaPlatformInitiator.java
/* * JBoss, Home of Professional Open Source. * Copyright 2022 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.as.jpa.hibernate.service; import java.util.Map; import org.hibernate.engine.transaction.jta.platform.internal.JtaPlatformInitiator; import org.hibernate.engine.transaction.jta.platform.spi.JtaPlatform; import org.hibernate.service.spi.ServiceRegistryImplementor; /** * Custom JtaPlatform initiator for use inside WildFly picking an appropriate * fallback JtaPlatform. * * @author Steve Ebersole */ public class WildFlyCustomJtaPlatformInitiator extends JtaPlatformInitiator { @Override public JtaPlatform initiateService(Map configurationValues, ServiceRegistryImplementor registry) { return new WildFlyCustomJtaPlatform(); } }
1,381
35.368421
102
java
null
wildfly-main/jpa/hibernate6/src/main/java/org/jboss/as/jpa/hibernate/service/WildFlyCustomRegionFactoryInitiator.java
/* * JBoss, Home of Professional Open Source. * Copyright 2022 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.as.jpa.hibernate.service; import static org.hibernate.cfg.AvailableSettings.CACHE_REGION_FACTORY; import static org.hibernate.cfg.AvailableSettings.JAKARTA_SHARED_CACHE_MODE; import static org.hibernate.cfg.AvailableSettings.USE_SECOND_LEVEL_CACHE; import static org.jboss.as.jpa.hibernate.JpaLogger.JPA_LOGGER; import java.util.Map; import org.hibernate.cache.internal.NoCachingRegionFactory; import org.hibernate.cache.internal.RegionFactoryInitiator; import org.hibernate.cache.spi.RegionFactory; import org.hibernate.service.spi.ServiceRegistryImplementor; /** * @author Steve Ebersole * @author Scott Marlow */ public class WildFlyCustomRegionFactoryInitiator extends RegionFactoryInitiator { private static final String INFINISPAN_REGION_FACTORY = "org.infinispan.hibernate.cache.v62.InfinispanRegionFactory"; private static final String UNSPECIFIED = "UNSPECIFIED"; private static final String NONE = "NONE"; @Override protected RegionFactory resolveRegionFactory(Map<String, Object> configurationValues, ServiceRegistryImplementor registry) { final Object useSecondLevelCache = configurationValues.get(USE_SECOND_LEVEL_CACHE); final String jpaSharedCodeModeValue = configurationValues.get(JAKARTA_SHARED_CACHE_MODE) != null ? configurationValues.get(JAKARTA_SHARED_CACHE_MODE).toString() : UNSPECIFIED; final Object regionFactory = configurationValues.get(CACHE_REGION_FACTORY); // treat Hibernate 2lc as off, if not specified. // Note that Hibernate 2lc in 5.1.x, defaults to disabled, so this code is only needed in 5.3.x+. if(Boolean.parseBoolean((String)useSecondLevelCache)) { JPA_LOGGER.tracef("WildFlyCustomRegionFactoryInitiator#resolveRegionFactory using %s for 2lc, useSecondLevelCache=%s, jpaSharedCodeModeValue=%s, regionFactory=%s", INFINISPAN_REGION_FACTORY, useSecondLevelCache,jpaSharedCodeModeValue, regionFactory); configurationValues.put(CACHE_REGION_FACTORY, INFINISPAN_REGION_FACTORY); return super.resolveRegionFactory(configurationValues, registry); } else if(UNSPECIFIED.equals(jpaSharedCodeModeValue) || NONE.equals(jpaSharedCodeModeValue)) { // explicitly disable 2lc cache JPA_LOGGER.tracef("WildFlyCustomRegionFactoryInitiator#resolveRegionFactory not using a 2lc, useSecondLevelCache=%s, jpaSharedCodeModeValue=%s, regionFactory=%s", useSecondLevelCache,jpaSharedCodeModeValue, regionFactory); return NoCachingRegionFactory.INSTANCE; } else { JPA_LOGGER.tracef("WildFlyCustomRegionFactoryInitiator#resolveRegionFactory using %s for 2lc, useSecondLevelCache=%s, jpaSharedCodeModeValue=%s, regionFactory=%s", INFINISPAN_REGION_FACTORY, useSecondLevelCache,jpaSharedCodeModeValue, regionFactory); configurationValues.put(CACHE_REGION_FACTORY, INFINISPAN_REGION_FACTORY); return super.resolveRegionFactory(configurationValues, registry); } } }
3,797
53.257143
183
java
null
wildfly-main/jpa/hibernate6/src/main/java/org/jboss/as/jpa/hibernate/service/ServiceContributorImpl.java
/* * JBoss, Home of Professional Open Source. * Copyright 2022 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.as.jpa.hibernate.service; import static org.jboss.as.jpa.hibernate.JpaLogger.JPA_LOGGER; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.service.spi.ServiceContributor; /** * Contribute specialized Hibernate Service impls * * @author Steve Ebersole * @author Scott Marlow */ public class ServiceContributorImpl implements ServiceContributor { private static final String CONTROLJTAINTEGRATION = "wildfly.jpa.jtaplatform"; // these properties are documented in org.jboss.as.jpa.config.Configuration private static final String CONTROL2LCINTEGRATION = "wildfly.jpa.regionfactory"; private static final String TRANSACTION_PLATFORM = "hibernate.transaction.jta.platform"; private static final String EHCACHE = "ehcache"; private static final String HIBERNATE_REGION_FACTORY_CLASS = "hibernate.cache.region.factory_class"; @Override public void contribute(StandardServiceRegistryBuilder serviceRegistryBuilder) { // note that the following deprecated getSettings() is agreed to be replaced with method that returns immutable copy of configuration settings. final Object jtaPlatformInitiatorEnabled = serviceRegistryBuilder.getSettings().getOrDefault(CONTROLJTAINTEGRATION, true); if (serviceRegistryBuilder.getSettings().get(TRANSACTION_PLATFORM) != null) { // applications that already specify the transaction platform property which will override the WildFlyCustomJtaPlatform. JPA_LOGGER.tracef("ServiceContributorImpl#contribute application configured the Jakarta Transactions Platform to be used instead of WildFlyCustomJtaPlatform (%s=%s)", TRANSACTION_PLATFORM, serviceRegistryBuilder.getSettings().get(TRANSACTION_PLATFORM)); } else if (jtaPlatformInitiatorEnabled == null || (jtaPlatformInitiatorEnabled instanceof Boolean && ((Boolean) jtaPlatformInitiatorEnabled).booleanValue()) || Boolean.parseBoolean(jtaPlatformInitiatorEnabled.toString())) { // use WildFlyCustomJtaPlatform unless they explicitly set wildfly.jpa.jtaplatform to false. JPA_LOGGER.tracef("ServiceContributorImpl#contribute application will use WildFlyCustomJtaPlatform"); serviceRegistryBuilder.addInitiator(new WildFlyCustomJtaPlatformInitiator()); } final Object regionFactoryInitiatorEnabled = serviceRegistryBuilder.getSettings().getOrDefault(CONTROL2LCINTEGRATION, true); final Object regionFactory = serviceRegistryBuilder.getSettings().get(HIBERNATE_REGION_FACTORY_CLASS); if ((regionFactory instanceof String) && ((String) regionFactory).contains(EHCACHE)) { JPA_LOGGER.tracef("ServiceContributorImpl#contribute application is using Ehcache via regionFactory=%s", regionFactory); } else if (regionFactoryInitiatorEnabled == null || (regionFactoryInitiatorEnabled instanceof Boolean && ((Boolean) regionFactoryInitiatorEnabled).booleanValue()) || Boolean.parseBoolean(regionFactoryInitiatorEnabled.toString())) { JPA_LOGGER.tracef("ServiceContributorImpl#contribute adding ORM initiator for 2lc region factory"); serviceRegistryBuilder.addInitiator(new WildFlyCustomRegionFactoryInitiator()); } } }
4,069
58.852941
178
java
null
wildfly-main/jpa/hibernate6/src/main/java/org/jboss/as/jpa/hibernate/management/HibernateEntityStatistics.java
/* * JBoss, Home of Professional Open Source. * Copyright 2022 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.as.jpa.hibernate.management; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Set; import jakarta.persistence.EntityManagerFactory; import org.hibernate.SessionFactory; import org.jipijapa.management.spi.EntityManagerFactoryAccess; import org.jipijapa.management.spi.Operation; import org.jipijapa.management.spi.PathAddress; /** * Hibernate entity statistics * * @author Scott Marlow */ public class HibernateEntityStatistics extends HibernateAbstractStatistics { public static final String OPERATION_ENTITY_DELETE_COUNT = "entity-delete-count"; public static final String OPERATION_ENTITY_INSERT_COUNT = "entity-insert-count"; public static final String OPERATION_ENTITY_LOAD_COUNT = "entity-load-count"; public static final String OPERATION_ENTITY_FETCH_COUNT = "entity-fetch-count"; public static final String OPERATION_ENTITY_UPDATE_COUNT = "entity-update-count"; public static final String OPERATION_OPTIMISTIC_FAILURE_COUNT = "optimistic-failure-count"; public HibernateEntityStatistics() { /** * specify the different operations */ operations.put(OPERATION_ENTITY_DELETE_COUNT, entityDeleteCount); types.put(OPERATION_ENTITY_DELETE_COUNT, Long.class); operations.put(OPERATION_ENTITY_INSERT_COUNT, entityInsertCount); types.put(OPERATION_ENTITY_INSERT_COUNT, Long.class); operations.put(OPERATION_ENTITY_LOAD_COUNT, entityLoadCount); types.put(OPERATION_ENTITY_LOAD_COUNT, Long.class); operations.put(OPERATION_ENTITY_FETCH_COUNT, entityFetchCount); types.put(OPERATION_ENTITY_FETCH_COUNT, Long.class); operations.put(OPERATION_ENTITY_UPDATE_COUNT, entityUpdateCount); types.put(OPERATION_ENTITY_UPDATE_COUNT, Long.class); operations.put(OPERATION_OPTIMISTIC_FAILURE_COUNT, optimisticFailureCount); types.put(OPERATION_OPTIMISTIC_FAILURE_COUNT, Long.class); } private org.hibernate.stat.Statistics getBaseStatistics(EntityManagerFactory entityManagerFactory) { if (entityManagerFactory == null) { return null; } SessionFactory sessionFactory = entityManagerFactory.unwrap(SessionFactory.class); if (sessionFactory != null) { return sessionFactory.getStatistics(); } return null; } private org.hibernate.stat.EntityStatistics getStatistics(EntityManagerFactory entityManagerFactory, PathAddress pathAddress) { if (entityManagerFactory == null) { return null; } SessionFactory sessionFactory = entityManagerFactory.unwrap(SessionFactory.class); if (sessionFactory != null) { return sessionFactory.getStatistics().getEntityStatistics(pathAddress.getValue(HibernateStatistics.ENTITY)); } return null; } private Operation entityDeleteCount = new Operation() { @Override public Object invoke(Object... args) { org.hibernate.stat.EntityStatistics statistics = getStatistics(getEntityManagerFactory(args), getPathAddress(args)); return Long.valueOf(statistics != null ? statistics.getDeleteCount() : 0); } }; private Operation entityFetchCount = new Operation() { @Override public Object invoke(Object... args) { org.hibernate.stat.EntityStatistics statistics = getStatistics(getEntityManagerFactory(args), getPathAddress(args)); return Long.valueOf(statistics != null ? statistics.getFetchCount() : 0); } }; private Operation entityInsertCount = new Operation() { @Override public Object invoke(Object... args) { org.hibernate.stat.EntityStatistics statistics = getStatistics(getEntityManagerFactory(args), getPathAddress(args)); return Long.valueOf(statistics != null ? statistics.getInsertCount() : 0); } }; private Operation entityLoadCount = new Operation() { @Override public Object invoke(Object... args) { org.hibernate.stat.EntityStatistics statistics = getStatistics(getEntityManagerFactory(args), getPathAddress(args)); return Long.valueOf(statistics != null ? statistics.getLoadCount() : 0); } }; private Operation entityUpdateCount = new Operation() { @Override public Object invoke(Object... args) { org.hibernate.stat.EntityStatistics statistics = getStatistics(getEntityManagerFactory(args), getPathAddress(args)); return Long.valueOf(statistics != null ? statistics.getUpdateCount() : 0); } }; private Operation optimisticFailureCount = new Operation() { @Override public Object invoke(Object... args) { org.hibernate.stat.EntityStatistics statistics = getStatistics(getEntityManagerFactory(args), getPathAddress(args)); return Long.valueOf(statistics != null ? statistics.getOptimisticFailureCount() : 0); } }; @Override public Set<String> getNames() { return Collections.unmodifiableSet(operations.keySet()); } @Override public Collection<String> getDynamicChildrenNames(EntityManagerFactoryAccess entityManagerFactoryLookup, PathAddress pathAddress) { org.hibernate.stat.Statistics statistics = getBaseStatistics(entityManagerFactoryLookup.entityManagerFactory(pathAddress.getValue(HibernateStatistics.PROVIDER_LABEL))); return statistics != null ? Collections.unmodifiableCollection(Arrays.asList( statistics.getEntityNames())) : Collections.EMPTY_LIST; } }
6,410
40.36129
176
java
null
wildfly-main/jpa/hibernate6/src/main/java/org/jboss/as/jpa/hibernate/management/HibernateManagementAdaptor.java
/* * JBoss, Home of Professional Open Source. * Copyright 2022 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.as.jpa.hibernate.management; import org.jboss.as.jpa.spi.ManagementAdaptor; import org.jipijapa.management.spi.Statistics; /** * Contains management support for Hibernate * * @author Scott Marlow */ public class HibernateManagementAdaptor implements ManagementAdaptor { // shared (per classloader) instance for all Hibernate 4.3 Jakarta Persistence deployments private static final HibernateManagementAdaptor INSTANCE = new HibernateManagementAdaptor(); private final Statistics statistics = new HibernateStatistics(); private static final String PROVIDER_LABEL = "hibernate-persistence-unit"; private static final String VERSION = "Hibernate ORM 4.3.x"; private HibernateManagementAdaptor() { } /** * The management statistics are shared across all Hibernate 4 Jakarta Persistence deployments * @return shared instance for all Hibernate 4 Jakarta Persistence deployments */ public static HibernateManagementAdaptor getInstance() { return INSTANCE; } @Override public String getIdentificationLabel() { return PROVIDER_LABEL; } @Override public String getVersion() { return VERSION; } @Override public Statistics getStatistics() { return statistics; } }
2,019
28.705882
98
java
null
wildfly-main/jpa/hibernate6/src/main/java/org/jboss/as/jpa/hibernate/management/HibernateQueryCacheStatistics.java
/* * JBoss, Home of Professional Open Source. * Copyright 2022 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.as.jpa.hibernate.management; import java.util.Collection; import java.util.HashSet; import java.util.Set; import jakarta.persistence.EntityManagerFactory; import org.hibernate.SessionFactory; import org.jipijapa.management.spi.EntityManagerFactoryAccess; import org.jipijapa.management.spi.Operation; import org.jipijapa.management.spi.PathAddress; /** * Hibernate query cache statistics * * @author Scott Marlow */ public class HibernateQueryCacheStatistics extends HibernateAbstractStatistics { public static final String ATTRIBUTE_QUERY_NAME = "query-name"; public static final String OPERATION_QUERY_EXECUTION_COUNT = "query-execution-count"; public static final String OPERATION_QUERY_EXECUTION_ROW_COUNT = "query-execution-row-count"; public static final String OPERATION_QUERY_EXECUTION_AVG_TIME = "query-execution-average-time"; public static final String OPERATION_QUERY_EXECUTION_MAX_TIME = "query-execution-max-time"; public static final String OPERATION_QUERY_EXECUTION_MIN_TIME = "query-execution-min-time"; public static final String OPERATION_QUERY_CACHE_HIT_COUNT = "query-cache-hit-count"; public static final String OPERATION_QUERY_CACHE_MISS_COUNT = "query-cache-miss-count"; public static final String OPERATION_QUERY_CACHE_PUT_COUNT = "query-cache-put-count"; public HibernateQueryCacheStatistics() { /** * specify the different operations */ operations.put(ATTRIBUTE_QUERY_NAME, showQueryName); types.put(ATTRIBUTE_QUERY_NAME,String.class); operations.put(OPERATION_QUERY_EXECUTION_COUNT, queryExecutionCount); types.put(OPERATION_QUERY_EXECUTION_COUNT, Long.class); operations.put(OPERATION_QUERY_EXECUTION_ROW_COUNT, queryExecutionRowCount); types.put(OPERATION_QUERY_EXECUTION_ROW_COUNT, Long.class); operations.put(OPERATION_QUERY_EXECUTION_AVG_TIME, queryExecutionAverageTime); types.put(OPERATION_QUERY_EXECUTION_AVG_TIME, Long.class); operations.put(OPERATION_QUERY_EXECUTION_MAX_TIME, queryExecutionMaximumTime); types.put(OPERATION_QUERY_EXECUTION_MAX_TIME, Long.class); operations.put(OPERATION_QUERY_EXECUTION_MIN_TIME, queryExecutionMinimumTime); types.put(OPERATION_QUERY_EXECUTION_MIN_TIME, Long.class); operations.put(OPERATION_QUERY_CACHE_HIT_COUNT, queryCacheHitCount); types.put(OPERATION_QUERY_CACHE_HIT_COUNT, Long.class); operations.put(OPERATION_QUERY_CACHE_MISS_COUNT, queryCacheMissCount); types.put(OPERATION_QUERY_CACHE_MISS_COUNT, Long.class); operations.put(OPERATION_QUERY_CACHE_PUT_COUNT, queryCachePutCount); types.put(OPERATION_QUERY_CACHE_PUT_COUNT, Long.class); } @Override public Collection<String> getDynamicChildrenNames(EntityManagerFactoryAccess entityManagerFactoryLookup, PathAddress pathAddress) { Set<String> result = new HashSet<>(); org.hibernate.stat.Statistics stats = getBaseStatistics(entityManagerFactoryLookup.entityManagerFactory(pathAddress.getValue(HibernateStatistics.PROVIDER_LABEL))); if (stats != null) { String[] queries = stats.getQueries(); if (queries != null) { for (String query : queries) { result.add(QueryName.queryName(query).getDisplayName()); } } } return result; } private org.hibernate.stat.Statistics getBaseStatistics(EntityManagerFactory entityManagerFactory) { if (entityManagerFactory == null) { return null; } SessionFactory sessionFactory = entityManagerFactory.unwrap(SessionFactory.class); if (sessionFactory != null) { return sessionFactory.getStatistics(); } return null; } private org.hibernate.stat.QueryStatistics getStatistics(EntityManagerFactory entityManagerFactory, String displayQueryName) { if (entityManagerFactory == null) { return null; } SessionFactory sessionFactory = entityManagerFactory.unwrap(SessionFactory.class); // convert displayed (transformed by QueryNames) query name to original query name to look up query statistics if (sessionFactory != null) { String[] originalQueryNames = sessionFactory.getStatistics().getQueries(); if (originalQueryNames != null) { for (String originalQueryName : originalQueryNames) { if (QueryName.queryName(originalQueryName).getDisplayName().equals(displayQueryName)) { return sessionFactory.getStatistics().getQueryStatistics(originalQueryName); } } } } return null; } private Operation queryExecutionCount = new Operation() { @Override public Object invoke(Object... args) { org.hibernate.stat.QueryStatistics statistics = getStatistics(getEntityManagerFactory(args), getQueryName(args)); return Long.valueOf(statistics != null ? statistics.getExecutionCount() : 0); } }; private Operation queryExecutionMaximumTime = new Operation() { @Override public Object invoke(Object... args) { org.hibernate.stat.QueryStatistics statistics = getStatistics(getEntityManagerFactory(args), getQueryName(args)); return Long.valueOf(statistics != null ? statistics.getExecutionMaxTime() : 0); } }; private Operation queryExecutionRowCount = new Operation() { @Override public Object invoke(Object... args) { org.hibernate.stat.QueryStatistics statistics = getStatistics(getEntityManagerFactory(args), getQueryName(args)); return Long.valueOf(statistics != null ? statistics.getExecutionRowCount() : 0); } }; private Operation queryExecutionAverageTime = new Operation() { @Override public Object invoke(Object... args) { org.hibernate.stat.QueryStatistics statistics = getStatistics(getEntityManagerFactory(args), getQueryName(args)); return Long.valueOf(statistics != null ? statistics.getExecutionAvgTime() : 0); } }; private Operation queryExecutionMinimumTime = new Operation() { @Override public Object invoke(Object... args) { org.hibernate.stat.QueryStatistics statistics = getStatistics(getEntityManagerFactory(args), getQueryName(args)); return Long.valueOf(statistics != null ? statistics.getExecutionMinTime() : 0); } }; private Operation queryCacheHitCount = new Operation() { @Override public Object invoke(Object... args) { org.hibernate.stat.QueryStatistics statistics = getStatistics(getEntityManagerFactory(args), getQueryName(args)); return Long.valueOf(statistics != null ? statistics.getCacheHitCount() : 0); } }; private Operation queryCacheMissCount = new Operation() { @Override public Object invoke(Object... args) { org.hibernate.stat.QueryStatistics statistics = getStatistics(getEntityManagerFactory(args), getQueryName(args)); return Long.valueOf(statistics != null ? statistics.getCacheMissCount() : 0); } }; private Operation queryCachePutCount = new Operation() { @Override public Object invoke(Object... args) { org.hibernate.stat.QueryStatistics statistics = getStatistics(getEntityManagerFactory(args), getQueryName(args)); return Long.valueOf(statistics != null ? statistics.getCachePutCount() : 0); } }; private Operation showQueryName = new Operation() { @Override public Object invoke(Object... args) { String displayQueryName = getQueryName(args); EntityManagerFactory entityManagerFactory = getEntityManagerFactory(args); if (displayQueryName != null && entityManagerFactory != null) { SessionFactory sessionFactory = entityManagerFactory.unwrap(SessionFactory.class); // convert displayed (transformed by QueryNames) query name to original query name if (sessionFactory != null) { String[] originalQueryNames = sessionFactory.getStatistics().getQueries(); if (originalQueryNames != null) { for (String originalQueryName : originalQueryNames) { if (QueryName.queryName(originalQueryName).getDisplayName().equals(displayQueryName)) { return originalQueryName; } } } } } return null; } }; private String getQueryName(Object... args) { PathAddress pathAddress = getPathAddress(args); if (pathAddress != null) { return pathAddress.getValue(HibernateStatistics.QUERYCACHE); } return null; } }
9,829
43.279279
171
java
null
wildfly-main/jpa/hibernate6/src/main/java/org/jboss/as/jpa/hibernate/management/QueryName.java
/* * JBoss, Home of Professional Open Source. * Copyright 2022 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.as.jpa.hibernate.management; /** * Represents the Hibernate query name which is passed in as a parameter. The displayQuery can be obtained which * has spaces and other symbols replaced with a textual description (which shouldn't be changed or localized. * The localization rule is so that one set of admin scripts will work against any back end system. If it becomes * more important to localize the textual descriptions, care should be taken to avoid duplicate values when doing so. * * @author Scott Marlow */ public class QueryName { // query name as returned from hibernate Statistics.getQueries() private final String hibernateQuery; // query name transformed for display use (allowed to be ugly but should be unique) private final String displayQuery; // HQL symbol or operators private static final String SQL_NE = "<>"; private static final String NE_BANG = "!="; private static final String NE_HAT = "^="; private static final String LE = "<="; private static final String GE = ">="; private static final String CONCAT = "||"; private static final String LT = "<"; private static final String EQ = "="; private static final String GT = ">"; private static final String OPEN = "("; private static final String CLOSE = ")"; private static final String OPEN_BRACKET = "["; private static final String CLOSE_BRACKET = "]"; private static final String PLUS = "+"; private static final String MINUS = "-"; private static final String STAR = "*"; private static final String DIV = "/"; private static final String MOD = "%"; private static final String COLON = ":"; private static final String PARAM = "?"; private static final String COMMA = ","; private static final String SPACE = " "; private static final String TAB = "\t"; private static final String NEWLINE = "\n"; private static final String LINEFEED = "\r"; private static final String QUOTE = "'"; private static final String DQUOTE = "\""; private static final String TICK = "`"; private static final String OPEN_BRACE = "{"; private static final String CLOSE_BRACE = "}"; private static final String HAT = "^"; private static final String AMPERSAND = "&"; // textual representation (not to be localized as we don't won't duplication between any of the values) private static final String NOT_EQUAL__ = "_not_equal_"; private static final String BANG_NOT_EQUAL__ = "_bang_not_equal_"; private static final String HAT_NOT_EQUAL__ = "_hat_not_equal_"; private static final String LESS_THAN_EQUAL__ = "_less_than_equal_"; private static final String GREATER_THAN_EQUAL__ = "_greater_than_equal_"; private static final String CONCAT__ = "_concat_"; private static final String LESS_THAN__ = "_less_than_"; private static final String EQUAL__ = "_equal_"; private static final String GREATER__ = "_greater_"; private static final String LEFT_PAREN__ = "_left_paren_"; private static final String RIGHT_PAREN__ = "_right_paren_"; private static final String LEFT_BRACKET__ = "_left_bracket_"; private static final String RIGHT_BRACKET__ = "_right_bracket_"; private static final String PLUS__ = "_plus_"; private static final String MINUS__ = "_minus_"; private static final String STAR__ = "_star_"; private static final String DIVIDE__ = "_divide_"; private static final String MODULUS__ = "_modulus_"; private static final String COLON__ = "_colon_"; private static final String PARAM__ = "_param_"; private static final String COMMA__ = "_comma_"; private static final String SPACE__ = "_space_"; private static final String TAB__ = "_tab_"; private static final String NEWLINE__ = "_newline_"; private static final String LINEFEED__ = "_linefeed_"; private static final String QUOTE__ = "_quote_"; private static final String DQUOTE__ = "_double_quote_"; private static final String TICK__ = "_tick_"; private static final String OPEN_BRACE__ = "_left_brace_"; private static final String CLOSE_BRACE__ = "_right_brace_"; private static final String HAT__ = "_hat_"; private static final String AMPERSAND__ = "_ampersand_"; public static QueryName queryName(String query) { return new QueryName(query); } /** * Construct * * @param query */ private QueryName(String query) { hibernateQuery = query; displayQuery = displayable(query); } public String getDisplayName() { return displayQuery; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; QueryName queryName = (QueryName) o; if (displayQuery != null ? !displayQuery.equals(queryName.displayQuery) : queryName.displayQuery != null) return false; if (hibernateQuery != null ? !hibernateQuery.equals(queryName.hibernateQuery) : queryName.hibernateQuery != null) return false; return true; } @Override public int hashCode() { int result = hibernateQuery != null ? hibernateQuery.hashCode() : 0; result = 31 * result + (displayQuery != null ? displayQuery.hashCode() : 0); return result; } /** * transform a Hibernate HQL query into something that can be displayed/used for management operations * * @param query * @return */ private String displayable(String query) { if (query == null || query.length() == 0) { return query; } StringBuilder buff = new StringBuilder(query); // handle two character transforms first subst(buff, SQL_NE, NOT_EQUAL__); subst(buff, NE_BANG, BANG_NOT_EQUAL__); subst(buff, NE_HAT, HAT_NOT_EQUAL__); subst(buff, LE, LESS_THAN_EQUAL__); subst(buff, GE, GREATER_THAN_EQUAL__); subst(buff, CONCAT, CONCAT__); subst(buff, LT, LESS_THAN__); subst(buff, EQ, EQUAL__); subst(buff, GT, GREATER__); subst(buff, OPEN, LEFT_PAREN__); subst(buff, CLOSE, RIGHT_PAREN__); subst(buff, OPEN_BRACKET, LEFT_BRACKET__); subst(buff, CLOSE_BRACKET, RIGHT_BRACKET__); subst(buff, PLUS, PLUS__); subst(buff, MINUS, MINUS__); subst(buff, STAR, STAR__); subst(buff, DIV, DIVIDE__); subst(buff, MOD, MODULUS__); subst(buff, COLON, COLON__); subst(buff, PARAM, PARAM__); subst(buff, COMMA, COMMA__); subst(buff, SPACE, SPACE__); subst(buff, TAB, TAB__); subst(buff, NEWLINE, NEWLINE__); subst(buff, LINEFEED, LINEFEED__); subst(buff, QUOTE, QUOTE__); subst(buff, DQUOTE, DQUOTE__); subst(buff, TICK, TICK__); subst(buff, OPEN_BRACE, OPEN_BRACE__); subst(buff, CLOSE_BRACE, CLOSE_BRACE__); subst(buff, HAT, HAT__); subst(buff, AMPERSAND, AMPERSAND__); return buff.toString(); } /** * Substitute sub-strings inside of a string. * * @param stringBuilder String buffer to use for substitution (buffer is not reset) * @param from String to substitute from * @param to String to substitute to */ private static void subst(final StringBuilder stringBuilder, final String from, final String to) { int begin = 0, end = 0; while ((end = stringBuilder.indexOf(from, end)) != -1) { stringBuilder.delete(end, end + from.length()); stringBuilder.insert(end, to); // update positions begin = end + to.length(); end = begin; } } }
8,531
38.317972
121
java
null
wildfly-main/jpa/hibernate6/src/main/java/org/jboss/as/jpa/hibernate/management/HibernateEntityCacheStatistics.java
/* * JBoss, Home of Professional Open Source. * Copyright 2022 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.as.jpa.hibernate.management; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import jakarta.persistence.EntityManagerFactory; import org.hibernate.SessionFactory; import org.jipijapa.management.spi.EntityManagerFactoryAccess; import org.jipijapa.management.spi.Operation; import org.jipijapa.management.spi.PathAddress; /** * Hibernate entity cache (SecondLevelCacheStatistics) statistics * * @author Scott Marlow */ public class HibernateEntityCacheStatistics extends HibernateAbstractStatistics { public static final String ATTRIBUTE_ENTITY_CACHE_REGION_NAME = "entity-cache-region-name"; public static final String OPERATION_SECOND_LEVEL_CACHE_HIT_COUNT = "second-level-cache-hit-count"; public static final String OPERATION_SECOND_LEVEL_CACHE_MISS_COUNT = "second-level-cache-miss-count"; public static final String OPERATION_SECOND_LEVEL_CACHE_PUT_COUNT = "second-level-cache-put-count"; public static final String OPERATION_SECOND_LEVEL_CACHE_COUNT_IN_MEMORY = "second-level-cache-count-in-memory"; public static final String OPERATION_SECOND_LEVEL_CACHE_SIZE_IN_MEMORY = "second-level-cache-size-in-memory"; public HibernateEntityCacheStatistics() { /** * specify the different operations */ operations.put(ATTRIBUTE_ENTITY_CACHE_REGION_NAME, getEntityCacheRegionName); types.put(ATTRIBUTE_ENTITY_CACHE_REGION_NAME,String.class); operations.put(OPERATION_SECOND_LEVEL_CACHE_HIT_COUNT, entityCacheHitCount); types.put(OPERATION_SECOND_LEVEL_CACHE_HIT_COUNT, Long.class); operations.put(OPERATION_SECOND_LEVEL_CACHE_MISS_COUNT, entityCacheMissCount); types.put(OPERATION_SECOND_LEVEL_CACHE_MISS_COUNT, Long.class); operations.put(OPERATION_SECOND_LEVEL_CACHE_PUT_COUNT, entityCachePutCount); types.put(OPERATION_SECOND_LEVEL_CACHE_PUT_COUNT, Long.class); operations.put(OPERATION_SECOND_LEVEL_CACHE_COUNT_IN_MEMORY, entityCacheCountInMemory); types.put(OPERATION_SECOND_LEVEL_CACHE_COUNT_IN_MEMORY, Long.class); operations.put(OPERATION_SECOND_LEVEL_CACHE_SIZE_IN_MEMORY, entityCacheSizeInMemory); types.put(OPERATION_SECOND_LEVEL_CACHE_SIZE_IN_MEMORY, Long.class); } @Override public Collection<String> getDynamicChildrenNames(EntityManagerFactoryAccess entityManagerFactoryLookup, PathAddress pathAddress) { org.hibernate.stat.Statistics stats = getBaseStatistics(entityManagerFactoryLookup.entityManagerFactory(pathAddress.getValue(HibernateStatistics.PROVIDER_LABEL))); if (stats == null) { return Collections.emptyList(); } return Collections.unmodifiableCollection(Arrays.asList(stats.getEntityNames())); } private org.hibernate.stat.Statistics getBaseStatistics(EntityManagerFactory entityManagerFactory) { if (entityManagerFactory == null) { return null; } SessionFactory sessionFactory = entityManagerFactory.unwrap(SessionFactory.class); if (sessionFactory != null) { return sessionFactory.getStatistics(); } return null; } org.hibernate.stat.CacheRegionStatistics getStatistics(EntityManagerFactoryAccess entityManagerFactoryaccess, PathAddress pathAddress) { String scopedPersistenceUnitName = pathAddress.getValue(HibernateStatistics.PROVIDER_LABEL); SessionFactory sessionFactory = entityManagerFactoryaccess.entityManagerFactory(scopedPersistenceUnitName).unwrap(SessionFactory.class); if (sessionFactory != null) { // Statistics#getCacheRegionStatistics() only expects the entity class name to be specified. return sessionFactory.getStatistics().getCacheRegionStatistics(pathAddress.getValue(HibernateStatistics.ENTITYCACHE)); } return null; } private Operation getEntityCacheRegionName = new Operation() { @Override public Object invoke(Object... args) { return getStatisticName(args); } }; private Operation entityCacheHitCount = new Operation() { @Override public Object invoke(Object... args) { org.hibernate.stat.CacheRegionStatistics statistics = getStatistics(getEntityManagerFactoryAccess(args), getPathAddress(args)); return Long.valueOf(statistics != null ? statistics.getHitCount() : 0); } }; private Operation entityCacheMissCount = new Operation() { @Override public Object invoke(Object... args) { org.hibernate.stat.CacheRegionStatistics statistics = getStatistics(getEntityManagerFactoryAccess(args), getPathAddress(args)); return Long.valueOf(statistics != null ? statistics.getMissCount() : 0); } }; private Operation entityCachePutCount = new Operation() { @Override public Object invoke(Object... args) { org.hibernate.stat.CacheRegionStatistics statistics = getStatistics(getEntityManagerFactoryAccess(args), getPathAddress(args)); return Long.valueOf(statistics != null ? statistics.getPutCount() : 0); } }; private Operation entityCacheSizeInMemory = new Operation() { @Override public Object invoke(Object... args) { org.hibernate.stat.CacheRegionStatistics statistics = getStatistics(getEntityManagerFactoryAccess(args), getPathAddress(args)); return Long.valueOf(statistics != null ? statistics.getSizeInMemory() : 0); } }; private Operation entityCacheCountInMemory = new Operation() { @Override public Object invoke(Object... args) { org.hibernate.stat.CacheRegionStatistics statistics = getStatistics(getEntityManagerFactoryAccess(args), getPathAddress(args)); return Long.valueOf(statistics != null ? statistics.getElementCountInMemory() : 0); } }; }
6,680
44.44898
171
java
null
wildfly-main/jpa/hibernate6/src/main/java/org/jboss/as/jpa/hibernate/management/HibernateStatistics.java
/* * JBoss, Home of Professional Open Source. * Copyright 2022 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.as.jpa.hibernate.management; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Map; import jakarta.persistence.Cache; import jakarta.persistence.EntityManagerFactory; import org.hibernate.SessionFactory; import org.jipijapa.management.spi.EntityManagerFactoryAccess; import org.jipijapa.management.spi.Operation; import org.jipijapa.management.spi.PathAddress; import org.jipijapa.management.spi.Statistics; /** * HibernateStatistics * * @author Scott Marlow */ public class HibernateStatistics extends HibernateAbstractStatistics { public static final String PROVIDER_LABEL = "hibernate-persistence-unit"; public static final String OPERATION_CLEAR = "clear"; public static final String OPERATION_EVICTALL = "evict-all"; public static final String OPERATION_SUMMARY = "summary"; public static final String OPERATION_STATISTICS_ENABLED_DEPRECATED = "enabled"; // deprecated by JIPI-28 public static final String OPERATION_STATISTICS_ENABLED = "statistics-enabled"; public static final String OPERATION_ENTITY_DELETE_COUNT = "entity-delete-count"; public static final String OPERATION_ENTITY_INSERT_COUNT = "entity-insert-count"; public static final String OPERATION_ENTITY_LOAD_COUNT = "entity-load-count"; public static final String OPERATION_ENTITY_FETCH_COUNT = "entity-fetch-count"; public static final String OPERATION_ENTITY_UPDATE_COUNT = "entity-update-count"; public static final String OPERATION_COLLECTION_FETCH_COUNT = "collection-fetch-count"; public static final String OPERATION_COLLECTION_LOAD_COUNT = "collection-load-count"; public static final String OPERATION_COLLECTION_RECREATED_COUNT = "collection-recreated-count"; public static final String OPERATION_COLLECTION_REMOVE_COUNT = "collection-remove-count"; public static final String OPERATION_COLLECTION_UPDATE_COUNT = "collection-update-count"; public static final String OPERATION_QUERYCACHE_HIT_COUNT = "query-cache-hit-count"; public static final String OPERATION_QUERYCACHE_MISS_COUNT ="query-cache-miss-count"; public static final String OPERATION_QUERYQUERYCACHE_PUT_COUNT ="query-cache-put-count"; public static final String OPERATION_QUERYEXECUTION_COUNT ="query-execution-count"; public static final String OPERATION_QUERYEXECUTION_MAX_TIME ="query-execution-max-time"; public static final String OPERATION_QUERYEXECUTION_MAX_TIME_STRING ="query-execution-max-time-query-string"; public static final String OPERATION_SECONDLEVELCACHE_HIT_COUNT= "second-level-cache-hit-count"; public static final String OPERATION_SECONDLEVELCACHE_MISS_COUNT="second-level-cache-miss-count"; public static final String OPERATION_SECONDLEVELCACHE_PUT_COUNT="second-level-cache-put-count"; public static final String OPERATION_FLUSH_COUNT = "flush-count"; public static final String OPERATION_CONNECT_COUNT = "connect-count"; public static final String OPERATION_SESSION_CLOSE_COUNT = "session-close-count"; public static final String OPERATION_SESSION_OPEN_COUNT = "session-open-count"; public static final String OPERATION_SUCCESSFUL_TRANSACTION_COUNT = "successful-transaction-count"; public static final String OPERATION_COMPLETED_TRANSACTION_COUNT = "completed-transaction-count"; public static final String OPERATION_PREPARED_STATEMENT_COUNT = "prepared-statement-count"; public static final String OPERATION_CLOSE_STATEMENT_COUNT = "close-statement-count"; public static final String OPERATION_OPTIMISTIC_FAILURE_COUNT = "optimistic-failure-count"; public static final String ENTITYCACHE = "entity-cache"; public static final String COLLECTION = "collection"; public static final String ENTITY = "entity"; public static final String QUERYCACHE = "query-cache"; private final Map<String, Statistics> childrenStatistics = new HashMap<String,Statistics>(); public HibernateStatistics() { /** * specify the different operations */ operations.put(PROVIDER_LABEL, label); types.put(PROVIDER_LABEL,String.class); operations.put(OPERATION_CLEAR, clear); types.put(OPERATION_CLEAR, Operation.class); operations.put(OPERATION_EVICTALL, evictAll); types.put(OPERATION_EVICTALL, Operation.class); operations.put(OPERATION_SUMMARY, summary); types.put(OPERATION_SUMMARY, Operation.class); operations.put(OPERATION_STATISTICS_ENABLED, statisticsEnabled); types.put(OPERATION_STATISTICS_ENABLED, Boolean.class); writeableNames.add(OPERATION_STATISTICS_ENABLED); // make 'enabled' writeable operations.put(OPERATION_STATISTICS_ENABLED_DEPRECATED, statisticsEnabled); types.put(OPERATION_STATISTICS_ENABLED_DEPRECATED, Boolean.class); writeableNames.add(OPERATION_STATISTICS_ENABLED_DEPRECATED); // make 'enabled' writeable operations.put(OPERATION_ENTITY_DELETE_COUNT, entityDeleteCount); types.put(OPERATION_ENTITY_DELETE_COUNT, Long.class); operations.put(OPERATION_COLLECTION_FETCH_COUNT, collectionFetchCount); types.put(OPERATION_COLLECTION_FETCH_COUNT, Long.class); operations.put(OPERATION_COLLECTION_LOAD_COUNT, collectionLoadCount); types.put(OPERATION_COLLECTION_LOAD_COUNT, Long.class); operations.put(OPERATION_COLLECTION_RECREATED_COUNT, collectionRecreatedCount); types.put(OPERATION_COLLECTION_RECREATED_COUNT, Long.class); operations.put(OPERATION_COLLECTION_REMOVE_COUNT, collectionRemoveCount); types.put(OPERATION_COLLECTION_REMOVE_COUNT, Long.class); operations.put(OPERATION_COLLECTION_UPDATE_COUNT, collectionUpdateCount); types.put(OPERATION_COLLECTION_UPDATE_COUNT, Long.class); operations.put(OPERATION_QUERYCACHE_HIT_COUNT, queryCacheHitCount); types.put(OPERATION_QUERYCACHE_HIT_COUNT, Long.class); operations.put(OPERATION_QUERYCACHE_MISS_COUNT, queryCacheMissCount); types.put(OPERATION_QUERYCACHE_MISS_COUNT, Long.class); operations.put(OPERATION_QUERYQUERYCACHE_PUT_COUNT, queryCachePutCount); types.put(OPERATION_QUERYQUERYCACHE_PUT_COUNT, Long.class); operations.put(OPERATION_QUERYEXECUTION_COUNT, queryExecutionCount); types.put(OPERATION_QUERYEXECUTION_COUNT, Long.class); operations.put(OPERATION_QUERYEXECUTION_MAX_TIME, queryExecutionMaxTime); types.put(OPERATION_QUERYEXECUTION_MAX_TIME, Long.class); operations.put(OPERATION_QUERYEXECUTION_MAX_TIME_STRING, queryExecutionMaxTimeString); types.put(OPERATION_QUERYEXECUTION_MAX_TIME_STRING, String.class); operations.put(OPERATION_ENTITY_INSERT_COUNT, entityInsertCount); types.put(OPERATION_ENTITY_INSERT_COUNT, Long.class); operations.put(OPERATION_ENTITY_LOAD_COUNT, entityLoadCount); types.put(OPERATION_ENTITY_LOAD_COUNT, Long.class); operations.put(OPERATION_ENTITY_FETCH_COUNT, entityFetchCount); types.put(OPERATION_ENTITY_FETCH_COUNT, Long.class); operations.put(OPERATION_ENTITY_UPDATE_COUNT, entityUpdateCount); types.put(OPERATION_ENTITY_UPDATE_COUNT, Long.class); operations.put(OPERATION_FLUSH_COUNT, flushCount); types.put(OPERATION_FLUSH_COUNT, Long.class); operations.put(OPERATION_CONNECT_COUNT, connectCount); types.put(OPERATION_CONNECT_COUNT, Long.class); operations.put(OPERATION_SESSION_CLOSE_COUNT, sessionCloseCount); types.put(OPERATION_SESSION_CLOSE_COUNT, Long.class); operations.put(OPERATION_SESSION_OPEN_COUNT, sessionOpenCount); types.put(OPERATION_SESSION_OPEN_COUNT, Long.class); operations.put(OPERATION_SUCCESSFUL_TRANSACTION_COUNT, transactionCount); types.put(OPERATION_SUCCESSFUL_TRANSACTION_COUNT, Long.class); operations.put(OPERATION_COMPLETED_TRANSACTION_COUNT, transactionCompletedCount); types.put(OPERATION_COMPLETED_TRANSACTION_COUNT, Long.class); operations.put(OPERATION_PREPARED_STATEMENT_COUNT, preparedStatementCount); types.put(OPERATION_PREPARED_STATEMENT_COUNT, Long.class); operations.put(OPERATION_CLOSE_STATEMENT_COUNT, closedStatementCount); types.put(OPERATION_CLOSE_STATEMENT_COUNT, Long.class); operations.put(OPERATION_OPTIMISTIC_FAILURE_COUNT, optimisticFailureCount); types.put(OPERATION_OPTIMISTIC_FAILURE_COUNT, Long.class); operations.put(OPERATION_SECONDLEVELCACHE_HIT_COUNT, secondLevelCacheHitCount); types.put(OPERATION_SECONDLEVELCACHE_HIT_COUNT, Long.class); operations.put(OPERATION_SECONDLEVELCACHE_MISS_COUNT, secondLevelCacheMissCount); types.put(OPERATION_SECONDLEVELCACHE_MISS_COUNT, Long.class); operations.put(OPERATION_SECONDLEVELCACHE_PUT_COUNT, secondLevelCachePutCount); types.put(OPERATION_SECONDLEVELCACHE_PUT_COUNT, Long.class); /** * Specify the children statistics */ childrenNames.add(ENTITY); childrenStatistics.put(ENTITY, new HibernateEntityStatistics()); childrenNames.add(ENTITYCACHE); childrenStatistics.put(ENTITYCACHE, new HibernateEntityCacheStatistics()); childrenNames.add(COLLECTION); childrenStatistics.put(COLLECTION, new HibernateCollectionStatistics()); childrenNames.add(QUERYCACHE); childrenStatistics.put(QUERYCACHE , new HibernateQueryCacheStatistics()); } @Override public Statistics getChild(String childName) { return childrenStatistics.get(childName); } static final org.hibernate.stat.Statistics getStatistics(final EntityManagerFactory entityManagerFactory) { if (entityManagerFactory == null) { return null; } SessionFactory sessionFactory = entityManagerFactory.unwrap(SessionFactory.class); if (sessionFactory != null) { return sessionFactory.getStatistics(); } return null; } @Override public Collection<String> getDynamicChildrenNames(EntityManagerFactoryAccess entityManagerFactoryLookup, PathAddress pathAddress) { return Collections.EMPTY_LIST; } private Operation clear = new Operation() { @Override public Object invoke(Object... args) { getStatistics(getEntityManagerFactory(args)).clear(); return null; } }; private Operation label = new Operation() { @Override public Object invoke(Object... args) { PathAddress pathAddress = getPathAddress(args); if (pathAddress != null) { return pathAddress.getValue(PROVIDER_LABEL); } return ""; } }; private Operation evictAll = new Operation() { @Override public Object invoke(Object... args) { Cache secondLevelCache = getEntityManagerFactory(args).getCache(); if (secondLevelCache != null) { secondLevelCache.evictAll(); } return null; } }; private Operation summary = new Operation() { @Override public Object invoke(Object... args) { getStatistics(getEntityManagerFactory(args)).logSummary(); return null; } }; private Operation statisticsEnabled = new Operation() { @Override public Object invoke(Object... args) { org.hibernate.stat.Statistics statistics = getStatistics(getEntityManagerFactory(args)); if (statistics != null) { if (args.length > 0 && args[0] instanceof Boolean) { Boolean newValue = (Boolean) args[0]; statistics.setStatisticsEnabled(newValue.booleanValue()); } return Boolean.valueOf(statistics.isStatisticsEnabled()); } return null; } }; private Operation entityDeleteCount = new Operation() { @Override public Object invoke(Object... args) { org.hibernate.stat.Statistics statistics = getStatistics(getEntityManagerFactory(args)); return Long.valueOf(statistics != null ? statistics.getEntityDeleteCount() : 0); } }; private Operation collectionLoadCount = new Operation() { @Override public Object invoke(Object... args) { org.hibernate.stat.Statistics statistics = getStatistics(getEntityManagerFactory(args)); return Long.valueOf(statistics != null ? statistics.getCollectionLoadCount() : 0); } }; private Operation collectionFetchCount = new Operation() { @Override public Object invoke(Object... args) { org.hibernate.stat.Statistics statistics = getStatistics(getEntityManagerFactory(args)); return Long.valueOf(statistics != null ? statistics.getCollectionFetchCount() : 0); } }; private Operation collectionRecreatedCount = new Operation() { @Override public Object invoke(Object... args) { org.hibernate.stat.Statistics statistics = getStatistics(getEntityManagerFactory(args)); return Long.valueOf(statistics != null ? statistics.getCollectionRecreateCount() : 0); } }; private Operation collectionRemoveCount = new Operation() { @Override public Object invoke(Object... args) { org.hibernate.stat.Statistics statistics = getStatistics(getEntityManagerFactory(args)); return Long.valueOf(statistics != null ? statistics.getCollectionRemoveCount() : 0); } }; private Operation collectionUpdateCount = new Operation() { @Override public Object invoke(Object... args) { org.hibernate.stat.Statistics statistics = getStatistics(getEntityManagerFactory(args)); return Long.valueOf(statistics != null ? statistics.getCollectionUpdateCount() : 0); } }; private Operation queryCacheHitCount = new Operation() { @Override public Object invoke(Object... args) { org.hibernate.stat.Statistics statistics = getStatistics(getEntityManagerFactory(args)); return Long.valueOf(statistics != null ? statistics.getQueryCacheHitCount() : 0); } }; private Operation queryCacheMissCount = new Operation() { @Override public Object invoke(Object... args) { org.hibernate.stat.Statistics statistics = getStatistics(getEntityManagerFactory(args)); return Long.valueOf(statistics != null ? statistics.getQueryCacheMissCount() : 0); } }; private Operation queryCachePutCount = new Operation() { @Override public Object invoke(Object... args) { org.hibernate.stat.Statistics statistics = getStatistics(getEntityManagerFactory(args)); return Long.valueOf(statistics != null ? statistics.getQueryCachePutCount() : 0); } }; private Operation queryExecutionCount = new Operation() { @Override public Object invoke(Object... args) { org.hibernate.stat.Statistics statistics = getStatistics(getEntityManagerFactory(args)); return Long.valueOf(statistics != null ? statistics.getQueryExecutionCount() : 0); } }; private Operation queryExecutionMaxTime = new Operation() { @Override public Object invoke(Object... args) { org.hibernate.stat.Statistics statistics = getStatistics(getEntityManagerFactory(args)); return Long.valueOf(statistics != null ? statistics.getQueryExecutionMaxTime() : 0); } }; private Operation queryExecutionMaxTimeString = new Operation() { @Override public Object invoke(Object... args) { org.hibernate.stat.Statistics statistics = getStatistics(getEntityManagerFactory(args)); return String.valueOf(statistics != null ? statistics.getQueryExecutionMaxTimeQueryString() : 0); } }; private Operation entityFetchCount = new Operation() { @Override public Object invoke(Object... args) { org.hibernate.stat.Statistics statistics = getStatistics(getEntityManagerFactory(args)); return Long.valueOf(statistics != null ? statistics.getEntityFetchCount() : 0); } }; private Operation entityInsertCount = new Operation() { @Override public Object invoke(Object... args) { org.hibernate.stat.Statistics statistics = getStatistics(getEntityManagerFactory(args)); return Long.valueOf(statistics != null ? statistics.getEntityInsertCount() : 0); } }; private Operation entityLoadCount = new Operation() { @Override public Object invoke(Object... args) { org.hibernate.stat.Statistics statistics = getStatistics(getEntityManagerFactory(args)); return Long.valueOf(statistics != null ? statistics.getEntityLoadCount() : 0); } }; private Operation entityUpdateCount = new Operation() { @Override public Object invoke(Object... args) { org.hibernate.stat.Statistics statistics = getStatistics(getEntityManagerFactory(args)); return Long.valueOf(statistics != null ? statistics.getEntityUpdateCount() : 0); } }; private Operation flushCount = new Operation() { @Override public Object invoke(Object... args) { org.hibernate.stat.Statistics statistics = getStatistics(getEntityManagerFactory(args)); return Long.valueOf(statistics != null ? statistics.getFlushCount() : 0); } }; private Operation connectCount = new Operation() { @Override public Object invoke(Object... args) { org.hibernate.stat.Statistics statistics = getStatistics(getEntityManagerFactory(args)); return Long.valueOf(statistics != null ? statistics.getConnectCount() : 0); } }; private Operation sessionCloseCount = new Operation() { @Override public Object invoke(Object... args) { org.hibernate.stat.Statistics statistics = getStatistics(getEntityManagerFactory(args)); return Long.valueOf(statistics != null ? statistics.getSessionCloseCount() : 0); } }; private Operation sessionOpenCount = new Operation() { @Override public Object invoke(Object... args) { org.hibernate.stat.Statistics statistics = getStatistics(getEntityManagerFactory(args)); return Long.valueOf(statistics != null ? statistics.getSessionOpenCount() : 0); } }; private Operation transactionCount = new Operation() { @Override public Object invoke(Object... args) { org.hibernate.stat.Statistics statistics = getStatistics(getEntityManagerFactory(args)); return Long.valueOf(statistics != null ? statistics.getTransactionCount() : 0); } }; private Operation transactionCompletedCount = new Operation() { @Override public Object invoke(Object... args) { org.hibernate.stat.Statistics statistics = getStatistics(getEntityManagerFactory(args)); return Long.valueOf(statistics != null ? statistics.getSuccessfulTransactionCount() : 0); } }; private Operation preparedStatementCount = new Operation() { @Override public Object invoke(Object... args) { org.hibernate.stat.Statistics statistics = getStatistics(getEntityManagerFactory(args)); return Long.valueOf(statistics != null ? statistics.getPrepareStatementCount() : 0); } }; private Operation closedStatementCount = new Operation() { @Override public Object invoke(Object... args) { org.hibernate.stat.Statistics statistics = getStatistics(getEntityManagerFactory(args)); return Long.valueOf(statistics != null ? statistics.getCloseStatementCount() : 0); } }; private Operation optimisticFailureCount = new Operation() { @Override public Object invoke(Object... args) { org.hibernate.stat.Statistics statistics = getStatistics(getEntityManagerFactory(args)); return Long.valueOf(statistics != null ? statistics.getOptimisticFailureCount() : 0); } }; private Operation secondLevelCacheHitCount = new Operation() { @Override public Object invoke(Object... args) { org.hibernate.stat.Statistics statistics = getStatistics(getEntityManagerFactory(args)); return Long.valueOf(statistics != null ? statistics.getSecondLevelCacheHitCount() : 0); } }; private Operation secondLevelCacheMissCount = new Operation() { @Override public Object invoke(Object... args) { org.hibernate.stat.Statistics statistics = getStatistics(getEntityManagerFactory(args)); return Long.valueOf(statistics != null ? statistics.getSecondLevelCacheMissCount() : 0); } }; private Operation secondLevelCachePutCount = new Operation() { @Override public Object invoke(Object... args) { org.hibernate.stat.Statistics statistics = getStatistics(getEntityManagerFactory(args)); return Long.valueOf(statistics != null ? statistics.getSecondLevelCachePutCount() : 0); } }; }
22,317
43.369781
135
java
null
wildfly-main/jpa/hibernate6/src/main/java/org/jboss/as/jpa/hibernate/management/HibernateCollectionStatistics.java
/* * JBoss, Home of Professional Open Source. * Copyright 2022 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.as.jpa.hibernate.management; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import jakarta.persistence.EntityManagerFactory; import org.hibernate.SessionFactory; import org.hibernate.stat.CollectionStatistics; import org.jipijapa.management.spi.EntityManagerFactoryAccess; import org.jipijapa.management.spi.Operation; import org.jipijapa.management.spi.PathAddress; /** * Hibernate collection statistics * * @author Scott Marlow */ public class HibernateCollectionStatistics extends HibernateAbstractStatistics { private static final String ATTRIBUTE_COLLECTION_NAME = "collection-name"; public static final String OPERATION_COLLECTION_LOAD_COUNT = "collection-load-count"; public static final String OPERATION_COLLECTION_FETCH_COUNT = "collection-fetch-count"; public static final String OPERATION_COLLECTION_UPDATE_COUNT = "collection-update-count"; public static final String OPERATION_COLLECTION_REMOVE_COUNT = "collection-remove-count"; public static final String OPERATION_COLLECTION_RECREATED_COUNT = "collection-recreated-count"; public HibernateCollectionStatistics() { /** * specify the different operations */ operations.put(ATTRIBUTE_COLLECTION_NAME, showCollectionName); types.put(ATTRIBUTE_COLLECTION_NAME,String.class); operations.put(OPERATION_COLLECTION_LOAD_COUNT, collectionLoadCount); types.put(OPERATION_COLLECTION_LOAD_COUNT, Long.class); operations.put(OPERATION_COLLECTION_FETCH_COUNT, collectionFetchCount); types.put(OPERATION_COLLECTION_FETCH_COUNT, Long.class); operations.put(OPERATION_COLLECTION_UPDATE_COUNT, collectionUpdateCount); types.put(OPERATION_COLLECTION_UPDATE_COUNT, Long.class); operations.put(OPERATION_COLLECTION_REMOVE_COUNT, collectionRemoveCount); types.put(OPERATION_COLLECTION_REMOVE_COUNT, Long.class); operations.put(OPERATION_COLLECTION_RECREATED_COUNT, collectionRecreatedCount); types.put(OPERATION_COLLECTION_RECREATED_COUNT, Long.class); } @Override public Collection<String> getDynamicChildrenNames(EntityManagerFactoryAccess entityManagerFactoryLookup, PathAddress pathAddress) { org.hibernate.stat.Statistics stats = getBaseStatistics(entityManagerFactoryLookup.entityManagerFactory(pathAddress.getValue(HibernateStatistics.PROVIDER_LABEL))); if (stats == null) { return Collections.emptyList(); } return Collections.unmodifiableCollection(Arrays.asList(stats.getCollectionRoleNames())); } private org.hibernate.stat.Statistics getBaseStatistics(EntityManagerFactory entityManagerFactory) { if (entityManagerFactory == null) { return null; } SessionFactory sessionFactory = entityManagerFactory.unwrap(SessionFactory.class); if (sessionFactory != null) { return sessionFactory.getStatistics(); } return null; } private CollectionStatistics getStatistics(final EntityManagerFactory entityManagerFactory, PathAddress pathAddress) { if (entityManagerFactory == null) { return null; } SessionFactory sessionFactory = entityManagerFactory.unwrap(SessionFactory.class); if (sessionFactory != null) { return sessionFactory.getStatistics().getCollectionStatistics(pathAddress.getValue(HibernateStatistics.COLLECTION)); } return null; } private Operation showCollectionName = new Operation() { @Override public Object invoke(Object... args) { return getStatisticName(args); } }; private Operation collectionUpdateCount = new Operation() { @Override public Object invoke(Object... args) { CollectionStatistics statistics = getStatistics(getEntityManagerFactory(args), getPathAddress(args)); return Long.valueOf(statistics != null ? statistics.getUpdateCount() : 0); } }; private Operation collectionRemoveCount = new Operation() { @Override public Object invoke(Object... args) { CollectionStatistics statistics = getStatistics(getEntityManagerFactory(args), getPathAddress(args)); return Long.valueOf(statistics != null ? statistics.getRemoveCount() : 0); } }; private Operation collectionRecreatedCount = new Operation() { @Override public Object invoke(Object... args) { CollectionStatistics statistics = getStatistics(getEntityManagerFactory(args), getPathAddress(args)); return Long.valueOf(statistics != null ? statistics.getRemoveCount() : 0); } }; private Operation collectionLoadCount = new Operation() { @Override public Object invoke(Object... args) { CollectionStatistics statistics = getStatistics(getEntityManagerFactory(args), getPathAddress(args)); return Long.valueOf(statistics != null ? statistics.getLoadCount() : 0); } }; private Operation collectionFetchCount = new Operation() { @Override public Object invoke(Object... args) { CollectionStatistics statistics = getStatistics(getEntityManagerFactory(args), getPathAddress(args)); return Long.valueOf(statistics != null ? statistics.getFetchCount() : 0); } }; }
6,165
40.945578
171
java
null
wildfly-main/jpa/hibernate6/src/main/java/org/jboss/as/jpa/hibernate/management/HibernateAbstractStatistics.java
/* * JBoss, Home of Professional Open Source. * Copyright 2022 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.as.jpa.hibernate.management; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Locale; import java.util.Map; import java.util.ResourceBundle; import java.util.Set; import jakarta.persistence.EntityManagerFactory; import org.jipijapa.management.spi.EntityManagerFactoryAccess; import org.jipijapa.management.spi.Operation; import org.jipijapa.management.spi.PathAddress; import org.jipijapa.management.spi.StatisticName; import org.jipijapa.management.spi.Statistics; /** * HibernateAbstractStatistics * * @author Scott Marlow */ public abstract class HibernateAbstractStatistics implements Statistics { private static final String RESOURCE_BUNDLE = HibernateAbstractStatistics.class.getPackage().getName() + ".LocalDescriptions"; private static final String RESOURCE_BUNDLE_KEY_PREFIX = "hibernate"; protected Map<String,Operation> operations = new HashMap<String, Operation>(); protected Set<String> childrenNames = new HashSet<String>(); protected Set<String> writeableNames = new HashSet<String>(); protected Map<String, Class> types = new HashMap<String, Class>(); protected Map<Locale, ResourceBundle> rbs = new HashMap<Locale, ResourceBundle>(); @Override public String getResourceBundleName() { return RESOURCE_BUNDLE; } @Override public String getResourceBundleKeyPrefix() { return RESOURCE_BUNDLE_KEY_PREFIX; } protected EntityManagerFactory getEntityManagerFactory(Object[] args) { PathAddress pathAddress = getPathAddress(args); for(Object arg :args) { if (arg instanceof EntityManagerFactoryAccess) { EntityManagerFactoryAccess entityManagerFactoryAccess = (EntityManagerFactoryAccess)arg; return entityManagerFactoryAccess.entityManagerFactory(pathAddress.getValue(HibernateStatistics.PROVIDER_LABEL)); } } return null; } @Override public Set<String> getNames() { return Collections.unmodifiableSet(operations.keySet()); } @Override public Class getType(String name) { return types.get(name); } @Override public boolean isOperation(String name) { return Operation.class.equals(getType(name)); } @Override public boolean isAttribute(String name) { return ! isOperation(name); } @Override public boolean isWriteable(String name) { return writeableNames.contains(name); } @Override public Object getValue(String name, EntityManagerFactoryAccess entityManagerFactoryAccess, StatisticName statisticName, PathAddress pathAddress) { return operations.get(name).invoke(entityManagerFactoryAccess, statisticName, pathAddress); } @Override public void setValue(String name, Object newValue, EntityManagerFactoryAccess entityManagerFactoryAccess, StatisticName statisticName, PathAddress pathAddress) { operations.get(name).invoke(newValue, entityManagerFactoryAccess, statisticName, pathAddress); } protected EntityManagerFactoryAccess getEntityManagerFactoryAccess(Object[] args) { for(Object arg :args) { if (arg instanceof EntityManagerFactoryAccess) { EntityManagerFactoryAccess entityManagerFactoryAccess = (EntityManagerFactoryAccess)arg; return entityManagerFactoryAccess; } } return null; } protected PathAddress getPathAddress(Object[] args) { for(Object arg :args) { if (arg instanceof PathAddress) { return (PathAddress)arg; } } return null; } protected String getStatisticName(Object[] args) { for(Object arg :args) { if (arg instanceof StatisticName) { StatisticName name = (StatisticName)arg; return name.getName(); } } return null; } @Override public Set<String> getChildrenNames() { return Collections.unmodifiableSet(childrenNames); } @Override public Statistics getChild(String childName) { return null; } }
4,920
32.47619
165
java
null
wildfly-main/jpa/hibernate6/src/main/java/org/jboss/as/jpa/hibernate/cache/CacheKeyImplementationMarshaller.java
/* * JBoss, Home of Professional Open Source. * Copyright 2023, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.jpa.hibernate.cache; import java.io.IOException; import java.util.Objects; import java.util.OptionalInt; import org.hibernate.cache.internal.CacheKeyImplementation; import org.infinispan.protostream.descriptors.WireType; import org.wildfly.clustering.marshalling.protostream.ProtoStreamMarshaller; import org.wildfly.clustering.marshalling.protostream.ProtoStreamReader; import org.wildfly.clustering.marshalling.protostream.ProtoStreamWriter; /** * ProtoStream marshaller for {@link CacheKeyImplementation}. * @author Paul Ferraro */ public class CacheKeyImplementationMarshaller implements ProtoStreamMarshaller<CacheKeyImplementation> { private static final int ID_INDEX = 1; private static final int ENTITY_INDEX = 2; private static final int TENANT_INDEX = 3; private static final int HASH_CODE_INDEX = 4; @Override public Class<? extends CacheKeyImplementation> getJavaClass() { return CacheKeyImplementation.class; } @Override public CacheKeyImplementation readFrom(ProtoStreamReader reader) throws IOException { Object id = null; String entity = null; String tenant = null; OptionalInt hashCode = OptionalInt.empty(); while (!reader.isAtEnd()) { int tag = reader.readTag(); switch (WireType.getTagFieldNumber(tag)) { case ID_INDEX: id = reader.readAny(); break; case ENTITY_INDEX: entity = reader.readString(); break; case TENANT_INDEX: tenant = reader.readString(); break; case HASH_CODE_INDEX: hashCode = OptionalInt.of(reader.readSFixed32()); break; default: reader.skipField(tag); } } return new CacheKeyImplementation(id, entity, tenant, hashCode.orElse(Objects.hashCode(id))); } @Override public void writeTo(ProtoStreamWriter writer, CacheKeyImplementation key) throws IOException { Object id = key.getId(); if (id != null) { writer.writeAny(ID_INDEX, id); } String entity = key.getEntityOrRoleName(); if (entity != null) { writer.writeString(ENTITY_INDEX, entity); } String tenant = key.getTenantId(); if (tenant != null) { writer.writeString(TENANT_INDEX, tenant); } int hashCode = key.hashCode(); if (hashCode != Objects.hashCode(id)) { writer.writeSFixed32(HASH_CODE_INDEX, hashCode); } } }
3,721
36.59596
104
java
null
wildfly-main/jpa/hibernate6/src/main/java/org/jboss/as/jpa/hibernate/cache/HibernateCacheInternalSerializationContextInitializer.java
/* * JBoss, Home of Professional Open Source. * Copyright 2023, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.jpa.hibernate.cache; import org.infinispan.protostream.SerializationContext; import org.infinispan.protostream.SerializationContextInitializer; import org.kohsuke.MetaInfServices; import org.wildfly.clustering.marshalling.protostream.AbstractSerializationContextInitializer; /** * {@link SerializationContextInitializer} for the {@link org.hibernate.cache.internal} package. * @author Paul Ferraro */ @MetaInfServices(SerializationContextInitializer.class) public class HibernateCacheInternalSerializationContextInitializer extends AbstractSerializationContextInitializer { public HibernateCacheInternalSerializationContextInitializer() { super("org.hibernate.cache.internal.proto"); } @Override public void registerMarshallers(SerializationContext context) { context.registerMarshaller(new BasicCacheKeyImplementationMarshaller()); context.registerMarshaller(new CacheKeyImplementationMarshaller()); context.registerMarshaller(new NaturalIdCacheKeyMarshaller()); } }
2,072
42.1875
116
java
null
wildfly-main/jpa/hibernate6/src/main/java/org/jboss/as/jpa/hibernate/cache/NaturalIdCacheKeyMarshaller.java
/* * JBoss, Home of Professional Open Source. * Copyright 2023, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.jpa.hibernate.cache; import java.io.IOException; import java.util.Objects; import java.util.OptionalInt; import org.hibernate.cache.internal.NaturalIdCacheKey; import org.infinispan.protostream.descriptors.WireType; import org.wildfly.clustering.marshalling.protostream.ProtoStreamMarshaller; import org.wildfly.clustering.marshalling.protostream.ProtoStreamReader; import org.wildfly.clustering.marshalling.protostream.ProtoStreamWriter; /** * ProtoStream marshaller for {@link NaturalIdCacheKey}. * @author Paul Ferraro */ public class NaturalIdCacheKeyMarshaller implements ProtoStreamMarshaller<NaturalIdCacheKey> { private static final int VALUES_INDEX = 1; private static final int ENTITY_INDEX = 2; private static final int TENANT_INDEX = 3; private static final int HASH_CODE_INDEX = 4; @Override public Class<? extends NaturalIdCacheKey> getJavaClass() { return NaturalIdCacheKey.class; } @Override public NaturalIdCacheKey readFrom(ProtoStreamReader reader) throws IOException { Object values = null; String entity = null; String tenant = null; OptionalInt hashCode = OptionalInt.empty(); while (!reader.isAtEnd()) { int tag = reader.readTag(); switch (WireType.getTagFieldNumber(tag)) { case VALUES_INDEX: values = reader.readAny(); break; case ENTITY_INDEX: entity = reader.readString(); break; case TENANT_INDEX: tenant = reader.readString(); break; case HASH_CODE_INDEX: hashCode = OptionalInt.of(reader.readSFixed32()); break; } } return new NaturalIdCacheKey(values, entity, tenant, hashCode.orElse(Objects.hashCode(values))); } @Override public void writeTo(ProtoStreamWriter writer, NaturalIdCacheKey key) throws IOException { Object values = key.getNaturalIdValues(); if (values != null) { writer.writeAny(VALUES_INDEX, values); } String entity = key.getEntityName(); if (entity != null) { writer.writeString(ENTITY_INDEX, entity); } String tenant = key.getTenantId(); if (tenant != null) { writer.writeString(TENANT_INDEX, tenant); } int hashCode = key.hashCode(); if (hashCode != Objects.hashCode(values)) { writer.writeSFixed32(HASH_CODE_INDEX, hashCode); } } }
3,659
36.731959
104
java
null
wildfly-main/jpa/hibernate6/src/main/java/org/jboss/as/jpa/hibernate/cache/BasicCacheKeyImplementationMarshaller.java
/* * JBoss, Home of Professional Open Source. * Copyright 2023, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.jpa.hibernate.cache; import java.io.IOException; import java.io.Serializable; import java.util.Objects; import java.util.OptionalInt; import org.hibernate.cache.internal.BasicCacheKeyImplementation; import org.infinispan.protostream.descriptors.WireType; import org.wildfly.clustering.marshalling.protostream.ProtoStreamMarshaller; import org.wildfly.clustering.marshalling.protostream.ProtoStreamReader; import org.wildfly.clustering.marshalling.protostream.ProtoStreamWriter; /** * ProtoStream marshaller for {@link BasicCacheKeyImplementation}. * @author Paul Ferraro */ public class BasicCacheKeyImplementationMarshaller implements ProtoStreamMarshaller<BasicCacheKeyImplementation> { private static final int ID_INDEX = 1; private static final int ENTITY_INDEX = 2; private static final int HASH_CODE_INDEX = 3; @Override public Class<? extends BasicCacheKeyImplementation> getJavaClass() { return BasicCacheKeyImplementation.class; } @Override public BasicCacheKeyImplementation readFrom(ProtoStreamReader reader) throws IOException { Serializable id = null; String entity = null; OptionalInt hashCode = OptionalInt.empty(); while (!reader.isAtEnd()) { int tag = reader.readTag(); switch (WireType.getTagFieldNumber(tag)) { case ID_INDEX: id = reader.readAny(Serializable.class); break; case ENTITY_INDEX: entity = reader.readString(); break; case HASH_CODE_INDEX: hashCode = OptionalInt.of(reader.readSFixed32()); break; default: reader.skipField(tag); } } return new BasicCacheKeyImplementation(id, entity, hashCode.orElse(Objects.hashCode(id))); } @Override public void writeTo(ProtoStreamWriter writer, BasicCacheKeyImplementation key) throws IOException { Object id = key.getId(); if (id != null) { writer.writeAny(ID_INDEX, id); } String entity = key.getEntityOrRoleName(); if (entity != null) { writer.writeString(ENTITY_INDEX, entity); } int hashCode = key.hashCode(); if (hashCode != Objects.hashCode(id)) { writer.writeSFixed32(HASH_CODE_INDEX, hashCode); } } }
3,485
37.307692
114
java
null
wildfly-main/jpa/eclipselink/src/main/java/org/jipijapa/eclipselink/JBossArchiveFactoryImpl.java
/* * JBoss, Home of Professional Open Source. * Copyright 2015, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jipijapa.eclipselink; import java.io.IOException; import java.net.URISyntaxException; import java.net.URL; import java.util.Map; import java.util.logging.Logger; import org.eclipse.persistence.internal.jpa.deployment.ArchiveFactoryImpl; import org.eclipse.persistence.jpa.Archive; /** * The JBossArchiveFactoryImpl provided here allows Eclipse to * scan JBoss AS 7 deployments for classes, so clasess don't have * to be explicitly listed in persistence.xml . * * To enable this, set the system property eclipselink.archive.factory * to the fully qualified name of this class. * * See https://community.jboss.org/wiki/HowToUseEclipseLinkWithAS7 * * @author Rich DiCroce * */ public class JBossArchiveFactoryImpl extends ArchiveFactoryImpl { private static final String VFS = "vfs"; public JBossArchiveFactoryImpl() { super(); } public JBossArchiveFactoryImpl(Logger logger) { super(logger); } @Override public Archive createArchive(URL rootUrl, String descriptorLocation, @SuppressWarnings("rawtypes") Map properties) throws URISyntaxException, IOException { String protocol = rootUrl.getProtocol(); if (VFS.equals(protocol)) { return new VFSArchive(rootUrl, descriptorLocation); } else { return super.createArchive(rootUrl, descriptorLocation, properties); } } }
2,424
33.15493
159
java
null
wildfly-main/jpa/eclipselink/src/main/java/org/jipijapa/eclipselink/VFSArchive.java
/* * JBoss, Home of Professional Open Source. * Copyright 2015, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jipijapa.eclipselink; import java.io.IOException; import java.io.InputStream; import java.net.URISyntaxException; import java.net.URL; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.eclipse.persistence.jpa.Archive; import org.jboss.vfs.VFS; import org.jboss.vfs.VirtualFile; import org.jboss.vfs.VirtualFileFilter; /** * This is the guts of the Eclipse-to-JBossAS7 integration for * automatic entity class discovery. The entry point is * JBossArchiveFactoryImpl; see there for how to use this. * * @author Rich DiCroce * */ public class VFSArchive implements Archive { protected URL rootUrl; protected String descriptorLocation; protected VirtualFile root; protected Map<String, VirtualFile> files; public VFSArchive(URL rootUrl, String descriptorLocation) throws URISyntaxException, IOException { this.rootUrl = rootUrl; this.descriptorLocation = descriptorLocation; root = VFS.getChild(rootUrl.toURI()); List<VirtualFile> children = root.getChildrenRecursively(new VirtualFileFilter() { @Override public boolean accepts(VirtualFile file) { return file.isFile(); } }); files = new HashMap<String, VirtualFile>(); for (VirtualFile file : children) { files.put(file.getPathNameRelativeTo(root), file); } } @Override public Iterator<String> getEntries() { return files.keySet().iterator(); } @Override public InputStream getEntry(String entryPath) throws IOException { return files.containsKey(entryPath) ? files.get(entryPath).openStream() : null; } @Override public URL getEntryAsURL(String entryPath) throws IOException { return files.containsKey(entryPath) ? files.get(entryPath).asFileURL() : null; } @Override public URL getRootURL() { return rootUrl; } @Override public InputStream getDescriptorStream() throws IOException { return files.get(descriptorLocation).openStream(); } @Override public void close() {} // nothing to close }
3,217
30.861386
102
java
null
wildfly-main/jpa/eclipselink/src/main/java/org/jipijapa/eclipselink/JBossAS7ServerPlatform.java
/* * JBoss, Home of Professional Open Source. * Copyright 2015, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jipijapa.eclipselink; import org.eclipse.persistence.sessions.DatabaseSession; /** * The fully qualified name of JBossASServerPlatform must be set as the value * of the eclipselink.target-server property on EclipseLink version 2.3.2 and * older. In newer versions where bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=365704 * has been fixed, setting eclipselink.target-server to "jboss" is sufficient. * * @author Craig Ringer <[email protected]> * * @deprecated use WildFlyServerPlatform instead */ public class JBossAS7ServerPlatform extends WildFlyServerPlatform { public JBossAS7ServerPlatform(DatabaseSession newDatabaseSession) { super(newDatabaseSession); } }
1,746
39.627907
90
java
null
wildfly-main/jpa/eclipselink/src/main/java/org/jipijapa/eclipselink/JBossLogger.java
/* * JBoss, Home of Professional Open Source. * Copyright 2015, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jipijapa.eclipselink; import java.util.HashMap; import java.util.Map; import org.eclipse.persistence.logging.AbstractSessionLog; import org.eclipse.persistence.logging.SessionLogEntry; import org.jboss.logging.Logger; import org.jboss.logging.Logger.Level; /** * JBossLogger integrates Eclipse's logging with JBoss logger, so you can * configure log levels via the server and get the same log formatting * as everything else. * <p/> * See https://community.jboss.org/wiki/HowToUseEclipseLinkWithAS7 */ public class JBossLogger extends AbstractSessionLog { private static final String ORG_ECLIPSE_PERSISTENCE = "org.eclipse.persistence"; private Map<String, Logger> loggers = new HashMap<String, Logger>(); @Override public void log(SessionLogEntry sessionLogEntry) { Logger logger = getLoggerForCategory(sessionLogEntry.getNameSpace()); Level level = convertLevelIntToEnum(sessionLogEntry.getLevel()); String message = formatMessage(sessionLogEntry); logger.log(level, message); } @Override public boolean shouldLog(int level, String category) { return getLoggerForCategory(category).isEnabled(convertLevelIntToEnum(level)); } private Logger getLoggerForCategory(String category) { Logger logger = loggers.get(category); if (logger == null) { logger = Logger.getLogger(ORG_ECLIPSE_PERSISTENCE, (category == null ? "" : category)); loggers.put(category, logger); } return logger; } private Level convertLevelIntToEnum(int level) { switch (level) { case SEVERE: return Level.FATAL; case WARNING: return Level.WARN; case CONFIG: case INFO: return Level.INFO; case FINE: return Level.DEBUG; case FINER: case FINEST: return Level.TRACE; default: getLoggerForCategory("logging").warnv("Received message for log level {0}, but no such level is defined in SessionLog! Logging at INFO level...", level); return Level.INFO; } } /** * Show bound parameters in EclipseLink logging (JIPI-5) * * @return true to show bind parameters */ @Override public boolean shouldDisplayData() { if (shouldDisplayData == null) { return getLoggerForCategory("sql").isDebugEnabled(); } else { return shouldDisplayData.booleanValue(); } } }
3,618
33.466667
169
java
null
wildfly-main/jpa/eclipselink/src/main/java/org/jipijapa/eclipselink/EclipseLinkPersistenceProviderAdaptor.java
/* * JBoss, Home of Professional Open Source. * Copyright 2015, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jipijapa.eclipselink; import java.util.Map; import jakarta.enterprise.inject.spi.BeanManager; import org.jipijapa.plugin.spi.JtaManager; import org.jipijapa.plugin.spi.ManagementAdaptor; import org.jipijapa.plugin.spi.PersistenceProviderAdaptor; import org.jipijapa.plugin.spi.PersistenceUnitMetadata; import org.jipijapa.plugin.spi.Platform; public class EclipseLinkPersistenceProviderAdaptor implements PersistenceProviderAdaptor { public static final String ECLIPSELINK_TARGET_SERVER = "eclipselink.target-server", ECLIPSELINK_ARCHIVE_FACTORY = "eclipselink.archive.factory", ECLIPSELINK_LOGGING_LOGGER = "eclipselink.logging.logger"; @SuppressWarnings({ "rawtypes", "unchecked" }) @Override public void addProviderProperties(Map properties, PersistenceUnitMetadata pu) { if (!pu.getProperties().containsKey(ECLIPSELINK_ARCHIVE_FACTORY)) { properties.put(ECLIPSELINK_ARCHIVE_FACTORY, JBossArchiveFactoryImpl.class.getName()); } if (!pu.getProperties().containsKey(ECLIPSELINK_TARGET_SERVER)) { properties.put(ECLIPSELINK_TARGET_SERVER, WildFlyServerPlatform.class.getName()); } if (!pu.getProperties().containsKey(ECLIPSELINK_LOGGING_LOGGER)) { properties.put(ECLIPSELINK_LOGGING_LOGGER, JBossLogger.class.getName()); } } @Override public void injectJtaManager(JtaManager jtaManager) { // No action required, EclipseLink looks this up from JNDI } @Override public void injectPlatform(Platform platform) { } @Override public void addProviderDependencies(PersistenceUnitMetadata pu) { // No action required } @Override public void beforeCreateContainerEntityManagerFactory( PersistenceUnitMetadata pu) { // no action required } @Override public void afterCreateContainerEntityManagerFactory( PersistenceUnitMetadata pu) { // TODO: Force creation of metamodel here? } @Override public ManagementAdaptor getManagementAdaptor() { // no action required return null; } @Override public boolean doesScopedPersistenceUnitNameIdentifyCacheRegionName(PersistenceUnitMetadata pu) { return false; } @Override public void cleanup(PersistenceUnitMetadata pu) { // no action required } @Override public Object beanManagerLifeCycle(BeanManager beanManager) { return null; } @Override public void markPersistenceUnitAvailable(Object wrapperBeanManagerLifeCycle) { } }
3,664
30.869565
101
java
null
wildfly-main/jpa/eclipselink/src/main/java/org/jipijapa/eclipselink/WildFlyServerPlatform.java
/* * JBoss, Home of Professional Open Source. * Copyright 2015, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jipijapa.eclipselink; import java.security.AccessController; import java.security.PrivilegedActionException; import java.security.PrivilegedExceptionAction; import java.util.List; import javax.management.MBeanServer; import javax.management.MBeanServerFactory; import javax.naming.InitialContext; import javax.naming.NamingException; import jakarta.transaction.TransactionManager; import org.eclipse.persistence.internal.security.PrivilegedAccessHelper; import org.eclipse.persistence.platform.server.jboss.JBossPlatform; import org.eclipse.persistence.sessions.DatabaseSession; import org.eclipse.persistence.sessions.ExternalTransactionController; import org.eclipse.persistence.transaction.jboss.JBossTransactionController; import org.jipijapa.JipiLogger; /** * The fully qualified name of WildFlyServerPlatform must be set as the value * of the eclipselink.target-server property on EclipseLink version 2.3.2 and * older. In newer versions where bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=365704 * has been fixed, setting eclipselink.target-server to "jboss" is sufficient. * * @author Craig Ringer <[email protected]> * */ public class WildFlyServerPlatform extends JBossPlatform { public WildFlyServerPlatform(DatabaseSession newDatabaseSession) { super(newDatabaseSession); } @Override public Class<? extends ExternalTransactionController> getExternalTransactionControllerClass() { return JBossAS7TransactionController.class; } @Override public MBeanServer getMBeanServer() { if(mBeanServer == null) { List<MBeanServer> mBeanServerList = null; try { if (PrivilegedAccessHelper.shouldUsePrivilegedAccess()) { try { mBeanServerList = AccessController.doPrivileged( new PrivilegedExceptionAction<List<MBeanServer>>() { public List<MBeanServer> run() { return MBeanServerFactory.findMBeanServer(null); } } ); } catch (PrivilegedActionException pae) { // Skip the superclass impl of a JNDI lookup } } else { mBeanServerList = MBeanServerFactory.findMBeanServer(null); } // Attempt to get the first MBeanServer we find - usually there is only one - when agentId == null we return a // List of them if (mBeanServer == null && mBeanServerList != null && !mBeanServerList.isEmpty()) { // Use the first MBeanServer by default - there may be multiple domains each with their own MBeanServer mBeanServer = mBeanServerList.get(JMX_MBEANSERVER_INDEX_DEFAULT_FOR_MULTIPLE_SERVERS); if (mBeanServerList.size() > 1 && null != mBeanServer.getDefaultDomain()) { // Prefer no default domain, as WildFly does not register an mbean server with a default domain for (int i = 1; i < mBeanServerList.size(); i++) { MBeanServer anMBeanServer = mBeanServerList.get(i); if (null == anMBeanServer.getDefaultDomain()) { mBeanServer = anMBeanServer; break; } } } // else { // Skip the superclass impl of trying ManagementFactory.getPlatformMBeanServer() // if privileged access is disabled. // WildFly has already called that by the time this code would get run, so if we // got here it's an error situation and we should just return null // } } } catch (Exception e) { JipiLogger.JPA_LOGGER.error(e.getLocalizedMessage(), e); } } return mBeanServer; } public static class JBossAS7TransactionController extends JBossTransactionController { private static final String JBOSS_TRANSACTION_MANAGER = "java:jboss/TransactionManager"; @Override protected TransactionManager acquireTransactionManager() throws Exception { try { return InitialContext.doLookup(JBOSS_TRANSACTION_MANAGER); } catch (NamingException ex) { return super.acquireTransactionManager(); } } } }
5,783
43.492308
126
java
null
wildfly-main/jpa/hibernatesearch/src/main/java/org/jipijapa/hibernate/search/HibernateSearchIntegratorAdaptor.java
/* * JBoss, Home of Professional Open Source. * Copyright 2023, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jipijapa.hibernate.search; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.function.Function; import java.util.regex.Pattern; import org.hibernate.search.engine.cfg.spi.ConvertUtils; import org.hibernate.search.mapper.orm.cfg.HibernateOrmMapperSettings; import org.jboss.jandex.Index; import org.jipijapa.plugin.spi.PersistenceProviderIntegratorAdaptor; import org.jipijapa.plugin.spi.PersistenceUnitMetadata; /** * Implements the PersistenceProviderIntegratorAdaptor for Hibernate Search */ public class HibernateSearchIntegratorAdaptor implements PersistenceProviderIntegratorAdaptor { // Same as org.hibernate.search.engine.cfg.impl.OptionalPropertyContextImpl.MULTI_VALUE_SEPARATOR_PATTERN private static final Pattern MULTI_VALUE_SEPARATOR_PATTERN = Pattern.compile( "," ); private Collection<Index> indexes; private final List<WildFlyHibernateOrmSearchMappingConfigurer> configurers = new ArrayList<>(); @Override public void injectIndexes(Collection<Index> indexes) { this.indexes = indexes; } @Override public void addIntegratorProperties(Map<String, Object> properties, PersistenceUnitMetadata pu) { // See WildFlyHibernateOrmSearchMappingConfigurer addMappingConfigurer(properties, pu); } private void addMappingConfigurer(Map<String, Object> properties, PersistenceUnitMetadata pu) { Properties puProperties = pu.getProperties(); List<Object> mappingConfigurerRefs = new ArrayList<>(); Object customMappingConfigurerRefs = puProperties.get(HibernateOrmMapperSettings.MAPPING_CONFIGURER); if (customMappingConfigurerRefs != null) { // We need to parse user-provided config to preserve it try { mappingConfigurerRefs.addAll(ConvertUtils.convertMultiValue(MULTI_VALUE_SEPARATOR_PATTERN, Function.identity(), customMappingConfigurerRefs)); } catch (RuntimeException e) { throw JpaHibernateSearchLogger.JPA_HIBERNATE_SEARCH_LOGGER.failOnPropertyParsingForIntegration( pu.getPersistenceUnitName(), HibernateOrmMapperSettings.MAPPING_CONFIGURER, e); } } // Change the default behavior of Hibernate Search regarding Jandex indexes WildFlyHibernateOrmSearchMappingConfigurer configurer = new WildFlyHibernateOrmSearchMappingConfigurer(indexes); configurers.add(configurer); // for cleaning up later, see methods below mappingConfigurerRefs.add(0, configurer); properties.put(HibernateOrmMapperSettings.MAPPING_CONFIGURER, mappingConfigurerRefs); } @Override public void afterCreateContainerEntityManagerFactory(PersistenceUnitMetadata pu) { // Don't keep any reference to indexes, as those can be quite large. indexes = null; for (WildFlyHibernateOrmSearchMappingConfigurer configurer : configurers) { configurer.clearIndexReferences(); } configurers.clear(); } }
4,159
43.255319
120
java
null
wildfly-main/jpa/hibernatesearch/src/main/java/org/jipijapa/hibernate/search/JpaHibernateSearchLogger.java
/* * JBoss, Home of Professional Open Source. * Copyright 2023, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jipijapa.hibernate.search; import org.jboss.logging.BasicLogger; import org.jboss.logging.Logger; import org.jboss.logging.annotations.Cause; import org.jboss.logging.annotations.Message; import org.jboss.logging.annotations.MessageLogger; /** * JipiJapa message range is 20200-20299 * note: keep duplicate messages in sync between different sub-projects that use the same messages */ @MessageLogger(projectCode = "JIPISEARCH") public interface JpaHibernateSearchLogger extends BasicLogger { /** * A logger with the category {@code org.jipijapa}. */ JpaHibernateSearchLogger JPA_HIBERNATE_SEARCH_LOGGER = Logger.getMessageLogger(JpaHibernateSearchLogger.class, "org.jipijapa"); @Message(id = 20290, value = "Failed to parse property '%2$s' while integrating Hibernate Search into persistence unit '%1$s") IllegalStateException failOnPropertyParsingForIntegration(String puUnitName, String propertyKey, @Cause Exception cause); }
1,999
41.553191
131
java
null
wildfly-main/jpa/hibernatesearch/src/main/java/org/jipijapa/hibernate/search/WildFlyHibernateOrmSearchMappingConfigurer.java
/* * JBoss, Home of Professional Open Source. * Copyright 2023, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jipijapa.hibernate.search; import org.hibernate.search.mapper.orm.mapping.HibernateOrmMappingConfigurationContext; import org.hibernate.search.mapper.orm.mapping.HibernateOrmSearchMappingConfigurer; import org.jboss.jandex.Index; import java.util.Collection; final class WildFlyHibernateOrmSearchMappingConfigurer implements HibernateOrmSearchMappingConfigurer { private Collection<Index> indexes; public WildFlyHibernateOrmSearchMappingConfigurer(Collection<Index> indexes) { this.indexes = indexes; } @Override public void configure(HibernateOrmMappingConfigurationContext context) { // Hibernate Search can't deal with WildFly's JAR URLs using vfs://, // so it fails to load Jandex indexes from the JARs. // Regardless, WildFly already has Jandex indexes in memory, // so we'll configure Hibernate Search to just use those. context.annotationMapping().discoverJandexIndexesFromAddedTypes(false) .buildMissingDiscoveredJandexIndexes(false); if (indexes != null) { for (Index index : indexes) { // This class is garbage-collected after bootstrap, // so the reference to indexes does not matter. context.annotationMapping().addJandexIndex(index); } } } public void clearIndexReferences() { indexes = null; } }
2,445
40.457627
103
java
null
wildfly-main/jsf/subsystem/src/test/java/org/jboss/as/jsf/deployment/JSFModuleIdFactoryTestCase.java
/* * JBoss, Home of Professional Open Source * Copyright 2012 Red Hat Inc. and/or its affiliates and other contributors * as indicated by the @author tags. All rights reserved. * See the copyright.txt in the distribution for a * full listing of individual contributors. * * This copyrighted material is made available to anyone wishing to use, * modify, copy, or redistribute it subject to the terms and conditions * of the GNU Lesser General Public License, v. 2.1. * This program is distributed in the hope that it will be useful, but WITHOUT A * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. * You should have received a copy of the GNU Lesser General Public License, * v.2.1 along with this distribution; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ package org.jboss.as.jsf.deployment; import java.util.List; import org.junit.Assert; import org.junit.Ignore; import org.junit.Test; /** * Tests for the JSFModuleIdFactory * * @author Stan Silvert [email protected] (C) 2012 Red Hat Inc. */ public class JSFModuleIdFactoryTestCase { private static final String API_MODULE = "jakarta.faces.api"; private static final String IMPL_MODULE = "jakarta.faces.impl"; private static final String INJECTION_MODULE = "org.jboss.as.jsf-injection"; private static final JSFModuleIdFactory factory = JSFModuleIdFactory.getInstance(); @Test public void getActiveJSFVersionsTest() { List<String> versions = factory.getActiveJSFVersions(); Assert.assertEquals(3, versions.size()); Assert.assertTrue(versions.contains("main")); Assert.assertTrue(versions.contains("myfaces")); } @Test public void computeSlotTest() { Assert.assertEquals("main", factory.computeSlot("main")); Assert.assertEquals("main", factory.computeSlot(null)); Assert.assertEquals("main", factory.computeSlot(JsfVersionMarker.JSF_4_0)); Assert.assertEquals("myfaces2", factory.computeSlot("myfaces2")); } @Test public void validSlotTest() { Assert.assertTrue(factory.isValidJSFSlot("main")); Assert.assertTrue(factory.isValidJSFSlot("myfaces")); Assert.assertTrue(factory.isValidJSFSlot(JsfVersionMarker.JSF_4_0)); Assert.assertFalse(factory.isValidJSFSlot(JsfVersionMarker.WAR_BUNDLES_JSF_IMPL)); Assert.assertFalse(factory.isValidJSFSlot("bogus")); Assert.assertFalse(factory.isValidJSFSlot("bogus2")); } @Test @Ignore("Depends on https://issues.redhat.com/browse/WFLY-17405") public void modIdsTest() { Assert.assertEquals(API_MODULE, factory.getApiModId("main").getName()); Assert.assertEquals("main", factory.getApiModId("main").getSlot()); Assert.assertEquals(IMPL_MODULE, factory.getImplModId("main").getName()); Assert.assertEquals("main", factory.getImplModId("main").getSlot()); Assert.assertEquals(INJECTION_MODULE, factory.getInjectionModId("main").getName()); Assert.assertEquals("main", factory.getInjectionModId("main").getSlot()); Assert.assertEquals(API_MODULE, factory.getApiModId("myfaces").getName()); Assert.assertEquals("myfaces", factory.getApiModId("myfaces").getSlot()); Assert.assertEquals(IMPL_MODULE, factory.getImplModId("myfaces").getName()); Assert.assertEquals("myfaces", factory.getImplModId("myfaces").getSlot()); Assert.assertEquals(INJECTION_MODULE, factory.getInjectionModId("myfaces").getName()); Assert.assertEquals("myfaces", factory.getInjectionModId("myfaces").getSlot()); Assert.assertEquals(API_MODULE, factory.getApiModId("myfaces2").getName()); Assert.assertEquals("myfaces2", factory.getApiModId("myfaces2").getSlot()); Assert.assertEquals(IMPL_MODULE, factory.getImplModId("myfaces2").getName()); Assert.assertEquals("myfaces2", factory.getImplModId("myfaces2").getSlot()); Assert.assertEquals(INJECTION_MODULE, factory.getInjectionModId("myfaces2").getName()); Assert.assertEquals("myfaces2", factory.getInjectionModId("myfaces2").getSlot()); } }
4,302
46.285714
95
java
null
wildfly-main/jsf/subsystem/src/test/java/org/jboss/as/jsf/subsystem/JSFSubsystemTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2011, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.jsf.subsystem; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SUBSYSTEM; import static org.junit.Assert.assertEquals; import java.io.IOException; import org.jboss.as.subsystem.test.AbstractSubsystemBaseTest; import org.jboss.as.subsystem.test.AdditionalInitialization; import org.jboss.as.subsystem.test.KernelServices; import org.jboss.as.subsystem.test.KernelServicesBuilder; import org.jboss.dmr.ModelNode; import org.junit.Test; /** * * @author Stuart Douglas */ public class JSFSubsystemTestCase extends AbstractSubsystemBaseTest { public JSFSubsystemTestCase() { super(JSFExtension.SUBSYSTEM_NAME, new JSFExtension()); } @Override protected String getSubsystemXml() throws IOException { return "<subsystem xmlns=\"urn:jboss:domain:jsf:1.1\"" + " default-jsf-impl-slot=\"${exp.default-jsf-impl-slot:main}\"" + " disallow-doctype-decl=\"${exp.disallow-doctype-decl:true}\" />"; } @Override protected String getSubsystemXsdPath() throws Exception { return "schema/jboss-as-jsf_1_1.xsd"; } @Test public void testAttributes() throws Exception { KernelServicesBuilder builder = createKernelServicesBuilder(AdditionalInitialization.MANAGEMENT) .setSubsystemXml(getSubsystemXml()); KernelServices kernelServices = builder.build(); ModelNode rootModel = kernelServices.readWholeModel(); ModelNode serverModel = rootModel.require(SUBSYSTEM).require(JSFExtension.SUBSYSTEM_NAME); assertEquals("main", serverModel.get(JSFResourceDefinition.DEFAULT_SLOT_ATTR_NAME).resolve().asString()); assertEquals(true, serverModel.get(JSFResourceDefinition.DISALLOW_DOCTYPE_DECL_ATTR_NAME).resolve().asBoolean()); } }
2,836
40.720588
121
java
null
wildfly-main/jsf/subsystem/src/main/java/org/jboss/as/jsf/logging/JSFLogger.java
/* * JBoss, Home of Professional Open Source. * Copyright 2021, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.jsf.logging; import static org.jboss.logging.Logger.Level.DEBUG; import static org.jboss.logging.Logger.Level.ERROR; import static org.jboss.logging.Logger.Level.INFO; import static org.jboss.logging.Logger.Level.WARN; import java.util.List; import org.jboss.as.server.deployment.DeploymentUnitProcessingException; import org.jboss.jandex.AnnotationTarget; import org.jboss.jandex.DotName; import org.jboss.logging.BasicLogger; import org.jboss.logging.Logger; import org.jboss.logging.annotations.Cause; import org.jboss.logging.annotations.LogMessage; import org.jboss.logging.annotations.Message; import org.jboss.logging.annotations.MessageLogger; import org.jboss.vfs.VirtualFile; /** * Date: 05.11.2011 * * @author Stuart Douglas * @author <a href="mailto:[email protected]">David M. Lloyd</a> */ @MessageLogger(projectCode = "WFLYJSF", length = 4) public interface JSFLogger extends BasicLogger { /** * A logger with a category of the package name. */ JSFLogger ROOT_LOGGER = Logger.getMessageLogger(JSFLogger.class, "org.jboss.as.jsf"); @LogMessage(level = WARN) @Message(id = 1, value = "WildFlyConversationAwareViewHandler was improperly initialized. Expected ViewHandler parent.") void viewHandlerImproperlyInitialized(); @LogMessage(level = ERROR) @Message(id = 2, value = "Could not load Jakarta Server Faces managed bean class: %s") void managedBeanLoadFail(String managedBean); @LogMessage(level = ERROR) @Message(id = 3, value = "Jakarta Server Faces managed bean class %s has no default constructor") void managedBeanNoDefaultConstructor(String managedBean); @LogMessage(level = ERROR) @Message(id = 4, value = "Failed to parse %s, Jakarta Server Faces artifacts defined in this file will not be available") void managedBeansConfigParseFailed(VirtualFile facesConfig); @LogMessage(level = WARN) @Message(id = 5, value = "Unknown Jakarta Server Faces version '%s'. Default version '%s' will be used instead.") void unknownJSFVersion(String version, String defaultVersion); @LogMessage(level = WARN) @Message(id = 6, value = "Jakarta Server Faces version slot '%s' is missing from module %s") void missingJSFModule(String version, String module); @LogMessage(level = INFO) @Message(id = 7, value = "Activated the following Jakarta Server Faces Implementations: %s") void activatedJSFImplementations(List target); @Message(id = 8, value = "Failed to load annotated class: %s") String classLoadingFailed(DotName clazz); @Message(id = 9, value = "Annotation %s in class %s is only allowed on classes") String invalidAnnotationLocation(Object annotation, AnnotationTarget classInfo); // @Message(id = 10, value = "Instance creation failed") // RuntimeException instanceCreationFailed(@Cause Throwable t); // // @Message(id = 11, value = "Instance destruction failed") // RuntimeException instanceDestructionFailed(@Cause Throwable t); // // @Message(id = 12, value = "Thread local injection container not set") // IllegalStateException noThreadLocalInjectionContainer(); @Message(id = 13, value = "@ManagedBean is only allowed at class level %s") String invalidManagedBeanAnnotation(AnnotationTarget target); @Message(id = 14, value = "Default Jakarta Server Faces implementation slot '%s' is invalid") DeploymentUnitProcessingException invalidDefaultJSFImpl(String defaultJsfVersion); // @LogMessage(level = ERROR) // @Message(id = 15, value = "Failed to parse %s, phase listeners defined in this file will not be available") // void phaseListenersConfigParseFailed(VirtualFile facesConfig); @Message(id = 16, value = "Failed to inject Jakarta Server Faces from slot %s") DeploymentUnitProcessingException jsfInjectionFailed(String slotName, @Cause Throwable cause); @LogMessage(level = DEBUG) @Message(id = 17, value = "Faces 1.2 classes detected. Using org.jboss.as.jsf.injection.weld.legacy.WeldApplicationFactoryLegacy.") void loadingJsf12(); @LogMessage(level = DEBUG) @Message(id = 18, value = "Faces 1.2 classes not detected. Using org.jboss.as.jsf.injection.weld.WeldApplicationFactory.") void loadingJsf2x(); @LogMessage(level = INFO) @Message(id = 19, value = "Jakarta Server Faces artifact %s with class %s has no default constructor so it will not be considered for injection") void jsfArtifactNoDefaultConstructor(String type, String className); @LogMessage(level = WARN) @Message(id = 20, value = "Lazy bean validation was enabled. This can result in missing @PreDestroy events when distributed web sessions expire.") void lazyBeanValidationEnabled(); }
5,776
43.782946
150
java
null
wildfly-main/jsf/subsystem/src/main/java/org/jboss/as/jsf/deployment/JSFCdiExtensionDeploymentProcessor.java
/** * JBoss, Home of Professional Open Source. * Copyright 2014, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.jsf.deployment; import static org.jboss.as.weld.Capabilities.WELD_CAPABILITY_NAME; import org.jboss.as.controller.capability.CapabilityServiceSupport; import org.jboss.as.server.deployment.Attachments; import org.jboss.as.server.deployment.DeploymentPhaseContext; import org.jboss.as.server.deployment.DeploymentUnit; import org.jboss.as.server.deployment.DeploymentUnitProcessingException; import org.jboss.as.server.deployment.DeploymentUnitProcessor; import org.jboss.as.weld.WeldCapability; /** * {@link DeploymentUnitProcessor} which registers CDI extensions. Currently only registers * {@link JSFPassivatingViewScopedCdiExtension} to workaround WFLY-3044 / JAVASERVERFACES-3191. * * @author <a href="http://www.radoslavhusar.com/">Radoslav Husar</a> * @version Apr 10, 2014 * @since 8.0.1 */ public class JSFCdiExtensionDeploymentProcessor implements DeploymentUnitProcessor { public void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException { final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit(); final DeploymentUnit parent = deploymentUnit.getParent() == null ? deploymentUnit : deploymentUnit.getParent(); if(JsfVersionMarker.isJsfDisabled(deploymentUnit)) { return; } final CapabilityServiceSupport support = deploymentUnit.getAttachment(Attachments.CAPABILITY_SERVICE_SUPPORT); if (support.hasCapability(WELD_CAPABILITY_NAME)) { support.getOptionalCapabilityRuntimeAPI(WELD_CAPABILITY_NAME, WeldCapability.class).get() .registerExtensionInstance(new JSFPassivatingViewScopedCdiExtension(), parent); } } }
2,732
46.12069
119
java
null
wildfly-main/jsf/subsystem/src/main/java/org/jboss/as/jsf/deployment/JSFPassivatingViewScopedCdiExtension.java
/** * JBoss, Home of Professional Open Source. * Copyright 2014, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.jsf.deployment; import jakarta.enterprise.event.Observes; import jakarta.enterprise.inject.spi.BeanManager; import jakarta.enterprise.inject.spi.BeforeBeanDiscovery; import jakarta.enterprise.inject.spi.Extension; import jakarta.faces.view.ViewScoped; /** * Workaround for WFLY-3044 / JAVASERVERFACES-3191 making {@link ViewScoped} annotation passivating. Proper fix * requires a spec maintenance release. * * @author <a href="http://www.radoslavhusar.com/">Radoslav Husar</a> * @version Apr 10, 2014 * @since 8.0.1 */ public class JSFPassivatingViewScopedCdiExtension implements Extension { public void beforeBeanDiscovery(@Observes BeforeBeanDiscovery event, BeanManager manager) { event.addScope(ViewScoped.class, true, true); } }
1,806
39.155556
111
java
null
wildfly-main/jsf/subsystem/src/main/java/org/jboss/as/jsf/deployment/JSFBeanValidationFactoryProcessor.java
/* * JBoss, Home of Professional Open Source. * Copyright 2013, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.jsf.deployment; import static jakarta.faces.validator.BeanValidator.VALIDATOR_FACTORY_KEY; import jakarta.validation.ValidatorFactory; import org.jboss.as.ee.beanvalidation.BeanValidationAttachments; import org.jboss.as.server.deployment.DeploymentPhaseContext; import org.jboss.as.server.deployment.DeploymentUnit; import org.jboss.as.server.deployment.DeploymentUnitProcessingException; import org.jboss.as.server.deployment.DeploymentUnitProcessor; import org.jboss.as.web.common.ServletContextAttribute; /** * Deployment processor that adds the Jakarta Contexts and Dependency Injection enabled ValidatorFactory to the servlet context. * * @author Farah Juma */ public class JSFBeanValidationFactoryProcessor implements DeploymentUnitProcessor { @Override public void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException { final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit(); if(JsfVersionMarker.isJsfDisabled(deploymentUnit)) { return; } // Get the Jakarta Contexts and Dependency Injection enabled ValidatorFactory and add it to the servlet context ValidatorFactory validatorFactory = deploymentUnit.getAttachment(BeanValidationAttachments.VALIDATOR_FACTORY); if(validatorFactory != null) { deploymentUnit.addToAttachmentList(ServletContextAttribute.ATTACHMENT_KEY, new ServletContextAttribute(VALIDATOR_FACTORY_KEY, validatorFactory)); } } }
2,569
41.833333
128
java
null
wildfly-main/jsf/subsystem/src/main/java/org/jboss/as/jsf/deployment/JSFMetadataProcessor.java
package org.jboss.as.jsf.deployment; import java.util.ArrayList; import java.util.List; import jakarta.faces.application.ViewHandler; import org.jboss.as.jsf.logging.JSFLogger; import org.jboss.as.server.deployment.DeploymentPhaseContext; import org.jboss.as.server.deployment.DeploymentUnit; import org.jboss.as.server.deployment.DeploymentUnitProcessingException; import org.jboss.as.server.deployment.DeploymentUnitProcessor; import org.jboss.as.web.common.WarMetaData; import org.jboss.metadata.javaee.spec.ParamValueMetaData; import org.jboss.metadata.web.jboss.JBossServletMetaData; import org.jboss.metadata.web.jboss.JBossWebMetaData; import org.jboss.metadata.web.spec.MultipartConfigMetaData; /** * @author Stuart Douglas */ public class JSFMetadataProcessor implements DeploymentUnitProcessor { public static final String JAVAX_FACES_WEBAPP_FACES_SERVLET = "jakarta.faces.webapp.FacesServlet"; private static final String DISALLOW_DOCTYPE_DECL = "com.sun.faces.disallowDoctypeDecl"; private static final String LAZY_BEAN_VALIDATION_PARAM = "com.sun.faces.enableLazyBeanValidation"; private static final int defaultBufferSize; // This is copied from org.wildfly.extension.undertow.ByteBufferPoolDefinition to come up with a decent default for // the jakarta.faces.FACELETS_BUFFER_SIZE property. We calculate this because the default is 1024, which is very // small, https://jakarta.ee/specifications/faces/4.0/jakarta-faces-4.0.html#a6088. Per the spec we could use -1 // as the default, but Mojarra does not currently support that. Once https://github.com/eclipse-ee4j/mojarra/issues/5262 // is resolved, and we can upgrade, we should be able to default to -1. static { long maxMemory = Runtime.getRuntime().maxMemory(); //smaller than 64mb of ram we use 512b buffers if (maxMemory < 64 * 1024 * 1024) { //use 512b buffers defaultBufferSize = 512; } else if (maxMemory < 128 * 1024 * 1024) { //use 1k buffers defaultBufferSize = 1024; } else { //use 16k buffers for best performance //as 16k is generally the max amount of data that can be sent in a single write() call defaultBufferSize = 1024 * 16; } } private final Boolean disallowDoctypeDecl; public JSFMetadataProcessor(final Boolean disallowDoctypeDecl) { this.disallowDoctypeDecl = disallowDoctypeDecl; } @Override public void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException { DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit(); WarMetaData metaData = deploymentUnit.getAttachment(WarMetaData.ATTACHMENT_KEY); if(JsfVersionMarker.isJsfDisabled(deploymentUnit)) { return; } if(metaData == null || metaData.getMergedJBossWebMetaData() == null || metaData.getMergedJBossWebMetaData().getServlets() == null) { return; } JBossServletMetaData jsf = null; for(JBossServletMetaData servlet : metaData.getMergedJBossWebMetaData().getServlets()) { if(JAVAX_FACES_WEBAPP_FACES_SERVLET.equals(servlet.getServletClass())) { jsf = servlet; } } if (jsf != null && jsf.getMultipartConfig() == null) { // WFLY-2329 File upload doesn't work jsf.setMultipartConfig(new MultipartConfigMetaData()); } if (disallowDoctypeDecl != null) { // Add the disallowDoctypeDecl context param if it's not already present setContextParameterIfAbsent(metaData.getMergedJBossWebMetaData(), DISALLOW_DOCTYPE_DECL, disallowDoctypeDecl.toString()); } // Auto-disable lazy bean validation for distributable web application. // This can otherwise cause missing @PreDestroy events. if (metaData.getMergedJBossWebMetaData().getDistributable() != null) { String disabled = Boolean.toString(false); if (!setContextParameterIfAbsent(metaData.getMergedJBossWebMetaData(), LAZY_BEAN_VALIDATION_PARAM, disabled).equals(disabled)) { JSFLogger.ROOT_LOGGER.lazyBeanValidationEnabled(); } } // Set a default buffer size as 1024 is too small final JBossWebMetaData webMetaData = metaData.getMergedJBossWebMetaData(); // First check the legacy facelets.BUFFER_SIZE property which is required for backwards compatibility if (!hasContextParam(webMetaData, "facelets.BUFFER_SIZE")) { // The legacy parameter has not been set, set a default buffer if the current parameter name has not been set. setContextParameterIfAbsent(metaData.getMergedJBossWebMetaData(), ViewHandler.FACELETS_BUFFER_SIZE_PARAM_NAME, Integer.toString(defaultBufferSize)); } } private static String setContextParameterIfAbsent(final JBossWebMetaData webMetaData, final String name, final String value) { List<ParamValueMetaData> contextParams = webMetaData.getContextParams(); if (contextParams == null) { contextParams = new ArrayList<>(); webMetaData.setContextParams(contextParams); } for (ParamValueMetaData param : contextParams) { if (name.equals(param.getParamName()) && param.getParamValue() != null) { // already set return param.getParamValue(); } } ParamValueMetaData param = new ParamValueMetaData(); param.setParamName(name); param.setParamValue(value); contextParams.add(param); return value; } private static boolean hasContextParam(final JBossWebMetaData webMetaData, final String name) { final List<ParamValueMetaData> contextParams = webMetaData.getContextParams(); if (contextParams == null) { return false; } return contextParams.stream() .anyMatch(value -> name.equals(value.getParamName())); } }
6,073
47.206349
160
java
null
wildfly-main/jsf/subsystem/src/main/java/org/jboss/as/jsf/deployment/JsfVersionMarker.java
/* * JBoss, Home of Professional Open Source * Copyright 2012, Red Hat Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.jsf.deployment; import org.jboss.as.server.deployment.AttachmentKey; import org.jboss.as.server.deployment.DeploymentUnit; /** * @author Stuart Douglas */ public class JsfVersionMarker { public static final String JSF_4_0 = "Mojarra-4.0"; public static final String WAR_BUNDLES_JSF_IMPL = "WAR_BUNDLES_JSF_IMPL"; public static final String NONE = "NONE"; private JsfVersionMarker() { } private static AttachmentKey<String> VERSION_KEY = AttachmentKey.create(String.class); public static void setVersion(final DeploymentUnit deploymentUnit, final String value) { deploymentUnit.putAttachment(VERSION_KEY, value); } public static String getVersion(final DeploymentUnit deploymentUnit) { final String version = deploymentUnit.getAttachment(VERSION_KEY); return version == null ? JSF_4_0 : version; } public static boolean isJsfDisabled(final DeploymentUnit deploymentUnit) { final String version = deploymentUnit.getAttachment(VERSION_KEY); return NONE.equals(version); } }
2,108
36
92
java
null
wildfly-main/jsf/subsystem/src/main/java/org/jboss/as/jsf/deployment/JSFSharedTldsProcessor.java
/* * JBoss, Home of Professional Open Source * Copyright 2012, Red Hat Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.jsf.deployment; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLStreamReader; import org.jboss.as.server.deployment.DeploymentPhaseContext; import org.jboss.as.server.deployment.DeploymentUnit; import org.jboss.as.server.deployment.DeploymentUnitProcessingException; import org.jboss.as.server.deployment.DeploymentUnitProcessor; import org.jboss.as.web.common.SharedTldsMetaDataBuilder; import org.jboss.metadata.parser.jsp.TldMetaDataParser; import org.jboss.metadata.parser.util.NoopXMLResolver; import org.jboss.metadata.web.spec.TldMetaData; import org.jboss.modules.Module; import org.jboss.modules.ModuleClassLoader; import org.jboss.modules.ModuleLoadException; /** * Cache the TLDs for JSF and add them to deployments as needed. * * @author Stan Silvert */ public class JSFSharedTldsProcessor implements DeploymentUnitProcessor { private static final String[] JSF_TAGLIBS = { "html_basic.tld", "jsf_core.tld", "mojarra_ext.tld", "myfaces_core.tld", "myfaces_html.tld" }; public JSFSharedTldsProcessor() { } private Map<String, List<TldMetaData>> getMap() { final Map<String, List<TldMetaData>> jsfTldMap = new HashMap<>(); JSFModuleIdFactory moduleFactory = JSFModuleIdFactory.getInstance(); List<String> jsfSlotNames = moduleFactory.getActiveJSFVersions(); for (String slot : jsfSlotNames) { final List<TldMetaData> jsfTlds = new ArrayList<TldMetaData>(); try { ModuleClassLoader jsf = Module.getModuleFromCallerModuleLoader(moduleFactory.getImplModId(slot)).getClassLoader(); for (String tld : JSF_TAGLIBS) { InputStream is = jsf.getResourceAsStream("META-INF/" + tld); if (is != null) { TldMetaData tldMetaData = parseTLD(is); jsfTlds.add(tldMetaData); } } } catch (ModuleLoadException e) { // Ignore } catch (Exception e) { // Ignore } jsfTldMap.put(slot, jsfTlds); } return jsfTldMap; } private TldMetaData parseTLD(InputStream is) throws Exception { try { final XMLInputFactory inputFactory = XMLInputFactory.newInstance(); inputFactory.setXMLResolver(NoopXMLResolver.create()); XMLStreamReader xmlReader = inputFactory.createXMLStreamReader(is); return TldMetaDataParser.parse(xmlReader ); } finally { try { if (is != null) { is.close(); } } catch (IOException e) { // Ignore } } } public void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException { final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit(); final DeploymentUnit topLevelDeployment = deploymentUnit.getParent() == null ? deploymentUnit : deploymentUnit.getParent(); if(JsfVersionMarker.isJsfDisabled(deploymentUnit)) { return; } String jsfVersion = JsfVersionMarker.getVersion(topLevelDeployment); if (jsfVersion.equals(JsfVersionMarker.WAR_BUNDLES_JSF_IMPL)) { return; } // Add the shared TLDs metadata List<TldMetaData> tldsMetaData = deploymentUnit.getAttachment(SharedTldsMetaDataBuilder.ATTACHMENT_KEY); if (tldsMetaData == null) tldsMetaData = new ArrayList<TldMetaData>(); String slot = jsfVersion; if (!JSFModuleIdFactory.getInstance().isValidJSFSlot(slot)) { slot = JSFModuleIdFactory.getInstance().getDefaultSlot(); } slot = JSFModuleIdFactory.getInstance().computeSlot(slot); List<TldMetaData> jsfTlds = this.getMap().get(slot); if (jsfTlds != null) tldsMetaData.addAll(jsfTlds); deploymentUnit.putAttachment(SharedTldsMetaDataBuilder.ATTACHMENT_KEY, tldsMetaData); } }
5,234
39.581395
144
java
null
wildfly-main/jsf/subsystem/src/main/java/org/jboss/as/jsf/deployment/JSFAnnotationProcessor.java
/* * JBoss, Home of Professional Open Source. * Copyright 2012, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.jsf.deployment; import java.lang.annotation.Annotation; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.jboss.as.jsf.logging.JSFLogger; import org.jboss.as.server.deployment.Attachments; import org.jboss.as.server.deployment.DeploymentPhaseContext; import org.jboss.as.server.deployment.DeploymentUnit; import org.jboss.as.server.deployment.DeploymentUnitProcessingException; import org.jboss.as.server.deployment.DeploymentUnitProcessor; import org.jboss.as.server.deployment.annotation.CompositeIndex; import org.jboss.as.web.common.ServletContextAttribute; import org.jboss.jandex.AnnotationInstance; import org.jboss.jandex.AnnotationTarget; import org.jboss.jandex.AnnotationValue; import org.jboss.jandex.ClassInfo; import org.jboss.jandex.DotName; import org.jboss.modules.Module; /** * {@link DeploymentUnitProcessor} implementation responsible for extracting Jakarta Server Faces annotations from a deployment and attaching them * to the deployment unit to eventually be added to the {@link jakarta.servlet.ServletContext}. * * @author John Bailey */ public class JSFAnnotationProcessor implements DeploymentUnitProcessor { public static final String FACES_ANNOTATIONS_SC_ATTR = "org.jboss.as.jsf.FACES_ANNOTATIONS"; private static final String MANAGED_ANNOTATION_PARAMETER = "managed"; public void deploy(final DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException { final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit(); if(JsfVersionMarker.isJsfDisabled(deploymentUnit)) { return; } final Map<Class<? extends Annotation>, Set<Class<?>>> instances = new HashMap<Class<? extends Annotation>, Set<Class<?>>>(); final CompositeIndex compositeIndex = deploymentUnit.getAttachment(Attachments.COMPOSITE_ANNOTATION_INDEX); if (compositeIndex == null) { return; // Can not continue without index } final Module module = deploymentUnit.getAttachment(Attachments.MODULE); if (module == null) { return; // Can not continue without module } final ClassLoader classLoader = module.getClassLoader(); for (FacesAnnotation annotation : FacesAnnotation.values()) { final List<AnnotationInstance> annotationInstances = compositeIndex.getAnnotations(annotation.indexName); if (annotationInstances == null || annotationInstances.isEmpty()) { continue; } final Set<Class<?>> discoveredClasses = new HashSet<Class<?>>(); instances.put(annotation.annotationClass, discoveredClasses); for (AnnotationInstance annotationInstance : annotationInstances) { final AnnotationTarget target = annotationInstance.target(); if (target instanceof ClassInfo) { final DotName className = ClassInfo.class.cast(target).name(); final Class<?> annotatedClass; try { annotatedClass = classLoader.loadClass(className.toString()); } catch (ClassNotFoundException e) { throw new DeploymentUnitProcessingException(JSFLogger.ROOT_LOGGER.classLoadingFailed(className)); } discoveredClasses.add(annotatedClass); } else { if (annotation == FacesAnnotation.FACES_VALIDATOR || annotation == FacesAnnotation.FACES_CONVERTER || annotation == FacesAnnotation.FACES_BEHAVIOR) { // Support for Injection into Jakarta Server Faces Managed Objects allows to inject FacesValidator, FacesConverter and FacesBehavior if managed = true // Jakarta Server Faces 2.3 spec chapter 5.9.1 - Jakarta Server Faces Objects Valid for @Inject Injection AnnotationValue value = annotationInstance.value(MANAGED_ANNOTATION_PARAMETER); if (value != null && value.asBoolean()) { continue; } } throw new DeploymentUnitProcessingException(JSFLogger.ROOT_LOGGER.invalidAnnotationLocation(annotation, target)); } } } deploymentUnit.addToAttachmentList(ServletContextAttribute.ATTACHMENT_KEY, new ServletContextAttribute(FACES_ANNOTATIONS_SC_ATTR, instances)); } }
5,582
48.848214
174
java
null
wildfly-main/jsf/subsystem/src/main/java/org/jboss/as/jsf/deployment/JSFVersionProcessor.java
/* * JBoss, Home of Professional Open Source * Copyright 2021, Red Hat Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.jsf.deployment; import static org.jboss.as.weld.Capabilities.WELD_CAPABILITY_NAME; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.Set; import org.jboss.as.controller.capability.CapabilityServiceSupport; import org.jboss.as.ee.structure.DeploymentType; import org.jboss.as.ee.structure.DeploymentTypeMarker; import org.jboss.as.server.deployment.Attachments; import org.jboss.as.server.deployment.DeploymentPhaseContext; import org.jboss.as.server.deployment.DeploymentUnit; import org.jboss.as.server.deployment.DeploymentUnitProcessingException; import org.jboss.as.server.deployment.DeploymentUnitProcessor; import org.jboss.as.server.deployment.annotation.CompositeIndex; import org.jboss.as.server.deployment.module.ResourceRoot; import org.jboss.as.web.common.WarMetaData; import org.jboss.as.weld.WeldCapability; import org.jboss.jandex.AnnotationInstance; import org.jboss.jandex.ClassInfo; import org.jboss.jandex.DotName; import org.jboss.metadata.javaee.spec.ParamValueMetaData; import org.jboss.metadata.web.spec.ServletMetaData; import org.jboss.metadata.web.spec.ServletsMetaData; import org.jboss.metadata.web.spec.WebCommonMetaData; import org.jboss.metadata.web.spec.WebFragmentMetaData; import org.jboss.vfs.VirtualFile; /** * Determines the Jakarta Server Faces version that will be used by a deployment, and if Jakarta Server Faces should be used at all * * @author Stuart Douglas * @author Stan Silvert */ public class JSFVersionProcessor implements DeploymentUnitProcessor { public static final String JSF_CONFIG_NAME_PARAM = "org.jboss.jbossfaces.JSF_CONFIG_NAME"; public static final String WAR_BUNDLES_JSF_IMPL_PARAM = "org.jboss.jbossfaces.WAR_BUNDLES_JSF_IMPL"; private static final DotName[] JSF_ANNOTATIONS = { DotName.createSimple("jakarta.faces.view.facelets.FaceletsResourceResolver"), DotName.createSimple("jakarta.faces.component.behavior.FacesBehavior"), DotName.createSimple("jakarta.faces.render.FacesBehaviorRenderer"), DotName.createSimple("jakarta.faces.component.FacesComponent"), DotName.createSimple("jakarta.faces.convert.FacesConverter"), DotName.createSimple("jakarta.faces.annotation.FacesConfig"), // Should actually be check for enabled bean, but difficult to guarantee, see SERVLET_SPEC-79 DotName.createSimple("jakarta.faces.validator.FacesValidator"), DotName.createSimple("jakarta.faces.event.ListenerFor"), DotName.createSimple("jakarta.faces.event.ListenersFor"), DotName.createSimple("jakarta.faces.bean.ManagedBean"), DotName.createSimple("jakarta.faces.event.NamedEvent"), DotName.createSimple("jakarta.faces.application.ResourceDependencies"), DotName.createSimple("jakarta.faces.application.ResourceDependency"), DotName.createSimple("jakarta.faces.annotation.ManagedProperty")}; private static final DotName[] JSF_INTERFACES = { DotName.createSimple("jakarta.faces.convert.Converter"), DotName.createSimple("jakarta.faces.event.PhaseListener"), DotName.createSimple("jakarta.faces.render.Renderer"), DotName.createSimple("jakarta.faces.component.UIComponent"), DotName.createSimple("jakarta.faces.validator.Validator")}; private static final String META_INF_FACES = "META-INF/faces-config.xml"; private static final String WEB_INF_FACES = "WEB-INF/faces-config.xml"; private static final String JAVAX_FACES_WEBAPP_FACES_SERVLET = "jakarta.faces.webapp.FacesServlet"; private static final String CONFIG_FILES = "jakarta.faces.application.CONFIG_FILES"; /** * Create the Jakarta Server Faces VersionProcessor and set the default Jakarta Server Faces implementation slot. * * @param jsfSlot The model for the Jakarta Server Faces subsystem. */ public JSFVersionProcessor(String jsfSlot) { JSFModuleIdFactory.getInstance().setDefaultSlot(jsfSlot); } @Override public void deploy(final DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException { final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit(); final DeploymentUnit topLevelDeployment = deploymentUnit.getParent() == null ? deploymentUnit : deploymentUnit.getParent(); final WarMetaData metaData = deploymentUnit.getAttachment(WarMetaData.ATTACHMENT_KEY); if (!shouldJsfActivate(deploymentUnit, metaData)) { JsfVersionMarker.setVersion(deploymentUnit, JsfVersionMarker.NONE); return; } try { // As per section 5.6 of the spec, mark deployment as requiring CDI. deploymentUnit.getAttachment(Attachments.CAPABILITY_SERVICE_SUPPORT) .getCapabilityRuntimeAPI(WELD_CAPABILITY_NAME, WeldCapability.class) .markAsWeldDeployment(deploymentUnit); } catch (CapabilityServiceSupport.NoSuchCapabilityException e) { throw new DeploymentUnitProcessingException(e); } if (metaData == null) { return; } List<ParamValueMetaData> contextParams = new ArrayList<ParamValueMetaData>(); if ((metaData.getWebMetaData() != null) && (metaData.getWebMetaData().getContextParams() != null)) { contextParams.addAll(metaData.getWebMetaData().getContextParams()); } if (metaData.getWebFragmentsMetaData() != null) { for (WebFragmentMetaData fragmentMetaData : metaData.getWebFragmentsMetaData().values()) { if (fragmentMetaData.getContextParams() != null) { contextParams.addAll(fragmentMetaData.getContextParams()); } } } //we need to set the Jakarta Server Faces version for the whole deployment //as otherwise linkage errors can occur //if the user does have an ear with two wars with two different //Jakarta Server Faces versions they are going to need to use deployment descriptors //to manually sort out the dependencies for (final ParamValueMetaData param : contextParams) { if ((param.getParamName().equals(WAR_BUNDLES_JSF_IMPL_PARAM) && (param.getParamValue() != null) && (param.getParamValue().toLowerCase(Locale.ENGLISH).equals("true")))) { JsfVersionMarker.setVersion(topLevelDeployment, JsfVersionMarker.WAR_BUNDLES_JSF_IMPL); break; // WAR_BUNDLES_JSF_IMPL always wins } if (param.getParamName().equals(JSF_CONFIG_NAME_PARAM)) { JsfVersionMarker.setVersion(topLevelDeployment, param.getParamValue()); break; } } } private boolean shouldJsfActivate(final DeploymentUnit deploymentUnit, WarMetaData warMetaData) { if (!DeploymentTypeMarker.isType(DeploymentType.WAR, deploymentUnit)) { return false; } if (warMetaData != null) { WebCommonMetaData jBossWebMetaData = warMetaData.getWebMetaData(); if (isJsfDeclarationsPresent(jBossWebMetaData)) { return true; } if (warMetaData.getWebFragmentsMetaData() != null) { for (WebFragmentMetaData fragmentMetaData : warMetaData.getWebFragmentsMetaData().values()) { if(isJsfDeclarationsPresent(fragmentMetaData)) { return true; } } } } Set<ResourceRoot> roots = new HashSet<>(); roots.add(deploymentUnit.getAttachment(Attachments.DEPLOYMENT_ROOT)); roots.addAll(deploymentUnit.getAttachmentList(Attachments.RESOURCE_ROOTS)); for (ResourceRoot root : roots) { VirtualFile c = root.getRoot().getChild(META_INF_FACES); if (c.exists()) { return true; } c = root.getRoot().getChild(WEB_INF_FACES); if (c.exists()) { return true; } } CompositeIndex index = deploymentUnit.getAttachment(Attachments.COMPOSITE_ANNOTATION_INDEX); for (DotName annotation : JSF_ANNOTATIONS) { List<AnnotationInstance> annotations = index.getAnnotations(annotation); if (!annotations.isEmpty()) { return true; } } for (DotName annotation : JSF_INTERFACES) { Set<ClassInfo> implementors = index.getAllKnownImplementors(annotation); if (!implementors.isEmpty()) { return true; } } return false; } private boolean isJsfDeclarationsPresent(WebCommonMetaData jBossWebMetaData) { if (jBossWebMetaData != null) { ServletsMetaData servlets = jBossWebMetaData.getServlets(); if (servlets != null) { for (ServletMetaData servlet : servlets) { if (JAVAX_FACES_WEBAPP_FACES_SERVLET.equals(servlet.getServletClass())) { return true; } } } List<ParamValueMetaData> sc = jBossWebMetaData.getContextParams(); if (sc != null) { for (ParamValueMetaData p : sc) { if (CONFIG_FILES.equals(p.getParamName())) { return true; } } } } return false; } }
10,668
44.7897
167
java
null
wildfly-main/jsf/subsystem/src/main/java/org/jboss/as/jsf/deployment/JSFDependencyProcessor.java
/* * JBoss, Home of Professional Open Source * Copyright 2021, Red Hat Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.jsf.deployment; import java.util.ArrayList; import java.util.List; import org.jboss.as.ee.structure.DeploymentType; import org.jboss.as.ee.structure.DeploymentTypeMarker; import org.jboss.as.jsf.logging.JSFLogger; import org.jboss.as.server.deployment.Attachments; import org.jboss.as.server.deployment.DeploymentPhaseContext; import org.jboss.as.server.deployment.DeploymentUnit; import org.jboss.as.server.deployment.DeploymentUnitProcessingException; import org.jboss.as.server.deployment.DeploymentUnitProcessor; import org.jboss.as.server.deployment.module.ModuleDependency; import org.jboss.as.server.deployment.module.ModuleSpecification; import org.jboss.as.web.common.WarMetaData; import org.jboss.metadata.javaee.spec.ParamValueMetaData; import org.jboss.metadata.web.jboss.JBossWebMetaData; import org.jboss.modules.Module; import org.jboss.modules.ModuleIdentifier; import org.jboss.modules.ModuleLoadException; import org.jboss.modules.ModuleLoader; import org.jboss.modules.filter.PathFilters; /** * @author Stan Silvert [email protected] (C) 2012 Red Hat Inc. * @author Stuart Douglas */ public class JSFDependencyProcessor implements DeploymentUnitProcessor { public static final String IS_CDI_PARAM = "org.jboss.jbossfaces.IS_CDI"; private static final ModuleIdentifier JSF_SUBSYSTEM = ModuleIdentifier.create("org.jboss.as.jsf"); // We use . instead of / on this stream as a workaround to get it transformed correctly by Batavia into a Jakarta namespace private static final String JAVAX_FACES_EVENT_NAMEDEVENT_class = "/jakarta.faces.event.NamedEvent".replaceAll("\\.", "/") + ".class"; private JSFModuleIdFactory moduleIdFactory = JSFModuleIdFactory.getInstance(); @Override public void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException { final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit(); final DeploymentUnit tl = deploymentUnit.getParent() == null ? deploymentUnit : deploymentUnit.getParent(); final ModuleSpecification moduleSpecification = deploymentUnit.getAttachment(Attachments.MODULE_SPECIFICATION); final ModuleLoader moduleLoader = Module.getBootModuleLoader(); //Set default when no default version has been set on the war file String jsfVersion = JsfVersionMarker.getVersion(tl).equals(JsfVersionMarker.NONE)? JSFModuleIdFactory.getInstance().getDefaultSlot() : JsfVersionMarker.getVersion(tl); String defaultJsfVersion = JSFModuleIdFactory.getInstance().getDefaultSlot(); if(JsfVersionMarker.isJsfDisabled(deploymentUnit)) { if (jsfVersion.equals(defaultJsfVersion) && !moduleIdFactory.isValidJSFSlot(jsfVersion)) { throw JSFLogger.ROOT_LOGGER.invalidDefaultJSFImpl(defaultJsfVersion); } addJSFAPI(JsfVersionMarker.JSF_4_0, moduleSpecification, moduleLoader); return; } if (!DeploymentTypeMarker.isType(DeploymentType.WAR, deploymentUnit) && !DeploymentTypeMarker.isType(DeploymentType.EAR, deploymentUnit)) { return; } if (jsfVersion.equals(JsfVersionMarker.WAR_BUNDLES_JSF_IMPL)) { //if Jakarta Server Faces is provided by the application we leave it alone return; } //TODO: we should do that same check that is done in com.sun.faces.config.FacesInitializer //and only add the dependency if Jakarta Server Faces is actually needed if (!moduleIdFactory.isValidJSFSlot(jsfVersion)) { JSFLogger.ROOT_LOGGER.unknownJSFVersion(jsfVersion, defaultJsfVersion); jsfVersion = defaultJsfVersion; } if (jsfVersion.equals(defaultJsfVersion) && !moduleIdFactory.isValidJSFSlot(jsfVersion)) { throw JSFLogger.ROOT_LOGGER.invalidDefaultJSFImpl(defaultJsfVersion); } addJSFAPI(jsfVersion, moduleSpecification, moduleLoader); addJSFImpl(jsfVersion, moduleSpecification, moduleLoader); moduleSpecification.addSystemDependency(new ModuleDependency(moduleLoader, JSF_SUBSYSTEM, false, false, true, false)); addJSFInjection(jsfVersion, moduleSpecification, moduleLoader); WarMetaData warMetaData = deploymentUnit.getAttachment(WarMetaData.ATTACHMENT_KEY); if(warMetaData != null) { addCDIFlag(warMetaData, deploymentUnit); } } private void addJSFAPI(String jsfVersion, ModuleSpecification moduleSpecification, ModuleLoader moduleLoader) { if (jsfVersion.equals(JsfVersionMarker.WAR_BUNDLES_JSF_IMPL)) return; ModuleIdentifier jsfModule = moduleIdFactory.getApiModId(jsfVersion); ModuleDependency jsfAPI = new ModuleDependency(moduleLoader, jsfModule, false, false, false, false); moduleSpecification.addSystemDependency(jsfAPI); } private void addJSFImpl(String jsfVersion, ModuleSpecification moduleSpecification, ModuleLoader moduleLoader) { if (jsfVersion.equals(JsfVersionMarker.WAR_BUNDLES_JSF_IMPL)) return; ModuleIdentifier jsfModule = moduleIdFactory.getImplModId(jsfVersion); ModuleDependency jsfImpl = new ModuleDependency(moduleLoader, jsfModule, false, false, true, false); jsfImpl.addImportFilter(PathFilters.getMetaInfFilter(), true); moduleSpecification.addSystemDependency(jsfImpl); } private void addJSFInjection(String jsfVersion, ModuleSpecification moduleSpecification, ModuleLoader moduleLoader) throws DeploymentUnitProcessingException { if (jsfVersion.equals(JsfVersionMarker.WAR_BUNDLES_JSF_IMPL)) return; ModuleIdentifier jsfInjectionModule = moduleIdFactory.getInjectionModId(jsfVersion); ModuleDependency jsfInjectionDependency = new ModuleDependency(moduleLoader, jsfInjectionModule, false, true, true, false); try { if (isJSF12(jsfInjectionDependency, jsfInjectionModule.toString())) { JSFLogger.ROOT_LOGGER.loadingJsf12(); jsfInjectionDependency.addImportFilter(PathFilters.is("META-INF/faces-config.xml"), false); jsfInjectionDependency.addImportFilter(PathFilters.is("META-INF/1.2/faces-config.xml"), true); } else { JSFLogger.ROOT_LOGGER.loadingJsf2x(); jsfInjectionDependency.addImportFilter(PathFilters.getMetaInfFilter(), true); // Exclude Faces 1.2 faces-config.xml to make extra sure it won't interfere with JSF 2.0 deployments jsfInjectionDependency.addImportFilter(PathFilters.is("META-INF/1.2/faces-config.xml"), false); } } catch (ModuleLoadException e) { throw JSFLogger.ROOT_LOGGER.jsfInjectionFailed(jsfVersion, e); } moduleSpecification.addSystemDependency(jsfInjectionDependency); } private boolean isJSF12(ModuleDependency moduleDependency, String identifier) throws ModuleLoadException { // The class jakarta.faces.event.NamedEvent was introduced in JSF 2.0 return (moduleDependency.getModuleLoader().loadModule(identifier) .getClassLoader().getResource(JAVAX_FACES_EVENT_NAMEDEVENT_class) == null); } // Add a flag to the servlet context so that we know if we need to instantiate // a Jakarta Contexts and Dependency Injection ViewHandler. private void addCDIFlag(WarMetaData warMetaData, DeploymentUnit deploymentUnit) { JBossWebMetaData webMetaData = warMetaData.getMergedJBossWebMetaData(); if (webMetaData == null) { webMetaData = new JBossWebMetaData(); warMetaData.setMergedJBossWebMetaData(webMetaData); } List<ParamValueMetaData> contextParams = webMetaData.getContextParams(); if (contextParams == null) { contextParams = new ArrayList<ParamValueMetaData>(); } ParamValueMetaData param = new ParamValueMetaData(); param.setParamName(IS_CDI_PARAM); param.setParamValue("true"); contextParams.add(param); webMetaData.setContextParams(contextParams); } }
9,170
49.114754
175
java
null
wildfly-main/jsf/subsystem/src/main/java/org/jboss/as/jsf/deployment/JSFComponentProcessor.java
/* * JBoss, Home of Professional Open Source * Copyright 2012, Red Hat Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.jsf.deployment; import java.io.InputStream; import java.util.Deque; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLStreamConstants; import javax.xml.stream.XMLStreamReader; import org.jboss.as.ee.component.ComponentDescription; import org.jboss.as.ee.component.EEApplicationClasses; import org.jboss.as.ee.component.EEModuleDescription; import org.jboss.as.ee.structure.DeploymentType; import org.jboss.as.ee.structure.DeploymentTypeMarker; import org.jboss.as.jsf.logging.JSFLogger; import org.jboss.as.server.deployment.Attachments; import org.jboss.as.server.deployment.DeploymentPhaseContext; import org.jboss.as.server.deployment.DeploymentUnit; import org.jboss.as.server.deployment.DeploymentUnitProcessor; import org.jboss.as.server.deployment.DeploymentUtils; import org.jboss.as.server.deployment.annotation.CompositeIndex; import org.jboss.as.server.deployment.module.ResourceRoot; import org.jboss.as.web.common.WarMetaData; import org.jboss.as.web.common.WebComponentDescription; import org.jboss.metadata.javaee.spec.ParamValueMetaData; import org.jboss.metadata.parser.util.NoopXMLResolver; import org.jboss.metadata.web.spec.WebMetaData; import org.jboss.modules.Module; import org.jboss.vfs.VirtualFile; /** * Sets up Jakarta Server Faces managed beans as components using information in the annotations and * * @author Stuart Douglas */ public class JSFComponentProcessor implements DeploymentUnitProcessor { private static final String WEB_INF_FACES_CONFIG = "WEB-INF/faces-config.xml"; private static final String CONFIG_FILES = "jakarta.faces.CONFIG_FILES"; /** * Jakarta Server Faces tags that should be checked in the configuration file. All the * tags that are needed for injection are taken into account. * If more artifacts should be included just add it to the enum and to * the <em>facesConfigElement</em> tree in order to be parsed. */ private enum JsfTag { FACES_CONFIG, FACTORY, APPLICATION_FACTORY, VISIT_CONTEXT_FACTORY, EXCEPTION_HANDLER_FACTORY, EXTERNAL_CONTEXT_FACTORY, FACES_CONTEXT_FACTORY, PARTIAL_VIEW_CONTEXT_FACTORY, LIFECYCLE_FACTORY, RENDER_KIT_FACTORY, VIEW_DECLARATION_LANGUAGE_FACTORY, FACELET_CACHE_FACTORY, TAG_HANDLER_DELEGATE_FACTORY, APPLICATION, EL_RESOLVER, RESOURCE_HANDLER, STATE_MANAGER, ACTION_LISTENER, NAVIGATION_HANDLER, VIEW_HANDLER, SYSTEM_EVENT_LISTENER, SYSTEM_EVENT_LISTENER_CLASS, LIFECYCLE, PHASE_LISTENER; private final String tagName; JsfTag() { tagName = this.name().toLowerCase().replaceAll("_", "-"); } public String getTagName() { return tagName; } } /** * Helper tree class to save the XML tree structure of elements * to take into consideration for injection. */ private static class JsfTree { private final JsfTag tag; private final Map<String, JsfTree> children; public JsfTree(JsfTag tag, JsfTree... children) { this.tag = tag; this.children = new HashMap<>(); for (JsfTree c : children) { this.children.put(c.getTag().getTagName(), c); } } public JsfTag getTag() { return tag; } public JsfTree getChild(String name) { return children.get(name); } public boolean isLeaf() { return children.isEmpty(); } } /** * Helper class to queue tags read from the Jakarta Server Faces XML configuration file. The * idea is saving the element which can be a known tree element or another * one that is not interested in injection. */ private static class JsfElement { private final JsfTree tree; private final String tag; public JsfElement(JsfTree tree) { this.tree = tree; this.tag = null; } public JsfElement(String tag) { this.tree = null; this.tag = tag; } public String getTag() { return tag; } public JsfTree getTree() { return tree; } public boolean isTree() { return tree != null; } } /** * The element tree to parse the XML artifacts for injection. */ private static final JsfTree facesConfigElement; static { // tree of jsf artifact tags with order facesConfigElement = new JsfTree(JsfTag.FACES_CONFIG, new JsfTree(JsfTag.FACTORY, new JsfTree(JsfTag.APPLICATION_FACTORY), new JsfTree(JsfTag.VISIT_CONTEXT_FACTORY), new JsfTree(JsfTag.EXCEPTION_HANDLER_FACTORY), new JsfTree(JsfTag.EXTERNAL_CONTEXT_FACTORY), new JsfTree(JsfTag.FACES_CONTEXT_FACTORY), new JsfTree(JsfTag.PARTIAL_VIEW_CONTEXT_FACTORY), new JsfTree(JsfTag.LIFECYCLE_FACTORY), new JsfTree(JsfTag.RENDER_KIT_FACTORY), new JsfTree(JsfTag.VIEW_DECLARATION_LANGUAGE_FACTORY), new JsfTree(JsfTag.FACELET_CACHE_FACTORY), new JsfTree(JsfTag.TAG_HANDLER_DELEGATE_FACTORY)), new JsfTree(JsfTag.APPLICATION, new JsfTree(JsfTag.EL_RESOLVER), new JsfTree(JsfTag.RESOURCE_HANDLER), new JsfTree(JsfTag.STATE_MANAGER), new JsfTree(JsfTag.ACTION_LISTENER), new JsfTree(JsfTag.NAVIGATION_HANDLER), new JsfTree(JsfTag.VIEW_HANDLER), new JsfTree(JsfTag.SYSTEM_EVENT_LISTENER, new JsfTree(JsfTag.SYSTEM_EVENT_LISTENER_CLASS))), new JsfTree(JsfTag.LIFECYCLE, new JsfTree(JsfTag.PHASE_LISTENER))); } @Override public void deploy(final DeploymentPhaseContext phaseContext) { final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit(); final CompositeIndex index = deploymentUnit.getAttachment(Attachments.COMPOSITE_ANNOTATION_INDEX); final Module module = deploymentUnit.getAttachment(Attachments.MODULE); if(JsfVersionMarker.isJsfDisabled(deploymentUnit)) { return; } if (index == null) { return; } if (module == null) { return; } if (!DeploymentTypeMarker.isType(DeploymentType.WAR, deploymentUnit)) { return; } // process all the other elements eligible for injection in the Jakarta Server Faces spec processJSFArtifactsForInjection(deploymentUnit); } /** * According to Jakarta Server Faces specification there is a table of eligible components * for Jakarta Contexts and Dependency Injection (TABLE 5-3 Jakarta Server Faces Artifacts Eligible for Injection in chapter * 5.4.1 Jakarta Server Faces Managed Classes and Jakarta EE Annotations). This method parses * the faces-config configuration files and registers the classes. * The parser is quite simplistic. The tags are saved into a queue and * using the facesConfigElement tree it is known when a tag is one of the * classes to use for injection. */ private void processJSFArtifactsForInjection(final DeploymentUnit deploymentUnit) { final EEApplicationClasses applicationClassesDescription = deploymentUnit.getAttachment(org.jboss.as.ee.component.Attachments.EE_APPLICATION_CLASSES_DESCRIPTION); final EEModuleDescription moduleDescription = deploymentUnit.getAttachment(org.jboss.as.ee.component.Attachments.EE_MODULE_DESCRIPTION); JsfElement current = null; Deque<JsfElement> queue = new LinkedList<>(); final Set<String> addedClasses = new HashSet<>(); for (final VirtualFile facesConfig : getConfigurationFiles(deploymentUnit)) { try (InputStream is = facesConfig.openStream()) { final XMLInputFactory inputFactory = XMLInputFactory.newInstance(); inputFactory.setXMLResolver(NoopXMLResolver.create()); XMLStreamReader parser = inputFactory.createXMLStreamReader(is); boolean finished = false; while (!finished) { int event = parser.next(); switch (event) { case XMLStreamConstants.END_DOCUMENT: finished = true; parser.close(); break; case XMLStreamConstants.START_ELEMENT: String tagName = parser.getLocalName(); if (current == null) { // first element => should be faces-context if (tagName.equals(JsfTag.FACES_CONFIG.getTagName())) { current = new JsfElement(facesConfigElement); } else { current = new JsfElement(tagName); } } else { JsfTree child = current.isTree()? current.getTree().getChild(tagName) : null; if (child != null && child.isLeaf()) { // leaf component => read the class and register the component String className = parser.getElementText().trim(); if (!addedClasses.contains(className)) { addedClasses.add(className); installJsfArtifactComponent(child.getTag().getTagName(), className, moduleDescription, deploymentUnit, applicationClassesDescription); } } else if (child != null) { // non-leaf known element => advance into it queue.push(current); current = new JsfElement(child); } else { // unknown element => just put it in the queue queue.push(current); current = new JsfElement(tagName); } } break; case XMLStreamConstants.END_ELEMENT: // end of current element, just get the previous element from the queue current = queue.isEmpty()? null : queue.pop(); break; } } } catch (Exception e) { JSFLogger.ROOT_LOGGER.managedBeansConfigParseFailed(facesConfig); } } } public Set<VirtualFile> getConfigurationFiles(DeploymentUnit deploymentUnit) { final Set<VirtualFile> ret = new HashSet<>(); final List<ResourceRoot> resourceRoots = DeploymentUtils.allResourceRoots(deploymentUnit); for (final ResourceRoot resourceRoot : resourceRoots) { final VirtualFile webInfFacesConfig = resourceRoot.getRoot().getChild(WEB_INF_FACES_CONFIG); if (webInfFacesConfig.exists()) { ret.add(webInfFacesConfig); } //look for files that end in .faces-config.xml final VirtualFile metaInf = resourceRoot.getRoot().getChild("META-INF"); if (metaInf.exists() && metaInf.isDirectory()) { for (final VirtualFile file : metaInf.getChildren()) { if (file.getName().equals("faces-config.xml") || file.getName().endsWith(".faces-config.xml")) { ret.add(file); } } } } String configFiles = null; //now look for files in the javax.faces.CONFIG_FILES context param final WarMetaData warMetaData = deploymentUnit.getAttachment(WarMetaData.ATTACHMENT_KEY); if (warMetaData != null) { final WebMetaData webMetaData = warMetaData.getWebMetaData(); if (webMetaData != null) { final List<ParamValueMetaData> contextParams = webMetaData.getContextParams(); if (contextParams != null) { for (final ParamValueMetaData param : contextParams) { if (param.getParamName().equals(CONFIG_FILES)) { configFiles = param.getParamValue(); break; } } } } } if (configFiles != null) { final String[] files = configFiles.split(","); final ResourceRoot deploymentRoot = deploymentUnit.getAttachment(Attachments.DEPLOYMENT_ROOT); if (deploymentRoot != null) { for (final String file : files) { if (!file.isEmpty()) { final VirtualFile configFile = deploymentRoot.getRoot().getChild(file); if (configFile.exists()) { ret.add(configFile); } } } } } return ret; } private void installJsfArtifactComponent(final String type, final String className, final EEModuleDescription moduleDescription, final DeploymentUnit deploymentUnit, final EEApplicationClasses applicationClassesDescription) { install(type, className, moduleDescription, deploymentUnit, applicationClassesDescription); } private void install(String type, String className, final EEModuleDescription moduleDescription, final DeploymentUnit deploymentUnit, final EEApplicationClasses applicationClassesDescription) { final ComponentDescription componentDescription = new WebComponentDescription(type + "." + className, className, moduleDescription, deploymentUnit.getServiceName(), applicationClassesDescription); moduleDescription.addComponent(componentDescription); deploymentUnit.addToAttachmentList(WebComponentDescription.WEB_COMPONENTS, componentDescription.getStartServiceName()); } }
16,188
43.111717
128
java
null
wildfly-main/jsf/subsystem/src/main/java/org/jboss/as/jsf/deployment/JSFModuleIdFactory.java
/* * JBoss, Home of Professional Open Source * Copyright 2012 Red Hat Inc. and/or its affiliates and other contributors * as indicated by the @author tags. All rights reserved. * See the copyright.txt in the distribution for a * full listing of individual contributors. * * This copyrighted material is made available to anyone wishing to use, * modify, copy, or redistribute it subject to the terms and conditions * of the GNU Lesser General Public License, v. 2.1. * This program is distributed in the hope that it will be useful, but WITHOUT A * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. * You should have received a copy of the GNU Lesser General Public License, * v.2.1 along with this distribution; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ package org.jboss.as.jsf.deployment; import java.io.File; import java.io.FileFilter; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.jboss.as.jsf.logging.JSFLogger; import org.jboss.as.jsf.subsystem.JSFResourceDefinition; import org.jboss.modules.ModuleIdentifier; /** * This class finds all the installed Jakarta Server Faces implementations and provides their ModuleId's. * * @author Stan Silvert [email protected] (C) 2012 Red Hat Inc. */ public class JSFModuleIdFactory { private static final String API_MODULE = "jakarta.faces.api"; private static final String IMPL_MODULE = "jakarta.faces.impl"; private static final String INJECTION_MODULE = "org.jboss.as.jsf-injection"; private static final JSFModuleIdFactory instance = new JSFModuleIdFactory(); // The default JSF impl slot. This can be overridden by the management layer. private String defaultSlot = JSFResourceDefinition.DEFAULT_SLOT; private Map<String, ModuleIdentifier> apiIds = new HashMap<>(); private Map<String, ModuleIdentifier> implIds = new HashMap<>(); private Map<String, ModuleIdentifier> injectionIds = new HashMap<>(); private Set<String> allVersions = new HashSet<>(); private List<String> activeVersions = new ArrayList<>(); public static JSFModuleIdFactory getInstance() { return instance; } private JSFModuleIdFactory() { String modulePath = System.getProperty("module.path", System.getenv("JAVA_MODULEPATH")); if (!isBogusPath(modulePath)) { loadIdsFromModulePath(modulePath); } if (!activeVersions.contains("main")) { loadIdsManually(); } JSFLogger.ROOT_LOGGER.activatedJSFImplementations(activeVersions); } void setDefaultSlot(String defaultSlot) { this.defaultSlot = defaultSlot; } String getDefaultSlot() { return this.defaultSlot; } private boolean isBogusPath(String path) { if (path == null) return true; // must have at least one existing directory in the path for (String dir : path.split(File.pathSeparator)) { if (new File(dir).exists()) return false; } return true; // no directory in the path exists } // just provide the default implementations private void loadIdsManually() { implIds.put("main", ModuleIdentifier.create(IMPL_MODULE)); apiIds.put("main", ModuleIdentifier.create(API_MODULE)); injectionIds.put("main", ModuleIdentifier.create(INJECTION_MODULE)); allVersions.add("main"); activeVersions.add("main"); } private void loadIdsFromModulePath(String modulePath) { for (String moduleRootDir : modulePath.split(File.pathSeparator)) { loadIds(moduleRootDir, apiIds, API_MODULE); loadIds(moduleRootDir, implIds, IMPL_MODULE); loadIds(moduleRootDir, injectionIds, INJECTION_MODULE); } checkVersionIntegrity(); } private void loadIds(String moduleRootDir, Map<String, ModuleIdentifier> idMap, String moduleName) { StringBuilder baseDirBuilder = new StringBuilder(moduleRootDir); baseDirBuilder.append(File.separator); baseDirBuilder.append(moduleName.replace(".", File.separator)); File moduleBaseDir = new File(baseDirBuilder.toString()); File[] slots = moduleBaseDir.listFiles(new FileFilter() { @Override public boolean accept(File pathname) { return pathname.isDirectory(); } }); if (slots == null) return; for (File slot : slots) { if (!new File(slot, "module.xml").exists()) continue; // make sure directory represents a real module String slotName = slot.getName(); allVersions.add(slotName); idMap.put(slotName, ModuleIdentifier.create(moduleName, slotName)); } } // make sure that each version has api, impl, and injection private void checkVersionIntegrity() { activeVersions.addAll(allVersions); for (String version : allVersions) { if (!apiIds.containsKey(version)) { JSFLogger.ROOT_LOGGER.missingJSFModule(version, API_MODULE); activeVersions.remove(version); } if (!implIds.containsKey(version)) { JSFLogger.ROOT_LOGGER.missingJSFModule(version, IMPL_MODULE); activeVersions.remove(version); } if (!injectionIds.containsKey(version)) { JSFLogger.ROOT_LOGGER.missingJSFModule(version, INJECTION_MODULE); activeVersions.remove(version); } } } /** * If needed, convert old JSFVersionMarker values to slot values. * * @param jsfVersion The version value from JSFVersionMarker, or null for default slot. * @return The equivalent slot value. */ String computeSlot(String jsfVersion) { if (jsfVersion == null) return defaultSlot; if (JsfVersionMarker.JSF_4_0.equals(jsfVersion)) return defaultSlot; return jsfVersion; } ModuleIdentifier getApiModId(String jsfVersion) { return this.apiIds.get(computeSlot(jsfVersion)); } ModuleIdentifier getImplModId(String jsfVersion) { return this.implIds.get(computeSlot(jsfVersion)); } ModuleIdentifier getInjectionModId(String jsfVersion) { return this.injectionIds.get(computeSlot(jsfVersion)); } boolean isValidJSFSlot(String slot) { String computedSlot = computeSlot(slot); return apiIds.containsKey(computedSlot) && implIds.containsKey(computedSlot) && injectionIds.containsKey(computedSlot); } /** * Return the slot id's of all active JSF versions. * * @return The slot id's of all active JSF versions. */ public List<String> getActiveJSFVersions() { return Collections.unmodifiableList(activeVersions); } }
7,118
34.954545
127
java
null
wildfly-main/jsf/subsystem/src/main/java/org/jboss/as/jsf/deployment/FacesAnnotation.java
package org.jboss.as.jsf.deployment; import java.lang.annotation.Annotation; import jakarta.faces.component.FacesComponent; import jakarta.faces.component.behavior.FacesBehavior; import jakarta.faces.convert.FacesConverter; import jakarta.faces.event.NamedEvent; import jakarta.faces.render.FacesBehaviorRenderer; import jakarta.faces.render.FacesRenderer; import jakarta.faces.validator.FacesValidator; import org.jboss.jandex.DotName; enum FacesAnnotation { FACES_COMPONENT(FacesComponent.class), FACES_CONVERTER(FacesConverter.class), FACES_VALIDATOR(FacesValidator.class), FACES_RENDERER(FacesRenderer.class), NAMED_EVENT(NamedEvent.class), FACES_BEHAVIOR(FacesBehavior.class), FACES_BEHAVIOR_RENDERER(FacesBehaviorRenderer.class); final Class<? extends Annotation> annotationClass; final DotName indexName; private FacesAnnotation(Class<? extends Annotation> annotationClass) { this.annotationClass = annotationClass; this.indexName = DotName.createSimple(annotationClass.getName()); } }
1,058
33.16129
74
java
null
wildfly-main/jsf/subsystem/src/main/java/org/jboss/as/jsf/subsystem/JSFExtension.java
/* * JBoss, Home of Professional Open Source. * Copyright 2012, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.jsf.subsystem; import org.jboss.as.controller.Extension; import org.jboss.as.controller.ExtensionContext; import org.jboss.as.controller.ModelVersion; import org.jboss.as.controller.PathElement; import org.jboss.as.controller.PersistentResourceXMLDescription; import org.jboss.as.controller.PersistentResourceXMLParser; import org.jboss.as.controller.SubsystemRegistration; import org.jboss.as.controller.descriptions.ParentResourceDescriptionResolver; import org.jboss.as.controller.descriptions.SubsystemResourceDescriptionResolver; import org.jboss.as.controller.parsing.ExtensionParsingContext; import org.jboss.as.jsf.logging.JSFLogger; import static org.jboss.as.controller.PersistentResourceXMLDescription.builder; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SUBSYSTEM; /** * Domain extension used to initialize the Jakarta Server Faces subsystem. * * @author Stuart Douglas * @author Emanuel Muckenhuber * @author Stan Silvert */ public class JSFExtension implements Extension { public static final String SUBSYSTEM_NAME = "jsf"; public static final String NAMESPACE_1_0 = "urn:jboss:domain:jsf:1.0"; public static final String NAMESPACE_1_1 = "urn:jboss:domain:jsf:1.1"; static final PathElement PATH_SUBSYSTEM = PathElement.pathElement(SUBSYSTEM, SUBSYSTEM_NAME); static final ParentResourceDescriptionResolver SUBSYSTEM_RESOLVER = new SubsystemResourceDescriptionResolver(SUBSYSTEM_NAME, JSFExtension.class); private static final ModelVersion CURRENT_MODEL_VERSION = ModelVersion.create(1, 1, 0); /** {@inheritDoc} */ @Override public void initialize(final ExtensionContext context) { JSFLogger.ROOT_LOGGER.debug("Activating JSF(Mojarra) Extension"); final SubsystemRegistration subsystem = context.registerSubsystem(SUBSYSTEM_NAME, CURRENT_MODEL_VERSION); subsystem.registerSubsystemModel(new JSFResourceDefinition()); subsystem.registerXMLElementWriter(JSFSubsystemParser_1_1.INSTANCE); } /** {@inheritDoc} */ @Override public void initializeParsers(final ExtensionParsingContext context) { context.setSubsystemXmlMapping(SUBSYSTEM_NAME, JSFExtension.NAMESPACE_1_0, () -> JSFSubsystemParser_1_0.INSTANCE); context.setSubsystemXmlMapping(SUBSYSTEM_NAME, JSFExtension.NAMESPACE_1_1, () -> JSFSubsystemParser_1_1.INSTANCE); } static class JSFSubsystemParser_1_0 extends PersistentResourceXMLParser { private static final JSFSubsystemParser_1_0 INSTANCE = new JSFSubsystemParser_1_0(); private static final PersistentResourceXMLDescription xmlDescription; static { xmlDescription = builder(PATH_SUBSYSTEM, NAMESPACE_1_0) .addAttributes(JSFResourceDefinition.DEFAULT_JSF_IMPL_SLOT) .build(); } @Override public PersistentResourceXMLDescription getParserDescription() { return xmlDescription; } } static class JSFSubsystemParser_1_1 extends PersistentResourceXMLParser { private static final JSFSubsystemParser_1_1 INSTANCE = new JSFSubsystemParser_1_1(); private static final PersistentResourceXMLDescription xmlDescription; static { xmlDescription = builder(PATH_SUBSYSTEM, NAMESPACE_1_1) .addAttributes(JSFResourceDefinition.DEFAULT_JSF_IMPL_SLOT) .addAttributes(JSFResourceDefinition.DISALLOW_DOCTYPE_DECL) .build(); } @Override public PersistentResourceXMLDescription getParserDescription() { return xmlDescription; } } }
4,716
41.495495
149
java
null
wildfly-main/jsf/subsystem/src/main/java/org/jboss/as/jsf/subsystem/JSFResourceDefinition.java
/* * JBoss, Home of Professional Open Source * Copyright 2012 Red Hat Inc. and/or its affiliates and other contributors * as indicated by the @author tags. All rights reserved. * See the copyright.txt in the distribution for a * full listing of individual contributors. * * This copyrighted material is made available to anyone wishing to use, * modify, copy, or redistribute it subject to the terms and conditions * of the GNU Lesser General Public License, v. 2.1. * This program is distributed in the hope that it will be useful, but WITHOUT A * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. * You should have received a copy of the GNU Lesser General Public License, * v.2.1 along with this distribution; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ package org.jboss.as.jsf.subsystem; import java.util.Arrays; import java.util.Collection; import org.jboss.as.controller.AttributeDefinition; import org.jboss.as.controller.PersistentResourceDefinition; import org.jboss.as.controller.ReloadRequiredRemoveStepHandler; import org.jboss.as.controller.SimpleAttributeDefinition; import org.jboss.as.controller.SimpleAttributeDefinitionBuilder; import org.jboss.as.controller.SimpleResourceDefinition; import org.jboss.as.controller.capability.RuntimeCapability; import org.jboss.as.controller.operations.common.GenericSubsystemDescribeHandler; import org.jboss.as.controller.registry.AttributeAccess; import org.jboss.as.controller.registry.ManagementResourceRegistration; import org.jboss.as.weld.Capabilities; import org.jboss.dmr.ModelNode; import org.jboss.dmr.ModelType; /** * Defines attributes and operations for the Jakarta Server Faces Subsystem * * @author Stan Silvert [email protected] (C) 2012 Red Hat Inc. */ public class JSFResourceDefinition extends PersistentResourceDefinition { public static final String DEFAULT_SLOT_ATTR_NAME = "default-jsf-impl-slot"; public static final String DISALLOW_DOCTYPE_DECL_ATTR_NAME = "disallow-doctype-decl"; public static final String DEFAULT_SLOT = "main"; private static final RuntimeCapability<Void> FACES_CAPABILITY = RuntimeCapability.Builder.of("org.wildfly.faces") .addRequirements(Capabilities.WELD_CAPABILITY_NAME) .build(); protected static final SimpleAttributeDefinition DEFAULT_JSF_IMPL_SLOT = new SimpleAttributeDefinitionBuilder(DEFAULT_SLOT_ATTR_NAME, ModelType.STRING, true) .setAllowExpression(true) .setXmlName(DEFAULT_SLOT_ATTR_NAME) .setFlags(AttributeAccess.Flag.RESTART_ALL_SERVICES) .setDefaultValue(new ModelNode(DEFAULT_SLOT)) .build(); static final SimpleAttributeDefinition DISALLOW_DOCTYPE_DECL = new SimpleAttributeDefinitionBuilder(DISALLOW_DOCTYPE_DECL_ATTR_NAME, ModelType.BOOLEAN, true) .setAllowExpression(true) .setFlags(AttributeAccess.Flag.RESTART_ALL_SERVICES) .build(); JSFResourceDefinition() { super(new SimpleResourceDefinition.Parameters(JSFExtension.PATH_SUBSYSTEM, JSFExtension.SUBSYSTEM_RESOLVER) .setAddHandler(JSFSubsystemAdd.INSTANCE) .setRemoveHandler(ReloadRequiredRemoveStepHandler.INSTANCE) .addCapabilities(FACES_CAPABILITY) ); } @Override public void registerOperations(ManagementResourceRegistration resourceRegistration) { super.registerOperations(resourceRegistration); resourceRegistration.registerOperationHandler(GenericSubsystemDescribeHandler.DEFINITION, GenericSubsystemDescribeHandler.INSTANCE); resourceRegistration.registerOperationHandler(JSFImplListHandler.DEFINITION, new JSFImplListHandler()); } @Override public Collection<AttributeDefinition> getAttributes() { return Arrays.asList(DEFAULT_JSF_IMPL_SLOT, DISALLOW_DOCTYPE_DECL); } }
4,106
46.206897
140
java
null
wildfly-main/jsf/subsystem/src/main/java/org/jboss/as/jsf/subsystem/JSFImplListHandler.java
/* * JBoss, Home of Professional Open Source * Copyright 2012 Red Hat Inc. and/or its affiliates and other contributors * as indicated by the @author tags. All rights reserved. * See the copyright.txt in the distribution for a * full listing of individual contributors. * * This copyrighted material is made available to anyone wishing to use, * modify, copy, or redistribute it subject to the terms and conditions * of the GNU Lesser General Public License, v. 2.1. * This program is distributed in the hope that it will be useful, but WITHOUT A * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. * You should have received a copy of the GNU Lesser General Public License, * v.2.1 along with this distribution; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ package org.jboss.as.jsf.subsystem; import org.jboss.as.controller.OperationContext; import org.jboss.as.controller.OperationDefinition; import org.jboss.as.controller.OperationFailedException; import org.jboss.as.controller.OperationStepHandler; import org.jboss.as.controller.SimpleOperationDefinitionBuilder; import org.jboss.as.jsf.deployment.JSFModuleIdFactory; import org.jboss.dmr.ModelNode; import org.jboss.dmr.ModelType; /** * Defines and handles the list-active-jsf-impls operation. * * @author Stan Silvert [email protected] (C) 2012 Red Hat Inc. */ public class JSFImplListHandler implements OperationStepHandler { public static final String OPERATION_NAME = "list-active-jsf-impls"; public static final OperationDefinition DEFINITION = new SimpleOperationDefinitionBuilder(OPERATION_NAME, JSFExtension.SUBSYSTEM_RESOLVER) .setRuntimeOnly() .setReadOnly() .setReplyType(ModelType.LIST) .setReplyValueType(ModelType.STRING) .build(); public void execute(OperationContext context, ModelNode operation) throws OperationFailedException { ModelNode result = context.getResult(); result.setEmptyList(); for (String impl : JSFModuleIdFactory.getInstance().getActiveJSFVersions()) { result.add(impl); } context.completeStep(OperationContext.RollbackHandler.NOOP_ROLLBACK_HANDLER); } }
2,395
41.785714
142
java
null
wildfly-main/jsf/subsystem/src/main/java/org/jboss/as/jsf/subsystem/JSFSubsystemAdd.java
/* * JBoss, Home of Professional Open Source. * Copyright 2012, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.jsf.subsystem; import static org.jboss.as.weld.Capabilities.WELD_CAPABILITY_NAME; import org.jboss.as.controller.AbstractBoottimeAddStepHandler; import org.jboss.as.controller.OperationContext; import org.jboss.as.controller.OperationFailedException; import org.jboss.as.controller.capability.CapabilityServiceSupport; import org.jboss.as.jsf.deployment.JSFAnnotationProcessor; import org.jboss.as.jsf.deployment.JSFBeanValidationFactoryProcessor; import org.jboss.as.jsf.deployment.JSFCdiExtensionDeploymentProcessor; import org.jboss.as.jsf.deployment.JSFComponentProcessor; import org.jboss.as.jsf.deployment.JSFDependencyProcessor; import org.jboss.as.jsf.deployment.JSFMetadataProcessor; import org.jboss.as.jsf.deployment.JSFSharedTldsProcessor; import org.jboss.as.jsf.deployment.JSFVersionProcessor; import org.jboss.as.server.AbstractDeploymentChainStep; import org.jboss.as.server.DeploymentProcessorTarget; import org.jboss.as.server.deployment.Phase; import org.jboss.dmr.ModelNode; /** * The Jakarta Server Faces subsystem add update handler. * * @author Stuart Douglas */ class JSFSubsystemAdd extends AbstractBoottimeAddStepHandler { static final JSFSubsystemAdd INSTANCE = new JSFSubsystemAdd(); @Override protected void populateModel(ModelNode operation, ModelNode model) throws OperationFailedException { JSFResourceDefinition.DEFAULT_JSF_IMPL_SLOT.validateAndSet(operation, model); JSFResourceDefinition.DISALLOW_DOCTYPE_DECL.validateAndSet(operation, model); } @Override protected void performBoottime(OperationContext context, ModelNode operation, final ModelNode model) throws OperationFailedException { final String defaultJSFSlot = JSFResourceDefinition.DEFAULT_JSF_IMPL_SLOT.resolveModelAttribute(context, model).asString(); final Boolean disallowDoctypeDecl = JSFResourceDefinition.DISALLOW_DOCTYPE_DECL.resolveModelAttribute(context, model).asBooleanOrNull(); context.addStep(new AbstractDeploymentChainStep() { protected void execute(DeploymentProcessorTarget processorTarget) { processorTarget.addDeploymentProcessor(JSFExtension.SUBSYSTEM_NAME, Phase.PARSE, Phase.PARSE_JSF_VERSION, new JSFVersionProcessor(defaultJSFSlot)); processorTarget.addDeploymentProcessor(JSFExtension.SUBSYSTEM_NAME, Phase.PARSE, Phase.PARSE_JSF_SHARED_TLDS, new JSFSharedTldsProcessor()); processorTarget.addDeploymentProcessor(JSFExtension.SUBSYSTEM_NAME, Phase.PARSE, Phase.PARSE_JSF_METADATA, new JSFMetadataProcessor(disallowDoctypeDecl)); processorTarget.addDeploymentProcessor(JSFExtension.SUBSYSTEM_NAME, Phase.DEPENDENCIES, Phase.DEPENDENCIES_JSF, new JSFDependencyProcessor()); processorTarget.addDeploymentProcessor(JSFExtension.SUBSYSTEM_NAME, Phase.POST_MODULE, Phase.POST_MODULE_JSF_MANAGED_BEANS, new JSFComponentProcessor()); CapabilityServiceSupport capabilities = context.getCapabilityServiceSupport(); if (capabilities.hasCapability(WELD_CAPABILITY_NAME)) { processorTarget.addDeploymentProcessor(JSFExtension.SUBSYSTEM_NAME, Phase.POST_MODULE, Phase.POST_MODULE_JSF_CDI_EXTENSIONS, new JSFCdiExtensionDeploymentProcessor()); } processorTarget.addDeploymentProcessor(JSFExtension.SUBSYSTEM_NAME, Phase.INSTALL, Phase.INSTALL_JSF_ANNOTATIONS, new JSFAnnotationProcessor()); if (context.hasOptionalCapability("org.wildfly.bean-validation", null, null)) { processorTarget.addDeploymentProcessor(JSFExtension.SUBSYSTEM_NAME, Phase.INSTALL, Phase.INSTALL_JSF_VALIDATOR_FACTORY, new JSFBeanValidationFactoryProcessor()); } } }, OperationContext.Stage.RUNTIME); } }
4,858
56.164706
187
java
null
wildfly-main/jsf/injection/src/main/java/org/jboss/as/jsf/injection/JSFInjectionProvider.java
/* * JBoss, Home of Professional Open Source * Copyright 2021, Red Hat Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.jsf.injection; import com.sun.faces.spi.DiscoverableInjectionProvider; import com.sun.faces.spi.InjectionProviderException; import org.jboss.as.web.common.StartupContext; import org.jboss.as.web.common.WebInjectionContainer; /** * @author Stuart Douglas */ public class JSFInjectionProvider extends DiscoverableInjectionProvider { public static final String JAVAX_FACES = "jakarta.faces."; public static final String COM_SUN_FACES = "com.sun.faces."; public static final String COM_SUN_FACES_TEST = "com.sun.faces.test."; private final WebInjectionContainer instanceManager; public JSFInjectionProvider() { this.instanceManager = StartupContext.getInjectionContainer(); } @Override public void inject(final Object managedBean) throws InjectionProviderException { } @Override public void invokePreDestroy(final Object managedBean) throws InjectionProviderException { if(instanceManager != null) { // WFLY-3820 instanceManager.destroyInstance(managedBean); } } @Override public void invokePostConstruct(final Object managedBean) throws InjectionProviderException { if(managedBean.getClass().getName().startsWith(JAVAX_FACES) || (managedBean.getClass().getName().startsWith(COM_SUN_FACES) && !managedBean.getClass().getName().startsWith(COM_SUN_FACES_TEST))) { //some internal Jakarta Server Faces instances are not destroyed properly, and they do not need to have //lifecycle callbacks anyway, so we don't use the instance manager to create them // avoid excluding elements from the Jakarta Server Faces test suite (tests fail because objects are not injected) return; } if(instanceManager == null) { // WFLY-3820 return; } try { instanceManager.newInstance(managedBean); } catch (Exception e) { throw new InjectionProviderException(e); } } }
3,064
39.328947
147
java
null
wildfly-main/jsf/injection/src/main/java/org/jboss/as/jsf/injection/JandexAnnotationProvider.java
/* * JBoss, Home of Professional Open Source. * Copyright 2021, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.jsf.injection; import com.sun.faces.spi.AnnotationProvider; import java.lang.annotation.Annotation; import jakarta.servlet.ServletContext; import java.util.Map; import java.util.Set; /** * {@link }AnnotationProvider} implementation which provides the Jakarta Server Faces annotations which we parsed from from a * Jandex index. * * @author John Bailey * @author Stan Silvert [email protected] (C) 2012 Red Hat Inc. */ public class JandexAnnotationProvider extends AnnotationProvider { private final Map<Class<? extends Annotation>, Set<Class<?>>> annotations; @SuppressWarnings("unchecked") public JandexAnnotationProvider(final ServletContext servletContext) { super(servletContext); annotations = AnnotationMap.get(servletContext); } // Note: The Mojarra 2.0 SPI specifies that this method takes Set<URL> as its argument. The Mojarra 2.1 SPI // makes a slight change and specifies Set<URI> as its argument. Since we aren't using this anyway, we can just // use a plain Set and it should work for both versions. @Override public Map<Class<? extends Annotation>, Set<Class<?>>> getAnnotatedClasses(final Set uris) { return annotations; // TODO: Should this be limited by URI } }
2,304
40.160714
125
java
null
wildfly-main/jsf/injection/src/main/java/org/jboss/as/jsf/injection/AnnotationMap.java
/* * JBoss, Home of Professional Open Source * Copyright 2021 Red Hat Inc. and/or its affiliates and other contributors * as indicated by the @author tags. All rights reserved. * See the copyright.txt in the distribution for a * full listing of individual contributors. * * This copyrighted material is made available to anyone wishing to use, * modify, copy, or redistribute it subject to the terms and conditions * of the GNU Lesser General Public License, v. 2.1. * This program is distributed in the hope that it will be useful, but WITHOUT A * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. * You should have received a copy of the GNU Lesser General Public License, * v.2.1 along with this distribution; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ package org.jboss.as.jsf.injection; import java.lang.annotation.Annotation; import java.util.HashMap; import java.util.Map; import java.util.Set; import jakarta.faces.component.FacesComponent; import jakarta.faces.component.behavior.FacesBehavior; import jakarta.faces.context.ExternalContext; import jakarta.faces.convert.FacesConverter; import jakarta.faces.event.NamedEvent; import jakarta.faces.render.FacesBehaviorRenderer; import jakarta.faces.render.FacesRenderer; import jakarta.faces.validator.FacesValidator; import jakarta.servlet.ServletContext; /** * This class retrieves the annotation map from application scope. This map was placed there by the JSFAnnotationProcessor * in the Jakarta Server Faces subsystem. * * The class also reloads the map if needed. The reason why the map must be reloaded is because the Jakarta Server Faces Annotation classes used as the map keys are always * loaded by the Jakarta Server Faces subsystem and thus always correspond to the default Jakarta Server Faces implementation. If a different Jakarta Server Faces * implementation is used then the Jakarta Server Faces impl will be looking for the wrong version of the map keys. So, we replace * the default implementations of the Jakarta Server Faces Annotation classes with whatever version the WAR is actually using. * * The reason this works is because we have a "slot" for jsf-injection for each Jakarta Server Faces implementation. And jsf-injection * points to its corresponding Jakarta Server Faces impl/api slots. * * @author Stan Silvert [email protected] (C) 2012 Red Hat Inc. */ public class AnnotationMap { /** * @see org.jboss.as.jsf.deployment.JSFAnnotationProcessor#FACES_ANNOTATIONS_SC_ATTR */ public static final String FACES_ANNOTATIONS_SC_ATTR = "org.jboss.as.jsf.FACES_ANNOTATIONS"; private static final String ANNOTATION_MAP_CONVERTED = "org.jboss.as.jsf.ANNOTATION_MAP_CONVERTED"; private static final Map<String, Class<? extends Annotation>> stringToAnnoMap = new HashMap<String, Class<? extends Annotation>>(); static { // These classes need to be loaded in order! Some can't be loaded if the Jakarta Server Faces version is too old. try { // all of the following classes are available from Faces 2.0 and Faces 2.1 stringToAnnoMap.put(FacesComponent.class.getName(), FacesComponent.class); stringToAnnoMap.put(FacesConverter.class.getName(), FacesConverter.class); stringToAnnoMap.put(FacesValidator.class.getName(), FacesValidator.class); stringToAnnoMap.put(FacesRenderer.class.getName(), FacesRenderer.class); stringToAnnoMap.put(NamedEvent.class.getName(), NamedEvent.class); stringToAnnoMap.put(FacesBehavior.class.getName(), FacesBehavior.class); stringToAnnoMap.put(FacesBehaviorRenderer.class.getName(), FacesBehaviorRenderer.class); // Put Jakarta Server Faces 2.2+ annotations below this line if any new ones are to be scanned. // Load the class to avoid a NoClassDefFoundError if it is not present in the impl ClassLoader loader = AnnotationMap.class.getClassLoader(); addAnnotationIfPresent(loader, "jakarta.faces.view.facelets.FaceletsResourceResolver"); } catch (Exception e) { // Ignore. Whatever classes are available have been loaded into the map. } } // don't allow instance private AnnotationMap() {} private static void addAnnotationIfPresent(ClassLoader loader, String name) { try { Class clazz = loader.loadClass(name); if (Annotation.class.isAssignableFrom(clazz)) { stringToAnnoMap.put(name, clazz); } } catch(ClassNotFoundException e) { // ignore, annotation not found in the used Jakarta Server Faces version } } public static Map<Class<? extends Annotation>, Set<Class<?>>> get(final ExternalContext extContext) { Map<String, Object> appMap = extContext.getApplicationMap(); if (appMap.get(ANNOTATION_MAP_CONVERTED) != null) { return (Map<Class<? extends Annotation>, Set<Class<?>>>)appMap.get(FACES_ANNOTATIONS_SC_ATTR); } else { appMap.put(ANNOTATION_MAP_CONVERTED, Boolean.TRUE); return convert((Map<Class<? extends Annotation>, Set<Class<?>>>)appMap.get(FACES_ANNOTATIONS_SC_ATTR)); } } public static Map<Class<? extends Annotation>, Set<Class<?>>> get(final ServletContext servletContext) { Map<Class<? extends Annotation>, Set<Class<?>>> annotations = (Map<Class<? extends Annotation>, Set<Class<?>>>) servletContext.getAttribute(FACES_ANNOTATIONS_SC_ATTR); if (servletContext.getAttribute(ANNOTATION_MAP_CONVERTED) != null) { return annotations; } else { servletContext.setAttribute(ANNOTATION_MAP_CONVERTED, Boolean.TRUE); return convert(annotations); } } private static Map<Class<? extends Annotation>, Set<Class<?>>> convert(Map<Class<? extends Annotation>, Set<Class<?>>> annotations) { final Map<Class<? extends Annotation>, Set<Class<?>>> convertedAnnotatedClasses = new HashMap<Class<? extends Annotation>, Set<Class<?>>>(); for (Map.Entry<Class<? extends Annotation>, Set<Class<?>>> entry : annotations.entrySet()) { final Class<? extends Annotation> annotation = entry.getKey(); final Set<Class<?>> annotated = entry.getValue(); final Class<? extends Annotation> knownAnnotation = stringToAnnoMap.get(annotation.getName()); if (knownAnnotation != null) { convertedAnnotatedClasses.put(knownAnnotation, annotated); // put back in the map with the proper version of the class } else { // just copy over the original annotation to annotated classes mapping convertedAnnotatedClasses.put(annotation, annotated); } } return convertedAnnotatedClasses; } }
7,042
52.356061
175
java
null
wildfly-main/jsf/injection/src/main/java/org/jboss/as/jsf/injection/weld/WeldApplication.java
/* * JBoss, Home of Professional Open Source * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.as.jsf.injection.weld; import jakarta.el.ELResolver; import jakarta.el.ExpressionFactory; import jakarta.enterprise.inject.spi.BeanManager; import jakarta.faces.application.Application; import jakarta.faces.application.ApplicationWrapper; import javax.naming.InitialContext; import javax.naming.NamingException; import org.jboss.weld.module.web.el.WeldELContextListener; /** * @author pmuir */ public class WeldApplication extends ApplicationWrapper { private static class AdjustableELResolver extends ForwardingELResolver { private ELResolver delegate; public void setDelegate(ELResolver delegate) { this.delegate = delegate; } @Override protected ELResolver delegate() { return delegate; } } private final Application application; private final AdjustableELResolver elResolver; private volatile ExpressionFactory expressionFactory; private volatile boolean initialized = false; private volatile BeanManager beanManager; public WeldApplication(Application application) { this.application = application; application.addELContextListener(new WeldELContextListener()); elResolver = new AdjustableELResolver(); elResolver.setDelegate(new DummyELResolver()); application.addELResolver(elResolver); } private void init() { if (!initialized) { synchronized (this) { if(!initialized) { if(beanManager() != null) { elResolver.setDelegate(beanManager().getELResolver()); } initialized = true; } } } } @Override public Application getWrapped() { init(); return application; } @Override public ExpressionFactory getExpressionFactory() { if (expressionFactory == null) { init(); synchronized (this) { if (expressionFactory == null) { BeanManager bm = beanManager(); if (bm == null) { expressionFactory = application.getExpressionFactory(); } else { expressionFactory = bm.wrapExpressionFactory(application.getExpressionFactory()); } } } } return expressionFactory; } private BeanManager beanManager() { if (beanManager == null) { synchronized (this) { if (beanManager == null) { try { // This can throw IllegalArgumentException on servlet context destroyed if init() was never called beanManager = (BeanManager) new InitialContext().lookup("java:comp/BeanManager"); } catch (NamingException | IllegalArgumentException e) { return null; } } } } return beanManager; } }
3,868
32.068376
122
java
null
wildfly-main/jsf/injection/src/main/java/org/jboss/as/jsf/injection/weld/WeldApplicationFactory.java
/* * JBoss, Home of Professional Open Source * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.as.jsf.injection.weld; import jakarta.faces.application.Application; import jakarta.faces.application.ApplicationFactory; /** * @author pmuir */ public class WeldApplicationFactory extends ForwardingApplicationFactory { private final ApplicationFactory applicationFactory; private volatile Application application; // This private constructor must never be called, but it is here to suppress the WELD-001529 warning // that an InjectionTarget is created for this class with no appropriate constructor. private WeldApplicationFactory() { super(); applicationFactory = null; } public WeldApplicationFactory(ApplicationFactory applicationFactory) { this.applicationFactory = applicationFactory; } @Override protected ApplicationFactory delegate() { return applicationFactory; } @Override public Application getApplication() { if (application == null) { synchronized (this) { if (application == null) { application = new WeldApplication(delegate().getApplication()); } } } return application; } @Override public void setApplication(final Application application) { synchronized (this) { this.application = null; super.setApplication(application); } } }
2,203
31.895522
104
java
null
wildfly-main/jsf/injection/src/main/java/org/jboss/as/jsf/injection/weld/ForwardingELResolver.java
/* * JBoss, Home of Professional Open Source * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.as.jsf.injection.weld; import java.beans.FeatureDescriptor; import java.util.Iterator; import jakarta.el.ELContext; import jakarta.el.ELResolver; public abstract class ForwardingELResolver extends ELResolver { protected abstract ELResolver delegate(); @Override public Class<?> getCommonPropertyType(ELContext context, Object base) { return delegate().getCommonPropertyType(context, base); } @Override public Iterator<FeatureDescriptor> getFeatureDescriptors(ELContext context, Object base) { return delegate().getFeatureDescriptors(context, base); } @Override public Class<?> getType(ELContext context, Object base, Object property) { return delegate().getType(context, base, property); } @Override public Object getValue(ELContext context, Object base, Object property) { return delegate().getValue(context, base, property); } @Override public boolean isReadOnly(ELContext context, Object base, Object property) { return delegate().isReadOnly(context, base, property); } @Override public void setValue(ELContext context, Object base, Object property, Object value) { delegate().setValue(context, base, property, value); } @Override public boolean equals(Object obj) { return this == obj || delegate().equals(obj); } @Override public int hashCode() { return delegate().hashCode(); } @Override public String toString() { return delegate().toString(); } }
2,355
30.837838
94
java
null
wildfly-main/jsf/injection/src/main/java/org/jboss/as/jsf/injection/weld/ForwardingApplicationFactory.java
/* * JBoss, Home of Professional Open Source * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.as.jsf.injection.weld; import jakarta.faces.application.Application; import jakarta.faces.application.ApplicationFactory; /** * @author pmuir * */ public abstract class ForwardingApplicationFactory extends ApplicationFactory { protected abstract ApplicationFactory delegate(); @Override public Application getApplication() { return delegate().getApplication(); } @Override public void setApplication(Application application) { delegate().setApplication(application); } @Override public boolean equals(Object obj) { return delegate().equals(obj); } @Override public int hashCode() { return delegate().hashCode(); } @Override public String toString() { return delegate().toString(); } @Override public ApplicationFactory getWrapped() { return delegate(); } }
1,695
27.745763
79
java
null
wildfly-main/jsf/injection/src/main/java/org/jboss/as/jsf/injection/weld/DummyELResolver.java
/* * JBoss, Home of Professional Open Source. * Copyright 2012, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.jsf.injection.weld; import java.beans.FeatureDescriptor; import java.util.Iterator; import jakarta.el.ELContext; import jakarta.el.ELResolver; public class DummyELResolver extends ELResolver { @Override public Class<?> getCommonPropertyType(ELContext context, Object base) { return null; } @Override public Iterator<FeatureDescriptor> getFeatureDescriptors(ELContext context, Object base) { return null; } @Override public Class<?> getType(ELContext context, Object base, Object property) { return null; } @Override public Object getValue(ELContext context, Object base, Object property) { return null; } @Override public boolean isReadOnly(ELContext context, Object base, Object property) { return false; } @Override public void setValue(ELContext context, Object base, Object property, Object value) { } }
1,975
30.365079
94
java
null
wildfly-main/jsf/injection/src/main/java/org/jboss/as/jsf/injection/weld/legacy/WeldApplicationFactoryLegacy.java
/* * JBoss, Home of Professional Open Source. * Copyright 2018, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.jsf.injection.weld.legacy; import jakarta.faces.application.Application; import jakarta.faces.application.ApplicationFactory; import org.jboss.as.jsf.injection.weld.ForwardingApplicationFactory; /** * @author <a href="[email protected]">Ingo Weiss</a> * * This is a copy of WeldApplicationFactory modified to use WeldApplicationLegacy instead */ public class WeldApplicationFactoryLegacy extends ForwardingApplicationFactory { private final ApplicationFactory applicationFactory; private volatile Application application; // This private constructor must never be called, but it is here to suppress the WELD-001529 warning // that an InjectionTarget is created for this class with no appropriate constructor. private WeldApplicationFactoryLegacy() { super(); applicationFactory = null; } public WeldApplicationFactoryLegacy(ApplicationFactory applicationFactory) { this.applicationFactory = applicationFactory; } @Override protected ApplicationFactory delegate() { return applicationFactory; } @Override public Application getApplication() { if (application == null) { synchronized (this) { if (application == null) { application = new WeldApplicationLegacy(delegate().getApplication()); } } } return application; } @Override public void setApplication(final Application application) { synchronized (this) { this.application = null; super.setApplication(application); } } }
2,669
34.6
104
java
null
wildfly-main/jsf/injection/src/main/java/org/jboss/as/jsf/injection/weld/legacy/WeldApplicationLegacy.java
/* * JBoss, Home of Professional Open Source. * Copyright 2018, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.jsf.injection.weld.legacy; import javax.naming.InitialContext; import javax.naming.NamingException; import jakarta.el.ELResolver; import jakarta.el.ExpressionFactory; import jakarta.enterprise.inject.spi.BeanManager; import jakarta.faces.application.Application; import org.jboss.as.jsf.injection.weld.DummyELResolver; import org.jboss.as.jsf.injection.weld.ForwardingELResolver; import org.jboss.weld.module.web.el.WeldELContextListener; /** * @author pmuir * * Bring this class back to allow Faces 1.2 to be used with WildFly * See https://issues.jboss.org/browse/WFLY-9708 */ public class WeldApplicationLegacy extends ForwardingApplication { private static class AdjustableELResolver extends ForwardingELResolver { private ELResolver delegate; public void setDelegate(ELResolver delegate) { this.delegate = delegate; } @Override protected ELResolver delegate() { return delegate; } } private final Application application; private final AdjustableELResolver elResolver; private volatile ExpressionFactory expressionFactory; private volatile boolean initialized = false; private volatile BeanManager beanManager; public WeldApplicationLegacy(Application application) { this.application = application; application.addELContextListener(new WeldELContextListener()); elResolver = new AdjustableELResolver(); elResolver.setDelegate(new DummyELResolver()); application.addELResolver(elResolver); } private void init() { if (!initialized) { synchronized (this) { if(!initialized) { if(beanManager() != null) { elResolver.setDelegate(beanManager().getELResolver()); } initialized = true; } } } } @Override protected Application delegate() { init(); return application; } @Override public ExpressionFactory getExpressionFactory() { // may be improved for thread safety, but right now the only risk is to invoke wrapExpressionFactory // multiple times for concurrent threads. This is ok, as the call is if (expressionFactory == null) { init(); synchronized (this) { if (expressionFactory == null) { BeanManager bm = beanManager(); if (bm == null) { expressionFactory = application.getExpressionFactory(); } else { expressionFactory = bm.wrapExpressionFactory(application.getExpressionFactory()); } } } } return expressionFactory; } private BeanManager beanManager() { if (beanManager == null) { synchronized (this) { if (beanManager == null) { try { // This can throw IllegalArgumentException on servlet context destroyed if init() was never called beanManager = (BeanManager) new InitialContext().lookup("java:comp/BeanManager"); } catch (NamingException | IllegalArgumentException e) { return null; } } } } return beanManager; } }
4,498
34.425197
122
java
null
wildfly-main/jsf/injection/src/main/java/org/jboss/as/jsf/injection/weld/legacy/ForwardingApplication.java
/* * JBoss, Home of Professional Open Source. * Copyright 2018, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.jsf.injection.weld.legacy; import java.util.Collection; import java.util.Iterator; import java.util.Locale; import java.util.Map; import java.util.ResourceBundle; import jakarta.el.ELContextListener; import jakarta.el.ELException; import jakarta.el.ELResolver; import jakarta.el.ExpressionFactory; import jakarta.el.ValueExpression; import jakarta.faces.FacesException; import jakarta.faces.application.Application; import jakarta.faces.application.NavigationHandler; import jakarta.faces.application.ProjectStage; import jakarta.faces.application.Resource; import jakarta.faces.application.ResourceHandler; import jakarta.faces.application.StateManager; import jakarta.faces.application.ViewHandler; import jakarta.faces.component.UIComponent; import jakarta.faces.component.behavior.Behavior; import jakarta.faces.context.FacesContext; import jakarta.faces.convert.Converter; import jakarta.faces.event.ActionListener; import jakarta.faces.event.SystemEvent; import jakarta.faces.event.SystemEventListener; import jakarta.faces.flow.FlowHandler; import jakarta.faces.validator.Validator; /** * @author pmuir * * Bring this class back to allow Faces 1.2 to be used with WildFly * See https://issues.jboss.org/browse/WFLY-9708 */ @SuppressWarnings({"deprecation"}) public abstract class ForwardingApplication extends Application { protected abstract Application delegate(); @Override public void addBehavior(String behaviorId, String behaviorClass) { delegate().addBehavior(behaviorId, behaviorClass); } @Override public void addComponent(String componentType, String componentClass) { delegate().addComponent(componentType, componentClass); } @Override public void addConverter(String converterId, String converterClass) { delegate().addConverter(converterId, converterClass); } @SuppressWarnings("unchecked") @Override public void addConverter(Class targetClass, String converterClass) { delegate().addConverter(targetClass, converterClass); } @Override public void addDefaultValidatorId(String validatorId) { delegate().addDefaultValidatorId(validatorId); } @Override public void addELContextListener(ELContextListener listener) { delegate().addELContextListener(listener); } @Override public void addELResolver(ELResolver resolver) { delegate().addELResolver(resolver); } @Override public void addValidator(String validatorId, String validatorClass) { delegate().addValidator(validatorId, validatorClass); } @Override public Behavior createBehavior(String behaviorId) throws FacesException { return delegate().createBehavior(behaviorId); } @Override public UIComponent createComponent(FacesContext context, Resource componentResource) { return delegate().createComponent(context, componentResource); } @Override public UIComponent createComponent(FacesContext context, String componentType, String rendererType) { return delegate().createComponent(context, componentType, rendererType); } @Override public UIComponent createComponent(ValueExpression componentExpression, FacesContext context, String componentType) throws FacesException { return delegate().createComponent(componentExpression, context, componentType); } @Override public UIComponent createComponent(ValueExpression componentExpression, FacesContext context, String componentType, String rendererType) { return delegate().createComponent(componentExpression, context, componentType, rendererType); } @Override public UIComponent createComponent(String componentType) throws FacesException { return delegate().createComponent(componentType); } @Override public Converter createConverter(String converterId) { return delegate().createConverter(converterId); } @SuppressWarnings("unchecked") @Override public Converter createConverter(Class targetClass) { return delegate().createConverter(targetClass); } @Override public Validator createValidator(String validatorId) throws FacesException { return delegate().createValidator(validatorId); } @Override public <T> T evaluateExpressionGet(FacesContext context, String expression, Class<? extends T> expectedType) throws ELException { return delegate().evaluateExpressionGet(context, expression, expectedType); } @Override public ActionListener getActionListener() { return delegate().getActionListener(); } @Override public Iterator<String> getBehaviorIds() { return delegate().getBehaviorIds(); } @Override public Iterator<String> getComponentTypes() { return delegate().getComponentTypes(); } @Override public Iterator<String> getConverterIds() { return delegate().getConverterIds(); } @SuppressWarnings("unchecked") @Override public Iterator<Class<?>> getConverterTypes() { return delegate().getConverterTypes(); } @Override public Locale getDefaultLocale() { return delegate().getDefaultLocale(); } @Override public String getDefaultRenderKitId() { return delegate().getDefaultRenderKitId(); } @Override public Map<String, String> getDefaultValidatorInfo() { return delegate().getDefaultValidatorInfo(); } @Override public ELContextListener[] getELContextListeners() { return delegate().getELContextListeners(); } @Override public ELResolver getELResolver() { return delegate().getELResolver(); } @Override public ExpressionFactory getExpressionFactory() { return delegate().getExpressionFactory(); } @Override public FlowHandler getFlowHandler() { return delegate().getFlowHandler(); } @Override public String getMessageBundle() { return delegate().getMessageBundle(); } @Override public NavigationHandler getNavigationHandler() { return delegate().getNavigationHandler(); } @Override public ProjectStage getProjectStage() { return delegate().getProjectStage(); } @Override public ResourceBundle getResourceBundle(FacesContext ctx, String name) { return delegate().getResourceBundle(ctx, name); } @Override public ResourceHandler getResourceHandler() { return delegate().getResourceHandler(); } @Override public StateManager getStateManager() { return delegate().getStateManager(); } @Override public Iterator<Locale> getSupportedLocales() { return delegate().getSupportedLocales(); } @Override public Iterator<String> getValidatorIds() { return delegate().getValidatorIds(); } @Override public ViewHandler getViewHandler() { return delegate().getViewHandler(); } @Override public void publishEvent(FacesContext context, Class<? extends SystemEvent> systemEventClass, Class<?> sourceBaseType, Object source) { delegate().publishEvent(context, systemEventClass, sourceBaseType, source); } @Override public void publishEvent(FacesContext context, Class<? extends SystemEvent> systemEventClass, Object source) { delegate().publishEvent(context, systemEventClass, source); } @Override public void removeELContextListener(ELContextListener listener) { delegate().removeELContextListener(listener); } @Override public void setActionListener(ActionListener listener) { delegate().setActionListener(listener); } @Override public void setDefaultLocale(Locale locale) { delegate().setDefaultLocale(locale); } @Override public void setDefaultRenderKitId(String renderKitId) { delegate().setDefaultRenderKitId(renderKitId); } @Override public void setFlowHandler(FlowHandler newHandler) { delegate().setFlowHandler(newHandler); } @Override public void setMessageBundle(String bundle) { delegate().setMessageBundle(bundle); } @Override public void setNavigationHandler(NavigationHandler handler) { delegate().setNavigationHandler(handler); } @Override public void setResourceHandler(ResourceHandler resourceHandler) { delegate().setResourceHandler(resourceHandler); } @Override public void setStateManager(StateManager manager) { delegate().setStateManager(manager); } @Override public void setSupportedLocales(Collection<Locale> locales) { delegate().setSupportedLocales(locales); } @Override public void setViewHandler(ViewHandler handler) { delegate().setViewHandler(handler); } @Override public void subscribeToEvent(Class<? extends SystemEvent> systemEventClass, Class<?> sourceClass, SystemEventListener listener) { delegate().subscribeToEvent(systemEventClass, sourceClass, listener); } @Override public void subscribeToEvent(Class<? extends SystemEvent> systemEventClass, SystemEventListener listener) { delegate().subscribeToEvent(systemEventClass, listener); } @Override public void unsubscribeFromEvent(Class<? extends SystemEvent> systemEventClass, Class<?> sourceClass, SystemEventListener listener) { delegate().unsubscribeFromEvent(systemEventClass, sourceClass, listener); } @Override public void unsubscribeFromEvent(Class<? extends SystemEvent> systemEventClass, SystemEventListener listener) { delegate().unsubscribeFromEvent(systemEventClass, listener); } @Override public boolean equals(Object obj) { return delegate().equals(obj); } @Override public int hashCode() { return delegate().hashCode(); } @Override public String toString() { return delegate().toString(); } }
11,183
29.145553
122
java
null
wildfly-main/ejb3/src/test/java/org/jboss/as/ejb3/timerservice/schedule/CalendarBasedTimeoutWithDifferentTimeZoneTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2009, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ejb3.timerservice.schedule; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.TimeZone; import jakarta.ejb.ScheduleExpression; import org.jboss.logging.Logger; import org.junit.Assert; import org.junit.Test; /** * CalendarBasedTimeoutTestCase * * @author Brad Maxwell * @version $Revision: $ */ public class CalendarBasedTimeoutWithDifferentTimeZoneTestCase { /** * Logger */ private static Logger logger = Logger.getLogger(CalendarBasedTimeoutWithDifferentTimeZoneTestCase.class); /** * Construct a testcase for the timezone */ public CalendarBasedTimeoutWithDifferentTimeZoneTestCase() { } @Test public void testScheduledTimezoneDifferentThanCurrentSystem() { // This tests replicates an automatic timer below being deployed in a system whose default timezone is America/Chicago // @Schedule(persistent = false, timezone = "America/New_York", dayOfMonth = "*", dayOfWeek = "*", month = "*", hour = // "2", minute = "*", second = "0", year = "*") // The schedule for the timer is to fire every minute where the hour is 2 in the America/New_York timezone ScheduleExpression sch = new ScheduleExpression(); sch.timezone("America/New_York"); sch.dayOfMonth("*"); sch.dayOfWeek("*"); sch.month("*"); sch.hour("2"); sch.minute("*"); sch.second("0"); sch.year("*"); CalendarBasedTimeout calendarTimeout = new CalendarBasedTimeout(sch); Calendar firstTimeout = calendarTimeout.getFirstTimeout(); Assert.assertNotNull("first timeout is null", firstTimeout); logger.info("First timeout is " + firstTimeout.getTime()); // currentCal sets up a dummy time in the future, the timezone is America/Chicago in which this imaginary system is // running TimeZone currentTimezone = TimeZone.getTimeZone("America/Chicago"); Calendar currentCal = new GregorianCalendar(currentTimezone); currentCal.set(Calendar.YEAR, 2014); currentCal.set(Calendar.MONTH, 1); currentCal.set(Calendar.DATE, 8); currentCal.set(Calendar.HOUR_OF_DAY, 1); currentCal.set(Calendar.MINUTE, 1); currentCal.set(Calendar.SECOND, 1); currentCal.set(Calendar.MILLISECOND, 0); // https://issues.jboss.org/browse/WFLY-2840 - @Schedule EJB Timer not using timezone when calcualting next timeout // Next test WFLY-2840, by calling getNextTimeout with the dummy time above, the expected result is for the timer to // fire at 1:02:00 // If the bug is not fixed it will return 2:00:00 Calendar nextTimeout = calendarTimeout.getNextTimeout(currentCal); logger.info("Next timeout is " + nextTimeout.getTime()); Calendar expectedCal = new GregorianCalendar(currentTimezone); expectedCal.set(Calendar.YEAR, 2014); expectedCal.set(Calendar.MONTH, 1); expectedCal.set(Calendar.DATE, 8); expectedCal.set(Calendar.HOUR_OF_DAY, 1); expectedCal.set(Calendar.MINUTE, 2); expectedCal.set(Calendar.SECOND, 0); expectedCal.set(Calendar.MILLISECOND, 0); Assert.assertEquals("[WFLY-2840] Next timeout should be: " + expectedCal.getTime(), expectedCal.getTime(), nextTimeout.getTime()); } }
4,434
39.318182
126
java
null
wildfly-main/ejb3/src/test/java/org/jboss/as/ejb3/timerservice/schedule/ScheduleValueTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2009, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ejb3.timerservice.schedule; import org.jboss.as.ejb3.timerservice.schedule.value.IncrementValue; import org.jboss.as.ejb3.timerservice.schedule.value.RangeValue; import org.junit.Assert; import org.junit.Test; public class ScheduleValueTestCase { @Test public void testInvalidRange() { String[] invalidRangeValues = {null, "", " ", "0.1", "1d", "1.0", "?", "%", "$", "!", "&", "-", "/", ",", ".", "1-", "1-2-3", "1+2", "**", "*-", "*,1", "1,*", "5/*", "1, 2/2", "---", "-", "--", " -2 -3 -4", "-0", "1--"}; for (String invalidRange : invalidRangeValues) { boolean accepts = RangeValue.accepts(invalidRange); Assert.assertFalse("Range value accepted an invalid value: " + invalidRange, accepts); try { RangeValue invalidRangeValue = new RangeValue(invalidRange); Assert.fail("Range value did *not* throw IllegalArgumentException for an invalid range: " + invalidRange); } catch (IllegalArgumentException iae) { // expected } } } @Test public void testValidRange() { String[] validRanges = {"1-8", "-7--1", "7--1", "1st Fri-1st Mon"}; for (String validRange : validRanges) { boolean accepts = RangeValue.accepts(validRange); Assert.assertTrue("Valid range value wasn't accepted: " + validRange, accepts); RangeValue validRangeValue = new RangeValue(validRange); } } @Test public void testInvalidIncrement() { String[] invalidValues = { "1/-1", "1/10.0", "10/*", "10/?", "10/", "10/-", "/10", "?/10", "-/10", "**/10", "10.0/10" }; for (String v : invalidValues) { try { new IncrementValue(v); Assert.fail("Failed to get IllegalArgumentException for invalid increment value: " + v); } catch (IllegalArgumentException e) { // expected } } } }
3,129
40.184211
124
java
null
wildfly-main/ejb3/src/test/java/org/jboss/as/ejb3/timerservice/schedule/CalendarBasedTimeoutTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2009, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ejb3.timerservice.schedule; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.List; import java.util.TimeZone; import jakarta.ejb.ScheduleExpression; import org.junit.Assert; import org.junit.Test; /** * CalendarBasedTimeoutTestCase * * @author Jaikiran Pai * @author Eduardo Martins * @author "<a href=\"mailto:[email protected]\">Wolf-Dieter Fink</a>" */ public class CalendarBasedTimeoutTestCase { /** * Logger */ // private static Logger logger = Logger.getLogger(CalendarBasedTimeoutTestCase.class); /** * The timezone which is in use */ private TimeZone timezone; private String timeZoneDisplayName; /** * This method returns a collection of all available timezones in the system. * The tests in this {@link CalendarBasedTimeoutTestCase} will then be run * against each of these timezones */ private static List<TimeZone> getTimezones() { String[] candidates = TimeZone.getAvailableIDs(); List<TimeZone> timeZones = new ArrayList<TimeZone>(candidates.length); for (String timezoneID : candidates) { TimeZone timeZone = TimeZone.getTimeZone(timezoneID); boolean different = true; for (int i = timeZones.size() - 1; i >= 0; i--) { TimeZone testee = timeZones.get(i); if (testee.hasSameRules(timeZone)) { different = false; break; } } if (different) { timeZones.add(timeZone); } } return timeZones; } /** * Asserts timeouts based on next day of week. * Uses expression dayOfWeek=saturday hour=3 minute=21 second=50. * Expected next timeout is SAT 2014-03-29 3:21:50 */ @Test public void testNextDayOfWeek() { // start date is SAT 2014-03-22 4:00:00, has to advance to SAT of next week testNextDayOfWeek(new GregorianCalendar(2014,2,22,4,0,0).getTime()); // start date is TUE 2014-03-25 2:00:00, has to advance to SAT of same week testNextDayOfWeek(new GregorianCalendar(2014,2,25,2,0,0).getTime()); } private void testNextDayOfWeek(Date start) { ScheduleExpression expression = new ScheduleExpression(); expression.dayOfWeek("6"); expression.hour("3"); expression.minute("21"); expression.second("50"); expression.start(start); CalendarBasedTimeout calendarTimeout = new CalendarBasedTimeout(expression); Calendar firstTimeout = calendarTimeout.getFirstTimeout(); Assert.assertNotNull(firstTimeout); Assert.assertEquals(50, firstTimeout.get(Calendar.SECOND)); Assert.assertEquals(21, firstTimeout.get(Calendar.MINUTE)); Assert.assertEquals(3, firstTimeout.get(Calendar.HOUR_OF_DAY)); Assert.assertEquals(7, firstTimeout.get(Calendar.DAY_OF_WEEK)); Assert.assertEquals(29, firstTimeout.get(Calendar.DAY_OF_MONTH)); } @Test public void testCalendarBasedTimeout() { for (TimeZone tz : getTimezones()) { this.timezone = tz; this.timeZoneDisplayName = this.timezone.getDisplayName(); testEverySecondTimeout(); testEveryMinuteEveryHourEveryDay(); testEveryMorningFiveFifteen(); testEveryWeekdayEightFifteen(); testEveryMonWedFriTwelveThirtyNoon(); testEvery31stOfTheMonth(); testRun29thOfFeb(); testSomeSpecificTime(); testEvery10Seconds(); } } //@Test public void testEverySecondTimeout() { ScheduleExpression everySecondExpression = this.getTimezoneSpecificScheduleExpression(); everySecondExpression.second("*"); everySecondExpression.minute("*"); everySecondExpression.hour("*"); CalendarBasedTimeout calendarTimeout = new CalendarBasedTimeout(everySecondExpression); Calendar firstTimeout = calendarTimeout.getFirstTimeout(); Calendar nextTimeout = calendarTimeout.getNextTimeout(firstTimeout); Assert.assertNotNull(timeZoneDisplayName, nextTimeout); Assert.assertTrue(timeZoneDisplayName, nextTimeout.after(firstTimeout)); // logger.debug("Previous timeout was: " + firstTimeout.getTime() + " Next timeout is " + nextTimeout.getTime()); long diff = nextTimeout.getTimeInMillis() - firstTimeout.getTimeInMillis(); Assert.assertEquals(timeZoneDisplayName, 1000, diff); } //@Test public void testEveryMinuteEveryHourEveryDay() { ScheduleExpression everyMinEveryHourEveryDay = this.getTimezoneSpecificScheduleExpression(); everyMinEveryHourEveryDay.minute("*"); everyMinEveryHourEveryDay.hour("*"); CalendarBasedTimeout calendarTimeout = new CalendarBasedTimeout(everyMinEveryHourEveryDay); Calendar firstTimeout = calendarTimeout.getFirstTimeout(); Calendar previousTimeout = firstTimeout; for (int i = 1; i <= 65; i++) { Calendar nextTimeout = calendarTimeout.getNextTimeout(previousTimeout); Assert.assertNotNull(timeZoneDisplayName, nextTimeout); Assert.assertTrue(timeZoneDisplayName, nextTimeout.after(previousTimeout)); // logger.debug("First timeout was: " + firstTimeout.getTime() + " Previous timeout was: " // + previousTimeout.getTime() + " Next timeout is " + nextTimeout.getTime()); long diff = nextTimeout.getTimeInMillis() - previousTimeout.getTimeInMillis(); long diffWithFirstTimeout = nextTimeout.getTimeInMillis() - firstTimeout.getTimeInMillis(); Assert.assertEquals(timeZoneDisplayName, 60 * 1000, diff); Assert.assertEquals(timeZoneDisplayName, 60 * 1000 * i, diffWithFirstTimeout); previousTimeout = nextTimeout; } } //@Test public void testEveryMorningFiveFifteen() { ScheduleExpression everyMorningFiveFifteen = this.getTimezoneSpecificScheduleExpression(); everyMorningFiveFifteen.minute(15); everyMorningFiveFifteen.hour(5); CalendarBasedTimeout calendarTimeout = new CalendarBasedTimeout(everyMorningFiveFifteen); Calendar firstTimeout = calendarTimeout.getFirstTimeout(); Assert.assertNotNull(timeZoneDisplayName, firstTimeout); int minute = firstTimeout.get(Calendar.MINUTE); int second = firstTimeout.get(Calendar.SECOND); int hour = firstTimeout.get(Calendar.HOUR_OF_DAY); int amOrPm = firstTimeout.get(Calendar.AM_PM); Assert.assertEquals(timeZoneDisplayName, 0, second); Assert.assertEquals(timeZoneDisplayName, 15, minute); Assert.assertEquals(timeZoneDisplayName, 5, hour); Assert.assertEquals(timeZoneDisplayName, Calendar.AM, amOrPm); Calendar previousTimeout = firstTimeout; for (int i = 1; i <= 370; i++) { Calendar nextTimeout = calendarTimeout.getNextTimeout(previousTimeout); Assert.assertNotNull(timeZoneDisplayName, nextTimeout); Assert.assertTrue(timeZoneDisplayName, nextTimeout.after(previousTimeout)); // logger.debug("First timeout was: " + firstTimeout.getTime() + " Previous timeout was: " // + previousTimeout.getTime() + " Next timeout is " + nextTimeout.getTime()); Assert.assertEquals(timeZoneDisplayName, 0, nextTimeout.get(Calendar.SECOND)); Assert.assertEquals(timeZoneDisplayName, 15, nextTimeout.get(Calendar.MINUTE)); Assert.assertEquals(timeZoneDisplayName, 5, nextTimeout.get(Calendar.HOUR_OF_DAY)); Assert.assertEquals(timeZoneDisplayName, Calendar.AM, nextTimeout.get(Calendar.AM_PM)); previousTimeout = nextTimeout; } } //@Test public void testEveryWeekdayEightFifteen() { ScheduleExpression everyWeekDayThreeFifteen = this.getTimezoneSpecificScheduleExpression(); everyWeekDayThreeFifteen.minute(15); everyWeekDayThreeFifteen.hour(8); everyWeekDayThreeFifteen.dayOfWeek("Mon-Fri"); CalendarBasedTimeout calendarTimeout = new CalendarBasedTimeout(everyWeekDayThreeFifteen); Calendar firstTimeout = calendarTimeout.getFirstTimeout(); Assert.assertNotNull(timeZoneDisplayName, firstTimeout); int minute = firstTimeout.get(Calendar.MINUTE); int second = firstTimeout.get(Calendar.SECOND); int hour = firstTimeout.get(Calendar.HOUR_OF_DAY); int amOrPm = firstTimeout.get(Calendar.AM_PM); Assert.assertEquals(timeZoneDisplayName, 0, second); Assert.assertEquals(timeZoneDisplayName, 15, minute); Assert.assertEquals(timeZoneDisplayName, 8, hour); Assert.assertEquals(timeZoneDisplayName, Calendar.AM, amOrPm); Assert.assertTrue(timeZoneDisplayName, this.isWeekDay(firstTimeout)); Calendar previousTimeout = firstTimeout; for (int i = 1; i <= 180; i++) { Calendar nextTimeout = calendarTimeout.getNextTimeout(previousTimeout); Assert.assertNotNull(timeZoneDisplayName, nextTimeout); Assert.assertTrue(timeZoneDisplayName, nextTimeout.after(previousTimeout)); // logger.debug("First timeout was: " + firstTimeoutDate + " Previous timeout was: " + previousTimeout.getTime() // + " Next timeout is " + nextTimeoutDate); int nextMinute = nextTimeout.get(Calendar.MINUTE); int nextSecond = nextTimeout.get(Calendar.SECOND); int nextHour = nextTimeout.get(Calendar.HOUR_OF_DAY); int nextAmOrPm = nextTimeout.get(Calendar.AM_PM); Assert.assertEquals(timeZoneDisplayName, 0, nextSecond); Assert.assertEquals(timeZoneDisplayName, 15, nextMinute); Assert.assertEquals(timeZoneDisplayName, 8, nextHour); Assert.assertEquals(timeZoneDisplayName, Calendar.AM, nextAmOrPm); Assert.assertTrue(timeZoneDisplayName, this.isWeekDay(nextTimeout)); previousTimeout = nextTimeout; } } //@Test public void testEveryMonWedFriTwelveThirtyNoon() { ScheduleExpression everyMonWedFriTwelveThirtyNoon = this.getTimezoneSpecificScheduleExpression(); everyMonWedFriTwelveThirtyNoon.hour(12); everyMonWedFriTwelveThirtyNoon.second("30"); everyMonWedFriTwelveThirtyNoon.dayOfWeek("Mon,Wed,Fri"); CalendarBasedTimeout calendarTimeout = new CalendarBasedTimeout(everyMonWedFriTwelveThirtyNoon); Calendar firstTimeout = calendarTimeout.getFirstTimeout(); Assert.assertNotNull(timeZoneDisplayName, firstTimeout); int minute = firstTimeout.get(Calendar.MINUTE); int second = firstTimeout.get(Calendar.SECOND); int hour = firstTimeout.get(Calendar.HOUR_OF_DAY); int amOrPm = firstTimeout.get(Calendar.AM_PM); int dayOfWeek = firstTimeout.get(Calendar.DAY_OF_WEEK); Assert.assertEquals(timeZoneDisplayName, 30, second); Assert.assertEquals(timeZoneDisplayName, 0, minute); Assert.assertEquals(timeZoneDisplayName, 12, hour); Assert.assertEquals(timeZoneDisplayName, Calendar.PM, amOrPm); List<Integer> validDays = new ArrayList<Integer>(); validDays.add(Calendar.MONDAY); validDays.add(Calendar.WEDNESDAY); validDays.add(Calendar.FRIDAY); Assert.assertTrue(timeZoneDisplayName, validDays.contains(dayOfWeek)); Calendar previousTimeout = firstTimeout; for (int i = 1; i <= 180; i++) { Calendar nextTimeout = calendarTimeout.getNextTimeout(previousTimeout); Assert.assertNotNull(timeZoneDisplayName, nextTimeout); Assert.assertTrue(timeZoneDisplayName, nextTimeout.after(previousTimeout)); // logger.debug("First timeout was: " + firstTimeoutDate + " Previous timeout was: " + previousTimeout.getTime() // + " Next timeout is " + nextTimeoutDate); int nextMinute = nextTimeout.get(Calendar.MINUTE); int nextSecond = nextTimeout.get(Calendar.SECOND); int nextHour = nextTimeout.get(Calendar.HOUR_OF_DAY); int nextAmOrPm = nextTimeout.get(Calendar.AM_PM); int nextDayOfWeek = nextTimeout.get(Calendar.DAY_OF_WEEK); Assert.assertEquals(timeZoneDisplayName, 30, nextSecond); Assert.assertEquals(timeZoneDisplayName, 0, nextMinute); Assert.assertEquals(timeZoneDisplayName, 12, nextHour); Assert.assertEquals(timeZoneDisplayName, Calendar.PM, nextAmOrPm); Assert.assertTrue(timeZoneDisplayName, validDays.contains(nextDayOfWeek)); previousTimeout = nextTimeout; } } //@Test public void testEvery31stOfTheMonth() { ScheduleExpression every31st9_30_15_AM = this.getTimezoneSpecificScheduleExpression(); every31st9_30_15_AM.dayOfMonth(31); every31st9_30_15_AM.hour(9); every31st9_30_15_AM.minute("30"); every31st9_30_15_AM.second(15); CalendarBasedTimeout calendarTimeout = new CalendarBasedTimeout(every31st9_30_15_AM); Calendar firstTimeout = calendarTimeout.getFirstTimeout(); Assert.assertNotNull(timeZoneDisplayName, firstTimeout); int minute = firstTimeout.get(Calendar.MINUTE); int second = firstTimeout.get(Calendar.SECOND); int hour = firstTimeout.get(Calendar.HOUR_OF_DAY); int amOrPm = firstTimeout.get(Calendar.AM_PM); int dayOfMonth = firstTimeout.get(Calendar.DAY_OF_MONTH); Assert.assertEquals(timeZoneDisplayName, 15, second); Assert.assertEquals(timeZoneDisplayName, 30, minute); Assert.assertEquals(timeZoneDisplayName, 9, hour); Assert.assertEquals(timeZoneDisplayName, Calendar.AM, amOrPm); Assert.assertEquals(timeZoneDisplayName, 31, dayOfMonth); Calendar previousTimeout = firstTimeout; for (int i = 1; i <= 18; i++) { Calendar nextTimeout = calendarTimeout.getNextTimeout(previousTimeout); Assert.assertNotNull(timeZoneDisplayName, nextTimeout); Assert.assertTrue(timeZoneDisplayName, nextTimeout.after(previousTimeout)); // logger.debug("First timeout was: " + firstTimeoutDate + " Previous timeout was: " + previousTimeout.getTime() // + " Next timeout is " + nextTimeoutDate); int nextMinute = nextTimeout.get(Calendar.MINUTE); int nextSecond = nextTimeout.get(Calendar.SECOND); int nextHour = nextTimeout.get(Calendar.HOUR_OF_DAY); int nextAmOrPm = nextTimeout.get(Calendar.AM_PM); int nextDayOfMonth = nextTimeout.get(Calendar.DAY_OF_MONTH); Assert.assertEquals(timeZoneDisplayName, 15, nextSecond); Assert.assertEquals(timeZoneDisplayName, 30, nextMinute); Assert.assertEquals(timeZoneDisplayName, 9, nextHour); Assert.assertEquals(timeZoneDisplayName, Calendar.AM, nextAmOrPm); Assert.assertEquals(timeZoneDisplayName, 31, nextDayOfMonth); previousTimeout = nextTimeout; } } //@Test public void testRun29thOfFeb() { ScheduleExpression everyLeapYearOn29thFeb = this.getTimezoneSpecificScheduleExpression(); everyLeapYearOn29thFeb.dayOfMonth(29); everyLeapYearOn29thFeb.month("fEb"); CalendarBasedTimeout calendarTimeout = new CalendarBasedTimeout(everyLeapYearOn29thFeb); Calendar firstTimeout = calendarTimeout.getFirstTimeout(); Assert.assertNotNull(timeZoneDisplayName, firstTimeout); int minute = firstTimeout.get(Calendar.MINUTE); int second = firstTimeout.get(Calendar.SECOND); int hour = firstTimeout.get(Calendar.HOUR_OF_DAY); int amOrPm = firstTimeout.get(Calendar.AM_PM); int dayOfMonth = firstTimeout.get(Calendar.DAY_OF_MONTH); int month = firstTimeout.get(Calendar.MONTH); Assert.assertEquals(timeZoneDisplayName, 0, second); Assert.assertEquals(timeZoneDisplayName, 0, minute); Assert.assertEquals(timeZoneDisplayName, 0, hour); Assert.assertEquals(timeZoneDisplayName, Calendar.AM, amOrPm); Assert.assertEquals(timeZoneDisplayName, 29, dayOfMonth); Assert.assertEquals(timeZoneDisplayName, Calendar.FEBRUARY, month); Assert.assertTrue(timeZoneDisplayName, this.isLeapYear(firstTimeout)); Calendar previousTimeout = firstTimeout; for (int i = 1; i <= 2; i++) { Calendar nextTimeout = calendarTimeout.getNextTimeout(previousTimeout); Assert.assertNotNull(timeZoneDisplayName, nextTimeout); Assert.assertTrue(timeZoneDisplayName, nextTimeout.after(previousTimeout)); // logger.debug("First timeout was: " + firstTimeoutDate + " Previous timeout was: " + previousTimeout.getTime() // + " Next timeout is " + nextTimeoutDate); int nextMinute = nextTimeout.get(Calendar.MINUTE); int nextSecond = nextTimeout.get(Calendar.SECOND); int nextHour = nextTimeout.get(Calendar.HOUR_OF_DAY); int nextAmOrPm = nextTimeout.get(Calendar.AM_PM); int nextDayOfMonth = nextTimeout.get(Calendar.DAY_OF_MONTH); int nextMonth = nextTimeout.get(Calendar.MONTH); Assert.assertEquals(timeZoneDisplayName, 0, nextSecond); Assert.assertEquals(timeZoneDisplayName, 0, nextMinute); Assert.assertEquals(timeZoneDisplayName, 0, nextHour); Assert.assertEquals(timeZoneDisplayName, Calendar.AM, nextAmOrPm); Assert.assertEquals(timeZoneDisplayName, 29, nextDayOfMonth); Assert.assertEquals(timeZoneDisplayName, Calendar.FEBRUARY, nextMonth); Assert.assertTrue(timeZoneDisplayName, this.isLeapYear(nextTimeout)); previousTimeout = nextTimeout; } } //@Test public void testSomeSpecificTime() { ScheduleExpression every0_15_30_Sec_At_9_30_PM = this.getTimezoneSpecificScheduleExpression(); every0_15_30_Sec_At_9_30_PM.dayOfMonth(31); every0_15_30_Sec_At_9_30_PM.month("Nov-Feb"); every0_15_30_Sec_At_9_30_PM.second("0,15,30"); every0_15_30_Sec_At_9_30_PM.minute(30); every0_15_30_Sec_At_9_30_PM.hour("21"); CalendarBasedTimeout calendarTimeout = new CalendarBasedTimeout(every0_15_30_Sec_At_9_30_PM); Calendar firstTimeout = calendarTimeout.getFirstTimeout(); Assert.assertNotNull(timeZoneDisplayName, firstTimeout); // logger.debug("First timeout is " + firstTimeoutDate); int minute = firstTimeout.get(Calendar.MINUTE); int second = firstTimeout.get(Calendar.SECOND); int hour = firstTimeout.get(Calendar.HOUR_OF_DAY); int amOrPm = firstTimeout.get(Calendar.AM_PM); int dayOfMonth = firstTimeout.get(Calendar.DAY_OF_MONTH); int month = firstTimeout.get(Calendar.MONTH); Assert.assertEquals(timeZoneDisplayName, 0, second); Assert.assertEquals(timeZoneDisplayName, 30, minute); Assert.assertEquals(timeZoneDisplayName, 21, hour); Assert.assertEquals(timeZoneDisplayName, Calendar.PM, amOrPm); Assert.assertEquals(timeZoneDisplayName, 31, dayOfMonth); List<Integer> validMonths = new ArrayList<Integer>(); validMonths.add(Calendar.NOVEMBER); validMonths.add(Calendar.DECEMBER); validMonths.add(Calendar.JANUARY); validMonths.add(Calendar.FEBRUARY); Assert.assertTrue(timeZoneDisplayName, validMonths.contains(month)); Calendar nextTimeout = calendarTimeout.getNextTimeout(firstTimeout); long diff = nextTimeout.getTimeInMillis() - firstTimeout.getTimeInMillis(); Assert.assertEquals(timeZoneDisplayName, 15 * 1000, diff); Calendar date = new GregorianCalendar(2014,3,18); Calendar nextTimeoutFromNow = calendarTimeout.getNextTimeout(date); // logger.debug("Next timeout from now is " + nextTimeoutFromNow.getTime()); int nextMinute = nextTimeoutFromNow.get(Calendar.MINUTE); int nextSecond = nextTimeoutFromNow.get(Calendar.SECOND); int nextHour = nextTimeoutFromNow.get(Calendar.HOUR_OF_DAY); int nextAmOrPM = nextTimeoutFromNow.get(Calendar.AM_PM); int nextDayOfMonth = nextTimeoutFromNow.get(Calendar.DAY_OF_MONTH); int nextMonth = nextTimeoutFromNow.get(Calendar.MONTH); List<Integer> validSeconds = new ArrayList<Integer>(); validSeconds.add(0); validSeconds.add(15); validSeconds.add(30); Assert.assertTrue(timeZoneDisplayName, validSeconds.contains(nextSecond)); Assert.assertEquals(timeZoneDisplayName, 30, nextMinute); Assert.assertEquals(timeZoneDisplayName, 21, nextHour); Assert.assertEquals(timeZoneDisplayName, Calendar.PM, nextAmOrPM); Assert.assertEquals(timeZoneDisplayName, 31, nextDayOfMonth); Assert.assertTrue(timeZoneDisplayName, validMonths.contains(nextMonth)); } //@Test public void testEvery10Seconds() { ScheduleExpression every10Secs = this.getTimezoneSpecificScheduleExpression(); every10Secs.second("*/10"); every10Secs.minute("*"); every10Secs.hour("*"); CalendarBasedTimeout calendarTimeout = new CalendarBasedTimeout(every10Secs); Calendar firstTimeout = calendarTimeout.getFirstTimeout(); int firstTimeoutSecond = firstTimeout.get(Calendar.SECOND); Assert.assertTrue(timeZoneDisplayName, firstTimeoutSecond % 10 == 0); Calendar previousTimeout = firstTimeout; for (int i = 0; i < 5; i++) { Calendar nextTimeout = calendarTimeout.getNextTimeout(previousTimeout); int nextTimeoutSecond = nextTimeout.get(Calendar.SECOND); Assert.assertTrue(timeZoneDisplayName, nextTimeoutSecond % 10 == 0); previousTimeout = nextTimeout; } } /** * WFLY-1468 * Create a Timeout with a schedule start date in the past (day before) to ensure the time is set correctly. * The schedule is on the first day of month to ensure that the calculated time must be moved to the next month. * * The test is run for each day of a whole year. */ @Test public void testWFLY1468() { ScheduleExpression schedule = new ScheduleExpression(); int year = 2013; int month = Calendar.JUNE; int dayOfMonth = 3; int hourOfDay = 2; int minutes = 0; Calendar start = new GregorianCalendar(year, month, dayOfMonth, hourOfDay, minutes); schedule.hour("0-12") .month("*") .dayOfMonth("3") .minute("0/5") .second("0") .start(start.getTime()); CalendarBasedTimeout calendarTimeout = new CalendarBasedTimeout(schedule); Calendar firstTimeout = calendarTimeout.getFirstTimeout(); // assert first timeout result if(firstTimeout.get(Calendar.DAY_OF_MONTH) != 3 || firstTimeout.get(Calendar.HOUR_OF_DAY) != 2 || firstTimeout.get(Calendar.MINUTE) != 0 || firstTimeout.get(Calendar.SECOND) != 0) { Assert.fail(firstTimeout.toString()); } } /** * Testcase #1 for WFLY-3947 */ @Test public void testWFLY3947_1() { TimeZone timeZone = TimeZone.getTimeZone("Europe/Lisbon"); int year = 2013; int month = Calendar.MARCH; int dayOfMonth = 31; int hourOfDay = 3; int minute = 30; int second = 0; Calendar start = new GregorianCalendar(timeZone); start.clear(); start.set(year, month, dayOfMonth, hourOfDay, minute, second); ScheduleExpression expression = new ScheduleExpression().timezone(timeZone.getID()).dayOfMonth("*").hour("1").minute("30").second("0").start(start.getTime()); CalendarBasedTimeout calendarTimeout = new CalendarBasedTimeout(expression); Calendar firstTimeout = calendarTimeout.getFirstTimeout(); Assert.assertNotNull(firstTimeout); Assert.assertEquals(year, firstTimeout.get(Calendar.YEAR)); Assert.assertEquals(Calendar.APRIL, firstTimeout.get(Calendar.MONTH)); Assert.assertEquals(1, firstTimeout.get(Calendar.DAY_OF_MONTH)); Assert.assertEquals(1, firstTimeout.get(Calendar.HOUR_OF_DAY)); Assert.assertEquals(30, firstTimeout.get(Calendar.MINUTE)); Assert.assertEquals(second, firstTimeout.get(Calendar.SECOND)); } /** * Testcase #2 for WFLY-3947 */ @Test public void testWFLY3947_2() { TimeZone timeZone = TimeZone.getTimeZone("Australia/Lord_Howe"); int year = 2013; int month = Calendar.OCTOBER; int dayOfMonth = 6; int hourOfDay = 2; int minute = 41; int second = 0; Calendar start = new GregorianCalendar(timeZone); start.clear(); start.set(year, month, dayOfMonth, hourOfDay, minute, second); ScheduleExpression expression = new ScheduleExpression().timezone(timeZone.getID()).dayOfMonth("*").hour("2, 3").minute("20, 40").second("0").start(start.getTime()); CalendarBasedTimeout calendarTimeout = new CalendarBasedTimeout(expression); Calendar firstTimeout = calendarTimeout.getFirstTimeout(); Assert.assertNotNull(firstTimeout); Assert.assertEquals(year, firstTimeout.get(Calendar.YEAR)); Assert.assertEquals(month, firstTimeout.get(Calendar.MONTH)); Assert.assertEquals(dayOfMonth, firstTimeout.get(Calendar.DAY_OF_MONTH)); Assert.assertEquals(3, firstTimeout.get(Calendar.HOUR_OF_DAY)); Assert.assertEquals(20, firstTimeout.get(Calendar.MINUTE)); Assert.assertEquals(second, firstTimeout.get(Calendar.SECOND)); } /** * If we have an overflow for minutes, the seconds must be reseted. * Test for WFLY-5995 */ @Test public void testWFLY5995_MinuteOverflow() { int year = 2016; int month = Calendar.JANUARY; int dayOfMonth = 14; int hourOfDay = 9; int minute = 46; int second = 42; Calendar start = new GregorianCalendar(); start.clear(); start.set(year, month, dayOfMonth, hourOfDay, minute, second); ScheduleExpression expression = new ScheduleExpression().dayOfMonth("*").hour("*").minute("0-45").second("0/10").start(start.getTime()); CalendarBasedTimeout calendarTimeout = new CalendarBasedTimeout(expression); Calendar firstTimeout = calendarTimeout.getFirstTimeout(); Assert.assertNotNull(firstTimeout); Assert.assertEquals(year, firstTimeout.get(Calendar.YEAR)); Assert.assertEquals(month, firstTimeout.get(Calendar.MONTH)); Assert.assertEquals(dayOfMonth, firstTimeout.get(Calendar.DAY_OF_MONTH)); Assert.assertEquals(10, firstTimeout.get(Calendar.HOUR_OF_DAY)); Assert.assertEquals(0, firstTimeout.get(Calendar.MINUTE)); Assert.assertEquals(0, firstTimeout.get(Calendar.SECOND)); } /** * If we have an overflow for hours, the minutes and seconds must be reseted. * Test for WFLY-5995 */ @Test public void testWFLY5995_HourOverflow() { int year = 2016; int month = Calendar.JANUARY; int dayOfMonth = 14; int hourOfDay = 9; int minute = 45; int second = 35; Calendar start = new GregorianCalendar(); start.clear(); start.set(year, month, dayOfMonth, hourOfDay, minute, second); ScheduleExpression expression = new ScheduleExpression().dayOfMonth("*").hour("20-22").minute("0/5").second("20,40").start(start.getTime()); CalendarBasedTimeout calendarTimeout = new CalendarBasedTimeout(expression); Calendar firstTimeout = calendarTimeout.getFirstTimeout(); Assert.assertNotNull(firstTimeout); Assert.assertEquals(year, firstTimeout.get(Calendar.YEAR)); Assert.assertEquals(month, firstTimeout.get(Calendar.MONTH)); Assert.assertEquals(dayOfMonth, firstTimeout.get(Calendar.DAY_OF_MONTH)); Assert.assertEquals(20, firstTimeout.get(Calendar.HOUR_OF_DAY)); Assert.assertEquals(0, firstTimeout.get(Calendar.MINUTE)); Assert.assertEquals(20, firstTimeout.get(Calendar.SECOND)); } /** * Check if the hour/minute/second is reseted correct if the day must be updated */ @Test public void testDayOverflow() { int year = 2016; int month = Calendar.JANUARY; int dayOfMonth = 14; int hourOfDay = 9; int minute = 56; int second = 0; Calendar start = new GregorianCalendar(); start.clear(); start.set(year, month, dayOfMonth, hourOfDay, minute, second); ScheduleExpression expression = new ScheduleExpression().dayOfMonth("2-13").hour("3-9").minute("0/5").second("0").start(start.getTime()); CalendarBasedTimeout calendarTimeout = new CalendarBasedTimeout(expression); Calendar firstTimeout = calendarTimeout.getFirstTimeout(); Assert.assertNotNull(firstTimeout); Assert.assertEquals(year, firstTimeout.get(Calendar.YEAR)); Assert.assertEquals(1, firstTimeout.get(Calendar.MONTH)); Assert.assertEquals(2, firstTimeout.get(Calendar.DAY_OF_MONTH)); Assert.assertEquals(3, firstTimeout.get(Calendar.HOUR_OF_DAY)); Assert.assertEquals(0, firstTimeout.get(Calendar.MINUTE)); Assert.assertEquals(0, firstTimeout.get(Calendar.SECOND)); } /** * Change CET winter time to CEST summer time. * The timer should be fired every 15 minutes (absolutely). * The calendar time will jump from 2:00CET to 3:00CEST * The test should be run similar in any OS/JVM default timezone * This is a test to ensure WFLY-9537 will not break this. */ @Test public void testChangeCET2CEST() { Calendar start = new GregorianCalendar(TimeZone.getTimeZone("Europe/Berlin")); start.clear(); // set half an hour before the CET->CEST DST switch 2017 start.set(2017, Calendar.MARCH, 26, 1, 30, 0); ScheduleExpression schedule = new ScheduleExpression(); schedule.hour("*") .minute("0/15") .second("0") .timezone("Europe/Berlin") // don't fail the check below if running in a not default TZ .start(start.getTime()); CalendarBasedTimeout calendarTimeout = new CalendarBasedTimeout(schedule); Calendar firstTimeout = calendarTimeout.getFirstTimeout(); // assert first timeout result Assert.assertNotNull(firstTimeout); if(firstTimeout.get(Calendar.YEAR) != 2017 || firstTimeout.get(Calendar.MONTH) != Calendar.MARCH || firstTimeout.get(Calendar.DAY_OF_MONTH) != 26 || firstTimeout.get(Calendar.HOUR_OF_DAY) != 1 || firstTimeout.get(Calendar.MINUTE) != 30 || firstTimeout.get(Calendar.SECOND) != 0 || firstTimeout.get(Calendar.DST_OFFSET) != 0) { Assert.fail("Start time unexpected : " + firstTimeout.toString()); } Calendar current = firstTimeout; for(int i = 0 ; i<3 ; i++) { Calendar next = calendarTimeout.getNextTimeout(current); if(current.getTimeInMillis() != (next.getTimeInMillis() - 900000)) { Assert.fail("Schedule is more than 15 minutes from " + current.getTime() + " to " + next.getTime()); } current = next; } if(current.get(Calendar.YEAR) != 2017 || current.get(Calendar.MONTH) != Calendar.MARCH || current.get(Calendar.DAY_OF_MONTH) != 26 || current.get(Calendar.HOUR_OF_DAY) != 3 || current.get(Calendar.MINUTE) != 15 || current.get(Calendar.DST_OFFSET) != 3600000) { Assert.fail("End time unexpected : " + current.toString()); } } /** * Change CEST summer time to CEST winter time. * The timer should be fired every 15 minutes (absolutely). * The calendar time will jump from 3:00CEST back to 2:00CET * but the timer must run within 2:00-3:00 CEST and 2:00-3:00CET! * The test should be run similar in any OS/JVM default timezone * This is a test for WFLY-9537 */ @Test public void testChangeCEST2CET() { Calendar start = new GregorianCalendar(TimeZone.getTimeZone("Europe/Berlin")); start.clear(); // set half an hour before the CEST->CET DST switch 2017 start.set(2017, Calendar.OCTOBER, 29, 1, 30, 0); ScheduleExpression schedule = new ScheduleExpression(); schedule.hour("*") .minute("5/15") .second("0") .timezone("Europe/Berlin") // don't fail the check below if running in a not default TZ .start(start.getTime()); CalendarBasedTimeout calendarTimeout = new CalendarBasedTimeout(schedule); Calendar firstTimeout = calendarTimeout.getFirstTimeout(); // assert first timeout result Assert.assertNotNull(firstTimeout); if(firstTimeout.get(Calendar.YEAR) != 2017 || firstTimeout.get(Calendar.MONTH) != Calendar.OCTOBER || firstTimeout.get(Calendar.DAY_OF_MONTH) != 29 || firstTimeout.get(Calendar.HOUR_OF_DAY) != 1 || firstTimeout.get(Calendar.MINUTE) != 35 || firstTimeout.get(Calendar.SECOND) != 0 || firstTimeout.get(Calendar.DST_OFFSET) != 3600000) { Assert.fail("Start time unexpected : " + firstTimeout.toString()); } Calendar current = firstTimeout; for(int i = 0 ; i<7 ; i++) { Calendar next = calendarTimeout.getNextTimeout(current); if(current.getTimeInMillis() != (next.getTimeInMillis() - 900000)) { Assert.fail("Schedule is more than 15 minutes from " + current.getTime() + " to " + next.getTime()); } current = next; } if(current.get(Calendar.YEAR) != 2017 || current.get(Calendar.MONTH) != Calendar.OCTOBER || current.get(Calendar.DAY_OF_MONTH) != 29 || current.get(Calendar.HOUR_OF_DAY) != 2 || current.get(Calendar.MINUTE) != 20 || current.get(Calendar.DST_OFFSET) != 0) { Assert.fail("End time unexpected : " + current.toString()); } } /** * Change PST winter time to PST summer time. * The timer should be fired every 15 minutes (absolutely). * This is a test to ensure WFLY-9537 will not break this. */ @Test public void testChangeUS2Summer() { Calendar start = new GregorianCalendar(TimeZone.getTimeZone("America/Los_Angeles")); start.clear(); // set half an hour before Los Angeles summer time switch start.set(2017, Calendar.MARCH, 12, 1, 30, 0); ScheduleExpression schedule = new ScheduleExpression(); schedule.hour("*") .minute("0/15") .second("0") .timezone("America/Los_Angeles") // don't fail the check below if running in a not default TZ .start(start.getTime()); CalendarBasedTimeout calendarTimeout = new CalendarBasedTimeout(schedule); Calendar firstTimeout = calendarTimeout.getFirstTimeout(); // assert first timeout result Assert.assertNotNull(firstTimeout); if(firstTimeout.get(Calendar.YEAR) != 2017 || firstTimeout.get(Calendar.MONTH) != Calendar.MARCH || firstTimeout.get(Calendar.DAY_OF_MONTH) != 12 || firstTimeout.get(Calendar.HOUR_OF_DAY) != 1 || firstTimeout.get(Calendar.MINUTE) != 30 || firstTimeout.get(Calendar.SECOND) != 0 || firstTimeout.get(Calendar.DST_OFFSET) != 0) { Assert.fail("Start time unexpected : " + firstTimeout.toString()); } Calendar current = firstTimeout; for(int i = 0 ; i<3 ; i++) { Calendar next = calendarTimeout.getNextTimeout(current); if(current.getTimeInMillis() != (next.getTimeInMillis() - 900000)) { Assert.fail("Schedule is more than 15 minutes from " + current.getTime() + " to " + next.getTime()); } current = next; } if(current.get(Calendar.YEAR) != 2017 || current.get(Calendar.MONTH) != Calendar.MARCH || current.get(Calendar.DAY_OF_MONTH) != 12 || current.get(Calendar.HOUR_OF_DAY) != 3 || current.get(Calendar.MINUTE) != 15 || current.get(Calendar.DST_OFFSET) != 3600000) { Assert.fail("End time unexpected : " + current.toString()); } } /** * Change PST summer time to PST winter time. * The timer should be fired every 15 minutes (absolutely). * This is a test for WFLY-9537 */ @Test public void testChangeUS2Winter() { Calendar start = new GregorianCalendar(TimeZone.getTimeZone("America/Los_Angeles")); start.clear(); // set half an hour before Los Angeles time switch to winter time start.set(2017, Calendar.NOVEMBER, 5, 0, 30, 0); ScheduleExpression schedule = new ScheduleExpression(); schedule.hour("*") .minute("0/15") .second("0") .timezone("America/Los_Angeles") // don't fail the check below if running in a not default TZ .start(start.getTime()); CalendarBasedTimeout calendarTimeout = new CalendarBasedTimeout(schedule); Calendar firstTimeout = calendarTimeout.getFirstTimeout(); // assert first timeout result Assert.assertNotNull(firstTimeout); if(firstTimeout.get(Calendar.YEAR) != 2017 || firstTimeout.get(Calendar.MONTH) != Calendar.NOVEMBER || firstTimeout.get(Calendar.DAY_OF_MONTH) != 5 || firstTimeout.get(Calendar.HOUR_OF_DAY) != 0 || firstTimeout.get(Calendar.MINUTE) != 30 || firstTimeout.get(Calendar.SECOND) != 0 || firstTimeout.get(Calendar.DST_OFFSET) != 3600000) { Assert.fail("Start time unexpected : " + firstTimeout.toString()); } Calendar current = firstTimeout; for(int i = 0 ; i<7 ; i++) { Calendar next = calendarTimeout.getNextTimeout(current); if(current.getTimeInMillis() != (next.getTimeInMillis() - 900000)) { Assert.fail("Schedule is more than 15 minutes from " + current.getTime() + " to " + next.getTime()); } current = next; } if(current.get(Calendar.YEAR) != 2017 || current.get(Calendar.MONTH) != Calendar.NOVEMBER || current.get(Calendar.DAY_OF_MONTH) != 5 || current.get(Calendar.HOUR_OF_DAY) != 1 || current.get(Calendar.MINUTE) != 15 || current.get(Calendar.DST_OFFSET) != 0) { Assert.fail("End time unexpected : " + current.toString()); } } /** * This test asserts that the timer increments in seconds, minutes and hours * are the same for a complete year using a DST timezone and a non-DST timezone. * * This test covers WFLY-10106 issue. */ @Test public void testTimeoutIncrements(){ TimeZone dstTimezone = TimeZone.getTimeZone("Atlantic/Canary"); TimeZone nonDstTimezone = TimeZone.getTimeZone("Africa/Abidjan"); Assert.assertTrue(dstTimezone.useDaylightTime()); Assert.assertTrue(!nonDstTimezone.useDaylightTime()); for (TimeZone tz : Arrays.asList(dstTimezone, nonDstTimezone)) { this.timezone = tz; testSecondIncrement(); testMinutesIncrement(); testHoursIncrement(); } } public void testSecondIncrement() { Calendar start = new GregorianCalendar(timezone); start.clear(); start.set(2018, Calendar.JANUARY, 1, 10, 00, 0); ScheduleExpression schedule = new ScheduleExpression(); schedule.hour("*") .minute("*") .second("*/30") .timezone(timezone.getID()) .start(start.getTime()); CalendarBasedTimeout calendarTimeout = new CalendarBasedTimeout(schedule); Calendar firstTimeout = calendarTimeout.getFirstTimeout(); Assert.assertNotNull(firstTimeout); if(firstTimeout.get(Calendar.YEAR) != 2018 || firstTimeout.get(Calendar.MONTH) != Calendar.JANUARY || firstTimeout.get(Calendar.DAY_OF_MONTH) != 1 || firstTimeout.get(Calendar.HOUR_OF_DAY) != 10 || firstTimeout.get(Calendar.MINUTE) != 0 || firstTimeout.get(Calendar.SECOND) != 0 || firstTimeout.get(Calendar.DST_OFFSET) != start.get(Calendar.DST_OFFSET) ) { Assert.fail("Start time unexpected : " + firstTimeout.toString()); } Calendar current = firstTimeout; long numInvocations = 366*24*60*60/30; long millisecondsDiff = 30*1000; for(int i = 0 ; i<numInvocations; i++) { Calendar next = calendarTimeout.getNextTimeout(current); if(current.getTimeInMillis() != (next.getTimeInMillis() - millisecondsDiff)) { Assert.fail("Schedule is more than 30 seconds from " + current.getTime() + " to " + next.getTime()); } current = next; } if(current.get(Calendar.YEAR) != 2019 || current.get(Calendar.MONTH) != Calendar.JANUARY || current.get(Calendar.DAY_OF_MONTH) != 2 || current.get(Calendar.HOUR_OF_DAY) != 10 || current.get(Calendar.MINUTE) != 0 || current.get(Calendar.SECOND) != 0 || current.get(Calendar.DST_OFFSET) != start.get(Calendar.DST_OFFSET) ) { Assert.fail("End time unexpected : " + current.toString()); } } public void testMinutesIncrement() { Calendar start = new GregorianCalendar(timezone); start.clear(); start.set(2017, Calendar.JANUARY, 1, 0, 0, 0); ScheduleExpression schedule = new ScheduleExpression(); schedule.hour("*") .minute("*/15") .second("0") .timezone(timezone.getID()) .start(start.getTime()); CalendarBasedTimeout calendarTimeout = new CalendarBasedTimeout(schedule); Calendar firstTimeout = calendarTimeout.getFirstTimeout(); Assert.assertNotNull(firstTimeout); if(firstTimeout.get(Calendar.YEAR) != 2017 || firstTimeout.get(Calendar.MONTH) != Calendar.JANUARY || firstTimeout.get(Calendar.DAY_OF_MONTH) != 1 || firstTimeout.get(Calendar.HOUR_OF_DAY) != 0 || firstTimeout.get(Calendar.MINUTE) != 0 || firstTimeout.get(Calendar.SECOND) != 0 || firstTimeout.get(Calendar.DST_OFFSET) != start.get(Calendar.DST_OFFSET) ) { Assert.fail("Start time unexpected : " + firstTimeout.toString()); } Calendar current = firstTimeout; long numInvocations = 366*24*60/15; long millisecondsDiff = 15*60*1000; for(int i = 0 ; i<numInvocations; i++) { Calendar next = calendarTimeout.getNextTimeout(current); if(current.getTimeInMillis() != (next.getTimeInMillis() - millisecondsDiff)) { Assert.fail("Schedule is more than 15 minutes from " + current.getTime() + " to " + next.getTime()); } current = next; } if(current.get(Calendar.YEAR) != 2018 || current.get(Calendar.MONTH) != Calendar.JANUARY || current.get(Calendar.DAY_OF_MONTH) != 2 || current.get(Calendar.HOUR_OF_DAY) != 0 || current.get(Calendar.MINUTE) != 0 || current.get(Calendar.SECOND) != 0 || current.get(Calendar.DST_OFFSET) != start.get(Calendar.DST_OFFSET) ) { Assert.fail("End time unexpected : " + current.toString()); } } public void testHoursIncrement() { Calendar start = new GregorianCalendar(timezone); start.clear(); start.set(2017, Calendar.JANUARY, 1, 0, 0, 0); ScheduleExpression schedule = new ScheduleExpression(); schedule.hour("*") .minute("30") .second("0") .timezone(timezone.getID()) .start(start.getTime()); CalendarBasedTimeout calendarTimeout = new CalendarBasedTimeout(schedule); Calendar firstTimeout = calendarTimeout.getFirstTimeout(); Assert.assertNotNull(firstTimeout); if(firstTimeout.get(Calendar.YEAR) != 2017 || firstTimeout.get(Calendar.MONTH) != Calendar.JANUARY || firstTimeout.get(Calendar.DAY_OF_MONTH) != 1 || firstTimeout.get(Calendar.HOUR_OF_DAY) != 0 || firstTimeout.get(Calendar.MINUTE) != 30 || firstTimeout.get(Calendar.SECOND) != 0 || firstTimeout.get(Calendar.DST_OFFSET) != start.get(Calendar.DST_OFFSET) ) { Assert.fail("Start time unexpected : " + firstTimeout.toString()); } Calendar current = firstTimeout; long numInvocations = 366*24; long millisecondsDiff = 60*60*1000; for(int i = 0 ; i<numInvocations; i++) { Calendar next = calendarTimeout.getNextTimeout(current); if(current.getTimeInMillis() != (next.getTimeInMillis() - millisecondsDiff)) { Assert.fail("Schedule is more than 1 hours from " + current.getTime() + " to " + next.getTime() + " for timezone " + timezone.getID()); } current = next; } if(current.get(Calendar.YEAR) != 2018 || current.get(Calendar.MONTH) != Calendar.JANUARY || current.get(Calendar.DAY_OF_MONTH) != 2 || current.get(Calendar.HOUR_OF_DAY) != 0 || current.get(Calendar.MINUTE) != 30 || current.get(Calendar.SECOND) != 0 || current.get(Calendar.DST_OFFSET) != start.get(Calendar.DST_OFFSET) ) { Assert.fail("End time unexpected : " + current.toString()); } } /** * This test asserts that a timer scheduled to run during the ambiguous hour when the * Daylight Savings period ends is not executed twice. * * It configures a timer to be fired on October 29, 2017 at 01:30:00 in Europe/Lisbon TZ. * There are two 01:30:00 that day: 01:30:00 WEST and 01:30:00 WET. The timer has to be * fired just once. */ @Test public void testTimerAtAmbiguousHourWESTtoWET() { // WEST -> WET // Sunday, 29 October 2017, 02:00:00 -> 01:00:00 Calendar start = new GregorianCalendar(TimeZone.getTimeZone("Europe/Lisbon")); start.clear(); start.set(2017, Calendar.OCTOBER, 29, 0, 0, 0); ScheduleExpression schedule = new ScheduleExpression(); schedule.hour("1") .minute("30") .second("0") .timezone("Europe/Lisbon") .start(start.getTime()); CalendarBasedTimeout calendarTimeout = new CalendarBasedTimeout(schedule); Calendar timeout = calendarTimeout.getFirstTimeout(); Assert.assertNotNull(timeout); //Assert timeout is 29 October at 01:30 WEST if (timeout.get(Calendar.YEAR) != 2017 || timeout.get(Calendar.MONTH) != Calendar.OCTOBER || timeout.get(Calendar.DAY_OF_MONTH) != 29 || timeout.get(Calendar.HOUR_OF_DAY) != 1 || timeout.get(Calendar.MINUTE) != 30 || timeout.get(Calendar.SECOND) != 0 || timeout.get(Calendar.DST_OFFSET) != 3600000) { Assert.fail("Time unexpected : " + timeout.toString()); } //Asserts elapsed time from start was 1h 30min: Assert.assertTrue("Schedule is more than 1h 30min hours from " + start.getTime() + " to " + timeout.getTime(), timeout.getTimeInMillis()-start.getTimeInMillis() == 1*60*60*1000 + 30*60*1000); timeout = calendarTimeout.getNextTimeout(timeout); //Assert timeout is 30 October at 01:30 WET if (timeout.get(Calendar.YEAR) != 2017 || timeout.get(Calendar.MONTH) != Calendar.OCTOBER || timeout.get(Calendar.DAY_OF_MONTH) != 30 || timeout.get(Calendar.HOUR_OF_DAY) != 1 || timeout.get(Calendar.MINUTE) != 30 || timeout.get(Calendar.SECOND) != 0 || timeout.get(Calendar.DST_OFFSET) != 0) { Assert.fail("Time unexpected : " + timeout.toString()); } } /** * This test asserts that a timer scheduled to run during the removed hour when the * Daylight Savings period starts is executed. * * It configures a timer to be fired on March 26, 2017 at 03:30:00 in Europe/Helsinki TZ. * This hour does not exist in that timezone, this test asserts the timer is fired once * during this ambiguous hour. */ @Test public void testTimerAtAmbiguousHourEETtoEEST() { // EET --> EEST // Sunday, 26 March 2017, 03:00:00 --> 04:00:00 Calendar start = new GregorianCalendar(TimeZone.getTimeZone("Europe/Helsinki")); start.clear(); start.set(2017, Calendar.MARCH, 26, 0, 0, 0); ScheduleExpression schedule = new ScheduleExpression(); schedule.hour("3") .minute("30") .second("0") .timezone("Europe/Helsinki") .start(start.getTime()); CalendarBasedTimeout calendarTimeout = new CalendarBasedTimeout(schedule); Calendar timeout = calendarTimeout.getFirstTimeout(); Assert.assertNotNull(timeout); //Assert timeout is 26 March at 03:30 EET if (timeout.get(Calendar.YEAR) != 2017 || timeout.get(Calendar.MONTH) != Calendar.MARCH || timeout.get(Calendar.DAY_OF_MONTH) != 26 || timeout.get(Calendar.HOUR_OF_DAY) != 3 || timeout.get(Calendar.MINUTE) != 30 || timeout.get(Calendar.SECOND) != 0 || timeout.get(Calendar.DST_OFFSET) != 0) { Assert.fail("Time unexpected : " + timeout.toString()); } //Asserts elapsed time from start was 3h 30min: Assert.assertTrue("Schedule is more than 3h 30min hours from " + start.getTime() + " to " + timeout.getTime(), timeout.getTimeInMillis()-start.getTimeInMillis() == 3*60*60*1000 + 30*60*1000); timeout = calendarTimeout.getNextTimeout(timeout); //Assert timeout is 27 March at 03:30 EEST if (timeout.get(Calendar.YEAR) != 2017 || timeout.get(Calendar.MONTH) != Calendar.MARCH || timeout.get(Calendar.DAY_OF_MONTH) != 27 || timeout.get(Calendar.HOUR_OF_DAY) != 3 || timeout.get(Calendar.MINUTE) != 30 || timeout.get(Calendar.SECOND) != 0 || timeout.get(Calendar.DST_OFFSET) != 3600000) { Assert.fail("Time unexpected : " + timeout.toString()); } } private ScheduleExpression getTimezoneSpecificScheduleExpression() { ScheduleExpression scheduleExpression = new ScheduleExpression().timezone(this.timezone.getID()); GregorianCalendar start = new GregorianCalendar(this.timezone); start.clear(); start.set(2014,0,1,1,0,0); return scheduleExpression.start(start.getTime()); } private boolean isLeapYear(Calendar cal) { int year = cal.get(Calendar.YEAR); return year % 4 == 0; } private boolean isWeekDay(Calendar cal) { int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK); switch (dayOfWeek) { case Calendar.SATURDAY: case Calendar.SUNDAY: return false; default: return true; } } }
53,872
44.347643
199
java
null
wildfly-main/ejb3/src/test/java/org/jboss/as/ejb3/timerservice/schedule/CalendarUtilTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2009, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ejb3.timerservice.schedule; import java.util.Calendar; import java.util.GregorianCalendar; import org.jboss.as.ejb3.timerservice.schedule.util.CalendarUtil; import org.junit.Assert; import org.junit.Test; /** * Tests {@link CalendarUtil} * * @author Jaikiran Pai * @version $Revision: $ */ public class CalendarUtilTestCase { /** * Tests that the {@link CalendarUtil#getLastDateOfMonth(java.util.Calendar)} returns the correct * date for various months. */ @Test public void testLastDateOfMonth() { // check last date of march Calendar march = new GregorianCalendar(); march.set(Calendar.MONTH, Calendar.MARCH); march.set(Calendar.DAY_OF_MONTH, 1); int lastDateOfMarch = CalendarUtil.getLastDateOfMonth(march); Assert.assertEquals("Unexpected last date for march", 31, lastDateOfMarch); // check for april Calendar april = new GregorianCalendar(); april.set(Calendar.MONTH, Calendar.APRIL); april.set(Calendar.DAY_OF_MONTH, 1); int lastDateOfApril = CalendarUtil.getLastDateOfMonth(april); Assert.assertEquals("Unexpected last date for april", 30, lastDateOfApril); // check of february (non-leap year) Calendar nonLeapFebruary = new GregorianCalendar(); nonLeapFebruary.set(Calendar.MONTH, Calendar.FEBRUARY); nonLeapFebruary.set(Calendar.YEAR, 2010); nonLeapFebruary.set(Calendar.DAY_OF_MONTH, 1); int lastDateOfNonLeapFebruary = CalendarUtil.getLastDateOfMonth(nonLeapFebruary); Assert.assertEquals("Unexpected last date for non-leap february", 28, lastDateOfNonLeapFebruary); // check for february (leap year) Calendar leapFebruary = new GregorianCalendar(); leapFebruary.set(Calendar.MONTH, Calendar.FEBRUARY); leapFebruary.set(Calendar.YEAR, 2012); leapFebruary.set(Calendar.DAY_OF_MONTH, 1); int lastDateOfLeapFebruary = CalendarUtil.getLastDateOfMonth(leapFebruary); Assert.assertEquals("Unexpected last date for leap february", 29, lastDateOfLeapFebruary); } @Test public void test1stXXXDay() { final int FIRST_WEEK = 1; // 1st Sun of July 2010 (hardcoded, after checking with the system calendar) int expectedDateOfFirstSunOfJuly2010 = 4; Calendar july2010 = new GregorianCalendar(); july2010.set(Calendar.DAY_OF_MONTH, 1); july2010.set(Calendar.MONTH, Calendar.JULY); july2010.set(Calendar.YEAR, 2010); int dateOfFirstSunOfJuly2010 = CalendarUtil.getNthDayOfMonth(july2010, FIRST_WEEK, Calendar.SUNDAY); Assert.assertEquals("Unexpected date for 1st sunday of July 2010", expectedDateOfFirstSunOfJuly2010, dateOfFirstSunOfJuly2010); // 1st Mon of June 2009 int expectedDateOfFirstMonOfJune2009 = 1; Calendar june2009 = new GregorianCalendar(); june2009.set(Calendar.DAY_OF_MONTH, 1); june2009.set(Calendar.MONTH, Calendar.JUNE); june2009.set(Calendar.YEAR, 2009); int dateOfFirstMonJune2009 = CalendarUtil.getNthDayOfMonth(june2009, FIRST_WEEK, Calendar.MONDAY); Assert.assertEquals("Unexpected date for 1st monday of June 2009", expectedDateOfFirstMonOfJune2009, dateOfFirstMonJune2009); // 1st Tue of Feb 2012 int expectedDateOfFirstTueOfFeb2012 = 7; Calendar feb2012 = new GregorianCalendar(); feb2012.set(Calendar.DAY_OF_MONTH, 1); feb2012.set(Calendar.MONTH, Calendar.FEBRUARY); feb2012.set(Calendar.YEAR, 2012); int dateOfFirstTueFeb2012 = CalendarUtil.getNthDayOfMonth(feb2012, FIRST_WEEK, Calendar.TUESDAY); Assert.assertEquals("Unexpected date for 1st tuesday of Feb 2012", expectedDateOfFirstTueOfFeb2012, dateOfFirstTueFeb2012); // 1st Wed of Jan 2006 int expectedDateOfFirstMonOfJan2006 = 4; Calendar jan2006 = new GregorianCalendar(); jan2006.set(Calendar.DAY_OF_MONTH, 1); jan2006.set(Calendar.MONTH, Calendar.JANUARY); jan2006.set(Calendar.YEAR, 2006); int dateOfFirstWedJan2006 = CalendarUtil.getNthDayOfMonth(jan2006, FIRST_WEEK, Calendar.WEDNESDAY); Assert.assertEquals("Unexpected date for 1st wednesday of Jan 2006", expectedDateOfFirstMonOfJan2006, dateOfFirstWedJan2006); // 1st Thu of June 1999 int expectedDateOfFirstThuOfSep1999 = 2; Calendar sep1999 = new GregorianCalendar(); sep1999.set(Calendar.DAY_OF_MONTH, 1); sep1999.set(Calendar.MONTH, Calendar.SEPTEMBER); sep1999.set(Calendar.YEAR, 1999); int dateOfFirstThuSep1999 = CalendarUtil.getNthDayOfMonth(sep1999, FIRST_WEEK, Calendar.THURSDAY); Assert.assertEquals("Unexpected date for 1st thursday of September 1999", expectedDateOfFirstThuOfSep1999, dateOfFirstThuSep1999); // 1st Fri of Dec 2058 int expectedDateOfFirstFriOfDec2058 = 6; Calendar dec2058 = new GregorianCalendar(); dec2058.set(Calendar.DAY_OF_MONTH, 1); dec2058.set(Calendar.MONTH, Calendar.DECEMBER); dec2058.set(Calendar.YEAR, 2058); int dateOfFirstFriDec2058 = CalendarUtil.getNthDayOfMonth(dec2058, FIRST_WEEK, Calendar.FRIDAY); Assert.assertEquals("Unexpected date for 1st friday of December 2058", expectedDateOfFirstFriOfDec2058, dateOfFirstFriDec2058); // 1st Sat of Aug 2000 int expectedDateOfFirstSatOfAug2000 = 5; Calendar aug2000 = new GregorianCalendar(); aug2000.set(Calendar.DAY_OF_MONTH, 1); aug2000.set(Calendar.MONTH, Calendar.AUGUST); aug2000.set(Calendar.YEAR, 2000); int dateOfFirstSatAug2000 = CalendarUtil.getNthDayOfMonth(aug2000, FIRST_WEEK, Calendar.SATURDAY); Assert.assertEquals("Unexpected date for 1st saturday of August 2000", expectedDateOfFirstSatOfAug2000, dateOfFirstSatAug2000); } @Test public void test2ndXXXDay() { final int SECOND_WEEK = 2; // 2nd Sun of May 2010 (hardcoded, after checking with the system calendar) int expectedDateOfSecondSunOfMay2010 = 9; Calendar may2010 = new GregorianCalendar(); may2010.set(Calendar.MONTH, Calendar.MAY); may2010.set(Calendar.YEAR, 2010); int dateOfSecondSunOfMay2010 = CalendarUtil.getNthDayOfMonth(may2010, SECOND_WEEK, Calendar.SUNDAY); Assert.assertEquals("Unexpected date for 2nd sunday of May 2010", expectedDateOfSecondSunOfMay2010, dateOfSecondSunOfMay2010); // 2nd Mon of Feb 2111 int expectedDateOfSecondMonOfFeb2111 = 9; Calendar feb2111 = new GregorianCalendar(); feb2111.set(Calendar.MONTH, Calendar.FEBRUARY); feb2111.set(Calendar.YEAR, 2111); int dateOfSecondMonFeb2111 = CalendarUtil.getNthDayOfMonth(feb2111, SECOND_WEEK, Calendar.MONDAY); Assert.assertEquals("Unexpected date for 2nd monday of Feb 2111", expectedDateOfSecondMonOfFeb2111, dateOfSecondMonFeb2111); // 2nd Tue of Oct 2016 int expectedDateOfSecondTueOct2016 = 11; Calendar oct2016 = new GregorianCalendar(); oct2016.set(Calendar.MONTH, Calendar.OCTOBER); oct2016.set(Calendar.YEAR, 2016); int dateOfSecondTueOct2016 = CalendarUtil.getNthDayOfMonth(oct2016, SECOND_WEEK, Calendar.TUESDAY); Assert.assertEquals("Unexpected date for 2nd tuesday of Oct 2016", expectedDateOfSecondTueOct2016, dateOfSecondTueOct2016); // 2nd Wed of Apr 2010 int expectedDateOfSecWedApr2010 = 14; Calendar apr2010 = new GregorianCalendar(); apr2010.set(Calendar.DAY_OF_MONTH, 1); apr2010.set(Calendar.MONTH, Calendar.APRIL); apr2010.set(Calendar.YEAR, 2010); int dateOfSecondWedApril2010 = CalendarUtil.getNthDayOfMonth(apr2010, SECOND_WEEK, Calendar.WEDNESDAY); Assert.assertEquals("Unexpected date for 2nd wednesday of April 2010", expectedDateOfSecWedApr2010, dateOfSecondWedApril2010); // 2nd Thu of Mar 2067 int expectedDateOfSecondThuMar2067 = 10; Calendar march2067 = new GregorianCalendar(); march2067.set(Calendar.DAY_OF_MONTH, 1); march2067.set(Calendar.MONTH, Calendar.MARCH); march2067.set(Calendar.YEAR, 2067); int dateOfSecThuMarch2067 = CalendarUtil.getNthDayOfMonth(march2067, SECOND_WEEK, Calendar.THURSDAY); Assert.assertEquals("Unexpected date for 2nd thursday of March 2067", expectedDateOfSecondThuMar2067, dateOfSecThuMarch2067); // 2nd Fri of Nov 2020 int expectedDateOfSecFriNov2020 = 13; Calendar nov2020 = new GregorianCalendar(); nov2020.set(Calendar.DAY_OF_MONTH, 1); nov2020.set(Calendar.MONTH, Calendar.NOVEMBER); nov2020.set(Calendar.YEAR, 2020); int dateOfFirstFriDec2058 = CalendarUtil.getNthDayOfMonth(nov2020, SECOND_WEEK, Calendar.FRIDAY); Assert.assertEquals("Unexpected date for 2nd friday of November 2020", expectedDateOfSecFriNov2020, dateOfFirstFriDec2058); // 2nd Sat of Sep 2013 int expectedDateOfSecSatOfSep2013 = 14; Calendar aug2000 = new GregorianCalendar(); aug2000.set(Calendar.DAY_OF_MONTH, 1); aug2000.set(Calendar.MONTH, Calendar.SEPTEMBER); aug2000.set(Calendar.YEAR, 2013); int dateOfSecSatSep2013 = CalendarUtil.getNthDayOfMonth(aug2000, SECOND_WEEK, Calendar.SATURDAY); Assert.assertEquals("Unexpected date for 2nd saturday of September 2013", expectedDateOfSecSatOfSep2013, dateOfSecSatSep2013); } @Test public void test3rdXXXDay() { // 1st Sun of July 2010 (hardcoded, after checking with the system calendar) int expectedDateOfFirstSunOfJuly2010 = 4; Calendar july2010 = new GregorianCalendar(); july2010.set(Calendar.MONTH, Calendar.JULY); july2010.set(Calendar.YEAR, 2010); int dateOfFirstSunOfJuly2010 = CalendarUtil.getNthDayOfMonth(july2010, 1, Calendar.SUNDAY); Assert.assertEquals("Unexpected date for 1st sunday of July 2010", expectedDateOfFirstSunOfJuly2010, dateOfFirstSunOfJuly2010); } @Test public void test4thXXXDay() { // 1st Sun of July 2010 (hardcoded, after checking with the system calendar) int expectedDateOfFirstSunOfJuly2010 = 4; Calendar july2010 = new GregorianCalendar(); july2010.set(Calendar.MONTH, Calendar.JULY); july2010.set(Calendar.YEAR, 2010); int dateOfFirstSunOfJuly2010 = CalendarUtil.getNthDayOfMonth(july2010, 1, Calendar.SUNDAY); Assert.assertEquals("Unexpected date for 1st sunday of July 2010", expectedDateOfFirstSunOfJuly2010, dateOfFirstSunOfJuly2010); } @Test public void test5thXXXDay() { // 1st Sun of July 2010 (hardcoded, after checking with the system calendar) int expectedDateOfFirstSunOfJuly2010 = 4; Calendar july2010 = new GregorianCalendar(); july2010.set(Calendar.MONTH, Calendar.JULY); july2010.set(Calendar.YEAR, 2010); int dateOfFirstSunOfJuly2010 = CalendarUtil.getNthDayOfMonth(july2010, 1, Calendar.SUNDAY); Assert.assertEquals("Unexpected date for 1st sunday of July 2010", expectedDateOfFirstSunOfJuly2010, dateOfFirstSunOfJuly2010); } @Test public void test1stSunday() { // 1st Sun of July 2010 (hardcoded, after checking with the system calendar) int expectedDateOfFirstSunOfJuly2010 = 4; Calendar july2010 = new GregorianCalendar(); july2010.set(Calendar.MONTH, Calendar.JULY); july2010.set(Calendar.YEAR, 2010); int dateOfFirstSunOfJuly2010 = CalendarUtil.getNthDayOfMonth(july2010, 1, Calendar.SUNDAY); Assert.assertEquals("Unexpected date for 1st sunday of July 2010", expectedDateOfFirstSunOfJuly2010, dateOfFirstSunOfJuly2010); } }
13,189
42.820598
114
java
null
wildfly-main/ejb3/src/test/java/org/jboss/as/ejb3/timerservice/persistence/database/DatabaseTimerPersistenceTestCase.java
package org.jboss.as.ejb3.timerservice.persistence.database; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Properties; import org.junit.Assert; import org.junit.Before; import org.junit.Test; public class DatabaseTimerPersistenceTestCase { private DatabaseTimerPersistence object = new DatabaseTimerPersistence(null, null, null, null, "", "part", "nodeA", 1000000, true); private Field field; private Method method; @Before public void initializeVars() throws NoSuchFieldException, NoSuchMethodException, IllegalAccessException { field = object.getClass().getDeclaredField("database"); field.setAccessible(true); method = object.getClass().getDeclaredMethod("investigateDialect"); method.setAccessible(true); final Field sqlField = object.getClass().getDeclaredField("sql"); sqlField.setAccessible(true); final Properties testSqlProperties = new Properties(); testSqlProperties.setProperty("create-auto-timer", "insert..."); sqlField.set(object, testSqlProperties); } @Test public void databaseValueTest() throws IllegalAccessException, InvocationTargetException { // test mysql field.set(object, "mysqlTest"); method.invoke(object); Assert.assertEquals("mysql", field.get(object)); field.set(object, "custom-mysql-driver"); method.invoke(object); Assert.assertEquals("mysql", field.get(object)); field.set(object, "testMysql"); method.invoke(object); Assert.assertEquals("mysql", field.get(object)); // test mariadb field.set(object, "mariadbTest"); method.invoke(object); Assert.assertEquals("mariadb", field.get(object)); field.set(object, "custom-mariadb-driver"); method.invoke(object); Assert.assertEquals("mariadb",field.get(object)); field.set(object, "testMariadb"); method.invoke(object); Assert.assertEquals("mariadb", field.get(object)); // test postgres field.set(object, "postgresTest"); method.invoke(object); Assert.assertEquals("postgresql", field.get(object)); field.set(object, "custom-postgres-driver"); method.invoke(object); Assert.assertEquals("postgresql", field.get(object)); field.set(object, "testPostgres"); method.invoke(object); Assert.assertEquals("postgresql", field.get(object)); // test db2 field.set(object, "db2Test"); method.invoke(object); Assert.assertEquals("db2", field.get(object)); field.set(object, "custom-db2-driver"); method.invoke(object); Assert.assertEquals("db2", field.get(object)); field.set(object, "testDb2"); method.invoke(object); Assert.assertEquals("db2", field.get(object)); // test hsql field.set(object, "hsqlTest"); method.invoke(object); Assert.assertEquals("hsql", field.get(object)); field.set(object, "custom-hsql-driver"); method.invoke(object); Assert.assertEquals("hsql", field.get(object)); field.set(object, "testHsql"); method.invoke(object); Assert.assertEquals("hsql", field.get(object)); // test hsql field.set(object, "h2Test"); method.invoke(object); Assert.assertEquals("h2", field.get(object)); field.set(object, "custom-h2-driver"); method.invoke(object); Assert.assertEquals("h2", field.get(object)); field.set(object, "testH2"); method.invoke(object); Assert.assertEquals("h2", field.get(object)); // test oracle field.set(object, "oracleTest"); method.invoke(object); Assert.assertEquals("oracle", field.get(object)); field.set(object, "custom-oracle-driver"); method.invoke(object); Assert.assertEquals("oracle", field.get(object)); field.set(object, "testOracle"); method.invoke(object); Assert.assertEquals("oracle", field.get(object)); // test mssql field.set(object, "microsoftTest"); method.invoke(object); Assert.assertEquals("mssql", field.get(object)); field.set(object, "custom-microsoft-driver"); method.invoke(object); Assert.assertEquals("mssql", field.get(object)); field.set(object, "testMicrosoft"); method.invoke(object); Assert.assertEquals("mssql", field.get(object)); field.set(object, "mssql"); method.invoke(object); Assert.assertEquals("mssql", field.get(object)); field.set(object, "MSSQL"); method.invoke(object); Assert.assertEquals("mssql", field.get(object)); field.set(object, "mssql-version-x"); method.invoke(object); Assert.assertEquals("mssql", field.get(object)); // test sybase field.set(object, "jconnectTest"); method.invoke(object); Assert.assertEquals("sybase", field.get(object)); field.set(object, "custom-jconnect-driver"); method.invoke(object); Assert.assertEquals("sybase", field.get(object)); field.set(object, "testJconnect"); method.invoke(object); Assert.assertEquals("sybase", field.get(object)); } }
5,461
31.903614
135
java
null
wildfly-main/ejb3/src/test/java/org/jboss/as/ejb3/timerservice/distributable/DefaultScheduleTimerOperationProviderTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2021, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ejb3.timerservice.distributable; import java.time.Duration; import java.time.Instant; import java.time.temporal.ChronoUnit; import java.util.Date; import java.util.function.UnaryOperator; import jakarta.ejb.ScheduleExpression; import org.junit.Assert; import org.junit.Test; import org.wildfly.clustering.ejb.timer.ImmutableScheduleExpression; import org.wildfly.clustering.ejb.timer.ScheduleTimerOperationProvider; /** * @author Paul Ferraro */ public class DefaultScheduleTimerOperationProviderTestCase { private final ScheduleTimerOperationProvider provider = new DefaultScheduleTimerOperationProvider(); @Test public void test() { ImmutableScheduleExpression expression = new SimpleImmutableScheduleExpression(new ScheduleExpression().hour("*").minute("*")); UnaryOperator<Instant> operator = this.provider.createOperator(expression); Instant lastTimeout = Instant.now().truncatedTo(ChronoUnit.MINUTES); Instant nextTimeout = operator.apply(lastTimeout); Assert.assertEquals(Duration.between(lastTimeout, nextTimeout), Duration.ofMinutes(1)); Assert.assertEquals(Duration.between(nextTimeout, operator.apply(nextTimeout)), Duration.ofMinutes(1)); // Validate that operation is idempotent Assert.assertEquals(Duration.between(nextTimeout, operator.apply(nextTimeout)), Duration.ofMinutes(1)); } @Test public void testInitialPast() { // Verify start date in past Instant start = Instant.now().minus(Duration.ofHours(1)).truncatedTo(ChronoUnit.SECONDS); ImmutableScheduleExpression expression = new SimpleImmutableScheduleExpression(new ScheduleExpression().hour("*").minute("*").second("*").start(Date.from(start))); UnaryOperator<Instant> operator = this.provider.createOperator(expression); Instant initialTimeout = operator.apply(null); Assert.assertEquals(start, initialTimeout); Assert.assertEquals(Duration.between(initialTimeout, operator.apply(initialTimeout)), Duration.ofSeconds(1)); } @Test public void testInitialFuture() { // Verify start date in future Instant start = Instant.now().plus(Duration.ofHours(1)).truncatedTo(ChronoUnit.SECONDS); ImmutableScheduleExpression expression = new SimpleImmutableScheduleExpression(new ScheduleExpression().hour("*").minute("*").second("*").start(Date.from(start))); UnaryOperator<Instant> operator = this.provider.createOperator(expression); Instant initialTimeout = operator.apply(null); Assert.assertEquals(start, initialTimeout); Assert.assertEquals(Duration.between(initialTimeout, operator.apply(initialTimeout)), Duration.ofSeconds(1)); } }
3,774
46.78481
171
java
null
wildfly-main/ejb3/src/test/java/org/jboss/as/ejb3/deployment/processors/ViewInterfacesTestCase.java
package org.jboss.as.ejb3.deployment.processors; import groovy.lang.MetaClass; import java.util.Set; import jakarta.jms.MessageListener; import org.junit.Assert; import org.junit.Test; /** * Tests {@link ViewInterfaces} * * @author Filipe Ferraz * @version $Revision: $ */ public class ViewInterfacesTestCase { /** * Tests that the {@link ViewInterfaces#getPotentialViewInterfaces(Class<?>)} returns the correct * implementation class for java class implementing MessageListener interface. */ @Test public void testJavaClass() { Set javaClasses = ViewInterfaces.getPotentialViewInterfaces(TestJavaMessageListener.class); Assert.assertEquals("One object epected in Java class", 1, javaClasses.size()); Assert.assertEquals("Expected interface in Java class", MessageListener.class, javaClasses.iterator().next()); } /** * Tests that the {@link ViewInterfaces#getPotentialViewInterfaces(Class<?>)} returns the correct * implementation class for groovy class implementing MessageListener interface. */ @Test public void testGroovyClass() { Set groovyClasses = ViewInterfaces.getPotentialViewInterfaces(TestGroovyMessageListener.class); Assert.assertEquals("One object epected in Groovy class", 1, groovyClasses.size()); Assert.assertEquals("Expected interface in Groovy class", MessageListener.class, groovyClasses.iterator().next()); } private abstract class TestJavaMessageListener implements MessageListener { } private abstract class TestGroovyMessageListener implements MessageListener, MetaClass { } }
1,644
33.270833
122
java
null
wildfly-main/ejb3/src/test/java/org/jboss/as/ejb3/subsystem/Ejb3TransformersTestCase.java
package org.jboss.as.ejb3.subsystem; import static org.jboss.as.controller.capability.RuntimeCapability.buildDynamicCapabilityName; import java.io.IOException; import java.util.List; import org.jboss.as.controller.ModelVersion; import org.jboss.as.controller.PathAddress; import org.jboss.as.model.test.FailedOperationTransformationConfig; import org.jboss.as.model.test.ModelFixer; import org.jboss.as.model.test.ModelTestControllerVersion; import org.jboss.as.model.test.ModelTestUtils; import org.jboss.as.subsystem.test.AbstractSubsystemBaseTest; import org.jboss.as.subsystem.test.AdditionalInitialization; import org.jboss.as.subsystem.test.KernelServices; import org.jboss.as.subsystem.test.KernelServicesBuilder; import org.jboss.dmr.ModelNode; import org.junit.Assert; /** * Test cases for transformers used in the EJB3 subsystem. * <p> * This checks the following features: * - basic subsystem testing (i.e. current model version boots successfully) * - registered transformers transform model and operations correctly between different API model versions * - expressions appearing in XML configurations are correctly rejected if so required * - bad attribute values are correctly rejected * * @author <a href="[email protected]"> Tomasz Cerar</a> * @author Richard Achmatowicz (c) 2015 Red Hat Inc. * @author Richard Achmatowicz (c) 2020 Red Hat Inc. * * NOTE: References in this file to Enterprise JavaBeans (EJB) refer to the Jakarta Enterprise Beans unless otherwise noted. */ public class Ejb3TransformersTestCase extends AbstractSubsystemBaseTest { private static final String LEGACY_EJB_CLIENT_ARTIFACT = "org.jboss:jboss-ejb-client:2.1.2.Final"; private static String formatWildflySubsystemArtifact(ModelTestControllerVersion version) { return formatArtifact("org.wildfly:wildfly-ejb3:%s", version); } private static String formatEAPSubsystemArtifact(ModelTestControllerVersion version) { return formatArtifact("org.jboss.eap:wildfly-ejb3:%s", version); } private static String formatLegacySubsystemArtifact(ModelTestControllerVersion version) { return formatArtifact("org.jboss.as:jboss-as-ejb3:%s", version); } private static String formatArtifact(String pattern, ModelTestControllerVersion version) { return String.format(pattern, version.getMavenGavVersion()); } public Ejb3TransformersTestCase() { super(EJB3Extension.SUBSYSTEM_NAME, new EJB3Extension()); } @Override protected String getSubsystemXml() throws IOException { return readResource("subsystem.xml"); } @Override protected String getSubsystemXsdPath() throws Exception { return "schema/wildfly-ejb3_10_0.xsd"; } /* * Add in required capabilities for external subsystem resources the ejb3 subsystem accesses */ @Override protected AdditionalInitialization createAdditionalInitialization() { return AdditionalInitialization.MANAGEMENT; } /** * Tests transformation of model from current version into specified version * The xml used should parse on legacy servers without rejections. * * @param model * @param controller * @param mavenResourceURLs * @throws Exception */ private void testTransformation(ModelVersion model, ModelTestControllerVersion controller, String... mavenResourceURLs) throws Exception { // create builder for current subsystem version KernelServicesBuilder builder = createKernelServicesBuilder(AdditionalInitialization.MANAGEMENT) .setSubsystemXmlResource("subsystem-ejb3-transform.xml"); // initialize the legacy services and add required jars builder.createLegacyKernelServicesBuilder(null, controller, model). addMavenResourceURL(mavenResourceURLs). skipReverseControllerCheck(); KernelServices services = builder.build(); KernelServices legacyServices = services.getLegacyServices(model); Assert.assertTrue(services.isSuccessfulBoot()); Assert.assertTrue(legacyServices.isSuccessfulBoot()); // check that both versions of the legacy model are the same and valid checkSubsystemModelTransformation(services, model, new DefaultModelFixer()); } protected AdditionalInitialization createAdditionalInitializationForRejectionTests() { return AdditionalInitialization.withCapabilities("org.wildfly.transactions.global-default-local-provider", buildDynamicCapabilityName("org.wildfly.security.security-domain", "ApplicationDomain"), buildDynamicCapabilityName("org.wildfly.remoting.connector", "http-remoting-connector"), buildDynamicCapabilityName("org.wildfly.remoting.connector", "remoting-connector"), buildDynamicCapabilityName("org.wildfly.clustering.infinispan.cache-container", "not-ejb"), buildDynamicCapabilityName("org.wildfly.ejb3.timer-service.timer-persistence-service", "file-data-store"), buildDynamicCapabilityName("org.wildfly.ejb3.mdb-delivery-group", "1"), buildDynamicCapabilityName("org.wildfly.ejb3.mdb-delivery-group", "2"), buildDynamicCapabilityName("org.wildfly.ejb3.mdb-delivery-group", "3"), buildDynamicCapabilityName("org.wildfly.ejb3.pool-config", "pool"), "org.wildfly.remoting.endpoint", "org.wildfly.security.jacc-policy"); } private void testRejections(ModelVersion model, ModelTestControllerVersion controller, String... mavenResourceURLs) throws Exception { // create builder for current subsystem version KernelServicesBuilder builder = createKernelServicesBuilder(this.createAdditionalInitializationForRejectionTests()); // initialize the legacy services and add required jars builder.createLegacyKernelServicesBuilder(this.createAdditionalInitializationForRejectionTests(), controller, model) .addMavenResourceURL(mavenResourceURLs) .dontPersistXml(); KernelServices services = builder.build(); Assert.assertTrue(services.isSuccessfulBoot()); KernelServices legacyServices = services.getLegacyServices(model); Assert.assertNotNull(legacyServices); Assert.assertTrue(legacyServices.isSuccessfulBoot()); List<ModelNode> operations = builder.parseXmlResource("subsystem-ejb3-transform-reject.xml"); ModelTestUtils.checkFailedTransformedBootOperations(services, model, operations, createFailedOperationTransformationConfig(services, model)); } private static FailedOperationTransformationConfig createFailedOperationTransformationConfig(KernelServices services, ModelVersion version) { FailedOperationTransformationConfig config = new FailedOperationTransformationConfig(); PathAddress subsystemAddress = PathAddress.pathAddress(EJB3Extension.SUBSYSTEM_PATH); // need to include all changes from current to 9.0.0 if (EJB3Model.VERSION_9_0_0.requiresTransformation(version)) { // reject the resource /subsystem=ejb3/simple-cache config.addFailedAttribute(subsystemAddress.append(EJB3SubsystemModel.SIMPLE_CACHE_PATH), FailedOperationTransformationConfig.REJECTED_RESOURCE); // reject the resource /subsystem=ejb3/distributable-cache config.addFailedAttribute(subsystemAddress.append(EJB3SubsystemModel.DISTRIBUTABLE_CACHE_PATH), FailedOperationTransformationConfig.REJECTED_RESOURCE); // Reject when default-data-store is undefined config.addFailedAttribute(subsystemAddress.append(EJB3SubsystemModel.TIMER_SERVICE_PATH), FailedOperationTransformationConfig.REJECTED_RESOURCE); } return config; } /* * Class to fix up some irredeemable errors in the legacy model before comparison */ private static class DefaultModelFixer implements ModelFixer { @Override public ModelNode fixModel(ModelNode modelNode) { // add any fixes required here return modelNode; } } }
8,189
46.616279
163
java
null
wildfly-main/ejb3/src/test/java/org/jboss/as/ejb3/subsystem/FilterSpecClassResolverFilterUnitTestCase.java
/* * Copyright (c) 2020. Red Hat, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.as.ejb3.subsystem; import static org.jboss.as.ejb3.subsystem.FilterSpecClassResolverFilter.DEFAULT_FILTER_SPEC; import java.util.Arrays; import java.util.HashSet; import java.util.Set; import org.junit.Assert; import org.junit.Test; public class FilterSpecClassResolverFilterUnitTestCase { private static final String[] DEFAULT_SPECS = DEFAULT_FILTER_SPEC.split(";"); @Test public void testBlockListSanity() { // It's fine to change this list if we change what we want. // This test is just a guard against unintended modification final String sanityFilterSpec = "!org.apache.commons.collections.functors.InvokerTransformer;" + "!org.apache.commons.collections.functors.InstantiateTransformer;" + "!org.apache.commons.collections4.functors.InvokerTransformer;" + "!org.apache.commons.collections4.functors.InstantiateTransformer;" + "!org.codehaus.groovy.runtime.ConvertedClosure;" + "!org.codehaus.groovy.runtime.MethodClosure;" + "!org.springframework.beans.factory.ObjectFactory;" + "!com.sun.org.apache.xalan.internal.xsltc.trax.TemplatesImpl;" + "!org.apache.xalan.xsltc.trax.TemplatesImpl"; Set<String> defaultSpec = new HashSet<>(Arrays.asList(DEFAULT_SPECS)); for (String spec : sanityFilterSpec.split(";")) { Assert.assertTrue(spec, defaultSpec.contains(spec)); } } @Test public void testDefaultBlocklist() { FilterSpecClassResolverFilter filter = new FilterSpecClassResolverFilter(); for (String spec : DEFAULT_SPECS) { boolean negate = spec.startsWith("!"); if (negate) { Assert.assertFalse(spec, filter.apply(spec.substring(1))); } else { Assert.assertTrue(spec, filter.apply(spec)); } } } @Test public void testDefaultBlocklistDisabled() { String currentFlag = System.getProperty("jboss.ejb.unmarshalling.filter.disabled"); try { System.setProperty("jboss.ejb.unmarshalling.filter.disabled", "true"); FilterSpecClassResolverFilter filter = new FilterSpecClassResolverFilter(); for (String spec : DEFAULT_SPECS) { spec = spec.startsWith("!") ? spec.substring(1) : spec; Assert.assertTrue(spec, filter.apply(spec)); } } finally { if (currentFlag == null) { System.clearProperty("jboss.ejb.unmarshalling.filter.disabled"); } else { System.setProperty("jboss.ejb.unmarshalling.filter.disabled", currentFlag); } } } @Test public void testBasicAllowlist() { FilterSpecClassResolverFilter filter = new FilterSpecClassResolverFilter("java.lang.String"); Assert.assertTrue(filter.apply("java.lang.String")); Assert.assertFalse(filter.apply("java.lang.Integer")); } @Test public void testAllowlistAllowsEjbClient() { FilterSpecClassResolverFilter filter = new FilterSpecClassResolverFilter("java.lang.String"); Assert.assertTrue(filter.apply("org.jboss.ejb.client.SessionId")); Assert.assertTrue(filter.apply("org.jboss.ejb.client.Foo")); Assert.assertFalse(filter.apply("org.jboss.ejb.client.foo.Bar")); } // It's fine to remove this test if the jboss.experimental.ejb.unmarshalling.filter.spec logic is removed @Test public void testExperimentalConfig() { String currentFlag = System.getProperty("jboss.experimental.ejb.unmarshalling.filter.spec"); try { System.setProperty("jboss.experimental.ejb.unmarshalling.filter.spec", "java.lang.String;java.lang.Boolean"); FilterSpecClassResolverFilter filter = new FilterSpecClassResolverFilter(); Assert.assertTrue(filter.apply("java.lang.String")); Assert.assertTrue(filter.apply("java.lang.Boolean")); Assert.assertFalse(filter.apply("java.lang.Integer")); } finally { if (currentFlag == null) { System.clearProperty("jboss.experimental.ejb.unmarshalling.filter.spec"); } else { System.setProperty("jboss.experimental.ejb.unmarshalling.filter.spec", currentFlag); } } } @Test public void testPackageAllowlist() { FilterSpecClassResolverFilter filter = new FilterSpecClassResolverFilter("foo.bar.*"); Assert.assertTrue(filter.apply("foo.bar.FooBar")); Assert.assertTrue(filter.apply("foo.bar.Baz")); Assert.assertFalse(filter.apply("foo.bar.baz.FooBar")); Assert.assertFalse(filter.apply("foo.barFly")); Assert.assertFalse(filter.apply("foo.baz.bar.FooBar")); } @Test public void testPackageBlocklist() { FilterSpecClassResolverFilter filter = new FilterSpecClassResolverFilter("!foo.bar.*"); Assert.assertFalse(filter.apply("foo.bar.FooBar")); Assert.assertFalse(filter.apply("foo.bar.Baz")); Assert.assertTrue(filter.apply("foo.bar.baz.FooBar")); Assert.assertTrue(filter.apply("foo.barFly")); Assert.assertTrue(filter.apply("foo.baz.bar.FooBar")); } @Test public void testPackageHierarchyAllowlist() { FilterSpecClassResolverFilter filter = new FilterSpecClassResolverFilter("foo.bar.**"); Assert.assertTrue(filter.apply("foo.bar.FooBar")); Assert.assertTrue(filter.apply("foo.bar.Baz")); Assert.assertTrue(filter.apply("foo.bar.baz.FooBar")); Assert.assertFalse(filter.apply("foo.barFly")); Assert.assertFalse(filter.apply("foo.baz.bar.FooBar")); } @Test public void testPackageHierarchyBlocklist() { FilterSpecClassResolverFilter filter = new FilterSpecClassResolverFilter("!foo.bar.**"); Assert.assertFalse(filter.apply("foo.bar.FooBar")); Assert.assertFalse(filter.apply("foo.bar.Baz")); Assert.assertFalse(filter.apply("foo.bar.baz.FooBar")); Assert.assertTrue(filter.apply("foo.barFly")); Assert.assertTrue(filter.apply("foo.baz.bar.FooBar")); } @Test public void testEndsWithAllowlist() { FilterSpecClassResolverFilter filter = new FilterSpecClassResolverFilter("foo.bar*"); Assert.assertTrue(filter.apply("foo.bar.FooBar")); Assert.assertTrue(filter.apply("foo.bar.Baz")); Assert.assertTrue(filter.apply("foo.bar.baz.FooBar")); Assert.assertTrue(filter.apply("foo.barFly")); Assert.assertFalse(filter.apply("foo.baz.bar.FooBar")); Assert.assertFalse(filter.apply("foo.bazFly")); } @Test public void testEndsWithBlocklist() { FilterSpecClassResolverFilter filter = new FilterSpecClassResolverFilter("!foo.bar*"); Assert.assertFalse(filter.apply("foo.bar.FooBar")); Assert.assertFalse(filter.apply("foo.bar.Baz")); Assert.assertFalse(filter.apply("foo.bar.baz.FooBar")); Assert.assertFalse(filter.apply("foo.barFly")); Assert.assertTrue(filter.apply("foo.baz.bar.FooBar")); Assert.assertTrue(filter.apply("foo.bazFly")); } @Test public void testGlobalAllowlist() { FilterSpecClassResolverFilter filter = new FilterSpecClassResolverFilter("*"); for (String spec : DEFAULT_SPECS) { spec = spec.startsWith("!") ? spec.substring(1) : spec; Assert.assertTrue(spec, filter.apply(spec)); } Assert.assertTrue(filter.apply("java.lang.String")); Assert.assertTrue(filter.apply("")); Assert.assertTrue(filter.apply("*")); // not really legal input but why not :) } @Test public void testEmptySpec() { FilterSpecClassResolverFilter filter = new FilterSpecClassResolverFilter(""); for (String spec : DEFAULT_SPECS) { spec = spec.startsWith("!") ? spec.substring(1) : spec; Assert.assertTrue(spec, filter.apply(spec)); } Assert.assertTrue(filter.apply("java.lang.String")); Assert.assertTrue(filter.apply("")); Assert.assertTrue(filter.apply("*")); // not really legal input but why not :) } @Test public void testGlobalBlocklist() { FilterSpecClassResolverFilter filter = new FilterSpecClassResolverFilter("!*"); for (String spec : DEFAULT_SPECS) { spec = spec.startsWith("!") ? spec.substring(1) : spec; Assert.assertFalse(spec, filter.apply(spec)); } Assert.assertFalse(filter.apply("java.lang.String")); Assert.assertFalse(filter.apply("")); Assert.assertFalse(filter.apply("*")); // not really legal input but why not :) } @Test public void testAllowlistExceptions() { exceptionTest("!foo.bar.Baz;foo.bar.*"); exceptionTest("foo.bar.*;!foo.bar.Baz"); exceptionTest("!foo.bar.Baz;foo.bar.**"); exceptionTest("foo.bar.**;!foo.bar.Baz"); exceptionTest("!foo.bar.Baz;foo.bar*"); exceptionTest("foo.bar*;!foo.bar.Baz"); exceptionTest("!foo.bar.Baz;foo.bar.FooBar"); exceptionTest("foo.bar.FooBar;!foo.bar.Baz"); // Negation overrules even exact allowlisting FilterSpecClassResolverFilter filter = new FilterSpecClassResolverFilter("!foo.bar.Baz;foo.bar.Baz"); Assert.assertFalse(filter.apply("foo.bar.Baz")); } private void exceptionTest(String filterSpec) { FilterSpecClassResolverFilter filter = new FilterSpecClassResolverFilter(filterSpec); Assert.assertFalse(filter.apply("foo.bar.Baz")); Assert.assertTrue(filter.apply("foo.bar.FooBar")); } @Test public void testNullInput() { FilterSpecClassResolverFilter filter = new FilterSpecClassResolverFilter(); try { filter.apply(null); Assert.fail("Null input accepted"); } catch (IllegalArgumentException good) { // good } } @Test public void testIllegalSpecs() { illegalSpecTest("foo.***"); illegalSpecTest("foo.*.**"); illegalSpecTest("foo.*.bar.**"); illegalSpecTest("foo.**.**"); illegalSpecTest("*foo.Bar"); illegalSpecTest("*foo.*"); illegalSpecTest("*foo.**"); illegalSpecTest("*foo*"); illegalSpecTest("foo.Bar;bar*.Baz"); illegalSpecTest("a=2"); illegalSpecTest("foo.*;a=2;bar.baz.**"); } private void illegalSpecTest(String spec) { try { new FilterSpecClassResolverFilter(spec); Assert.fail("Illegal spec should have been rejected: " + spec); } catch (IllegalArgumentException good) { // good } } }
11,508
40.699275
121
java
null
wildfly-main/ejb3/src/test/java/org/jboss/as/ejb3/subsystem/Ejb3SubsystemUnitTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2010, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ejb3.subsystem; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.io.IOException; import java.util.HashSet; import java.util.Set; import org.jboss.as.controller.PathAddress; import org.jboss.as.controller.operations.common.Util; import org.jboss.as.subsystem.test.AbstractSubsystemBaseTest; import org.jboss.as.subsystem.test.AdditionalInitialization; import org.jboss.as.subsystem.test.KernelServices; import org.jboss.dmr.ModelNode; import org.junit.Test; import org.wildfly.clustering.ejb.timer.TimerServiceRequirement; import org.wildfly.clustering.singleton.SingletonDefaultRequirement; /** * Test case for testing the integrity of the EJB3 subsystem. * * This checks the following features: * - basic subsystem testing (i.e. current model version boots successfully) * - registered transformers transform model and operations correctly between different API model versions * - expressions appearing in XML configurations are correctly rejected if so required * - bad attribute values are correctly rejected * * @author Emanuel Muckenhuber */ public class Ejb3SubsystemUnitTestCase extends AbstractSubsystemBaseTest { private static final AdditionalInitialization ADDITIONAL_INITIALIZATION = AdditionalInitialization.withCapabilities( TimerServiceRequirement.TIMER_MANAGEMENT_PROVIDER.resolve("transient"), TimerServiceRequirement.TIMER_MANAGEMENT_PROVIDER.resolve("persistent"), SingletonDefaultRequirement.POLICY.getName() ); public Ejb3SubsystemUnitTestCase() { super(EJB3Extension.SUBSYSTEM_NAME, new EJB3Extension()); } @Override protected AdditionalInitialization createAdditionalInitialization() { return ADDITIONAL_INITIALIZATION; } @Override protected Set<PathAddress> getIgnoredChildResourcesForRemovalTest() { Set<PathAddress> ignoredChildren = new HashSet<PathAddress>(); // ignoredChildren.add(PathAddress.pathAddress(PathElement.pathElement("subsystem", "ejb3"), PathElement.pathElement("passivation-store", "infinispan"))); return ignoredChildren; } @Override protected String getSubsystemXml() throws IOException { return readResource("subsystem.xml"); } @Override protected String getSubsystemXsdPath() throws Exception { return "schema/wildfly-ejb3_10_0.xsd"; } @Test public void test15() throws Exception { standardSubsystemTest("subsystem15.xml", false); } /** WFLY-7797 */ @Test public void testPoolSizeAlternatives() throws Exception { // Parse the subsystem xml and install into the first controller final String subsystemXml = getSubsystemXml(); final KernelServices ks = createKernelServicesBuilder(AdditionalInitialization.MANAGEMENT).setSubsystemXml(subsystemXml).build(); assertTrue("Subsystem boot failed!", ks.isSuccessfulBoot()); PathAddress pa = PathAddress.pathAddress("subsystem", "ejb3").append("strict-max-bean-instance-pool", "slsb-strict-max-pool"); ModelNode composite = Util.createEmptyOperation("composite", PathAddress.EMPTY_ADDRESS); ModelNode steps = composite.get("steps"); ModelNode writeMax = Util.getWriteAttributeOperation(pa, "max-pool-size", 5); ModelNode writeDerive = Util.getWriteAttributeOperation(pa, "derive-size", "none"); steps.add(writeMax); steps.add(writeDerive); // none works in combo with max-pool-size ModelNode response = ks.executeOperation(composite); assertEquals(response.toString(), "success", response.get("outcome").asString()); validatePoolConfig(ks, pa); steps.setEmptyList(); // Other values fail in combo with max-pool-size writeMax.get("value").set(10); writeDerive.get("value").set("from-cpu-count"); steps.add(writeMax); steps.add(writeDerive); ks.executeForFailure(composite); validatePoolConfig(ks, pa); } @Test public void testDefaultPools() throws Exception { final String subsystemXml = readResource("subsystem-pools.xml"); final KernelServices ks = createKernelServicesBuilder(AdditionalInitialization.MANAGEMENT).setSubsystemXml(subsystemXml).build(); assertTrue("Subsystem boot failed!", ks.isSuccessfulBoot()); // add a test pool String testPoolName = "test-pool"; final PathAddress ejb3Address = PathAddress.pathAddress("subsystem", "ejb3"); PathAddress testPoolAddress = ejb3Address.append("strict-max-bean-instance-pool", testPoolName); final ModelNode addPool = Util.createAddOperation(testPoolAddress); ModelNode response = ks.executeOperation(addPool); assertEquals(response.toString(), "success", response.get("outcome").asString()); // set default-mdb-instance-pool writeAndReadPool(ks, ejb3Address, "default-mdb-instance-pool", testPoolName); writeAndReadPool(ks, ejb3Address, "default-mdb-instance-pool", null); writeAndReadPool(ks, ejb3Address, "default-mdb-instance-pool", null); writeAndReadPool(ks, ejb3Address, "default-mdb-instance-pool", "mdb-strict-max-pool"); // set default-slsb-instance-pool writeAndReadPool(ks, ejb3Address, "default-slsb-instance-pool", null); writeAndReadPool(ks, ejb3Address, "default-slsb-instance-pool", null); writeAndReadPool(ks, ejb3Address, "default-slsb-instance-pool", testPoolName); writeAndReadPool(ks, ejb3Address, "default-slsb-instance-pool", testPoolName); writeAndReadPool(ks, ejb3Address, "default-slsb-instance-pool", "slsb-strict-max-pool"); final ModelNode removePool = Util.createRemoveOperation(testPoolAddress); response = ks.executeOperation(removePool); assertEquals(response.toString(), "success", response.get("outcome").asString()); } /** * Verifies that attributes with expression are handled properly. * @throws Exception for any test failures */ @Test public void testExpressionInAttributeValue() throws Exception { final String subsystemXml = readResource("with-expression-subsystem.xml"); final KernelServices ks = createKernelServicesBuilder(createAdditionalInitialization()).setSubsystemXml(subsystemXml).build(); final ModelNode ejb3 = ks.readWholeModel().get("subsystem", getMainSubsystemName()); final String statisticsEnabled = ejb3.get("statistics-enabled").resolve().asString(); assertEquals("true", statisticsEnabled); final String logSystemException = ejb3.get("log-system-exceptions").resolve().asString(); assertEquals("false", logSystemException); final String passByValue = ejb3.get("in-vm-remote-interface-invocation-pass-by-value").resolve().asString(); assertEquals("false", passByValue); final String gracefulTxn = ejb3.get("enable-graceful-txn-shutdown").resolve().asString(); assertEquals("false", gracefulTxn); final String disableDefaultEjbPermission = ejb3.get("disable-default-ejb-permissions").resolve().asString(); assertEquals("false", disableDefaultEjbPermission); final int defaultStatefulSessionTimeout = ejb3.get("default-stateful-bean-session-timeout").resolve().asInt(); assertEquals(600000, defaultStatefulSessionTimeout); final int defaultStatefulAccessTimeout = ejb3.get("default-stateful-bean-access-timeout").resolve().asInt(); assertEquals(5000, defaultStatefulAccessTimeout); final String defaultSlsbInstancePool = ejb3.get("default-slsb-instance-pool").resolve().asString(); assertEquals("slsb-strict-max-pool", defaultSlsbInstancePool); final int defaultSingletonAccessTimeout = ejb3.get("default-singleton-bean-access-timeout").resolve().asInt(); assertEquals(5000, defaultSingletonAccessTimeout); final String defaultSfsbPassivationDisabledCache = ejb3.get("default-sfsb-passivation-disabled-cache").resolve().asString(); assertEquals("simple", defaultSfsbPassivationDisabledCache); final String defaultSfsbCache = ejb3.get("default-sfsb-cache").resolve().asString(); assertEquals("distributable", defaultSfsbCache); final String defaultSecurityDomain = ejb3.get("default-security-domain").resolve().asString(); assertEquals("domain", defaultSecurityDomain); final String defaultResourceAdapterName = ejb3.get("default-resource-adapter-name").resolve().asString(); assertEquals("activemq-ra.rar", defaultResourceAdapterName); final String defaultMissingMethodPermissionDenyAccess = ejb3.get("default-missing-method-permissions-deny-access").resolve().asString(); assertEquals("false", defaultMissingMethodPermissionDenyAccess); final String defaultMdbInstancePool = ejb3.get("default-mdb-instance-pool").resolve().asString(); assertEquals("mdb-strict-max-pool", defaultMdbInstancePool); final String defaultEntityBeanOptimisticLocking = ejb3.get("default-entity-bean-optimistic-locking").resolve().asString(); assertEquals("true", defaultEntityBeanOptimisticLocking); final String defaultEntityBeanInstancePool = ejb3.get("default-entity-bean-instance-pool").resolve().asString(); assertEquals("entity-strict-max-pool", defaultEntityBeanInstancePool); final String defaultDistinctName = ejb3.get("default-distinct-name").resolve().asString(); assertEquals("myname", defaultDistinctName); final String allowEjbNameRegex = ejb3.get("allow-ejb-name-regex").resolve().asString(); assertEquals("false", allowEjbNameRegex); final String cachePassivationStore = ejb3.get("cache").asPropertyList().get(1).getValue().get("passivation-store").resolve().asString(); assertEquals("infinispan", cachePassivationStore); final String mdbDeliveryGroupActive = ejb3.get("mdb-delivery-group").asPropertyList().get(1).getValue().get("active").resolve().asString(); assertEquals("false", mdbDeliveryGroupActive); final ModelNode passivationStore = ejb3.get("passivation-store").asPropertyList().get(0).getValue(); assertEquals("default", passivationStore.get("bean-cache").asString()); assertEquals("ejb", passivationStore.get("cache-container").asString()); assertEquals(10, passivationStore.get("max-size").resolve().asInt()); final ModelNode remotingProfile = ejb3.get("remoting-profile").asPropertyList().get(0).getValue(); assertEquals("true", remotingProfile.get("exclude-local-receiver").resolve().asString()); assertEquals("true", remotingProfile.get("local-receiver-pass-by-value").resolve().asString()); final ModelNode remoteHttpConnection = remotingProfile.get("remote-http-connection").asPropertyList().get(0).getValue(); assertEquals("http://localhost:8180/wildfly-services", remoteHttpConnection.get("uri").resolve().asString()); final ModelNode remotingEjbReceiver = remotingProfile.get("remoting-ejb-receiver").asPropertyList().get(0).getValue(); assertEquals(5000, remotingEjbReceiver.get("connect-timeout").resolve().asInt()); assertEquals("connection-ref", remotingEjbReceiver.get("outbound-connection-ref").resolve().asString()); final ModelNode channelCreationOption = remotingEjbReceiver.get("channel-creation-options").asPropertyList().get(0).getValue(); assertEquals(20, channelCreationOption.get("value").resolve().asInt()); final String asyncThreadPoolName = ejb3.get("service", "async", "thread-pool-name").resolve().asString(); assertEquals("default", asyncThreadPoolName); final String iiopEnableByDefault = ejb3.get("service", "iiop", "enable-by-default").resolve().asString(); assertEquals("true", iiopEnableByDefault); final String useQualifiedName = ejb3.get("service", "iiop", "use-qualified-name").resolve().asString(); assertEquals("true", useQualifiedName); final ModelNode remote = ejb3.get("service", "remote"); assertEquals("ejb", remote.get("cluster").asString()); assertEquals("false", remote.get("execute-in-worker").resolve().asString()); assertEquals("default", remote.get("thread-pool-name").resolve().asString()); assertEquals(20, remote.get("channel-creation-options").asPropertyList().get(0).getValue().get("value").resolve().asInt()); final ModelNode timerService = ejb3.get("service", "timer-service"); final String fileDataStorePath = timerService.get("file-data-store").asPropertyList().get(0).getValue().get("path").resolve().asString(); assertEquals("timer-service-data", fileDataStorePath); final ModelNode databaseStore = timerService.get("database-data-store").asPropertyList().get(0).getValue(); assertEquals("java:global/DataSource", databaseStore.get("datasource-jndi-name").resolve().asString()); assertEquals("hsql", databaseStore.get("database").resolve().asString()); assertEquals("mypartition", databaseStore.get("partition").resolve().asString()); assertEquals("true", databaseStore.get("allow-execution").resolve().asString()); assertEquals("100", databaseStore.get("refresh-interval").resolve().asString()); final ModelNode strictMaxBeanInstancePool = ejb3.get("strict-max-bean-instance-pool").asPropertyList().get(0).getValue(); assertEquals("from-cpu-count", strictMaxBeanInstancePool.get("derive-size").resolve().asString()); assertEquals(5, strictMaxBeanInstancePool.get("timeout").resolve().asInt()); assertEquals("MINUTES", strictMaxBeanInstancePool.get("timeout-unit").resolve().asString()); final ModelNode strictMaxBeanInstancePool2 = ejb3.get("strict-max-bean-instance-pool").asPropertyList().get(1).getValue(); assertEquals(20, strictMaxBeanInstancePool2.get("max-pool-size").resolve().asInt()); final ModelNode threadPool = ejb3.get("thread-pool").asPropertyList().get(0).getValue(); assertEquals(10, threadPool.get("max-threads").resolve().asInt()); assertEquals(10, threadPool.get("core-threads").resolve().asInt()); } private void writeAndReadPool(KernelServices ks, PathAddress ejb3Address, String attributeName, String testPoolName) { ModelNode writeAttributeOperation = testPoolName == null ? Util.getUndefineAttributeOperation(ejb3Address, attributeName) : Util.getWriteAttributeOperation(ejb3Address, attributeName, testPoolName); ModelNode response = ks.executeOperation(writeAttributeOperation); assertEquals(response.toString(), "success", response.get("outcome").asString()); final String expectedPoolName = testPoolName == null ? "undefined" : testPoolName; final ModelNode readAttributeOperation = Util.getReadAttributeOperation(ejb3Address, attributeName); response = ks.executeOperation(readAttributeOperation); final String poolName = response.get("result").asString(); assertEquals("Unexpected pool name", expectedPoolName, poolName); } private void validatePoolConfig(KernelServices ks, PathAddress pa) { ModelNode ra = Util.createEmptyOperation("read-attribute", pa); ra.get("name").set("max-pool-size"); ModelNode response = ks.executeOperation(ra); assertEquals(response.toString(), 5, response.get("result").asInt()); ra.get("name").set("derive-size"); response = ks.executeOperation(ra); assertFalse(response.toString(), response.hasDefined("result")); } }
16,864
51.538941
161
java
null
wildfly-main/ejb3/src/test/java/org/jboss/as/ejb3/util/TaintedBean.java
/* * JBoss, Home of Professional Open Source. * Copyright 2023, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ejb3.util; public class TaintedBean extends TaintedBase { @SuppressWarnings("unused") public int cleanMethod1() { return 1; } }
1,194
37.548387
70
java
null
wildfly-main/ejb3/src/test/java/org/jboss/as/ejb3/util/CleanBean.java
/* * JBoss, Home of Professional Open Source. * Copyright (c) 2023, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ejb3.util; public class CleanBean implements BusinessInterface { @SuppressWarnings("unused") @Override public void businessMethod(String argumentOne, int argumentTwo) { } @SuppressWarnings("unused") @Override public void businessMethod(String argumentOne, int argumentTwo, boolean argumentThree) { } @SuppressWarnings("unused") public void notABusinessMethod(String argumentOne) { } @SuppressWarnings("unused") protected static void protectedStatic() { } @SuppressWarnings("unused") protected final void protectedFinal() { } @SuppressWarnings("unused") static void packageStatic() { } @SuppressWarnings("unused") final void packageFinal() { } }
1,793
31.035714
92
java
null
wildfly-main/ejb3/src/test/java/org/jboss/as/ejb3/util/EjbWithStaticMethod.java
/* * JBoss, Home of Professional Open Source. * Copyright (c) 2023, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ejb3.util; public class EjbWithStaticMethod { public static void method() { } }
1,140
35.806452
70
java
null
wildfly-main/ejb3/src/test/java/org/jboss/as/ejb3/util/TaintedBase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2023, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ejb3.util; public abstract class TaintedBase { @SuppressWarnings("unused") public static void publicStatic() { } @SuppressWarnings("unused") public final void publicFinal() { } }
1,250
35.794118
70
java
null
wildfly-main/ejb3/src/test/java/org/jboss/as/ejb3/util/InvalidMdbOnMessageCantBeFinal.java
/* * JBoss, Home of Professional Open Source. * Copyright 2018, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ejb3.util; /** * * @author <a href="mailto:[email protected]">Romain Pelisse</a> */ public class InvalidMdbOnMessageCantBeFinal { public final void onMessage() { }; }
1,224
36.121212
70
java
null
wildfly-main/ejb3/src/test/java/org/jboss/as/ejb3/util/InvalidMdbWithFinalizeMethod.java
/* * JBoss, Home of Professional Open Source. * Copyright 2018, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ejb3.util; /** * * @author <a href="mailto:[email protected]">Romain Pelisse</a> */ public class InvalidMdbWithFinalizeMethod { @SuppressWarnings("deprecation") protected void finalize() { } }
1,254
35.911765
70
java
null
wildfly-main/ejb3/src/test/java/org/jboss/as/ejb3/util/InvalidMdbOnMessageCantBeStatic.java
/* * JBoss, Home of Professional Open Source. * Copyright 2018, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ejb3.util; public class InvalidMdbOnMessageCantBeStatic { public static void onMessage() { } }
1,150
37.366667
70
java
null
wildfly-main/ejb3/src/test/java/org/jboss/as/ejb3/util/InvalidMdbOnMessageCantBePrivate.java
/* * JBoss, Home of Professional Open Source. * Copyright 2018, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ejb3.util; /** * * @author <a href="mailto:[email protected]">Romain Pelisse</a> */ public class InvalidMdbOnMessageCantBePrivate { private void onMessage() { }; }
1,221
36.030303
70
java
null
wildfly-main/ejb3/src/test/java/org/jboss/as/ejb3/util/EjbValidationsUtilTest.java
/* * JBoss, Home of Professional Open Source. * Copyright 2018, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ejb3.util; import static org.jboss.as.ejb3.util.EjbValidationsUtil.assertEjbClassValidity; import static org.jboss.as.ejb3.util.EjbValidationsUtil.verifyEjbPublicMethodAreNotFinalNorStatic; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.io.IOException; import java.io.InputStream; import org.jboss.jandex.ClassInfo; import org.jboss.jandex.DotName; import org.jboss.jandex.Index; import org.jboss.jandex.Indexer; import org.junit.Test; /** * Unit test for Mdb validation logic - see Jakarta Enterprise Beans 3.2 specification section 5.6.2 and 5.6.4 for more information * * @author <a href="mailto:[email protected]">Romain Pelisse</a> */ public class EjbValidationsUtilTest { @Test public void mdbWithFinalClass() { assertTrue(assertEjbClassValidity(buildClassInfoForClass(InvalidMdbFinalClass.class.getName())).contains( MdbValidityStatus.MDB_CLASS_CANNOT_BE_PRIVATE_ABSTRACT_OR_FINAL)); } @Test public void mdbWithInterface() { assertTrue(assertEjbClassValidity(buildClassInfoForClass(InvalidMdbInterface.class.getName())).contains( MdbValidityStatus.MDB_CANNOT_BE_AN_INTERFACE)); } @Test public void mdbWithFinalOnMessageMethod() { assertTrue(assertEjbClassValidity(buildClassInfoForClass(InvalidMdbOnMessageCantBeFinal.class.getName())).contains( MdbValidityStatus.MDB_ON_MESSAGE_METHOD_CANT_BE_FINAL)); } @Test public void mdbWithStaticOnMessageMethod() { assertTrue(assertEjbClassValidity(buildClassInfoForClass(InvalidMdbOnMessageCantBeStatic.class.getName())).contains( MdbValidityStatus.MDB_ON_MESSAGE_METHOD_CANT_BE_STATIC)); } @Test public void mdbWithPrivateOnMessageMethod() { assertTrue(assertEjbClassValidity(buildClassInfoForClass(InvalidMdbOnMessageCantBePrivate.class.getName())).contains( MdbValidityStatus.MDB_ON_MESSAGE_METHOD_CANT_BE_PRIVATE)); } @Test public void mdbWithFinalizeMethod() { assertTrue(assertEjbClassValidity(buildClassInfoForClass(InvalidMdbWithFinalizeMethod.class.getName())).contains( MdbValidityStatus.MDB_SHOULD_NOT_HAVE_FINALIZE_METHOD)); } @Test public void ejbWithFinalOrStaticMethods() { assertTrue(assertEjbClassValidity(buildClassInfoForClass(EjbWithPrivateFinalMethod.class.getName())).isEmpty()); assertTrue(verifyEjbPublicMethodAreNotFinalNorStatic(EjbWithPrivateFinalMethod.class.getMethods(), EjbWithPrivateFinalMethod.class.getName())); // EjbWithStaticMethod and EjbWithFinalMethod should produce false validation result assertFalse(verifyEjbPublicMethodAreNotFinalNorStatic(EjbWithStaticMethod.class.getMethods(), EjbWithStaticMethod.class.getName())); assertFalse(verifyEjbPublicMethodAreNotFinalNorStatic(EjbWithFinalMethod.class.getMethods(), EjbWithFinalMethod.class.getName())); // CleanBean contains some non-public final or static methods along with regular business methods, // and should not cause validation warning assertTrue(verifyEjbPublicMethodAreNotFinalNorStatic(CleanBean.class.getMethods(), CleanBean.class.getName())); // TaintedBean inherits public static and final methods from its super class, so produce false validation result assertFalse(verifyEjbPublicMethodAreNotFinalNorStatic(TaintedBean.class.getMethods(), TaintedBean.class.getName())); } private ClassInfo buildClassInfoForClass(String mdbClassName) { String mdbClassNameAsResource = mdbClassName.replaceAll("\\.", "/").concat(".class"); Index index = indexStream(getClass().getClassLoader().getResourceAsStream(mdbClassNameAsResource)).complete(); return index.getClassByName(DotName.createSimple(mdbClassName)); } private Indexer indexStream(InputStream stream) { try { Indexer indexer = new Indexer(); indexer.index(stream); stream.close(); return indexer; } catch (IOException e) { throw new IllegalStateException(e); } } }
5,219
44
151
java
null
wildfly-main/ejb3/src/test/java/org/jboss/as/ejb3/util/InvalidMdbInterface.java
/* * JBoss, Home of Professional Open Source. * Copyright 2018, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ejb3.util; /** * * @author <a href="mailto:[email protected]">Romain Pelisse</a> */ public interface InvalidMdbInterface { void aMethod(); }
1,195
35.242424
70
java
null
wildfly-main/ejb3/src/test/java/org/jboss/as/ejb3/util/EjbWithFinalMethod.java
/* * JBoss, Home of Professional Open Source. * Copyright (c) 2023, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ejb3.util; public class EjbWithFinalMethod { public final void method() { } }
1,138
35.741935
70
java
null
wildfly-main/ejb3/src/test/java/org/jboss/as/ejb3/util/InvalidMdbFinalClass.java
/* * JBoss, Home of Professional Open Source. * Copyright 2018, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ejb3.util; /** * * @author <a href="mailto:[email protected]">Romain Pelisse</a> */ public final class InvalidMdbFinalClass { public void aRegularMethod() { }; }
1,220
34.911765
70
java
null
wildfly-main/ejb3/src/test/java/org/jboss/as/ejb3/util/EjbWithPrivateFinalMethod.java
/* * JBoss, Home of Professional Open Source. * Copyright (c) 2023, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ejb3.util; public class EjbWithPrivateFinalMethod { private final void privateFinalMethodIsOk() { } private static void privateStaticFinalMehtodIsAlsoOK() { } public void method() { this.privateFinalMethodIsOk(); EjbWithPrivateFinalMethod.privateStaticFinalMehtodIsAlsoOK(); } }
1,374
33.375
70
java
null
wildfly-main/ejb3/src/test/java/org/jboss/as/ejb3/util/BusinessInterface.java
/* * JBoss, Home of Professional Open Source. * Copyright (c) 2023, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ejb3.util; public interface BusinessInterface { void businessMethod(String argumentOne, int argumentTwo); void businessMethod(String argumentOne, int argumentTwo, boolean argumentThree); }
1,249
39.322581
84
java
null
wildfly-main/ejb3/src/test/java/org/jboss/as/ejb3/concurrency/EJBReadWriteLockTest.java
/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ejb3.concurrency; import org.jboss.as.ejb3.component.singleton.EJBReadWriteLock; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import jakarta.ejb.ConcurrentAccessTimeoutException; import jakarta.ejb.IllegalLoopbackException; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.Lock; /** * Tests the {@link EJBReadWriteLock} * * @author Jaikiran Pai * @version $Revision: $ */ public class EJBReadWriteLockTest { /** * Used in tests */ private EJBReadWriteLock ejbReadWriteLock; @Before public void beforeTest() { this.ejbReadWriteLock = new EJBReadWriteLock(); } @After public void afterTest() { this.ejbReadWriteLock = null; } /** * Test that a {@link jakarta.ejb.IllegalLoopbackException} is thrown when the thread owning a read lock * tries to obtain a write lock * * @throws Exception */ @Test public void testIllegalLoopBack() throws Exception { // get a read lock Lock readLock = this.ejbReadWriteLock.readLock(); // lock it! readLock.lock(); // now get a write lock and try to lock it (should fail with IllegalLoopBack) Lock writeLock = this.ejbReadWriteLock.writeLock(); try { writeLock.lock(); // unlock the (unexpected obtained lock) and then fail the testcase writeLock.unlock(); Assert.fail("Unexpected acquired write lock"); } catch (IllegalLoopbackException ilbe) { // expected } finally { // unlock the write lock readLock.unlock(); } } /** * Test that when a thread tries to obtain a read lock when another thread holds a write lock, * fails to acquire the lock, if the write lock is not released within the timeout specified * * @throws Exception */ @Test public void testTimeout() throws Exception { // we use a countdown latch for the 2 threads involved CountDownLatch latch = new CountDownLatch(2); // get a write lock Lock writeLock = this.ejbReadWriteLock.writeLock(); // create a thread which will get hold of a write lock // and do some processing for 5 seconds Thread threadHoldingWriteLock = new Thread(new ThreadHoldingWriteLock(latch, writeLock, 5000)); // get a read lock Lock readLock = this.ejbReadWriteLock.readLock(); // start the write lock thread (which internally will obtain // a write lock and start a 5 second processing) threadHoldingWriteLock.start(); // wait for few milli sec for the write lock thread to obtain a write lock Thread.sleep(500); // now try and get a read lock, *shouldn't* be able to obtain the lock // before the 2 second timeout try { // try a read lock with 2 second timeout boolean readLockAcquired = readLock.tryLock(2, TimeUnit.SECONDS); Assert.assertFalse("Unexpected obtained a read lock", readLockAcquired); } catch (ConcurrentAccessTimeoutException cate) { // expected } finally { // let the latch know that this thread is done with its part // of processing latch.countDown(); // now let's wait for the other thread to complete processing // and bringing down the count on the latch latch.await(); } } /** * Tests that a thread can first get a write lock and at a later point in time, get * a read lock * * @throws Exception */ @Test public void testSameThreadCanGetWriteThenReadLock() throws Exception { Lock writeLock = this.ejbReadWriteLock.writeLock(); // lock it! writeLock.lock(); Lock readLock = this.ejbReadWriteLock.readLock(); // lock it! (should work, because we are going from a write to read and *not* // the other way round) try { boolean readLockAcquired = readLock.tryLock(2, TimeUnit.SECONDS); // unlock the read lock, because we don't need it anymore if (readLockAcquired) { readLock.unlock(); } Assert.assertTrue("Could not obtain read lock when write lock was held by the same thread!", readLockAcquired); } finally { // unlock our write lock writeLock.unlock(); } } /** * An implementation of {@link Runnable} which in its {@link #run()} method * will first obtain a lock and then will go to sleep for the specified amount * of time. After processing, it will unlock the {@link java.util.concurrent.locks.Lock} * * @author Jaikiran Pai * @version $Revision: $ */ private class ThreadHoldingWriteLock implements Runnable { /** * Lock */ private Lock lock; /** * The amount of time, in milliseconds, this {@link ThreadHoldingWriteLock} * will sleep for in its {@link #run()} method */ private long processingTime; /** * A latch for notifying any waiting threads */ private CountDownLatch latch; /** * Creates a {@link ThreadHoldingWriteLock} * * @param latch A latch for notifying any waiting threads * @param lock A lock that will be used for obtaining a lock during processing * @param processingTime The amount of time in milliseconds, this thread will sleep (a.k.a process) * in its {@link #run()} method */ public ThreadHoldingWriteLock(CountDownLatch latch, Lock lock, long processingTime) { this.lock = lock; this.processingTime = processingTime; this.latch = latch; } /** * Obtains a lock, sleeps for {@link #processingTime} milliseconds and then unlocks the lock * * @see Runnable#run() */ @Override public void run() { // lock it! this.lock.lock(); // process(sleep) for the specified time try { Thread.sleep(this.processingTime); } catch (InterruptedException e) { // ignore } finally { // unlock this.lock.unlock(); // let any waiting threads know that we are done processing this.latch.countDown(); } } } }
7,739
32.652174
123
java
null
wildfly-main/ejb3/src/test/java/org/jboss/as/ejb3/pool/common/MockBean.java
/* * JBoss, Home of Professional Open Source. * Copyright (c) 2011, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ejb3.pool.common; import java.util.concurrent.atomic.AtomicInteger; import org.jboss.logging.Logger; /** * Comment * * @author <a href="mailto:[email protected]">Carlo de Wolf</a> */ public class MockBean { private static final Logger log = Logger.getLogger(MockBean.class); static final AtomicInteger finalized = new AtomicInteger(0); static final AtomicInteger preDestroys = new AtomicInteger(0); static final AtomicInteger postConstructs= new AtomicInteger(0); @Override protected void finalize() throws Throwable { log.info("finalize"); finalized.incrementAndGet(); super.finalize(); } public static int getFinalized() { return finalized.get(); } public static int getPreDestroys() { return preDestroys.get(); } public static int getPostConstructs() { return postConstructs.get(); } public void postConstruct() { log.info("postConstruct"); postConstructs.incrementAndGet(); } public void preDestroy() { log.info("preDestroy"); preDestroys.incrementAndGet(); } public static void reset() { finalized.set(0); preDestroys.set(0); postConstructs.set(0); } }
2,307
29.368421
71
java
null
wildfly-main/ejb3/src/test/java/org/jboss/as/ejb3/pool/common/MockFactory.java
/* * JBoss, Home of Professional Open Source. * Copyright (c) 2011, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ejb3.pool.common; import org.jboss.as.ejb3.pool.StatelessObjectFactory; /** * Comment * * @author <a href="mailto:[email protected]">Carlo de Wolf</a> * @version $Revision: $ */ public class MockFactory implements StatelessObjectFactory<MockBean> { public MockBean create() { MockBean bean = new MockBean(); bean.postConstruct(); return bean; } public void destroy(MockBean obj) { obj.preDestroy(); } }
1,513
33.409091
70
java
null
wildfly-main/ejb3/src/test/java/org/jboss/as/ejb3/pool/strictmax/StrictMaxUnitTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2007, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ejb3.pool.strictmax; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import java.util.concurrent.Callable; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import org.jboss.as.ejb3.logging.EjbLogger; import org.jboss.as.ejb3.pool.Pool; import org.jboss.as.ejb3.pool.StatelessObjectFactory; import org.jboss.as.ejb3.pool.common.MockBean; import org.jboss.as.ejb3.pool.common.MockFactory; import org.junit.Test; /** * Comment * * @author <a href="mailto:[email protected]">Carlo de Wolf</a> * @version $Revision: $ */ public class StrictMaxUnitTestCase { AtomicInteger used = new AtomicInteger(0); protected void setUp() throws Exception { MockBean.reset(); used = new AtomicInteger(0); } @Test public void test1() { MockBean.reset(); StatelessObjectFactory<MockBean> factory = new MockFactory(); Pool<MockBean> pool = new StrictMaxPool<MockBean>(factory, 10, 1, TimeUnit.SECONDS); pool.start(); MockBean[] beans = new MockBean[10]; for (int i = 0; i < beans.length; i++) { beans[i] = pool.get(); } for (int i = 0; i < beans.length; i++) { pool.release(beans[i]); beans[i] = null; } pool.stop(); assertEquals(10, MockBean.getPostConstructs()); assertEquals(10, MockBean.getPreDestroys()); } /** * More threads than the pool size. */ @Test public void testMultiThread() throws Exception { MockBean.reset(); StatelessObjectFactory<MockBean> factory = new MockFactory(); final Pool<MockBean> pool = new StrictMaxPool<MockBean>(factory, 10, 60, TimeUnit.SECONDS); pool.start(); final CountDownLatch in = new CountDownLatch(1); final CountDownLatch ready = new CountDownLatch(10); Callable<Void> task = new Callable<Void>() { public Void call() throws Exception { MockBean bean = pool.get(); ready.countDown(); in.await(); pool.release(bean); bean = null; used.incrementAndGet(); return null; } }; ExecutorService service = Executors.newFixedThreadPool(20); Future<?>[] results = new Future<?>[20]; for (int i = 0; i < results.length; i++) { results[i] = service.submit(task); } ready.await(120, TimeUnit.SECONDS); in.countDown(); for (Future<?> result : results) { result.get(5, TimeUnit.SECONDS); } service.shutdown(); pool.stop(); assertEquals(20, used.intValue()); assertEquals(10, MockBean.getPostConstructs()); assertEquals(10, MockBean.getPreDestroys()); } @Test public void testTooMany() { MockBean.reset(); StatelessObjectFactory<MockBean> factory = new MockFactory(); Pool<MockBean> pool = new StrictMaxPool<MockBean>(factory, 10, 1, TimeUnit.SECONDS); pool.start(); MockBean[] beans = new MockBean[10]; for (int i = 0; i < beans.length; i++) { beans[i] = pool.get(); } try { pool.get(); fail("should have thrown an exception"); } catch (Exception e) { assertEquals(EjbLogger.ROOT_LOGGER.failedToAcquirePermit(1, TimeUnit.SECONDS).getMessage(), e.getMessage()); } for (int i = 0; i < beans.length; i++) { pool.release(beans[i]); beans[i] = null; } pool.stop(); assertEquals(10, MockBean.getPostConstructs()); assertEquals(10, MockBean.getPreDestroys()); } }
5,022
30.198758
120
java
null
wildfly-main/ejb3/src/test/java/org/jboss/as/ejb3/component/stateful/StatefulSessionSynchronizationInterceptorTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright (c) 2011, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ejb3.component.stateful; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import java.util.Arrays; import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.concurrent.TimeUnit; import java.util.function.Supplier; import jakarta.transaction.Status; import jakarta.transaction.Synchronization; import jakarta.transaction.TransactionSynchronizationRegistry; import org.jboss.as.ee.component.Component; import org.jboss.as.ee.component.ComponentInstance; import org.jboss.as.ejb3.component.stateful.cache.StatefulSessionBean; import org.jboss.as.ejb3.component.stateful.cache.StatefulSessionBeanCache; import org.jboss.as.ejb3.concurrency.AccessTimeoutDetails; import org.jboss.ejb.client.SessionID; import org.jboss.invocation.Interceptor; import org.jboss.invocation.InterceptorContext; import org.junit.Test; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; /** * @author <a href="mailto:[email protected]">Carlo de Wolf</a> */ public class StatefulSessionSynchronizationInterceptorTestCase { private static AccessTimeoutDetails defaultAccessTimeout() { return new AccessTimeoutDetails(5, TimeUnit.MINUTES); } private static Interceptor noop() { return new Interceptor() { @Override public Object processInvocation(InterceptorContext context) throws Exception { return null; } }; } /** * After the bean is accessed within a tx and the tx has committed, the * association should be gone (and thus it is ready for another tx). */ @Test public void testDifferentTx() throws Exception { final Interceptor interceptor = new StatefulSessionSynchronizationInterceptor(true); final InterceptorContext context = new InterceptorContext(); context.setInterceptors(Arrays.asList(noop())); final StatefulSessionComponent component = mock(StatefulSessionComponent.class); context.putPrivateData(Component.class, component); when(component.getAccessTimeout(null)).thenReturn(defaultAccessTimeout()); StatefulSessionBeanCache<SessionID, StatefulSessionComponentInstance> cache = mock(StatefulSessionBeanCache.class); when(component.getCache()).thenReturn(cache); Supplier<SessionID> identifierFactory = mock(Supplier.class); when(cache.getIdentifierFactory()).thenReturn(identifierFactory); final TransactionSynchronizationRegistry transactionSynchronizationRegistry = mock(TransactionSynchronizationRegistry.class); when(component.getTransactionSynchronizationRegistry()).thenReturn(transactionSynchronizationRegistry); when(transactionSynchronizationRegistry.getTransactionKey()).thenReturn("TX1"); final List<Synchronization> synchronizations = new LinkedList<Synchronization>(); doAnswer(new Answer<Void>() { @Override public Void answer(InvocationOnMock invocation) throws Throwable { Synchronization synchronization = (Synchronization) invocation.getArguments()[0]; synchronizations.add(synchronization); return null; } }).when(transactionSynchronizationRegistry).registerInterposedSynchronization((Synchronization) any()); final StatefulSessionComponentInstance instance = new StatefulSessionComponentInstance(component, org.jboss.invocation.Interceptors.getTerminalInterceptor(), Collections.EMPTY_MAP, Collections.emptyMap()); context.putPrivateData(ComponentInstance.class, instance); StatefulSessionBean<SessionID, StatefulSessionComponentInstance> bean = mock(StatefulSessionBean.class); when(bean.getInstance()).thenReturn(instance); context.putPrivateData(StatefulSessionBean.class, bean); interceptor.processInvocation(context); // commit for (Synchronization synchronization : synchronizations) { synchronization.beforeCompletion(); } for (Synchronization synchronization : synchronizations) { synchronization.afterCompletion(Status.STATUS_COMMITTED); } synchronizations.clear(); when(transactionSynchronizationRegistry.getTransactionKey()).thenReturn("TX2"); interceptor.processInvocation(context); } }
5,536
45.529412
213
java
null
wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/PrimitiveClassLoaderUtil.java
/* * JBoss, Home of Professional Open Source. * Copyright 2011, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ejb3; /** * PrimitiveClassLoaderUtil * <p/> * Util for centralizing the logic for handling primitive types * during classloading. Use the {@link #loadClass(String, ClassLoader)} * to centralize the logic of checking for primitive types to ensure that * the {@link ClassLoader#loadClass(String)} method is not invoked for primitives. * * @author Jaikiran Pai * @version $Revision: $ */ public class PrimitiveClassLoaderUtil { /** * First checks if <code>name</code> is a primitive type. If yes, then returns * the corresponding {@link Class} for that primitive. If it's not a primitive * then the {@link Class#forName(String, boolean, ClassLoader)} method is invoked, passing * it the <code>name</code>, false and the <code>cl</code> classloader * * @param name The class that has to be loaded * @param cl The {@link ClassLoader} to use, if <code>name</code> is *not* a primitive * @return Returns the {@link Class} corresponding to <code>name</code> * @throws ClassNotFoundException If the class for <code>name</code> could not be found * @see ClassLoader#loadClass(String) */ public static Class<?> loadClass(String name, ClassLoader cl) throws ClassNotFoundException { /* * Handle Primitives */ if (name.equals(void.class.getName())) { return void.class; } if (name.equals(byte.class.getName())) { return byte.class; } if (name.equals(short.class.getName())) { return short.class; } if (name.equals(int.class.getName())) { return int.class; } if (name.equals(long.class.getName())) { return long.class; } if (name.equals(char.class.getName())) { return char.class; } if (name.equals(boolean.class.getName())) { return boolean.class; } if (name.equals(float.class.getName())) { return float.class; } if (name.equals(double.class.getName())) { return double.class; } // Now that we know its not a primitive, lets just allow // the passed classloader to handle the request. // Note that we are intentionally using Class.forName(name,boolean,cl) // to handle issues with loading array types in Java 6 http://bugs.sun.com/view_bug.do?bug_id=6434149 return Class.forName(name, false, cl); } }
3,532
38.696629
109
java
null
wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/validator/EjbProxyNormalizerCdiExtension.java
/* * JBoss, Home of Professional Open Source. * Copyright 2020, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ejb3.validator; import jakarta.enterprise.event.Observes; import jakarta.enterprise.inject.spi.AfterBeanDiscovery; import jakarta.enterprise.inject.spi.Extension; /** * @author <a href="mailto:[email protected]">Tomasz Adamski</a> */ public class EjbProxyNormalizerCdiExtension implements Extension { public void addEjbProxyNormalizer(@Observes AfterBeanDiscovery afterBeanDiscovery){ afterBeanDiscovery.addBean(new EjbProxyBeanMetaDataClassNormalizer()); } }
1,529
38.230769
87
java
null
wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/validator/EjbProxyBeanMetaDataClassNormalizer.java
/* * JBoss, Home of Professional Open Source. * Copyright 2020, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ejb3.validator; import java.lang.annotation.Annotation; import java.lang.reflect.Type; import java.util.Collections; import java.util.Set; import jakarta.enterprise.context.ApplicationScoped; import jakarta.enterprise.context.spi.CreationalContext; import jakarta.enterprise.inject.literal.NamedLiteral; import jakarta.enterprise.inject.spi.Bean; import jakarta.enterprise.inject.spi.InjectionPoint; import jakarta.enterprise.inject.spi.PassivationCapable; import org.hibernate.validator.cdi.spi.BeanNames; import org.hibernate.validator.metadata.BeanMetaDataClassNormalizer; /** * * This class is used to provide bean validation with a interface instead of Jakarta Enterprise Beans proxy. This is necessary as Jakarta Enterprise Beans proxy * does not contain generics data. * @see <a href="https://issues.redhat.com/browse/WFLY-11566">WFLY-11566</a> * * @author <a href="mailto:[email protected]">Tomasz Adamski</a> */ public class EjbProxyBeanMetaDataClassNormalizer implements BeanMetaDataClassNormalizer, Bean<BeanMetaDataClassNormalizer>, PassivationCapable { private static final Set<Type> TYPES = Collections.singleton(BeanMetaDataClassNormalizer.class); private static final Set<Annotation> QUALIFIERS = Collections.singleton(NamedLiteral.of(BeanNames.BEAN_META_DATA_CLASS_NORMALIZER)); @Override public <T> Class<? super T> normalize(Class<T> clazz) { if (EjbProxy.class.isAssignableFrom(clazz) && clazz.getSuperclass() != Object.class) { return clazz.getSuperclass(); } return clazz; } @Override public Class<?> getBeanClass() { return BeanMetaDataClassNormalizer.class; } @Override public Set<InjectionPoint> getInjectionPoints() { return Collections.emptySet(); } // This method is removed from jakarta.enterprise.inject.spi.Bean. // So comment out @Override to be able to compile with either javax or jakarta cdi-api // @Override public boolean isNullable() { return false; } @Override public BeanMetaDataClassNormalizer create(CreationalContext<BeanMetaDataClassNormalizer> creationalContext) { return new EjbProxyBeanMetaDataClassNormalizer(); } @Override public void destroy(BeanMetaDataClassNormalizer beanMetaDataClassNormalizer, CreationalContext<BeanMetaDataClassNormalizer> creationalContext) { } @Override public Set<Type> getTypes() { return TYPES; } @Override public Set<Annotation> getQualifiers() { return QUALIFIERS; } @Override public Class<? extends Annotation> getScope() { return ApplicationScoped.class; } @Override public String getName() { return BeanNames.BEAN_META_DATA_CLASS_NORMALIZER; } @Override public Set<Class<? extends Annotation>> getStereotypes() { return Collections.emptySet(); } @Override public boolean isAlternative() { return false; } @Override public String getId() { return EjbProxyBeanMetaDataClassNormalizer.class.getName(); } }
4,153
32.5
160
java
null
wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/validator/EjbProxy.java
/* * JBoss, Home of Professional Open Source. * Copyright 2020, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ /** * Markup inteface for Jakarta Enterprise Beans proxies. * * @author <a href="mailto:[email protected]">Tomasz Adamski</a> */ package org.jboss.as.ejb3.validator; public interface EjbProxy { }
1,228
36.242424
70
java
null
wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/security/RolesAllowedInterceptor.java
/* * JBoss, Home of Professional Open Source. * Copyright 2015, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ejb3.security; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import org.jboss.as.ee.component.Component; import org.jboss.as.ejb3.component.EJBComponent; import org.jboss.as.ejb3.logging.EjbLogger; import org.jboss.invocation.Interceptor; import org.jboss.invocation.InterceptorContext; import org.wildfly.security.auth.server.SecurityDomain; import org.wildfly.security.auth.server.SecurityIdentity; import org.wildfly.security.authz.Roles; /** * @author <a href="mailto:[email protected]">David M. Lloyd</a> */ class RolesAllowedInterceptor implements Interceptor { private final Collection<String> rolesAllowed; RolesAllowedInterceptor(final Collection<String> rolesAllowed) { this.rolesAllowed = rolesAllowed; } static final RolesAllowedInterceptor DENY_ALL = new RolesAllowedInterceptor(Collections.emptyList()); public Object processInvocation(final InterceptorContext context) throws Exception { final Component component = context.getPrivateData(Component.class); if (! (component instanceof EJBComponent)) { throw EjbLogger.ROOT_LOGGER.unexpectedComponent(component, EJBComponent.class); } final Iterator<String> iterator = rolesAllowed.iterator(); if (iterator.hasNext()) { final SecurityDomain securityDomain = context.getPrivateData(SecurityDomain.class); final SecurityIdentity identity = securityDomain.getCurrentSecurityIdentity(); final Roles ejbRoles = identity.getRoles("ejb", true); do { final String role = iterator.next(); if (ejbRoles.contains(role) || (role.equals("**") && !identity.isAnonymous())) { return context.proceed(); } } while (iterator.hasNext()); } throw EjbLogger.ROOT_LOGGER.invocationOfMethodNotAllowed(context.getMethod(), ((EJBComponent) component).getComponentName()); } }
3,041
42.457143
133
java
null
wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/security/RunAsPrincipalInterceptor.java
/* * JBoss, Home of Professional Open Source. * Copyright 2015, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ejb3.security; import java.security.PrivilegedActionException; import org.jboss.as.ee.component.Component; import org.jboss.as.ejb3.component.EJBComponent; import org.jboss.as.ejb3.logging.EjbLogger; import org.jboss.invocation.Interceptor; import org.jboss.invocation.InterceptorContext; import org.wildfly.common.Assert; import org.wildfly.security.auth.server.RealmIdentity; import org.wildfly.security.auth.server.RealmUnavailableException; import org.wildfly.security.auth.server.SecurityDomain; import org.wildfly.security.auth.server.SecurityIdentity; import org.wildfly.security.authz.AuthorizationFailureException; /** * @author <a href="mailto:[email protected]">David M. Lloyd</a> */ public class RunAsPrincipalInterceptor implements Interceptor { public static final String ANONYMOUS_PRINCIPAL = "anonymous"; private final String runAsPrincipal; public RunAsPrincipalInterceptor(final String runAsPrincipal) { this.runAsPrincipal = runAsPrincipal; } public Object processInvocation(final InterceptorContext context) throws Exception { final Component component = context.getPrivateData(Component.class); if (component instanceof EJBComponent == false) { throw EjbLogger.ROOT_LOGGER.unexpectedComponent(component, EJBComponent.class); } final EJBComponent ejbComponent = (EJBComponent) component; // Set the incomingRunAsIdentity before switching users final SecurityDomain securityDomain = context.getPrivateData(SecurityDomain.class); Assert.checkNotNullParam("securityDomain", securityDomain); final SecurityIdentity currentIdentity = securityDomain.getCurrentSecurityIdentity(); final SecurityIdentity oldIncomingRunAsIdentity = ejbComponent.getIncomingRunAsIdentity(); SecurityIdentity newIdentity; try { // The run-as-principal operation should succeed if the current identity is authorized to // run as a user with the given name or if the caller has sufficient permission if (runAsPrincipal.equals(ANONYMOUS_PRINCIPAL)) { try { newIdentity = currentIdentity.createRunAsAnonymous(); } catch (AuthorizationFailureException ex) { newIdentity = currentIdentity.createRunAsAnonymous(false); } } else { if (! runAsPrincipalExists(securityDomain, runAsPrincipal)) { newIdentity = securityDomain.createAdHocIdentity(runAsPrincipal); } else { try { newIdentity = currentIdentity.createRunAsIdentity(runAsPrincipal); } catch (AuthorizationFailureException ex) { newIdentity = currentIdentity.createRunAsIdentity(runAsPrincipal, false); } } } ejbComponent.setIncomingRunAsIdentity(currentIdentity); return newIdentity.runAs(context); } catch (PrivilegedActionException e) { Throwable cause = e.getCause(); if(cause != null) { if(cause instanceof Exception) { throw (Exception) cause; } else { throw new RuntimeException(e); } } else { throw e; } } finally { ejbComponent.setIncomingRunAsIdentity(oldIncomingRunAsIdentity); } } private boolean runAsPrincipalExists(final SecurityDomain securityDomain, final String runAsPrincipal) throws RealmUnavailableException { RealmIdentity realmIdentity = null; try { realmIdentity = securityDomain.getIdentity(runAsPrincipal); return realmIdentity.exists(); } finally { if (realmIdentity != null) { realmIdentity.dispose(); } } } }
5,011
43.353982
141
java
null
wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/security/SecurityRolesAddingInterceptor.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ejb3.security; import java.security.AccessController; import java.security.PrivilegedAction; import java.security.PrivilegedActionException; import java.util.Map; import java.util.Set; import org.jboss.invocation.Interceptor; import org.jboss.invocation.InterceptorContext; import org.wildfly.common.Assert; import org.wildfly.security.auth.server.SecurityDomain; import org.wildfly.security.auth.server.SecurityIdentity; import org.wildfly.security.authz.RoleMapper; import org.wildfly.security.authz.Roles; import org.wildfly.security.manager.WildFlySecurityManager; /** * @author <a href="mailto:[email protected]">Farah Juma</a> */ public class SecurityRolesAddingInterceptor implements Interceptor { private final String category; private final Map<String, Set<String>> principalVsRolesMap; public SecurityRolesAddingInterceptor(final String category, final Map<String,Set<String>> principalVsRolesMap) { this.category = category; this.principalVsRolesMap = principalVsRolesMap; } public Object processInvocation(final InterceptorContext context) throws Exception { final SecurityDomain securityDomain = context.getPrivateData(SecurityDomain.class); Assert.checkNotNullParam("securityDomain", securityDomain); final SecurityIdentity currentIdentity = securityDomain.getCurrentSecurityIdentity(); final Set<String> securityRoles = principalVsRolesMap.get(currentIdentity.getPrincipal().getName()); if (securityRoles != null && ! securityRoles.isEmpty()) { final RoleMapper roleMapper = RoleMapper.constant(Roles.fromSet(securityRoles)); final RoleMapper mergeMapper = roleMapper.or((roles) -> currentIdentity.getRoles(category)); final SecurityIdentity newIdentity; if(WildFlySecurityManager.isChecking()) { newIdentity = AccessController.doPrivileged((PrivilegedAction<SecurityIdentity>) () -> currentIdentity.withRoleMapper(category, mergeMapper)); } else { newIdentity = currentIdentity.withRoleMapper(category, mergeMapper); } try { return newIdentity.runAs(context); } catch (PrivilegedActionException e) { Throwable cause = e.getCause(); if(cause != null) { if(cause instanceof Exception) { throw (Exception) cause; } else { throw new RuntimeException(e); } } else { throw e; } } } else { return context.proceed(); } } }
3,738
42.988235
158
java
null
wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/security/IdentityEJBClientInterceptor.java
/* * JBoss, Home of Professional Open Source. * Copyright 2022, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ejb3.security; import static org.jboss.as.ejb3.security.IdentityUtil.getCurrentSecurityDomain; import org.jboss.ejb.client.EJBClientInterceptor; import org.jboss.ejb.client.EJBClientInvocationContext; import org.wildfly.security.auth.server.SecurityDomain; import org.wildfly.security.auth.server.SecurityIdentity; /** * An {@code EJBClientInterceptor} that will always runAs the current {@code SecurityIdentity} * to activate any outflow identities. * * @author <a href="mailto:[email protected]">Farah Juma</a> */ public final class IdentityEJBClientInterceptor implements EJBClientInterceptor { public static final IdentityEJBClientInterceptor INSTANCE = new IdentityEJBClientInterceptor(); @Override public void handleInvocation(EJBClientInvocationContext context) throws Exception { final SecurityDomain securityDomain = getCurrentSecurityDomain(); if (securityDomain != null) { SecurityIdentity identity = securityDomain.getCurrentSecurityIdentity(); identity.runAsSupplierEx(() -> { context.sendRequest(); return null; }); } else { context.sendRequest(); } } @Override public Object handleInvocationResult(EJBClientInvocationContext context) throws Exception { return context.getResult(); } }
2,404
37.790323
99
java
null
wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/security/EjbJaccConfig.java
/* * JBoss, Home of Professional Open Source. * Copyright 2012, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ejb3.security; import java.security.Permission; import java.util.ArrayList; import java.util.List; import java.util.Map; /** * Class that stores the JACC config for an Jakarta Enterprise Beans before being consumed by the JACC service. * * @author Stuart Douglas * @see EjbJaccService */ public class EjbJaccConfig { private final List<Map.Entry<String, Permission>> roles = new ArrayList<Map.Entry<String, Permission>>(); private final List<Permission> permit = new ArrayList<Permission>(); private final List<Permission> deny = new ArrayList<Permission>(); public void addRole(String role, Permission permission) { roles.add(new Entry<>(role, permission)); } public List<Map.Entry<String, Permission>> getRoles() { return roles; } public void addPermit(Permission permission) { permit.add(permission); } public List<Permission> getPermit() { return permit; } public void addDeny(Permission permission) { deny.add(permission); } public List<Permission> getDeny() { return deny; } private static final class Entry<K, V> implements Map.Entry<K, V> { private final K key; private final V value; public Entry(final K key, final V value) { this.key = key; this.value = value; } public K getKey() { return key; } public V getValue() { return value; } @Override public V setValue(final V value) { return null; } } }
2,637
28.977273
111
java
null
wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/security/IdentityOutflowInterceptorFactory.java
/* * JBoss, Home of Professional Open Source. * Copyright 2016, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ejb3.security; import java.util.Set; import java.util.function.Function; import org.jboss.as.ee.component.Component; import org.jboss.as.ee.component.ComponentInterceptorFactory; import org.jboss.as.ejb3.logging.EjbLogger; import org.jboss.as.ejb3.component.EJBComponent; import org.jboss.invocation.Interceptor; import org.jboss.invocation.InterceptorFactory; import org.jboss.invocation.InterceptorFactoryContext; import org.wildfly.security.auth.server.SecurityIdentity; import org.wildfly.security.authz.RoleMapper; /** * @author <a href="mailto:[email protected]">Farah Juma</a> */ public class IdentityOutflowInterceptorFactory extends ComponentInterceptorFactory { public static final InterceptorFactory INSTANCE = new IdentityOutflowInterceptorFactory(); private final String category; private final RoleMapper roleMapper; public IdentityOutflowInterceptorFactory() { this(null, null); } public IdentityOutflowInterceptorFactory(final String category, final RoleMapper roleMapper) { this.category = category; this.roleMapper = roleMapper; } @Override protected Interceptor create(final Component component, final InterceptorFactoryContext context) { if (! (component instanceof EJBComponent)) { throw EjbLogger.ROOT_LOGGER.unexpectedComponent(component, EJBComponent.class); } final EJBComponent ejbComponent = (EJBComponent) component; final Function<SecurityIdentity, Set<SecurityIdentity>> identityOutflowFunction = ejbComponent.getIdentityOutflowFunction(); return new IdentityOutflowInterceptor(identityOutflowFunction, category, roleMapper); } }
2,730
39.761194
132
java
null
wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/security/EjbJaccService.java
/* * JBoss, Home of Professional Open Source. * Copyright 2011, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ejb3.security; import java.security.Permission; import java.util.Map.Entry; import jakarta.security.jacc.PolicyConfiguration; import jakarta.security.jacc.PolicyContextException; import org.jboss.as.ee.security.JaccService; import org.jboss.as.server.deployment.AttachmentList; /** * A service that creates JACC permissions for an ejb deployment * * @author <a href="mailto:[email protected]">Marcus Moyses</a> * @author [email protected] * @author [email protected] * @author Stuart Douglas */ public class EjbJaccService extends JaccService<AttachmentList<EjbJaccConfig>> { public EjbJaccService(String contextId, AttachmentList<EjbJaccConfig> metaData, Boolean standalone) { super(contextId, metaData, standalone); } @Override public void createPermissions(final AttachmentList<EjbJaccConfig> metaData, final PolicyConfiguration policyConfiguration) throws PolicyContextException { for (EjbJaccConfig permission : metaData) { for (Permission deny : permission.getDeny()) { policyConfiguration.addToExcludedPolicy(deny); } for (Permission permit : permission.getPermit()) { policyConfiguration.addToUncheckedPolicy(permit); } for (Entry<String, Permission> role : permission.getRoles()) { policyConfiguration.addToRole(role.getKey(), role.getValue()); } } } }
2,495
38.619048
158
java
null
wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/security/SecurityDomainInterceptorFactory.java
/* * JBoss, Home of Professional Open Source. * Copyright 2016, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ejb3.security; import static org.jboss.as.ejb3.logging.EjbLogger.ROOT_LOGGER; import org.jboss.as.ee.component.Component; import org.jboss.as.ee.component.ComponentInterceptorFactory; import org.jboss.as.ejb3.logging.EjbLogger; import org.jboss.as.ejb3.component.EJBComponent; import org.jboss.invocation.Interceptor; import org.jboss.invocation.InterceptorFactory; import org.jboss.invocation.InterceptorFactoryContext; import org.wildfly.security.auth.server.SecurityDomain; /** * @author <a href="mailto:[email protected]">Farah Juma</a> */ public class SecurityDomainInterceptorFactory extends ComponentInterceptorFactory { public static final InterceptorFactory INSTANCE = new SecurityDomainInterceptorFactory(); private static final String DEFAULT_DOMAIN = "other"; @Override protected Interceptor create(final Component component, final InterceptorFactoryContext context) { if (! (component instanceof EJBComponent)) { throw EjbLogger.ROOT_LOGGER.unexpectedComponent(component, EJBComponent.class); } final EJBComponent ejbComponent = (EJBComponent) component; final EJBSecurityMetaData securityMetaData = ejbComponent.getSecurityMetaData(); String securityDomainName = securityMetaData.getSecurityDomainName(); if (securityDomainName == null) { securityDomainName = DEFAULT_DOMAIN; } final SecurityDomain securityDomain = ejbComponent.getSecurityDomain(); if (securityDomain == null) { throw EjbLogger.ROOT_LOGGER.invalidSecurityForDomainSet(ejbComponent.getComponentName()); } if (ROOT_LOGGER.isTraceEnabled()) { ROOT_LOGGER.trace("Using security domain: " + securityDomainName + " for EJB " + ejbComponent.getComponentName()); } return new SecurityDomainInterceptor(securityDomain); } }
2,924
42.014706
126
java
null
wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/security/JaccInterceptor.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ejb3.security; import static java.security.AccessController.doPrivileged; import java.lang.reflect.Method; import java.security.AccessController; import java.security.Policy; import java.security.Principal; import java.security.PrivilegedAction; import java.security.PrivilegedActionException; import java.security.PrivilegedExceptionAction; import java.security.ProtectionDomain; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.function.Function; import jakarta.security.jacc.EJBMethodPermission; import org.jboss.as.ee.component.Component; import org.jboss.as.ee.component.ComponentView; import org.jboss.as.ejb3.component.EJBComponent; import org.jboss.as.ejb3.logging.EjbLogger; import org.jboss.invocation.Interceptor; import org.jboss.invocation.InterceptorContext; import org.jboss.metadata.ejb.spec.MethodInterfaceType; import org.wildfly.common.Assert; import org.wildfly.security.auth.server.SecurityDomain; import org.wildfly.security.auth.server.SecurityIdentity; import org.wildfly.security.manager.WildFlySecurityManager; /** * @author <a href="mailto:[email protected]">Pedro Igor</a> */ public class JaccInterceptor implements Interceptor { private static final Principal[] NO_PRINCIPALS = new Principal[0]; private final String viewClassName; private final Method viewMethod; public JaccInterceptor(String viewClassName, Method viewMethod) { this.viewClassName = viewClassName; this.viewMethod = viewMethod; } @Override public Object processInvocation(InterceptorContext context) throws Exception { Component component = context.getPrivateData(Component.class); final SecurityDomain securityDomain = context.getPrivateData(SecurityDomain.class); Assert.checkNotNullParam("securityDomain", securityDomain); final SecurityIdentity currentIdentity = securityDomain.getCurrentSecurityIdentity(); if (component instanceof EJBComponent == false) { throw EjbLogger.ROOT_LOGGER.unexpectedComponent(component, EJBComponent.class); } Method invokedMethod = context.getMethod(); ComponentView componentView = context.getPrivateData(ComponentView.class); String viewClassOfInvokedMethod = componentView.getViewClass().getName(); // shouldn't really happen if the interceptor was setup correctly. But let's be safe and do a check if (!viewClassName.equals(viewClassOfInvokedMethod) || !viewMethod.equals(invokedMethod)) { throw EjbLogger.ROOT_LOGGER.failProcessInvocation(getClass().getName(), invokedMethod, viewClassOfInvokedMethod, viewMethod, viewClassName); } EJBComponent ejbComponent = (EJBComponent) component; if(WildFlySecurityManager.isChecking()) { try { AccessController.doPrivileged((PrivilegedExceptionAction<Object>) () -> { hasPermission(ejbComponent, componentView, invokedMethod, currentIdentity); return null; }); } catch (PrivilegedActionException e) { throw e.getException(); } } else { hasPermission(ejbComponent, componentView, invokedMethod, currentIdentity); } // successful authorization, let the invocation proceed return context.proceed(); } private EJBMethodPermission createEjbMethodPermission(Method invokedMethod, EJBComponent ejbComponent, MethodInterfaceType methodIntfType) { return new EJBMethodPermission(ejbComponent.getComponentName(), methodIntfType.name(), invokedMethod); } private void hasPermission(EJBComponent ejbComponent, ComponentView componentView, Method method, SecurityIdentity securityIdentity) { MethodInterfaceType methodIntfType = componentView.getPrivateData(MethodInterfaceType.class); EJBMethodPermission permission = createEjbMethodPermission(method, ejbComponent, methodIntfType); ProtectionDomain domain = new ProtectionDomain (componentView.getProxyClass().getProtectionDomain().getCodeSource(), null, null, getGrantedRoles(securityIdentity)); Policy policy = WildFlySecurityManager.isChecking() ? doPrivileged((PrivilegedAction<Policy>) Policy::getPolicy) : Policy.getPolicy(); if (!policy.implies(domain, permission)) { throw EjbLogger.ROOT_LOGGER.invocationOfMethodNotAllowed(method,ejbComponent.getComponentName()); } } /** * Returns an array of {@link Principal} representing the roles associated with the identity * invoking the Jakarta Enterprise Beans. This method will check performs checks against run as identities in order to * resolve the correct set of roles to be granted. * * @param securityIdentity the identity invoking the Jakarta Enterprise Beans * @return an array of {@link Principal} representing the roles associated with the identity */ public static Principal[] getGrantedRoles(SecurityIdentity securityIdentity) { Set<String> roles = new HashSet<>(); for (String s : securityIdentity.getRoles("ejb")) { roles.add(s); } List<Principal> list = new ArrayList<>(); Function<String, Principal> mapper = roleName -> (Principal) () -> roleName; for (String role : roles) { Principal principal = mapper.apply(role); list.add(principal); } return list.toArray(NO_PRINCIPALS); } }
6,583
44.406897
172
java
null
wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/security/EJBSecurityViewConfigurator.java
/* * JBoss, Home of Professional Open Source. * Copyright 2011, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ejb3.security; import static org.jboss.as.ejb3.logging.EjbLogger.ROOT_LOGGER; import static org.jboss.as.server.deployment.Attachments.CAPABILITY_SERVICE_SUPPORT; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Set; import org.jboss.as.controller.capability.CapabilityServiceSupport; import org.jboss.as.ee.component.ComponentConfiguration; import org.jboss.as.ee.component.ViewConfiguration; import org.jboss.as.ee.component.ViewConfigurator; import org.jboss.as.ee.component.ViewDescription; import org.jboss.as.ee.component.interceptors.InterceptorOrder; import org.jboss.as.ee.component.serialization.WriteReplaceInterface; import org.jboss.as.ejb3.component.EJBComponentDescription; import org.jboss.as.ejb3.component.EJBViewDescription; import org.jboss.as.ejb3.deployment.ApplicableMethodInformation; import org.jboss.as.ejb3.logging.EjbLogger; import org.jboss.as.ejb3.security.service.EJBViewMethodSecurityAttributesService; import org.jboss.as.server.deployment.DeploymentPhaseContext; import org.jboss.as.server.deployment.DeploymentUnit; import org.jboss.as.server.deployment.DeploymentUnitProcessingException; import org.jboss.as.server.deployment.reflect.ClassReflectionIndexUtil; import org.jboss.as.server.deployment.reflect.DeploymentReflectionIndex; import org.jboss.invocation.ImmediateInterceptorFactory; import org.jboss.invocation.Interceptor; import org.jboss.invocation.InterceptorFactory; import org.jboss.metadata.ejb.spec.MethodInterfaceType; import org.jboss.msc.service.ServiceName; /** * {@link ViewConfigurator} responsible for setting up necessary security interceptors on an EJB view. * * NOTE: References in this file to Enterprise JavaBeans (EJB) refer to the Jakarta Enterprise Beans unless otherwise noted. * * <p/> * User: Jaikiran Pai */ public class EJBSecurityViewConfigurator implements ViewConfigurator { @Override public void configure(DeploymentPhaseContext context, ComponentConfiguration componentConfiguration, ViewDescription viewDescription, ViewConfiguration viewConfiguration) throws DeploymentUnitProcessingException { if (componentConfiguration.getComponentDescription() instanceof EJBComponentDescription == false) { throw EjbLogger.ROOT_LOGGER.invalidEjbComponent(componentConfiguration.getComponentName(), componentConfiguration.getComponentClass()); } final DeploymentUnit deploymentUnit = context.getDeploymentUnit(); final EJBComponentDescription ejbComponentDescription = (EJBComponentDescription) componentConfiguration.getComponentDescription(); final boolean elytronSecurityDomain = ejbComponentDescription.getSecurityDomainServiceName() != null; final String viewClassName = viewDescription.getViewClassName(); final EJBViewDescription ejbViewDescription = (EJBViewDescription) viewDescription; final EJBViewMethodSecurityAttributesService.Builder viewMethodSecurityAttributesServiceBuilder; final ServiceName viewMethodSecurityAttributesServiceName; // The way @WebService view integrates with EJBs is tricky. It marks the fully qualified bean class name as the view name of the service endpoint. Now, if that bean also has a @LocalBean (i.e. no-interface view) // then we now have 2 views with the same view name. In such cases, it's fine to skip one of those views and register this service only once, since essentially, the service is expected to return the same data // for both these views. So here we skip the @WebService view if the bean also has a @LocalBean (no-interface) view and let the EJBViewMethodSecurityAttributesService be built when the no-interface view is processed // note that we always install this service for SERVICE_ENDPOINT views, even if security is not enabled if (MethodInterfaceType.ServiceEndpoint == ejbViewDescription.getMethodIntf()) { viewMethodSecurityAttributesServiceBuilder = new EJBViewMethodSecurityAttributesService.Builder(); viewMethodSecurityAttributesServiceName = EJBViewMethodSecurityAttributesService.getServiceName(ejbComponentDescription.getApplicationName(), ejbComponentDescription.getModuleName(), ejbComponentDescription.getEJBName(), viewClassName); } else { viewMethodSecurityAttributesServiceBuilder = null; viewMethodSecurityAttributesServiceName = null; } if (!legacySecurityAvailable(deploymentUnit) && !elytronSecurityDomain) { // the security subsystem is not present and Elytron is not being used for security, we don't apply any security settings installAttributeServiceIfRequired(context, viewMethodSecurityAttributesServiceBuilder, viewMethodSecurityAttributesServiceName); return; } final DeploymentReflectionIndex deploymentReflectionIndex = deploymentUnit.getAttachment(org.jboss.as.server.deployment.Attachments.REFLECTION_INDEX); // The getSecurityDomain() will return a null value if neither an explicit security domain is configured // for the bean nor there's any default security domain that's configured at EJB3 subsystem level. // In such cases, we do *not* apply any security interceptors String resolvedSecurityDomain = ejbComponentDescription.getResolvedSecurityDomain(); if (elytronSecurityDomain == false && (resolvedSecurityDomain == null || resolvedSecurityDomain.isEmpty())) { if (ROOT_LOGGER.isDebugEnabled()) { ROOT_LOGGER .debug("Security is *not* enabled on EJB: " + ejbComponentDescription.getEJBName() + ", since no explicit security domain is configured for the bean, nor is there any default security domain configured in the EJB3 subsystem"); } installAttributeServiceIfRequired(context, viewMethodSecurityAttributesServiceBuilder, viewMethodSecurityAttributesServiceName); return; } // setup the JACC contextID. String contextID = deploymentUnit.getName(); if (deploymentUnit.getParent() != null) { contextID = deploymentUnit.getParent().getName() + "!" + contextID; } // setup the method specific security interceptor(s) boolean beanHasMethodLevelSecurityMetadata = false; final List<Method> viewMethods = viewConfiguration.getProxyFactory().getCachedMethods(); final List<Method> methodsWithoutExplicitSecurityConfiguration = new ArrayList<Method>(); for (final Method viewMethod : viewMethods) { // TODO: proxy factory exposes non-public methods, is this a bug in the no-interface view? if (!Modifier.isPublic(viewMethod.getModifiers())) { continue; } if (viewMethod.getDeclaringClass() == WriteReplaceInterface.class) { continue; } // setup the authorization interceptor final ApplicableMethodInformation<EJBMethodSecurityAttribute> permissions = ejbComponentDescription.getDescriptorMethodPermissions(); boolean methodHasSecurityMetadata = handlePermissions(contextID, componentConfiguration, viewConfiguration, deploymentReflectionIndex, viewClassName, ejbViewDescription, viewMethod, permissions, false, viewMethodSecurityAttributesServiceBuilder, ejbComponentDescription, elytronSecurityDomain, resolvedSecurityDomain); if (!methodHasSecurityMetadata) { //if it was not handled by the descriptor processor we look for annotation basic info methodHasSecurityMetadata = handlePermissions(contextID, componentConfiguration, viewConfiguration, deploymentReflectionIndex, viewClassName, ejbViewDescription, viewMethod, ejbComponentDescription.getAnnotationMethodPermissions(), true, viewMethodSecurityAttributesServiceBuilder, ejbComponentDescription, elytronSecurityDomain, resolvedSecurityDomain); } // if any method has security metadata then the bean has method level security metadata if (methodHasSecurityMetadata) { beanHasMethodLevelSecurityMetadata = true; } else { // make a note that this method didn't have any explicit method permissions configured methodsWithoutExplicitSecurityConfiguration.add(viewMethod); } } final boolean securityRequired = beanHasMethodLevelSecurityMetadata || ejbComponentDescription.hasBeanLevelSecurityMetadata(); if (securityRequired) { ejbComponentDescription.setSecurityRequired(securityRequired); } // setup the security context interceptor if (elytronSecurityDomain) { final HashMap<Integer, InterceptorFactory> elytronInterceptorFactories = ejbComponentDescription.getElytronInterceptorFactories(contextID, ejbComponentDescription.requiresJacc(), true); elytronInterceptorFactories.forEach((priority, elytronInterceptorFactory) -> viewConfiguration.addViewInterceptor(elytronInterceptorFactory, priority)); } else if (securityRequired) { throw ROOT_LOGGER.legacySecurityUnsupported(resolvedSecurityDomain); } // now add the authorization interceptor if the bean has *any* security metadata applicable if (securityRequired) { // check the missing-method-permissions-deny-access configuration and add the authorization interceptor // to methods which don't have explicit method permissions. // (@see http://anil-identity.blogspot.in/2010/02/tip-interpretation-of-missing-ejb.html for details) final Boolean denyAccessToMethodsMissingPermissions = ((EJBComponentDescription) componentConfiguration.getComponentDescription()).isMissingMethodPermissionsDeniedAccess(); // default to "deny access" if (denyAccessToMethodsMissingPermissions != Boolean.FALSE) { for (final Method viewMethod : methodsWithoutExplicitSecurityConfiguration) { if (viewMethodSecurityAttributesServiceBuilder != null) { // build the EJBViewMethodSecurityAttributesService to expose these security attributes to other components like WS (@see https://issues.jboss.org/browse/WFLY-308) viewMethodSecurityAttributesServiceBuilder.addMethodSecurityMetadata(viewMethod, EJBMethodSecurityAttribute.denyAll()); } // "deny access" implies we need the authorization interceptor to be added so that it can nuke the invocation if (elytronSecurityDomain) { viewConfiguration.addViewInterceptor(viewMethod, new ImmediateInterceptorFactory(RolesAllowedInterceptor.DENY_ALL), InterceptorOrder.View.EJB_SECURITY_AUTHORIZATION_INTERCEPTOR); } else { throw ROOT_LOGGER.legacySecurityUnsupported(resolvedSecurityDomain); } } } } installAttributeServiceIfRequired(context, viewMethodSecurityAttributesServiceBuilder, viewMethodSecurityAttributesServiceName); } private static boolean legacySecurityAvailable(DeploymentUnit deploymentUnit) { final CapabilityServiceSupport support = deploymentUnit.getAttachment(CAPABILITY_SERVICE_SUPPORT); return support.hasCapability("org.wildfly.legacy-security"); } private void installAttributeServiceIfRequired(DeploymentPhaseContext context, EJBViewMethodSecurityAttributesService.Builder viewMethodSecurityAttributesServiceBuilder, ServiceName viewMethodSecurityAttributesServiceName) { if (viewMethodSecurityAttributesServiceBuilder != null) { final EJBViewMethodSecurityAttributesService viewMethodSecurityAttributesService = viewMethodSecurityAttributesServiceBuilder.build(); context.getServiceTarget().addService(viewMethodSecurityAttributesServiceName, viewMethodSecurityAttributesService).install(); } } private boolean handlePermissions(String contextID, ComponentConfiguration componentConfiguration, ViewConfiguration viewConfiguration, DeploymentReflectionIndex deploymentReflectionIndex, String viewClassName, EJBViewDescription ejbViewDescription, Method viewMethod, ApplicableMethodInformation<EJBMethodSecurityAttribute> permissions, boolean annotations, final EJBViewMethodSecurityAttributesService.Builder viewMethodSecurityAttributesServiceBuilder, EJBComponentDescription componentDescription, boolean elytronSecurityDomain, final String resolvedSecurityDomain) { EJBMethodSecurityAttribute ejbMethodSecurityMetaData = permissions.getViewAttribute(ejbViewDescription.getMethodIntf(), viewMethod); final List<EJBMethodSecurityAttribute> allAttributes = new ArrayList<EJBMethodSecurityAttribute>(); allAttributes.addAll(permissions.getAllAttributes(ejbViewDescription.getMethodIntf(), viewMethod)); if (ejbMethodSecurityMetaData == null) { ejbMethodSecurityMetaData = permissions.getViewAttribute(MethodInterfaceType.Bean, viewMethod); } allAttributes.addAll(permissions.getAllAttributes(MethodInterfaceType.Bean, viewMethod)); final Method classMethod = ClassReflectionIndexUtil.findMethod(deploymentReflectionIndex, componentConfiguration.getComponentClass(), viewMethod); if (ejbMethodSecurityMetaData == null && classMethod != null) { // if this is null we try with the corresponding bean method ejbMethodSecurityMetaData = permissions.getAttribute(ejbViewDescription.getMethodIntf(), classMethod); if (ejbMethodSecurityMetaData == null) { ejbMethodSecurityMetaData = permissions.getAttribute(MethodInterfaceType.Bean, classMethod); } } if (classMethod != null) { allAttributes.addAll(permissions.getAllAttributes(ejbViewDescription.getMethodIntf(), classMethod)); allAttributes.addAll(permissions.getAllAttributes(MethodInterfaceType.Bean, classMethod)); } //we do not add the security interceptor if there is no security information if (ejbMethodSecurityMetaData != null) { if (!annotations && !ejbMethodSecurityMetaData.isDenyAll() && !ejbMethodSecurityMetaData.isPermitAll()) { //roles are additive when defined in the deployment descriptor final Set<String> rolesAllowed = new HashSet<String>(); for (EJBMethodSecurityAttribute attr : allAttributes) { rolesAllowed.addAll(attr.getRolesAllowed()); } ejbMethodSecurityMetaData = EJBMethodSecurityAttribute.rolesAllowed(rolesAllowed); } // build the EJBViewMethodSecurityAttributesService to expose these security attributes to other components like WS (@see https://issues.jboss.org/browse/WFLY-308) if (viewMethodSecurityAttributesServiceBuilder != null) { viewMethodSecurityAttributesServiceBuilder.addMethodSecurityMetadata(viewMethod, ejbMethodSecurityMetaData); } if (ejbMethodSecurityMetaData.isPermitAll()) { // no need to add authorizing interceptor return true; } // add the interceptor final Interceptor authorizationInterceptor; if (elytronSecurityDomain) { if (ejbMethodSecurityMetaData.isDenyAll()) { authorizationInterceptor = RolesAllowedInterceptor.DENY_ALL; } else { if (componentDescription.requiresJacc()) { authorizationInterceptor = new JaccInterceptor(viewClassName, viewMethod); } else { authorizationInterceptor = new RolesAllowedInterceptor(ejbMethodSecurityMetaData.getRolesAllowed()); } } } else { throw ROOT_LOGGER.legacySecurityUnsupported(resolvedSecurityDomain); } viewConfiguration.addViewInterceptor(viewMethod, new ImmediateInterceptorFactory(authorizationInterceptor), InterceptorOrder.View.EJB_SECURITY_AUTHORIZATION_INTERCEPTOR); return true; } return false; } }
17,734
64.442804
370
java
null
wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/security/EjbJaccConfigurator.java
/* * JBoss, Home of Professional Open Source. * Copyright 2012, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ejb3.security; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.security.Permission; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import jakarta.security.jacc.EJBMethodPermission; import jakarta.security.jacc.EJBRoleRefPermission; import org.jboss.as.ee.component.ComponentConfiguration; import org.jboss.as.ee.component.ComponentConfigurator; import org.jboss.as.ee.component.ComponentDescription; import org.jboss.as.ee.component.ViewConfiguration; import org.jboss.as.ee.component.serialization.WriteReplaceInterface; import org.jboss.as.ejb3.component.EJBComponentDescription; import org.jboss.as.ejb3.component.EJBViewConfiguration; import org.jboss.as.ejb3.component.session.SessionBeanComponentDescription; import org.jboss.as.ejb3.deployment.ApplicableMethodInformation; import org.jboss.as.ejb3.deployment.EjbDeploymentAttachmentKeys; import org.jboss.as.server.deployment.Attachments; import org.jboss.as.server.deployment.DeploymentPhaseContext; import org.jboss.as.server.deployment.DeploymentUnit; import org.jboss.as.server.deployment.DeploymentUnitProcessingException; import org.jboss.as.server.deployment.reflect.ClassReflectionIndexUtil; import org.jboss.as.server.deployment.reflect.DeploymentReflectionIndex; import org.jboss.metadata.ejb.spec.MethodInterfaceType; import org.jboss.metadata.javaee.spec.SecurityRoleMetaData; import org.jboss.metadata.javaee.spec.SecurityRolesMetaData; /** * Component configurator the calculates JACC roles * * @author Stuart Douglas * @author <a href="mailto:[email protected]">Stefan Guilhen</a> */ public class EjbJaccConfigurator implements ComponentConfigurator { private static final String ANY_AUTHENTICATED_USER_ROLE = "**"; @Override public void configure(final DeploymentPhaseContext context, final ComponentDescription description, final ComponentConfiguration configuration) throws DeploymentUnitProcessingException { final DeploymentUnit deploymentUnit = context.getDeploymentUnit(); final DeploymentReflectionIndex reflectionIndex = deploymentUnit.getAttachment(Attachments.REFLECTION_INDEX); final EJBComponentDescription ejbComponentDescription = EJBComponentDescription.class.cast(description); final EjbJaccConfig ejbJaccConfig = new EjbJaccConfig(); context.getDeploymentUnit().addToAttachmentList(EjbDeploymentAttachmentKeys.JACC_PERMISSIONS, ejbJaccConfig); // process the method permissions. for (final ViewConfiguration viewConfiguration : configuration.getViews()) { final List<Method> viewMethods = viewConfiguration.getProxyFactory().getCachedMethods(); for (final Method viewMethod : viewMethods) { if (!Modifier.isPublic(viewMethod.getModifiers()) || viewMethod.getDeclaringClass() == WriteReplaceInterface.class) { continue; } final EJBViewConfiguration ejbViewConfiguration = EJBViewConfiguration.class.cast(viewConfiguration); // try to create permissions using the descriptor metadata first. ApplicableMethodInformation<EJBMethodSecurityAttribute> permissions = ejbComponentDescription.getDescriptorMethodPermissions(); boolean createdPerms = this.createPermissions(ejbJaccConfig, ejbComponentDescription, ejbViewConfiguration, viewMethod, reflectionIndex, permissions); // no permissions created using the descriptor metadata - try to use annotation metadata. if (!createdPerms) { permissions = ejbComponentDescription.getAnnotationMethodPermissions(); createPermissions(ejbJaccConfig, ejbComponentDescription, ejbViewConfiguration, viewMethod, reflectionIndex, permissions); } } } Set<String> securityRoles = new HashSet<String>(); // get all roles from the deployments descriptor (assembly descriptor roles) SecurityRolesMetaData secRolesMetaData = ejbComponentDescription.getSecurityRoles(); if (secRolesMetaData != null) { for (SecurityRoleMetaData secRoleMetaData : secRolesMetaData) { securityRoles.add(secRoleMetaData.getRoleName()); } } // at this point any roles specified via RolesAllowed annotation have been mapped to EJBMethodPermissions, so // going through the permissions allows us to retrieve these roles. // TODO there might be a better way to retrieve just annotated roles without going through all processed permissions List<Map.Entry<String, Permission>> processedRoles = ejbJaccConfig.getRoles(); for (Map.Entry<String, Permission> entry : processedRoles) { securityRoles.add(entry.getKey()); } securityRoles.add(ANY_AUTHENTICATED_USER_ROLE); // process the security-role-ref from the deployment descriptor. Map<String, Collection<String>> securityRoleRefs = ejbComponentDescription.getSecurityRoleLinks(); for (Map.Entry<String, Collection<String>> entry : securityRoleRefs.entrySet()) { String roleName = entry.getKey(); for (String roleLink : entry.getValue()) { EJBRoleRefPermission p = new EJBRoleRefPermission(ejbComponentDescription.getEJBName(), roleName); ejbJaccConfig.addRole(roleLink, p); } securityRoles.remove(roleName); } // process remaining annotated declared roles that were not overridden in the descriptor. Set<String> declaredRoles = ejbComponentDescription.getDeclaredRoles(); for (String role : declaredRoles) { if (!securityRoleRefs.containsKey(role)) { EJBRoleRefPermission p = new EJBRoleRefPermission(ejbComponentDescription.getEJBName(), role); ejbJaccConfig.addRole(role, p); } securityRoles.remove(role); } // an EJBRoleRefPermission must be created for each declared role that does not appear in the security-role-ref. for (String role : securityRoles) { EJBRoleRefPermission p = new EJBRoleRefPermission(ejbComponentDescription.getEJBName(), role); ejbJaccConfig.addRole(role, p); } // special handling of stateful session bean getEJBObject due how the stateful session handles acquire the // proxy by sending an invocation to the ejb container. if (ejbComponentDescription instanceof SessionBeanComponentDescription) { SessionBeanComponentDescription session = SessionBeanComponentDescription.class.cast(ejbComponentDescription); if (session.isStateful()) { EJBMethodPermission p = new EJBMethodPermission(ejbComponentDescription.getEJBName(), "getEJBObject", "Home", null); ejbJaccConfig.addPermit(p); } } } protected boolean createPermissions(final EjbJaccConfig ejbJaccConfig, final EJBComponentDescription description, final EJBViewConfiguration ejbViewConfiguration, final Method viewMethod, final DeploymentReflectionIndex index, final ApplicableMethodInformation<EJBMethodSecurityAttribute> permissions) { EJBMethodSecurityAttribute ejbMethodSecurityMetaData = permissions.getViewAttribute(ejbViewConfiguration.getMethodIntf(), viewMethod); //if this is null we try with the corresponding bean method. if (ejbMethodSecurityMetaData == null) { ejbMethodSecurityMetaData = permissions.getViewAttribute(MethodInterfaceType.Bean, viewMethod); } final Method classMethod = ClassReflectionIndexUtil.findMethod(index, ejbViewConfiguration.getComponentConfiguration().getComponentClass(), viewMethod); if (ejbMethodSecurityMetaData == null && classMethod != null) { // if this is null we try with the corresponding bean method. ejbMethodSecurityMetaData = permissions.getAttribute(ejbViewConfiguration.getMethodIntf(), classMethod); if (ejbMethodSecurityMetaData == null) { ejbMethodSecurityMetaData = permissions.getAttribute(MethodInterfaceType.Bean, classMethod); } } // check if any security metadata was defined for the method. if (ejbMethodSecurityMetaData != null) { final MethodInterfaceType interfaceType = ejbViewConfiguration.getMethodIntf(); final EJBMethodPermission permission = new EJBMethodPermission(description.getEJBName(), interfaceType.name(), viewMethod); if (ejbMethodSecurityMetaData.isPermitAll()) { ejbJaccConfig.addPermit(permission); } if (ejbMethodSecurityMetaData.isDenyAll()) { ejbJaccConfig.addDeny(permission); } for (String role : ejbMethodSecurityMetaData.getRolesAllowed()) { ejbJaccConfig.addRole(role, permission); } return true; } return false; } }
10,221
51.963731
190
java
null
wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/security/IdentityUtil.java
/* * JBoss, Home of Professional Open Source. * Copyright 2022, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ejb3.security; import java.security.AccessController; import java.security.PrivilegedAction; import org.wildfly.security.auth.server.SecurityDomain; import org.wildfly.security.manager.WildFlySecurityManager; /** * @author <a href="mailto:[email protected]">Farah Juma</a> */ class IdentityUtil { public static SecurityDomain getCurrentSecurityDomain() { if (WildFlySecurityManager.isChecking()) { return AccessController.doPrivileged((PrivilegedAction<SecurityDomain>) SecurityDomain::getCurrent); } else { return SecurityDomain.getCurrent(); } } }
1,656
36.659091
112
java
null
wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/security/IdentityInterceptor.java
/* * JBoss, Home of Professional Open Source. * Copyright 2022, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ejb3.security; import static org.jboss.as.ejb3.security.IdentityUtil.getCurrentSecurityDomain; import org.jboss.invocation.Interceptor; import org.jboss.invocation.InterceptorContext; import org.wildfly.security.auth.server.SecurityDomain; import org.wildfly.security.auth.server.SecurityIdentity; /** * An {@code Interceptor} that will always runAs the current {@code SecurityIdentity} * to activate any outflow identities. * * @author <a href="mailto:[email protected]">Farah Juma</a> */ public final class IdentityInterceptor implements Interceptor { public static final IdentityInterceptor INSTANCE = new IdentityInterceptor(); @Override public Object processInvocation(InterceptorContext context) throws Exception { final SecurityDomain securityDomain = getCurrentSecurityDomain(); if (securityDomain != null) { SecurityIdentity identity = securityDomain.getCurrentSecurityIdentity(); return identity.runAsSupplierEx(() -> context.proceed()); } else { return context.proceed(); } } }
2,128
38.425926
85
java