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
infinispan-main/client/hotrod/src/main/java/org/infinispan/hotrod/transaction/lookup/GenericTransactionManagerLookup.java
package org.infinispan.hotrod.transaction.lookup; import java.util.Optional; import javax.naming.InitialContext; import javax.naming.NamingException; import jakarta.transaction.TransactionManager; import org.infinispan.hotrod.transaction.manager.RemoteTransactionManager; import org.infinispan.commons.util.Util; import org.infinispan.commons.tx.lookup.LookupNames; import org.infinispan.commons.tx.lookup.TransactionManagerLookup; import net.jcip.annotations.GuardedBy; /** * A {@link TransactionManagerLookup} implementation that attempts to locate a {@link TransactionManager}. * <p> * A variety of different classes and JNDI locations are tried, for servers such as: <ul> <li> JBoss <li> JRun4 <li> * Resin <li> Orion <li> JOnAS <li> BEA Weblogic <li> Websphere 4.0, 5.0, 5.1, 6.0 <li> Sun, Glassfish </ul>. * <p> * If a transaction manager is not found, returns an {@link RemoteTransactionManager}. * * @since 14.0 */ public class GenericTransactionManagerLookup implements TransactionManagerLookup { private static final GenericTransactionManagerLookup INSTANCE = new GenericTransactionManagerLookup(); @GuardedBy("this") private TransactionManager transactionManager = null; private GenericTransactionManagerLookup() { } public static GenericTransactionManagerLookup getInstance() { return INSTANCE; } @Override public synchronized TransactionManager getTransactionManager() { if (transactionManager != null) { return transactionManager; } transactionManager = tryTmFactoryLookup().orElseGet(RemoteTransactionManager::getInstance); transactionManager = tryJndiLookup().orElseGet( () -> tryTmFactoryLookup().orElseGet(RemoteTransactionManager::getInstance)); return transactionManager; } private Optional<TransactionManager> tryJndiLookup() { InitialContext ctx; try { ctx = new InitialContext(); } catch (NamingException e) { return Optional.empty(); } try { //probe jndi lookups first for (LookupNames.JndiTransactionManager knownJNDIManager : LookupNames.JndiTransactionManager.values()) { Object jndiObject; try { jndiObject = ctx.lookup(knownJNDIManager.getJndiLookup()); } catch (NamingException e) { continue; } if (jndiObject instanceof TransactionManager) { return Optional.of((TransactionManager) jndiObject); } } } finally { Util.close(ctx); } return Optional.empty(); } private Optional<TransactionManager> tryTmFactoryLookup() { for (LookupNames.TransactionManagerFactory transactionManagerFactory : LookupNames.TransactionManagerFactory .values()) { TransactionManager transactionManager = transactionManagerFactory .tryLookup(GenericTransactionManagerLookup.class.getClassLoader()); if (transactionManager != null) { return Optional.of(transactionManager); } } return Optional.empty(); } }
3,135
33.844444
116
java
null
infinispan-main/client/hotrod/src/main/java/org/infinispan/hotrod/transaction/lookup/RemoteTransactionManagerLookup.java
package org.infinispan.hotrod.transaction.lookup; import jakarta.transaction.TransactionManager; import org.infinispan.hotrod.transaction.manager.RemoteTransactionManager; import org.infinispan.commons.tx.lookup.TransactionManagerLookup; /** * Returns an instance of {@link RemoteTransactionManager}. * * @since 14.0 */ public class RemoteTransactionManagerLookup implements TransactionManagerLookup { private static final RemoteTransactionManagerLookup INSTANCE = new RemoteTransactionManagerLookup(); private RemoteTransactionManagerLookup() { } public static TransactionManagerLookup getInstance() { return INSTANCE; } @Override public TransactionManager getTransactionManager() { return RemoteTransactionManager.getInstance(); } @Override public String toString() { return "RemoteTransactionManagerLookup"; } }
878
24.852941
103
java
null
infinispan-main/query-core/src/test/java/org/infinispan/query/core/tests/QueryCoreTest.java
package org.infinispan.query.core.tests; import static org.assertj.core.api.Assertions.assertThat; import static org.infinispan.functional.FunctionalTestUtils.await; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertTrue; import java.util.List; import org.infinispan.Cache; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.query.core.Search; import org.infinispan.query.core.stats.IndexStatistics; import org.infinispan.query.core.stats.QueryStatistics; import org.infinispan.query.core.stats.SearchStatistics; import org.infinispan.query.dsl.Query; import org.infinispan.query.dsl.QueryFactory; import org.infinispan.test.SingleCacheManagerTest; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.testng.annotations.Test; @Test(groups = "functional", testName = "query.core.tests.QueryCoreTest") public class QueryCoreTest extends SingleCacheManagerTest { private Cache<String, Person> cacheWithStats; private static class Person { private String _name; private String _surname; public String getName() { return _name; } public void setName(String name) { this._name = name; } public String getSurname() { return _surname; } public void setSurname(String surname) { this._surname = surname; } @Override public String toString() { return "Person{name='" + _name + "', surname='" + _surname + "'}"; } } @Override protected EmbeddedCacheManager createCacheManager() { ConfigurationBuilder c = getDefaultStandaloneCacheConfig(false); ConfigurationBuilder stat = getDefaultStandaloneCacheConfig(false); stat.statistics().enable(); EmbeddedCacheManager cm = TestCacheManagerFactory.createCacheManager(false); cm.defineConfiguration("test", c.build()); cm.defineConfiguration("stat", stat.build()); cache = cm.getCache("test"); cacheWithStats = cm.getCache("stat"); return cm; } public void testQuery() { Person spidey = new Person(); spidey.setName("Hombre"); spidey.setSurname("Araña"); cache.put("key1", spidey); Person superMujer = new Person(); superMujer.setName("Super"); superMujer.setSurname("Woman"); cache.put("key2", superMujer); assertEquals(2, cache.size()); QueryFactory queryFactory = Search.getQueryFactory(cache); Query<Person> query = queryFactory.create("from " + Person.class.getName() + " where name='Hombre'"); List<Person> results = query.execute().list(); assertEquals("Araña", results.get(0).getSurname()); } @Test public void testStats() { String q = String.format("FROM %s", Person.class.getName()); // Cache without stats enabled QueryFactory queryFactory = Search.getQueryFactory(cache); Query<Person> query = queryFactory.create(q); query.execute().list(); SearchStatistics searchStatistics = Search.getSearchStatistics(cache); QueryStatistics queryStatistics = searchStatistics.getQueryStatistics(); IndexStatistics indexStatistics = searchStatistics.getIndexStatistics(); assertTrue(await(indexStatistics.computeIndexInfos()).isEmpty()); assertTrue(await(Search.getClusteredSearchStatistics(cache)).getIndexStatistics().indexInfos().isEmpty()); assertEquals(0, queryStatistics.getNonIndexedQueryCount()); // Cache with stats enabled queryFactory = Search.getQueryFactory(cacheWithStats); query = queryFactory.create(String.format("FROM %s", Person.class.getName())); query.execute().list(); searchStatistics = Search.getSearchStatistics(cacheWithStats); queryStatistics = searchStatistics.getQueryStatistics(); indexStatistics = searchStatistics.getIndexStatistics(); assertTrue(await(indexStatistics.computeIndexInfos()).isEmpty()); assertTrue(await(Search.getClusteredSearchStatistics(cacheWithStats) .thenCompose(s -> s.getIndexStatistics().computeIndexInfos())).isEmpty()); assertEquals(1, queryStatistics.getNonIndexedQueryCount()); assertTrue(queryStatistics.getNonIndexedQueryAvgTime() > 0); assertTrue(queryStatistics.getNonIndexedQueryMaxTime() > 0); assertTrue(queryStatistics.getNonIndexedQueryTotalTime() > 0); assertEquals(q, queryStatistics.getSlowestNonIndexedQuery()); assertThat(indexStatistics.genericIndexingFailures()).isZero(); assertThat(indexStatistics.entityIndexingFailures()).isZero(); } }
4,686
34.778626
112
java
null
infinispan-main/query-core/src/test/java/org/infinispan/query/core/impl/MappingIteratorTest.java
package org.infinispan.query.core.impl; import java.util.Arrays; import java.util.List; import java.util.function.Function; import java.util.stream.StreamSupport; import org.infinispan.commons.util.Closeables; import org.testng.Assert; import org.testng.annotations.Test; @Test(groups = "unit", testName = "query.core.impl.MappingIteratorTest") public class MappingIteratorTest { private final List<Integer> integers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); @Test public void testIteration() { MappingIterator<Integer, String> mapIterator = createMappingIterator(integers); assertIterator(mapIterator, "1", "2", "3", "4", "5", "6", "7", "8", "9", "10"); mapIterator = createMappingIterator(integers).limit(0); assertIterator(mapIterator); mapIterator = createMappingIterator(integers).limit(2); assertIterator(mapIterator, "1", "2"); mapIterator = createMappingIterator(integers).limit(20); assertIterator(mapIterator, "1", "2", "3", "4", "5", "6", "7", "8", "9", "10"); mapIterator = createMappingIterator(integers).skip(4); assertIterator(mapIterator, "5", "6", "7", "8", "9", "10"); mapIterator = createMappingIterator(integers).skip(11); assertIterator(mapIterator); mapIterator = createMappingIterator(integers).skip(0).limit(10); assertIterator(mapIterator, "1", "2", "3", "4", "5", "6", "7", "8", "9", "10"); mapIterator = createMappingIterator(integers).skip(5).limit(2); assertIterator(mapIterator, "6", "7"); mapIterator = createMappingIterator(integers).skip(1).limit(1); assertIterator(mapIterator, "2"); mapIterator = createMappingIterator(integers).skip(50).limit(2); assertIterator(mapIterator); mapIterator = createMappingIterator(Arrays.asList(1, null, 3, null, 4)); assertIterator(mapIterator, "1", "3", "4"); mapIterator = createMappingIterator(Arrays.asList(1, null, 3, null, 4, 5, 6)).skip(1).limit(3); assertIterator(mapIterator, "3", "4", "5"); } @Test public void testFiltering() { Function<Integer, String> EVEN = integer -> integer % 2 != 0 ? null : String.valueOf(integer); Function<Integer, String> LT5 = integer -> integer < 5 ? String.valueOf(integer) : null; Function<Integer, String> ALL = String::valueOf; Function<Integer, String> NONE = integer -> null; MappingIterator<Integer, String> mappingIterator = createMappingIterator(integers, EVEN).skip(1); assertIterator(mappingIterator, "4", "6", "8", "10"); mappingIterator = createMappingIterator(integers, EVEN); assertIterator(mappingIterator, "2", "4", "6", "8", "10"); mappingIterator = createMappingIterator(integers, EVEN).skip(1); assertIterator(mappingIterator, "4", "6", "8", "10"); mappingIterator = createMappingIterator(integers, LT5); assertIterator(mappingIterator, "1", "2", "3", "4"); mappingIterator = createMappingIterator(integers, ALL); assertIterator(mappingIterator, "1", "2", "3", "4", "5", "6", "7", "8", "9", "10"); mappingIterator = createMappingIterator(integers, LT5).skip(1).limit(1); assertIterator(mappingIterator, "2"); mappingIterator = createMappingIterator(integers, LT5).skip(5).limit(10); assertIterator(mappingIterator); mappingIterator = createMappingIterator(integers, NONE); assertIterator(mappingIterator); } private MappingIterator<Integer, String> createMappingIterator(List<Integer> data) { return new MappingIterator<>(Closeables.iterator(data.iterator()), String::valueOf); } private MappingIterator<Integer, String> createMappingIterator(List<Integer> data, Function<Integer, String> fn) { return new MappingIterator<>(Closeables.iterator(data.iterator()), fn); } private void assertIterator(MappingIterator<Integer, String> iterator, String... expected) { Iterable<String> iterable = () -> iterator; Object[] elements = StreamSupport.stream(iterable.spliterator(), false).toArray(); Assert.assertEquals(elements, expected); } }
4,128
39.881188
117
java
null
infinispan-main/query-core/src/test/java/org/infinispan/query/core/stats/impl/LocalQueryStatisticsTest.java
package org.infinispan.query.core.stats.impl; import static org.infinispan.query.core.stats.impl.LocalQueryStatisticsTest.QueryType.HYBRID; import static org.infinispan.query.core.stats.impl.LocalQueryStatisticsTest.QueryType.INDEX_DISTRIBUTED; import static org.infinispan.query.core.stats.impl.LocalQueryStatisticsTest.QueryType.INDEX_LOCAL; import static org.infinispan.query.core.stats.impl.LocalQueryStatisticsTest.QueryType.NON_INDEXED; import static org.testng.AssertJUnit.assertEquals; import java.util.Map; import java.util.Map.Entry; import java.util.Random; import java.util.concurrent.BlockingQueue; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.LinkedBlockingDeque; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; import java.util.stream.LongStream; import org.testng.annotations.Test; @Test(groups = "unit", testName = "query.core.impl.LocalQueryStatisticsTest") public class LocalQueryStatisticsTest { public static final int THREADS = 10; public static final int MAX_SAMPLE_LATENCY = 10_000; public static final int SAMPLE_SIZE = 1_000_000; private static final Random RANDOM = new Random(0); enum QueryType {INDEX_LOCAL, INDEX_DISTRIBUTED, HYBRID, NON_INDEXED} private final Map<Query, Long> timePerQuery = LongStream.rangeClosed(1, SAMPLE_SIZE).boxed() .collect(Collectors.toMap(Query::random, l -> (long) RANDOM.nextInt(MAX_SAMPLE_LATENCY))); @Test public void testRecord() throws Exception { LocalQueryStatistics statistics = new LocalQueryStatistics(); ExecutorService executorService = Executors.newFixedThreadPool(THREADS); BlockingQueue<Entry<Query, Long>> data = new LinkedBlockingDeque<>(timePerQuery.entrySet()); CountDownLatch countDownLatch = new CountDownLatch(1); for (int i = 1; i <= THREADS; i++) { executorService.submit(() -> { try { countDownLatch.await(); while (!data.isEmpty()) { Entry<Query, Long> take = data.poll(1, TimeUnit.SECONDS); if (take == null) continue; Query q = take.getKey(); Long time = take.getValue(); switch (q.getType()) { case INDEX_LOCAL: statistics.localIndexedQueryExecuted(q.str, time); break; case HYBRID: statistics.hybridQueryExecuted(q.str, time); break; case INDEX_DISTRIBUTED: statistics.distributedIndexedQueryExecuted(q.str, time); break; case NON_INDEXED: statistics.nonIndexedQueryExecuted(q.str, time); break; } statistics.entityLoaded(time / 2); } } catch (InterruptedException ignored) { } }); } countDownLatch.countDown(); executorService.shutdown(); executorService.awaitTermination(30, TimeUnit.SECONDS); assertEquals(count(INDEX_LOCAL), statistics.getLocalIndexedQueryCount()); assertEquals(avg(INDEX_LOCAL), statistics.getLocalIndexedQueryAvgTime()); assertEquals(max(INDEX_LOCAL), statistics.getLocalIndexedQueryMaxTime()); assertEquals(slowestQuery(INDEX_LOCAL), statistics.getSlowestLocalIndexedQuery()); assertEquals(count(INDEX_DISTRIBUTED), statistics.getDistributedIndexedQueryCount()); assertEquals(avg(INDEX_DISTRIBUTED), statistics.getDistributedIndexedQueryAvgTime()); assertEquals(max(INDEX_DISTRIBUTED), statistics.getLocalIndexedQueryMaxTime()); assertEquals(slowestQuery(INDEX_DISTRIBUTED), statistics.getSlowestDistributedIndexedQuery()); assertEquals(count(HYBRID), statistics.getHybridQueryCount()); assertEquals(avg(HYBRID), statistics.getHybridQueryAvgTime()); assertEquals(max(HYBRID), statistics.getHybridQueryMaxTime()); assertEquals(slowestQuery(HYBRID), statistics.getSlowestHybridQuery()); assertEquals(count(NON_INDEXED), statistics.getNonIndexedQueryCount()); assertEquals(avg(NON_INDEXED), statistics.getNonIndexedQueryAvgTime()); assertEquals(max(NON_INDEXED), statistics.getNonIndexedQueryMaxTime()); assertEquals(slowestQuery(NON_INDEXED), statistics.getSlowestNonIndexedQuery()); assertEquals(SAMPLE_SIZE, statistics.getLoadCount()); } private long count(QueryType queryType) { return timePerQuery.entrySet().stream().filter(e -> e.getKey().getType().equals(queryType)).count(); } private double avg(QueryType queryType) { return timePerQuery.entrySet().stream() .filter(e -> e.getKey().getType().equals(queryType)) .map(Entry::getValue).collect(Collectors.averagingLong(l -> l)); } private long max(QueryType queryType) { return timePerQuery.entrySet().stream() .filter(e -> e.getKey().getType().equals(queryType)) .map(Entry::getValue).max(Long::compareTo).orElse(-1L); } private String slowestQuery(QueryType queryType) { return timePerQuery.entrySet().stream(). filter(e -> e.getKey().getType().equals(queryType)) .reduce((e1, e2) -> e1.getValue().compareTo(e2.getValue()) >= 0 ? e1 : e2) .map(e -> e.getKey().str).orElse(null); } static class Query { private final QueryType type; private final String str; public Query(QueryType type, String str) { this.type = type; this.str = str; } public QueryType getType() { return type; } public String getStr() { return str; } public static Query random(long q) { QueryType[] values = QueryType.values(); return new Query(values[RANDOM.nextInt(values.length)], String.valueOf(q)); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Query query = (Query) o; if (type != query.type) return false; return str.equals(query.str); } @Override public int hashCode() { int result = type.hashCode(); result = 31 * result + str.hashCode(); return result; } @Override public String toString() { return "Query{" + "type=" + type + ", q='" + str + '\'' + '}'; } } }
6,688
37.66474
106
java
null
infinispan-main/query-core/src/main/java/org/infinispan/query/core/Search.java
package org.infinispan.query.core; import java.util.Map; import java.util.concurrent.CompletionStage; import org.infinispan.AdvancedCache; import org.infinispan.Cache; import org.infinispan.factories.ComponentRegistry; import org.infinispan.notifications.cachelistener.filter.CacheEventFilterConverter; import org.infinispan.objectfilter.ObjectFilter; import org.infinispan.objectfilter.impl.ReflectionMatcher; import org.infinispan.query.api.continuous.ContinuousQuery; import org.infinispan.query.core.impl.EmbeddedQueryFactory; import org.infinispan.query.core.impl.QueryEngine; import org.infinispan.query.core.impl.continuous.ContinuousQueryImpl; import org.infinispan.query.core.impl.eventfilter.IckleCacheEventFilterConverter; import org.infinispan.query.core.impl.eventfilter.IckleFilterAndConverter; import org.infinispan.query.core.stats.SearchStatistics; import org.infinispan.query.core.stats.SearchStatisticsSnapshot; import org.infinispan.query.core.stats.impl.SearchStatsRetriever; import org.infinispan.query.dsl.Query; import org.infinispan.query.dsl.QueryFactory; import org.infinispan.security.AuthorizationManager; import org.infinispan.security.AuthorizationPermission; import org.infinispan.security.actions.SecurityActions; /** * <b>EXPERIMENTAL</b> * This is the entry point for the Infinispan index-less query API. It provides the {@link QueryFactory} which is your * starting point for building Ickle queries or DSL-based queries, continuous queries and event filters for unindexed * caches. * * @author anistor@redhat.com * @since 10.1 */ public final class Search { private Search() { // prevent instantiation } /** * Create an event filter out of an Ickle query string. */ public static <K, V> CacheEventFilterConverter<K, V, ObjectFilter.FilterResult> makeFilter(String queryString) { return makeFilter(queryString, null); } /** * Create an event filter out of an Ickle query string. */ public static <K, V> CacheEventFilterConverter<K, V, ObjectFilter.FilterResult> makeFilter(String queryString, Map<String, Object> namedParameters) { IckleFilterAndConverter<K, V> filterAndConverter = new IckleFilterAndConverter<>(queryString, namedParameters, ReflectionMatcher.class); return new IckleCacheEventFilterConverter<>(filterAndConverter); } /** * Create an event filter out of an Ickle query. */ public static <K, V> CacheEventFilterConverter<K, V, ObjectFilter.FilterResult> makeFilter(Query<?> query) { return makeFilter(query.getQueryString(), query.getParameters()); } /** * Obtain the query factory for building DSL based Ickle queries. */ public static QueryFactory getQueryFactory(Cache<?, ?> cache) { AdvancedCache<?, ?> advancedCache = getAdvancedCache(cache); QueryEngine<?> queryEngine = SecurityActions.getCacheComponentRegistry(advancedCache).getComponent(QueryEngine.class); if (queryEngine == null) { throw new IllegalStateException(QueryEngine.class.getName() + " not found in component registry"); } return new EmbeddedQueryFactory(queryEngine); } private static AdvancedCache<?, ?> getAdvancedCache(Cache<?, ?> cache) { if (cache == null) { throw new IllegalArgumentException("cache parameter must not be null"); } AdvancedCache<?, ?> advancedCache = cache.getAdvancedCache(); if (advancedCache == null) { throw new IllegalArgumentException("The given cache must expose an AdvancedCache"); } checkBulkReadPermission(advancedCache); return advancedCache; } /** * Obtain the {@link ContinuousQuery} object for a cache. */ public static <K, V> ContinuousQuery<K, V> getContinuousQuery(Cache<K, V> cache) { return new ContinuousQueryImpl<>(cache); } private static void checkBulkReadPermission(AdvancedCache<?, ?> cache) { AuthorizationManager authorizationManager = SecurityActions.getCacheAuthorizationManager(cache); if (authorizationManager != null) { authorizationManager.checkPermission(AuthorizationPermission.BULK_READ); } } private static SearchStatsRetriever getStatsRetriever(Cache<?, ?> cache) { AdvancedCache<?, ?> advancedCache = getAdvancedCache(cache); ComponentRegistry registry = SecurityActions.getCacheComponentRegistry(advancedCache); return registry.getComponent(SearchStatsRetriever.class); } /** * @return {@link SearchStatistics} for the Cache. */ public static SearchStatistics getSearchStatistics(Cache<?, ?> cache) { return getStatsRetriever(cache).getSearchStatistics(); } /** * @return {@link SearchStatistics} for the whole cluster combined. The returned object is a snapshot. */ public static CompletionStage<SearchStatisticsSnapshot> getClusteredSearchStatistics(Cache<?, ?> cache) { return getStatsRetriever(cache).getDistributedSearchStatistics(); } }
4,988
39.893443
152
java
null
infinispan-main/query-core/src/main/java/org/infinispan/query/core/impl/package-info.java
/** * Query-core implementation. * * @since 10.1 * @api.private */ package org.infinispan.query.core.impl;
112
13.125
39
java
null
infinispan-main/query-core/src/main/java/org/infinispan/query/core/impl/EmbeddedQueryBuilder.java
package org.infinispan.query.core.impl; import org.infinispan.query.dsl.Query; import org.infinispan.query.dsl.impl.BaseQueryBuilder; import org.infinispan.query.dsl.impl.QueryStringCreator; import org.infinispan.util.logging.LogFactory; /** * @author anistor@redhat.com * @since 7.0 */ final class EmbeddedQueryBuilder extends BaseQueryBuilder { private static final Log log = LogFactory.getLog(EmbeddedQueryBuilder.class, Log.class); private final QueryEngine<?> queryEngine; EmbeddedQueryBuilder(EmbeddedQueryFactory queryFactory, QueryEngine<?> queryEngine, String rootType) { super(queryFactory, rootType); this.queryEngine = queryEngine; } @Override public <T> Query<T> build() { QueryStringCreator generator = new QueryStringCreator(); String queryString = accept(generator); if (log.isTraceEnabled()) { log.tracef("Query string : %s", queryString); } return new DelegatingQuery<>(queryEngine, queryFactory, queryString, generator.getNamedParameters(), getProjectionPaths(), startOffset, maxResults, false); } }
1,100
32.363636
161
java
null
infinispan-main/query-core/src/main/java/org/infinispan/query/core/impl/ExternalizerIds.java
package org.infinispan.query.core.impl; //TODO [anistor] assign proper range /** * Identifiers used by the Marshaller to delegate to specialized Externalizers. For details, read * https://infinispan.org/docs/10.0.x/user_guide/user_guide.html#preassigned_externalizer_id_ranges * <p> * The range reserved for the Infinispan Query Core module is from 1600 to 1699. * * @author anistor@redhat.com * @since 10.1 */ public interface ExternalizerIds { Integer ICKLE_FILTER_AND_CONVERTER = 1600; Integer ICKLE_FILTER_RESULT = 1611; Integer ICKLE_CACHE_EVENT_FILTER_CONVERTER = 1614; Integer ICKLE_CONTINUOUS_QUERY_CACHE_EVENT_FILTER_CONVERTER = 1616; Integer ICKLE_CONTINUOUS_QUERY_RESULT = 1617; Integer ICKLE_DELETE_FUNCTION = 1618; }
763
27.296296
99
java
null
infinispan-main/query-core/src/main/java/org/infinispan/query/core/impl/Log.java
package org.infinispan.query.core.impl; import org.infinispan.commons.CacheException; import org.infinispan.objectfilter.ParsingException; import org.infinispan.partitionhandling.AvailabilityException; import org.jboss.logging.BasicLogger; import org.jboss.logging.Logger; import org.jboss.logging.annotations.Message; import org.jboss.logging.annotations.MessageLogger; import org.jboss.logging.annotations.ValidIdRange; //TODO [anistor] query-core and query modules share the id range now and in the future these loggers will probably merge /** * Log abstraction for the query-core module. For this module, message ids ranging from 14001 to 14500 inclusively have been * reserved. * * @author anistor@redhat.com * @since 10.1 */ @MessageLogger(projectCode = "ISPN") @ValidIdRange(min = 14001, max = 14500) public interface Log extends BasicLogger { String LOG_ROOT = "org.infinispan."; Log CONTAINER = Logger.getMessageLogger(Log.class, LOG_ROOT + "CONTAINER"); @Message(value = "Queries containing grouping and aggregation functions must use projections.", id = 14021) ParsingException groupingAndAggregationQueriesMustUseProjections(); @Message(value = "Cannot have aggregate functions in GROUP BY clause", id = 14022) IllegalStateException cannotHaveAggregationsInGroupByClause(); @Message(value = "Using the multi-valued property path '%s' in the GROUP BY clause is not currently supported", id = 14023) ParsingException multivaluedPropertyCannotBeUsedInGroupBy(String propertyPath); @Message(value = "The property path '%s' cannot be used in the ORDER BY clause because it is multi-valued", id = 14024) ParsingException multivaluedPropertyCannotBeUsedInOrderBy(String propertyPath); @Message(value = "The query must not use grouping or aggregation", id = 14025) IllegalStateException queryMustNotUseGroupingOrAggregation(); @Message(value = "The expression '%s' must be part of an aggregate function or it should be included in the GROUP BY clause", id = 14026) ParsingException expressionMustBePartOfAggregateFunctionOrShouldBeIncludedInGroupByClause(String propertyPath); @Message(value = "The property path '%s' cannot be projected because it is multi-valued", id = 14027) ParsingException multivaluedPropertyCannotBeProjected(String propertyPath); @Message(value = "Cannot execute query: cluster is operating in degraded mode and partition handling configuration doesn't allow reads and writes.", id = 14042) AvailabilityException partitionDegraded(); @Message(value = "Only DELETE statements are supported by executeStatement", id = 14056) CacheException unsupportedStatement(); @Message(value = "DELETE statements cannot use paging (firstResult/maxResults)", id = 14057) CacheException deleteStatementsCannotUsePaging(); @Message(value = "Projections are not supported with entryIterator()", id = 14058) CacheException entryIteratorDoesNotAllowProjections(); }
2,966
48.45
163
java
null
infinispan-main/query-core/src/main/java/org/infinispan/query/core/impl/SlicingCollector.java
package org.infinispan.query.core.impl; import java.util.Set; import java.util.function.BiConsumer; import java.util.function.BinaryOperator; import java.util.function.Function; import java.util.function.Supplier; import java.util.stream.Collector; /** * Delegates to the underlying collector only if item is inside the supplied window, while still keeping the count * of all items of the stream. * * @since 12.1 */ class SlicingCollector<U, A, R> implements Collector<U, A, R> { private final Collector<U, A, R> collector; private final long skip; private final long limit; private long count = 0; public SlicingCollector(Collector<U, A, R> collector, long skip, long limit) { this.collector = collector; this.skip = skip; this.limit = limit < 0 ? -1 : limit; } long getCount() { return count; } @Override public Supplier<A> supplier() { return collector.supplier(); } @Override public BiConsumer<A, U> accumulator() { BiConsumer<A, U> accumulator = collector.accumulator(); return (a, u) -> { count++; if (count > skip && (limit == -1 || count <= skip + limit)) accumulator.accept(a, u); }; } @Override public BinaryOperator<A> combiner() { return collector.combiner(); } @Override public Function<A, R> finisher() { return collector.finisher(); } @Override public Set<Characteristics> characteristics() { return collector.characteristics(); } }
1,527
23.645161
114
java
null
infinispan-main/query-core/src/main/java/org/infinispan/query/core/impl/EmbeddedQueryFactory.java
package org.infinispan.query.core.impl; import org.infinispan.query.dsl.QueryBuilder; import org.infinispan.query.dsl.impl.BaseQuery; import org.infinispan.query.dsl.impl.BaseQueryFactory; /** * @author anistor@redhat.com * @since 7.0 */ public final class EmbeddedQueryFactory extends BaseQueryFactory { private final QueryEngine<?> queryEngine; public EmbeddedQueryFactory(QueryEngine<?> queryEngine) { if (queryEngine == null) { throw new IllegalArgumentException("queryEngine cannot be null"); } this.queryEngine = queryEngine; } @Override public <T> BaseQuery<T> create(String queryString) { return new DelegatingQuery<>(queryEngine, this, queryString); } @Override public QueryBuilder from(Class<?> type) { return new EmbeddedQueryBuilder(this, queryEngine, type.getName()); } @Override public QueryBuilder from(String type) { return new EmbeddedQueryBuilder(this, queryEngine, type); } }
986
25.675676
74
java
null
infinispan-main/query-core/src/main/java/org/infinispan/query/core/impl/EmptyResultQuery.java
package org.infinispan.query.core.impl; import java.util.Arrays; import java.util.Comparator; import java.util.Map; import java.util.NoSuchElementException; import org.infinispan.AdvancedCache; import org.infinispan.commons.util.CloseableIterator; import org.infinispan.objectfilter.ObjectFilter; import org.infinispan.objectfilter.impl.syntax.parser.IckleParsingResult; import org.infinispan.query.core.stats.impl.LocalQueryStatistics; import org.infinispan.query.dsl.QueryFactory; import org.infinispan.util.logging.LogFactory; /** * A query that does not return any results because the query filter is a boolean contradiction. * * @author anistor@redhat.com * @since 8.0 */ public final class EmptyResultQuery<T> extends BaseEmbeddedQuery<T> { private static final Log LOG = LogFactory.getLog(EmptyResultQuery.class, Log.class); public EmptyResultQuery(QueryFactory queryFactory, AdvancedCache<?, ?> cache, String queryString, IckleParsingResult.StatementType statementType, Map<String, Object> namedParameters, long startOffset, int maxResults, LocalQueryStatistics queryStatistics) { super(queryFactory, cache, queryString, statementType, namedParameters, null, startOffset, maxResults, queryStatistics, false); } @Override protected void recordQuery(long time) { // this never got executed, we could record 0 but that would just pollute the stats } @Override protected Comparator<Comparable<?>[]> getComparator() { return null; } @Override protected CloseableIterator<ObjectFilter.FilterResult> getInternalIterator() { return new CloseableIterator<ObjectFilter.FilterResult>() { @Override public void close() { } @Override public boolean hasNext() { return false; } @Override public ObjectFilter.FilterResult next() { throw new NoSuchElementException(); } }; } @Override public int executeStatement() { if (isSelectStatement()) { throw LOG.unsupportedStatement(); } return 0; } @Override public String toString() { return "EmptyResultQuery{" + "queryString=" + queryString + ", statementType=" + statementType + ", namedParameters=" + namedParameters + ", projection=" + Arrays.toString(projection) + ", startOffset=" + startOffset + ", maxResults=" + maxResults + ", timeout=" + timeout + '}'; } }
2,622
30.22619
133
java
null
infinispan-main/query-core/src/main/java/org/infinispan/query/core/impl/EmbeddedQuery.java
package org.infinispan.query.core.impl; import java.io.ObjectInput; import java.io.ObjectOutput; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.concurrent.TimeUnit; import java.util.function.Function; import static org.infinispan.query.core.impl.Log.CONTAINER; import org.infinispan.AdvancedCache; import org.infinispan.CacheStream; import org.infinispan.commons.marshall.AdvancedExternalizer; import org.infinispan.commons.util.CloseableIterator; import org.infinispan.commons.util.Closeables; import org.infinispan.container.entries.CacheEntry; import org.infinispan.context.Flag; import org.infinispan.factories.annotations.Inject; import org.infinispan.factories.scopes.Scope; import org.infinispan.factories.scopes.Scopes; import org.infinispan.filter.CacheFilters; import org.infinispan.objectfilter.ObjectFilter; import org.infinispan.objectfilter.impl.syntax.parser.IckleParsingResult; import org.infinispan.query.core.impl.eventfilter.IckleFilterAndConverter; import org.infinispan.query.core.stats.impl.LocalQueryStatistics; import org.infinispan.query.dsl.QueryFactory; import org.infinispan.query.dsl.QueryResult; /** * Non-indexed embedded-mode query. * * @author anistor@redhat.com * @since 7.0 */ public final class EmbeddedQuery<T> extends BaseEmbeddedQuery<T> { private final QueryEngine<?> queryEngine; private IckleFilterAndConverter<?, ?> filter; private final int defaultMaxResults; public EmbeddedQuery(QueryEngine<?> queryEngine, QueryFactory queryFactory, AdvancedCache<?, ?> cache, String queryString, IckleParsingResult.StatementType statementType, Map<String, Object> namedParameters, String[] projection, long startOffset, int maxResults, int defaultMaxResults, LocalQueryStatistics queryStatistics, boolean local) { super(queryFactory, cache, queryString, statementType, namedParameters, projection, startOffset, maxResults, queryStatistics, local); this.queryEngine = queryEngine; this.defaultMaxResults = defaultMaxResults; if (maxResults == -1) { // apply the default super.maxResults = defaultMaxResults; } } @Override public void resetQuery() { super.resetQuery(); filter = null; } @Override protected void recordQuery(long time) { queryStatistics.nonIndexedQueryExecuted(queryString, time); } private IckleFilterAndConverter<?, ?> createFilter() { // filter is created first time only, or again if resetQuery was called meanwhile if (filter == null) { filter = queryEngine.createAndWireFilter(queryString, namedParameters); // force early query validation, at creation time, rather than deferring to execution time filter.getObjectFilter(); } return filter; } @Override protected Comparator<Comparable<?>[]> getComparator() { return createFilter().getObjectFilter().getComparator(); } @Override protected CloseableIterator<ObjectFilter.FilterResult> getInternalIterator() { IckleFilterAndConverter<Object, Object> ickleFilter = (IckleFilterAndConverter<Object, Object>) createFilter(); AdvancedCache<Object, Object> cache = (AdvancedCache<Object, Object>) (isLocal() ? this.cache.withFlags(Flag.CACHE_MODE_LOCAL) : this.cache); CacheStream<CacheEntry<Object, Object>> entryStream = cache.cacheEntrySet().stream(); if (timeout > 0) { entryStream = entryStream.timeout(timeout, TimeUnit.NANOSECONDS); } CacheStream<ObjectFilter.FilterResult> resultStream = CacheFilters.filterAndConvertToValue(entryStream, ickleFilter); if (timeout > 0) { resultStream = resultStream.timeout(timeout, TimeUnit.NANOSECONDS); } return Closeables.iterator(resultStream); } @Override public QueryResult<T> execute() { if (isSelectStatement()) { return super.execute(); } return new QueryResultImpl<>(executeStatement(), Collections.emptyList()); } @Override public int executeStatement() { if (isSelectStatement()) { throw CONTAINER.unsupportedStatement(); } if (getStartOffset() != 0 || getMaxResults() != defaultMaxResults) { throw CONTAINER.deleteStatementsCannotUsePaging(); } IckleFilterAndConverter<Object, Object> ickleFilter = (IckleFilterAndConverter<Object, Object>) createFilter(); AdvancedCache<Object, Object> cache = (AdvancedCache<Object, Object>) (isLocal() ? this.cache.withFlags(Flag.CACHE_MODE_LOCAL) : this.cache); CacheStream<CacheEntry<Object, Object>> entryStream = cache.cacheEntrySet().stream(); if (timeout > 0) { entryStream = entryStream.timeout(timeout, TimeUnit.NANOSECONDS); } CacheStream<?> filteredKeyStream = CacheFilters.filterAndConvertToKey(entryStream, ickleFilter); if (timeout > 0) { filteredKeyStream = filteredKeyStream.timeout(timeout, TimeUnit.NANOSECONDS); } Optional<Integer> count = filteredKeyStream.map(new DeleteFunction()).reduce(Integer::sum); filteredKeyStream.close(); return count.orElse(0); } @Scope(Scopes.NONE) static final class DeleteFunction implements Function<Object, Integer> { @Inject AdvancedCache<?,?> cache; @Override public Integer apply(Object key) { key = cache.getKeyDataConversion().fromStorage(key); return cache.remove(key) == null ? 0 : 1; } } public static final class DeleteFunctionExternalizer implements AdvancedExternalizer<DeleteFunction> { @Override public void writeObject(ObjectOutput output, DeleteFunction object) { } @Override public DeleteFunction readObject(ObjectInput input) { return new DeleteFunction(); } @Override public Set<Class<? extends DeleteFunction>> getTypeClasses() { return Collections.singleton(DeleteFunction.class); } @Override public Integer getId() { return ExternalizerIds.ICKLE_DELETE_FUNCTION; } }; @Override public String toString() { return "EmbeddedQuery{" + "queryString=" + queryString + ", statementType=" + statementType + ", namedParameters=" + namedParameters + ", projection=" + Arrays.toString(projection) + ", startOffset=" + startOffset + ", maxResults=" + maxResults + ", defaultMaxResults=" + defaultMaxResults + ", timeout=" + timeout + '}'; } }
6,734
34.078125
147
java
null
infinispan-main/query-core/src/main/java/org/infinispan/query/core/impl/QueryCache.java
package org.infinispan.query.core.impl; import java.util.EnumSet; import java.util.List; import java.util.Optional; import java.util.concurrent.TimeUnit; import org.infinispan.Cache; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.factories.annotations.Inject; import org.infinispan.factories.scopes.Scope; import org.infinispan.factories.scopes.Scopes; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.objectfilter.impl.aggregation.FieldAccumulator; import org.infinispan.registry.InternalCacheRegistry; import org.infinispan.transaction.TransactionMode; import org.infinispan.util.logging.LogFactory; import net.jcip.annotations.ThreadSafe; /** * A local cache for 'parsed' queries. Each cache manager has at most one QueryCache which is backed by a lazily created * Cache. * * @author anistor@redhat.com * @since 7.0 */ @ThreadSafe @Scope(Scopes.GLOBAL) public final class QueryCache { @FunctionalInterface public interface QueryCreator<Q> { /** * Create a new query object based on the input args, or just return {@code null}. If {@code null} is returned * this will be propagated to the caller of {@link QueryCache#get} and the {@code null} will not be cached. */ Q create(String queryString, List<FieldAccumulator> accumulators); } private static final Log log = LogFactory.getLog(QueryCache.class, Log.class); /** * Users can define a cache configuration with this name if they need to fine tune query caching. If they do not do * so a default config is used (see {@link QueryCache#getQueryCacheConfig()}). */ public static final String QUERY_CACHE_NAME = "___query_cache"; /** * Max number of cached entries. */ private static final long MAX_ENTRIES = 200; /** * Cache entry lifespan in seconds. */ private static final long ENTRY_LIFESPAN = 300; @Inject EmbeddedCacheManager cacheManager; @Inject InternalCacheRegistry internalCacheRegistry; private volatile Cache<QueryCacheKey, Object> lazyCache; /** * Gets the cached query object. The key used for lookup is an object pair containing the query string and a * discriminator value which is usually the Class of the cached query object and an optional {@link List} of {@link * FieldAccumulator}s. */ public <T> T get(String cacheName, String queryString, List<FieldAccumulator> accumulators, Object queryTypeDiscriminator, QueryCreator<T> queryCreator) { QueryCacheKey key = new QueryCacheKey(cacheName, queryString, accumulators, queryTypeDiscriminator); return (T) getOptionalCache(true).map(c -> c.computeIfAbsent(key, (k) -> queryCreator.create(k.queryString, k.accumulators))).orElse(null); } public void clear() { log.debug("Clearing query cache for all caches"); getOptionalCache(false).ifPresent(Cache::clear); } public void clear(String cacheName) { log.debugf("Clearing query cache for cache %s", cacheName); getOptionalCache(false).ifPresent(c -> c.keySet().removeIf(k -> k.cacheName.equals(cacheName))); } /** * Obtain and return the cache, starting it lazily if needed. */ private Optional<Cache<QueryCacheKey, Object>> getOptionalCache(boolean createIfAbsent) { Cache<QueryCacheKey, Object> cache = lazyCache; if (createIfAbsent && cache == null) { synchronized (this) { if (lazyCache == null) { // define the query cache configuration if it does not already exist (from a previous call or manually defined by the user) internalCacheRegistry.registerInternalCache(QUERY_CACHE_NAME, getQueryCacheConfig().build(), EnumSet.noneOf(InternalCacheRegistry.Flag.class)); lazyCache = cacheManager.getCache(QUERY_CACHE_NAME); } cache = lazyCache; } } return Optional.ofNullable(cache); } /** * Create the configuration of the internal query cache. */ private ConfigurationBuilder getQueryCacheConfig() { ConfigurationBuilder cfgBuilder = new ConfigurationBuilder(); cfgBuilder .clustering().cacheMode(CacheMode.LOCAL) .transaction().transactionMode(TransactionMode.NON_TRANSACTIONAL) .expiration().maxIdle(ENTRY_LIFESPAN, TimeUnit.SECONDS) .memory().maxCount(MAX_ENTRIES); return cfgBuilder; } /** * The key of the query cache: a tuple with 3 components. Serialization of this object is not expected as the cache * is local and there is no store configured. */ private static final class QueryCacheKey { final String cacheName; final String queryString; final List<FieldAccumulator> accumulators; final Object queryTypeDiscriminator; QueryCacheKey(String cacheName, String queryString, List<FieldAccumulator> accumulators, Object queryTypeDiscriminator) { this.cacheName = cacheName; this.queryString = queryString; this.accumulators = accumulators; this.queryTypeDiscriminator = queryTypeDiscriminator; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (!(obj instanceof QueryCacheKey)) return false; QueryCacheKey other = (QueryCacheKey) obj; return cacheName.equals(other.cacheName) && queryString.equals(other.queryString) && (accumulators != null ? accumulators.equals(other.accumulators) : other.accumulators == null) && queryTypeDiscriminator.equals(other.queryTypeDiscriminator); } @Override public int hashCode() { int result = cacheName.hashCode(); result = 31 * result + queryString.hashCode(); result = 31 * result + (accumulators != null ? accumulators.hashCode() : 0); result = 31 * result + queryTypeDiscriminator.hashCode(); return result; } @Override public String toString() { return "QueryCacheKey{" + "cacheName='" + cacheName + '\'' + ", queryString='" + queryString + '\'' + ", accumulators=" + accumulators + ", queryTypeDiscriminator=" + queryTypeDiscriminator + '}'; } } }
6,402
36.226744
158
java
null
infinispan-main/query-core/src/main/java/org/infinispan/query/core/impl/TimedCollector.java
package org.infinispan.query.core.impl; import java.util.Set; import java.util.function.BiConsumer; import java.util.function.BinaryOperator; import java.util.function.Function; import java.util.function.Supplier; import java.util.stream.Collector; import org.infinispan.commons.time.DefaultTimeService; import org.infinispan.commons.time.TimeService; import org.infinispan.query.SearchTimeoutException; /** * @since 11.0 */ class TimedCollector<U, A, R> implements Collector<U, A, R> { private final Collector<U, A, R> collector; private final long timeout; private static final TimeService TIME_SERVICE = DefaultTimeService.INSTANCE; public TimedCollector(Collector<U, A, R> collector, long timeout) { this.collector = collector; this.timeout = timeout; } @Override public Supplier<A> supplier() { return collector.supplier(); } @Override public BiConsumer<A, U> accumulator() { BiConsumer<A, U> accumulator = collector.accumulator(); if (timeout < 0) return accumulator; return new BiConsumer<A, U>() { int index = 0; long limit = TIME_SERVICE.time() + timeout; boolean divBy32(int i) { return (i & ((1 << 5) - 1)) == 0; } @Override public void accept(A a, U u) { if (divBy32(index++) && TIME_SERVICE.isTimeExpired(limit)) { throw new SearchTimeoutException(); } accumulator.accept(a, u); } }; } @Override public BinaryOperator<A> combiner() { return collector.combiner(); } @Override public Function<A, R> finisher() { return collector.finisher(); } @Override public Set<Characteristics> characteristics() { return collector.characteristics(); } }
1,814
24.208333
79
java
null
infinispan-main/query-core/src/main/java/org/infinispan/query/core/impl/QueryResultImpl.java
package org.infinispan.query.core.impl; import java.util.Collections; import java.util.List; import org.infinispan.query.dsl.QueryResult; import org.infinispan.query.dsl.TotalHitCount; /** * @since 11.0 */ public final class QueryResultImpl<E> implements QueryResult<E> { public static final QueryResult<?> EMPTY = new QueryResultImpl<>(TotalHitCount.EMPTY, Collections.emptyList()); private final TotalHitCount count; private final List<E> list; public QueryResultImpl(int hitCount, List<E> list) { this(new TotalHitCount(hitCount, true), list); } public QueryResultImpl(TotalHitCount count, List<E> list) { this.count = count; this.list = list; } @Override public TotalHitCount count() { return count; } @Override public List<E> list() { return list; } }
837
21.052632
114
java
null
infinispan-main/query-core/src/main/java/org/infinispan/query/core/impl/MappingIterator.java
package org.infinispan.query.core.impl; import java.util.NoSuchElementException; import java.util.function.Function; import org.infinispan.commons.util.CloseableIterator; /** * A {@link CloseableIterator} decorator that can be sliced and have its elements transformed. * * @param <S> Type of the original iterator * @param <T> Resulting type * @since 11.0 */ public final class MappingIterator<S, T> implements CloseableIterator<T> { private final CloseableIterator<S> iterator; private final Function<? super S, ? extends T> mapper; private long skip = 0; private long max = -1; private T current; private long index; public MappingIterator(CloseableIterator<S> iterator, Function<? super S, ? extends T> mapper) { this.iterator = iterator; this.mapper = mapper; } public MappingIterator(CloseableIterator<S> iterator) { this.iterator = iterator; this.mapper = null; } @Override public boolean hasNext() { updateNext(); return current != null; } @Override public T next() { if (hasNext()) { T element = current; current = null; return element; } else { throw new NoSuchElementException(); } } private void updateNext() { while (current == null && iterator.hasNext()) { T mapped = transform(iterator.next()); if (mapped != null) { index++; } if (index > skip && (max == -1 || index <= skip + max)) { current = mapped; } } } private T transform(S s) { if (s == null) { return null; } if (mapper == null) { return (T) s; } return mapper.apply(s); } public MappingIterator<S, T> skip(long skip) { this.skip = skip; return this; } public MappingIterator<S, T> limit(long max) { this.max = max; return this; } @Override public void close() { iterator.close(); } }
2,011
21.10989
99
java
null
infinispan-main/query-core/src/main/java/org/infinispan/query/core/impl/BaseEmbeddedQuery.java
package org.infinispan.query.core.impl; import static java.util.Spliterators.spliteratorUnknownSize; import static java.util.stream.Collector.Characteristics.IDENTITY_FINISH; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Map; import java.util.PriorityQueue; import java.util.stream.Collector; import java.util.stream.Collectors; import java.util.stream.StreamSupport; import org.infinispan.AdvancedCache; import org.infinispan.commons.util.CloseableIterator; import org.infinispan.commons.util.Closeables; import org.infinispan.objectfilter.ObjectFilter.FilterResult; import org.infinispan.objectfilter.impl.syntax.parser.IckleParsingResult; import org.infinispan.query.core.stats.impl.LocalQueryStatistics; import org.infinispan.query.dsl.QueryFactory; import org.infinispan.query.dsl.QueryResult; import org.infinispan.query.dsl.impl.BaseQuery; import org.infinispan.query.dsl.impl.logging.Log; import org.jboss.logging.Logger; /** * Base class for embedded-mode query implementations. Subclasses need to implement {@link #getInternalIterator()} and * {@link #getComparator()} methods and this class will take care of sorting (fully in-memory). * * @author anistor@redhat.com * @since 8.0 */ public abstract class BaseEmbeddedQuery<T> extends BaseQuery<T> { private static final Log log = Logger.getMessageLogger(Log.class, BaseEmbeddedQuery.class.getName()); /** * Initial capacity of the collection used for collecting results when performing internal sorting. */ private static final int INITIAL_CAPACITY = 1000; protected final IckleParsingResult.StatementType statementType; protected final AdvancedCache<?, ?> cache; protected final PartitionHandlingSupport partitionHandlingSupport; protected final LocalQueryStatistics queryStatistics; protected BaseEmbeddedQuery(QueryFactory queryFactory, AdvancedCache<?, ?> cache, String queryString, IckleParsingResult.StatementType statementType, Map<String, Object> namedParameters, String[] projection, long startOffset, int maxResults, LocalQueryStatistics queryStatistics, boolean local) { super(queryFactory, queryString, namedParameters, projection, startOffset, maxResults, local); this.statementType = statementType; this.cache = cache; this.partitionHandlingSupport = new PartitionHandlingSupport(cache); this.queryStatistics = queryStatistics; } @Override public void resetQuery() { } @Override public List<T> list() { return execute().list(); } protected abstract void recordQuery(long time); @Override public QueryResult<T> execute() { partitionHandlingSupport.checkCacheAvailable(); long start = queryStatistics.isEnabled() ? System.nanoTime() : 0; QueryResult<T> result = executeInternal(getComparator()); if (queryStatistics.isEnabled()) recordQuery(start); return result; } @Override public CloseableIterator<T> iterator() { partitionHandlingSupport.checkCacheAvailable(); Comparator<Comparable<?>[]> comparator = getComparator(); if (comparator == null) { MappingIterator<FilterResult, Object> iterator = new MappingIterator<>(getInternalIterator(), this::mapFilterResult); return (CloseableIterator<T>) iterator; } QueryResult<T> result = executeInternal(comparator); return Closeables.iterator(result.list().iterator()); } private QueryResult<T> executeInternal(Comparator<Comparable<?>[]> comparator) { List<Object> results; try (CloseableIterator<FilterResult> iterator = getInternalIterator()) { if (!iterator.hasNext()) { return (QueryResult<T>) QueryResultImpl.EMPTY; } else { if (comparator == null) { final SlicingCollector<Object, Object, List<Object>> collector = new SlicingCollector<>(new TimedCollector<>(Collectors.toList(), timeout), startOffset, maxResults); results = StreamSupport.stream(spliteratorUnknownSize(iterator, 0), false) .map(this::mapFilterResult) .collect(collector); return new QueryResultImpl((int) collector.getCount(), results); } else { log.warnPerfSortedNonIndexed(queryString); final int[] count = new int[1]; // Collect and sort results in a PriorityQueue, in reverse order for now. We'll reverse them again before returning. // We keep the FilterResult wrapper in the queue rather than the actual value because we need FilterResult.getSortProjection() to perform sorting. PriorityQueue<FilterResult> queue = StreamSupport.stream(spliteratorUnknownSize(iterator, 0), false) .peek(filterResult -> count[0]++) .collect(new TimedCollector<>(Collector.of(() -> new PriorityQueue<>(INITIAL_CAPACITY, new ReverseFilterResultComparator(comparator)), this::addToPriorityQueue, (q1, q2) -> q1, IDENTITY_FINISH), timeout)); // trim the results that are outside of the requested range and reverse them int queueSize = count[0]; if (queue.size() > startOffset) { Object[] res = new Object[queue.size() - startOffset]; int i = queue.size(); while (i-- > startOffset) { FilterResult r = queue.remove(); res[i - startOffset] = mapFilterResult(r); } results = Arrays.asList(res); } else { results = Collections.emptyList(); } return new QueryResultImpl<>(queueSize, (List<T>) results); } } } } private void addToPriorityQueue(PriorityQueue<FilterResult> queue, FilterResult filterResult) { queue.add(filterResult); if (maxResults != -1 && queue.size() > startOffset + maxResults) { // remove the head, which is actually the lowest ranking result because the queue is reversed (initially) queue.remove(); } } /** * Create a comparator to be used for ordering the results returned by {@link #getInternalIterator()}. * * @return the comparator or {@code null} if no sorting needs to be applied */ protected abstract Comparator<Comparable<?>[]> getComparator(); /** * Create an iterator over the results of the query, in no particular order. Ordering will be provided if {@link * #getComparator()} returns a non-null {@link Comparator}. Please note this it not the same iterator as the one * retuend by {@link #iterator()}. */ protected abstract CloseableIterator<FilterResult> getInternalIterator(); @Override public int getResultSize() { int count = 0; try (CloseableIterator<?> iterator = getInternalIterator()) { while (iterator.hasNext()) { iterator.next(); count++; } } return count; } private Object mapFilterResult(FilterResult result) { return projection != null ? result.getProjection() : result.getInstance(); } protected boolean isSelectStatement() { return statementType == IckleParsingResult.StatementType.SELECT; } @Override public String toString() { return "BaseEmbeddedQuery{" + "queryString=" + queryString + ", statementType=" + statementType + ", namedParameters=" + namedParameters + ", projection=" + Arrays.toString(projection) + ", startOffset=" + startOffset + ", maxResults=" + maxResults + ", timeout=" + timeout + '}'; } /** * Compares two {@link FilterResult} objects based on a given {@link Comparator} and reverses the * result. */ private static final class ReverseFilterResultComparator implements Comparator<FilterResult> { private final Comparator<Comparable<?>[]> comparator; private ReverseFilterResultComparator(Comparator<Comparable<?>[]> comparator) { this.comparator = comparator; } @Override public int compare(FilterResult o1, FilterResult o2) { return -comparator.compare(o1.getSortProjection(), o2.getSortProjection()); } } }
8,524
38.836449
161
java
null
infinispan-main/query-core/src/main/java/org/infinispan/query/core/impl/QueryEngine.java
package org.infinispan.query.core.impl; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import org.infinispan.AdvancedCache; import org.infinispan.objectfilter.Matcher; import org.infinispan.objectfilter.ObjectFilter; import org.infinispan.objectfilter.SortField; import org.infinispan.objectfilter.impl.BaseMatcher; import org.infinispan.objectfilter.impl.ReflectionMatcher; import org.infinispan.objectfilter.impl.RowMatcher; import org.infinispan.objectfilter.impl.aggregation.FieldAccumulator; import org.infinispan.objectfilter.impl.ql.AggregationFunction; import org.infinispan.objectfilter.impl.ql.PropertyPath; import org.infinispan.objectfilter.impl.syntax.AggregationExpr; import org.infinispan.objectfilter.impl.syntax.AndExpr; import org.infinispan.objectfilter.impl.syntax.BooleanExpr; import org.infinispan.objectfilter.impl.syntax.BooleanFilterNormalizer; import org.infinispan.objectfilter.impl.syntax.ComparisonExpr; import org.infinispan.objectfilter.impl.syntax.ConstantBooleanExpr; import org.infinispan.objectfilter.impl.syntax.ConstantValueExpr; import org.infinispan.objectfilter.impl.syntax.ExprVisitor; import org.infinispan.objectfilter.impl.syntax.FullTextVisitor; import org.infinispan.objectfilter.impl.syntax.IsNullExpr; import org.infinispan.objectfilter.impl.syntax.LikeExpr; import org.infinispan.objectfilter.impl.syntax.NotExpr; import org.infinispan.objectfilter.impl.syntax.OrExpr; import org.infinispan.objectfilter.impl.syntax.PropertyValueExpr; import org.infinispan.objectfilter.impl.syntax.SyntaxTreePrinter; import org.infinispan.objectfilter.impl.syntax.ValueExpr; import org.infinispan.objectfilter.impl.syntax.parser.AggregationPropertyPath; import org.infinispan.objectfilter.impl.syntax.parser.IckleParser; import org.infinispan.objectfilter.impl.syntax.parser.IckleParsingResult; import org.infinispan.objectfilter.impl.syntax.parser.ObjectPropertyHelper; import org.infinispan.objectfilter.impl.syntax.parser.RowPropertyHelper; import org.infinispan.query.core.impl.eventfilter.IckleFilterAndConverter; import org.infinispan.query.core.stats.impl.LocalQueryStatistics; import org.infinispan.query.dsl.Query; import org.infinispan.query.dsl.QueryFactory; import org.infinispan.query.dsl.impl.BaseQuery; import org.infinispan.query.dsl.impl.QueryStringCreator; import org.infinispan.security.actions.SecurityActions; import org.infinispan.util.logging.LogFactory; /** * Builds Query object implementations based on an Ickle query string. * * @param <TypeMetadata> the metadata of the indexed entities, either a java.lang.Class or an * org.infinispan.protostream.descriptors.Descriptor */ public class QueryEngine<TypeMetadata> { private static final Log log = LogFactory.getLog(QueryEngine.class, Log.class); protected final AdvancedCache<?, ?> cache; protected final Matcher matcher; protected final Class<? extends Matcher> matcherImplClass; protected final ObjectPropertyHelper<TypeMetadata> propertyHelper; /** * Optional cache for internal intermediate query objects, to save some query parsing. */ protected final QueryCache queryCache; private final int defaultMaxResults; protected LocalQueryStatistics queryStatistics; protected static final BooleanFilterNormalizer booleanFilterNormalizer = new BooleanFilterNormalizer(); protected QueryEngine(AdvancedCache<?, ?> cache, Class<? extends Matcher> matcherImplClass) { this.cache = cache; this.matcherImplClass = matcherImplClass; this.queryCache = SecurityActions.getGlobalComponentRegistry(cache.getCacheManager()).getComponent(QueryCache.class); this.queryStatistics = SecurityActions.getCacheComponentRegistry(cache).getComponent(LocalQueryStatistics.class); this.matcher = SecurityActions.getCacheComponentRegistry(cache).getComponent(matcherImplClass); this.defaultMaxResults = cache.getCacheConfiguration().query().defaultMaxResults(); propertyHelper = ((BaseMatcher<TypeMetadata, ?, ?>) matcher).getPropertyHelper(); } QueryEngine(AdvancedCache<?, ?> cache) { this(cache, ReflectionMatcher.class); } public Query<?> buildQuery(QueryFactory queryFactory, IckleParsingResult<TypeMetadata> parsingResult, Map<String, Object> namedParameters, long startOffset, int maxResults, boolean local) { if (log.isDebugEnabled()) { log.debugf("Building query '%s' with parameters %s", parsingResult.getQueryString(), namedParameters); } BaseQuery<?> query = parsingResult.hasGroupingOrAggregations() ? buildQueryWithAggregations(queryFactory, parsingResult.getQueryString(), namedParameters, startOffset, maxResults, parsingResult, local) : buildQueryNoAggregations(queryFactory, parsingResult.getQueryString(), namedParameters, startOffset, maxResults, parsingResult, local); query.validateNamedParameters(); return query; } protected BaseQuery<?> buildQueryWithAggregations(QueryFactory queryFactory, String queryString, Map<String, Object> namedParameters, long startOffset, int maxResults, IckleParsingResult<TypeMetadata> parsingResult, boolean local) { if (parsingResult.getProjectedPaths() == null) { throw log.groupingAndAggregationQueriesMustUseProjections(); } LinkedHashMap<PropertyPath, RowPropertyHelper.ColumnMetadata> columns = new LinkedHashMap<>(); if (parsingResult.getGroupBy() != null) { for (PropertyPath<?> p : parsingResult.getGroupBy()) { if (p instanceof AggregationPropertyPath) { throw log.cannotHaveAggregationsInGroupByClause(); // should not really be possible because this was validated during parsing } // Duplicates in 'group by' are accepted and silently discarded. This behaviour is similar to SQL. if (!columns.containsKey(p)) { if (propertyHelper.isRepeatedProperty(parsingResult.getTargetEntityMetadata(), p.asArrayPath())) { // this constraint will be relaxed later: https://issues.jboss.org/browse/ISPN-6015 throw log.multivaluedPropertyCannotBeUsedInGroupBy(p.toString()); } Class<?> propertyType = propertyHelper.getPrimitivePropertyType(parsingResult.getTargetEntityMetadata(), p.asArrayPath()); int idx = columns.size(); columns.put(p, new RowPropertyHelper.ColumnMetadata(idx, "C" + idx, propertyType)); } } } final int noOfGroupingColumns = columns.size(); for (int i = 0; i < parsingResult.getProjectedPaths().length; i++) { PropertyPath<?> p = parsingResult.getProjectedPaths()[i]; RowPropertyHelper.ColumnMetadata c = columns.get(p); if (!(p instanceof AggregationPropertyPath)) { // this must be an already processed 'group by' field, or else it's an invalid query if (c == null || c.getColumnIndex() >= noOfGroupingColumns) { throw log.expressionMustBePartOfAggregateFunctionOrShouldBeIncludedInGroupByClause(p.toString()); } } if (c == null) { Class<?> propertyType = FieldAccumulator.getOutputType(((AggregationPropertyPath) p).getAggregationFunction(), parsingResult.getProjectedTypes()[i]); int idx = columns.size(); columns.put(p, new RowPropertyHelper.ColumnMetadata(idx, "C" + idx, propertyType)); } } if (parsingResult.getSortFields() != null) { for (SortField sortField : parsingResult.getSortFields()) { PropertyPath<?> p = sortField.getPath(); RowPropertyHelper.ColumnMetadata c = columns.get(p); if (!(p instanceof AggregationPropertyPath)) { // this must be an already processed 'group by' field, or else it's an invalid query if (c == null || c.getColumnIndex() >= noOfGroupingColumns) { throw log.expressionMustBePartOfAggregateFunctionOrShouldBeIncludedInGroupByClause(p.toString()); } } if (c == null) { Class<?> propertyType = propertyHelper.getPrimitivePropertyType(parsingResult.getTargetEntityMetadata(), p.asArrayPath()); int idx = columns.size(); columns.put(p, new RowPropertyHelper.ColumnMetadata(idx, "C" + idx, propertyType)); } } } String havingClause = null; if (parsingResult.getHavingClause() != null) { BooleanExpr normalizedHavingClause = booleanFilterNormalizer.normalize(parsingResult.getHavingClause()); if (normalizedHavingClause == ConstantBooleanExpr.FALSE) { return new EmptyResultQuery<>(queryFactory, cache, queryString, parsingResult.getStatementType(), namedParameters, startOffset, maxResults, queryStatistics); } if (normalizedHavingClause != ConstantBooleanExpr.TRUE) { havingClause = SyntaxTreePrinter.printTree(swapVariables(normalizedHavingClause, parsingResult.getTargetEntityMetadata(), columns, namedParameters, propertyHelper)); } } // validity of query is established at this point, no more checks needed for (PropertyPath<?> p : columns.keySet()) { if (propertyHelper.isRepeatedProperty(parsingResult.getTargetEntityMetadata(), p.asArrayPath())) { return buildQueryWithRepeatedAggregations(queryFactory, queryString, namedParameters, startOffset, maxResults, parsingResult, havingClause, columns, noOfGroupingColumns, local); } } LinkedHashMap<String, Integer> inColumns = new LinkedHashMap<>(); List<FieldAccumulator> accumulators = new LinkedList<>(); RowPropertyHelper.ColumnMetadata[] _columns = new RowPropertyHelper.ColumnMetadata[columns.size()]; for (PropertyPath<?> p : columns.keySet()) { RowPropertyHelper.ColumnMetadata c = columns.get(p); _columns[c.getColumnIndex()] = c; String asStringPath = p.asStringPath(); Integer inIdx = inColumns.get(asStringPath); if (inIdx == null) { inIdx = inColumns.size(); inColumns.put(asStringPath, inIdx); } if (p instanceof AggregationPropertyPath) { FieldAccumulator acc = FieldAccumulator.makeAccumulator(((AggregationPropertyPath) p).getAggregationFunction(), inIdx, c.getColumnIndex(), c.getPropertyType()); accumulators.add(acc); } } StringBuilder firstPhaseQuery = new StringBuilder(); firstPhaseQuery.append("SELECT "); { boolean isFirst = true; for (String p : inColumns.keySet()) { if (isFirst) { isFirst = false; } else { firstPhaseQuery.append(", "); } firstPhaseQuery.append(QueryStringCreator.DEFAULT_ALIAS).append('.').append(p); } } firstPhaseQuery.append(" FROM ").append(parsingResult.getTargetEntityName()).append(' ').append(QueryStringCreator.DEFAULT_ALIAS); if (parsingResult.getWhereClause() != null) { // the WHERE clause should not touch aggregated fields BooleanExpr normalizedWhereClause = booleanFilterNormalizer.normalize(parsingResult.getWhereClause()); if (normalizedWhereClause == ConstantBooleanExpr.FALSE) { return new EmptyResultQuery<>(queryFactory, cache, queryString, parsingResult.getStatementType(), namedParameters, startOffset, maxResults, queryStatistics); } if (normalizedWhereClause != ConstantBooleanExpr.TRUE) { firstPhaseQuery.append(' ').append(SyntaxTreePrinter.printTree(normalizedWhereClause)); } } StringBuilder secondPhaseQuery = new StringBuilder(); secondPhaseQuery.append("SELECT "); { for (int i = 0; i < parsingResult.getProjectedPaths().length; i++) { PropertyPath<?> p = parsingResult.getProjectedPaths()[i]; RowPropertyHelper.ColumnMetadata c = columns.get(p); if (i != 0) { secondPhaseQuery.append(", "); } secondPhaseQuery.append(c.getColumnName()); } } secondPhaseQuery.append(" FROM Row "); if (havingClause != null) { secondPhaseQuery.append(' ').append(havingClause); } if (parsingResult.getSortFields() != null) { secondPhaseQuery.append(" ORDER BY "); boolean isFirst = true; for (SortField sortField : parsingResult.getSortFields()) { if (isFirst) { isFirst = false; } else { secondPhaseQuery.append(", "); } RowPropertyHelper.ColumnMetadata c = columns.get(sortField.getPath()); secondPhaseQuery.append(c.getColumnName()).append(' ').append(sortField.isAscending() ? "ASC" : "DESC"); } } // first phase: gather rows matching the 'where' clause String firstPhaseQueryStr = firstPhaseQuery.toString(); // TODO ISPN-13986 Improve the efficiency of aggregation deletege them to Search! BaseQuery<?> baseQuery = buildQueryNoAggregations(queryFactory, firstPhaseQueryStr, namedParameters, -1, Integer.MAX_VALUE, parse(firstPhaseQueryStr), local); // second phase: grouping, aggregation, 'having' clause filtering, sorting and pagination String secondPhaseQueryStr = secondPhaseQuery.toString(); return new AggregatingQuery<>(queryFactory, cache, secondPhaseQueryStr, namedParameters, noOfGroupingColumns, accumulators, false, getObjectFilter(new RowMatcher(_columns), secondPhaseQueryStr, namedParameters, null), startOffset, maxResults, baseQuery, queryStatistics, local); } /** * Swaps all occurrences of PropertyPaths in given expression tree (the HAVING clause) with new PropertyPaths * according to the mapping found in {@code columns} map. */ private BooleanExpr swapVariables(BooleanExpr expr, TypeMetadata targetEntityMetadata, LinkedHashMap<PropertyPath, RowPropertyHelper.ColumnMetadata> columns, Map<String, Object> namedParameters, ObjectPropertyHelper<TypeMetadata> propertyHelper) { class PropertyReplacer extends ExprVisitor { @Override public BooleanExpr visit(NotExpr notExpr) { return new NotExpr(notExpr.getChild().acceptVisitor(this)); } @Override public BooleanExpr visit(OrExpr orExpr) { List<BooleanExpr> visitedChildren = new ArrayList<>(); for (BooleanExpr c : orExpr.getChildren()) { visitedChildren.add(c.acceptVisitor(this)); } return new OrExpr(visitedChildren); } @Override public BooleanExpr visit(AndExpr andExpr) { List<BooleanExpr> visitedChildren = new ArrayList<>(); for (BooleanExpr c : andExpr.getChildren()) { visitedChildren.add(c.acceptVisitor(this)); } return new AndExpr(visitedChildren); } @Override public BooleanExpr visit(ConstantBooleanExpr constantBooleanExpr) { return constantBooleanExpr; } @Override public BooleanExpr visit(IsNullExpr isNullExpr) { return new IsNullExpr(isNullExpr.getChild().acceptVisitor(this)); } @Override public BooleanExpr visit(ComparisonExpr comparisonExpr) { return new ComparisonExpr(comparisonExpr.getLeftChild().acceptVisitor(this), comparisonExpr.getRightChild(), comparisonExpr.getComparisonType()); } @Override public BooleanExpr visit(LikeExpr likeExpr) { return new LikeExpr(likeExpr.getChild().acceptVisitor(this), likeExpr.getPattern(namedParameters)); } @Override public ValueExpr visit(ConstantValueExpr constantValueExpr) { return constantValueExpr; } @Override public ValueExpr visit(PropertyValueExpr propertyValueExpr) { RowPropertyHelper.ColumnMetadata c = columns.get(propertyValueExpr.getPropertyPath()); if (c == null) { throw log.expressionMustBePartOfAggregateFunctionOrShouldBeIncludedInGroupByClause(propertyValueExpr.toQueryString()); } return new PropertyValueExpr(c.getColumnName(), propertyValueExpr.isRepeated(), propertyValueExpr.getPrimitiveType()); } @Override public ValueExpr visit(AggregationExpr aggregationExpr) { RowPropertyHelper.ColumnMetadata c = columns.get(aggregationExpr.getPropertyPath()); if (c == null) { Class<?> propertyType = propertyHelper.getPrimitivePropertyType(targetEntityMetadata, aggregationExpr.getPropertyPath().asArrayPath()); propertyType = FieldAccumulator.getOutputType(aggregationExpr.getAggregationType(), propertyType); int idx = columns.size(); c = new RowPropertyHelper.ColumnMetadata(idx, "C" + idx, propertyType); columns.put(aggregationExpr.getPropertyPath(), c); return new PropertyValueExpr(c.getColumnName(), aggregationExpr.isRepeated(), propertyType); } return new PropertyValueExpr(c.getColumnName(), aggregationExpr.isRepeated(), aggregationExpr.getPrimitiveType()); } } return expr.acceptVisitor(new PropertyReplacer()); } private BaseQuery<?> buildQueryWithRepeatedAggregations(QueryFactory queryFactory, String queryString, Map<String, Object> namedParameters, long startOffset, int maxResults, IckleParsingResult<TypeMetadata> parsingResult, String havingClause, LinkedHashMap<PropertyPath, RowPropertyHelper.ColumnMetadata> columns, int noOfGroupingColumns, boolean local) { // these types of aggregations can only be computed in memory StringBuilder firstPhaseQuery = new StringBuilder(); firstPhaseQuery.append("FROM ").append(parsingResult.getTargetEntityName()).append(' ').append(QueryStringCreator.DEFAULT_ALIAS); if (parsingResult.getWhereClause() != null) { // the WHERE clause should not touch aggregated fields BooleanExpr normalizedWhereClause = booleanFilterNormalizer.normalize(parsingResult.getWhereClause()); if (normalizedWhereClause == ConstantBooleanExpr.FALSE) { return new EmptyResultQuery<>(queryFactory, cache, queryString, parsingResult.getStatementType(), namedParameters, startOffset, maxResults, queryStatistics); } if (normalizedWhereClause != ConstantBooleanExpr.TRUE) { firstPhaseQuery.append(' ').append(SyntaxTreePrinter.printTree(normalizedWhereClause)); } } String firstPhaseQueryStr = firstPhaseQuery.toString(); BaseQuery<?> baseQuery = buildQueryNoAggregations(queryFactory, firstPhaseQueryStr, namedParameters, -1, -1, parse(firstPhaseQueryStr), local); List<FieldAccumulator> secondPhaseAccumulators = new LinkedList<>(); List<FieldAccumulator> thirdPhaseAccumulators = new LinkedList<>(); RowPropertyHelper.ColumnMetadata[] _columns = new RowPropertyHelper.ColumnMetadata[columns.size()]; StringBuilder secondPhaseQuery = new StringBuilder(); secondPhaseQuery.append("SELECT "); for (PropertyPath<?> p : columns.keySet()) { RowPropertyHelper.ColumnMetadata c = columns.get(p); if (c.getColumnIndex() > 0) { secondPhaseQuery.append(", "); } // only multi-valued fields need to be accumulated in this phase; for the others the accumulator is null if (p instanceof AggregationPropertyPath) { FieldAccumulator acc = FieldAccumulator.makeAccumulator(((AggregationPropertyPath) p).getAggregationFunction(), c.getColumnIndex(), c.getColumnIndex(), c.getPropertyType()); if (propertyHelper.isRepeatedProperty(parsingResult.getTargetEntityMetadata(), p.asArrayPath())) { secondPhaseAccumulators.add(acc); if (((AggregationPropertyPath) p).getAggregationFunction() == AggregationFunction.COUNT) { c = new RowPropertyHelper.ColumnMetadata(c.getColumnIndex(), c.getColumnName(), Long.class); acc = FieldAccumulator.makeAccumulator(AggregationFunction.SUM, c.getColumnIndex(), c.getColumnIndex(), Long.class); } } else { secondPhaseAccumulators.add(null); } thirdPhaseAccumulators.add(acc); } else { secondPhaseAccumulators.add(null); } secondPhaseQuery.append(QueryStringCreator.DEFAULT_ALIAS).append('.').append(p.asStringPath()); _columns[c.getColumnIndex()] = c; } secondPhaseQuery.append(" FROM ").append(parsingResult.getTargetEntityName()).append(' ').append(QueryStringCreator.DEFAULT_ALIAS); String secondPhaseQueryStr = secondPhaseQuery.toString(); HybridQuery<?, ?> projectingAggregatingQuery = new HybridQuery<>(queryFactory, cache, secondPhaseQueryStr, parsingResult.getStatementType(), namedParameters, getObjectFilter(matcher, secondPhaseQueryStr, namedParameters, secondPhaseAccumulators), startOffset, maxResults, baseQuery, queryStatistics, local); StringBuilder thirdPhaseQuery = new StringBuilder(); thirdPhaseQuery.append("SELECT "); for (int i = 0; i < parsingResult.getProjectedPaths().length; i++) { PropertyPath<?> p = parsingResult.getProjectedPaths()[i]; RowPropertyHelper.ColumnMetadata c = columns.get(p); if (i != 0) { thirdPhaseQuery.append(", "); } thirdPhaseQuery.append(c.getColumnName()); } thirdPhaseQuery.append(" FROM Row "); if (havingClause != null) { thirdPhaseQuery.append(' ').append(havingClause); } if (parsingResult.getSortFields() != null) { thirdPhaseQuery.append(" ORDER BY "); boolean isFirst = true; for (SortField sortField : parsingResult.getSortFields()) { if (isFirst) { isFirst = false; } else { thirdPhaseQuery.append(", "); } RowPropertyHelper.ColumnMetadata c = columns.get(sortField.getPath()); thirdPhaseQuery.append(c.getColumnName()).append(' ').append(sortField.isAscending() ? "ASC" : "DESC"); } } String thirdPhaseQueryStr = thirdPhaseQuery.toString(); return new AggregatingQuery<>(queryFactory, cache, thirdPhaseQueryStr, namedParameters, noOfGroupingColumns, thirdPhaseAccumulators, true, getObjectFilter(new RowMatcher(_columns), thirdPhaseQueryStr, namedParameters, null), startOffset, maxResults, projectingAggregatingQuery, queryStatistics, local); } protected BaseQuery<?> buildQueryNoAggregations(QueryFactory queryFactory, String queryString, Map<String, Object> namedParameters, long startOffset, int maxResults, IckleParsingResult<TypeMetadata> parsingResult, boolean local) { if (parsingResult.hasGroupingOrAggregations()) { throw log.queryMustNotUseGroupingOrAggregation(); // may happen only due to internal programming error } if (parsingResult.getWhereClause() != null) { boolean isFullTextQuery = parsingResult.getWhereClause().acceptVisitor(FullTextVisitor.INSTANCE); if (isFullTextQuery) { throw new IllegalStateException("The cache must be indexed in order to use full-text queries."); } } if (parsingResult.getSortFields() != null) { for (SortField sortField : parsingResult.getSortFields()) { PropertyPath<?> p = sortField.getPath(); if (propertyHelper.isRepeatedProperty(parsingResult.getTargetEntityMetadata(), p.asArrayPath())) { throw log.multivaluedPropertyCannotBeUsedInOrderBy(p.toString()); } } } if (parsingResult.getProjectedPaths() != null) { for (PropertyPath<?> p : parsingResult.getProjectedPaths()) { if (propertyHelper.isRepeatedProperty(parsingResult.getTargetEntityMetadata(), p.asArrayPath())) { throw log.multivaluedPropertyCannotBeProjected(p.asStringPath()); } } } BooleanExpr normalizedWhereClause = booleanFilterNormalizer.normalize(parsingResult.getWhereClause()); if (normalizedWhereClause == ConstantBooleanExpr.FALSE) { // the query is a contradiction, there are no matches return new EmptyResultQuery<>(queryFactory, cache, queryString, parsingResult.getStatementType(), namedParameters, startOffset, maxResults, queryStatistics); } return new EmbeddedQuery<>(this, queryFactory, cache, queryString, parsingResult.getStatementType(), namedParameters, parsingResult.getProjections(), startOffset, maxResults, defaultMaxResults, queryStatistics, local); } protected IckleParsingResult<TypeMetadata> parse(String queryString) { return queryCache != null ? queryCache.get(cache.getName(), queryString, null, IckleParsingResult.class, (qs, accumulators) -> IckleParser.parse(qs, propertyHelper)) : IckleParser.parse(queryString, propertyHelper); } protected final ObjectFilter getObjectFilter(Matcher matcher, String queryString, Map<String, Object> namedParameters, List<FieldAccumulator> accumulators) { ObjectFilter objectFilter = queryCache != null ? queryCache.get(cache.getName(), queryString, accumulators, matcher.getClass(), matcher::getObjectFilter) : matcher.getObjectFilter(queryString, accumulators); return namedParameters != null ? objectFilter.withParameters(namedParameters) : objectFilter; } protected final IckleFilterAndConverter createAndWireFilter(String queryString, Map<String, Object> namedParameters) { IckleFilterAndConverter filter = createFilter(queryString, namedParameters); SecurityActions.getCacheComponentRegistry(cache).wireDependencies(filter); return filter; } protected IckleFilterAndConverter createFilter(String queryString, Map<String, Object> namedParameters) { return new IckleFilterAndConverter(queryString, namedParameters, matcherImplClass); } }
26,799
51.755906
235
java
null
infinispan-main/query-core/src/main/java/org/infinispan/query/core/impl/DelegatingQuery.java
package org.infinispan.query.core.impl; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; import org.infinispan.commons.util.CloseableIterator; import org.infinispan.objectfilter.impl.syntax.parser.IckleParsingResult; import org.infinispan.query.dsl.Query; import org.infinispan.query.dsl.QueryFactory; import org.infinispan.query.dsl.QueryResult; import org.infinispan.query.dsl.impl.BaseQuery; import org.infinispan.query.dsl.impl.logging.Log; import org.jboss.logging.Logger; /** * @author anistor@redhat.com * @since 8.0 */ final class DelegatingQuery<TypeMetadata, T> extends BaseQuery<T> { private static final Log log = Logger.getMessageLogger(Log.class, DelegatingQuery.class.getName()); private final QueryEngine<TypeMetadata> queryEngine; private final IckleParsingResult<TypeMetadata> parsingResult; /** * The actual query object to which execution will be delegated. This is created in {@link #createQuery()} method. */ private Query<T> query; DelegatingQuery(QueryEngine<TypeMetadata> queryEngine, QueryFactory queryFactory, String queryString) { super(queryFactory, queryString); this.queryEngine = queryEngine; // parse and validate early parsingResult = queryEngine.parse(queryString); if (!parsingResult.getParameterNames().isEmpty()) { namedParameters = new HashMap<>(parsingResult.getParameterNames().size()); for (String paramName : parsingResult.getParameterNames()) { namedParameters.put(paramName, null); } } } DelegatingQuery(QueryEngine<TypeMetadata> queryEngine, QueryFactory queryFactory, String queryString, Map<String, Object> namedParameters, String[] projection, long startOffset, int maxResults, boolean local) { super(queryFactory, queryString, namedParameters, projection, startOffset, maxResults, local); this.queryEngine = queryEngine; // parse and validate early; we also discover the param names parsingResult = queryEngine.parse(queryString); if (namedParameters != null) { List<String> unknownParams = null; for (String paramName : namedParameters.keySet()) { if (paramName == null || paramName.isEmpty()) { throw log.parameterNameCannotBeNulOrEmpty(); } if (!parsingResult.getParameterNames().contains(paramName)) { if (unknownParams == null) { unknownParams = new ArrayList<>(); } unknownParams.add(paramName); } } if (unknownParams != null) { throw log.parametersNotFound(unknownParams.toString()); } } } @Override public String[] getProjection() { return parsingResult.getProjections(); } @Override public void resetQuery() { query = null; } private Query<T> createQuery() { // the query is created first time only if (query == null) { query = (Query<T>) queryEngine.buildQuery(queryFactory, parsingResult, namedParameters, startOffset, maxResults, local); if (timeout > 0) { query.timeout(timeout, TimeUnit.NANOSECONDS); } if (hitCountAccuracy != null) { query.hitCountAccuracy(hitCountAccuracy); } } return query; } @Override public List<T> list() { return createQuery().list(); } @Override public QueryResult<T> execute() { return createQuery().execute(); } @Override public int executeStatement() { return createQuery().executeStatement(); } @Override public CloseableIterator<T> iterator() { return createQuery().iterator(); } @Override public <K> CloseableIterator<Map.Entry<K, T>> entryIterator() { return createQuery().entryIterator(); } @Override public int getResultSize() { return createQuery().getResultSize(); } @Override public String toString() { return "DelegatingQuery{" + "queryString=" + queryString + ", namedParameters=" + namedParameters + ", projection=" + Arrays.toString(projection) + ", startOffset=" + startOffset + ", maxResults=" + maxResults + ", timeout=" + timeout + '}'; } }
4,456
29.951389
129
java
null
infinispan-main/query-core/src/main/java/org/infinispan/query/core/impl/FilteringIterator.java
package org.infinispan.query.core.impl; import java.util.NoSuchElementException; import java.util.function.Function; import org.infinispan.commons.util.CloseableIterator; // TODO [anistor] Unused ?? /** * A {@link CloseableIterator} decorator that filters and transforms its elements. */ public final class FilteringIterator<S, T> implements CloseableIterator<T> { private final CloseableIterator<S> iterator; private final Function<? super S, ? extends T> function; private T nextResult = null; private boolean isReady = false; public FilteringIterator(CloseableIterator<S> iterator, Function<? super S, ? extends T> function) { this.iterator = iterator; this.function = function; } @Override public void close() { iterator.close(); } @Override public boolean hasNext() { updateNext(); return nextResult != null; } @Override public T next() { updateNext(); if (nextResult != null) { T next = nextResult; isReady = false; nextResult = null; return next; } else { throw new NoSuchElementException(); } } private void updateNext() { if (!isReady) { while (iterator.hasNext()) { S next = iterator.next(); nextResult = function.apply(next); if (nextResult != null) { break; } } isReady = true; } } }
1,463
21.523077
103
java
null
infinispan-main/query-core/src/main/java/org/infinispan/query/core/impl/MappingEntryIterator.java
package org.infinispan.query.core.impl; import java.util.Map; import java.util.NoSuchElementException; import java.util.function.BiFunction; import org.infinispan.commons.util.CloseableIterator; public class MappingEntryIterator<K, S, T> implements CloseableIterator<T> { private final CloseableIterator<Map.Entry<K, S>> entryIterator; private final BiFunction<K, S, T> mapper; private long skip = 0; private long max = -1; private T current; private long index; public MappingEntryIterator(CloseableIterator<Map.Entry<K, S>> entryIterator, BiFunction<K, S, T> mapper) { this.entryIterator = entryIterator; this.mapper = mapper; } @Override public boolean hasNext() { updateNext(); return current != null; } @Override public T next() { if (hasNext()) { T element = current; current = null; return element; } else { throw new NoSuchElementException(); } } private void updateNext() { while (current == null && entryIterator.hasNext()) { Map.Entry<K, S> next = entryIterator.next(); T mapped = transform(next.getKey(), next.getValue()); if (mapped != null) { index++; } if (index > skip && (max == -1 || index <= skip + max)) { current = mapped; } } } private T transform(K k, S s) { if (s == null) { return null; } if (mapper == null) { return (T) s; } return mapper.apply(k, s); } public MappingEntryIterator<K, S, T> skip(long skip) { this.skip = skip; return this; } public MappingEntryIterator<K, S, T> limit(long max) { this.max = max; return this; } @Override public void close() { entryIterator.close(); } }
1,850
21.851852
110
java
null
infinispan-main/query-core/src/main/java/org/infinispan/query/core/impl/HybridQuery.java
package org.infinispan.query.core.impl; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.Map; import org.infinispan.AdvancedCache; import org.infinispan.commons.util.CloseableIterator; import org.infinispan.objectfilter.ObjectFilter; import org.infinispan.objectfilter.impl.syntax.parser.IckleParsingResult; import org.infinispan.query.core.stats.impl.LocalQueryStatistics; import org.infinispan.query.dsl.Query; import org.infinispan.query.dsl.QueryFactory; import org.infinispan.query.dsl.QueryResult; import org.infinispan.util.logging.LogFactory; /** * A non-indexed query performed on top of the results returned by another query (usually a Lucene based query). This * mechanism is used to implement hybrid two-stage queries that perform an index query using a partial query using only * the indexed fields and then filter the result again in memory with the full filter. * * @author anistor@redhat.com * @since 8.0 */ public class HybridQuery<T, S> extends BaseEmbeddedQuery<T> { private static final Log LOG = LogFactory.getLog(HybridQuery.class, Log.class); // An object filter is used to further filter the baseQuery protected final ObjectFilter objectFilter; protected final Query<S> baseQuery; public HybridQuery(QueryFactory queryFactory, AdvancedCache<?, ?> cache, String queryString, IckleParsingResult.StatementType statementType, Map<String, Object> namedParameters, ObjectFilter objectFilter, long startOffset, int maxResults, Query<?> baseQuery, LocalQueryStatistics queryStatistics, boolean local) { super(queryFactory, cache, queryString, statementType, namedParameters, objectFilter.getProjection(), startOffset, maxResults, queryStatistics, local); this.objectFilter = objectFilter; this.baseQuery = (Query<S>) baseQuery; } @Override protected void recordQuery(long time) { queryStatistics.hybridQueryExecuted(queryString, time); } @Override protected Comparator<Comparable<?>[]> getComparator() { return objectFilter.getComparator(); } @Override protected CloseableIterator<ObjectFilter.FilterResult> getInternalIterator() { return new MappingIterator<>(getBaseIterator(), objectFilter::filter); } protected CloseableIterator<?> getBaseIterator() { // Hybrid query, as they are, they require an unbounded max results, another reason to avoid using them return baseQuery.startOffset(0).maxResults(Integer.MAX_VALUE).local(local).iterator(); } @Override public QueryResult<T> execute() { if (isSelectStatement()) { return super.execute(); } return new QueryResultImpl<>(executeStatement(), Collections.emptyList()); } @Override public int executeStatement() { if (isSelectStatement()) { throw LOG.unsupportedStatement(); } try (CloseableIterator<Map.Entry<Object, S>> entryIterator = baseQuery.startOffset(0).maxResults(-1).local(local).entryIterator()) { Iterator<ObjectFilter.FilterResult> it = new MappingIterator<>(entryIterator, e -> objectFilter.filter(e.getKey(), e.getValue())); int count = 0; while (it.hasNext()) { ObjectFilter.FilterResult fr = it.next(); Object removed = cache.remove(fr.getKey()); if (removed != null) { count++; } } return count; } } @Override public String toString() { return "HybridQuery{" + "queryString=" + queryString + ", statementType=" + statementType + ", namedParameters=" + namedParameters + ", projection=" + Arrays.toString(projection) + ", startOffset=" + startOffset + ", maxResults=" + maxResults + ", timeout=" + timeout + ", baseQuery=" + baseQuery + '}'; } }
3,985
36.252336
157
java
null
infinispan-main/query-core/src/main/java/org/infinispan/query/core/impl/AggregatingQuery.java
package org.infinispan.query.core.impl; import java.util.Arrays; import java.util.List; import java.util.Map; import org.infinispan.AdvancedCache; import org.infinispan.commons.util.CloseableIterator; import org.infinispan.commons.util.Closeables; import org.infinispan.objectfilter.ObjectFilter; import org.infinispan.objectfilter.impl.aggregation.FieldAccumulator; import org.infinispan.objectfilter.impl.aggregation.RowGrouper; import org.infinispan.objectfilter.impl.syntax.parser.IckleParsingResult; import org.infinispan.query.core.stats.impl.LocalQueryStatistics; import org.infinispan.query.dsl.QueryFactory; import org.infinispan.query.dsl.impl.BaseQuery; /** * Executes grouping and aggregation on top of a base query. * * @author anistor@redhat.com * @since 8.0 */ public final class AggregatingQuery<T> extends HybridQuery<T, Object[]> { /** * The number of columns at the beginning of the row that are used as group key. */ private final int noOfGroupingColumns; private final FieldAccumulator[] accumulators; private final boolean twoPhaseAcc; public AggregatingQuery(QueryFactory queryFactory, AdvancedCache<?, ?> cache, String queryString, Map<String, Object> namedParameters, int noOfGroupingColumns, List<FieldAccumulator> accumulators, boolean twoPhaseAcc, ObjectFilter objectFilter, long startOffset, int maxResults, BaseQuery<?> baseQuery, LocalQueryStatistics queryStatistics, boolean local) { super(queryFactory, cache, queryString, IckleParsingResult.StatementType.SELECT, namedParameters, objectFilter, startOffset, maxResults, baseQuery, queryStatistics, local); if (!baseQuery.hasProjections()) { throw new IllegalArgumentException("Base query must use projections"); } if (projection == null) { throw new IllegalArgumentException("Aggregating query must use projections"); } this.noOfGroupingColumns = noOfGroupingColumns; this.accumulators = accumulators != null ? accumulators.toArray(new FieldAccumulator[0]) : null; this.twoPhaseAcc = twoPhaseAcc; } @Override protected CloseableIterator<?> getBaseIterator() { // get the base iterator and add grouping on top of it RowGrouper grouper = new RowGrouper(noOfGroupingColumns, accumulators, twoPhaseAcc); try (CloseableIterator<Object[]> iterator = baseQuery.iterator()) { iterator.forEachRemaining(grouper::addRow); } return Closeables.iterator(grouper.finish()); } @Override public int executeStatement() { throw new UnsupportedOperationException(); } @Override public <K> CloseableIterator<Map.Entry<K, T>> entryIterator() { throw new UnsupportedOperationException(); } @Override public String toString() { return "AggregatingQuery{" + "queryString=" + queryString + ", namedParameters=" + namedParameters + ", noOfGroupingColumns=" + noOfGroupingColumns + ", accumulators=" + Arrays.toString(accumulators) + ", projection=" + Arrays.toString(projection) + ", startOffset=" + startOffset + ", maxResults=" + maxResults + ", timeout=" + timeout + ", baseQuery=" + baseQuery + '}'; } }
3,421
37.886364
178
java
null
infinispan-main/query-core/src/main/java/org/infinispan/query/core/impl/PartitionHandlingSupport.java
package org.infinispan.query.core.impl; import org.infinispan.AdvancedCache; import org.infinispan.configuration.cache.ClusteringConfiguration; import org.infinispan.partitionhandling.AvailabilityMode; import org.infinispan.partitionhandling.PartitionHandling; import org.infinispan.util.logging.LogFactory; /** * @since 9.4 */ public final class PartitionHandlingSupport { private static final Log log = LogFactory.getLog(PartitionHandlingSupport.class, Log.class); private final boolean isClustered; private final PartitionHandling partitionHandling; private final AdvancedCache<?, ?> cache; public PartitionHandlingSupport(AdvancedCache<?, ?> cache) { this.cache = cache; ClusteringConfiguration clusteringConfiguration = cache.getCacheConfiguration().clustering(); this.isClustered = clusteringConfiguration.cacheMode().isClustered(); this.partitionHandling = isClustered ? clusteringConfiguration.partitionHandling().whenSplit() : null; } public void checkCacheAvailable() { if (isClustered) { if (cache.getAvailability() != AvailabilityMode.AVAILABLE) { if (partitionHandling != PartitionHandling.ALLOW_READ_WRITES) { throw log.partitionDegraded(); } } } } }
1,290
33.891892
108
java
null
infinispan-main/query-core/src/main/java/org/infinispan/query/core/impl/LifecycleManager.java
package org.infinispan.query.core.impl; import static org.infinispan.marshall.protostream.impl.SerializationContextRegistry.MarshallerType.PERSISTENCE; import java.util.LinkedHashSet; import java.util.Map; import java.util.Set; import org.infinispan.AdvancedCache; import org.infinispan.Cache; import org.infinispan.commons.marshall.AdvancedExternalizer; import org.infinispan.commons.util.AggregatedClassLoader; import org.infinispan.configuration.cache.Configuration; import org.infinispan.configuration.global.GlobalConfiguration; import org.infinispan.factories.ComponentRegistry; import org.infinispan.factories.GlobalComponentRegistry; import org.infinispan.factories.annotations.InfinispanModule; import org.infinispan.lifecycle.ModuleLifecycle; import org.infinispan.marshall.protostream.impl.SerializationContextRegistry; import org.infinispan.objectfilter.impl.ReflectionMatcher; import org.infinispan.query.core.impl.continuous.ContinuousQueryResult; import org.infinispan.query.core.impl.continuous.IckleContinuousQueryCacheEventFilterConverter; import org.infinispan.query.core.impl.eventfilter.IckleCacheEventFilterConverter; import org.infinispan.query.core.impl.eventfilter.IckleFilterAndConverter; import org.infinispan.query.core.stats.IndexStatistics; import org.infinispan.query.core.stats.impl.IndexStatisticsSnapshotImpl; import org.infinispan.query.core.stats.impl.LocalQueryStatistics; import org.infinispan.query.core.stats.impl.PersistenceContextInitializerImpl; import org.infinispan.query.core.stats.impl.SearchStatsRetriever; import org.infinispan.registry.InternalCacheRegistry; import org.infinispan.registry.InternalCacheRegistry.Flag; /** * @author anistor@redhat.com * @since 10.1 */ @InfinispanModule(name = "query-core", requiredModules = "core") public class LifecycleManager implements ModuleLifecycle { @Override public void cacheStarting(ComponentRegistry cr, Configuration cfg, String cacheName) { InternalCacheRegistry icr = cr.getGlobalComponentRegistry().getComponent(InternalCacheRegistry.class); if (!icr.isInternalCache(cacheName) || icr.internalCacheHasFlag(cacheName, Flag.QUERYABLE)) { cr.registerComponent(new IndexStatisticsSnapshotImpl(), IndexStatistics.class); cr.registerComponent(new LocalQueryStatistics(), LocalQueryStatistics.class); cr.registerComponent(new SearchStatsRetriever(), SearchStatsRetriever.class); AdvancedCache<?, ?> cache = cr.getComponent(Cache.class).getAdvancedCache(); ClassLoader aggregatedClassLoader = makeAggregatedClassLoader(cr.getGlobalComponentRegistry().getGlobalConfiguration().classLoader()); cr.registerComponent(new ReflectionMatcher(aggregatedClassLoader), ReflectionMatcher.class); cr.registerComponent(new QueryEngine<>(cache), QueryEngine.class); } } @Override public void cacheStarted(ComponentRegistry cr, String cacheName) { } /** * Create a class loader that delegates loading to an ordered set of class loaders. * * @param globalClassLoader the cache manager's global ClassLoader from GlobalConfiguration * @return the aggregated ClassLoader */ private ClassLoader makeAggregatedClassLoader(ClassLoader globalClassLoader) { // use an ordered set to deduplicate them Set<ClassLoader> classLoaders = new LinkedHashSet<>(6); // add the cache manager's CL if (globalClassLoader != null) { classLoaders.add(globalClassLoader); } // add Infinispan's CL classLoaders.add(AggregatedClassLoader.class.getClassLoader()); // TODO [anistor] // add Hibernate Search's CL //classLoaders.add(ClassLoaderService.class.getClassLoader()); // add this module's CL classLoaders.add(getClass().getClassLoader()); // add the TCCL try { ClassLoader tccl = Thread.currentThread().getContextClassLoader(); if (tccl != null) { classLoaders.add(tccl); } } catch (Exception e) { // ignored } // add the system CL try { ClassLoader syscl = ClassLoader.getSystemClassLoader(); if (syscl != null) { classLoaders.add(syscl); } } catch (Exception e) { // ignored } return new AggregatedClassLoader(classLoaders); } @Override public void cacheStopping(ComponentRegistry cr, String cacheName) { } @Override public void cacheStopped(ComponentRegistry cr, String cacheName) { } @Override public void cacheManagerStarting(GlobalComponentRegistry gcr, GlobalConfiguration globalCfg) { gcr.registerComponent(new QueryCache(), QueryCache.class); Map<Integer, AdvancedExternalizer<?>> externalizerMap = globalCfg.serialization().advancedExternalizers(); externalizerMap.put(ExternalizerIds.ICKLE_FILTER_AND_CONVERTER, new IckleFilterAndConverter.IckleFilterAndConverterExternalizer()); externalizerMap.put(ExternalizerIds.ICKLE_FILTER_RESULT, new IckleFilterAndConverter.FilterResultExternalizer()); externalizerMap.put(ExternalizerIds.ICKLE_CACHE_EVENT_FILTER_CONVERTER, new IckleCacheEventFilterConverter.Externalizer()); externalizerMap.put(ExternalizerIds.ICKLE_CONTINUOUS_QUERY_CACHE_EVENT_FILTER_CONVERTER, new IckleContinuousQueryCacheEventFilterConverter.Externalizer()); externalizerMap.put(ExternalizerIds.ICKLE_CONTINUOUS_QUERY_RESULT, new ContinuousQueryResult.Externalizer()); externalizerMap.put(ExternalizerIds.ICKLE_DELETE_FUNCTION, new EmbeddedQuery.DeleteFunctionExternalizer()); SerializationContextRegistry ctxRegistry = gcr.getComponent(SerializationContextRegistry.class); ctxRegistry.addContextInitializer(PERSISTENCE, new PersistenceContextInitializerImpl()); } @Override public void cacheManagerStopped(GlobalComponentRegistry gcr) { } }
5,902
42.725926
161
java
null
infinispan-main/query-core/src/main/java/org/infinispan/query/core/impl/MetadataHybridQuery.java
package org.infinispan.query.core.impl; import java.util.Map; import org.infinispan.AdvancedCache; import org.infinispan.commons.util.CloseableIterator; import org.infinispan.objectfilter.ObjectFilter; import org.infinispan.objectfilter.impl.syntax.parser.IckleParsingResult; import org.infinispan.query.core.stats.impl.LocalQueryStatistics; import org.infinispan.query.dsl.Query; import org.infinispan.query.dsl.QueryFactory; public class MetadataHybridQuery<T, S> extends HybridQuery<T, S> { public MetadataHybridQuery(QueryFactory queryFactory, AdvancedCache<?, ?> cache, String queryString, IckleParsingResult.StatementType statementType, Map<String, Object> namedParameters, ObjectFilter objectFilter, long startOffset, int maxResults, Query<?> baseQuery, LocalQueryStatistics queryStatistics, boolean local) { super(queryFactory, cache, queryString, statementType, namedParameters, objectFilter, startOffset, maxResults, baseQuery, queryStatistics, local); } @Override protected CloseableIterator<ObjectFilter.FilterResult> getInternalIterator() { CloseableIterator<Map.Entry<Object, S>> iterator = baseQuery .startOffset(0).maxResults(Integer.MAX_VALUE).local(local).entryIterator(); return new MappingEntryIterator<>(iterator, objectFilter::filter); } }
1,402
47.37931
152
java
null
infinispan-main/query-core/src/main/java/org/infinispan/query/core/impl/eventfilter/package-info.java
/** * Filters based on Ickle queries. */ package org.infinispan.query.core.impl.eventfilter;
95
18.2
51
java
null
infinispan-main/query-core/src/main/java/org/infinispan/query/core/impl/eventfilter/IckleCacheEventFilterConverter.java
package org.infinispan.query.core.impl.eventfilter; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.util.Collections; import java.util.Set; import org.infinispan.commons.marshall.AbstractExternalizer; import org.infinispan.factories.ComponentRegistry; import org.infinispan.factories.annotations.Inject; import org.infinispan.factories.scopes.Scope; import org.infinispan.factories.scopes.Scopes; import org.infinispan.metadata.Metadata; import org.infinispan.notifications.cachelistener.filter.AbstractCacheEventFilterConverter; import org.infinispan.notifications.cachelistener.filter.EventType; import org.infinispan.notifications.cachelistener.filter.IndexedFilter; import org.infinispan.query.core.impl.ExternalizerIds; /** * @author anistor@redhat.com * @since 7.2 */ @Scope(Scopes.NONE) public class IckleCacheEventFilterConverter<K, V, C> extends AbstractCacheEventFilterConverter<K, V, C> implements IndexedFilter<K, V, C> { protected final IckleFilterAndConverter<K, V> filterAndConverter; public IckleCacheEventFilterConverter(IckleFilterAndConverter<K, V> filterAndConverter) { this.filterAndConverter = filterAndConverter; } @Inject protected void injectDependencies(ComponentRegistry componentRegistry) { componentRegistry.wireDependencies(filterAndConverter); } @Override public C filterAndConvert(K key, V oldValue, Metadata oldMetadata, V newValue, Metadata newMetadata, EventType eventType) { return (C) filterAndConverter.filterAndConvert(key, newValue, newMetadata); } public static final class Externalizer extends AbstractExternalizer<IckleCacheEventFilterConverter> { @Override public void writeObject(ObjectOutput output, IckleCacheEventFilterConverter object) throws IOException { output.writeObject(object.filterAndConverter); } @Override public IckleCacheEventFilterConverter readObject(ObjectInput input) throws IOException, ClassNotFoundException { IckleFilterAndConverter filterAndConverter = (IckleFilterAndConverter) input.readObject(); return new IckleCacheEventFilterConverter(filterAndConverter); } @Override public Integer getId() { return ExternalizerIds.ICKLE_CACHE_EVENT_FILTER_CONVERTER; } @Override public Set<Class<? extends IckleCacheEventFilterConverter>> getTypeClasses() { return Collections.singleton(IckleCacheEventFilterConverter.class); } } }
2,525
36.701493
139
java
null
infinispan-main/query-core/src/main/java/org/infinispan/query/core/impl/eventfilter/IckleFilterAndConverter.java
package org.infinispan.query.core.impl.eventfilter; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Set; import java.util.function.Function; import org.infinispan.commons.CacheException; import org.infinispan.commons.io.UnsignedNumeric; import org.infinispan.commons.marshall.AbstractExternalizer; import org.infinispan.factories.ComponentRegistry; import org.infinispan.factories.annotations.Inject; import org.infinispan.factories.scopes.Scope; import org.infinispan.factories.scopes.Scopes; import org.infinispan.filter.AbstractKeyValueFilterConverter; import org.infinispan.metadata.Metadata; import org.infinispan.objectfilter.Matcher; import org.infinispan.objectfilter.ObjectFilter; import org.infinispan.objectfilter.impl.FilterResultImpl; import org.infinispan.query.core.impl.ExternalizerIds; import org.infinispan.query.core.impl.QueryCache; /** * A filter implementation that is both a KeyValueFilter and a converter. The implementation relies on the Matcher and a * Ickle query string. * * @author anistor@redhat.com * @since 7.0 */ @Scope(Scopes.NONE) public class IckleFilterAndConverter<K, V> extends AbstractKeyValueFilterConverter<K, V, ObjectFilter.FilterResult> implements Function<Map.Entry<K, V>, ObjectFilter.FilterResult> { private String cacheName; /** * Optional cache for query objects. */ private QueryCache queryCache; /** * The Ickle query to execute. */ private final String queryString; private final Map<String, Object> namedParameters; /** * The implementation class of the Matcher component to lookup and use. */ protected Class<? extends Matcher> matcherImplClass; /** * The Matcher, acquired via dependency injection. */ private Matcher matcher; /** * The ObjectFilter is created lazily. */ private ObjectFilter objectFilter; public IckleFilterAndConverter(String queryString, Map<String, Object> namedParameters, Class<? extends Matcher> matcherImplClass) { if (queryString == null || matcherImplClass == null) { throw new IllegalArgumentException("Arguments cannot be null"); } this.queryString = queryString; this.namedParameters = namedParameters; this.matcherImplClass = matcherImplClass; } /** * Acquires a Matcher instance from the ComponentRegistry of the given Cache object. */ @Inject protected void injectDependencies(ComponentRegistry componentRegistry, QueryCache queryCache) { this.queryCache = queryCache; cacheName = componentRegistry.getCache().wired().getName(); matcher = componentRegistry.getComponent(matcherImplClass); if (matcher == null) { throw new CacheException("Expected component not found in registry: " + matcherImplClass.getName()); } } public ObjectFilter getObjectFilter() { if (objectFilter == null) { objectFilter = queryCache != null ? queryCache.get(cacheName, queryString, null, matcherImplClass, (qs, accumulators) -> matcher.getObjectFilter(qs)) : matcher.getObjectFilter(queryString); } return namedParameters != null ? objectFilter.withParameters(namedParameters) : objectFilter; } public String getQueryString() { return queryString; } public Map<String, Object> getNamedParameters() { return namedParameters; } public Matcher getMatcher() { return matcher; } @Override public ObjectFilter.FilterResult filterAndConvert(K key, V value, Metadata metadata) { if (value == null) { return null; } return getObjectFilter().filter(key, value); } @Override public ObjectFilter.FilterResult apply(Map.Entry<K, V> cacheEntry) { return filterAndConvert(cacheEntry.getKey(), cacheEntry.getValue(), null); } @Override public String toString() { return getClass().getSimpleName() + "{queryString='" + queryString + "'}"; } public static final class IckleFilterAndConverterExternalizer extends AbstractExternalizer<IckleFilterAndConverter> { @Override public void writeObject(ObjectOutput output, IckleFilterAndConverter filterAndConverter) throws IOException { output.writeUTF(filterAndConverter.queryString); Map<String, Object> namedParameters = filterAndConverter.namedParameters; if (namedParameters != null) { UnsignedNumeric.writeUnsignedInt(output, namedParameters.size()); for (Map.Entry<String, Object> e : namedParameters.entrySet()) { output.writeUTF(e.getKey()); output.writeObject(e.getValue()); } } else { UnsignedNumeric.writeUnsignedInt(output, 0); } output.writeObject(filterAndConverter.matcherImplClass); } @Override public IckleFilterAndConverter readObject(ObjectInput input) throws IOException, ClassNotFoundException { String queryString = input.readUTF(); int paramsSize = UnsignedNumeric.readUnsignedInt(input); Map<String, Object> namedParameters = null; if (paramsSize != 0) { namedParameters = new HashMap<>(paramsSize); for (int i = 0; i < paramsSize; i++) { String paramName = input.readUTF(); Object paramValue = input.readObject(); namedParameters.put(paramName, paramValue); } } Class<? extends Matcher> matcherImplClass = (Class<? extends Matcher>) input.readObject(); return new IckleFilterAndConverter(queryString, namedParameters, matcherImplClass); } @Override public Integer getId() { return ExternalizerIds.ICKLE_FILTER_AND_CONVERTER; } @Override public Set<Class<? extends IckleFilterAndConverter>> getTypeClasses() { return Collections.singleton(IckleFilterAndConverter.class); } } public static final class FilterResultExternalizer extends AbstractExternalizer<FilterResultImpl> { @Override public void writeObject(ObjectOutput output, FilterResultImpl filterResult) throws IOException { if (filterResult.getProjection() != null) { // skip serializing the key and instance if there is a projection output.writeObject(null); output.writeObject(filterResult.getProjection()); } else { output.writeObject(filterResult.getInstance()); output.writeObject(filterResult.getKey()); } output.writeObject(filterResult.getSortProjection()); } @Override public FilterResultImpl readObject(ObjectInput input) throws IOException, ClassNotFoundException { Object instance = input.readObject(); Object key = instance == null ? null : input.readObject(); Object[] projection = instance == null ? (Object[]) input.readObject() : null; Comparable[] sortProjection = (Comparable[]) input.readObject(); return new FilterResultImpl(key, instance, projection, sortProjection); } @Override public Integer getId() { return ExternalizerIds.ICKLE_FILTER_RESULT; } @Override public Set<Class<? extends FilterResultImpl>> getTypeClasses() { return Collections.singleton(FilterResultImpl.class); } } }
7,504
35.081731
181
java
null
infinispan-main/query-core/src/main/java/org/infinispan/query/core/impl/eventfilter/IckleFilterIndexingServiceProvider.java
package org.infinispan.query.core.impl.eventfilter; import java.util.Map; import org.infinispan.commons.marshall.WrappedByteArray; import org.infinispan.notifications.cachelistener.EventWrapper; import org.infinispan.notifications.cachelistener.event.CacheEntryEvent; import org.infinispan.notifications.cachelistener.filter.FilterIndexingServiceProvider; import org.infinispan.notifications.cachelistener.filter.IndexedFilter; import org.infinispan.objectfilter.Matcher; import org.infinispan.objectfilter.impl.FilterResultImpl; import org.kohsuke.MetaInfServices; /** * @author anistor@redhat.com * @since 7.2 */ @MetaInfServices(FilterIndexingServiceProvider.class) public class IckleFilterIndexingServiceProvider extends BaseIckleFilterIndexingServiceProvider { @Override public boolean supportsFilter(IndexedFilter<?, ?, ?> indexedFilter) { return indexedFilter.getClass() == IckleCacheEventFilterConverter.class; } protected Matcher getMatcher(IndexedFilter<?, ?, ?> indexedFilter) { return ((IckleCacheEventFilterConverter) indexedFilter).filterAndConverter.getMatcher(); } protected String getQueryString(IndexedFilter<?, ?, ?> indexedFilter) { return ((IckleCacheEventFilterConverter) indexedFilter).filterAndConverter.getQueryString(); } protected Map<String, Object> getNamedParameters(IndexedFilter<?, ?, ?> indexedFilter) { return ((IckleCacheEventFilterConverter) indexedFilter).filterAndConverter.getNamedParameters(); } @Override protected boolean isDelta(IndexedFilter<?, ?, ?> indexedFilter) { return false; } @Override protected <K, V> void matchEvent(EventWrapper<K, V, CacheEntryEvent<K, V>> eventWrapper, Matcher matcher) { CacheEntryEvent<?, ?> event = eventWrapper.getEvent(); Object instance = event.getValue(); if (instance != null) { if (instance.getClass() == WrappedByteArray.class) { instance = ((WrappedByteArray) instance).getBytes(); } matcher.match(eventWrapper, event.getType(), instance); } } protected Object makeFilterResult(Object userContext, Object eventType, Object key, Object instance, Object[] projection, Comparable[] sortProjection) { return new FilterResultImpl(key, instance, projection, sortProjection); } }
2,321
38.355932
155
java
null
infinispan-main/query-core/src/main/java/org/infinispan/query/core/impl/eventfilter/BaseIckleFilterIndexingServiceProvider.java
package org.infinispan.query.core.impl.eventfilter; import java.lang.annotation.Annotation; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Set; import java.util.UUID; import java.util.concurrent.CompletionStage; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import org.infinispan.encoding.DataConversion; import org.infinispan.factories.annotations.Inject; import org.infinispan.factories.scopes.Scope; import org.infinispan.factories.scopes.Scopes; import org.infinispan.interceptors.locking.ClusteringDependentLogic; import org.infinispan.notifications.Listener; import org.infinispan.notifications.cachelistener.CacheEntryListenerInvocation; import org.infinispan.notifications.cachelistener.CacheNotifier; import org.infinispan.notifications.cachelistener.CacheNotifierImpl; import org.infinispan.notifications.cachelistener.EventWrapper; import org.infinispan.notifications.cachelistener.annotation.CacheEntriesEvicted; import org.infinispan.notifications.cachelistener.annotation.CacheEntryActivated; import org.infinispan.notifications.cachelistener.annotation.CacheEntryCreated; import org.infinispan.notifications.cachelistener.annotation.CacheEntryExpired; import org.infinispan.notifications.cachelistener.annotation.CacheEntryInvalidated; import org.infinispan.notifications.cachelistener.annotation.CacheEntryLoaded; import org.infinispan.notifications.cachelistener.annotation.CacheEntryModified; import org.infinispan.notifications.cachelistener.annotation.CacheEntryPassivated; import org.infinispan.notifications.cachelistener.annotation.CacheEntryRemoved; import org.infinispan.notifications.cachelistener.annotation.CacheEntryVisited; import org.infinispan.notifications.cachelistener.event.CacheEntryEvent; import org.infinispan.notifications.cachelistener.event.Event; import org.infinispan.notifications.cachelistener.event.impl.EventImpl; import org.infinispan.notifications.cachelistener.filter.CacheEventConverter; import org.infinispan.notifications.cachelistener.filter.CacheEventFilter; import org.infinispan.notifications.cachelistener.filter.DelegatingCacheEntryListenerInvocation; import org.infinispan.notifications.cachelistener.filter.FilterIndexingServiceProvider; import org.infinispan.notifications.cachelistener.filter.IndexedFilter; import org.infinispan.objectfilter.FilterCallback; import org.infinispan.objectfilter.FilterSubscription; import org.infinispan.objectfilter.Matcher; import org.infinispan.util.concurrent.CompletionStages; /** * @author anistor@redhat.com * @since 8.1 */ @Scope(Scopes.NAMED_CACHE) public abstract class BaseIckleFilterIndexingServiceProvider implements FilterIndexingServiceProvider { private final ConcurrentMap<Matcher, FilteringListenerInvocation<?, ?>> filteringInvocations = new ConcurrentHashMap<>(4); private CacheNotifierImpl<?, ?> cacheNotifier; private ClusteringDependentLogic clusteringDependentLogic; @Inject protected void injectDependencies(CacheNotifier cacheNotifier, ClusteringDependentLogic clusteringDependentLogic) { this.cacheNotifier = (CacheNotifierImpl) cacheNotifier; this.clusteringDependentLogic = clusteringDependentLogic; } @Override public void start() { } @Override public void stop() { Collection<FilteringListenerInvocation<?, ?>> invocations = filteringInvocations.values(); cacheNotifier.getListenerCollectionForAnnotation(CacheEntryActivated.class).removeAll(invocations); cacheNotifier.getListenerCollectionForAnnotation(CacheEntryCreated.class).removeAll(invocations); cacheNotifier.getListenerCollectionForAnnotation(CacheEntryInvalidated.class).removeAll(invocations); cacheNotifier.getListenerCollectionForAnnotation(CacheEntryLoaded.class).removeAll(invocations); cacheNotifier.getListenerCollectionForAnnotation(CacheEntryModified.class).removeAll(invocations); cacheNotifier.getListenerCollectionForAnnotation(CacheEntryPassivated.class).removeAll(invocations); cacheNotifier.getListenerCollectionForAnnotation(CacheEntryRemoved.class).removeAll(invocations); cacheNotifier.getListenerCollectionForAnnotation(CacheEntryVisited.class).removeAll(invocations); cacheNotifier.getListenerCollectionForAnnotation(CacheEntriesEvicted.class).removeAll(invocations); cacheNotifier.getListenerCollectionForAnnotation(CacheEntryExpired.class).removeAll(invocations); filteringInvocations.clear(); } @Override public <K, V> DelegatingCacheEntryListenerInvocation<K, V> interceptListenerInvocation(CacheEntryListenerInvocation<K, V> invocation) { return new DelegatingCacheEntryListenerInvocationImpl<>(invocation); } @Override public <K, V> void registerListenerInvocations(boolean isClustered, boolean isPrimaryOnly, boolean filterAndConvert, IndexedFilter<?, ?, ?> indexedFilter, Map<Class<? extends Annotation>, List<DelegatingCacheEntryListenerInvocation<K, V>>> listeners, DataConversion keyDataConversion, DataConversion valueDataConversion) { final Matcher matcher = getMatcher(indexedFilter); final String queryString = getQueryString(indexedFilter); final Map<String, Object> namedParameters = getNamedParameters(indexedFilter); final boolean isDeltaFilter = isDelta(indexedFilter); addFilteringInvocationForMatcher(matcher, keyDataConversion, valueDataConversion); Event.Type[] eventTypes = new Event.Type[listeners.keySet().size()]; int i = 0; for (Class<? extends Annotation> annotation : listeners.keySet()) { eventTypes[i++] = getEventTypeFromAnnotation(annotation); } Callback<K, V> callback = new Callback<>(matcher, isClustered, isPrimaryOnly, filterAndConvert, listeners); callback.subscription = matcher.registerFilter(queryString, namedParameters, callback, isDeltaFilter, eventTypes); } /** * Obtains the event type that corresponds to the given event annotation. * * @param annotation a CacheEntryXXX annotation * @return the event type or {@code null} if the given annotation is not supported */ private Event.Type getEventTypeFromAnnotation(Class<? extends Annotation> annotation) { if (annotation == CacheEntryCreated.class) return Event.Type.CACHE_ENTRY_CREATED; if (annotation == CacheEntryModified.class) return Event.Type.CACHE_ENTRY_MODIFIED; if (annotation == CacheEntryRemoved.class) return Event.Type.CACHE_ENTRY_REMOVED; if (annotation == CacheEntryActivated.class) return Event.Type.CACHE_ENTRY_ACTIVATED; if (annotation == CacheEntryInvalidated.class) return Event.Type.CACHE_ENTRY_INVALIDATED; if (annotation == CacheEntryLoaded.class) return Event.Type.CACHE_ENTRY_LOADED; if (annotation == CacheEntryPassivated.class) return Event.Type.CACHE_ENTRY_PASSIVATED; if (annotation == CacheEntryVisited.class) return Event.Type.CACHE_ENTRY_VISITED; if (annotation == CacheEntriesEvicted.class) return Event.Type.CACHE_ENTRY_EVICTED; if (annotation == CacheEntryExpired.class) return Event.Type.CACHE_ENTRY_EXPIRED; return null; } private void addFilteringInvocationForMatcher(Matcher matcher, DataConversion keyDataConversion, DataConversion valueDataConversion) { if (!filteringInvocations.containsKey(matcher)) { FilteringListenerInvocation filteringInvocation = new FilteringListenerInvocation(matcher, keyDataConversion, valueDataConversion); if (filteringInvocations.putIfAbsent(matcher, filteringInvocation) == null) { // todo these are added but never removed until stop is called cacheNotifier.getListenerCollectionForAnnotation(CacheEntryActivated.class).add(filteringInvocation); cacheNotifier.getListenerCollectionForAnnotation(CacheEntryCreated.class).add(filteringInvocation); cacheNotifier.getListenerCollectionForAnnotation(CacheEntryInvalidated.class).add(filteringInvocation); cacheNotifier.getListenerCollectionForAnnotation(CacheEntryLoaded.class).add(filteringInvocation); cacheNotifier.getListenerCollectionForAnnotation(CacheEntryModified.class).add(filteringInvocation); cacheNotifier.getListenerCollectionForAnnotation(CacheEntryPassivated.class).add(filteringInvocation); cacheNotifier.getListenerCollectionForAnnotation(CacheEntryRemoved.class).add(filteringInvocation); cacheNotifier.getListenerCollectionForAnnotation(CacheEntryVisited.class).add(filteringInvocation); cacheNotifier.getListenerCollectionForAnnotation(CacheEntriesEvicted.class).add(filteringInvocation); cacheNotifier.getListenerCollectionForAnnotation(CacheEntryExpired.class).add(filteringInvocation); } } } private final class Callback<K, V> implements FilterCallback { private final boolean isClustered; private final boolean isPrimaryOnly; private final boolean filterAndConvert; private final DelegatingCacheEntryListenerInvocation<K, V>[] activated_invocations; private final DelegatingCacheEntryListenerInvocation<K, V>[] created_invocations; private final DelegatingCacheEntryListenerInvocation<K, V>[] invalidated_invocations; private final DelegatingCacheEntryListenerInvocation<K, V>[] loaded_invocations; private final DelegatingCacheEntryListenerInvocation<K, V>[] modified_invocations; private final DelegatingCacheEntryListenerInvocation<K, V>[] passivated_invocations; private final DelegatingCacheEntryListenerInvocation<K, V>[] removed_invocations; private final DelegatingCacheEntryListenerInvocation<K, V>[] visited_invocations; private final DelegatingCacheEntryListenerInvocation<K, V>[] evicted_invocations; private final DelegatingCacheEntryListenerInvocation<K, V>[] expired_invocations; private final Matcher matcher; volatile FilterSubscription subscription; Callback(Matcher matcher, boolean isClustered, boolean isPrimaryOnly, boolean filterAndConvert, Map<Class<? extends Annotation>, List<DelegatingCacheEntryListenerInvocation<K, V>>> listeners) { this.matcher = matcher; this.isClustered = isClustered; this.isPrimaryOnly = isPrimaryOnly; this.filterAndConvert = filterAndConvert; activated_invocations = makeArray(listeners, CacheEntryActivated.class); created_invocations = makeArray(listeners, CacheEntryCreated.class); invalidated_invocations = makeArray(listeners, CacheEntryInvalidated.class); loaded_invocations = makeArray(listeners, CacheEntryLoaded.class); modified_invocations = makeArray(listeners, CacheEntryModified.class); passivated_invocations = makeArray(listeners, CacheEntryPassivated.class); removed_invocations = makeArray(listeners, CacheEntryRemoved.class); visited_invocations = makeArray(listeners, CacheEntryVisited.class); evicted_invocations = makeArray(listeners, CacheEntriesEvicted.class); expired_invocations = makeArray(listeners, CacheEntryExpired.class); } private DelegatingCacheEntryListenerInvocation<K, V>[] makeArray(Map<Class<? extends Annotation>, List<DelegatingCacheEntryListenerInvocation<K, V>>> listeners, Class<? extends Annotation> eventType) { List<DelegatingCacheEntryListenerInvocation<K, V>> invocations = listeners.get(eventType); if (invocations == null) { return null; } DelegatingCacheEntryListenerInvocation<K, V>[] invocationsArray = invocations.toArray(new DelegatingCacheEntryListenerInvocation[invocations.size()]); for (DelegatingCacheEntryListenerInvocation di : invocationsArray) { ((DelegatingCacheEntryListenerInvocationImpl) di).callback = this; } return invocationsArray; } void unregister() { FilterSubscription s = subscription; if (s != null) { // unregister only once matcher.unregisterFilter(s); subscription = null; } } @Override public void onFilterResult(Object userContext, Object eventType, Object instance, Object[] projection, Comparable[] sortProjection) { EventWrapper eventWrapper = (EventWrapper) userContext; CacheEntryEvent<K, V> event = (CacheEntryEvent<K, V>) eventWrapper.getEvent(); if (event.isPre() && isClustered || isPrimaryOnly && !clusteringDependentLogic.getCacheTopology().getDistribution(eventWrapper.getKey()).isPrimary()) { return; } DelegatingCacheEntryListenerInvocation<K, V>[] invocations; switch (event.getType()) { case CACHE_ENTRY_ACTIVATED: invocations = activated_invocations; break; case CACHE_ENTRY_CREATED: invocations = created_invocations; break; case CACHE_ENTRY_INVALIDATED: invocations = invalidated_invocations; break; case CACHE_ENTRY_LOADED: invocations = loaded_invocations; break; case CACHE_ENTRY_MODIFIED: invocations = modified_invocations; break; case CACHE_ENTRY_PASSIVATED: invocations = passivated_invocations; break; case CACHE_ENTRY_REMOVED: invocations = removed_invocations; break; case CACHE_ENTRY_VISITED: invocations = visited_invocations; break; case CACHE_ENTRY_EVICTED: invocations = evicted_invocations; break; case CACHE_ENTRY_EXPIRED: invocations = expired_invocations; break; default: return; } boolean conversionDone = false; if (invocations == null) { return; } for (DelegatingCacheEntryListenerInvocation<K, V> invocation : invocations) { if (invocation.getObservation().shouldInvoke(event.isPre())) { if (!conversionDone) { if (filterAndConvert && event instanceof EventImpl) { //todo [anistor] can it not be an EventImpl? can it not be filterAndConvert? EventImpl<K, V> eventImpl = (EventImpl<K, V>) event; EventImpl<K, V> clone = eventImpl.clone(); clone.setValue((V) makeFilterResult(userContext, eventType, event.getKey(), projection == null ? instance : null, projection, sortProjection)); event = clone; } conversionDone = true; } // TODO: [anistor] // TODO: We need a way to propagate the CompletionStages down to the caller - so continuous query // can be non blocking. This is to be fixed in https://issues.jboss.org/browse/ISPN-9729 CompletionStage<Void> invocationStage = invocation.invokeNoChecks(new EventWrapper<>(event.getKey(), event, null), false, filterAndConvert, true); if (invocationStage != null) { CompletionStages.join(invocationStage); } } } } } private final class DelegatingCacheEntryListenerInvocationImpl<K, V> extends DelegatingCacheEntryListenerInvocation<K, V> { protected Callback<K, V> callback; DelegatingCacheEntryListenerInvocationImpl(CacheEntryListenerInvocation<K, V> invocation) { super(invocation); } @Override public void unregister() { if (callback != null) { callback.unregister(); } } } private final class FilteringListenerInvocation<K, V> implements CacheEntryListenerInvocation<K, V> { private final Matcher matcher; private final DataConversion keyDataConversion; private final DataConversion valueDataConversion; private FilteringListenerInvocation(Matcher matcher, DataConversion keyDataConversion, DataConversion valueDataConversion) { this.matcher = matcher; this.keyDataConversion = keyDataConversion; this.valueDataConversion = valueDataConversion; } @Override public Object getTarget() { return BaseIckleFilterIndexingServiceProvider.this; } @Override public CompletionStage<Void> invoke(Event<K, V> event) { return null; } @Override public CompletionStage<Void> invoke(EventWrapper<K, V, CacheEntryEvent<K, V>> event, boolean isLocalNodePrimaryOwner) { // TODO: make this non blocking at some point? matchEvent(event, matcher); return null; } @Override public CompletionStage<Void> invokeNoChecks(EventWrapper<K, V, CacheEntryEvent<K, V>> event, boolean skipQueue, boolean skipConverter, boolean needsConvert) { return null; } @Override public boolean isClustered() { return false; } @Override public boolean isSync() { return true; } @Override public UUID getIdentifier() { return null; } @Override public Listener.Observation getObservation() { return Listener.Observation.BOTH; } @Override public Class<? extends Annotation> getAnnotation() { return null; } @Override public CacheEventFilter<? super K, ? super V> getFilter() { return null; } @Override public <C> CacheEventConverter<? super K, ? super V, C> getConverter() { return null; } @Override public Set<Class<? extends Annotation>> getFilterAnnotations() { return null; } @Override public DataConversion getKeyDataConversion() { return keyDataConversion; } @Override public DataConversion getValueDataConversion() { return valueDataConversion; } @Override public boolean useStorageFormat() { return true; } } protected abstract Matcher getMatcher(IndexedFilter<?, ?, ?> indexedFilter); protected abstract String getQueryString(IndexedFilter<?, ?, ?> indexedFilter); protected abstract Map<String, Object> getNamedParameters(IndexedFilter<?, ?, ?> indexedFilter); protected abstract boolean isDelta(IndexedFilter<?, ?, ?> indexedFilter); protected abstract <K, V> void matchEvent(EventWrapper<K, V, CacheEntryEvent<K, V>> eventWrapper, Matcher matcher); protected abstract Object makeFilterResult(Object userContext, Object eventType, Object key, Object instance, Object[] projection, Comparable[] sortProjection); }
19,118
46.7975
207
java
null
infinispan-main/query-core/src/main/java/org/infinispan/query/core/impl/continuous/package-info.java
/** * Continuous query implementation. */ package org.infinispan.query.core.impl.continuous;
95
18.2
50
java
null
infinispan-main/query-core/src/main/java/org/infinispan/query/core/impl/continuous/IckleContinuousQueryFilterIndexingServiceProvider.java
package org.infinispan.query.core.impl.continuous; import java.util.Map; import org.infinispan.commons.marshall.WrappedByteArray; import org.infinispan.notifications.cachelistener.EventWrapper; import org.infinispan.notifications.cachelistener.event.CacheEntryEvent; import org.infinispan.notifications.cachelistener.event.CacheEntryRemovedEvent; import org.infinispan.notifications.cachelistener.event.Event; import org.infinispan.notifications.cachelistener.event.impl.EventImpl; import org.infinispan.notifications.cachelistener.filter.FilterIndexingServiceProvider; import org.infinispan.notifications.cachelistener.filter.IndexedFilter; import org.infinispan.objectfilter.Matcher; import org.infinispan.query.core.impl.eventfilter.BaseIckleFilterIndexingServiceProvider; import org.kohsuke.MetaInfServices; /** * @author anistor@redhat.com * @since 8.1 */ @MetaInfServices(FilterIndexingServiceProvider.class) public class IckleContinuousQueryFilterIndexingServiceProvider extends BaseIckleFilterIndexingServiceProvider { private final Object joiningEvent; private final Object updatedEvent; private final Object leavingEvent; public IckleContinuousQueryFilterIndexingServiceProvider() { this(ContinuousQueryResult.ResultType.JOINING, ContinuousQueryResult.ResultType.UPDATED, ContinuousQueryResult.ResultType.LEAVING); } protected IckleContinuousQueryFilterIndexingServiceProvider(Object joiningEvent, Object updatedEvent, Object leavingEvent) { this.joiningEvent = joiningEvent; this.updatedEvent = updatedEvent; this.leavingEvent = leavingEvent; } @Override public boolean supportsFilter(IndexedFilter<?, ?, ?> indexedFilter) { return indexedFilter.getClass() == IckleContinuousQueryCacheEventFilterConverter.class; } @Override protected Matcher getMatcher(IndexedFilter<?, ?, ?> indexedFilter) { return ((IckleContinuousQueryCacheEventFilterConverter) indexedFilter).getMatcher(); } @Override protected String getQueryString(IndexedFilter<?, ?, ?> indexedFilter) { return ((IckleContinuousQueryCacheEventFilterConverter) indexedFilter).getQueryString(); } @Override protected Map<String, Object> getNamedParameters(IndexedFilter<?, ?, ?> indexedFilter) { return ((IckleContinuousQueryCacheEventFilterConverter) indexedFilter).getNamedParameters(); } @Override protected boolean isDelta(IndexedFilter<?, ?, ?> indexedFilter) { return true; } @Override protected <K, V> void matchEvent(EventWrapper<K, V, CacheEntryEvent<K, V>> eventWrapper, Matcher matcher) { CacheEntryEvent<?, ?> event = eventWrapper.getEvent(); Object oldValue = event.getType() == Event.Type.CACHE_ENTRY_REMOVED ? ((CacheEntryRemovedEvent) event).getOldValue() : null; if (event.getType() == Event.Type.CACHE_ENTRY_MODIFIED) { oldValue = ((EventImpl) event).getOldValue(); } Object newValue = event.getValue(); if (event.getType() == Event.Type.CACHE_ENTRY_EXPIRED) { oldValue = newValue; // expired events have the expired value as newValue newValue = null; } if (oldValue != null || newValue != null) { if (oldValue != null && oldValue.getClass() == WrappedByteArray.class) { oldValue = ((WrappedByteArray) oldValue).getBytes(); } if (newValue != null && newValue.getClass() == WrappedByteArray.class) { newValue = ((WrappedByteArray) newValue).getBytes(); } matcher.matchDelta(eventWrapper, event.getType(), oldValue, newValue, joiningEvent, updatedEvent, leavingEvent); } } @Override protected Object makeFilterResult(Object userContext, Object eventType, Object key, Object instance, Object[] projection, Comparable[] sortProjection) { return new ContinuousQueryResult<>((ContinuousQueryResult.ResultType) eventType, instance, projection); } }
3,942
41.397849
155
java
null
infinispan-main/query-core/src/main/java/org/infinispan/query/core/impl/continuous/IckleContinuousQueryCacheEventFilterConverter.java
package org.infinispan.query.core.impl.continuous; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Set; import org.infinispan.Cache; import org.infinispan.commons.CacheException; import org.infinispan.commons.io.UnsignedNumeric; import org.infinispan.commons.marshall.AbstractExternalizer; import org.infinispan.factories.ComponentRegistry; import org.infinispan.factories.annotations.Inject; import org.infinispan.factories.scopes.Scope; import org.infinispan.factories.scopes.Scopes; import org.infinispan.metadata.Metadata; import org.infinispan.notifications.cachelistener.filter.AbstractCacheEventFilterConverter; import org.infinispan.notifications.cachelistener.filter.EventType; import org.infinispan.notifications.cachelistener.filter.IndexedFilter; import org.infinispan.objectfilter.Matcher; import org.infinispan.objectfilter.ObjectFilter; import org.infinispan.query.core.impl.ExternalizerIds; import org.infinispan.query.core.impl.QueryCache; /** * @author anistor@redhat.com * @since 8.0 */ @Scope(Scopes.NONE) public class IckleContinuousQueryCacheEventFilterConverter<K, V, C> extends AbstractCacheEventFilterConverter<K, V, C> implements IndexedFilter<K, V, C> { /** * The Ickle query to execute. */ protected final String queryString; protected final Map<String, Object> namedParameters; /** * The implementation class of the Matcher component to lookup and use. */ protected Class<? extends Matcher> matcherImplClass; protected String cacheName; /** * Optional cache for query objects. */ protected QueryCache queryCache; /** * The Matcher, acquired via dependency injection. */ protected Matcher matcher; /** * The ObjectFilter is created lazily. */ protected ObjectFilter objectFilter; public IckleContinuousQueryCacheEventFilterConverter(String queryString, Map<String, Object> namedParameters, Class<? extends Matcher> matcherImplClass) { if (queryString == null || matcherImplClass == null) { throw new IllegalArgumentException("Arguments cannot be null"); } this.queryString = queryString; this.namedParameters = namedParameters; this.matcherImplClass = matcherImplClass; } public Matcher getMatcher() { return matcher; } public String getQueryString() { return queryString; } public Map<String, Object> getNamedParameters() { return namedParameters; } /** * Acquires a Matcher instance from the ComponentRegistry of the given Cache object. */ @Inject protected void injectDependencies(Cache<?, ?> cache) { cacheName = cache.getName(); ComponentRegistry componentRegistry = cache.getAdvancedCache().getComponentRegistry(); queryCache = componentRegistry.getComponent(QueryCache.class); matcher = componentRegistry.getComponent(matcherImplClass); if (matcher == null) { throw new CacheException("Expected component not found in registry: " + matcherImplClass.getName()); } } protected ObjectFilter getObjectFilter() { if (objectFilter == null) { objectFilter = queryCache != null ? queryCache.get(cacheName, queryString, null, matcherImplClass, (qs, accumulators) -> matcher.getObjectFilter(qs)) : matcher.getObjectFilter(queryString); } return namedParameters != null ? objectFilter.withParameters(namedParameters) : objectFilter; } @Override public C filterAndConvert(K key, V oldValue, Metadata oldMetadata, V newValue, Metadata newMetadata, EventType eventType) { if (eventType.isExpired()) { oldValue = newValue; // expired events have the expired value as newValue newValue = null; } ObjectFilter objectFilter = getObjectFilter(); ObjectFilter.FilterResult f1 = oldValue == null ? null : objectFilter.filter(key, oldValue); ObjectFilter.FilterResult f2 = newValue == null ? null : objectFilter.filter(key, newValue); if (f1 == null) { if (f2 != null) { // result joining return (C) new ContinuousQueryResult<>(ContinuousQueryResult.ResultType.JOINING, f2.getProjection() == null ? newValue : null, f2.getProjection()); } } else { if (f2 != null) { // result updated return (C) new ContinuousQueryResult<>(ContinuousQueryResult.ResultType.UPDATED, f2.getProjection() == null ? newValue : null, f2.getProjection()); } else { // result leaving return (C) new ContinuousQueryResult<V>(ContinuousQueryResult.ResultType.LEAVING, null, null); } } return null; } @Override public String toString() { return "IckleContinuousQueryCacheEventFilterConverter{queryString='" + queryString + "'}"; } public static final class Externalizer extends AbstractExternalizer<IckleContinuousQueryCacheEventFilterConverter> { @Override public void writeObject(ObjectOutput output, IckleContinuousQueryCacheEventFilterConverter filterAndConverter) throws IOException { output.writeUTF(filterAndConverter.queryString); Map<String, Object> namedParameters = filterAndConverter.namedParameters; if (namedParameters != null) { UnsignedNumeric.writeUnsignedInt(output, namedParameters.size()); for (Map.Entry<String, Object> e : namedParameters.entrySet()) { output.writeUTF(e.getKey()); output.writeObject(e.getValue()); } } else { UnsignedNumeric.writeUnsignedInt(output, 0); } output.writeObject(filterAndConverter.matcherImplClass); } @Override public IckleContinuousQueryCacheEventFilterConverter readObject(ObjectInput input) throws IOException, ClassNotFoundException { String queryString = input.readUTF(); int paramsSize = UnsignedNumeric.readUnsignedInt(input); Map<String, Object> namedParameters = null; if (paramsSize != 0) { namedParameters = new HashMap<>(paramsSize); for (int i = 0; i < paramsSize; i++) { String paramName = input.readUTF(); Object paramValue = input.readObject(); namedParameters.put(paramName, paramValue); } } Class<? extends Matcher> matcherImplClass = (Class<? extends Matcher>) input.readObject(); return new IckleContinuousQueryCacheEventFilterConverter(queryString, namedParameters, matcherImplClass); } @Override public Integer getId() { return ExternalizerIds.ICKLE_CONTINUOUS_QUERY_CACHE_EVENT_FILTER_CONVERTER; } @Override public Set<Class<? extends IckleContinuousQueryCacheEventFilterConverter>> getTypeClasses() { return Collections.singleton(IckleContinuousQueryCacheEventFilterConverter.class); } } }
7,091
36.723404
159
java
null
infinispan-main/query-core/src/main/java/org/infinispan/query/core/impl/continuous/ContinuousQueryImpl.java
package org.infinispan.query.core.impl.continuous; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; import org.infinispan.Cache; import org.infinispan.notifications.Listener; import org.infinispan.notifications.cachelistener.annotation.CacheEntryCreated; import org.infinispan.notifications.cachelistener.annotation.CacheEntryExpired; import org.infinispan.notifications.cachelistener.annotation.CacheEntryModified; import org.infinispan.notifications.cachelistener.annotation.CacheEntryRemoved; import org.infinispan.notifications.cachelistener.event.CacheEntryEvent; import org.infinispan.objectfilter.impl.ReflectionMatcher; import org.infinispan.query.api.continuous.ContinuousQuery; import org.infinispan.query.api.continuous.ContinuousQueryListener; import org.infinispan.query.dsl.Query; /** * A container of continuous query listeners for a cache. * <p>This class is not threadsafe. * * @author anistor@redhat.com * @since 8.2 */ public final class ContinuousQueryImpl<K, V> implements ContinuousQuery<K, V> { private final Cache<K, V> cache; private final List<EntryListener<K, V, ?>> listeners = new ArrayList<>(); public ContinuousQueryImpl(Cache<K, V> cache) { if (cache == null) { throw new IllegalArgumentException("cache parameter cannot be null"); } this.cache = cache; } @Override public <C> void addContinuousQueryListener(String queryString, ContinuousQueryListener<K, C> listener) { addContinuousQueryListener(queryString, null, listener); } @Override public <C> void addContinuousQueryListener(String queryString, Map<String, Object> namedParameters, ContinuousQueryListener<K, C> listener) { EntryListener<K, V, C> entryListener = new EntryListener<>(listener); IckleContinuousQueryCacheEventFilterConverter<K, V, ContinuousQueryResult<V>> filterConverter = new IckleContinuousQueryCacheEventFilterConverter<>(queryString, namedParameters, ReflectionMatcher.class); cache.addListener(entryListener, filterConverter, null); listeners.add(entryListener); } @Override public <C> void addContinuousQueryListener(Query<?> query, ContinuousQueryListener<K, C> listener) { addContinuousQueryListener(query.getQueryString(), query.getParameters(), listener); } @Override public void removeContinuousQueryListener(ContinuousQueryListener<K, ?> listener) { for (Iterator<EntryListener<K, V, ?>> it = listeners.iterator(); it.hasNext(); ) { EntryListener<K, V, ?> l = it.next(); if (l.listener == listener) { cache.removeListener(l); it.remove(); break; } } } @Override public List<ContinuousQueryListener<K, ?>> getListeners() { List<ContinuousQueryListener<K, ?>> queryListeners = new ArrayList<>(listeners.size()); for (EntryListener<K, V, ?> l : listeners) { queryListeners.add(l.listener); } return queryListeners; } @Override public void removeAllListeners() { for (EntryListener<K, V, ?> l : listeners) { cache.removeListener(l); } listeners.clear(); } @Listener(clustered = true, includeCurrentState = true, observation = Listener.Observation.POST) private static final class EntryListener<K, V, C> { private final ContinuousQueryListener<K, C> listener; EntryListener(ContinuousQueryListener<K, C> listener) { this.listener = listener; } @CacheEntryRemoved @CacheEntryCreated @CacheEntryModified @CacheEntryExpired public void handleEvent(CacheEntryEvent<K, ContinuousQueryResult<V>> event) { ContinuousQueryResult<V> cqr = event.getValue(); switch (cqr.getResultType()) { case JOINING: { C value = cqr.getValue() != null ? (C) cqr.getValue() : (C) cqr.getProjection(); listener.resultJoining(event.getKey(), value); break; } case UPDATED: { C value = cqr.getValue() != null ? (C) cqr.getValue() : (C) cqr.getProjection(); listener.resultUpdated(event.getKey(), value); break; } case LEAVING: { listener.resultLeaving(event.getKey()); break; } default: throw new IllegalStateException("Unexpected result type : " + cqr.getResultType()); } } } }
4,532
35.556452
144
java
null
infinispan-main/query-core/src/main/java/org/infinispan/query/core/impl/continuous/ContinuousQueryResult.java
package org.infinispan.query.core.impl.continuous; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.util.Arrays; import java.util.Collections; import java.util.Set; import org.infinispan.commons.marshall.AbstractExternalizer; import org.infinispan.query.core.impl.ExternalizerIds; /** * @author anistor@redhat.com * @since 8.0 */ public final class ContinuousQueryResult<V> { public enum ResultType { JOINING, UPDATED, LEAVING } private final ResultType resultType; private final V value; private final Object[] projection; ContinuousQueryResult(ResultType resultType, V value, Object[] projection) { this.resultType = resultType; this.value = value; this.projection = projection; } public ResultType getResultType() { return resultType; } public V getValue() { return value; } public Object[] getProjection() { return projection; } @Override public String toString() { return "ContinuousQueryResult{" + "resultType=" + resultType + ", value=" + value + ", projection=" + Arrays.toString(projection) + '}'; } public static final class Externalizer extends AbstractExternalizer<ContinuousQueryResult> { @Override public void writeObject(ObjectOutput output, ContinuousQueryResult continuousQueryResult) throws IOException { output.writeInt(continuousQueryResult.resultType.ordinal()); if (continuousQueryResult.resultType != ResultType.LEAVING) { if (continuousQueryResult.projection != null) { // skip serializing the instance if there is a projection output.writeObject(null); int projLen = continuousQueryResult.projection.length; output.writeInt(projLen); for (int i = 0; i < projLen; i++) { output.writeObject(continuousQueryResult.projection[i]); } } else { output.writeObject(continuousQueryResult.value); } } } @Override public ContinuousQueryResult readObject(ObjectInput input) throws IOException, ClassNotFoundException { ResultType type = ResultType.values()[input.readInt()]; Object value = null; Object[] projection = null; if (type != ResultType.LEAVING) { value = input.readObject(); if (value == null) { int projLen = input.readInt(); projection = new Object[projLen]; for (int i = 0; i < projLen; i++) { projection[i] = input.readObject(); } } } return new ContinuousQueryResult<>(type, value, projection); } @Override public Integer getId() { return ExternalizerIds.ICKLE_CONTINUOUS_QUERY_RESULT; } @Override public Set<Class<? extends ContinuousQueryResult>> getTypeClasses() { return Collections.singleton(ContinuousQueryResult.class); } } }
3,136
28.317757
116
java
null
infinispan-main/query-core/src/main/java/org/infinispan/query/core/stats/IndexInfo.java
package org.infinispan.query.core.stats; import org.infinispan.commons.dataconversion.internal.Json; import org.infinispan.commons.dataconversion.internal.JsonSerialization; import org.infinispan.commons.marshall.ProtoStreamTypeIds; import org.infinispan.protostream.annotations.ProtoFactory; import org.infinispan.protostream.annotations.ProtoField; import org.infinispan.protostream.annotations.ProtoTypeId; /** * Runtime information about an index. * * @since 12.0 */ @ProtoTypeId(ProtoStreamTypeIds.INDEX_INFO) public class IndexInfo implements JsonSerialization { private final long count; private final long size; @ProtoFactory public IndexInfo(long count, long size) { this.count = count; this.size = size; } /** * @return Number of entities indexed. */ @ProtoField(number = 1, defaultValue = "0") public long count() { return count; } /** * @return Size of index in bytes. */ @ProtoField(number = 2, defaultValue = "0") public long size() { return size; } public IndexInfo merge(IndexInfo indexInfo) { long mergedCount = count, mergedSize = size; mergedCount += indexInfo.count; mergedSize += indexInfo.size; return new IndexInfo(mergedCount, mergedSize); } @Override public Json toJson() { return Json.object() .set("count", count()) .set("size", size()); } @Override public String toString() { return "IndexInfo{" + "count=" + count + ", size=" + size + '}'; } }
1,584
23.765625
72
java
null
infinispan-main/query-core/src/main/java/org/infinispan/query/core/stats/QueryStatisticsSnapshot.java
package org.infinispan.query.core.stats; import org.infinispan.commons.dataconversion.internal.JsonSerialization; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionStage; /** * A snapshot of {@link QueryStatistics}. * * @see QueryStatistics#computeSnapshot() * @since 12.0 */ public interface QueryStatisticsSnapshot extends QueryStatistics, JsonSerialization { @Override default CompletionStage<QueryStatisticsSnapshot> computeSnapshot() { return CompletableFuture.completedFuture(this); } /** * Merge with another {@link QueryStatisticsSnapshot} * * @return self. */ QueryStatisticsSnapshot merge(QueryStatisticsSnapshot other); }
716
23.724138
85
java
null
infinispan-main/query-core/src/main/java/org/infinispan/query/core/stats/SearchStatistics.java
package org.infinispan.query.core.stats; import java.util.concurrent.CompletionStage; /** * Exposes query and index statistics for a cache. * * @since 12.0 */ public interface SearchStatistics { /** * @return {@link QueryStatistics} */ QueryStatistics getQueryStatistics(); /** * @return {@link IndexStatistics} */ IndexStatistics getIndexStatistics(); /** * @return A snapshot of self. */ CompletionStage<SearchStatisticsSnapshot> computeSnapshot(); }
505
17.071429
63
java
null
infinispan-main/query-core/src/main/java/org/infinispan/query/core/stats/QueryStatistics.java
package org.infinispan.query.core.stats; import java.util.concurrent.CompletionStage; /** * Exposes query statistics for a particular cache. * * @since 12.0 */ public interface QueryStatistics { /** * @return Number of queries executed in the local index. */ long getLocalIndexedQueryCount(); /** * @return Number of distributed indexed queries executed from the local node. */ long getDistributedIndexedQueryCount(); /** * @return Number of hybrid queries (two phase indexed and non-indexed) executed from the local node. */ long getHybridQueryCount(); /** * @return Number of non-indexed queries executed from the local node. */ long getNonIndexedQueryCount(); /** * @return The total time in nanoseconds of all indexed queries. */ long getLocalIndexedQueryTotalTime(); /** * @return The total time in nanoseconds of all distributed indexed queries. */ long getDistributedIndexedQueryTotalTime(); /** * @return The total time in nanoseconds for all hybrid queries. */ long getHybridQueryTotalTime(); /** * @return The total time in nanoseconds for all non-indexed queries. */ long getNonIndexedQueryTotalTime(); /** * @return The time in nanoseconds of the slowest indexed query. */ long getLocalIndexedQueryMaxTime(); /** * @return The time in nanoseconds of the slowest distributed indexed query. */ long getDistributedIndexedQueryMaxTime(); /** * @return The time in nanoseconds of the slowest hybrid query. */ long getHybridQueryMaxTime(); /** * @return The time in nanoseconds of the slowest non-indexed query. */ long getNonIndexedQueryMaxTime(); /** * @return The average time in nanoseconds of all indexed queries. */ double getLocalIndexedQueryAvgTime(); /** * @return The average time in nanoseconds of all distributed indexed queries. */ double getDistributedIndexedQueryAvgTime(); /** * @return The average time in nanoseconds of all hybrid indexed queries. */ double getHybridQueryAvgTime(); /** * @return The average time in nanoseconds of all non-indexed indexed queries. */ double getNonIndexedQueryAvgTime(); /** * @return The Ickle query string of the slowest indexed query. */ String getSlowestLocalIndexedQuery(); /** * @return The Ickle query string of the slowest distributed indexed query. */ String getSlowestDistributedIndexedQuery(); /** * @return The Ickle query string of the slowest hybrid query. */ String getSlowestHybridQuery(); /** * @return The Ickle query string of the slowest non-indexed query. */ String getSlowestNonIndexedQuery(); /** * @return The max time in nanoseconds to load entities from a Cache after an indexed query. */ long getLoadMaxTime(); /** * @return The average time in nanoseconds to load entities from a Cache after an indexed query. */ double getLoadAvgTime(); /** * @return The number of operations to load entities from a Cache after an indexed query. */ long getLoadCount(); /** * @return The total time to load entities from a Cache after an indexed query. */ long getLoadTotalTime(); /** * Clear all statistics. */ void clear(); /** * @return A snapshot of self. */ CompletionStage<QueryStatisticsSnapshot> computeSnapshot(); /** * @return true if the Cache has statistics enabled. */ boolean isEnabled(); }
3,586
23.401361
104
java
null
infinispan-main/query-core/src/main/java/org/infinispan/query/core/stats/SearchStatisticsSnapshot.java
package org.infinispan.query.core.stats; import org.infinispan.commons.dataconversion.internal.JsonSerialization; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionStage; /** * A snapshot of {@link SearchStatistics}. * * @since 12.0 */ public interface SearchStatisticsSnapshot extends SearchStatistics, JsonSerialization { @Override QueryStatisticsSnapshot getQueryStatistics(); @Override IndexStatisticsSnapshot getIndexStatistics(); @Override default CompletionStage<SearchStatisticsSnapshot> computeSnapshot() { return CompletableFuture.completedFuture(this); } /** * Merge with another {@link SearchStatisticsSnapshot} * * @return self. */ SearchStatisticsSnapshot merge(SearchStatisticsSnapshot other); }
806
23.454545
87
java
null
infinispan-main/query-core/src/main/java/org/infinispan/query/core/stats/IndexStatisticsSnapshot.java
package org.infinispan.query.core.stats; import org.infinispan.commons.dataconversion.internal.JsonSerialization; import java.util.Map; import java.util.Set; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionStage; /** * A snapshot of {@link IndexStatistics}. * * @since 12.0 * @see IndexStatistics#computeSnapshot() */ public interface IndexStatisticsSnapshot extends IndexStatistics, JsonSerialization { @Override default Set<String> indexedEntities() { return indexInfos().keySet(); } @Override default CompletionStage<Map<String, IndexInfo>> computeIndexInfos() { return CompletableFuture.completedFuture(indexInfos()); } @Override default CompletionStage<IndexStatisticsSnapshot> computeSnapshot() { return CompletableFuture.completedFuture(this); } /** * @return The {@link IndexInfo} for each indexed entity configured in the cache. The name of the entity is * either the class name annotated with @Index, or the protobuf Message name. */ Map<String, IndexInfo> indexInfos(); /** * Merge with another {@link IndexStatisticsSnapshot}. * * @return self */ IndexStatisticsSnapshot merge(IndexStatisticsSnapshot other); }
1,285
26.361702
111
java
null
infinispan-main/query-core/src/main/java/org/infinispan/query/core/stats/IndexStatistics.java
package org.infinispan.query.core.stats; import java.util.Map; import java.util.Set; import java.util.concurrent.CompletionStage; /** * * Exposes index statistics for a particular cache. * * @since 12.0 */ public interface IndexStatistics { /** * @return The name of all indexed entities configured in the cache. The name of the entity is * either the class name annotated with @Index, or the protobuf Message name. */ Set<String> indexedEntities(); /** * @return The {@link IndexInfo} for each indexed entity configured in the cache. The name of the entity is * either the class name annotated with @Index, or the protobuf Message name. */ CompletionStage<Map<String, IndexInfo>> computeIndexInfos(); boolean reindexing(); int genericIndexingFailures(); int entityIndexingFailures(); CompletionStage<IndexStatisticsSnapshot> computeSnapshot(); }
909
24.277778
110
java
null
infinispan-main/query-core/src/main/java/org/infinispan/query/core/stats/impl/SearchStatsRetriever.java
package org.infinispan.query.core.stats.impl; import java.util.Collection; import java.util.concurrent.CompletionStage; import java.util.concurrent.ConcurrentLinkedQueue; import org.infinispan.Cache; import org.infinispan.commons.CacheException; import org.infinispan.commons.util.Util; import org.infinispan.factories.annotations.Inject; import org.infinispan.factories.scopes.Scope; import org.infinispan.factories.scopes.Scopes; import org.infinispan.manager.ClusterExecutor; import org.infinispan.query.core.stats.IndexStatistics; import org.infinispan.query.core.stats.SearchStatistics; import org.infinispan.query.core.stats.SearchStatisticsSnapshot; import org.infinispan.security.actions.SecurityActions; /** * Retrieves {@link SearchStatistics} for a cache. * * @since 12.0 */ @Scope(Scopes.NAMED_CACHE) public class SearchStatsRetriever { @Inject LocalQueryStatistics localQueryStatistics; @Inject IndexStatistics localIndexStatistics; @Inject Cache<?, ?> cache; public SearchStatistics getSearchStatistics() { return new SearchStatisticsImpl(localQueryStatistics, localIndexStatistics); } public CompletionStage<SearchStatisticsSnapshot> getDistributedSearchStatistics() { StatsTask statsTask = new StatsTask(cache.getName()); ClusterExecutor clusterExecutor = SecurityActions.getClusterExecutor(cache); Collection<SearchStatisticsSnapshot> stats = new ConcurrentLinkedQueue<>(); return clusterExecutor.submitConsumer(statsTask, (address, searchStats, throwable) -> { if (throwable != null) { Throwable rootCause = Util.getRootCause(throwable); throw new CacheException("Error obtaining statistics from node", rootCause); } stats.add(searchStats); }).thenApply(v -> stats.stream().reduce(new SearchStatisticsSnapshotImpl(), SearchStatisticsSnapshot::merge)); } }
1,891
39.255319
116
java
null
infinispan-main/query-core/src/main/java/org/infinispan/query/core/stats/impl/PersistenceContextInitializer.java
package org.infinispan.query.core.stats.impl; import org.infinispan.protostream.SerializationContextInitializer; import org.infinispan.protostream.annotations.AutoProtoSchemaBuilder; import org.infinispan.query.core.stats.IndexInfo; /** * @since 12.0 */ @AutoProtoSchemaBuilder( includeClasses = { QueryMetrics.class, LocalQueryStatistics.class, IndexStatisticsSnapshotImpl.class, SearchStatisticsSnapshotImpl.class, IndexInfo.class, IndexEntry.class, StatsTask.class }, schemaFileName = "persistence.query.core.proto", schemaFilePath = "proto/generated", schemaPackageName = "org.infinispan.persistence.query.core" ) interface PersistenceContextInitializer extends SerializationContextInitializer { }
820
30.576923
81
java
null
infinispan-main/query-core/src/main/java/org/infinispan/query/core/stats/impl/QueryMetrics.java
package org.infinispan.query.core.stats.impl; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.LongAdder; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; import org.infinispan.commons.dataconversion.internal.Json; import org.infinispan.commons.dataconversion.internal.JsonSerialization; import org.infinispan.commons.marshall.ProtoStreamTypeIds; import org.infinispan.protostream.annotations.ProtoFactory; import org.infinispan.protostream.annotations.ProtoField; import org.infinispan.protostream.annotations.ProtoTypeId; /** * Store statistics for a certain kind of query. * * @since 12.0 */ @ProtoTypeId(ProtoStreamTypeIds.QUERY_METRICS) class QueryMetrics implements JsonSerialization { final LongAdder count = new LongAdder(); final LongAdder totalTime = new LongAdder(); final AtomicLong maxTime = new AtomicLong(-1); volatile String slowest = null; final ReadWriteLock lock = new ReentrantReadWriteLock(); final Lock recordLock = lock.readLock(); final Lock summaryLock = lock.writeLock(); public QueryMetrics() { count.reset(); totalTime.reset(); } @ProtoFactory public QueryMetrics(long count, long totalTime, long maxTime, String slowest) { this.count.add(count); this.totalTime.add(totalTime); this.maxTime.set(maxTime); this.slowest = slowest; } @ProtoField(number = 1, defaultValue = "0") long count() { return count.longValue(); } @ProtoField(number = 2, defaultValue = "0") long totalTime() { return totalTime.longValue(); } @ProtoField(number = 3, defaultValue = "0") long maxTime() { return maxTime.get(); } @ProtoField(number = 4) public String slowest() { return slowest; } double avg() { summaryLock.lock(); try { long countValue = count.longValue(); if (countValue == 0) return 0; return this.totalTime.doubleValue() / count.longValue(); } finally { summaryLock.unlock(); } } void record(String q, long timeNanos) { recordLock.lock(); try { count.increment(); totalTime.add(timeNanos); updateMaxQuery(q, timeNanos); } finally { recordLock.unlock(); } } void record(long timeNanos) { record(null, timeNanos); } void clear() { count.reset(); totalTime.reset(); maxTime.set(0); slowest = null; } private void updateMaxQuery(String q, long time) { long localMax = maxTime.get(); while (time > localMax) { if (maxTime.compareAndSet(localMax, time)) { slowest = q; return; } localMax = maxTime.get(); } } @Override public Json toJson() { Json object = Json.object().set("count", count()).set("average", avg()).set("max", maxTime()); if (slowest != null) object.set("slowest", slowest()); return object; } }
3,083
25.358974
100
java
null
infinispan-main/query-core/src/main/java/org/infinispan/query/core/stats/impl/StatsTask.java
package org.infinispan.query.core.stats.impl; import java.util.function.Function; import org.infinispan.Cache; import org.infinispan.commons.marshall.ProtoStreamTypeIds; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.protostream.annotations.ProtoFactory; import org.infinispan.protostream.annotations.ProtoField; import org.infinispan.protostream.annotations.ProtoTypeId; import org.infinispan.query.core.stats.SearchStatisticsSnapshot; import org.infinispan.security.actions.SecurityActions; import org.infinispan.util.concurrent.CompletionStages; @ProtoTypeId(ProtoStreamTypeIds.STATS_TASK) public class StatsTask implements Function<EmbeddedCacheManager, SearchStatisticsSnapshot> { @ProtoField(number = 1) String cacheName; @ProtoFactory public StatsTask(String cacheName) { this.cacheName = cacheName; } @Override public SearchStatisticsSnapshot apply(EmbeddedCacheManager cacheManager) { Cache<?, ?> cache = SecurityActions.getCache(cacheManager, cacheName); SearchStatsRetriever searchStatsRetriever = SecurityActions.getCacheComponentRegistry(cache.getAdvancedCache()).getComponent(SearchStatsRetriever.class); return CompletionStages.join(searchStatsRetriever.getSearchStatistics().computeSnapshot()); } }
1,296
38.30303
159
java
null
infinispan-main/query-core/src/main/java/org/infinispan/query/core/stats/impl/SearchStatisticsImpl.java
package org.infinispan.query.core.stats.impl; import org.infinispan.query.core.stats.IndexStatistics; import org.infinispan.query.core.stats.QueryStatistics; import org.infinispan.query.core.stats.SearchStatistics; import org.infinispan.query.core.stats.SearchStatisticsSnapshot; import java.util.concurrent.CompletionStage; /** * Query and Index statistics for a Cache. * * since 12.0 */ public final class SearchStatisticsImpl implements SearchStatistics { private QueryStatistics queryStatistics; private IndexStatistics indexStatistics; public SearchStatisticsImpl(QueryStatistics queryStatistics, IndexStatistics indexStatistics) { this.queryStatistics = queryStatistics; this.indexStatistics = indexStatistics; } @Override public QueryStatistics getQueryStatistics() { return queryStatistics; } @Override public IndexStatistics getIndexStatistics() { return indexStatistics; } @Override public CompletionStage<SearchStatisticsSnapshot> computeSnapshot() { return queryStatistics.computeSnapshot() .thenCombine(indexStatistics.computeSnapshot(), SearchStatisticsSnapshotImpl::new); } }
1,185
28.65
98
java
null
infinispan-main/query-core/src/main/java/org/infinispan/query/core/stats/impl/IndexEntry.java
package org.infinispan.query.core.stats.impl; import org.infinispan.commons.marshall.ProtoStreamTypeIds; import org.infinispan.protostream.annotations.ProtoFactory; import org.infinispan.protostream.annotations.ProtoField; import org.infinispan.protostream.annotations.ProtoTypeId; import org.infinispan.query.core.stats.IndexInfo; /** * Workaround to marshall a Map&lt;String,IndexInfo&gt;. * * @since 12.0 */ @ProtoTypeId(ProtoStreamTypeIds.INDEX_INFO_ENTRY) class IndexEntry { private final String name; private final IndexInfo indexInfo; @ProtoFactory public IndexEntry(String name, IndexInfo indexInfo) { this.name = name; this.indexInfo = indexInfo; } @ProtoField(number = 1) public String getName() { return name; } @ProtoField(number = 2) public IndexInfo getIndexInfo() { return indexInfo; } }
870
23.194444
59
java
null
infinispan-main/query-core/src/main/java/org/infinispan/query/core/stats/impl/SearchStatisticsSnapshotImpl.java
package org.infinispan.query.core.stats.impl; import org.infinispan.commons.dataconversion.internal.Json; import org.infinispan.commons.marshall.ProtoStreamTypeIds; import org.infinispan.protostream.annotations.ProtoFactory; import org.infinispan.protostream.annotations.ProtoField; import org.infinispan.protostream.annotations.ProtoTypeId; import org.infinispan.query.core.stats.IndexStatisticsSnapshot; import org.infinispan.query.core.stats.QueryStatisticsSnapshot; import org.infinispan.query.core.stats.SearchStatisticsSnapshot; /** * Query and Index statistics for a Cache. * <p> * since 12.0 */ @ProtoTypeId(ProtoStreamTypeIds.SEARCH_STATISTICS) public final class SearchStatisticsSnapshotImpl implements SearchStatisticsSnapshot { private final QueryStatisticsSnapshot queryStatistics; private final IndexStatisticsSnapshot indexStatistics; public SearchStatisticsSnapshotImpl() { this(new LocalQueryStatistics(), new IndexStatisticsSnapshotImpl()); } @ProtoFactory public SearchStatisticsSnapshotImpl(LocalQueryStatistics queryStatistics, IndexStatisticsSnapshotImpl indexStatistics) { this.queryStatistics = queryStatistics; this.indexStatistics = indexStatistics; } public SearchStatisticsSnapshotImpl(QueryStatisticsSnapshot queryStatistics, IndexStatisticsSnapshot indexStatistics) { this.queryStatistics = queryStatistics; this.indexStatistics = indexStatistics; } @Override @ProtoField(number = 1, javaType = LocalQueryStatistics.class) public QueryStatisticsSnapshot getQueryStatistics() { return queryStatistics; } @Override @ProtoField(number = 2, javaType = IndexStatisticsSnapshotImpl.class) public IndexStatisticsSnapshot getIndexStatistics() { return indexStatistics; } @Override public SearchStatisticsSnapshot merge(SearchStatisticsSnapshot other) { queryStatistics.merge(other.getQueryStatistics()); indexStatistics.merge(other.getIndexStatistics()); return this; } @Override public Json toJson() { return Json.object() .set("query", Json.make(queryStatistics)) .set("index", Json.make(indexStatistics)); } }
2,207
34.047619
123
java
null
infinispan-main/query-core/src/main/java/org/infinispan/query/core/stats/impl/IndexStatisticsSnapshotImpl.java
package org.infinispan.query.core.stats.impl; import org.infinispan.commons.dataconversion.internal.Json; import org.infinispan.commons.marshall.ProtoStreamTypeIds; import org.infinispan.protostream.annotations.ProtoFactory; import org.infinispan.protostream.annotations.ProtoField; import org.infinispan.protostream.annotations.ProtoTypeId; import org.infinispan.query.core.stats.IndexInfo; import org.infinispan.query.core.stats.IndexStatistics; import org.infinispan.query.core.stats.IndexStatisticsSnapshot; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; /** * A snapshot for {@link IndexStatistics}. * * @since 12.0 */ @ProtoTypeId(ProtoStreamTypeIds.LOCAL_INDEX_STATS) public class IndexStatisticsSnapshotImpl implements IndexStatisticsSnapshot { private final Map<String, IndexInfo> indexInfos; private final boolean reindexing; private int genericIndexingFailures; private int entityIndexingFailures; public IndexStatisticsSnapshotImpl() { // Don't use Collections.emptyMap() here, the map needs to be mutable to support merge(). this(new HashMap<>(), false, 0, 0); } @ProtoFactory public IndexStatisticsSnapshotImpl(List<IndexEntry> entries, boolean reindexing, int genericIndexingFailures, int entityIndexingFailures) { this(toMap(entries), reindexing, genericIndexingFailures, entityIndexingFailures); } public IndexStatisticsSnapshotImpl(Map<String, IndexInfo> indexInfos, boolean reindexing, int genericIndexingFailures, int entityIndexingFailures) { this.indexInfos = indexInfos; this.reindexing = reindexing; this.genericIndexingFailures = genericIndexingFailures; this.entityIndexingFailures = entityIndexingFailures; } @Override public Map<String, IndexInfo> indexInfos() { return indexInfos; } @ProtoField(number = 1, collectionImplementation = ArrayList.class) public List<IndexEntry> getEntries() { return fromMap(indexInfos); } static Map<String, IndexInfo> toMap(List<IndexEntry> entries) { return Collections.unmodifiableMap(entries.stream().collect(Collectors.toMap(IndexEntry::getName, IndexEntry::getIndexInfo))); } static List<IndexEntry> fromMap(Map<String, IndexInfo> map) { return map.entrySet().stream() .map(e -> new IndexEntry(e.getKey(), e.getValue())).collect(Collectors.toList()); } @Override @ProtoField(number = 2, defaultValue = "false") public boolean reindexing() { return reindexing; } @Override @ProtoField(number = 3, defaultValue = "0") public int genericIndexingFailures() { return genericIndexingFailures; } @Override @ProtoField(number = 4, defaultValue = "0") public int entityIndexingFailures() { return entityIndexingFailures; } @Override public Json toJson() { return Json.object() .set("types", Json.make(indexInfos)) .set("reindexing", Json.make(reindexing)) .set("genericIndexingFailures", Json.make(genericIndexingFailures)) .set("entityIndexingFailures", Json.make(entityIndexingFailures)); } @Override public IndexStatisticsSnapshot merge(IndexStatisticsSnapshot other) { other.indexInfos().forEach((k, v) -> indexInfos.merge(k, v, IndexInfo::merge)); genericIndexingFailures += other.genericIndexingFailures(); entityIndexingFailures += other.entityIndexingFailures(); return this; } }
3,574
33.708738
151
java
null
infinispan-main/query-core/src/main/java/org/infinispan/query/core/stats/impl/LocalQueryStatistics.java
package org.infinispan.query.core.stats.impl; import org.infinispan.commons.dataconversion.internal.Json; import org.infinispan.commons.marshall.ProtoStreamTypeIds; import org.infinispan.configuration.cache.Configuration; import org.infinispan.factories.annotations.Inject; import org.infinispan.factories.scopes.Scope; import org.infinispan.factories.scopes.Scopes; import org.infinispan.protostream.annotations.ProtoFactory; import org.infinispan.protostream.annotations.ProtoField; import org.infinispan.protostream.annotations.ProtoTypeId; import org.infinispan.query.core.stats.QueryStatisticsSnapshot; import org.infinispan.security.AuthorizationPermission; import org.infinispan.security.impl.Authorizer; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionStage; /** * Manages query statistics for a Cache. * * @since 12.0 */ @Scope(Scopes.NAMED_CACHE) @ProtoTypeId(ProtoStreamTypeIds.LOCAL_QUERY_STATS) public class LocalQueryStatistics implements QueryStatisticsSnapshot { @ProtoField(number = 1) QueryMetrics localIndexedQueries = new QueryMetrics(); @ProtoField(number = 2) QueryMetrics distIndexedQueries = new QueryMetrics(); @ProtoField(number = 3) QueryMetrics hybridQueries = new QueryMetrics(); @ProtoField(number = 4) QueryMetrics nonIndexedQueries = new QueryMetrics(); @ProtoField(number = 5) QueryMetrics loads = new QueryMetrics(); @Inject Configuration configuration; @Inject Authorizer authorizer; public LocalQueryStatistics() { } @ProtoFactory LocalQueryStatistics(QueryMetrics localIndexedQueries, QueryMetrics distIndexedQueries, QueryMetrics hybridQueries, QueryMetrics nonIndexedQueries, QueryMetrics loads) { this.localIndexedQueries = localIndexedQueries; this.distIndexedQueries = distIndexedQueries; this.hybridQueries = hybridQueries; this.nonIndexedQueries = nonIndexedQueries; this.loads = loads; } public void localIndexedQueryExecuted(String q, long timeNanos) { localIndexedQueries.record(q, timeNanos); } public void distributedIndexedQueryExecuted(String q, long timeNanos) { distIndexedQueries.record(q, timeNanos); } public void hybridQueryExecuted(String q, long timeNanos) { hybridQueries.record(q, timeNanos); } public void nonIndexedQueryExecuted(String q, long timeNanos) { nonIndexedQueries.record(q, timeNanos); } public void entityLoaded(long timeNanos) { loads.record(timeNanos); } /** * @return Number of queries executed in the local index. */ @Override public long getLocalIndexedQueryCount() { return localIndexedQueries.count(); } /** * @return Number of distributed indexed queries executed from the local node. */ @Override public long getDistributedIndexedQueryCount() { return distIndexedQueries.count(); } /** * @return Number of hybrid queries (two phase indexed and non-indexed) executed from the local node. */ @Override public long getHybridQueryCount() { return hybridQueries.count(); } /** * @return Number of non-indexed queries executed from the local node. */ @Override public long getNonIndexedQueryCount() { return nonIndexedQueries.count(); } /** * @return The total time in nanoseconds of all indexed queries. */ @Override public long getLocalIndexedQueryTotalTime() { return localIndexedQueries.totalTime(); } /** * @return The total time in nanoseconds of all distributed indexed queries. */ @Override public long getDistributedIndexedQueryTotalTime() { return distIndexedQueries.totalTime(); } /** * @return The total time in nanoseconds for all hybrid queries. */ @Override public long getHybridQueryTotalTime() { return hybridQueries.totalTime(); } /** * @return The total time in nanoseconds for all non-indexed queries. */ @Override public long getNonIndexedQueryTotalTime() { return nonIndexedQueries.totalTime(); } /** * @return The time in nanoseconds of the slowest indexed query. */ @Override public long getLocalIndexedQueryMaxTime() { return localIndexedQueries.maxTime(); } /** * @return The time in nanoseconds of the slowest distributed indexed query. */ @Override public long getDistributedIndexedQueryMaxTime() { return distIndexedQueries.maxTime(); } /** * @return The time in nanoseconds of the slowest hybrid query. */ @Override public long getHybridQueryMaxTime() { return hybridQueries.maxTime(); } /** * @return The time in nanoseconds of the slowest non-indexed query. */ @Override public long getNonIndexedQueryMaxTime() { return nonIndexedQueries.maxTime(); } /** * @return The average time in nanoseconds of all indexed queries. */ @Override public double getLocalIndexedQueryAvgTime() { return localIndexedQueries.avg(); } /** * @return The average time in nanoseconds of all distributed indexed queries. */ @Override public double getDistributedIndexedQueryAvgTime() { return distIndexedQueries.avg(); } /** * @return The average time in nanoseconds of all hybrid indexed queries. */ @Override public double getHybridQueryAvgTime() { return hybridQueries.avg(); } /** * @return The average time in nanoseconds of all non-indexed indexed queries. */ @Override public double getNonIndexedQueryAvgTime() { return nonIndexedQueries.avg(); } /** * @return The Ickle query string of the slowest indexed query. */ @Override public String getSlowestLocalIndexedQuery() { return localIndexedQueries.slowest(); } /** * @return The Ickle query string of the slowest distributed indexed query. */ @Override public String getSlowestDistributedIndexedQuery() { return distIndexedQueries.slowest(); } /** * @return The Ickle query string of the slowest hybrid query. */ @Override public String getSlowestHybridQuery() { return hybridQueries.slowest(); } /** * @return The Ickle query string of the slowest non-indexed query. */ @Override public String getSlowestNonIndexedQuery() { return nonIndexedQueries.slowest(); } /** * @return The max time in nanoseconds to load entities from a Cache after an indexed query. */ @Override public long getLoadMaxTime() { return loads.maxTime(); } /** * @return The average time in nanoseconds to load entities from a Cache after an indexed query. */ @Override public double getLoadAvgTime() { return loads.avg(); } /** * @return The number of entities loaded from a Cache after an indexed query. */ @Override public long getLoadCount() { return loads.count(); } /** * @return The total time to load entities from a Cache after an indexed query. */ @Override public long getLoadTotalTime() { return loads.totalTime(); } protected QueryMetrics getLocalIndexedQueries() { return localIndexedQueries; } protected QueryMetrics getDistIndexedQueries() { return distIndexedQueries; } protected QueryMetrics getHybridQueries() { return hybridQueries; } protected QueryMetrics getNonIndexedQueries() { return nonIndexedQueries; } public QueryMetrics getLoads() { return loads; } @Override public boolean isEnabled() { return configuration.statistics().enabled(); } @Override public CompletionStage<QueryStatisticsSnapshot> computeSnapshot() { return CompletableFuture.completedFuture(new LocalQueryStatistics().merge(this)); } @Override public void clear() { authorizer.checkPermission(AuthorizationPermission.ADMIN); localIndexedQueries.clear(); distIndexedQueries.clear(); nonIndexedQueries.clear(); hybridQueries.clear(); loads.clear(); } private void mergeMetrics(QueryMetrics metrics, long count, long totalTime, long maxTime, String slowest) { metrics.count.add(count); metrics.totalTime.add(totalTime); if (metrics.maxTime.longValue() < maxTime) { metrics.maxTime.set(maxTime); metrics.slowest = slowest; } } @Override public QueryStatisticsSnapshot merge(QueryStatisticsSnapshot other) { mergeMetrics(this.localIndexedQueries, other.getLocalIndexedQueryCount(), other.getLocalIndexedQueryTotalTime(), other.getLocalIndexedQueryMaxTime(), other.getSlowestLocalIndexedQuery()); mergeMetrics(this.distIndexedQueries, other.getDistributedIndexedQueryCount(), other.getDistributedIndexedQueryTotalTime(), other.getDistributedIndexedQueryMaxTime(), other.getSlowestDistributedIndexedQuery()); mergeMetrics(this.hybridQueries, other.getHybridQueryCount(), other.getHybridQueryTotalTime(), other.getHybridQueryMaxTime(), other.getSlowestHybridQuery()); mergeMetrics(this.nonIndexedQueries, other.getNonIndexedQueryCount(), other.getNonIndexedQueryMaxTime(), other.getNonIndexedQueryMaxTime(), other.getSlowestNonIndexedQuery()); mergeMetrics(this.loads, other.getLoadCount(), other.getLoadTotalTime(), other.getLoadMaxTime(), null); return this; } @Override public Json toJson() { return Json.object() .set("indexed_local", Json.make(getLocalIndexedQueries())) .set("indexed_distributed", Json.make(getDistIndexedQueries())) .set("hybrid", Json.make(getHybridQueries())) .set("non_indexed", Json.make(getNonIndexedQueries())) .set("entity_load", Json.make(getLoads())); } }
9,970
27.488571
129
java
null
infinispan-main/cloudevents-integration/src/test/java/org/infinispan/cloudevents/CacheEntryCloudEventsTest.java
package org.infinispan.cloudevents; import static java.util.concurrent.TimeUnit.SECONDS; import static org.infinispan.cloudevents.impl.StructuredEventBuilder.DATA; import static org.infinispan.cloudevents.impl.StructuredEventBuilder.DATACONTENTTYPE; import static org.infinispan.cloudevents.impl.StructuredEventBuilder.INFINISPAN_DATA_ISBASE64; import static org.infinispan.cloudevents.impl.StructuredEventBuilder.INFINISPAN_SUBJECT_CONTENTTYPE; import static org.infinispan.cloudevents.impl.StructuredEventBuilder.INFINISPAN_SUBJECT_ISBASE64; import static org.infinispan.cloudevents.impl.StructuredEventBuilder.SOURCE; import static org.infinispan.cloudevents.impl.StructuredEventBuilder.SPECVERSION; import static org.infinispan.cloudevents.impl.StructuredEventBuilder.SUBJECT; import static org.infinispan.cloudevents.impl.StructuredEventBuilder.TIME; import static org.infinispan.cloudevents.impl.StructuredEventBuilder.TYPE; import static org.infinispan.commons.dataconversion.MediaType.APPLICATION_JSON; import static org.infinispan.commons.dataconversion.MediaType.APPLICATION_JSON_TYPE; import static org.infinispan.commons.dataconversion.MediaType.APPLICATION_OBJECT; import static org.infinispan.commons.dataconversion.MediaType.APPLICATION_PROTOSTREAM; import static org.infinispan.commons.dataconversion.MediaType.APPLICATION_UNKNOWN; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertFalse; import static org.testng.AssertJUnit.assertTrue; import java.nio.charset.StandardCharsets; import java.time.Instant; import java.util.Arrays; import java.util.Base64; import java.util.LinkedHashMap; import java.util.Map; import java.util.Optional; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionStage; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeoutException; import org.apache.kafka.clients.producer.ProducerRecord; import org.infinispan.AdvancedCache; import org.infinispan.Cache; import org.infinispan.cloudevents.configuration.CloudEventsGlobalConfigurationBuilder; import org.infinispan.cloudevents.impl.KafkaEventSender; import org.infinispan.commands.module.TestGlobalConfigurationBuilder; import org.infinispan.commons.dataconversion.MediaType; import org.infinispan.commons.dataconversion.internal.Json; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.cache.StorageType; import org.infinispan.configuration.global.GlobalConfigurationBuilder; import org.infinispan.configuration.internal.PrivateGlobalConfigurationBuilder; import org.infinispan.context.Flag; import org.infinispan.distribution.MagicKey; import org.infinispan.encoding.DataConversion; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.marshall.core.EncoderRegistry; import org.infinispan.remoting.transport.Address; import org.infinispan.test.MultipleCacheManagersTest; import org.infinispan.test.TestDataSCI; import org.infinispan.test.TestingUtil; import org.infinispan.test.op.TestWriteOperation; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; @Test(groups = "functional", testName = "cloudevents.impl.CacheEntryCloudEventsTest") public class CacheEntryCloudEventsTest extends MultipleCacheManagersTest { public static final String CACHE_NAME = "testCache"; private final MockKafkaEventSender mockSender = new MockKafkaEventSender(); private StorageType storageType; private boolean serverMode; @Override public Object[] factory() { return new Object[]{ new CacheEntryCloudEventsTest().storageType(StorageType.OBJECT), new CacheEntryCloudEventsTest().storageType(StorageType.BINARY), new CacheEntryCloudEventsTest().storageType(StorageType.HEAP).serverMode(true), }; } @DataProvider public static Object[][] operations() { return new Object[][]{ {TestWriteOperation.PUT_CREATE}, {TestWriteOperation.PUT_OVERWRITE}, {TestWriteOperation.PUT_IF_ABSENT}, {TestWriteOperation.REPLACE}, {TestWriteOperation.REPLACE_EXACT}, {TestWriteOperation.REMOVE}, {TestWriteOperation.REMOVE_EXACT}, {TestWriteOperation.PUT_MAP_CREATE}, }; } public CacheEntryCloudEventsTest storageType(StorageType storageType) { this.storageType = storageType; return this; } private Object serverMode(boolean serverMode) { this.serverMode = serverMode; return this; } @Override protected void createCacheManagers() { addNode(); addNode(); addNode(); waitForClusterToForm(); } @Override protected String[] parameterNames() { return new String[]{"storage", "server"}; } @Override protected Object[] parameterValues() { return new Object[]{storageType, serverMode ? "y" : null}; } private Address addNode() { GlobalConfigurationBuilder managerBuilder = GlobalConfigurationBuilder.defaultClusteredBuilder(); managerBuilder.defaultCacheName(CACHE_NAME).serialization().addContextInitializer(TestDataSCI.INSTANCE); if (serverMode) { managerBuilder.addModule(PrivateGlobalConfigurationBuilder.class).serverMode(true); } CloudEventsGlobalConfigurationBuilder cloudEventsGlobalBuilder = managerBuilder.addModule(CloudEventsGlobalConfigurationBuilder.class); cloudEventsGlobalBuilder.bootstrapServers("localhost:9092"); cloudEventsGlobalBuilder.cacheEntriesTopic("ispn"); TestGlobalConfigurationBuilder testGlobalConfigurationBuilder = managerBuilder.addModule(TestGlobalConfigurationBuilder.class); testGlobalConfigurationBuilder.testGlobalComponent(KafkaEventSender.class.getName(), mockSender); ConfigurationBuilder cacheBuilder = new ConfigurationBuilder(); cacheBuilder.clustering().cacheMode(CacheMode.DIST_SYNC); cacheBuilder.memory().storage(storageType); EmbeddedCacheManager manager = addClusterEnabledCacheManager(managerBuilder, cacheBuilder); return manager.getAddress(); } @Test(dataProvider = "operations") public void testSingleKeyOperations(TestWriteOperation op) throws InterruptedException, TimeoutException, ExecutionException { AdvancedCache<Object, Object> originator = advancedCache(0); for (Cache<Object, Object> cache : caches()) { MagicKey key = new MagicKey(cache); if (op.getPreviousValue() != null) { mockSender.clear(); // Skipping listener notification skips the cloudevents integration originator.withFlags(Flag.SKIP_LISTENER_NOTIFICATION).put(key, op.getPreviousValue()); assertTrue(mockSender.getProducer().history().isEmpty()); } mockSender.clear(); CompletionStage<?> stage = op.performAsync(originator, key); assertFalse(stage.toCompletableFuture().isDone()); mockSender.completeSend(); stage.toCompletableFuture().get(30, SECONDS); Object eventValue = op.getValue() != null ? op.getValue() : op.getPreviousValue(); assertEntryEventSent(key, eventValue, op); Object returnValue = stage.toCompletableFuture().get(30, SECONDS); assertEquals(op.getReturnValue(), returnValue); assertEntryEventSent(key, eventValue, op); } } public void testMultiKeyOperations() throws InterruptedException, TimeoutException, ExecutionException { Map<MagicKey, Object> data = new LinkedHashMap<>(); for (int i = 0; i < caches().size(); i++) { MagicKey key = new MagicKey("key-" + i, cache(i)); String value = "value-" + i; data.put(key, value); } for (Cache<Object, Object> cache : caches()) { log.tracef("Testing on %s", address(cache)); mockSender.clear(); CompletableFuture<Void> putAllFuture = cache.putAllAsync(data); assertFalse(putAllFuture.isDone()); mockSender.completeSend(data.size()); ((CompletionStage<?>) putAllFuture).toCompletableFuture().get(30, SECONDS); data.forEach((key, value) -> { assertEntryEventSent(key, value, TestWriteOperation.PUT_MAP_CREATE); }); mockSender.clear(); CompletableFuture<Void> clearFuture = cache.clearAsync(); assertFalse(clearFuture.isDone()); mockSender.completeSend(data.size()); ((CompletionStage<?>) clearFuture).toCompletableFuture().get(30, SECONDS); data.forEach((key, value) -> { assertEntryEventSent(key, value, TestWriteOperation.REMOVE); }); } } private void assertEntryEventSent(Object key, Object value, TestWriteOperation op) { byte[] expectedKeyBytes = getKeyBytes(key); byte[] expectedValueBytes = getValueBytes(value); String type = translateType(op); Optional<ProducerRecord<byte[], byte[]>> record = mockSender.getProducer().history().stream() .filter(r -> Arrays.equals(r.key(), expectedKeyBytes)) .findFirst(); assertTrue(record.isPresent()); byte[] eventBytes = record.get().value(); Json json = Json.read(new String(eventBytes)); assertEquals("1.0", json.at(SPECVERSION).asString()); assertEquals(type, json.at(TYPE).asString()); String source = json.at(SOURCE).asString(); assertTrue(source.startsWith("/infinispan")); assertTrue(source.endsWith("/" + CACHE_NAME)); Instant.parse(json.at(TIME).asString()); boolean keyIsBase64 = json.at(INFINISPAN_SUBJECT_ISBASE64, false).asBoolean(); assertEquals(expectedContentType(keyIsBase64).toString(), json.at(INFINISPAN_SUBJECT_CONTENTTYPE, APPLICATION_JSON_TYPE).asString()); String subject = json.at(SUBJECT).asString(); byte[] keyBytes = keyIsBase64 ? Base64.getDecoder().decode(subject) : subject.getBytes(StandardCharsets.UTF_8); assertEquals(expectedKeyBytes, keyBytes); String data = json.at(DATA).asString(); boolean valueIsBase64 = json.at(INFINISPAN_DATA_ISBASE64, false).asBoolean(); assertEquals(expectedContentType(valueIsBase64).toString(), json.at(DATACONTENTTYPE, APPLICATION_JSON_TYPE).asString()); byte[] valueBytes = valueIsBase64 ? Base64.getDecoder().decode(data) : data.getBytes(StandardCharsets.UTF_8); assertEquals(expectedValueBytes, valueBytes); } private MediaType expectedContentType(boolean isBase64) { return isBase64 ? serverMode ? APPLICATION_UNKNOWN : APPLICATION_PROTOSTREAM : APPLICATION_JSON; } private byte[] getKeyBytes(Object key) { DataConversion keyDataConversion = advancedCache(0).getKeyDataConversion(); return getBytes(key, keyDataConversion); } private byte[] getValueBytes(Object value) { DataConversion valueDataConversion = advancedCache(0).getValueDataConversion(); return getBytes(value, valueDataConversion); } private byte[] getBytes(Object o, DataConversion dataConversion) { MediaType storageMediaType = dataConversion.getStorageMediaType(); if (storageMediaType.match(APPLICATION_OBJECT)) { if (o instanceof String) { return getBytes((String) o); } else { Object protostream = transcode(o, APPLICATION_OBJECT, APPLICATION_PROTOSTREAM); return (byte[]) transcode(protostream, APPLICATION_PROTOSTREAM, MediaType.APPLICATION_JSON); } } else { return (byte[]) dataConversion.getWrapper().unwrap(dataConversion.toStorage(o)); } } private Object transcode(Object o, MediaType sourceMediaType, MediaType targetMediaType) { EncoderRegistry encoderRegistry = TestingUtil.extractGlobalComponent(manager(0), EncoderRegistry.class); return encoderRegistry.getTranscoder(sourceMediaType, targetMediaType) .transcode(o, sourceMediaType, targetMediaType); } private byte[] getBytes(String s) { return s.getBytes(StandardCharsets.UTF_8); } private static String translateType(TestWriteOperation op) { switch (op) { case PUT_CREATE: case PUT_IF_ABSENT: case PUT_MAP_CREATE: return "org.infinispan.entry.created"; // case CACHE_ENTRY_EVICTED: // return "org.infinispan.entry.evicted"; // case CACHE_ENTRY_EXPIRED: // return "org.infinispan.entry.expired"; case PUT_OVERWRITE: case REPLACE: case REPLACE_EXACT: return "org.infinispan.entry.modified"; case REMOVE: case REMOVE_EXACT: return "org.infinispan.entry.removed"; default: throw new IllegalArgumentException("Unsupported event type: " + op); } } }
13,034
42.45
126
java
null
infinispan-main/cloudevents-integration/src/test/java/org/infinispan/cloudevents/MockKafkaEventSender.java
package org.infinispan.cloudevents; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionStage; import java.util.concurrent.TimeUnit; import org.apache.kafka.clients.producer.MockProducer; import org.apache.kafka.clients.producer.ProducerRecord; import org.apache.kafka.common.serialization.ByteArraySerializer; import org.infinispan.cloudevents.impl.KafkaEventSender; import org.infinispan.cloudevents.impl.Log; import org.infinispan.test.TestingUtil; import org.infinispan.util.concurrent.TimeoutException; import org.infinispan.util.logging.LogFactory; public class MockKafkaEventSender implements KafkaEventSender { private static final Log log = LogFactory.getLog(MockKafkaEventSender.class, Log.class); MockProducer<byte[], byte[]> producer = new MockProducer<>(false, new ByteArraySerializer(), new ByteArraySerializer()); @Override public CompletionStage<Void> send(ProducerRecord<byte[], byte[]> record) { CompletableFuture<Void> cf = new CompletableFuture<>(); producer.send(record, (metadata, exception) -> { if (exception != null) { cf.completeExceptionally(exception); } else { cf.complete(null); } }); return cf; } public MockProducer<byte[], byte[]> getProducer() { return producer; } void clear() { producer.clear(); } public void completeSend() { long deadlineNanos = System.nanoTime() + TimeUnit.SECONDS.toNanos(10); while (!producer.completeNext()) { if (System.nanoTime() - deadlineNanos > 0) { throw new TimeoutException(); } TestingUtil.sleepThread(10); } List<ProducerRecord<byte[], byte[]>> history = getProducer().history(); log.tracef("Completed send %s", history.get(history.size() - 1).key()); } public void completeSend(int count) { for (int i = 0; i < count; i++) { completeSend(); } } }
1,997
32.3
123
java
null
infinispan-main/cloudevents-integration/src/test/java/org/infinispan/cloudevents/CloudEventsConfigurationSerializerTest.java
package org.infinispan.cloudevents; import static org.infinispan.commons.test.Exceptions.expectException; import static org.infinispan.test.fwk.TestCacheManagerFactory.createClusteredCacheManager; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertFalse; import static org.testng.AssertJUnit.assertNotNull; import static org.testng.AssertJUnit.assertNull; import static org.testng.AssertJUnit.assertTrue; import static org.testng.AssertJUnit.fail; import java.io.IOException; import org.infinispan.cloudevents.configuration.CloudEventsConfiguration; import org.infinispan.cloudevents.configuration.CloudEventsGlobalConfiguration; import org.infinispan.commons.CacheConfigurationException; import org.infinispan.configuration.cache.Configuration; import org.infinispan.configuration.global.GlobalConfiguration; import org.infinispan.configuration.parsing.ConfigurationBuilderHolder; import org.infinispan.configuration.parsing.ParserRegistry; import org.infinispan.configuration.serializer.AbstractConfigurationSerializerTest; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.test.fwk.CleanupAfterMethod; import org.testng.annotations.Test; /** * Tests the configuration parser and serializer. * * @author Pedro Ruivo * @since 9.0 */ @Test(groups = "functional", testName = "cloudevents.CloudEventsConfigurationSerializerTest") @CleanupAfterMethod public class CloudEventsConfigurationSerializerTest extends AbstractConfigurationSerializerTest { public void testParser() throws IOException { ConfigurationBuilderHolder holder = new ParserRegistry().parseFile("configs/all/cloudevents.xml"); try (EmbeddedCacheManager cacheManager = createClusteredCacheManager(false, holder)) { CloudEventsGlobalConfiguration cloudEventsGlobalConfiguration = cacheManager.getCacheManagerConfiguration().module(CloudEventsGlobalConfiguration.class); assertEquals("127.0.0.1:9092", cloudEventsGlobalConfiguration.bootstrapServers()); assertEquals("0", cloudEventsGlobalConfiguration.acks()); assertEquals("audit", cloudEventsGlobalConfiguration.auditTopic()); assertTrue(cloudEventsGlobalConfiguration.auditEventsEnabled()); assertEquals("cache-events", cloudEventsGlobalConfiguration.cacheEntriesTopic()); assertTrue(cloudEventsGlobalConfiguration.cacheEntryEventsEnabled()); // Cache cache1 has cache entry events enabled Configuration cache1 = cacheManager.getCacheConfiguration("cache1"); assertNull(cache1.module(CloudEventsConfiguration.class)); // Cache cache2 has cache entry events disabled Configuration cache2 = cacheManager.getCacheConfiguration("cache2"); assertFalse(cache2.module(CloudEventsConfiguration.class).enabled()); } } public void testInvalid() throws IOException { ConfigurationBuilderHolder holder = new ParserRegistry().parseFile("configs/cloudevents-missing-bootstrap-servers.xml"); expectException(CacheConfigurationException.class, "ISPN030502: .*", () -> holder.getGlobalConfigurationBuilder().build()); } @Override protected void compareExtraGlobalConfiguration(GlobalConfiguration configurationBefore, GlobalConfiguration configurationAfter) { CloudEventsGlobalConfiguration before = configurationBefore.module(CloudEventsGlobalConfiguration.class); CloudEventsGlobalConfiguration after = configurationAfter.module(CloudEventsGlobalConfiguration.class); assertNotNull(before); assertNotNull(after); assertEquals(before.bootstrapServers(), after.bootstrapServers()); assertEquals(before.auditTopic(), after.auditTopic()); assertEquals(before.cacheEntriesTopic(), after.cacheEntriesTopic()); } @Override protected void compareExtraConfiguration(String name, Configuration configurationBefore, Configuration configurationAfter) { CloudEventsConfiguration before = configurationBefore.module(CloudEventsConfiguration.class); CloudEventsConfiguration after = configurationAfter.module(CloudEventsConfiguration.class); if (before == null && after == null) return; if (before == null || after == null) { // Only one of them is null fail("before=" + before + ", after=" + after); } assertEquals(before.enabled(), after.enabled()); } }
4,552
46.926316
111
java
null
infinispan-main/cloudevents-integration/src/main/java/org/infinispan/cloudevents/CloudEventsModule.java
package org.infinispan.cloudevents; import static org.infinispan.commons.logging.Log.CONFIG; import org.infinispan.cloudevents.configuration.CloudEventsConfiguration; import org.infinispan.cloudevents.configuration.CloudEventsGlobalConfiguration; import org.infinispan.cloudevents.impl.EntryEventListener; import org.infinispan.cloudevents.impl.KafkaEventSender; import org.infinispan.commons.util.Experimental; import org.infinispan.configuration.cache.Configuration; import org.infinispan.configuration.global.GlobalConfiguration; import org.infinispan.factories.ComponentRegistry; import org.infinispan.factories.GlobalComponentRegistry; import org.infinispan.factories.annotations.InfinispanModule; import org.infinispan.factories.impl.DynamicModuleMetadataProvider; import org.infinispan.factories.impl.ModuleMetadataBuilder; import org.infinispan.lifecycle.ModuleLifecycle; import org.infinispan.registry.InternalCacheRegistry; /** * Install the required components for CloudEvents integration * * @author Dan Berindei * @since 12 */ @Experimental @InfinispanModule(name = "cloudevents", requiredModules = "core") public final class CloudEventsModule implements ModuleLifecycle, DynamicModuleMetadataProvider { public static final String CLOUDEVENTS_FEATURE = "cloudevents"; private GlobalConfiguration globalConfiguration; private CloudEventsGlobalConfiguration cloudEventsGlobalConfiguration; private InternalCacheRegistry internalCacheRegistry; @Override public void registerDynamicMetadata(ModuleMetadataBuilder.ModuleBuilder moduleBuilder, GlobalConfiguration globalConfiguration) { } @Override public void cacheManagerStarting(GlobalComponentRegistry gcr, GlobalConfiguration globalConfiguration) { this.globalConfiguration = globalConfiguration; internalCacheRegistry = gcr.getComponent(InternalCacheRegistry.class); cloudEventsGlobalConfiguration = globalConfiguration.module(CloudEventsGlobalConfiguration.class); if (cloudEventsGlobalConfiguration == null) return; if (!cloudEventsGlobalConfiguration.cacheEntryEventsEnabled() && !cloudEventsGlobalConfiguration.auditEventsEnabled()) return; if (!globalConfiguration.features().isAvailable(CLOUDEVENTS_FEATURE)) throw CONFIG.featureDisabled(CLOUDEVENTS_FEATURE); // Eagerly create and register the sender component gcr.getComponent(KafkaEventSender.class); } @Override public void cacheStarting(ComponentRegistry cr, Configuration configuration, String cacheName) { if (cloudEventsGlobalConfiguration == null || !cloudEventsGlobalConfiguration.cacheEntryEventsEnabled()) return; if (internalCacheRegistry.isInternalCache(cr.getCacheName())) return; CloudEventsConfiguration cloudEventsConfiguration = configuration.module(CloudEventsConfiguration.class); if (cloudEventsConfiguration != null && !cloudEventsConfiguration.enabled()) return; if (!globalConfiguration.features().isAvailable(CLOUDEVENTS_FEATURE)) throw CONFIG.featureDisabled(CLOUDEVENTS_FEATURE); EntryEventListener listener = new EntryEventListener(); cr.registerComponent(listener, EntryEventListener.class); } }
3,259
40.265823
132
java
null
infinispan-main/cloudevents-integration/src/main/java/org/infinispan/cloudevents/configuration/CloudEventsConfigurationSerializer.java
package org.infinispan.cloudevents.configuration; import static org.infinispan.cloudevents.configuration.CloudEventsConfigurationParser.NAMESPACE; import static org.infinispan.cloudevents.configuration.CloudEventsConfigurationParser.PREFIX; import org.infinispan.commons.configuration.io.ConfigurationWriter; import org.infinispan.commons.util.Version; import org.infinispan.configuration.serializing.ConfigurationSerializer; public class CloudEventsConfigurationSerializer implements ConfigurationSerializer<CloudEventsConfiguration> { @Override public void serialize(ConfigurationWriter writer, CloudEventsConfiguration configuration) { String xmlns = NAMESPACE + Version.getMajorMinor(); writer.writeStartElement(PREFIX, xmlns, Element.CLOUDEVENTS_CACHE.getLocalName()); writer.writeNamespace(PREFIX, xmlns); configuration.attributes().write(writer); writer.writeEndElement(); } }
933
41.454545
96
java
null
infinispan-main/cloudevents-integration/src/main/java/org/infinispan/cloudevents/configuration/CloudEventsConfiguration.java
package org.infinispan.cloudevents.configuration; import org.infinispan.commons.configuration.BuiltBy; import org.infinispan.commons.configuration.attributes.AttributeDefinition; import org.infinispan.commons.configuration.attributes.AttributeSet; import org.infinispan.commons.util.Experimental; import org.infinispan.configuration.serializing.SerializedWith; /** * Configuration module to control the CloudEvents integration for a cache. * * @since 12 * @author Dan Berindei */ @Experimental @SerializedWith(CloudEventsConfigurationSerializer.class) @BuiltBy(CloudEventsConfigurationBuilder.class) public class CloudEventsConfiguration { static final AttributeDefinition<Boolean> ENABLED = AttributeDefinition.builder("enabled", true).immutable().build(); private final AttributeSet attributes; public CloudEventsConfiguration(AttributeSet attributes) { this.attributes = attributes; } public static AttributeSet attributeSet() { return new AttributeSet(CloudEventsConfiguration.class, ENABLED); } public AttributeSet attributes() { return attributes; } public boolean enabled() { return attributes.attribute(ENABLED).get(); } @Override public String toString() { return "CloudEventsConfiguration" + attributes.toString(null); } }
1,324
28.444444
75
java
null
infinispan-main/cloudevents-integration/src/main/java/org/infinispan/cloudevents/configuration/CloudEventsConfigurationParser.java
package org.infinispan.cloudevents.configuration; import static org.infinispan.cloudevents.configuration.CloudEventsConfigurationParser.NAMESPACE; import org.infinispan.commons.configuration.io.ConfigurationReader; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.global.GlobalConfigurationBuilder; import org.infinispan.configuration.parsing.ConfigurationBuilderHolder; import org.infinispan.configuration.parsing.ConfigurationParser; import org.infinispan.configuration.parsing.Namespace; import org.infinispan.configuration.parsing.Namespaces; import org.infinispan.configuration.parsing.ParseUtils; import org.infinispan.configuration.parsing.Parser; import org.infinispan.configuration.parsing.ParserScope; import org.kohsuke.MetaInfServices; /** * CloudEvents integration parser extension. * * This extension parses elements in the "urn:infinispan:config:ce" namespace * * @author Dan Berindei * @since 12 */ @MetaInfServices @Namespaces({ @Namespace(root = "cloudevents"), @Namespace(root = "cloudevents-cache"), @Namespace(uri = NAMESPACE + "*", root = "cloudevents", since = "12.0"), @Namespace(uri = NAMESPACE + "*", root = "cloudevents-cache", since = "12.0"), }) public class CloudEventsConfigurationParser implements ConfigurationParser { static final String PREFIX = "cloudevents"; static final String NAMESPACE = Parser.NAMESPACE + PREFIX + ":"; @Override public void readElement(ConfigurationReader reader, ConfigurationBuilderHolder holder) { if (holder.inScope(ParserScope.CACHE_CONTAINER)) { GlobalConfigurationBuilder globalBuilder = holder.getGlobalConfigurationBuilder(); Element element = Element.forName(reader.getLocalName()); switch (element) { case CLOUDEVENTS: { CloudEventsGlobalConfigurationBuilder cloudEventsGlobalBuilder = globalBuilder.addModule(CloudEventsGlobalConfigurationBuilder.class); parseGlobalCloudEvents(reader, cloudEventsGlobalBuilder); break; } default: { throw ParseUtils.unexpectedElement(reader); } } } else if (holder.inScope(ParserScope.CACHE) || holder.inScope(ParserScope.CACHE_TEMPLATE)) { ConfigurationBuilder builder = holder.getCurrentConfigurationBuilder(); Element element = Element.forName(reader.getLocalName()); switch (element) { case CLOUDEVENTS_CACHE: { CloudEventsConfigurationBuilder cloudEventsBuilder = builder.addModule(CloudEventsConfigurationBuilder.class); parseCacheCloudEvents(reader, cloudEventsBuilder); break; } default: { throw ParseUtils.unexpectedElement(reader); } } } else { throw new IllegalStateException("WRONG SCOPE"); } } private void parseGlobalCloudEvents(ConfigurationReader reader, CloudEventsGlobalConfigurationBuilder builder) { for (int i = 0; i < reader.getAttributeCount(); i++) { ParseUtils.requireNoNamespaceAttribute(reader, i); String value = reader.getAttributeValue(i); Attribute attribute = Attribute.forName(reader.getAttributeName(i)); switch (attribute) { case BOOTSTRAP_SERVERS: { builder.bootstrapServers(value); break; } case ACKS: { builder.acks(value); break; } case AUDIT_TOPIC: { builder.auditTopic(value); break; } case CACHE_ENTRIES_TOPIC: { builder.cacheEntriesTopic(value); break; } default: { throw ParseUtils.unexpectedAttribute(reader, i); } } } ParseUtils.requireNoContent(reader); } private void parseCacheCloudEvents(ConfigurationReader reader, CloudEventsConfigurationBuilder builder) { for (int i = 0; i < reader.getAttributeCount(); i++) { ParseUtils.requireNoNamespaceAttribute(reader, i); String value = reader.getAttributeValue(i); Attribute attribute = Attribute.forName(reader.getAttributeName(i)); switch (attribute) { case ENABLED: { builder.enabled(Boolean.parseBoolean(value)); break; } default: { throw ParseUtils.unexpectedAttribute(reader, i); } } } ParseUtils.requireNoContent(reader); } @Override public Namespace[] getNamespaces() { return ParseUtils.getNamespaceAnnotations(getClass()); } }
4,806
37.150794
115
java
null
infinispan-main/cloudevents-integration/src/main/java/org/infinispan/cloudevents/configuration/Element.java
package org.infinispan.cloudevents.configuration; import java.util.HashMap; import java.util.Map; /** * Element. * * @author Dan Berindei * @since 12 */ public enum Element { // must be first UNKNOWN(null), CLOUDEVENTS("cloudevents"), CLOUDEVENTS_CACHE("cloudevents-cache"), ; private final String name; Element(final String name) { this.name = name; } /** * Get the local name of this element. * * @return the local name */ public String getLocalName() { return name; } private static final Map<String, Element> MAP; static { final Map<String, Element> map = new HashMap<String, Element>(8); for (Element element : values()) { final String name = element.getLocalName(); if (name != null) { map.put(name, element); } } MAP = map; } public static Element forName(final String localName) { final Element element = MAP.get(localName); return element == null ? UNKNOWN : element; } }
1,046
18.754717
71
java
null
infinispan-main/cloudevents-integration/src/main/java/org/infinispan/cloudevents/configuration/CloudEventsGlobalConfigurationSerializer.java
package org.infinispan.cloudevents.configuration; import static org.infinispan.cloudevents.configuration.CloudEventsConfigurationParser.NAMESPACE; import static org.infinispan.cloudevents.configuration.CloudEventsConfigurationParser.PREFIX; import org.infinispan.commons.configuration.io.ConfigurationWriter; import org.infinispan.commons.util.Version; import org.infinispan.configuration.serializing.ConfigurationSerializer; /** * A {@link ConfigurationSerializer} implementation for {@link CloudEventsGlobalConfiguration}. * <p> * The {@link CloudEventsGlobalConfiguration} is only to be used internally so this implementation is a no-op. * * @author Pedro Ruivo * @since 9.0 */ public class CloudEventsGlobalConfigurationSerializer implements ConfigurationSerializer<CloudEventsGlobalConfiguration> { @Override public void serialize(ConfigurationWriter writer, CloudEventsGlobalConfiguration configuration) { String xmlns = NAMESPACE + Version.getMajorMinor(); writer.writeStartElement(PREFIX, xmlns, Element.CLOUDEVENTS.getLocalName()); writer.writeNamespace(PREFIX, xmlns); configuration.attributes().write(writer); writer.writeEndElement(); } }
1,200
41.892857
122
java
null
infinispan-main/cloudevents-integration/src/main/java/org/infinispan/cloudevents/configuration/CloudEventsGlobalConfiguration.java
package org.infinispan.cloudevents.configuration; import org.infinispan.commons.configuration.BuiltBy; import org.infinispan.commons.configuration.attributes.AttributeDefinition; import org.infinispan.commons.configuration.attributes.AttributeSet; import org.infinispan.commons.util.Experimental; import org.infinispan.configuration.serializing.SerializedWith; /** * Cloud events integration configuration. * <p> * * @author Dan Berindei * @since 12 */ @Experimental @SerializedWith(CloudEventsGlobalConfigurationSerializer.class) @BuiltBy(CloudEventsGlobalConfigurationBuilder.class) public class CloudEventsGlobalConfiguration { static final AttributeDefinition<String> BOOTSTRAP_SERVERS = AttributeDefinition.builder("bootstrap-servers", "").immutable().build(); static final AttributeDefinition<String> ACKS = AttributeDefinition.builder("acks", "all").immutable().build(); static final AttributeDefinition<String> CACHE_ENTRIES_TOPIC = AttributeDefinition.builder("cache-entries-topic", "").immutable().build(); static final AttributeDefinition<String> AUDIT_TOPIC = AttributeDefinition.builder("audit-topic", "").immutable().build(); private final AttributeSet attributes; CloudEventsGlobalConfiguration(AttributeSet attributeSet) { this.attributes = attributeSet.checkProtection(); } static AttributeSet attributeSet() { return new AttributeSet(CloudEventsGlobalConfiguration.class, BOOTSTRAP_SERVERS, ACKS, AUDIT_TOPIC, CACHE_ENTRIES_TOPIC); } public AttributeSet attributes() { return attributes; } public String bootstrapServers() { return attributes.attribute(BOOTSTRAP_SERVERS).get(); } public String acks() { return attributes.attribute(ACKS).get(); } public String auditTopic() { return attributes.attribute(AUDIT_TOPIC).get(); } public String cacheEntriesTopic() { return attributes.attribute(CACHE_ENTRIES_TOPIC).get(); } @Override public String toString() { return "CloudEventsGlobalConfiguration [attributes=" + attributes + ']'; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; CloudEventsGlobalConfiguration that = (CloudEventsGlobalConfiguration) o; return attributes.equals(that.attributes); } @Override public int hashCode() { return attributes.hashCode(); } public boolean auditEventsEnabled() { return !auditTopic().isEmpty(); } public boolean cacheEntryEventsEnabled() { return !cacheEntriesTopic().isEmpty(); } }
2,670
29.352273
127
java
null
infinispan-main/cloudevents-integration/src/main/java/org/infinispan/cloudevents/configuration/CloudEventsConfigurationBuilder.java
package org.infinispan.cloudevents.configuration; import org.infinispan.commons.configuration.Builder; import org.infinispan.commons.configuration.Combine; import org.infinispan.commons.configuration.attributes.AttributeSet; import org.infinispan.commons.util.Experimental; import org.infinispan.configuration.cache.ConfigurationBuilder; /** * Configuration module builder to control the CloudEvents integration for a cache. * * @see CloudEventsConfiguration * * @since 12 * @author Dan Berindei */ @Experimental public class CloudEventsConfigurationBuilder implements Builder<CloudEventsConfiguration> { private final AttributeSet attributes; private final ConfigurationBuilder rootBuilder; public CloudEventsConfigurationBuilder(ConfigurationBuilder builder) { rootBuilder = builder; this.attributes = CloudEventsConfiguration.attributeSet(); } @Override public AttributeSet attributes() { return attributes; } /** * Enable or disable anchored keys. */ public void enabled(boolean enabled) { attributes.attribute(CloudEventsConfiguration.ENABLED).set(enabled); } @Override public CloudEventsConfiguration create() { return new CloudEventsConfiguration(attributes); } @Override public Builder<?> read(CloudEventsConfiguration template, Combine combine) { attributes.read(template.attributes(), combine); return this; } }
1,434
27.7
91
java
null
infinispan-main/cloudevents-integration/src/main/java/org/infinispan/cloudevents/configuration/CloudEventsGlobalConfigurationBuilder.java
package org.infinispan.cloudevents.configuration; import static org.infinispan.cloudevents.impl.Log.CONFIG; import org.infinispan.commons.configuration.Builder; import org.infinispan.commons.configuration.Combine; import org.infinispan.commons.configuration.attributes.AttributeSet; import org.infinispan.commons.util.Experimental; import org.infinispan.configuration.global.GlobalConfigurationBuilder; /** * A {@link Builder} implementation of {@link CloudEventsGlobalConfiguration}. * * @author Dan Berindei * @see CloudEventsGlobalConfiguration * @since 12 */ @Experimental public class CloudEventsGlobalConfigurationBuilder implements Builder<CloudEventsGlobalConfiguration> { private final AttributeSet attributes; public CloudEventsGlobalConfigurationBuilder(GlobalConfigurationBuilder builder) { this.attributes = CloudEventsGlobalConfiguration.attributeSet(); } @Override public AttributeSet attributes() { return attributes; } public CloudEventsGlobalConfigurationBuilder bootstrapServers(String bootstrapServers) { this.attributes.attribute(CloudEventsGlobalConfiguration.BOOTSTRAP_SERVERS).set(bootstrapServers); return this; } public CloudEventsGlobalConfigurationBuilder acks(String acks) { this.attributes.attribute(CloudEventsGlobalConfiguration.ACKS).set(acks); return this; } public CloudEventsGlobalConfigurationBuilder auditTopic(String topic) { this.attributes.attribute(CloudEventsGlobalConfiguration.AUDIT_TOPIC).set(topic); return this; } public CloudEventsGlobalConfigurationBuilder cacheEntriesTopic(String topic) { this.attributes.attribute(CloudEventsGlobalConfiguration.CACHE_ENTRIES_TOPIC).set(topic); return this; } @Override public void validate() { String bootstrapServers = attributes.attribute(CloudEventsGlobalConfiguration.BOOTSTRAP_SERVERS).get(); String cacheEntriesTopic = attributes.attribute(CloudEventsGlobalConfiguration.CACHE_ENTRIES_TOPIC).get(); String auditTopic = attributes.attribute(CloudEventsGlobalConfiguration.AUDIT_TOPIC).get(); if (!cacheEntriesTopic.isEmpty() || !auditTopic.isEmpty()) { if (bootstrapServers.isEmpty()) { throw CONFIG.bootstrapServersRequired(); } } } @Override public CloudEventsGlobalConfiguration create() { return new CloudEventsGlobalConfiguration(attributes.protect()); } @Override public Builder<?> read(CloudEventsGlobalConfiguration template, Combine combine) { this.attributes.read(template.attributes(), combine); return this; } @Override public String toString() { return "CloudEventsGlobalConfigurationBuilder [attributes=" + attributes + ']'; } }
2,777
33.725
112
java
null
infinispan-main/cloudevents-integration/src/main/java/org/infinispan/cloudevents/configuration/Attribute.java
package org.infinispan.cloudevents.configuration; import java.util.HashMap; import java.util.Map; /** * Attribute. * * @author Dan Berindei * @since 12 */ public enum Attribute { // must be first UNKNOWN(null), BOOTSTRAP_SERVERS("bootstrap-servers"), ACKS("acks"), AUDIT_TOPIC("audit-topic"), CACHE_ENTRIES_TOPIC("cache-entries-topic"), ENABLED("enabled"), ; private final String name; private Attribute(final String name) { this.name = name; } /** * Get the local name of this element. * * @return the local name */ public String getLocalName() { return name; } private static final Map<String, Attribute> attributes; static { Map<String, Attribute> map = new HashMap<>(); for (Attribute attribute : values()) { final String name = attribute.getLocalName(); if (name != null) { map.put(name, attribute); } } attributes = map; } public static Attribute forName(final String localName) { final Attribute attribute = attributes.get(localName); return attribute == null ? UNKNOWN : attribute; } }
1,168
19.875
60
java
null
infinispan-main/cloudevents-integration/src/main/java/org/infinispan/cloudevents/impl/Log.java
package org.infinispan.cloudevents.impl; import static org.jboss.logging.Logger.Level.ERROR; import org.infinispan.commons.CacheConfigurationException; import org.infinispan.notifications.cachelistener.event.Event; import org.jboss.logging.BasicLogger; import org.jboss.logging.Logger; import org.jboss.logging.annotations.LogMessage; import org.jboss.logging.annotations.Message; import org.jboss.logging.annotations.MessageLogger; /** * This module reserves range 30501 - 31000 */ @MessageLogger(projectCode = "ISPN") public interface Log extends BasicLogger { Log CONFIG = Logger.getMessageLogger(Log.class, org.infinispan.util.logging.Log.LOG_ROOT + "CONFIG"); @LogMessage(level = ERROR) @Message(value = "Failed to send cloudevents message for %s %s %s event", id = 30501) void sendError(Event.Type eventType, Object key, Object source); @Message(value = "Attribute 'bootstrap-servers' is required when a topic is enabled", id = 30502) CacheConfigurationException bootstrapServersRequired(); }
1,024
36.962963
104
java
null
infinispan-main/cloudevents-integration/src/main/java/org/infinispan/cloudevents/impl/KafkaEventSenderImpl.java
package org.infinispan.cloudevents.impl; import static org.infinispan.factories.scopes.Scopes.GLOBAL; import java.util.Properties; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionStage; import org.apache.kafka.clients.producer.KafkaProducer; import org.apache.kafka.clients.producer.ProducerRecord; import org.infinispan.cloudevents.configuration.CloudEventsGlobalConfiguration; import org.infinispan.configuration.global.GlobalConfiguration; import org.infinispan.factories.annotations.Inject; import org.infinispan.factories.annotations.Start; import org.infinispan.factories.annotations.Stop; import org.infinispan.factories.scopes.Scope; /** * Send messages to Kafka topics. * * @author Dan Berindei * @since 12 */ @Scope(GLOBAL) public class KafkaEventSenderImpl implements KafkaEventSender { @Inject GlobalConfiguration globalConfiguration; private KafkaProducer<byte[], byte[]> producer; @Start void start() { Properties kafkaProperties = new Properties(); CloudEventsGlobalConfiguration cloudEventsGlobalConfiguration = globalConfiguration.module(CloudEventsGlobalConfiguration.class); kafkaProperties.setProperty("bootstrap.servers", cloudEventsGlobalConfiguration.bootstrapServers()); kafkaProperties.setProperty("acks", String.valueOf(cloudEventsGlobalConfiguration.acks())); kafkaProperties.setProperty("key.serializer", "org.apache.kafka.common.serialization.ByteArraySerializer"); kafkaProperties.setProperty("value.serializer", "org.apache.kafka.common.serialization.ByteArraySerializer"); producer = new KafkaProducer<>(kafkaProperties); connect(cloudEventsGlobalConfiguration); } @Stop void stop() { producer.close(); } private void connect(CloudEventsGlobalConfiguration cloudEventsGlobalConfiguration) { // Force the client to connect and receive metadata for the topics if (cloudEventsGlobalConfiguration.cacheEntryEventsEnabled()) { producer.partitionsFor(cloudEventsGlobalConfiguration.cacheEntriesTopic()); } if (cloudEventsGlobalConfiguration.auditEventsEnabled()) { producer.partitionsFor(cloudEventsGlobalConfiguration.auditTopic()); } } @Override public CompletionStage<Void> send(ProducerRecord<byte[], byte[]> record) { CompletableFuture<Void> cf = new CompletableFuture<>(); producer.send(record, (metadata, exception) -> { if (exception != null) { cf.completeExceptionally(exception); } else { cf.complete(null); } }); return cf; } }
2,645
35.75
115
java
null
infinispan-main/cloudevents-integration/src/main/java/org/infinispan/cloudevents/impl/KafkaEventSenderFactory.java
package org.infinispan.cloudevents.impl; import org.infinispan.factories.AutoInstantiableFactory; import org.infinispan.factories.ComponentFactory; import org.infinispan.factories.annotations.DefaultFactoryFor; import org.infinispan.factories.scopes.Scope; import org.infinispan.factories.scopes.Scopes; /** * Use a factory for {@link KafkaEventSender} so that tests can replace it with a mock * using {@code org.infinispan.commands.module.TestGlobalConfigurationBuilder}. * * @author Dan Berindei * @since 12 */ @Scope(Scopes.GLOBAL) @DefaultFactoryFor(classes = KafkaEventSender.class) public class KafkaEventSenderFactory implements ComponentFactory, AutoInstantiableFactory { @Override public Object construct(String componentName) { return new KafkaEventSenderImpl(); } }
800
32.375
91
java
null
infinispan-main/cloudevents-integration/src/main/java/org/infinispan/cloudevents/impl/StructuredEventBuilder.java
package org.infinispan.cloudevents.impl; import java.nio.charset.StandardCharsets; import java.util.Base64; import org.apache.kafka.clients.producer.ProducerRecord; import org.infinispan.commons.dataconversion.MediaType; import org.infinispan.commons.dataconversion.internal.Json; /** * Serialize cache events into cloudevents-encoded JSON. */ public class StructuredEventBuilder { public static final int VALIDATION_BUFFER_SIZE = 512; public static final String SPECVERSION = "specversion"; public static final String SPEC_VERSION_10 = "1.0"; public static final String ID = "id"; public static final String SOURCE = "source"; public static final String SUBJECT = "subject"; public static final String TYPE = "type"; public static final String TIME = "time"; public static final String DATA = "data"; public static final String DATACONTENTTYPE = "datacontenttype"; public static final String INFINISPAN_SUBJECT_CONTENTTYPE = "orginfinispansubject_contenttype"; public static final String INFINISPAN_SUBJECT_ISBASE64 = "orginfinispansubject_isbase64"; public static final String INFINISPAN_DATA_ISBASE64 = "orginfinispandata_isbase64"; public static final String INFINISPAN_ENTRYVERSION = "orginfinispanentryversion"; Json json; private byte[] key; public StructuredEventBuilder() { json = Json.object(); json.set(SPECVERSION, SPEC_VERSION_10); } public ProducerRecord<byte[], byte[]> toKafkaRecord(String topic) { return new ProducerRecord<>(topic, key, json.toString().getBytes(StandardCharsets.UTF_8)); } public void setId(String id) { json.set(ID, id); } public void setSource(String source) { json.set(SOURCE, source); } public void setType(String type) { json.set(TYPE, type); } public void setTime(String time) { json.set(TIME, time); } public void setSubject(String subject, MediaType mediaType, boolean validUtf8) { json.set(SUBJECT, subject); if (!mediaType.equals(MediaType.APPLICATION_JSON)) { json.set(INFINISPAN_SUBJECT_CONTENTTYPE, mediaType); if (!validUtf8) { json.set(INFINISPAN_SUBJECT_ISBASE64, Json.factory().bool(true)); } } } public void setData(byte[] data, MediaType dataMediaType, boolean validUtf8) { if (dataMediaType.equals(MediaType.APPLICATION_JSON)) { String string = new String(data, dataMediaType.getCharset()); json.set(DATA, Json.factory().raw(string)); } else { json.set(DATACONTENTTYPE, dataMediaType); String valueString; if (!validUtf8) { json.set(INFINISPAN_DATA_ISBASE64, Json.factory().bool(true)); valueString = Base64.getEncoder().encodeToString(data); } else { valueString = new String(data, dataMediaType.getCharset()); } json.set(DATA, Json.factory().string(valueString)); } } public void setPrimitiveData(Object data) { json.set(DATA, Json.factory().make(data)); } public void setEntryVersion(byte[] version) { json.set(INFINISPAN_ENTRYVERSION, Base64.getEncoder().encodeToString(version)); } /** * Check if the value can be represented as JSON with just primitive types and arrays. * Lists, sets, and maps are not supported, because they would require us to check each element. */ static boolean isJsonPrimitive(Class<?> valueClass) { return valueClass == String.class || valueClass == Boolean.class || Number.class.isAssignableFrom(valueClass) || valueClass.isArray() && isJsonPrimitive(valueClass.getComponentType()); } public void setKey(byte[] keyBytes) { this.key = keyBytes; } }
3,779
33.363636
99
java
null
infinispan-main/cloudevents-integration/src/main/java/org/infinispan/cloudevents/impl/EntryEventListener.java
package org.infinispan.cloudevents.impl; import static org.infinispan.cloudevents.impl.StructuredEventBuilder.isJsonPrimitive; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.CharBuffer; import java.nio.charset.CharsetDecoder; import java.nio.charset.CoderResult; import java.nio.charset.CodingErrorAction; import java.nio.charset.StandardCharsets; import java.time.Instant; import java.util.Base64; import java.util.concurrent.CompletionStage; import java.util.concurrent.ThreadLocalRandom; import org.apache.kafka.clients.producer.ProducerRecord; import org.infinispan.cloudevents.configuration.CloudEventsGlobalConfiguration; import org.infinispan.commons.dataconversion.MediaType; import org.infinispan.commons.dataconversion.Transcoder; import org.infinispan.commons.dataconversion.internal.Json; import org.infinispan.configuration.global.GlobalConfiguration; import org.infinispan.container.versioning.EntryVersion; import org.infinispan.encoding.impl.StorageConfigurationManager; import org.infinispan.factories.KnownComponentNames; import org.infinispan.factories.annotations.ComponentName; import org.infinispan.factories.annotations.Inject; import org.infinispan.factories.annotations.Start; import org.infinispan.factories.scopes.Scope; import org.infinispan.factories.scopes.Scopes; import org.infinispan.marshall.core.EncoderRegistry; import org.infinispan.marshall.persistence.PersistenceMarshaller; import org.infinispan.notifications.Listener; import org.infinispan.notifications.cachelistener.CacheNotifier; import org.infinispan.notifications.cachelistener.annotation.CacheEntryCreated; import org.infinispan.notifications.cachelistener.annotation.CacheEntryExpired; import org.infinispan.notifications.cachelistener.annotation.CacheEntryModified; import org.infinispan.notifications.cachelistener.annotation.CacheEntryRemoved; import org.infinispan.notifications.cachelistener.event.CacheEntryEvent; import org.infinispan.notifications.cachelistener.event.CacheEntryRemovedEvent; import org.infinispan.notifications.cachelistener.event.Event; import org.infinispan.util.logging.LogFactory; /** * Serialize cache events into cloudevents-encoded JSON. */ @Scope(Scopes.NAMED_CACHE) @Listener(primaryOnly = true, observation = Listener.Observation.POST) public class EntryEventListener { private static final Log log = LogFactory.getLog(EntryEventListener.class, Log.class); private static final boolean trace = log.isTraceEnabled(); @Inject StorageConfigurationManager storageConfigurationManager; @ComponentName(KnownComponentNames.PERSISTENCE_MARSHALLER) @Inject PersistenceMarshaller persistenceMarshaller; @Inject CacheNotifier<?, ?> cacheNotifier; @Inject KafkaEventSender kafkaEventSender; private Transcoder keyJsonTranscoder; private Transcoder valueJsonTranscoder; private String clusterName; private String cacheEntriesTopic; @Inject void inject(EncoderRegistry encoderRegistry, GlobalConfiguration globalConfiguration) { MediaType keyBytesMediaType = bytesMediaType(storageConfigurationManager.getKeyStorageMediaType(), persistenceMarshaller.mediaType()); if (encoderRegistry.isConversionSupported(keyBytesMediaType, MediaType.APPLICATION_JSON)) { keyJsonTranscoder = encoderRegistry.getTranscoder(keyBytesMediaType, MediaType.APPLICATION_JSON); } MediaType valueBytesMediaType = bytesMediaType(storageConfigurationManager.getKeyStorageMediaType(), persistenceMarshaller.mediaType()); if (encoderRegistry.isConversionSupported(keyBytesMediaType, MediaType.APPLICATION_JSON)) { valueJsonTranscoder = encoderRegistry.getTranscoder(valueBytesMediaType, MediaType.APPLICATION_JSON); } clusterName = globalConfiguration.transport().clusterName(); CloudEventsGlobalConfiguration cloudEventsGlobalConfiguration = globalConfiguration.module(CloudEventsGlobalConfiguration.class); cacheEntriesTopic = cloudEventsGlobalConfiguration.cacheEntriesTopic(); } @Start void start() { cacheNotifier.addListener(this); } @CacheEntryCreated @CacheEntryModified @CacheEntryRemoved @CacheEntryExpired public CompletionStage<Void> handleCacheEntryEvent(CacheEntryEvent<?, ?> e) { try { ProducerRecord<byte[], byte[]> record = entryEventToKafkaMessage(e); if (trace) log.tracef("Sending cloudevents message for %s %s %s event", e.getType(), e.getKey(), e.getSource()); return kafkaEventSender.send(record); } catch (IOException ioException) { log.sendError(e.getType(), e.getKey(), e.getSource()); return null; } catch (InterruptedException interruptedException) { if (trace) log.tracef("Cache manager is shutting down, skipping event"); return null; } } private MediaType bytesMediaType(MediaType storageMediaType, MediaType persistenceMediaType) { return storageMediaType.match(MediaType.APPLICATION_OBJECT) ? persistenceMediaType : storageMediaType; } public ProducerRecord<byte[], byte[]> entryEventToKafkaMessage(CacheEntryEvent<?, ?> event) throws IOException, InterruptedException { StructuredEventBuilder writer = new StructuredEventBuilder(); Object key = storageConfigurationManager.getKeyWrapper().unwrap(event.getKey()); Object wrappedValue = event.getType() != Event.Type.CACHE_ENTRY_REMOVED ? event.getValue() : ((CacheEntryRemovedEvent<?, ?>) event).getOldValue(); Object value = storageConfigurationManager.getValueWrapper().unwrap(wrappedValue); String cacheName = event.getCache().getName(); writer.setSource("/infinispan/" + clusterName + "/" + cacheName); writer.setType(translateType(event.getType())); writer.setTime(Instant.now().toString()); String stringKey = writeKey(writer, key, storageConfigurationManager.getKeyStorageMediaType()); Object source = event.getSource(); if (source == null) { source = ThreadLocalRandom.current().nextLong(); } // The key + the tx id (or non-tx invocation id) can uniquely identify an event // Consumers should ignore duplicates sent with the same id, e.g. when a command is retried writer.setId(stringKey + ":" + source); MediaType storageMediaType = storageConfigurationManager.getValueStorageMediaType(); writeValue(writer, value, storageMediaType); writeVersion(event, writer); return writer.toKafkaRecord(cacheEntriesTopic); } private String writeKey(StructuredEventBuilder writer, Object key, MediaType storageMediaType) throws IOException, InterruptedException { String keyString = null; byte[] keyBytes; MediaType mediaType; boolean validUtf8; if (storageMediaType.match(MediaType.APPLICATION_OBJECT)) { if (isJsonPrimitive(key.getClass())) { keyString = Json.make(key).toString(); keyBytes = keyString.getBytes(StandardCharsets.UTF_8); validUtf8 = true; mediaType = MediaType.APPLICATION_JSON; } else { byte[] storageBytes = persistenceMarshaller.getUserMarshaller().objectToByteBuffer(key); if (valueJsonTranscoder != null) { // The persistence marshaller's output can be converted to JSON Object jsonBytes = keyJsonTranscoder.transcode(storageBytes, storageMediaType, MediaType.APPLICATION_JSON); keyBytes = (byte[]) jsonBytes; mediaType = MediaType.APPLICATION_JSON; validUtf8 = true; } else { keyBytes = storageBytes; mediaType = storageMediaType; validUtf8 = isValidUtf8(storageBytes); } } } else { keyBytes = (byte[]) key; mediaType = storageMediaType; validUtf8 = isValidUtf8(keyBytes); } if (keyString == null) { keyString = bytesToString(keyBytes, validUtf8); } writer.setKey(keyBytes); writer.setSubject(keyString, mediaType, validUtf8); return keyString; } private void writeValue(StructuredEventBuilder writer, Object value, MediaType storageMediaType) throws IOException, InterruptedException { if (value != null) { if (storageMediaType.match(MediaType.APPLICATION_OBJECT)) { if (isJsonPrimitive(value.getClass())) { writer.setPrimitiveData(value); } else { byte[] storageBytes = persistenceMarshaller.getUserMarshaller().objectToByteBuffer(value); if (valueJsonTranscoder != null) { // The persistence marshaller's output can be converted to JSON Object jsonBytes = valueJsonTranscoder.transcode(storageBytes, storageMediaType, MediaType.APPLICATION_JSON); writer.setData((byte[]) jsonBytes, MediaType.APPLICATION_JSON, !isValidUtf8((byte[]) jsonBytes)); } else { writer.setData(storageBytes, storageMediaType, !isValidUtf8(storageBytes)); } } } else { byte[] valueBytes = (byte[]) value; writer.setData(valueBytes, storageMediaType, !isValidUtf8(valueBytes)); } } else { writer.setPrimitiveData(null); } } private String bytesToString(byte[] valueBytes, boolean validUtf8) { if (!validUtf8) { return Base64.getEncoder().encodeToString(valueBytes); } else { return new String(valueBytes, StandardCharsets.UTF_8); } } private void writeVersion(CacheEntryEvent<?, ?> event, StructuredEventBuilder writer) throws IOException, InterruptedException { if (event.getMetadata() != null) { EntryVersion version = event.getMetadata().version(); if (version != null) { byte[] versionBytes = persistenceMarshaller.objectToByteBuffer(version); writer.setEntryVersion(versionBytes); } } } private static String translateType(Event.Type type) { switch (type) { case CACHE_ENTRY_CREATED: return "org.infinispan.entry.created"; case CACHE_ENTRY_EVICTED: return "org.infinispan.entry.evicted"; case CACHE_ENTRY_EXPIRED: return "org.infinispan.entry.expired"; case CACHE_ENTRY_MODIFIED: return "org.infinispan.entry.modified"; case CACHE_ENTRY_REMOVED: return "org.infinispan.entry.removed"; default: throw new IllegalArgumentException("Unsupported event type: " + type); } } private static boolean isValidUtf8(byte[] bytes) { if (bytes.length == 0) return true; CharsetDecoder utf8Decoder = StandardCharsets.UTF_8.newDecoder() .onMalformedInput(CodingErrorAction.REPORT) .onUnmappableCharacter(CodingErrorAction.REPORT); ByteBuffer in = ByteBuffer.wrap(bytes); CharBuffer out = CharBuffer.allocate(StructuredEventBuilder.VALIDATION_BUFFER_SIZE); for (; ; ) { if (!in.hasRemaining()) break; CoderResult cr = utf8Decoder.decode(in, out, true); if (cr.isUnderflow()) break; if (cr.isOverflow()) { continue; } // Malformed input or unmappable character return false; } return true; } }
11,859
41.815884
113
java
null
infinispan-main/cloudevents-integration/src/main/java/org/infinispan/cloudevents/impl/KafkaEventSender.java
package org.infinispan.cloudevents.impl; import java.util.concurrent.CompletionStage; import org.apache.kafka.clients.producer.ProducerRecord; /** * Send messages to Kafka topics. * * @author Dan Berindei * @since 12 */ public interface KafkaEventSender { CompletionStage<Void> send(ProducerRecord<byte[], byte[]> record); }
336
20.0625
69
java
null
infinispan-main/cdi/common/src/main/java/org/infinispan/cdi/common/package-info.java
/** * This is the Infinispan CDI module. This package contains the CDI extension implementation, the mechanism allowing * to inject and configure an Infinispan cache. For further details see the * <a href="https://docs.jboss.org/author/display/ISPN/CDI+Support">CDI Support</a> documentation. */ package org.infinispan.cdi.common;
335
47
116
java
null
infinispan-main/cdi/common/src/main/java/org/infinispan/cdi/common/util/package-info.java
/** * This package contains utility classes. */ package org.infinispan.cdi.common.util;
90
17.2
41
java
null
infinispan-main/cdi/common/src/main/java/org/infinispan/cdi/common/util/InjectableMethod.java
package org.infinispan.cdi.common.util; import java.util.ArrayList; import java.util.Collection; import java.util.List; import jakarta.enterprise.context.spi.CreationalContext; import jakarta.enterprise.inject.spi.AnnotatedMethod; import jakarta.enterprise.inject.spi.Bean; import jakarta.enterprise.inject.spi.BeanManager; import jakarta.enterprise.inject.spi.InjectionPoint; /** * <p> * Allows an {@link AnnotatedMethod} to be injected using the CDI type safe * resolution rules. * </p> * <p/> * <p> * {@link ParameterValueRedefiner} allows the default value to be overridden by * the caller of * {@link #invoke(Object, CreationalContext, ParameterValueRedefiner)}. * </p> * * @param <X> the declaring type * @author Pete Muir */ public class InjectableMethod<X> { private final AnnotatedMethod<X> method; private final List<InjectionPoint> parameters; private final BeanManager beanManager; /** * Instantiate a new {@link InjectableMethod}. * * @param method the method which will be injected upon a call to * {@link #invoke(Object, CreationalContext)} * @param bean the bean which defines the injectable method * @param beanManager the {@link BeanManager} to use to obtain the parameter * values */ public InjectableMethod(AnnotatedMethod<X> method, Bean<?> declaringBean, BeanManager beanManager) { this(method, Beans.createInjectionPoints(method, declaringBean, beanManager), beanManager); } /** * Instantiate a new {@link InjectableMethod}. * * @param method the method which will be injected upon a call to * {@link #invoke(Object, CreationalContext)} * @param parameters a collection of injection points representing the * parameters of the method * @param beanManager the {@link BeanManager} to use to obtain the parameter * values */ public InjectableMethod(AnnotatedMethod<X> method, Collection<InjectionPoint> parameters, BeanManager beanManager) { this.method = method; this.parameters = new ArrayList<InjectionPoint>(parameters); this.beanManager = beanManager; } /** * Get the bean manager used by this injectable method. * * @return the bean manager in use */ protected BeanManager getBeanManager() { return beanManager; } /** * Get the injectable parameters of this method. * * @return a collection of injection points representing the parameters of * this method */ protected List<InjectionPoint> getParameters() { return parameters; } /** * Invoke the method, causing all parameters to be injected according to the * CDI type safe resolution rules. * * @param <T> the return type of the method * @param receiver the instance upon which to call the method * @param creationalContext the creational context to use to obtain * injectable references for each parameter * @return the result of invoking the method or null if the method's return * type is void * @throws RuntimeException if this <code>Method</code> object enforces Java * language access control and the underlying method is * inaccessible or if the underlying method throws an exception or * if the initialization provoked by this method fails. * @throws IllegalArgumentException if the method is an instance method and * the specified <code>receiver</code> argument is not an instance * of the class or interface declaring the underlying method (or * of a subclass or implementor thereof); if an unwrapping * conversion for primitive arguments fails; or if, after possible * unwrapping, a parameter value cannot be converted to the * corresponding formal parameter type by a method invocation * conversion. * @throws NullPointerException if the specified <code>receiver</code> is * null and the method is an instance method. * @throws ExceptionInInitializerError if the initialization provoked by this * method fails. */ public <T> T invoke(Object receiver, CreationalContext<T> creationalContext) { return invoke(receiver, creationalContext, null); } /** * Invoke the method, calling the parameter redefiner for each parameter, * allowing the caller to override the default value obtained via the CDI * type safe resolver. * * @param <T> the return type of the method * @param receiver the instance upon which to call the method * @param creationalContext the creational context to use to obtain * injectable references for each parameter * @return the result of invoking the method or null if the method's return * type is void * @throws RuntimeException if this <code>Method</code> object enforces Java * language access control and the underlying method is * inaccessible or if the underlying method throws an exception or * if the initialization provoked by this method fails. * @throws IllegalArgumentException if the method is an instance method and * the specified <code>receiver</code> argument is not an instance * of the class or interface declaring the underlying method (or * of a subclass or implementor thereof); if an unwrapping * conversion for primitive arguments fails; or if, after possible * unwrapping, a parameter value cannot be converted to the * corresponding formal parameter type by a method invocation * conversion. * @throws NullPointerException if the specified <code>receiver</code> is * null and the method is an instance method. * @throws ExceptionInInitializerError if the initialization provoked by this * method fails. */ public <T> T invoke(Object receiver, CreationalContext<T> creationalContext, ParameterValueRedefiner redefinition) { List<Object> parameterValues = new ArrayList<Object>(); for (int i = 0; i < getParameters().size(); i++) { if (redefinition != null) { ParameterValueRedefiner.ParameterValue value = new ParameterValueRedefiner.ParameterValue(i, getParameters().get(i), getBeanManager()); parameterValues.add(redefinition.redefineParameterValue(value)); } else { parameterValues.add(getBeanManager().getInjectableReference(getParameters().get(i), creationalContext)); } } @SuppressWarnings("unchecked") T result = (T) Reflections.invokeMethod(true, method.getJavaMember(), receiver, parameterValues.toArray(Reflections.EMPTY_OBJECT_ARRAY)); return result; } }
7,834
48.27673
151
java
null
infinispan-main/cdi/common/src/main/java/org/infinispan/cdi/common/util/DummyInjectionTarget.java
package org.infinispan.cdi.common.util; import static java.util.Collections.emptySet; import java.util.Set; import jakarta.enterprise.context.spi.CreationalContext; import jakarta.enterprise.inject.spi.InjectionPoint; import jakarta.enterprise.inject.spi.InjectionTarget; /** * Injection target implementation that does nothing * * @author Stuart Douglas */ public class DummyInjectionTarget<T> implements InjectionTarget<T> { public void inject(T instance, CreationalContext<T> ctx) { } public void postConstruct(T instance) { } public void preDestroy(T instance) { } public void dispose(T instance) { } public Set<InjectionPoint> getInjectionPoints() { return emptySet(); } public T produce(CreationalContext<T> ctx) { return null; } }
817
19.974359
68
java
null
infinispan-main/cdi/common/src/main/java/org/infinispan/cdi/common/util/Types.java
package org.infinispan.cdi.common.util; /** * Utility class for Types * * @author Pete Muir */ public class Types { public static Class<?> boxedClass(Class<?> type) { if (!type.isPrimitive()) { return type; } else if (type.equals(Boolean.TYPE)) { return Boolean.class; } else if (type.equals(Character.TYPE)) { return Character.class; } else if (type.equals(Byte.TYPE)) { return Byte.class; } else if (type.equals(Short.TYPE)) { return Short.class; } else if (type.equals(Integer.TYPE)) { return Integer.class; } else if (type.equals(Long.TYPE)) { return Long.class; } else if (type.equals(Float.TYPE)) { return Float.class; } else if (type.equals(Double.TYPE)) { return Double.class; } else if (type.equals(Void.TYPE)) { return Void.class; } else { // Vagaries of if/else statement, can't be reached ;-) return type; } } }
1,145
18.1
63
java
null
infinispan-main/cdi/common/src/main/java/org/infinispan/cdi/common/util/Annotateds.java
package org.infinispan.cdi.common.util; import java.lang.annotation.Annotation; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Set; import jakarta.enterprise.inject.spi.Annotated; import jakarta.enterprise.inject.spi.AnnotatedCallable; import jakarta.enterprise.inject.spi.AnnotatedConstructor; import jakarta.enterprise.inject.spi.AnnotatedField; import jakarta.enterprise.inject.spi.AnnotatedMethod; import jakarta.enterprise.inject.spi.AnnotatedParameter; import jakarta.enterprise.inject.spi.AnnotatedType; /** * <p> * Utilities for working with {@link Annotated}s. * </p> * <p/> * <p> * Includes utilities to check the equality of and create unique id's for * <code>Annotated</code> instances. * </p> * * @author Stuart Douglas &lt;stuart@baileyroberts.com.au&gt; */ public class Annotateds { /** * Does the first stage of comparing AnnoatedCallables, however it cannot * compare the method parameters */ private static class AnnotatedCallableComparator<T> implements Comparator<AnnotatedCallable<? super T>> { public int compare(AnnotatedCallable<? super T> arg0, AnnotatedCallable<? super T> arg1) { // compare the names first int result = (arg0.getJavaMember().getName().compareTo(arg1.getJavaMember().getName())); if (result != 0) { return result; } result = arg0.getJavaMember().getDeclaringClass().getName().compareTo(arg1.getJavaMember().getDeclaringClass().getName()); if (result != 0) { return result; } result = arg0.getParameters().size() - arg1.getParameters().size(); return result; } } private static class AnnotatedMethodComparator<T> implements Comparator<AnnotatedMethod<? super T>> { public static <T> Comparator<AnnotatedMethod<? super T>> instance() { return new AnnotatedMethodComparator<T>(); } private AnnotatedCallableComparator<T> callableComparator = new AnnotatedCallableComparator<T>(); public int compare(AnnotatedMethod<? super T> arg0, AnnotatedMethod<? super T> arg1) { int result = callableComparator.compare(arg0, arg1); if (result != 0) { return result; } for (int i = 0; i < arg0.getJavaMember().getParameterCount(); ++i) { Class<?> p0 = arg0.getJavaMember().getParameterTypes()[i]; Class<?> p1 = arg1.getJavaMember().getParameterTypes()[i]; result = p0.getName().compareTo(p1.getName()); if (result != 0) { return result; } } return 0; } } private static class AnnotatedConstructorComparator<T> implements Comparator<AnnotatedConstructor<? super T>> { public static <T> Comparator<AnnotatedConstructor<? super T>> instance() { return new AnnotatedConstructorComparator<T>(); } private AnnotatedCallableComparator<T> callableComparator = new AnnotatedCallableComparator<T>(); public int compare(AnnotatedConstructor<? super T> arg0, AnnotatedConstructor<? super T> arg1) { int result = callableComparator.compare(arg0, arg1); if (result != 0) { return result; } for (int i = 0; i < arg0.getJavaMember().getParameterCount(); ++i) { Class<?> p0 = arg0.getJavaMember().getParameterTypes()[i]; Class<?> p1 = arg1.getJavaMember().getParameterTypes()[i]; result = p0.getName().compareTo(p1.getName()); if (result != 0) { return result; } } return 0; } } private static class AnnotatedFieldComparator<T> implements Comparator<AnnotatedField<? super T>> { public static <T> Comparator<AnnotatedField<? super T>> instance() { return new AnnotatedFieldComparator<T>(); } public int compare(AnnotatedField<? super T> arg0, AnnotatedField<? super T> arg1) { if (arg0.getJavaMember().getName().equals(arg1.getJavaMember().getName())) { return arg0.getJavaMember().getDeclaringClass().getName().compareTo(arg1.getJavaMember().getDeclaringClass().getName()); } return arg0.getJavaMember().getName().compareTo(arg1.getJavaMember().getName()); } } private static class AnnotationComparator implements Comparator<Annotation> { public static final Comparator<Annotation> INSTANCE = new AnnotationComparator(); public int compare(Annotation arg0, Annotation arg1) { return arg0.annotationType().getName().compareTo(arg1.annotationType().getName()); } } private static class MethodComparator implements Comparator<Method> { public static final Comparator<Method> INSTANCE = new MethodComparator(); public int compare(Method arg0, Method arg1) { return arg0.getName().compareTo(arg1.getName()); } } private static final char SEPERATOR = ';'; private Annotateds() { } /** * Generates a deterministic signature for an {@link AnnotatedType}. Two * <code>AnnotatedType</code>s that have the same annotations and underlying * type will generate the same signature. * <p/> * This can be used to create a unique bean id for a passivation capable bean * that is added directly through the SPI. * * @param annotatedType The type to generate a signature for * @return A string representation of the annotated type */ public static <X> String createTypeId(AnnotatedType<X> annotatedType) { return createTypeId(annotatedType.getJavaClass(), annotatedType.getAnnotations(), annotatedType.getMethods(), annotatedType.getFields(), annotatedType.getConstructors()); } /** * Generates a unique signature for a concrete class. Annotations are not * read directly from the class, but are read from the * <code>annotations</code>, <code>methods</code>, <code>fields</code> and * <code>constructors</code> arguments * * @param clazz The java class tyoe * @param annotations Annotations present on the java class * @param methods The AnnotatedMethods to include in the signature * @param fields The AnnotatedFields to include in the signature * @param constructors The AnnotatedConstructors to include in the signature * @return A string representation of the type */ public static <X> String createTypeId(Class<X> clazz, Collection<Annotation> annotations, Collection<AnnotatedMethod<? super X>> methods, Collection<AnnotatedField<? super X>> fields, Collection<AnnotatedConstructor<X>> constructors) { StringBuilder builder = new StringBuilder(); builder.append(clazz.getName()); builder.append(createAnnotationCollectionId(annotations)); builder.append("{"); // now deal with the fields List<AnnotatedField<? super X>> sortedFields = new ArrayList<AnnotatedField<? super X>>(); sortedFields.addAll(fields); Collections.sort(sortedFields, AnnotatedFieldComparator.<X>instance()); for (AnnotatedField<? super X> field : sortedFields) { if (!field.getAnnotations().isEmpty()) { builder.append(createFieldId(field)); builder.append(SEPERATOR); } } // methods List<AnnotatedMethod<? super X>> sortedMethods = new ArrayList<AnnotatedMethod<? super X>>(); sortedMethods.addAll(methods); Collections.sort(sortedMethods, AnnotatedMethodComparator.<X>instance()); for (AnnotatedMethod<? super X> method : sortedMethods) { if (!method.getAnnotations().isEmpty() || hasMethodParameters(method)) { builder.append(createCallableId(method)); builder.append(SEPERATOR); } } // constructors List<AnnotatedConstructor<? super X>> sortedConstructors = new ArrayList<AnnotatedConstructor<? super X>>(); sortedConstructors.addAll(constructors); Collections.sort(sortedConstructors, AnnotatedConstructorComparator.<X>instance()); for (AnnotatedConstructor<? super X> constructor : sortedConstructors) { if (!constructor.getAnnotations().isEmpty() || hasMethodParameters(constructor)) { builder.append(createCallableId(constructor)); builder.append(SEPERATOR); } } builder.append("}"); return builder.toString(); } /** * Generates a deterministic signature for an {@link AnnotatedField}. Two * <code>AnnotatedField</code>s that have the same annotations and * underlying field will generate the same signature. */ public static <X> String createFieldId(AnnotatedField<X> field) { return createFieldId(field.getJavaMember(), field.getAnnotations()); } /** * Creates a deterministic signature for a {@link Field}. * * @param field The field to generate the signature for * @param annotations The annotations to include in the signature */ public static <X> String createFieldId(Field field, Collection<Annotation> annotations) { StringBuilder builder = new StringBuilder(); builder.append(field.getDeclaringClass().getName()); builder.append('.'); builder.append(field.getName()); builder.append(createAnnotationCollectionId(annotations)); return builder.toString(); } /** * Generates a deterministic signature for an {@link AnnotatedCallable}. Two * <code>AnnotatedCallable</code>s that have the same annotations and * underlying callable will generate the same signature. */ public static <X> String createCallableId(AnnotatedCallable<X> method) { StringBuilder builder = new StringBuilder(); builder.append(method.getJavaMember().getDeclaringClass().getName()); builder.append('.'); builder.append(method.getJavaMember().getName()); builder.append(createAnnotationCollectionId(method.getAnnotations())); builder.append(createParameterListId(method.getParameters())); return builder.toString(); } /** * Generates a unique string representation of a list of * {@link AnnotatedParameter}s. */ public static <X> String createParameterListId(List<AnnotatedParameter<X>> parameters) { StringBuilder builder = new StringBuilder(); builder.append("("); for (int i = 0; i < parameters.size(); ++i) { AnnotatedParameter<X> ap = parameters.get(i); builder.append(createParameterId(ap)); if (i + 1 != parameters.size()) { builder.append(','); } } builder.append(")"); return builder.toString(); } /** * Creates a string representation of an {@link AnnotatedParameter}. */ public static <X> String createParameterId(AnnotatedParameter<X> annotatedParameter) { return createParameterId(annotatedParameter.getBaseType(), annotatedParameter.getAnnotations()); } /** * Creates a string representation of a given type and set of annotations. */ public static <X> String createParameterId(Type type, Set<Annotation> annotations) { StringBuilder builder = new StringBuilder(); if (type instanceof Class<?>) { Class<?> c = (Class<?>) type; builder.append(c.getName()); } else { builder.append(type.toString()); } builder.append(createAnnotationCollectionId(annotations)); return builder.toString(); } private static <X> boolean hasMethodParameters(AnnotatedCallable<X> callable) { for (AnnotatedParameter<X> parameter : callable.getParameters()) { if (!parameter.getAnnotations().isEmpty()) { return true; } } return false; } private static String createAnnotationCollectionId(Collection<Annotation> annotations) { if (annotations.isEmpty()) { return ""; } StringBuilder builder = new StringBuilder(); builder.append('['); List<Annotation> annotationList = new ArrayList<Annotation>(annotations.size()); annotationList.addAll(annotations); Collections.sort(annotationList, AnnotationComparator.INSTANCE); for (Annotation a : annotationList) { builder.append('@'); builder.append(a.annotationType().getName()); builder.append('('); Method[] declaredMethods = a.annotationType().getDeclaredMethods(); List<Method> methods = new ArrayList<Method>(declaredMethods.length); for (Method m : declaredMethods) { methods.add(m); } Collections.sort(methods, MethodComparator.INSTANCE); for (int i = 0; i < methods.size(); ++i) { Method method = methods.get(i); try { Object value = method.invoke(a); builder.append(method.getName()); builder.append('='); builder.append(value.toString()); } catch (NullPointerException e) { throw new RuntimeException("NullPointerException accessing annotation member, annotation:" + a.annotationType().getName() + " member: " + method.getName(), e); } catch (IllegalArgumentException e) { throw new RuntimeException("IllegalArgumentException accessing annotation member, annotation:" + a.annotationType().getName() + " member: " + method.getName(), e); } catch (IllegalAccessException e) { throw new RuntimeException("IllegalAccessException accessing annotation member, annotation:" + a.annotationType().getName() + " member: " + method.getName(), e); } catch (InvocationTargetException e) { throw new RuntimeException("InvocationTargetException accessing annotation member, annotation:" + a.annotationType().getName() + " member: " + method.getName(), e); } if (i + 1 != methods.size()) { builder.append(','); } } builder.append(')'); } builder.append(']'); return builder.toString(); } }
14,936
40.723464
239
java
null
infinispan-main/cdi/common/src/main/java/org/infinispan/cdi/common/util/Arrays2.java
package org.infinispan.cdi.common.util; import java.util.HashSet; import java.util.Set; /** * A collection of utilities for working with Arrays that goes beyond that in * the JDK. * * @author Pete Muir */ public class Arrays2 { private Arrays2() { } /** * Create a set from an array. If the array contains duplicate objects, the * last object in the array will be placed in resultant set. * * @param <T> the type of the objects in the set * @param array the array from which to create the set * @return the created sets */ public static <T> Set<T> asSet(T... array) { Set<T> result = new HashSet<T>(); for (T a : array) { result.add(a); } return result; } }
769
21.647059
79
java
null
infinispan-main/cdi/common/src/main/java/org/infinispan/cdi/common/util/ContextualReference.java
package org.infinispan.cdi.common.util; import java.lang.annotation.Annotation; import java.lang.reflect.Type; import jakarta.enterprise.context.spi.CreationalContext; import jakarta.enterprise.inject.spi.Bean; import jakarta.enterprise.inject.spi.BeanManager; /** * Represents a non-contextual instance */ public class ContextualReference<T> { private final Bean<T> bean; private T instance; private boolean disposed = false; public ContextualReference(BeanManager beanManager, Type beantype, Annotation... qualifiers) { this.bean = (Bean<T>) beanManager.resolve(beanManager.getBeans(beantype, qualifiers)); } /** * Get the instance */ public T get() { return instance; } /** * Create the instance */ public ContextualReference<T> create(CreationalContext<T> ctx) { if (this.instance != null) { throw new IllegalStateException("Trying to call create() on already constructed instance"); } if (disposed) { throw new IllegalStateException("Trying to call create() on an already disposed instance"); } this.instance = bean.create(ctx); return this; } /** * destroy the bean */ public ContextualReference<T> destroy(CreationalContext<T> ctx) { if (this.instance == null) { throw new IllegalStateException("Trying to call destroy() before create() was called"); } if (disposed) { throw new IllegalStateException("Trying to call destroy() on already disposed instance"); } this.disposed = true; bean.destroy(instance, ctx); return this; } }
1,701
27.366667
103
java
null
infinispan-main/cdi/common/src/main/java/org/infinispan/cdi/common/util/AnyLiteral.java
package org.infinispan.cdi.common.util; import jakarta.enterprise.inject.Any; import jakarta.enterprise.util.AnnotationLiteral; public class AnyLiteral extends AnnotationLiteral<Any> implements Any { private static final long serialVersionUID = -6858406907917381581L; public static final Any INSTANCE = new AnyLiteral(); }
334
29.454545
71
java
null
infinispan-main/cdi/common/src/main/java/org/infinispan/cdi/common/util/BeanBuilder.java
package org.infinispan.cdi.common.util; import java.lang.annotation.Annotation; import java.lang.reflect.Type; import java.util.Collection; import java.util.HashSet; import java.util.Set; import jakarta.enterprise.context.Dependent; import jakarta.enterprise.inject.Alternative; import jakarta.enterprise.inject.spi.AnnotatedType; import jakarta.enterprise.inject.spi.Bean; import jakarta.enterprise.inject.spi.BeanManager; import jakarta.enterprise.inject.spi.InjectionPoint; import jakarta.enterprise.inject.spi.InjectionTarget; import jakarta.enterprise.inject.spi.PassivationCapable; import jakarta.inject.Named; /** * <p> * A builder class for creating immutable beans. The builder can create * {@link PassivationCapable} beans, using * {@link Annotateds#createTypeId(AnnotatedType)} to generate the id. * </p> * <p/> * <p> * The builder can read from an {@link AnnotatedType} and have any attribute * modified. This class is not thread-safe, but the bean created by calling * {@link #create()} is. * </p> * <p/> * <p> * It is advised that a new bean builder is instantiated for each bean created. * </p> * * @author Stuart Douglas * @author Pete Muir * @see ImmutableBean * @see ImmutablePassivationCapableBean */ public class BeanBuilder<T> { private final BeanManager beanManager; private Class<?> beanClass; private String name; private Set<Annotation> qualifiers; private Class<? extends Annotation> scope; private Set<Class<? extends Annotation>> stereotypes; private Set<Type> types; private Set<InjectionPoint> injectionPoints; private boolean alternative; private boolean nullable; private ContextualLifecycle<T> beanLifecycle; boolean passivationCapable; private String id; private String toString; /** * Instantiate a new bean builder. * * @param beanManager the bean manager to use for creating injection targets * and determining if annotations are qualifiers, scopes or * stereotypes. */ public BeanBuilder(BeanManager beanManager) { this.beanManager = beanManager; this.types = new HashSet<Type>(); } /** * <p> * Read the {@link AnnotatedType}, creating a bean from the class and it's * annotations. * </p> * <p/> * <p> * By default the bean lifecycle will wrap the result of calling * {@link BeanManager#createInjectionTarget(AnnotatedType)}. * </p> * <p/> * <p> * {@link BeanBuilder} does <em>not</em> support reading members of the class * to create producers or observer methods. * </p> * * @param type the type to read */ public BeanBuilder<T> readFromType(AnnotatedType<T> type) { this.beanClass = type.getJavaClass(); InjectionTarget<T> injectionTarget; if (!type.getJavaClass().isInterface()) { injectionTarget = beanManager .getInjectionTargetFactory(beanManager.createAnnotatedType(type.getJavaClass())) .createInjectionTarget(null); } else { injectionTarget = new DummyInjectionTarget<T>(); } this.beanLifecycle = new DelegatingContextualLifecycle<T>(injectionTarget); this.injectionPoints = injectionTarget.getInjectionPoints(); this.qualifiers = new HashSet<Annotation>(); this.stereotypes = new HashSet<Class<? extends Annotation>>(); for (Annotation annotation : type.getAnnotations()) { if (beanManager.isQualifier(annotation.annotationType())) { this.qualifiers.add(annotation); } else if (beanManager.isScope(annotation.annotationType())) { this.scope = annotation.annotationType(); } else if (beanManager.isStereotype(annotation.annotationType())) { this.stereotypes.add(annotation.annotationType()); } if (annotation instanceof Named) { this.name = ((Named) annotation).value(); } if (annotation instanceof Alternative) { this.alternative = true; } } if (this.scope == null) { this.scope = Dependent.class; } for (Class<?> c = type.getJavaClass(); c != Object.class && c != null; c = c.getSuperclass()) { this.types.add(c); } for (Class<?> i : type.getJavaClass().getInterfaces()) { this.types.add(i); } if (qualifiers.isEmpty()) { qualifiers.add(DefaultLiteral.INSTANCE); } qualifiers.add(AnyLiteral.INSTANCE); this.id = ImmutableBean.class.getName() + ":" + Annotateds.createTypeId(type); return this; } /** * <p> * Use the bean builder's current state to define the bean. * </p> * * @return the bean */ public Bean<T> create() { if (!passivationCapable) { return new ImmutableBean<T>(beanClass, name, qualifiers, scope, stereotypes, types, alternative, nullable, injectionPoints, beanLifecycle, toString); } else { return new ImmutablePassivationCapableBean<T>(id, beanClass, name, qualifiers, scope, stereotypes, types, alternative, nullable, injectionPoints, beanLifecycle, toString); } } /** * Qualifiers currently defined for bean creation. * * @return the qualifiers current defined */ public Set<Annotation> getQualifiers() { return qualifiers; } /** * Define the qualifiers used for bean creation. * * @param qualifiers the qualifiers to use */ public BeanBuilder<T> qualifiers(Set<Annotation> qualifiers) { this.qualifiers = qualifiers; return this; } /** * Define the qualifiers used for bean creation. * * @param qualifiers the qualifiers to use */ public BeanBuilder<T> qualifiers(Annotation... qualifiers) { this.qualifiers = Arrays2.asSet(qualifiers); return this; } /** * Add to the qualifiers used for bean creation. * * @param qualifiers the additional qualifier to use */ public BeanBuilder<T> addQualifier(Annotation qualifier) { this.qualifiers.add(qualifier); return this; } /** * Add to the qualifiers used for bean creation. * * @param qualifiers the additional qualifiers to use */ public BeanBuilder<T> addQualifiers(Annotation... qualifiers) { this.qualifiers.addAll(Arrays2.asSet(qualifiers)); return this; } /** * Add to the qualifiers used for bean creation. * * @param qualifiers the additional qualifiers to use */ public BeanBuilder<T> addQualifiers(Collection<Annotation> qualifiers) { this.qualifiers.addAll(qualifiers); return this; } /** * Scope currently defined for bean creation. * * @return the scope currently defined */ public Class<? extends Annotation> getScope() { return scope; } /** * Define the scope used for bean creation. * * @param scope the scope to use */ public BeanBuilder<T> scope(Class<? extends Annotation> scope) { this.scope = scope; return this; } /** * Stereotypes currently defined for bean creation. * * @return the stereotypes currently defined */ public Set<Class<? extends Annotation>> getStereotypes() { return stereotypes; } /** * Define the stereotypes used for bean creation. * * @param stereotypes the stereotypes to use */ public BeanBuilder<T> stereotypes(Set<Class<? extends Annotation>> stereotypes) { this.stereotypes = stereotypes; return this; } /** * Type closure currently defined for bean creation. * * @return the type closure currently defined */ public Set<Type> getTypes() { return types; } /** * Define the type closure used for bean creation. * * @param types the type closure to use */ public BeanBuilder<T> types(Set<Type> types) { this.types = types; return this; } /** * Define the type closure used for bean creation. * * @param types the type closure to use */ public BeanBuilder<T> types(Type... types) { this.types = Arrays2.asSet(types); return this; } /** * Add to the type closure used for bean creation. * * @param type additional type to use */ public BeanBuilder<T> addType(Type type) { this.types.add(type); return this; } /** * Add to the type closure used for bean creation. * * @param types the additional types to use */ public BeanBuilder<T> addTypes(Type... types) { this.types.addAll(Arrays2.asSet(types)); return this; } /** * Add to the type closure used for bean creation. * * @param types the additional types to use */ public BeanBuilder<T> addTypes(Collection<Type> types) { this.types.addAll(types); return this; } /** * Whether the created bean will be an alternative. * * @return <code>true</code> if the created bean will be an alternative, * otherwise <code>false</code> */ public boolean isAlternative() { return alternative; } /** * Define that the created bean will (or will not) be an alternative. * * @param alternative <code>true</code> if the created bean should be an * alternative, otherwise <code>false</code> */ public BeanBuilder<T> alternative(boolean alternative) { this.alternative = alternative; return this; } /** * Whether the created bean will be nullable. * * @return <code>true</code> if the created bean will be nullable, otherwise * <code>false</code> */ public boolean isNullable() { return nullable; } /** * Define that the created bean will (or will not) be nullable. * * @param nullable <code>true</code> if the created bean should be nullable, * otherwise <code>false</code> */ public BeanBuilder<T> nullable(boolean nullable) { this.nullable = nullable; return this; } /** * The {@link ContextualLifecycle} currently defined for bean creation. * * @return the bean lifecycle currently defined */ public ContextualLifecycle<T> getBeanLifecycle() { return beanLifecycle; } /** * Define the {@link ContextualLifecycle} used for bean creation. * * @param beanLifecycle the {@link ContextualLifecycle} to use for bean * creation. */ public BeanBuilder<T> beanLifecycle(ContextualLifecycle<T> beanLifecycle) { this.beanLifecycle = beanLifecycle; return this; } /** * The bean class currently defined for bean creation. * * @return the bean class currently defined. */ public Class<?> getBeanClass() { return beanClass; } /** * Define the bean class used for bean creation. * * @param beanClass the bean class to use */ public BeanBuilder<T> beanClass(Class<?> beanClass) { this.beanClass = beanClass; return this; } /** * The bean manager in use. This cannot be changed for this * {@link BeanBuilder}. * * @return the bean manager in use */ public BeanManager getBeanManager() { return beanManager; } /** * The name of the bean currently defined for bean creation. * * @return the name of the bean or <code>null</code> if the bean has no name */ public String getName() { return name; } /** * Define the name of the bean used for bean creation. * * @param name the name of the bean to use or <code>null</code> if the bean * should have no name */ public BeanBuilder<T> name(String name) { this.name = name; return this; } /** * Whether the created bean will be passivation capable. * * @return <code>true</code> if the created bean will be passivation capable, * otherwise <code>false</code> */ public boolean isPassivationCapable() { return passivationCapable; } /** * Define that the created bean will (or will not) be passivation capable. * * @param nullable <code>true</code> if the created bean should be * passivation capable, otherwise <code>false</code> */ public BeanBuilder<T> passivationCapable(boolean passivationCapable) { this.passivationCapable = passivationCapable; return this; } /** * The id currently defined for bean creation. * * @return the id currently defined. */ public String getId() { return id; } /** * Define the id used for bean creation. * * @param id the id to use */ public BeanBuilder<T> id(String id) { this.id = id; return this; } /** * The injection points currently defined for bean creation. * * @return the injection points currently defined. */ public Set<InjectionPoint> getInjectionPoints() { return injectionPoints; } /** * Define the injection points used for bean creation. * * @param injectionPoints the injection points to use */ public BeanBuilder<T> injectionPoints(Set<InjectionPoint> injectionPoints) { this.injectionPoints = injectionPoints; return this; } /** * Define the string used when {@link #toString()} is called on the bean. * * @param toString the string to use */ public BeanBuilder<T> toString(String toString) { this.toString = toString; return this; } /** * The string used when {@link #toString()} is called on the bean. * * @return the string currently defined */ public String getToString() { return toString; } }
14,360
27.953629
183
java
null
infinispan-main/cdi/common/src/main/java/org/infinispan/cdi/common/util/CDIHelper.java
package org.infinispan.cdi.common.util; import jakarta.enterprise.inject.spi.BeanManager; public class CDIHelper { public static final boolean isCDIAvailable() { try { CDIHelper.class.getClassLoader().loadClass("jakarta.enterprise.inject.spi.BeanManager"); return true; } catch(ClassNotFoundException e) { return false; } } public static final BeanManager getBeanManager() { try { return BeanManagerProvider.getInstance().getBeanManager(); } catch (IllegalStateException ise) { return null; } } }
594
23.791667
97
java
null
infinispan-main/cdi/common/src/main/java/org/infinispan/cdi/common/util/ContextualLifecycle.java
package org.infinispan.cdi.common.util; import jakarta.enterprise.context.spi.CreationalContext; import jakarta.enterprise.inject.spi.Bean; /** * Callbacks used by {@link BeanBuilder} and {@link ImmutableBean} to allow control * of the creation and destruction of a custom bean. * * @param <T> the class of the bean instance * @author Stuart Douglas */ public interface ContextualLifecycle<T> { /** * Callback invoked by a created bean when * {@link Bean#create(CreationalContext)} is called. * * @param bean the bean initiating the callback * @param creationalContext the context in which this instance was created */ public T create(Bean<T> bean, CreationalContext<T> creationalContext); /** * Callback invoked by a created bean when * {@link Bean#destroy(Object, CreationalContext)} is called. * * @param bean the bean initiating the callback * @param instance the contextual instance to destroy * @param creationalContext the context in which this instance was created */ default void destroy(Bean<T> bean, T instance, CreationalContext<T> creationalContext) { // No-op } }
1,215
32.777778
92
java
null
infinispan-main/cdi/common/src/main/java/org/infinispan/cdi/common/util/Contracts.java
package org.infinispan.cdi.common.util; /** * An helper class providing useful assertion methods. * * @author Kevin Pollet &lt;kevin.pollet@serli.com&gt; (C) 2011 SERLI */ public final class Contracts { /** * Disable instantiation. */ private Contracts() { } /** * Asserts that the given parameter is not {@code null}. * * @param param the parameter to check. * @param message the exception message used if the parameter to check is {@code null}. * @throws NullPointerException if the given parameter is {@code null}. */ public static void assertNotNull(Object param, String message) { if (param == null) { throw new NullPointerException(message); } } }
733
25.214286
90
java
null
infinispan-main/cdi/common/src/main/java/org/infinispan/cdi/common/util/ForwardingObserverMethod.java
package org.infinispan.cdi.common.util; import java.lang.annotation.Annotation; import java.lang.reflect.Type; import java.util.Set; import jakarta.enterprise.event.Reception; import jakarta.enterprise.event.TransactionPhase; import jakarta.enterprise.inject.spi.ObserverMethod; /** * An implementation of {@link ObserverMethod} that forwards all calls to * {@link #delegate()}. * * @param <T> The event type * @author Pete Muir */ public abstract class ForwardingObserverMethod<T> implements ObserverMethod<T> { /** * All calls to this {@link ObserverMethod} instance are forwarded to the * delegate unless overridden. * * @return the delegate {@link ObserverMethod} */ protected abstract ObserverMethod<T> delegate(); public Class<?> getBeanClass() { return delegate().getBeanClass(); } public Set<Annotation> getObservedQualifiers() { return delegate().getObservedQualifiers(); } public Type getObservedType() { return delegate().getObservedType(); } public Reception getReception() { return delegate().getReception(); } public TransactionPhase getTransactionPhase() { return delegate().getTransactionPhase(); } public void notify(T event) { delegate().notify(event); } @Override public boolean equals(Object obj) { return delegate().equals(obj); } @Override public int hashCode() { return delegate().hashCode(); } @Override public String toString() { return delegate().toString(); } }
1,598
22.514706
80
java
null
infinispan-main/cdi/common/src/main/java/org/infinispan/cdi/common/util/Synthetic.java
package org.infinispan.cdi.common.util; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.util.HashMap; import java.util.Map; import java.util.concurrent.atomic.AtomicLong; import jakarta.enterprise.util.AnnotationLiteral; import jakarta.inject.Qualifier; /** * <p> * A synthetic qualifier that can be used to replace other user-supplied * configuration at deployment. * </p> * <p/> * <p/> * * @author Stuart Douglas &lt;stuart@baileyroberts.com.au&gt; * @author Pete Muir */ @Retention(RetentionPolicy.RUNTIME) @Qualifier public @interface Synthetic { long index(); String namespace(); public static class SyntheticLiteral extends AnnotationLiteral<Synthetic> implements Synthetic { private final Long index; private final String namespace; public SyntheticLiteral(String namespace, Long index) { this.namespace = namespace; this.index = index; } public long index() { return index; } public String namespace() { return namespace; } } /** * <p> * Provides a unique Synthetic qualifier for the specified namespace * </p> * <p/> * <p> * {@link Provider} is thread safe. * </p> * * @author Pete Muir */ public static class Provider { // Map of generic Object to a SyntheticQualifier private final Map<Object, Synthetic> synthetics; private final String namespace; private AtomicLong count; public Provider(String namespace) { this.synthetics = new HashMap<Object, Synthetic>(); this.namespace = namespace; this.count = new AtomicLong(); } /** * Get a synthetic qualifier. The provided annotation is used to map the * generated qualifier, allowing later retrieval. * * @param annotation * @return */ public Synthetic get(Object object) { // This may give us data races, but these don't matter as Annotation use it's type and it's members values // for equality, it does not use instance equality. // Note that count is atomic if (!synthetics.containsKey(object)) { synthetics.put(object, new Synthetic.SyntheticLiteral(namespace, count.getAndIncrement())); } return synthetics.get(object); } /** * Get a synthetic qualifier. The qualifier will not be stored for later * retrieval. * * @return */ public Synthetic get() { return new Synthetic.SyntheticLiteral(namespace, count.getAndIncrement()); } public void clear() { this.synthetics.clear(); } } }
2,873
25.127273
118
java
null
infinispan-main/cdi/common/src/main/java/org/infinispan/cdi/common/util/DefaultLiteral.java
package org.infinispan.cdi.common.util; import jakarta.enterprise.inject.Default; import jakarta.enterprise.util.AnnotationLiteral; public class DefaultLiteral extends AnnotationLiteral<Default> implements Default { private static final long serialVersionUID = -8137340248362361317L; public static final Default INSTANCE = new DefaultLiteral(); }
358
31.636364
83
java
null
infinispan-main/cdi/common/src/main/java/org/infinispan/cdi/common/util/BeanManagerProvider.java
package org.infinispan.cdi.common.util; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.logging.Logger; import jakarta.enterprise.event.Observes; import jakarta.enterprise.inject.spi.AfterBeanDiscovery; import jakarta.enterprise.inject.spi.AfterDeploymentValidation; import jakarta.enterprise.inject.spi.BeanManager; import jakarta.enterprise.inject.spi.BeforeShutdown; import jakarta.enterprise.inject.spi.Extension; import javax.naming.InitialContext; import javax.naming.NamingException; /** * <p>This class provides access to the {@link BeanManager} * by registering the current {@link BeanManager} in an extension and * making it available via a singleton factory for the current application.</p> * <p>This is really handy if you like to access CDI functionality * from places where no injection is available.</p> * <p>If a simple but manual bean-lookup is needed, it's easier to use the {@link BeanProvider}.</p> * <p/> * <p>As soon as an application shuts down, the reference to the {@link BeanManager} will be removed.<p> * <p/> * <p>Usage:<p/> * <pre> * BeanManager bm = BeanManagerProvider.getInstance().getBeanManager(); * * </pre> * * <p><b>Attention:</b> This method is intended for being used in user code at runtime. * If this method gets used during Container boot (in an Extension), non-portable * behaviour results. During bootstrapping an Extension shall &#064;Inject BeanManager to get * access to the underlying BeanManager (see e.g. {@link #cleanupFinalBeanManagers} ). * This is the only way to guarantee to get the right * BeanManager in more complex Container scenarios.</p> */ public class BeanManagerProvider implements Extension { private static final Logger LOG = Logger.getLogger(BeanManagerProvider.class.getName()); private static BeanManagerProvider bmpSingleton = null; /** * This data container is used for storing the BeanManager for each * WebApplication. This is needed in EAR or other multi-webapp scenarios * if the DeltaSpike classes (jars) are provided in a shared ClassLoader. */ private static class BeanManagerInfo { /** * The BeanManager picked up via Extension loading */ private BeanManager loadTimeBm = null; /** * The final BeanManagers. * After the container did finally boot, we first try to resolve them from JNDI, * and only if we don't find any BM there we take the ones picked up at startup. */ private BeanManager finalBm = null; /** * Whether the CDI Application has finally booted. * Please note that this is only a nearby value * as there is no reliable event for this status in EE6. */ private boolean booted = false; } /** * <p>The BeanManagerInfo for the current ClassLoader.</p> * <p><b>Attention:</b> This instance must only be used through the {@link #bmpSingleton} singleton!</p> */ private volatile Map<ClassLoader, BeanManagerInfo> bmInfos = new ConcurrentHashMap<ClassLoader, BeanManagerInfo>(); /** * Returns if the {@link BeanManagerProvider} has been initialized. * Usually it isn't needed to call this method in application code. * It's e.g. useful for other frameworks to check if DeltaSpike and the CDI container in general have been started. * * @return true if the bean-manager-provider is ready to be used */ public static boolean isActive() { return bmpSingleton != null; } /** * Allows to get the current provider instance which provides access to the current {@link BeanManager} * * @throws IllegalStateException if the {@link BeanManagerProvider} isn't ready to be used. * That's the case if the environment isn't configured properly and therefore the {@link AfterBeanDiscovery} * hasn't be called before this method gets called. * @return the singleton BeanManagerProvider */ public static BeanManagerProvider getInstance() { /*X TODO Java-EE5 support needs to be discussed if (bmpSingleton == null) { // workaround for some Java-EE5 environments in combination with a special // StartupBroadcaster for bootstrapping CDI // CodiStartupBroadcaster.broadcastStartup(); // here bmp might not be null (depends on the broadcasters) } */ if (bmpSingleton == null) { throw new IllegalStateException("No " + BeanManagerProvider.class.getName() + " in place! " + "Please ensure that you configured the CDI implementation of your choice properly. " + "If your setup is correct, please clear all caches and compiled artifacts."); } return bmpSingleton; } /** * It basically doesn't matter which of the system events we use, * but basically we use the {@link AfterBeanDiscovery} event since it allows to use the * {@link BeanManagerProvider} for all events which occur after the {@link AfterBeanDiscovery} event. * * @param afterBeanDiscovery event which we don't actually use ;) * @param beanManager the BeanManager we store and make available. */ public void setBeanManager(@Observes AfterBeanDiscovery afterBeanDiscovery, BeanManager beanManager) { setBeanManagerProvider(this); BeanManagerInfo bmi = getBeanManagerInfo(getClassLoader(null)); bmi.loadTimeBm = beanManager; } /** * The active {@link BeanManager} for the current application (/{@link ClassLoader}). This method will throw an * {@link IllegalStateException} if the BeanManager cannot be found. * * @return the current bean-manager, never <code>null</code> * @throws IllegalStateException if the BeanManager cannot be found */ public BeanManager getBeanManager() { BeanManagerInfo bmi = getBeanManagerInfo(getClassLoader(null)); // warn the user if he tries to use the BeanManager before container startup if (!bmi.booted) { LOG.warning("When using the BeanManager to retrieve Beans before the Container is started," + " non-portable behaviour results!"); } BeanManager result = bmi.finalBm; if (result == null) { synchronized (this) { result = bmi.finalBm; if (result == null) { // first we look for a BeanManager from JNDI result = resolveBeanManagerViaJndi(); if (result == null) { // if none found, we take the one we got from the Extension loading result = bmi.loadTimeBm; } if (result == null) { throw new IllegalStateException("Unable to find BeanManager. " + "Please ensure that you configured the CDI implementation of your choice properly."); } // store the resolved BeanManager in the result cache until #cleanupFinalBeanManagers gets called // -> afterwards the next call of #getBeanManager will trigger the final lookup bmi.finalBm = result; } } } return result; } /** * Detect the right ClassLoader. * The lookup order is determined by: * <ol> * <li>ContextClassLoader of the current Thread</li> * <li>ClassLoader of the given Object 'o'</li> * <li>ClassLoader of this very ClassUtils class</li> * </ol> * * @param o if not <code>null</code> it may get used to detect the classloader. * @return The {@link ClassLoader} which should get used to create new instances */ public static ClassLoader getClassLoader(Object o) { ClassLoader loader = Thread.currentThread().getContextClassLoader(); if (loader == null && o != null) { loader = o.getClass().getClassLoader(); } if (loader == null) { loader = BeanManagerProvider.class.getClassLoader(); } return loader; } /** * By cleaning the final BeanManager map after the Deployment got Validated, * we prevent premature loading of information from JNDI in cases where the * container might not be fully setup yet. * * This might happen if someone uses the BeanManagerProvider during Extension * startup. */ public void cleanupFinalBeanManagers(@Observes AfterDeploymentValidation adv) { for (BeanManagerInfo bmi : bmpSingleton.bmInfos.values()) { bmi.finalBm = null; bmi.booted = true; /*possible issue with >weld< based servers: if #getBeanManager gets called in a custom AfterDeploymentValidation observer >after< this observer, the wrong bean-manager might get stored (not deterministic due to the unspecified order of observers). finally a bean-manager for a single bda will be stored and returned (which isn't the bm exposed via jndi).*/ } } /** * Cleanup on container shutdown * * @param beforeShutdown cdi shutdown event */ public void cleanupStoredBeanManagerOnShutdown(@Observes BeforeShutdown beforeShutdown) { if (bmpSingleton == null) { // this happens if there has been a failure at startup return; } ClassLoader classLoader = getClassLoader(null); bmpSingleton.bmInfos.remove(classLoader); //X TODO this might not be enough as there might be //X ClassLoaders used during Weld startup which are not the TCCL... } /** * Get the BeanManager from the JNDI registry. * * @return current {@link BeanManager} which is provided via JNDI */ private BeanManager resolveBeanManagerViaJndi() { try { // this location is specified in JSR-299 and must be // supported in all certified EE environments return (BeanManager) new InitialContext().lookup("java:comp/BeanManager"); } catch (NamingException e) { //workaround didn't work -> return null return null; } } /** * Get or create the BeanManagerInfo for the given ClassLoader */ private BeanManagerInfo getBeanManagerInfo(ClassLoader cl) { BeanManagerInfo bmi = bmpSingleton.bmInfos.get(cl); if (bmi == null) { synchronized (this) { bmi = bmpSingleton.bmInfos.get(cl); if (bmi == null) { bmi = new BeanManagerInfo(); bmpSingleton.bmInfos.put(cl, bmi); } } } return bmi; } /** * This function exists to prevent findbugs to complain about * setting a static member from a non-static function. * * @param beanManagerProvider the bean-manager-provider which should be used if there isn't an existing provider * @return the first BeanManagerProvider */ private static BeanManagerProvider setBeanManagerProvider(BeanManagerProvider beanManagerProvider) { if (bmpSingleton == null) { bmpSingleton = beanManagerProvider; } return bmpSingleton; } }
11,674
36.181529
120
java
null
infinispan-main/cdi/common/src/main/java/org/infinispan/cdi/common/util/ForwardingBean.java
package org.infinispan.cdi.common.util; import java.lang.annotation.Annotation; import java.lang.reflect.Type; import java.util.Set; import jakarta.enterprise.context.spi.CreationalContext; import jakarta.enterprise.inject.spi.Bean; import jakarta.enterprise.inject.spi.InjectionPoint; /** * An implementation of {@link Bean} that forwards all calls to the * {@link #delegate()}. * * @param <T> the class of the bean * @author Pete Muir */ public abstract class ForwardingBean<T> implements Bean<T> { /** * All calls to this {@link Bean} instance are forwarded to the delegate * unless overridden. * * @return the delegate {@link Bean} */ protected abstract Bean<T> delegate(); public Class<?> getBeanClass() { return delegate().getBeanClass(); } public Set<InjectionPoint> getInjectionPoints() { return delegate().getInjectionPoints(); } public String getName() { return delegate().getName(); } public Set<Annotation> getQualifiers() { return delegate().getQualifiers(); } public Class<? extends Annotation> getScope() { return delegate().getScope(); } public Set<Class<? extends Annotation>> getStereotypes() { return delegate().getStereotypes(); } public Set<Type> getTypes() { return delegate().getTypes(); } public boolean isAlternative() { return delegate().isAlternative(); } public boolean isNullable() { return false; } public T create(CreationalContext<T> creationalContext) { return delegate().create(creationalContext); } public void destroy(T instance, CreationalContext<T> creationalContext) { delegate().destroy(instance, creationalContext); } @Override public int hashCode() { return delegate().hashCode(); } @Override public boolean equals(Object obj) { return delegate().equals(obj); } @Override public String toString() { return delegate().toString(); } }
2,069
22.522727
77
java
null
infinispan-main/cdi/common/src/main/java/org/infinispan/cdi/common/util/ImmutablePassivationCapableBean.java
package org.infinispan.cdi.common.util; import java.lang.annotation.Annotation; import java.lang.reflect.Type; import java.util.Set; import jakarta.enterprise.inject.spi.Bean; import jakarta.enterprise.inject.spi.InjectionPoint; import jakarta.enterprise.inject.spi.PassivationCapable; /** * <p> * A base class for implementing a {@link PassivationCapable} {@link Bean}. The * attributes are immutable, and collections are defensively copied on * instantiation. It uses the defaults from the specification for properties if * not specified. * </p> * <p/> * <p> * This bean delegates it's lifecycle to the callbacks on the provided * {@link ContextualLifecycle}. * </p> * * @author Stuart Douglas * @author Pete Muir * @see ImmutableBean * @see BeanBuilder */ public class ImmutablePassivationCapableBean<T> extends ImmutableBean<T> implements PassivationCapable { private final String id; public ImmutablePassivationCapableBean(String id, Class<?> beanClass, String name, Set<Annotation> qualifiers, Class<? extends Annotation> scope, Set<Class<? extends Annotation>> stereotypes, Set<Type> types, boolean alternative, boolean nullable, Set<InjectionPoint> injectionPoints, ContextualLifecycle<T> beanLifecycle, String toString) { super(beanClass, name, qualifiers, scope, stereotypes, types, alternative, nullable, injectionPoints, beanLifecycle, toString); this.id = id; } public String getId() { return id; } }
1,481
34.285714
345
java
null
infinispan-main/cdi/common/src/main/java/org/infinispan/cdi/common/util/AbstractImmutableBean.java
package org.infinispan.cdi.common.util; import java.lang.annotation.Annotation; import java.lang.reflect.Type; import java.util.Collections; import java.util.HashSet; import java.util.Set; import jakarta.enterprise.context.Dependent; import jakarta.enterprise.context.spi.CreationalContext; import jakarta.enterprise.inject.Default; import jakarta.enterprise.inject.spi.Bean; import jakarta.enterprise.inject.spi.InjectionPoint; import org.infinispan.cdi.common.util.logging.Log; import org.infinispan.commons.logging.LogFactory; /** * <p> * A base class for implementing {@link Bean}. The attributes are immutable, and * collections are defensively copied on instantiation. It uses the defaults * from the specification for properties if not specified. * </p> * <p/> * <p> * This class does not provide any bean lifecycle operations * </p> * * @author Pete Muir * @see ImmutableBean * @see ImmutableNarrowingBean */ public abstract class AbstractImmutableBean<T> implements Bean<T> { private static final Log log = LogFactory.getLog(AbstractImmutableBean.class, Log.class); private final Class<?> beanClass; private final String name; private final Set<Annotation> qualifiers; private final Class<? extends Annotation> scope; private final Set<Class<? extends Annotation>> stereotypes; private final Set<Type> types; private final boolean alternative; private final boolean nullable; private final Set<InjectionPoint> injectionPoints; private final String toString; /** * Create a new, immutable bean. All arguments passed as collections are * defensively copied. * * @param beanClass The Bean class, may not be null * @param name The bean name * @param qualifiers The bean's qualifiers, if null, a singleton set of * {@link Default} is used * @param scope The bean's scope, if null, the default scope of * {@link Dependent} is used * @param stereotypes The bean's stereotypes, if null, an empty set is used * @param types The bean's types, if null, the beanClass and {@link Object} * will be used * @param alternative True if the bean is an alternative * @param nullable True if the bean is nullable * @param injectionPoints the bean's injection points, if null an empty set * is used * @param beanLifecycle Handler for {@link #create(CreationalContext)} and * {@link #destroy(Object, CreationalContext)} * @throws IllegalArgumentException if the beanClass is null */ public AbstractImmutableBean(Class<?> beanClass, String name, Set<Annotation> qualifiers, Class<? extends Annotation> scope, Set<Class<? extends Annotation>> stereotypes, Set<Type> types, boolean alternative, boolean nullable, Set<InjectionPoint> injectionPoints, String toString) { if (beanClass == null) { throw new IllegalArgumentException("beanClass cannot be null"); } this.beanClass = beanClass; this.name = name; if (qualifiers == null) { this.qualifiers = Collections.<Annotation>singleton(DefaultLiteral.INSTANCE); log.trace("No qualifers provided for bean class " + beanClass + ", using singleton set of @Default"); } else { this.qualifiers = new HashSet<Annotation>(qualifiers); } if (scope == null) { this.scope = Dependent.class; log.trace("No scope provided for bean class " + beanClass + ", using @Dependent"); } else { this.scope = scope; } if (stereotypes == null) { this.stereotypes = Collections.emptySet(); } else { this.stereotypes = new HashSet<Class<? extends Annotation>>(stereotypes); } if (types == null) { this.types = Arrays2.<Type>asSet(Object.class, beanClass); log.trace("No types provided for bean class " + beanClass + ", using [java.lang.Object.class, " + beanClass.getName() + ".class]"); } else { this.types = new HashSet<Type>(types); } if (injectionPoints == null) { this.injectionPoints = Collections.emptySet(); } else { this.injectionPoints = new HashSet<InjectionPoint>(injectionPoints); } this.alternative = alternative; this.nullable = nullable; if (toString != null) { this.toString = toString; } else { this.toString = "Custom Bean with bean class " + beanClass + " and qualifiers " + qualifiers; } } @Override public Class<?> getBeanClass() { return beanClass; } @Override public Set<InjectionPoint> getInjectionPoints() { return injectionPoints; } @Override public String getName() { return name; } @Override public Set<Annotation> getQualifiers() { return Collections.unmodifiableSet(qualifiers); } @Override public Class<? extends Annotation> getScope() { return scope; } @Override public Set<Class<? extends Annotation>> getStereotypes() { return Collections.unmodifiableSet(stereotypes); } @Override public Set<Type> getTypes() { return Collections.unmodifiableSet(types); } @Override public boolean isAlternative() { return alternative; } public boolean isNullable() { return nullable; } @Override public String toString() { return toString; } }
5,702
34.203704
286
java
null
infinispan-main/cdi/common/src/main/java/org/infinispan/cdi/common/util/DelegatingContextualLifecycle.java
package org.infinispan.cdi.common.util; import jakarta.enterprise.context.spi.CreationalContext; import jakarta.enterprise.inject.spi.Bean; import jakarta.enterprise.inject.spi.InjectionTarget; /** * An implementation of {@link ContextualLifecycle} that is backed by an * {@link InjectionTarget}. * * @param <T> * @author Pete Muir * @author Stuart Douglas */ public class DelegatingContextualLifecycle<T> implements ContextualLifecycle<T> { private final InjectionTarget<T> injectionTarget; /** * Instantiate a new {@link ContextualLifecycle} backed by an * {@link InjectionTarget}. * * @param injectionTarget the {@link InjectionTarget} used to create and * destroy instances */ public DelegatingContextualLifecycle(InjectionTarget<T> injectionTarget) { this.injectionTarget = injectionTarget; } public T create(Bean<T> bean, CreationalContext<T> creationalContext) { T instance = injectionTarget.produce(creationalContext); injectionTarget.inject(instance, creationalContext); injectionTarget.postConstruct(instance); return instance; } public void destroy(Bean<T> bean, T instance, CreationalContext<T> creationalContext) { try { injectionTarget.preDestroy(instance); creationalContext.release(); } catch (Exception e) { throw new RuntimeException(e); } } }
1,461
30.106383
91
java
null
infinispan-main/cdi/common/src/main/java/org/infinispan/cdi/common/util/Beans.java
package org.infinispan.cdi.common.util; import java.lang.annotation.Annotation; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import jakarta.enterprise.context.Dependent; import jakarta.enterprise.inject.Produces; import jakarta.enterprise.inject.spi.AnnotatedMethod; import jakarta.enterprise.inject.spi.AnnotatedParameter; import jakarta.enterprise.inject.spi.Bean; import jakarta.enterprise.inject.spi.BeanManager; import jakarta.enterprise.inject.spi.InjectionPoint; import jakarta.inject.Inject; /** * A set of utility methods for working with beans. * * @author Pete Muir */ public class Beans { private Beans() { } /** * Returns a new set with @Default and @Any added as needed * @return */ public static Set<Annotation> buildQualifiers(Set<Annotation> annotations) { Set<Annotation> qualifiers = new HashSet<Annotation>(annotations); if (annotations.isEmpty()) { qualifiers.add(DefaultLiteral.INSTANCE); } qualifiers.add(AnyLiteral.INSTANCE); return qualifiers; } public static void checkReturnValue(Object instance, Bean<?> bean, InjectionPoint injectionPoint, BeanManager beanManager) { if (instance == null && !Dependent.class.equals(bean.getScope())) { throw new IllegalStateException("Cannot return null from a non-dependent producer method: " + bean); } else if (instance != null) { boolean passivating = beanManager.isPassivatingScope(bean.getScope()); boolean instanceSerializable = Reflections.isSerializable(instance.getClass()); if (passivating && !instanceSerializable) { throw new IllegalStateException("Producers cannot declare passivating scope and return a non-serializable class: " + bean); } if (injectionPoint != null && injectionPoint.getBean() != null) { if (!instanceSerializable && beanManager.isPassivatingScope(injectionPoint.getBean().getScope())) { if (injectionPoint.getMember() instanceof Field) { if (!injectionPoint.isTransient() && instance != null && !instanceSerializable) { throw new IllegalStateException("Producers cannot produce non-serializable instances for injection into non-transient fields of passivating beans. Producer " + bean + "at injection point " + injectionPoint); } } else if (injectionPoint.getMember() instanceof Method) { Method method = (Method) injectionPoint.getMember(); if (method.isAnnotationPresent(Inject.class)) { throw new IllegalStateException("Producers cannot produce non-serializable instances for injection into parameters of initializers of beans declaring passivating scope. Producer " + bean + "at injection point " + injectionPoint); } if (method.isAnnotationPresent(Produces.class)) { throw new IllegalStateException("Producers cannot produce non-serializable instances for injection into parameters of producer methods declaring passivating scope. Producer " + bean + "at injection point " + injectionPoint); } } else if (injectionPoint.getMember() instanceof Constructor<?>) { throw new IllegalStateException("Producers cannot produce non-serializable instances for injection into parameters of constructors of beans declaring passivating scope. Producer " + bean + "at injection point " + injectionPoint); } } } } } /** * Given a method, and the bean on which the method is declared, create a * collection of injection points representing the parameters of the method. * * @param <X> the type declaring the method * @param method the method * @param declaringBean the bean on which the method is declared * @param beanManager the bean manager to use to create the injection points * @return the injection points */ public static <X> List<InjectionPoint> createInjectionPoints(AnnotatedMethod<X> method, Bean<?> declaringBean, BeanManager beanManager) { List<InjectionPoint> injectionPoints = new ArrayList<InjectionPoint>(); for (AnnotatedParameter<X> parameter : method.getParameters()) { InjectionPoint injectionPoint = new ImmutableInjectionPoint(parameter, beanManager, declaringBean, false, false); injectionPoints.add(injectionPoint); } return injectionPoints; } }
4,865
50.221053
257
java
null
infinispan-main/cdi/common/src/main/java/org/infinispan/cdi/common/util/ImmutableInjectionPoint.java
package org.infinispan.cdi.common.util; import static java.util.Collections.unmodifiableSet; import java.lang.annotation.Annotation; import java.lang.reflect.Member; import java.lang.reflect.Type; import java.util.HashSet; import java.util.Set; import jakarta.enterprise.inject.spi.Annotated; import jakarta.enterprise.inject.spi.AnnotatedField; import jakarta.enterprise.inject.spi.AnnotatedParameter; import jakarta.enterprise.inject.spi.Bean; import jakarta.enterprise.inject.spi.BeanManager; import jakarta.enterprise.inject.spi.InjectionPoint; /** * <p> * A base class for implementing {@link InjectionPoint}. The attributes are * immutable, and collections are defensively copied on instantiation. * </p> * * @author Stuart Douglas * @author Pete Muir */ public class ImmutableInjectionPoint implements InjectionPoint { private final Annotated annotated; private final Member member; private final Bean<?> declaringBean; private final Set<Annotation> qualifiers; private final Type type; private final boolean _transient; private final boolean delegate; /** * Instantiate a new {@link InjectionPoint} based upon an * {@link AnnotatedField}. * * @param field the field for which to create the injection point * @param qualifiers the qualifiers on the injection point * @param declaringBean the declaringBean declaring the injection point * @param _transient <code>true</code> if the injection point is transient * @param delegate <code>true</code> if the injection point is a delegate * injection point on a decorator */ public ImmutableInjectionPoint(AnnotatedField<?> field, Set<Annotation> qualifiers, Bean<?> declaringBean, boolean _transient, boolean delegate) { this.annotated = field; this.member = field.getJavaMember(); this.qualifiers = new HashSet<Annotation>(qualifiers); this.type = field.getJavaMember().getGenericType(); this._transient = _transient; this.delegate = delegate; this.declaringBean = declaringBean; } /** * Instantiate a new {@link InjectionPoint} based upon an * {@link AnnotatedField}, reading the qualifiers from the annotations * declared on the field. * * @param field the field for which to create the injection point * @param declaringBean the declaringBean declaring the injection point * @param _transient <code>true</code> if the injection point is transient * @param delegate <code>true</code> if the injection point is a delegate * injection point on a decorator */ public ImmutableInjectionPoint(AnnotatedField<?> field, BeanManager beanManager, Bean<?> declaringBean, boolean _transient, boolean delegate) { this.annotated = field; this.member = field.getJavaMember(); this.qualifiers = Reflections.getQualifiers(beanManager, field.getAnnotations()); this.type = field.getJavaMember().getGenericType(); this._transient = _transient; this.delegate = delegate; this.declaringBean = declaringBean; } /** * Instantiate a new {@link InjectionPoint} based upon an * {@link AnnotatedParameter}. * * @param parameter the parameter for which to create the injection point * @param qualifiers the qualifiers on the injection point * @param declaringBean the declaringBean declaring the injection point * @param _transient <code>true</code> if the injection point is transient * @param delegate <code>true</code> if the injection point is a delegate * injection point on a decorator */ public ImmutableInjectionPoint(AnnotatedParameter<?> parameter, Set<Annotation> qualifiers, Bean<?> declaringBean, boolean _transient, boolean delegate) { this.annotated = parameter; this.member = parameter.getDeclaringCallable().getJavaMember(); this.qualifiers = new HashSet<Annotation>(qualifiers); this._transient = _transient; this.delegate = delegate; this.declaringBean = declaringBean; this.type = parameter.getBaseType(); } /** * Instantiate a new {@link InjectionPoint} based upon an * {@link AnnotatedParameter}, reading the qualifiers from the annotations * declared on the parameter. * * @param parameter the parameter for which to create the injection point * @param declaringBean the declaringBean declaring the injection point * @param _transient <code>true</code> if the injection point is transient * @param delegate <code>true</code> if the injection point is a delegate * injection point on a decorator */ public ImmutableInjectionPoint(AnnotatedParameter<?> parameter, BeanManager beanManager, Bean<?> declaringBean, boolean _transient, boolean delegate) { this.annotated = parameter; this.member = parameter.getDeclaringCallable().getJavaMember(); this.qualifiers = Reflections.getQualifiers(beanManager, parameter.getAnnotations()); this._transient = _transient; this.delegate = delegate; this.declaringBean = declaringBean; this.type = parameter.getBaseType(); } public Annotated getAnnotated() { return annotated; } public Bean<?> getBean() { return declaringBean; } public Member getMember() { return member; } public Set<Annotation> getQualifiers() { return unmodifiableSet(qualifiers); } public Type getType() { return type; } public boolean isDelegate() { return delegate; } public boolean isTransient() { return _transient; } }
5,864
38.1
158
java
null
infinispan-main/cdi/common/src/main/java/org/infinispan/cdi/common/util/ParameterValueRedefiner.java
package org.infinispan.cdi.common.util; import jakarta.enterprise.context.spi.CreationalContext; import jakarta.enterprise.inject.spi.BeanManager; import jakarta.enterprise.inject.spi.InjectionPoint; /** * Provides the ability to redefine the value of a parameter on an * {@link InjectableMethod} via the * {@link #redefineParameterValue(ParameterValue)} callback. * * @author Pete Muir * @see InjectableMethod */ public interface ParameterValueRedefiner { /** * Provides the default parameter's value, along with metadata about the * parameter to a parameter redefinition. * * @author Pete Muir * @see ParameterValueRedefiner * @see InjectableMethod */ public static class ParameterValue { private final int position; private final InjectionPoint injectionPoint; private final BeanManager beanManager; ParameterValue(int position, InjectionPoint injectionPoint, BeanManager beanManager) { this.position = position; this.injectionPoint = injectionPoint; this.beanManager = beanManager; } /** * Get the position of the parameter in the member's parameter list. * * @return the position of the parameter */ public int getPosition() { return position; } /** * Get the {@link InjectionPoint} for the parameter. * * @return the injection point */ public InjectionPoint getInjectionPoint() { return injectionPoint; } /** * Get the default value of the parameter. The default value is that which * would be injected according to the CDI type safe resolution rules. * * @param creationalContext the creationalContext to use to obtain the * injectable reference. * @return the default value */ public Object getDefaultValue(CreationalContext<?> creationalContext) { return beanManager.getInjectableReference(injectionPoint, creationalContext); } } /** * Callback allowing the default parameter value (that which would be * injected according to the CDI type safe resolution rules) to be * overridden. * * @param value the default value * @return the overridden value */ public Object redefineParameterValue(ParameterValue value); }
2,475
29.95
94
java
null
infinispan-main/cdi/common/src/main/java/org/infinispan/cdi/common/util/ImmutableBean.java
package org.infinispan.cdi.common.util; import java.lang.annotation.Annotation; import java.lang.reflect.Type; import java.util.Set; import jakarta.enterprise.context.Dependent; import jakarta.enterprise.context.spi.CreationalContext; import jakarta.enterprise.inject.Default; import jakarta.enterprise.inject.spi.Bean; import jakarta.enterprise.inject.spi.InjectionPoint; /** * <p> * A base class for implementing {@link Bean}. The attributes are immutable, and * collections are defensively copied on instantiation. It uses the defaults * from the specification for properties if not specified. * </p> * <p/> * <p> * This bean delegates it's lifecycle to the callbacks on the provided * {@link ContextualLifecycle}. * </p> * * @author Stuart Douglas * @author Pete Muir * @see AbstractImmutableBean * @see BeanBuilder * @see ImmutablePassivationCapableBean */ public class ImmutableBean<T> extends AbstractImmutableBean<T> implements Bean<T> { private final ContextualLifecycle<T> contextualLifecycle; /** * Create a new, immutable bean. All arguments passed as collections are * defensively copied. * * @param beanClass The Bean class, may not be null * @param name The bean name * @param qualifiers The bean's qualifiers, if null, a singleton set of * {@link Default} is used * @param scope The bean's scope, if null, the default scope of * {@link Dependent} is used * @param stereotypes The bean's stereotypes, if null, an empty set is used * @param types The bean's types, if null, the beanClass and {@link Object} * will be used * @param alternative True if the bean is an alternative * @param nullable True if the bean is nullable * @param injectionPoints the bean's injection points, if null an empty set * is used * @param contextualLifecycle Handler for {@link #create(CreationalContext)} * and {@link #destroy(Object, CreationalContext)} * @param toString the string representation of the bean, if null the built * in representation is used, which states the bean class and * qualifiers * @throws IllegalArgumentException if the beanClass is null */ public ImmutableBean(Class<?> beanClass, String name, Set<Annotation> qualifiers, Class<? extends Annotation> scope, Set<Class<? extends Annotation>> stereotypes, Set<Type> types, boolean alternative, boolean nullable, Set<InjectionPoint> injectionPoints, ContextualLifecycle<T> contextualLifecycle, String toString) { super(beanClass, name, qualifiers, scope, stereotypes, types, alternative, nullable, injectionPoints, toString); this.contextualLifecycle = contextualLifecycle; } public T create(CreationalContext<T> arg0) { return contextualLifecycle.create(this, arg0); } public void destroy(T arg0, CreationalContext<T> arg1) { contextualLifecycle.destroy(this, arg0, arg1); } }
3,243
43.438356
322
java
null
infinispan-main/cdi/common/src/main/java/org/infinispan/cdi/common/util/HierarchyDiscovery.java
package org.infinispan.cdi.common.util; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.lang.reflect.TypeVariable; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; /** * Utility class for resolving all bean types from a given type. */ public class HierarchyDiscovery { private final Type type; private Map<Type, Class<?>> types; public HierarchyDiscovery(Type type) { this.type = type; } protected void add(Class<?> clazz, Type type) { types.put(type, clazz); } public Set<Type> getTypeClosure() { if (types == null) { init(); } // Return an independent set with no ties to the BiMap used return new HashSet<Type>(types.keySet()); } private void init() { this.types = new HashMap<Type, Class<?>>(); try { discoverTypes(type); } catch (StackOverflowError e) { Thread.dumpStack(); throw e; } } public Type getResolvedType() { if (type instanceof Class<?>) { Class<?> clazz = (Class<?>) type; return resolveType(clazz); } return type; } private void discoverTypes(Type type) { if (type != null) { if (type instanceof Class<?>) { Class<?> clazz = (Class<?>) type; add(clazz, resolveType(clazz)); discoverFromClass(clazz); } else { Class<?> clazz = null; if (type instanceof ParameterizedType) { Type rawType = ((ParameterizedType) type).getRawType(); if (rawType instanceof Class<?>) { discoverFromClass((Class<?>) rawType); clazz = (Class<?>) rawType; } } add(clazz, type); } } } private Type resolveType(Class<?> clazz) { if (clazz.getTypeParameters().length > 0) { TypeVariable<?>[] actualTypeParameters = clazz.getTypeParameters(); ParameterizedType parameterizedType = new ParameterizedTypeImpl(clazz, actualTypeParameters, clazz.getDeclaringClass()); return parameterizedType; } else { return clazz; } } private void discoverFromClass(Class<?> clazz) { discoverTypes(resolveType(type, type, clazz.getGenericSuperclass())); for (Type c : clazz.getGenericInterfaces()) { discoverTypes(resolveType(type, type, c)); } } /** * Gets the actual types by resolving TypeParameters. * * @param beanType * @param type * @return actual type */ private Type resolveType(Type beanType, Type beanType2, Type type) { if (type instanceof ParameterizedType) { if (beanType instanceof ParameterizedType) { return resolveParameterizedType((ParameterizedType) beanType, (ParameterizedType) type); } if (beanType instanceof Class<?>) { return resolveType(((Class<?>) beanType).getGenericSuperclass(), beanType2, type); } } if (type instanceof TypeVariable<?>) { if (beanType instanceof ParameterizedType) { return resolveTypeParameter((ParameterizedType) beanType, beanType2, (TypeVariable<?>) type); } if (beanType instanceof Class<?>) { return resolveType(((Class<?>) beanType).getGenericSuperclass(), beanType2, type); } } return type; } private Type resolveParameterizedType(ParameterizedType beanType, ParameterizedType parameterizedType) { Type rawType = parameterizedType.getRawType(); Type[] actualTypes = parameterizedType.getActualTypeArguments(); Type resolvedRawType = resolveType(beanType, beanType, rawType); Type[] resolvedActualTypes = new Type[actualTypes.length]; for (int i = 0; i < actualTypes.length; i++) { resolvedActualTypes[i] = resolveType(beanType, beanType, actualTypes[i]); } // reconstruct ParameterizedType by types resolved TypeVariable. return new ParameterizedTypeImpl(resolvedRawType, resolvedActualTypes, parameterizedType.getOwnerType()); } private Type resolveTypeParameter(ParameterizedType type, Type beanType, TypeVariable<?> typeVariable) { // step1. raw type Class<?> actualType = (Class<?>) type.getRawType(); TypeVariable<?>[] typeVariables = actualType.getTypeParameters(); Type[] actualTypes = type.getActualTypeArguments(); for (int i = 0; i < typeVariables.length; i++) { if (typeVariables[i].equals(typeVariable) && !actualTypes[i].equals(typeVariable)) { return resolveType(this.type, beanType, actualTypes[i]); } } // step2. generic super class Type genericSuperType = actualType.getGenericSuperclass(); Type resolvedGenericSuperType = resolveType(genericSuperType, beanType, typeVariable); if (!(resolvedGenericSuperType instanceof TypeVariable<?>)) { return resolvedGenericSuperType; } // step3. generic interfaces if (beanType instanceof ParameterizedType) { for (Type interfaceType : ((Class<?>) ((ParameterizedType) beanType).getRawType()).getGenericInterfaces()) { Type resolvedType = resolveType(interfaceType, interfaceType, typeVariable); if (!(resolvedType instanceof TypeVariable<?>)) { return resolvedType; } } } // don't resolve type variable return typeVariable; } }
5,857
34.289157
132
java
null
infinispan-main/cdi/common/src/main/java/org/infinispan/cdi/common/util/ParameterizedTypeImpl.java
package org.infinispan.cdi.common.util; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.Arrays; public class ParameterizedTypeImpl implements ParameterizedType { private final Type[] actualTypeArguments; private final Type rawType; private final Type ownerType; public ParameterizedTypeImpl(Type rawType, Type[] actualTypeArguments, Type ownerType) { this.actualTypeArguments = actualTypeArguments; this.rawType = rawType; this.ownerType = ownerType; } public Type[] getActualTypeArguments() { return Arrays.copyOf(actualTypeArguments, actualTypeArguments.length); } public Type getOwnerType() { return ownerType; } public Type getRawType() { return rawType; } @Override public int hashCode() { return Arrays.hashCode(actualTypeArguments) ^ (ownerType == null ? 0 : ownerType.hashCode()) ^ (rawType == null ? 0 : rawType.hashCode()); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } else if (obj instanceof ParameterizedType) { ParameterizedType that = (ParameterizedType) obj; Type thatOwnerType = that.getOwnerType(); Type thatRawType = that.getRawType(); return (ownerType == null ? thatOwnerType == null : ownerType.equals(thatOwnerType)) && (rawType == null ? thatRawType == null : rawType.equals(thatRawType)) && Arrays.equals(actualTypeArguments, that.getActualTypeArguments()); } else { return false; } } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(rawType); if (actualTypeArguments.length > 0) { sb.append("<"); for (Type actualType : actualTypeArguments) { sb.append(actualType); sb.append(","); } sb.delete(sb.length() - 1, sb.length()); sb.append(">"); } return sb.toString(); } }
2,096
30.298507
239
java