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/query/src/main/java/org/infinispan/query/impl/massindex/DistributedExecutorMassIndexer.java
package org.infinispan.query.impl.massindex; import java.util.Arrays; import java.util.Collection; import java.util.HashSet; import java.util.Set; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionStage; import java.util.concurrent.TimeUnit; import org.infinispan.AdvancedCache; import org.infinispan.commons.CacheException; import org.infinispan.factories.scopes.Scope; import org.infinispan.factories.scopes.Scopes; import org.infinispan.jmx.annotations.MBean; import org.infinispan.jmx.annotations.ManagedOperation; import org.infinispan.manager.ClusterExecutor; import org.infinispan.query.Indexer; import org.infinispan.query.logging.Log; import org.infinispan.remoting.transport.Address; import org.infinispan.security.AuthorizationPermission; import org.infinispan.security.impl.Authorizer; import org.infinispan.commons.util.concurrent.CompletableFutures; import org.infinispan.util.concurrent.CompletionStages; import org.infinispan.util.function.TriConsumer; import org.infinispan.util.logging.LogFactory; /** * @author gustavonalle * @since 7.1 */ @MBean(objectName = "MassIndexer", description = "Component that rebuilds the Lucene index from the cached data") @Scope(Scopes.NAMED_CACHE) public class DistributedExecutorMassIndexer implements Indexer { private static final Log LOG = LogFactory.getLog(DistributedExecutorMassIndexer.class, Log.class); private final AdvancedCache<?, ?> cache; private final IndexUpdater indexUpdater; private final ClusterExecutor executor; private final IndexLock lock; private final Authorizer authorizer; private volatile boolean isRunning = false; private static final TriConsumer<Address, Void, Throwable> TRI_CONSUMER = (a, v, t) -> { if (t != null) { throw new CacheException(t); } }; public DistributedExecutorMassIndexer(AdvancedCache<?, ?> cache) { this.cache = cache; this.indexUpdater = new IndexUpdater(cache); this.executor = cache.getCacheManager().executor(); this.lock = MassIndexerLockFactory.buildLock(cache); this.authorizer = cache.getComponentRegistry().getComponent(Authorizer.class); } @ManagedOperation(description = "Starts rebuilding the index", displayName = "Rebuild index") public void start() { CompletionStages.join(executeInternal(false, false)); } @Override public CompletionStage<Void> run() { return executeInternal(false, false).toCompletableFuture(); } @Override public CompletionStage<Void> runLocal() { return executeInternal(false, true).toCompletableFuture(); } @Override public CompletionStage<Void> run(Object... keys) { authorizer.checkPermission(AuthorizationPermission.ADMIN); CompletableFuture<Void> future = null; Set<Object> keySet = new HashSet<>(); for (Object key : keys) { if (cache.containsKey(key)) { keySet.add(key); } else { LOG.warn("cache contains no mapping for the key"); } } TriConsumer<Address, Void, Throwable> triConsumer = (a, v, t) -> { if (t != null) { throw new CacheException(t); } }; if (keySet.size() > 0) { IndexWorker indexWorker = new IndexWorker(cache.getName(), null, false, keySet); future = executor.submitConsumer(indexWorker, triConsumer); } return future != null ? future : CompletableFutures.completedNull(); } @Override public CompletionStage<Void> remove() { return executeInternal(true, false).toCompletableFuture(); } @Override public CompletionStage<Void> remove(Class<?>... entities) { return executeInternal(true, false, entities); } @Override public boolean isRunning() { return isRunning; } private CompletionStage<Void> executeInternal(boolean skipIndex, boolean local, Class<?>... entities) { authorizer.checkPermission(AuthorizationPermission.ADMIN); CompletionStage<Boolean> lockStage = lock.lock(); return lockStage.thenCompose(acquired -> { if (!acquired) { return CompletableFuture.failedFuture(new MassIndexerAlreadyStartedException()); } try { isRunning = true; Collection<Class<?>> javaClasses = (entities.length == 0) ? indexUpdater.allJavaClasses() : Arrays.asList(entities); IndexWorker indexWork = new IndexWorker(cache.getName(), javaClasses, skipIndex, null); ClusterExecutor clusterExecutor = executor.timeout(Long.MAX_VALUE, TimeUnit.SECONDS); if (local) { clusterExecutor = clusterExecutor.filterTargets(a -> a.equals(cache.getRpcManager().getAddress())); } return clusterExecutor.timeout(Long.MAX_VALUE, TimeUnit.SECONDS).submitConsumer(indexWork, TRI_CONSUMER); } catch (Throwable t) { return CompletableFuture.failedFuture(t); } finally { lock.unlock(); isRunning = false; } }); } }
5,094
35.134752
117
java
null
infinispan-main/query/src/main/java/org/infinispan/query/impl/externalizers/package-info.java
/** * Externalizers for several Lucene objects. * * @api.private */ package org.infinispan.query.impl.externalizers;
121
16.428571
48
java
null
infinispan-main/query/src/main/java/org/infinispan/query/impl/externalizers/LuceneTopDocsExternalizer.java
package org.infinispan.query.impl.externalizers; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.util.Collections; import java.util.Set; import org.apache.lucene.search.ScoreDoc; import org.apache.lucene.search.TopDocs; import org.apache.lucene.search.TotalHits; import org.infinispan.commons.io.UnsignedNumeric; import org.infinispan.commons.marshall.AbstractExternalizer; public class LuceneTopDocsExternalizer extends AbstractExternalizer<TopDocs> { @Override public Set<Class<? extends TopDocs>> getTypeClasses() { return Collections.singleton(TopDocs.class); } @Override public TopDocs readObject(final ObjectInput input) throws IOException, ClassNotFoundException { final long totalHits = UnsignedNumeric.readUnsignedLong(input); final int scoreCount = UnsignedNumeric.readUnsignedInt(input); final ScoreDoc[] scoreDocs = new ScoreDoc[scoreCount]; for (int i = 0; i < scoreCount; i++) { scoreDocs[i] = (ScoreDoc) input.readObject(); } return new TopDocs(new TotalHits(totalHits, TotalHits.Relation.EQUAL_TO), scoreDocs); } @Override public void writeObject(final ObjectOutput output, final TopDocs topDocs) throws IOException { UnsignedNumeric.writeUnsignedLong(output, topDocs.totalHits.value); final ScoreDoc[] scoreDocs = topDocs.scoreDocs; final int count = scoreDocs.length; UnsignedNumeric.writeUnsignedInt(output, count); for (ScoreDoc scoreDoc : scoreDocs) { output.writeObject(scoreDoc); } } @Override public Integer getId() { return ExternalizerIds.LUCENE_TOPDOCS; } }
1,679
33.285714
98
java
null
infinispan-main/query/src/main/java/org/infinispan/query/impl/externalizers/LuceneScoreDocExternalizer.java
package org.infinispan.query.impl.externalizers; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.util.Collections; import java.util.Set; import org.apache.lucene.search.ScoreDoc; import org.infinispan.commons.io.UnsignedNumeric; import org.infinispan.commons.marshall.AbstractExternalizer; public class LuceneScoreDocExternalizer extends AbstractExternalizer<ScoreDoc> { @Override public Set<Class<? extends ScoreDoc>> getTypeClasses() { return Collections.singleton(ScoreDoc.class); } @Override public ScoreDoc readObject(final ObjectInput input) throws IOException, ClassNotFoundException { return readObjectStatic(input); } @Override public void writeObject(final ObjectOutput output, final ScoreDoc sortField) throws IOException { writeObjectStatic(output, sortField); } @Override public Integer getId() { return ExternalizerIds.LUCENE_SCORE_DOC; } private static void writeObjectStatic(final ObjectOutput output, final ScoreDoc sortField) throws IOException { output.writeFloat(sortField.score); UnsignedNumeric.writeUnsignedInt(output, sortField.doc); output.writeInt(sortField.shardIndex); } private static ScoreDoc readObjectStatic(final ObjectInput input) throws IOException { final float score = input.readFloat(); final int doc = UnsignedNumeric.readUnsignedInt(input); final int shardId = input.readInt(); return new ScoreDoc(doc, score, shardId); } }
1,536
31.020833
114
java
null
infinispan-main/query/src/main/java/org/infinispan/query/impl/externalizers/ExternalizerIds.java
package org.infinispan.query.impl.externalizers; /** * 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 * * The range reserved for the Infinispan Query module is from 1600 to 1699. * * @author Sanne Grinovero * @since 7.0 */ public interface ExternalizerIds { Integer LUCENE_SORT = 1604; Integer LUCENE_SORT_FIELD = 1605; Integer LUCENE_TOPDOCS = 1606; Integer CLUSTERED_QUERY_TOPDOCS = 1607; Integer LUCENE_SCORE_DOC = 1608; Integer LUCENE_TOPFIELDDOCS = 1609; Integer LUCENE_FIELD_SCORE_DOC = 1610; Integer INDEX_WORKER = 1613; Integer LUCENE_BYTES_REF = 1615; Integer QUERY_DEFINITION = 1621; Integer CLUSTERED_QUERY_COMMAND_RESPONSE = 1622; Integer FULL_TEXT_FILTER = 1623; Integer CLUSTERED_QUERY_OPERATION = 1624; Integer POJO_TYPE_IDENTIFIER = 1625; Integer LUCENE_TOTAL_HITS = 1626; }
1,007
21.909091
117
java
null
infinispan-main/query/src/main/java/org/infinispan/query/impl/externalizers/LuceneBytesRefExternalizer.java
package org.infinispan.query.impl.externalizers; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.util.Collections; import java.util.Set; import org.apache.lucene.util.BytesRef; import org.infinispan.commons.io.UnsignedNumeric; import org.infinispan.commons.marshall.AbstractExternalizer; public class LuceneBytesRefExternalizer extends AbstractExternalizer<BytesRef> { @Override public Integer getId() { return ExternalizerIds.LUCENE_BYTES_REF; } @Override public Set<Class<? extends BytesRef>> getTypeClasses() { return Collections.singleton(BytesRef.class); } @Override public void writeObject(ObjectOutput output, BytesRef object) throws IOException { UnsignedNumeric.writeUnsignedInt(output, object.length); output.write(object.bytes, object.offset, object.length); } @Override public BytesRef readObject(ObjectInput input) throws IOException, ClassNotFoundException { int length = UnsignedNumeric.readUnsignedInt(input); byte[] bytes = new byte[length]; input.readFully(bytes, 0, length); return new BytesRef(bytes, 0, length); } }
1,178
28.475
93
java
null
infinispan-main/query/src/main/java/org/infinispan/query/impl/externalizers/LuceneTopFieldDocsExternalizer.java
package org.infinispan.query.impl.externalizers; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.util.Collections; import java.util.Set; import org.apache.lucene.search.ScoreDoc; import org.apache.lucene.search.SortField; import org.apache.lucene.search.TopFieldDocs; import org.apache.lucene.search.TotalHits; import org.infinispan.commons.io.UnsignedNumeric; import org.infinispan.commons.marshall.AbstractExternalizer; public class LuceneTopFieldDocsExternalizer extends AbstractExternalizer<TopFieldDocs> { @Override public Set<Class<? extends TopFieldDocs>> getTypeClasses() { return Collections.singleton(TopFieldDocs.class); } @Override public TopFieldDocs readObject(final ObjectInput input) throws IOException, ClassNotFoundException { TotalHits totalHits = (TotalHits) input.readObject(); final int sortFieldsCount = UnsignedNumeric.readUnsignedInt(input); final SortField[] sortFields = new SortField[sortFieldsCount]; for (int i = 0; i < sortFieldsCount; i++) { sortFields[i] = LuceneSortFieldExternalizer.readObjectStatic(input); } final int scoreDocsCount = UnsignedNumeric.readUnsignedInt(input); final ScoreDoc[] scoreDocs = new ScoreDoc[scoreDocsCount]; for (int i = 0; i < scoreDocsCount; i++) { scoreDocs[i] = (ScoreDoc) input.readObject(); } return new TopFieldDocs(totalHits, scoreDocs, sortFields); } @Override public void writeObject(final ObjectOutput output, final TopFieldDocs topFieldDocs) throws IOException { output.writeObject(topFieldDocs.totalHits); final SortField[] sortFields = topFieldDocs.fields; UnsignedNumeric.writeUnsignedInt(output, sortFields.length); for (SortField sortField : sortFields) { LuceneSortFieldExternalizer.writeObjectStatic(output, sortField); } final ScoreDoc[] scoreDocs = topFieldDocs.scoreDocs; UnsignedNumeric.writeUnsignedInt(output, scoreDocs.length); for (ScoreDoc scoreDoc : scoreDocs) { output.writeObject(scoreDoc); } } @Override public Integer getId() { return ExternalizerIds.LUCENE_TOPFIELDDOCS; } }
2,226
36.745763
107
java
null
infinispan-main/query/src/main/java/org/infinispan/query/impl/externalizers/LuceneTotalHitsExternalizer.java
package org.infinispan.query.impl.externalizers; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.util.Collections; import java.util.Set; import org.apache.lucene.search.TotalHits; import org.infinispan.commons.io.UnsignedNumeric; import org.infinispan.commons.marshall.AbstractExternalizer; import org.infinispan.commons.marshall.MarshallUtil; public class LuceneTotalHitsExternalizer extends AbstractExternalizer<TotalHits> { private static final TotalHits.Relation[] TOTALHITS_RELATION_VALUES = TotalHits.Relation.values(); @Override public Integer getId() { return ExternalizerIds.LUCENE_TOTAL_HITS; } @Override public Set<Class<? extends TotalHits>> getTypeClasses() { return Collections.singleton(TotalHits.class); } @Override public void writeObject(ObjectOutput output, TotalHits totalHits) throws IOException { UnsignedNumeric.writeUnsignedLong(output, totalHits.value); MarshallUtil.marshallEnum(totalHits.relation, output); } @Override public TotalHits readObject(ObjectInput input) throws IOException, ClassNotFoundException { long value = UnsignedNumeric.readUnsignedLong(input); TotalHits.Relation relation = MarshallUtil.unmarshallEnum(input, (ordinal) -> TOTALHITS_RELATION_VALUES[ordinal]); return new TotalHits(value, relation); } }
1,388
32.878049
120
java
null
infinispan-main/query/src/main/java/org/infinispan/query/impl/externalizers/LuceneSortExternalizer.java
package org.infinispan.query.impl.externalizers; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.util.Collections; import java.util.Set; import org.apache.lucene.search.Sort; import org.apache.lucene.search.SortField; import org.infinispan.commons.io.UnsignedNumeric; import org.infinispan.commons.marshall.AbstractExternalizer; public class LuceneSortExternalizer extends AbstractExternalizer<Sort> { @Override public Set<Class<? extends Sort>> getTypeClasses() { return Collections.singleton(Sort.class); } @Override public Sort readObject(final ObjectInput input) throws IOException, ClassNotFoundException { final int count = UnsignedNumeric.readUnsignedInt(input); SortField[] sortfields = new SortField[count]; for (int i = 0; i < count; i++) { sortfields[i] = LuceneSortFieldExternalizer.readObjectStatic(input); } Sort sort = new Sort(); sort.setSort(sortfields); return sort; } @Override public void writeObject(final ObjectOutput output, final Sort sort) throws IOException { final SortField[] sortFields = sort.getSort(); final int count = sortFields.length; UnsignedNumeric.writeUnsignedInt(output, count); for (int i = 0; i < count; i++) { LuceneSortFieldExternalizer.writeObjectStatic(output, sortFields[i]); } } @Override public Integer getId() { return ExternalizerIds.LUCENE_SORT; } }
1,497
29.571429
95
java
null
infinispan-main/query/src/main/java/org/infinispan/query/impl/externalizers/LuceneSortFieldExternalizer.java
package org.infinispan.query.impl.externalizers; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.util.Collections; import java.util.Set; import org.apache.lucene.search.SortField; import org.apache.lucene.search.SortField.Type; import org.infinispan.commons.marshall.AbstractExternalizer; import org.infinispan.commons.marshall.MarshallUtil; /** * WARNING: this Externalizer implementation drops some state associated to the SortField instance. * * A CUSTOM Sort Type is unsupported, and it is also not possible to use a custom Field Parser * or options related to missing value sorting. */ public class LuceneSortFieldExternalizer extends AbstractExternalizer<SortField> { private static final SortField.Type[] SORTFIELD_TYPE_VALUES = SortField.Type.values(); @Override public Set<Class<? extends SortField>> getTypeClasses() { return Collections.singleton(SortField.class); } @Override public SortField readObject(ObjectInput input) throws IOException { return readObjectStatic(input); } @Override public void writeObject(ObjectOutput output, SortField sortField) throws IOException { writeObjectStatic(output, sortField); } @Override public Integer getId() { return ExternalizerIds.LUCENE_SORT_FIELD; } static void writeObjectStatic(ObjectOutput output, SortField sortField) throws IOException { Type sortType = sortField.getType(); MarshallUtil.marshallEnum(sortType, output); if (!Type.SCORE.equals(sortType)) { output.writeUTF(sortField.getField()); } output.writeBoolean(sortField.getReverse()); } static SortField readObjectStatic(ObjectInput input) throws IOException { Type sortType = MarshallUtil.unmarshallEnum(input, (ordinal) -> SORTFIELD_TYPE_VALUES[ordinal]); String fieldName = null; if (!Type.SCORE.equals(sortType)) { fieldName = input.readUTF(); } boolean reverseSort = input.readBoolean(); return new SortField(fieldName, sortType, reverseSort); } }
2,095
31.75
102
java
null
infinispan-main/query/src/main/java/org/infinispan/query/impl/externalizers/LuceneFieldDocExternalizer.java
package org.infinispan.query.impl.externalizers; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.util.Collections; import java.util.Set; import org.apache.lucene.search.FieldDoc; import org.infinispan.commons.io.UnsignedNumeric; import org.infinispan.commons.marshall.AbstractExternalizer; public class LuceneFieldDocExternalizer extends AbstractExternalizer<FieldDoc> { @Override public Set<Class<? extends FieldDoc>> getTypeClasses() { return Collections.singleton(FieldDoc.class); } @Override public FieldDoc readObject(final ObjectInput input) throws IOException, ClassNotFoundException { return readObjectStatic(input); } @Override public void writeObject(final ObjectOutput output, final FieldDoc sortField) throws IOException { writeObjectStatic(output, sortField); } @Override public Integer getId() { return ExternalizerIds.LUCENE_FIELD_SCORE_DOC; } static void writeObjectStatic(final ObjectOutput output, final FieldDoc sortField) throws IOException { output.writeFloat(sortField.score); UnsignedNumeric.writeUnsignedInt(output, sortField.doc); output.writeInt(sortField.shardIndex); final Object[] fields = sortField.fields; UnsignedNumeric.writeUnsignedInt(output, fields.length); for (int i = 0; i < fields.length; i++) { output.writeObject(fields[i]); } } static FieldDoc readObjectStatic(final ObjectInput input) throws IOException, ClassNotFoundException { final float score = input.readFloat(); final int doc = UnsignedNumeric.readUnsignedInt(input); final int shardId = input.readInt(); final int fieldsArrayLenght = UnsignedNumeric.readUnsignedInt(input); Object[] fields = new Object[fieldsArrayLenght]; for (int i = 0; i < fieldsArrayLenght; i++) { fields[i] = input.readObject(); } return new FieldDoc(doc, score, fields, shardId); } }
1,997
33.448276
106
java
null
infinispan-main/query/src/main/java/org/infinispan/query/impl/externalizers/PojoRawTypeIdentifierExternalizer.java
package org.infinispan.query.impl.externalizers; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.util.Collections; import java.util.Optional; import java.util.Set; import org.hibernate.search.mapper.pojo.model.spi.PojoRawTypeIdentifier; import org.infinispan.commons.marshall.AbstractExternalizer; import org.infinispan.commons.util.ReflectionUtil; public class PojoRawTypeIdentifierExternalizer extends AbstractExternalizer<PojoRawTypeIdentifier> { @Override public Integer getId() { return ExternalizerIds.POJO_TYPE_IDENTIFIER; } @Override public Set<Class<? extends PojoRawTypeIdentifier>> getTypeClasses() { return Collections.singleton(PojoRawTypeIdentifier.class); } @Override public void writeObject(ObjectOutput output, PojoRawTypeIdentifier object) throws IOException { output.writeObject(object.javaClass()); if (object.isNamed()) { // TODO avoid reflection here String name = (String) ReflectionUtil.getValue(object, "name"); output.writeObject(Optional.of(name)); } else { output.writeObject(Optional.empty()); } } @Override public PojoRawTypeIdentifier readObject(ObjectInput input) throws IOException, ClassNotFoundException { Class<?> javaClass = (Class<?>) input.readObject(); Optional<String> typeName = (Optional<String>) input.readObject(); return (typeName.isPresent()) ? PojoRawTypeIdentifier.of(javaClass, typeName.get()) : PojoRawTypeIdentifier.of(javaClass); } }
1,581
33.391304
106
java
null
infinispan-main/query/src/main/java/org/infinispan/query/stats/impl/LocalIndexStatistics.java
package org.infinispan.query.stats.impl; import java.util.HashMap; import java.util.Map; import java.util.Set; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionStage; import org.hibernate.search.backend.lucene.index.LuceneIndexManager; import org.hibernate.search.engine.backend.work.execution.OperationSubmitter; import org.hibernate.search.engine.common.execution.spi.SimpleScheduledExecutor; import org.hibernate.search.engine.search.predicate.dsl.SearchPredicateFactory; import org.hibernate.search.util.common.SearchException; 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.query.Indexer; import org.infinispan.query.concurrent.InfinispanIndexingExecutorProvider; import org.infinispan.query.core.stats.IndexInfo; import org.infinispan.query.core.stats.IndexStatistics; import org.infinispan.query.core.stats.IndexStatisticsSnapshot; import org.infinispan.query.core.stats.impl.IndexStatisticsSnapshotImpl; import org.infinispan.query.logging.Log; import org.infinispan.search.mapper.mapping.SearchIndexedEntity; import org.infinispan.search.mapper.mapping.SearchMapping; import org.infinispan.search.mapper.scope.SearchScope; import org.infinispan.search.mapper.session.SearchSession; import org.infinispan.util.concurrent.AggregateCompletionStage; import org.infinispan.util.concurrent.BlockingManager; import org.infinispan.util.concurrent.CompletionStages; import org.infinispan.util.logging.LogFactory; /** * A {@link IndexStatistics} for an indexed Cache. * * @since 12.0 */ @Scope(Scopes.NAMED_CACHE) public class LocalIndexStatistics implements IndexStatistics { private static final Log log = LogFactory.getLog(LocalIndexStatistics.class, Log.class); @Inject SearchMapping searchMapping; @Inject BlockingManager blockingManager; @Inject Indexer indexer; private SimpleScheduledExecutor offloadingExecutor; @Start void start() { offloadingExecutor = InfinispanIndexingExecutorProvider.writeExecutor(blockingManager); } @Override public Set<String> indexedEntities() { return searchMapping.allIndexedEntityNames(); } @Override public CompletionStage<Map<String, IndexInfo>> computeIndexInfos() { Map<String, CompletionStage<IndexInfo>> infoStages = new HashMap<>(); AggregateCompletionStage<Map<String, IndexInfo>> aggregateCompletionStage = CompletionStages.aggregateCompletionStage(new HashMap<>()); for (SearchIndexedEntity entity : searchMapping.indexedEntitiesForStatistics()) { CompletionStage<IndexInfo> stage = indexInfos(entity); infoStages.put(entity.name(), stage); aggregateCompletionStage.dependsOn(stage); } return aggregateCompletionStage.freeze() .thenApply(map -> { // When we get here, all stages have completed successfully, so the join is safe. infoStages.forEach((name, stage) -> map.put(name, CompletionStages.join(stage))); return map; }); } private CompletionStage<IndexInfo> indexInfos(SearchIndexedEntity indexedEntity) { CompletionStage<Long> countStage = blockingManager.supplyBlocking( () -> { SearchSession session = searchMapping.getMappingSession(); SearchScope<?> scope = session.scope(indexedEntity.javaClass(), indexedEntity.name()); long hitCount = -1; try { hitCount = session.search(scope).where(SearchPredicateFactory::matchAll).fetchTotalHitCount(); } catch (Throwable throwable) { log.concurrentReindexingOnGetStatistics(throwable); } return hitCount; }, this); return countStage .thenCompose(count -> { CompletionStage<Long> sizeStage; if (count == -1L || reindexing()) { sizeStage = CompletableFuture.completedFuture(-1L); } else { try { sizeStage = indexedEntity.indexManager().unwrap(LuceneIndexManager.class) .computeSizeInBytesAsync(OperationSubmitter.offloading(task -> offloadingExecutor.submit(task))) .exceptionally(throwable -> { log.concurrentReindexingOnGetStatistics(throwable); return -1L; }); } catch (SearchException exception) { if (exception.getMessage().contains("HSEARCH000563")) { // in this case the engine orchestrator is stopped (not allowing to submit more tasks), // it means that the engine is stopping, // it means we cannot compute side at the moment sizeStage = CompletableFuture.completedFuture(-1L); } else { // in the all other cases we get an unexpected error from the search engine throw exception; } } } return sizeStage.thenApply(size -> new IndexInfo(count, size)); }); } @Override public boolean reindexing() { return indexer.isRunning(); } @Override public int genericIndexingFailures() { return searchMapping.genericIndexingFailures(); } @Override public int entityIndexingFailures() { return searchMapping.entityIndexingFailures(); } @Override public CompletionStage<IndexStatisticsSnapshot> computeSnapshot() { return computeIndexInfos().thenApply(infos -> new IndexStatisticsSnapshotImpl(infos, reindexing(), genericIndexingFailures(), entityIndexingFailures())); } }
5,981
39.972603
159
java
null
infinispan-main/query/src/main/java/org/infinispan/query/internal/QueryBlockHoundIntegration.java
package org.infinispan.query.internal; import org.apache.lucene.util.NamedSPILoader; import org.kohsuke.MetaInfServices; import reactor.blockhound.BlockHound; import reactor.blockhound.integration.BlockHoundIntegration; @MetaInfServices public class QueryBlockHoundIntegration implements BlockHoundIntegration { @Override public void applyTo(BlockHound.Builder builder) { // Loading a service may require opening a file from classpath builder.allowBlockingCallsInside(NamedSPILoader.class.getName(), "reload"); } }
539
30.764706
81
java
null
infinispan-main/build/component-processor/src/main/java/org/infinispan/component/processor/ComponentAnnotationProcessor.java
package org.infinispan.component.processor; import static org.infinispan.component.processor.AnnotationTypeValuesExtractor.getTypeValues; import java.io.IOException; import java.lang.annotation.Annotation; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.function.Function; import java.util.regex.Pattern; import java.util.stream.Collectors; import java.util.stream.Stream; import javax.annotation.processing.AbstractProcessor; import javax.annotation.processing.Filer; import javax.annotation.processing.ProcessingEnvironment; import javax.annotation.processing.Processor; import javax.annotation.processing.RoundEnvironment; import javax.annotation.processing.SupportedAnnotationTypes; import javax.annotation.processing.SupportedSourceVersion; import javax.lang.model.AnnotatedConstruct; import javax.lang.model.SourceVersion; import javax.lang.model.element.Element; import javax.lang.model.element.ElementKind; import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.Modifier; import javax.lang.model.element.Name; import javax.lang.model.element.TypeElement; import javax.lang.model.element.VariableElement; import javax.lang.model.type.DeclaredType; import javax.lang.model.type.PrimitiveType; import javax.lang.model.type.TypeMirror; import javax.lang.model.util.ElementScanner8; import javax.lang.model.util.Elements; import javax.lang.model.util.Types; import javax.tools.Diagnostic; import org.infinispan.factories.annotations.ComponentName; import org.infinispan.factories.annotations.DefaultFactoryFor; import org.infinispan.factories.annotations.InfinispanModule; import org.infinispan.factories.annotations.Inject; import org.infinispan.factories.annotations.Start; import org.infinispan.factories.annotations.Stop; import org.infinispan.factories.annotations.SurvivesRestarts; import org.infinispan.factories.scopes.Scope; import org.infinispan.factories.scopes.Scopes; import org.infinispan.jmx.annotations.DataType; import org.infinispan.jmx.annotations.MBean; import org.infinispan.jmx.annotations.ManagedAttribute; import org.infinispan.jmx.annotations.ManagedOperation; import org.infinispan.jmx.annotations.Parameter; import org.infinispan.jmx.annotations.Units; import org.kohsuke.MetaInfServices; @SupportedSourceVersion(SourceVersion.RELEASE_11) @SupportedAnnotationTypes({ComponentAnnotationProcessor.INFINISPAN_MODULE, ComponentAnnotationProcessor.DEFAULT_FACTORY_FOR, ComponentAnnotationProcessor.SURVIVES_RESTARTS, ComponentAnnotationProcessor.SCOPE, ComponentAnnotationProcessor.MBEAN, ComponentAnnotationProcessor.INJECT, ComponentAnnotationProcessor.START, ComponentAnnotationProcessor.STOP, ComponentAnnotationProcessor.MANAGED_ATTRIBUTE, ComponentAnnotationProcessor.MANAGED_OPERATION, ComponentAnnotationProcessor.MANAGED_OPERATION_PARAMETER}) @MetaInfServices(Processor.class) public class ComponentAnnotationProcessor extends AbstractProcessor { static final String INFINISPAN_MODULE = "org.infinispan.factories.annotations.InfinispanModule"; static final String DEFAULT_FACTORY_FOR = "org.infinispan.factories.annotations.DefaultFactoryFor"; static final String SURVIVES_RESTARTS = "org.infinispan.factories.annotations.SurvivesRestarts"; static final String SCOPE = "org.infinispan.factories.scopes.Scope"; static final String MBEAN = "org.infinispan.jmx.annotations.MBean"; static final String INJECT = "org.infinispan.factories.annotations.Inject"; static final String START = "org.infinispan.factories.annotations.Start"; static final String STOP = "org.infinispan.factories.annotations.Stop"; static final String MANAGED_ATTRIBUTE = "org.infinispan.jmx.annotations.ManagedAttribute"; static final String MANAGED_OPERATION = "org.infinispan.jmx.annotations.ManagedOperation"; static final String MANAGED_OPERATION_PARAMETER = "org.infinispan.jmx.annotations.Parameter"; private static final String FACTORY_CLASSES = "classes"; private static final String COMPONENT_REF_CLASS = "org.infinispan.factories.impl.ComponentRef"; private static final String AUTO_INSTANTIABLE_FACTORY_CLASS = "org.infinispan.factories.AutoInstantiableFactory"; private static final Pattern MODULE_NAME_PATTERN = Pattern.compile("[a-zA-Z][-a-zA-Z0-9]*"); private static final Pattern MODULE_NAME_SEPARATOR_PATTERN = Pattern.compile("-"); private boolean errorReported = false; private ModelBuilder modelBuilder; private TypeMirror autoInstantiableType; @Override public synchronized void init(ProcessingEnvironment processingEnv) { super.init(processingEnv); modelBuilder = new ModelBuilder(); try { parseGeneratedSources(modelBuilder); } catch (Throwable t) { uncaughtException(t); } } @Override public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) { try { TypeElement autoInstantiableElement = elements().getTypeElement(AUTO_INSTANTIABLE_FACTORY_CLASS); if (autoInstantiableElement == null) { error(null, "Could not find type %s in the classpath, please rebuild", AUTO_INSTANTIABLE_FACTORY_CLASS); return false; } autoInstantiableType = autoInstantiableElement.asType(); modelBuilder.scan(roundEnv.getRootElements(), null); // In theory we could generate the package classes early (or better generate a class for each component) // but the classes we generate don't have any annotations for other processors to parse. if (roundEnv.processingOver()) { Model model = modelBuilder.getModel(); if (modelBuilder.module == null) { error(null, "@InfinispanModule annotation not found in any class, please perform a clean build. " + "Found components %s", modelBuilder.annotatedTypes.keySet()); return true; } // Only generate classes if valid if (errorReported || roundEnv.errorRaised()) return true; Generator generator = new Generator(model, filer()); generator.writePackageClasses(); // IntelliJ will delete the generated file before compilation if any of the source elements has changed // We make the module impl and service fine depend only on the module class, // so we know either they are present on disk or the module class is being compiled. TypeElement[] sourceElements = {model.module.typeElement}; generator.writeModuleClass(sourceElements); generator.writeServiceFile(sourceElements); } } catch (Throwable t) { uncaughtException(t); } return true; } private void parseGeneratedSources(ModelBuilder modelBuilder) throws IOException { // Set an empty default to simplify early returns modelBuilder.parsedTypes = Collections.emptyMap(); String moduleImplementationName = Generator.readServiceFile(filer()); if (moduleImplementationName == null) { return; } Map.Entry<String, Set<String>> moduleClassAndPackages = Generator.readModuleClass(filer(), moduleImplementationName); if (moduleClassAndPackages == null) { info(null, "Ignoring removed or renamed module implementation %s", moduleImplementationName); return; } TypeElement moduleClassElement = elements().getTypeElement(moduleClassAndPackages.getKey()); InfinispanModule moduleAnnotation = moduleClassElement != null ? getAnnotation(moduleClassElement, InfinispanModule.class) : null; if (moduleAnnotation == null) { error(null, "Ignoring invalid module implementation %s", moduleImplementationName); return; } String classPrefix = moduleToClassPrefix(moduleAnnotation.name()); Set<String> packages = moduleClassAndPackages.getValue(); Map<String, Model.ParsedType> parsedTypes = new HashMap<>(); for (String packageName : packages) { Map<String, List<String>> packageSources = Generator.readPackageClass(filer(), packageName, classPrefix); if (packageSources == null) { info(null, "Ignoring removed or renamed package implementation %s", packageName); continue; } packageSources.forEach((qualifiedName, code) -> { TypeElement sourceType = elements().getTypeElement(qualifiedName); if (sourceType == null) { info( null, "Ignoring removed component class %s", qualifiedName); } else { parsedTypes.put(qualifiedName, new Model.ParsedType(sourceType, qualifiedName, packageName, code)); } }); } modelBuilder.parsedTypes = parsedTypes; modelBuilder.setModuleClass(moduleClassElement, moduleAnnotation, classPrefix); } private <A extends Annotation> A getAnnotation(AnnotatedConstruct moduleClassElement, Class<A> annotationType) { try { return moduleClassElement.getAnnotation(annotationType); } catch (ClassCastException e) { // The annotation has unresolved values // java.lang.ClassCastException: class com.sun.tools.javac.code.Attribute$UnresolvedClass // cannot be cast to class com.sun.tools.javac.code.Attribute$Class // The code doesn't compile anyway, so we can ignore the annotation. return null; } } private static String extractAttributeName(String setterOrGetter) { String name = null; if (setterOrGetter.startsWith("set") || setterOrGetter.startsWith("get")) name = setterOrGetter.substring(3); else if (setterOrGetter.startsWith("is")) name = setterOrGetter.substring(2); if (name != null && name.length() > 1) { return Character.toLowerCase(name.charAt(0)) + name.substring(1); } return null; } private void uncaughtException(Throwable t) { String stackTrace = Stream.of(t.getStackTrace()) .map(Object::toString) .collect(Collectors.joining("\n\tat ", "\tat ", "")); error(null, "ComponentAnnotationProcessor unexpected error: %s\n%s", t, stackTrace); } private void error(Element e, String format, Object... params) { log(Diagnostic.Kind.ERROR, e, format, params); errorReported = true; } private void warn(Element e, String format, Object... params) { log(Diagnostic.Kind.WARNING, e, format, params); } private void info(Element e, String format, Object... params) { log(Diagnostic.Kind.NOTE, e, format, params); } private void log(Diagnostic.Kind level, Element e, String format, Object... params) { String formatted = String.format(format, params); if (e != null) { processingEnv.getMessager().printMessage(level, formatted, e); } else { processingEnv.getMessager().printMessage(level, formatted); } } private Elements elements() { return processingEnv.getElementUtils(); } private Types types() { return processingEnv.getTypeUtils(); } private Filer filer() { return processingEnv.getFiler(); } private String moduleToClassPrefix(CharSequence moduleName) { StringBuilder classPrefix = new StringBuilder(); for (String element : MODULE_NAME_SEPARATOR_PATTERN.split(moduleName)) { classPrefix.append(Character.toUpperCase(element.charAt(0))) .append(element.subSequence(1, element.length())); } return classPrefix.toString(); } private class ModelBuilder extends ElementScanner8<Void, Void> { private Model.Module module; Map<String, Model.ParsedType> parsedTypes; private final Map<String, Model.AnnotatedType> annotatedTypes = new HashMap<>(); private Model.AnnotatedType currentType; @Override public Void visitType(TypeElement e, Void ignored) { Model.AnnotatedType savedType = currentType; String qualifiedName = e.getQualifiedName().toString(); InfinispanModule moduleAnnotation = getAnnotation(e, InfinispanModule.class); if (moduleAnnotation != null) { String classPrefix = moduleToClassPrefix(moduleAnnotation.name()); setModuleClass(e, moduleAnnotation, classPrefix); } Scope scope = getAnnotation(e, Scope.class); MBean mbean = getAnnotation(e, MBean.class); boolean survivesRestarts = getAnnotation(e, SurvivesRestarts.class) != null; if (!survivesRestarts) { requireAnnotationOnSubType(e, SurvivesRestarts.class); } if (scope != null || mbean != null) { String binaryName = binaryName(e); String packageName = elements().getPackageOf(e).getQualifiedName().toString(); Model.AnnotatedType annotatedType = new Model.AnnotatedType(e, qualifiedName, binaryName, packageName); annotatedTypes.put(qualifiedName, annotatedType); currentType = annotatedType; if (scope != null) { validatePackagePrivate(e, Scope.class); requireSameScope(e, scope); List<String> factoryComponentNames = getFactoryComponentNames(e); boolean autoInstantiable = types().isAssignable(e.asType(), autoInstantiableType); String superBinaryName = binaryName(getSuperClass(e, Scope.class)); annotatedType.component = new Model.Component(scope, survivesRestarts, factoryComponentNames, autoInstantiable, superBinaryName); } else { requireAnnotationOnSubType(e, Scope.class); } if (mbean != null) { String superMComponent = binaryName(getSuperClass(e, MBean.class)); annotatedType.mComponent = new Model.MComponent(mbean, superMComponent); } else { requireAnnotationOnSubType(e, MBean.class); } } // Ignore the parsed code parsedTypes.remove(qualifiedName); try { return super.visitType(e, ignored); } finally { currentType = savedType; } } private void setModuleClass(TypeElement e, InfinispanModule moduleAnnotation, String classPrefix) { validateModule(e, moduleAnnotation); String modulePackageName = elements().getPackageOf(e).getQualifiedName().toString(); module = new Model.Module(moduleAnnotation, e, modulePackageName, classPrefix); } private void validateModule(TypeElement e, InfinispanModule moduleAnnotation) { String moduleName = moduleAnnotation.name(); if (!MODULE_NAME_PATTERN.matcher(moduleName).matches()) { error(e, "@InfinispanModule name attribute must include only letters, digits or `-`"); } Name moduleClassName = e.getQualifiedName(); if (module != null && !moduleClassName.contentEquals(module.moduleClassName)) { error(e, "@InfinispanModule allowed on a single class, already present on %s", module.moduleClassName); } } @Override public Void visitExecutable(ExecutableElement e, Void ignored) { String methodName = e.getSimpleName().toString(); if (getAnnotation(e, Inject.class) != null) { validatePackagePrivate(e, Scope.class); if (isValidComponent(e, Inject.class)) { List<Model.InjectField> parameters = e.getParameters().stream() .map(this::makeInjectField) .collect(Collectors.toList()); currentType.component.injectMethods.add(new Model.InjectMethod(methodName, parameters)); } } addLifecycleMethod(e, Start.class, c -> c.startMethods, Start::priority); addLifecycleMethod(e, Stop.class, c -> c.stopMethods, Stop::priority); if (getAnnotation(e, ManagedAttribute.class) != null && isValidMComponent(e, ManagedAttribute.class)) { ManagedAttribute attribute = getAnnotation(e, ManagedAttribute.class); String name = attribute != null ? attribute.name() : ""; if (name.isEmpty()) { name = extractAttributeName(methodName); } boolean is = methodName.startsWith("is"); String type; String boxedType; if (methodName.startsWith("set")) { TypeMirror t = e.getParameters().get(0).asType(); type = types().erasure(t).toString(); boxedType = t.getKind().isPrimitive() ? types().boxedClass((PrimitiveType) t).toString() : type; } else if (methodName.startsWith("get") || is) { TypeMirror t = e.getReturnType(); type = types().erasure(t).toString(); boxedType = t.getKind().isPrimitive() ? types().boxedClass((PrimitiveType) t).toString() : type; } else { error(e, "Method annotated with @ManagedAttribute does not start with `set`, `get`, or `is`"); type = boxedType = ""; } validateUnits(e, attribute); currentType.mComponent.attributes.add(new Model.MAttribute(name, methodName, attribute, true, type, boxedType, is)); } if (getAnnotation(e, ManagedOperation.class) != null) if (isValidMComponent(e, ManagedOperation.class)) { ManagedOperation operation = getAnnotation(e, ManagedOperation.class); List<Model.MParameter> parameters = new ArrayList<>(); for (VariableElement parameter : e.getParameters()) { Parameter parameterAnnotation = getAnnotation(parameter, Parameter.class); String name = (parameterAnnotation != null && !parameterAnnotation.name().isEmpty()) ? parameterAnnotation.name() : parameter.getSimpleName().toString(); String type = types().erasure(parameter.asType()).toString(); String description = parameterAnnotation != null ? parameterAnnotation.description() : null; parameters.add(new Model.MParameter(name, type, description)); } currentType.mComponent.operations.add( new Model.MOperation(methodName, operation, types().erasure(e.getReturnType()).toString(), parameters)); } return super.visitExecutable(e, ignored); } private void validateUnits(Element e, ManagedAttribute attribute) { if (attribute.dataType() == DataType.TIMER) { if (!Units.TIME_UNITS.contains(attribute.units())) { error(e, "@ManagedAttribute.units is expected to be a time unit since `dataType` is DataType.TIMER"); } } } private <A extends Annotation> void addLifecycleMethod(ExecutableElement e, Class<A> annotationType, Function<Model.Component, List<Model.LifecycleMethod>> methodsExtractor, Function<A, Integer> priorityExtractor) { A annotation = getAnnotation(e, annotationType); if (annotation == null) return; if (isValidComponent(e, annotationType)) { validateLifecycleMethod(e, annotationType); List<Model.LifecycleMethod> methodList = methodsExtractor.apply(currentType.component); Integer priority = priorityExtractor.apply(annotation); methodList.add(new Model.LifecycleMethod(e.getSimpleName().toString(), priority)); } } private <A extends Annotation> void validateLifecycleMethod(ExecutableElement method, Class<A> annotationType) { validatePackagePrivate(method, annotationType); if (!method.getParameters().isEmpty()) { error(method, "Methods annotated @%s must have no parameters", annotationType.getSimpleName()); } if (existsInSuper(method, annotationType)) { error(method, "Inherited lifecycle methods should not be annotated with @%s", annotationType.getSimpleName()); } } private <A extends Annotation> boolean existsInSuper(ExecutableElement method, Class<A> annotationType) { TypeElement superAccessorType = getSuperClass(currentType.typeElement, Scope.class); while (superAccessorType != null) { for (Element element : superAccessorType.getEnclosedElements()) { if (element.getKind() == ElementKind.METHOD && element.getSimpleName().contentEquals(method.getSimpleName()) && getAnnotation(element, annotationType) != null) { // Method is already included in the super class lifecycle, ignore it return true; } } superAccessorType = getSuperClass(superAccessorType, Scope.class); } return false; } @Override public Void visitVariable(VariableElement e, Void ignored) { if (getAnnotation(e, Inject.class) != null) { validatePackagePrivate(e, Scope.class); if (isValidComponent(e, Inject.class)) { currentType.component.injectFields.add(makeInjectField(e)); } } ManagedAttribute attribute = getAnnotation(e, ManagedAttribute.class); if (attribute != null) { if (isValidMComponent(e, ManagedAttribute.class)) { String name = e.getSimpleName().toString(); TypeMirror t = e.asType(); String type = types().erasure(t).toString(); String boxedType = t.getKind().isPrimitive() ? types().boxedClass((PrimitiveType) t).toString() : type; validateUnits(e, attribute); currentType.mComponent.attributes.add(new Model.MAttribute(name, name, attribute, false, type, boxedType, false)); } } return super.visitVariable(e, ignored); } private Model.InjectField makeInjectField(VariableElement e) { String fieldName = e.getSimpleName().toString(); TypeMirror componentType = getInjectedType(e); String binaryName = binaryName(componentType); String componentName = getComponentName(e, binaryName); String qualifiedTypeName = componentType.toString(); boolean isComponentRef = isComponentRef(e); return new Model.InjectField(fieldName, qualifiedTypeName, componentName, isComponentRef); } private void requireSameScope(TypeElement e, Scope scope) { for (TypeMirror superType : types().directSupertypes(e.asType())) { Element superTypeElement = ((DeclaredType) superType).asElement(); Scope superScope = getAnnotation(superTypeElement, Scope.class); if (superScope != null && superScope.value() != Scopes.NONE) { if (scope.value() != superScope.value()) { error(e, "Scope declared on class %s (%s) does not match scope inherited from %s (%s)", e.getSimpleName(), scope.value(), superTypeElement.getSimpleName(), superScope.value()); } } } } private boolean isValidComponent(Element methodOrField, Class<? extends Annotation> methodAnnotation) { boolean valid = true; if (currentType == null || currentType.component == null) { error(methodOrField, "When a method is annotated with @%s, the type must be annotated with @%s", methodAnnotation.getSimpleName(), Scope.class.getSimpleName()); valid = false; } if (!methodOrField.getEnclosingElement().getKind().isClass()) { error(methodOrField, "Interface methods must not be annotated with @%s", methodAnnotation.getSimpleName()); valid = false; } return valid; } private boolean isValidMComponent(Element methodOrField, Class<? extends Annotation> methodAnnotation) { boolean valid = true; // ResourceDMBean still uses reflection, so it doesn't need package-private if (currentType == null || currentType.mComponent == null) { error(methodOrField, "When a method is annotated with @%s, the class must be annotated with @%s", methodAnnotation.getSimpleName(), MBean.class.getSimpleName()); valid = false; } if (!methodOrField.getEnclosingElement().getKind().isClass()) { error(methodOrField, "Interface methods must not be annotated with @%s", methodAnnotation.getSimpleName()); valid = false; } return valid; } private void validatePackagePrivate(Element element, Class<? extends Annotation> annotationType) { if (element.getModifiers().contains(Modifier.PRIVATE)) { String kind; if (element.getKind().isField()) { kind = "Fields"; } else if (element.getKind() == ElementKind.METHOD) { kind = "Methods"; } else { kind = "Types"; } error(element, "%s annotated with @%s must not be private", kind, annotationType); } } private void requireAnnotationOnSubType(TypeElement typeElement, Class<? extends Annotation> typeAnnotation) { for (TypeMirror supertype : types().directSupertypes(typeElement.asType())) { TypeElement superTypeElement = (TypeElement) ((DeclaredType) supertype).asElement(); if (getAnnotation(superTypeElement, typeAnnotation) != null) { error(typeElement, "Type %s must have annotation @%s because it extends/implements %s. " + "Note that interface annotations are not inherited", typeElement.getSimpleName(), typeAnnotation.getSimpleName(), superTypeElement.getSimpleName()); } } } public Model getModel() { Map<String, Model.Package> packages = new HashMap<>(); for (Model.AnnotatedType annotatedType : annotatedTypes.values()) { Model.Package aPackage = packages.computeIfAbsent(annotatedType.packageName, Model.Package::new); aPackage.annotatedTypes.add(annotatedType); aPackage.typeElements.add(annotatedType.typeElement); } for (Model.ParsedType parsedType : parsedTypes.values()) { Model.Package aPackage = packages.computeIfAbsent(parsedType.packageName, Model.Package::new); aPackage.parsedTypes.add(parsedType); aPackage.typeElements.add(parsedType.typeElement); } return new Model(module, annotatedTypes, parsedTypes, packages); } private List<String> getFactoryComponentNames(TypeElement typeElement) { DefaultFactoryFor factoryAnnotation = getAnnotation(typeElement, DefaultFactoryFor.class); List<String> componentNames = new ArrayList<>(); if (factoryAnnotation != null) { TypeElement defaultFactoryForType = elements().getTypeElement(DefaultFactoryFor.class.getName()); List<TypeMirror> producedTypes = getTypeValues(typeElement, defaultFactoryForType, FACTORY_CLASSES); for (TypeMirror type : producedTypes) { componentNames.add(binaryName(type)); } Collections.addAll(componentNames, factoryAnnotation.names()); } return componentNames; } private String binaryName(TypeElement typeElement) { if (typeElement == null) return null; return elements().getBinaryName(typeElement).toString(); } private TypeMirror getInjectedType(VariableElement injectFieldOrParameter) { DeclaredType declaredType = (DeclaredType) injectFieldOrParameter.asType(); TypeMirror componentType = types().erasure(declaredType); if (componentType.toString().equals(COMPONENT_REF_CLASS)) { List<? extends TypeMirror> typeArguments = declaredType.getTypeArguments(); componentType = types().erasure(typeArguments.get(0)); } return componentType; } private String getComponentName(VariableElement parameter, String componentTypeName) { ComponentName nameAnnotation = getAnnotation(parameter, ComponentName.class); return nameAnnotation != null ? nameAnnotation.value() : componentTypeName; } private boolean isComponentRef(VariableElement injectFieldOrParameter) { String erasedType = types().erasure(injectFieldOrParameter.asType()).toString(); return COMPONENT_REF_CLASS.equals(erasedType); } private String binaryName(TypeMirror type) { return binaryName((TypeElement) types().asElement(type)); } private TypeElement getSuperClass(TypeElement typeElement, Class<? extends Annotation> annotationClass) { TypeElement superElement = (TypeElement) types().asElement(typeElement.getSuperclass()); if (superElement == null || getAnnotation(superElement, annotationClass) != null) return superElement; return getSuperClass(superElement, annotationClass); } } }
30,098
45.16411
129
java
null
infinispan-main/build/component-processor/src/main/java/org/infinispan/component/processor/Model.java
package org.infinispan.component.processor; import java.util.ArrayList; import java.util.List; import java.util.Map; import javax.lang.model.element.TypeElement; import org.infinispan.factories.annotations.InfinispanModule; import org.infinispan.factories.scopes.Scope; import org.infinispan.jmx.annotations.MBean; import org.infinispan.jmx.annotations.ManagedAttribute; import org.infinispan.jmx.annotations.ManagedOperation; /** * Information about annotated classes being processed. * * @author Dan Berindei * @since 10.0 */ public class Model { final Module module; final Map<String, AnnotatedType> annotatedTypes; final Map<String, ParsedType> parsedTypes; final Map<String, Package> packages; Model(Module module, Map<String, AnnotatedType> annotatedTypes, Map<String, ParsedType> parsedTypes, Map<String, Package> packages) { this.module = module; this.annotatedTypes = annotatedTypes; this.parsedTypes = parsedTypes; this.packages = packages; } public static class Module { final InfinispanModule moduleAnnotation; final TypeElement typeElement; final String moduleClassName; final String packageName; final String classPrefix; public Module(InfinispanModule moduleAnnotation, TypeElement typeElement, String packageName, String classPrefix) { this.moduleAnnotation = moduleAnnotation; this.typeElement = typeElement; this.moduleClassName = typeElement.getQualifiedName().toString(); this.packageName = packageName; this.classPrefix = classPrefix; } } static class ParsedType { final TypeElement typeElement; final String qualifiedName; final String packageName; final List<String> code; ParsedType(TypeElement typeElement, String qualifiedName, String packageName, List<String> code) { this.typeElement = typeElement; this.qualifiedName = qualifiedName; this.packageName = packageName; this.code = code; } } public static class AnnotatedType { final TypeElement typeElement; final String qualifiedName; final String binaryName; final String packageName; Component component; MComponent mComponent; AnnotatedType(TypeElement typeElement, String qualifiedName, String binaryName, String packageName) { this.typeElement = typeElement; this.binaryName = binaryName; this.qualifiedName = qualifiedName; this.packageName = packageName; } } public static class Component { final Scope scope; final boolean survivesRestarts; final List<String> factoryComponentNames; final boolean autoInstantiable; final String superBinaryName; final List<InjectField> injectFields = new ArrayList<>(); final List<InjectMethod> injectMethods = new ArrayList<>(); final List<LifecycleMethod> startMethods = new ArrayList<>(); final List<LifecycleMethod> stopMethods = new ArrayList<>(); public Component(Scope scope, boolean survivesRestarts, List<String> factoryComponentNames, boolean autoInstantiable, String superBinaryName) { this.scope = scope; this.survivesRestarts = survivesRestarts; this.superBinaryName = superBinaryName; this.factoryComponentNames = factoryComponentNames; this.autoInstantiable = autoInstantiable; } boolean hasDependenciesOrLifecycle() { return !injectFields.isEmpty() || !injectMethods.isEmpty() || hasLifecycle(); } private boolean hasLifecycle() { return !startMethods.isEmpty() || !stopMethods.isEmpty(); } } static class LifecycleMethod { final String name; final int priority; LifecycleMethod(String name, int priority) { this.name = name; this.priority = priority; } } static class InjectMethod { final String name; final List<InjectField> parameters; InjectMethod(String name, List<InjectField> parameters) { this.name = name; this.parameters = parameters; } } static class InjectField { final String name; final String typeName; final String componentName; final boolean isComponentRef; InjectField(String name, String typeName, String componentName, boolean isComponentRef) { this.name = name; this.typeName = typeName; this.componentName = componentName; this.isComponentRef = isComponentRef; } } static class MComponent { final MBean mbean; final String superBinaryName; final List<MAttribute> attributes = new ArrayList<>(); final List<MOperation> operations = new ArrayList<>(); MComponent(MBean mbean, String superBinaryName) { this.mbean = mbean; this.superBinaryName = superBinaryName; } } static class MAttribute { final String name; final String propertyAccessor; final ManagedAttribute attribute; final boolean useSetter; final String type; final String boxedType; final boolean is; MAttribute(String name, String propertyAccessor, ManagedAttribute attribute, boolean useSetter, String type, String boxedType, boolean is) { this.name = name; this.propertyAccessor = propertyAccessor; this.attribute = attribute; this.useSetter = useSetter; this.type = type; this.boxedType = boxedType; this.is = is; } } static class MOperation { final String name; final ManagedOperation operation; final String returnType; final List<MParameter> parameters; MOperation(String name, ManagedOperation operation, String returnType, List<MParameter> parameters) { this.name = name; this.operation = operation; this.returnType = returnType; this.parameters = parameters; } } static class MParameter { final String name; final String type; final String description; MParameter(String name, String type, String description) { this.name = name; this.type = type; this.description = description; } } static class Package { final String packageName; final List<TypeElement> typeElements = new ArrayList<>(); final List<AnnotatedType> annotatedTypes = new ArrayList<>(); final List<ParsedType> parsedTypes = new ArrayList<>(); Package(String packageName) { this.packageName = packageName; } } }
6,685
29.953704
146
java
null
infinispan-main/build/component-processor/src/main/java/org/infinispan/component/processor/AnnotationTypeValuesExtractor.java
package org.infinispan.component.processor; import java.util.ArrayList; import java.util.List; import java.util.Map; import javax.lang.model.element.AnnotationMirror; import javax.lang.model.element.AnnotationValue; import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.TypeElement; import javax.lang.model.element.VariableElement; import javax.lang.model.type.TypeMirror; import javax.lang.model.util.AbstractAnnotationValueVisitor8; public class AnnotationTypeValuesExtractor extends AbstractAnnotationValueVisitor8<Void, List<TypeMirror>> { public static List<TypeMirror> getTypeValues(TypeElement typeElement, TypeElement annotationType, String valueName) { ArrayList<TypeMirror> list = new ArrayList<>(); AnnotationMirror annotation = getAnnotation(typeElement, annotationType); if (annotation != null) { AnnotationValue annotationValue = getAnnotationValue(annotation, valueName); if (annotationValue != null) { annotationValue.accept(new AnnotationTypeValuesExtractor(), list); return list; } } return list; } private static AnnotationMirror getAnnotation(TypeElement clazz, TypeElement annotationType) { List<? extends AnnotationMirror> annotationMirrors = clazz.getAnnotationMirrors(); for (AnnotationMirror annotationMirror : annotationMirrors) { if (annotationMirror.getAnnotationType().equals(annotationType.asType())) { return annotationMirror; } } return null; } private static AnnotationValue getAnnotationValue(AnnotationMirror annotationMirror, String key) { for (Map.Entry<? extends ExecutableElement, ? extends AnnotationValue> entry : annotationMirror.getElementValues().entrySet()) { if (entry.getKey().getSimpleName().toString().equals(key)) { return entry.getValue(); } } return null; } @Override public Void visitArray(List<? extends AnnotationValue> vals, List<TypeMirror> list) { for (AnnotationValue val : vals) { val.accept(this, list); } return null; } @Override public Void visitType(TypeMirror t, List<TypeMirror> list) { list.add(t); return null; } @Override public Void visitBoolean(boolean b, List<TypeMirror> p) { return null; } @Override public Void visitByte(byte b, List<TypeMirror> p) { return null; } @Override public Void visitChar(char c, List<TypeMirror> p) { return null; } @Override public Void visitDouble(double d, List<TypeMirror> p) { return null; } @Override public Void visitFloat(float f, List<TypeMirror> p) { return null; } @Override public Void visitInt(int i, List<TypeMirror> p) { return null; } @Override public Void visitLong(long i, List<TypeMirror> p) { return null; } @Override public Void visitShort(short s, List<TypeMirror> p) { return null; } @Override public Void visitString(String s, List<TypeMirror> p) { return null; } @Override public Void visitEnumConstant(VariableElement c, List<TypeMirror> p) { return null; } @Override public Void visitAnnotation(AnnotationMirror a, List<TypeMirror> p) { return null; } }
3,352
27.905172
134
java
null
infinispan-main/build/component-processor/src/main/java/org/infinispan/component/processor/Generator.java
package org.infinispan.component.processor; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.IOException; import java.io.PrintWriter; import java.nio.file.NoSuchFileException; import java.time.Instant; import java.util.AbstractMap; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.annotation.processing.Filer; import javax.lang.model.element.TypeElement; import javax.tools.FileObject; import javax.tools.JavaFileObject; import javax.tools.StandardLocation; import org.infinispan.factories.annotations.InfinispanModule; import org.infinispan.factories.scopes.Scopes; import org.infinispan.jmx.annotations.DataType; import org.infinispan.jmx.annotations.MBean; import org.infinispan.jmx.annotations.ManagedAttribute; import org.infinispan.jmx.annotations.ManagedOperation; /** * Generate component accessors. * * @author Dan Berindei * @since 10.0 */ public class Generator { private static final String MODULE_METADATA_BUILDER_SERVICE_NAME = "META-INF/services/org.infinispan.factories.impl.ModuleMetadataBuilder"; private final Model model; private final Filer filer; public Generator(Model model, Filer filer) { this.model = model; this.filer = filer; } public void writePackageClasses() throws IOException { for (Model.Package p : model.packages.values()) { writePackageClass(p); } } private void writePackageClass(Model.Package p) throws IOException { String packageClassName = String.format("%s.%sPackageImpl", p.packageName, model.module.classPrefix); // IntelliJ will delete the generated file before compilation if any of the source elements has changed // We need the old PackageImpl source to parse the accessors of any classes not compiled in this round, // so we don't set any source elements. JavaFileObject packageFile = filer.createSourceFile(packageClassName); try (PrintWriter writer = new PrintWriter(packageFile.openWriter(), false)) { writer.printf("package %s;%n%n", p.packageName); writer.printf("import java.util.Arrays;%n"); writer.printf("import java.util.Collections;%n"); writer.printf("import javax.annotation.processing.Generated;%n"); writer.printf("%n"); writer.printf("import org.infinispan.factories.impl.ComponentAccessor;%n"); writer.printf("import org.infinispan.factories.impl.ModuleMetadataBuilder;%n"); writer.printf("import org.infinispan.factories.impl.MBeanMetadata;%n"); writer.printf("import org.infinispan.factories.impl.MBeanMetadata.AttributeMetadata;%n"); writer.printf("import org.infinispan.factories.impl.MBeanMetadata.OperationMetadata;%n"); writer.printf("import org.infinispan.factories.impl.MBeanMetadata.OperationParameterMetadata;%n"); writer.printf("import org.infinispan.factories.impl.WireContext;%n"); writer.printf("import org.infinispan.lifecycle.ModuleLifecycle;%n"); writer.printf("%n"); writer.printf("/**%n * @api.private %n */%n"); writer.printf("@Generated(value = \"%s\", date = \"%s\")%n", getClass().getName(), Instant.now().toString()); writer.printf("public final class %sPackageImpl {%n", model.module.classPrefix); writer.printf(" public static void registerMetadata(ModuleMetadataBuilder.ModuleBuilder builder) {%n"); for (Model.AnnotatedType c : p.annotatedTypes) { writer.printf("//start %s%n", c.typeElement.getQualifiedName()); if (c.component != null) { writeComponentAccessor(writer, c); writer.printf("%n"); } if (c.mComponent != null) { writeMBeanMetadata(writer, c); writer.printf("%n"); } } for (Model.ParsedType parsedType : p.parsedTypes) { for (String line : parsedType.code) { writer.println(line); } } writer.printf("//end%n"); writer.printf(" }%n"); writer.printf("}%n"); } } private void writeComponentAccessor(PrintWriter writer, Model.AnnotatedType annotatedType) { CharSequence simpleClassName = annotatedType.qualifiedName.substring(annotatedType.packageName.length() + 1); CharSequence binaryName = annotatedType.binaryName; Model.Component c = annotatedType.component; Scopes scope = c.scope.value(); String scopeLiteral = String.valueOf(scope.ordinal()); boolean survivesRestarts = c.survivesRestarts; boolean autoInstantiable = c.autoInstantiable; CharSequence superAccessor = stringLiteral(c.superBinaryName); CharSequence eagerDependencies = listLiteral(getEagerDependencies(c)); CharSequence factoryComponents = listLiteral(c.factoryComponentNames); writer.printf(" builder.registerComponentAccessor(\"%s\",%n", binaryName); writer.printf(" %s,%n", factoryComponents); if (!c.hasDependenciesOrLifecycle() && !autoInstantiable) { // Component doesn't need an anonymous class, eagerDependencies is always empty writer.printf(" new ComponentAccessor<%s>(\"%s\",%n" + " %s, %s, %s,%n" + " %s));%n", simpleClassName, binaryName, scopeLiteral, survivesRestarts, superAccessor, eagerDependencies); return; } writer.printf(" new ComponentAccessor<%s>(\"%s\",%n" + " %s, %s, %s,%n" + " %s) {%n", simpleClassName, binaryName, scopeLiteral, survivesRestarts, superAccessor, eagerDependencies); if (!c.injectFields.isEmpty() || !c.injectMethods.isEmpty()) { writer.printf(" protected void wire(%s instance, WireContext context, boolean start) {%n", simpleClassName); for (Model.InjectField injectField : c.injectFields) { String componentType = injectField.typeName; CharSequence componentName = injectField.componentName; String lazy = injectField.isComponentRef ? "Lazy" : ""; writer.printf(" instance.%s = context.get%s(\"%s\", %s.class, start);%n", injectField.name, lazy, componentName, componentType); } for (Model.InjectMethod injectMethod : c.injectMethods) { writer.printf(" instance.%s(%n", injectMethod.name); List<Model.InjectField> parameters = injectMethod.parameters; for (int i = 0; i < parameters.size(); i++) { Model.InjectField parameter = parameters.get(i); String componentType = parameter.typeName; CharSequence componentName = parameter.componentName; String lazy = parameter.isComponentRef ? "Lazy" : ""; writer.printf(" context.get%s(\"%s\", %s.class, start)%s%n", lazy, componentName, componentType, optionalComma(i, parameters.size())); } writer.printf(" );%n"); } writer.printf(" }%n"); writer.printf("%n"); } if (!c.startMethods.isEmpty()) { writer.printf(" protected void start(%s instance) throws Exception {%n", simpleClassName); writeLifecycleMethodInvocations(writer, c.startMethods); writer.printf(" }%n"); writer.printf("%n"); } if (!c.stopMethods.isEmpty()) { writer.printf(" protected void stop(%s instance) throws Exception {%n", simpleClassName); writeLifecycleMethodInvocations(writer, c.stopMethods); writer.printf(" }%n"); writer.printf("%n"); } if (autoInstantiable) { writer.printf(" protected %s newInstance() {%n", simpleClassName); writer.printf(" return new %s();%n", simpleClassName); writer.printf(" }%n"); writer.printf("%n"); } writer.printf(" });%n"); } private void writeLifecycleMethodInvocations(PrintWriter writer, List<Model.LifecycleMethod> methods) { for (Model.LifecycleMethod method : sortByPriority(methods)) { writer.printf(" instance.%s();%n", method.name); } } private List<Model.LifecycleMethod> sortByPriority(List<Model.LifecycleMethod> methods) { List<Model.LifecycleMethod> result = new ArrayList<>(methods); result.sort(Comparator.comparing(method -> method.priority)); return result; } private List<CharSequence> getEagerDependencies(Model.Component c) { List<CharSequence> eagerDependencies = new ArrayList<>(); for (Model.InjectField injectField : c.injectFields) { if (!injectField.isComponentRef) { eagerDependencies.add(injectField.componentName); } } for (Model.InjectMethod injectMethod : c.injectMethods) { for (Model.InjectField parameter : injectMethod.parameters) { if (!parameter.isComponentRef) { eagerDependencies.add(parameter.componentName); } } } return eagerDependencies; } private void writeMBeanMetadata(PrintWriter writer, Model.AnnotatedType c) { CharSequence binaryName = c.binaryName; Model.MComponent m = c.mComponent; MBean mbean = m.mbean; CharSequence superMBeanName = stringLiteral(m.superBinaryName); List<Model.MAttribute> attributes = m.attributes; List<Model.MOperation> operations = m.operations; writer.printf(" builder.registerMBeanMetadata(\"%s\",%n", binaryName); int count = attributes.size() + operations.size(); writer.printf(" MBeanMetadata.of(\"%s\", \"%s\", %s%s%n", mbean.objectName(), mbean.description(), superMBeanName, optionalComma(-1, count)); int i = 0; for (Model.MAttribute attribute : attributes) { writeManagedAttribute(writer, attribute.name, attribute.attribute, attribute.useSetter, attribute.type, attribute.is, makeGetterFunction(c, attribute), makeSetterFunction(c, attribute), optionalComma(i++, count)); } for (Model.MOperation method : operations) { ManagedOperation operation = method.operation; // OperationMetadata(String methodName, String operationName, String description, String returnType, // OperationParameterMetadata... methodParameters) List<Model.MParameter> parameters = method.parameters; writer.printf(" new OperationMetadata(\"%s\", \"%s\", \"%s\", \"%s\"%s%n", method.name, operation.name(), operation.description(), method.returnType, optionalComma(-1, parameters.size())); for (int j = 0; j < parameters.size(); j++) { Model.MParameter parameter = parameters.get(j); // OperationParameterMetadata(String name, String type, String description) writer.printf(" new OperationParameterMetadata(\"%s\", \"%s\", \"%s\")%s%n", parameter.name, parameter.type, parameter.description, optionalComma(j, parameters.size())); } writer.printf(" )%s%n", optionalComma(i++, count)); } writer.printf(" ));%n"); } private String makeGetterFunction(Model.AnnotatedType clazz, Model.MAttribute attribute) { // provide accessor function only for a select list of types that are interesting for metrics if (attribute.attribute.dataType() == DataType.MEASUREMENT && ( attribute.boxedType.equals("java.lang.Integer") || attribute.boxedType.equals("java.lang.Long") || attribute.boxedType.equals("java.lang.Short") || attribute.boxedType.equals("java.lang.Byte") || attribute.boxedType.equals("java.lang.Float") || attribute.boxedType.equals("java.lang.Double") || attribute.boxedType.equals("java.math.BigDecimal") || attribute.boxedType.equals("java.math.BigInteger"))) { return "(java.util.function.Function<" + clazz.qualifiedName + ", ?>) " + (attribute.useSetter ? clazz.qualifiedName + "::" : "_x -> _x.") + attribute.propertyAccessor; } return "null"; } private String makeSetterFunction(Model.AnnotatedType clazz, Model.MAttribute attribute) { // no need for setter unless it is a histogram or timer if (attribute.attribute.dataType() == DataType.HISTOGRAM || attribute.attribute.dataType() == DataType.TIMER) { return "(" + clazz.qualifiedName + " _x, Object _y) -> _x." + attribute.propertyAccessor + (attribute.useSetter ? "((" + attribute.boxedType + ") _y)" : " = (" + attribute.boxedType + ") _y"); } return "null"; } private void writeManagedAttribute(PrintWriter writer, CharSequence name, ManagedAttribute attribute, boolean useSetter, String type, boolean is, String getterFunction, String setterFunction, String comma) { // AttributeMetadata(String name, String description, boolean writable, boolean useSetter, String type, boolean is, Function<?, ?> getterFunction, BiConsumer<?, ?> setterFunction) writer.printf(" new AttributeMetadata(\"%s\", \"%s\", %b, %b, \"%s\", %s, %s, %s)%s%n", name, attribute.description(), attribute.writable(), useSetter, type, is, getterFunction, setterFunction, comma); } public void writeModuleClass(TypeElement[] sourceElements) throws IOException { InfinispanModule moduleAnnotation = model.module.moduleAnnotation; Model.Module module = model.module; String moduleClassName = String.format("%s.%sModuleImpl", module.packageName, module.classPrefix); JavaFileObject moduleFile = filer.createSourceFile(moduleClassName, sourceElements); try (PrintWriter writer = new PrintWriter(moduleFile.openWriter(), false)) { writer.printf("package %s;%n%n", module.packageName); writer.printf("import java.util.Arrays;%n"); writer.printf("import java.util.Collection;%n"); writer.printf("import java.util.Collections;%n"); writer.printf("import javax.annotation.processing.Generated;%n"); writer.printf("%n"); writer.printf("import org.infinispan.factories.impl.ModuleMetadataBuilder;%n"); writer.printf("import org.infinispan.lifecycle.ModuleLifecycle;%n"); writer.printf("import org.infinispan.manager.ModuleRepository;%n"); writer.printf("%n"); writer.printf("/**%n * @api.private %n */%n"); writer.printf("@Generated(value = \"%s\", date = \"%s\")%n", getClass().getName(), Instant.now().toString()); writer.printf("public final class %sModuleImpl implements ModuleMetadataBuilder {%n", module.classPrefix); writer.printf("//module %s%n", module.moduleClassName); writer.printf(" public String getModuleName() {%n"); writer.printf(" return \"%s\";%n", moduleAnnotation.name()); writer.printf(" }%n"); writer.printf("%n"); writer.printf(" public Collection<String> getRequiredDependencies() {%n"); writer.printf(" return %s;%n", listLiteral(Arrays.asList(moduleAnnotation.requiredModules()))); writer.printf(" }%n"); writer.printf("%n"); writer.printf(" public Collection<String> getOptionalDependencies() {%n"); writer.printf(" return %s;%n", listLiteral(Arrays.asList(moduleAnnotation.optionalModules()))); writer.printf(" }%n"); writer.printf("%n"); writer.printf(" public ModuleLifecycle newModuleLifecycle() {%n"); writer.printf(" return new %s();%n", module.moduleClassName); writer.printf(" }%n"); writer.printf("%n"); writer.printf(" public void registerMetadata(ModuleBuilder builder) {%n"); for (String packageName : model.packages.keySet()) { writer.printf("//package %s%n", packageName); writer.printf(" %s.%sPackageImpl.registerMetadata(builder);%n", packageName, module.classPrefix); } writer.printf(" }%n"); writer.printf("}%n"); } } public void writeServiceFile(TypeElement[] sourceElements) throws IOException { FileObject serviceFile = filer.createResource(StandardLocation.CLASS_OUTPUT, "", MODULE_METADATA_BUILDER_SERVICE_NAME, sourceElements); try (PrintWriter writer = new PrintWriter(serviceFile.openWriter(), false)) { writer.printf("%s.%sModuleImpl", model.module.packageName, model.module.classPrefix); } } public static String readServiceFile(Filer filer) throws IOException { try { FileObject serviceFile = filer.getResource(StandardLocation.CLASS_OUTPUT, "", MODULE_METADATA_BUILDER_SERVICE_NAME); try (BufferedReader reader = new BufferedReader(serviceFile.openReader(false))) { return reader.readLine(); } } catch (FileNotFoundException | NoSuchFileException e) { return null; } } public static Map.Entry<String, Set<String>> readModuleClass(Filer filer, String moduleImplementationName) throws IOException { String moduleImplPath = String.format("%s.java", moduleImplementationName.replace(".", "/")); try { FileObject sourceFile = filer.getResource(StandardLocation.SOURCE_OUTPUT, "", moduleImplPath); try (BufferedReader reader = new BufferedReader(sourceFile.openReader(false))) { String moduleClass = null; Set<String> packages = new HashSet<>(); String line; while ((line = reader.readLine()) != null) { Matcher matcher = Pattern.compile("//(module|package) (.*)").matcher(line); if (matcher.matches()) { if (matcher.group(1).equals("module")) { moduleClass = matcher.group(2); } else { // package packages.add(matcher.group(2)); } } } return new AbstractMap.SimpleEntry<>(moduleClass, packages); } } catch (FileNotFoundException | NoSuchFileException e) { // Module class does not exist, ignore it return null; } } public static Map<String, List<String>> readPackageClass(Filer filer, String packageName, CharSequence classPrefix) throws IOException { String packageImplPath = String.format("%s/%sPackageImpl.java", packageName.replace(".", "/"), classPrefix); try { FileObject sourceFile = filer.getResource(StandardLocation.SOURCE_OUTPUT, "", packageImplPath); try (BufferedReader reader = new BufferedReader(sourceFile.openReader(false))) { Map<String, List<String>> components = new HashMap<>(); String currentComponent = null; List<String> currentSource = null; String line; while ((line = reader.readLine()) != null) { Matcher matcher = Pattern.compile("//(start |end)(.*)").matcher(line); if (matcher.matches()) { if (matcher.group(1).equals("start ")) { if (currentComponent != null) { components.put(currentComponent, currentSource); } currentComponent = matcher.group(2); currentSource = new ArrayList<>(); currentSource.add(line); } else { // end components.put(currentComponent, currentSource); currentComponent = null; currentSource = null; } } else if (currentComponent != null) { currentSource.add(line); } } return components; } } catch (FileNotFoundException | NoSuchFileException e) { // Module class does not exist, ignore it return null; } } private CharSequence stringLiteral(String value) { return value == null ? null : "\"" + value + '"'; } private CharSequence listLiteral(List<? extends CharSequence> list) { if (list == null || list.isEmpty()) return "Collections.emptyList()"; StringBuilder sb = new StringBuilder("Arrays.asList("); boolean first = true; for (CharSequence componentName : list) { if (first) { first = false; } else { sb.append(", "); } sb.append('"').append(componentName).append('"'); } sb.append(')'); return sb; } private String optionalComma(int index, int size) { return index + 1 < size ? "," : ""; } }
21,467
46.390728
185
java
null
infinispan-main/build/component-processor/src/main/java/org/infinispan/component/processor/external/JGroupsComponentProcessor.java
package org.infinispan.component.processor.external; import java.io.IOException; import java.io.PrintWriter; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.time.Instant; import java.util.Set; import java.util.concurrent.atomic.AtomicBoolean; import javax.annotation.processing.AbstractProcessor; import javax.annotation.processing.Processor; import javax.annotation.processing.RoundEnvironment; import javax.annotation.processing.SupportedAnnotationTypes; import javax.annotation.processing.SupportedSourceVersion; import javax.lang.model.SourceVersion; import javax.lang.model.element.Element; import javax.lang.model.element.TypeElement; import javax.lang.model.type.DeclaredType; import org.infinispan.external.JGroupsProtocolComponent; import org.jgroups.annotations.ManagedAttribute; import org.jgroups.conf.ClassConfigurator; import org.jgroups.protocols.MsgStats; import org.jgroups.protocols.RED; import org.jgroups.protocols.TP; import org.jgroups.stack.Protocol; import org.jgroups.util.ThreadPool; import org.kohsuke.MetaInfServices; /** * @since 14.0 **/ @SupportedSourceVersion(SourceVersion.RELEASE_11) @SupportedAnnotationTypes("org.infinispan.external.JGroupsProtocolComponent") @MetaInfServices(Processor.class) public class JGroupsComponentProcessor extends AbstractProcessor { @Override public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) { for (TypeElement annotation : annotations) { for (Element element : roundEnv.getElementsAnnotatedWith(annotation)) { JGroupsProtocolComponent component = element.getAnnotation(JGroupsProtocolComponent.class); DeclaredType typeMirror = (DeclaredType) element.asType(); TypeElement type = (TypeElement) typeMirror.asElement(); String fqcn = type.getQualifiedName().toString(); int lastDot = fqcn.lastIndexOf('.'); String packageName = fqcn.substring(0, lastDot); try (PrintWriter w = new PrintWriter(processingEnv.getFiler().createSourceFile(packageName + '.' + component.value()).openWriter())) { generate(w, packageName, component.value()); } catch (IOException e) { throw new RuntimeException(e); } } } return true; } public void generate(PrintWriter w, String packageName, String className) throws IOException { w.printf("package %s;%n", packageName); w.println("import java.util.ArrayList;"); w.println("import java.util.Collection;"); w.println("import java.util.HashMap;"); w.println("import java.util.List;"); w.println("import java.util.Map;"); w.println("import java.util.function.Function;"); w.println("import javax.annotation.processing.Generated;"); w.println("import static org.infinispan.factories.impl.MBeanMetadata.AttributeMetadata;"); w.println("import org.jgroups.stack.Protocol;"); w.println(); w.printf("@Generated(value = \"%s\", date = \"%s\")%n", getClass().getName(), Instant.now().toString()); w.printf("public class %s {%n", className); w.println(" public static final Map<Class<? extends Protocol>, Collection<AttributeMetadata>> PROTOCOL_METADATA = new HashMap<>();"); w.printf(" private %s() {}%n", className); w.println(" static {"); w.println(" List<AttributeMetadata> attributes;"); for (short id = 0; id < 256; id++) { Class<?> protocol = ClassConfigurator.getProtocol(id); addProtocol(protocol, w); } // RED protocol does not have an ID // Reason: protocol that does not send headers around does not need an ID. // Add it manually if an ID is not found. if (ClassConfigurator.getProtocolId(RED.class) == 0) { addProtocol(RED.class, w); } w.println(" }"); w.println("}"); w.println(); w.flush(); w.close(); } private static void addProtocol(Class<?> protocol, PrintWriter w) { if (protocol == null || !Protocol.class.isAssignableFrom(protocol) || Modifier.isAbstract(protocol.getModifiers())) { return; } AtomicBoolean hasAttributes = new AtomicBoolean(false); for (Method method : protocol.getMethods()) { ManagedAttribute annotation = method.getAnnotation(ManagedAttribute.class); if (annotation != null && !Modifier.isStatic(method.getModifiers()) && method.getParameterCount() == 0 && isNumber(method.getReturnType())) { if (hasAttributes.compareAndSet(false, true)) { w.println(" attributes = new ArrayList<>();"); } w.printf(" attributes.add(new AttributeMetadata(\"%s\", \"%s\", false, false, \"%s\",\n" + " false, (Function<%s, ?>) %s::%s, null));%n", method.getName(), annotation.description().replace('"', '\''), method.getReturnType().getName(), protocol.getName(), protocol.getName(), method.getName()); } } if (TP.class.isAssignableFrom(protocol)) { addTPComponent("getThreadPool", protocol, ThreadPool.class, w, hasAttributes); addTPComponent("getMessageStats", protocol, MsgStats.class, w, hasAttributes); } if (hasAttributes.get()) { // only put the protocol in PROTOCOL_METADATA if we have attributes available w.printf(" PROTOCOL_METADATA.put(%s.class, attributes);%n", protocol.getName()); } } private static boolean isNumber(Class<?> type) { return short.class == type || byte.class == type || long.class == type || int.class == type || float.class == type || double.class == type || Number.class.isAssignableFrom(type); } private static void addTPComponent(String getterMethodName, Class<?> protocol, Class<?> component, PrintWriter w, AtomicBoolean hasAttributes) { for (Method method : component.getMethods()) { ManagedAttribute annotation = method.getAnnotation(ManagedAttribute.class); if (annotation != null && !Modifier.isStatic(method.getModifiers()) && method.getParameterCount() == 0 && isNumber(method.getReturnType())) { if (hasAttributes.compareAndSet(false, true)) { w.println(" attributes = new ArrayList<>();"); } w.printf(" attributes.add(new AttributeMetadata(\"%s\", \"%s\", false, false, \"%s\",\n" + " false, (Function<%s, ?>) p -> p.%s().%s(), null));%n", method.getName(), annotation.description().replace('"', '\''), method.getReturnType().getName(), protocol.getName(), getterMethodName, method.getName()); } } } }
6,804
46.587413
184
java
null
infinispan-main/build/component-annotations/src/main/java/org/infinispan/external/JGroupsProtocolComponent.java
package org.infinispan.external; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * @since 14.0 **/ @Target({ ElementType.TYPE }) @Retention(RetentionPolicy.SOURCE) public @interface JGroupsProtocolComponent { String value(); }
351
21
44
java
null
infinispan-main/build/component-annotations/src/main/java/org/infinispan/jmx/annotations/package-info.java
/** * JMX 2.0-like annotations, with no dependencies on JMX 2.0. These annotations are for internal use, to allow * Infinispan components to expose attributes and operations via JMX. * * @api.private */ package org.infinispan.jmx.annotations;
248
30.125
110
java
null
infinispan-main/build/component-annotations/src/main/java/org/infinispan/jmx/annotations/MeasurementType.java
package org.infinispan.jmx.annotations; /** * Indicates whether the measured values consistently increase or decrease over time or are dynamic and can "randomly" * be higher or lower than previous values. */ public enum MeasurementType { DYNAMIC, TRENDSUP, TRENDSDOWN; @Override public String toString() { return name().toLowerCase(); } }
363
21.75
118
java
null
infinispan-main/build/component-annotations/src/main/java/org/infinispan/jmx/annotations/MBean.java
package org.infinispan.jmx.annotations; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Inherited; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Classes annotated with this will be exposed as MBeans. If you are looking for more fined grained way of exposing JMX * attributes/operations, take a look at {@link ManagedAttribute} and {@link ManagedOperation} * * @author Mircea.Markus@jboss.com * @since 4.0 */ @Retention(RetentionPolicy.CLASS) @Target(ElementType.TYPE) @Inherited @Documented public @interface MBean { /** * This name becomes the value of the "component" key of the final ObjectName of the MBean. If missing, it defaults * to the name of the component in the component registry. */ String objectName() default ""; String description() default ""; }
936
29.225806
119
java
null
infinispan-main/build/component-annotations/src/main/java/org/infinispan/jmx/annotations/Parameter.java
package org.infinispan.jmx.annotations; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Target(ElementType.PARAMETER) @Retention(RetentionPolicy.CLASS) @Documented public @interface Parameter { /** * Operation parameter name. */ String name() default ""; /** * Operation parameter description. */ String description() default ""; }
518
20.625
44
java
null
infinispan-main/build/component-annotations/src/main/java/org/infinispan/jmx/annotations/ManagedAttribute.java
package org.infinispan.jmx.annotations; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Indicates that a method in a MBean class defines a MBean attribute. This annotation can be applied to a non-static * non-private getter or setter method of a public class that is itself annotated with an @MBean annotation, or inherits * such an annotation from a superclass. * * @author (various) * @author Galder Zamarreño * @since 4.0 */ @Retention(RetentionPolicy.CLASS) @Target(ElementType.METHOD) @Documented public @interface ManagedAttribute { /** * The name of the JMX attribute. If left empty it defaults to the name of the Java property. */ String name() default ""; /** * The human-readable description of the attribute. Probably more detailed than {@link #displayName}. */ String description() default ""; /** * Indicates if the attribute is writable or just read-only (default). If this flag is true a setter method must * exist. */ boolean writable() default false; /** * A brief and user friendly name. */ String displayName() default ""; DataType dataType() default DataType.MEASUREMENT; MeasurementType measurementType() default MeasurementType.DYNAMIC; Units units() default Units.NONE; }
1,440
27.82
120
java
null
infinispan-main/build/component-annotations/src/main/java/org/infinispan/jmx/annotations/DataType.java
package org.infinispan.jmx.annotations; /** * The type of data that is to be collected. This type also effects the way the data is exported for management and for * metrics. */ public enum DataType { /** * A value of the running system that changes rarely or never. This is exposed as a JMX manageable attribute, but * never as a metric. */ TRAIT, /** * Numeric data that normally changes over time and it interesting to be exposed as a metric. If this is applied to a * non-numeric property it will not be exported as a metric but will still be exported as a JMX manageable * attribute. */ MEASUREMENT, /** * Similar to {@link #MEASUREMENT}, but instead of instantaneous values this provides a histogram of past values. */ HISTOGRAM, /** * Similar to {@link #HISTOGRAM} but the measured values are time durations. */ TIMER; @Override public String toString() { return name().toLowerCase(); } }
987
25.702703
120
java
null
infinispan-main/build/component-annotations/src/main/java/org/infinispan/jmx/annotations/Units.java
package org.infinispan.jmx.annotations; import java.util.EnumSet; public enum Units { NONE, SECONDS, MILLISECONDS, MICROSECONDS, NANOSECONDS, PER_SECOND, PERCENTAGE, BITS, BYTES, KILO_BYTES, MEGA_BYTES; public static final EnumSet<Units> TIME_UNITS = EnumSet.of(SECONDS, MILLISECONDS, MICROSECONDS, NANOSECONDS); @Override public String toString() { return name().toLowerCase(); } }
449
11.5
112
java
null
infinispan-main/build/component-annotations/src/main/java/org/infinispan/jmx/annotations/ManagedOperation.java
package org.infinispan.jmx.annotations; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Indicates that a method in an MBean class defines an MBean operation. @ManagedOperation annotation can be applied to * a public method of a public class that is itself optionally annotated with an @MBean annotation, or inherits such an * annotation from a superclass. * * @author (various) * @since 4.0 */ @Retention(RetentionPolicy.CLASS) @Target(ElementType.METHOD) @Documented public @interface ManagedOperation { /** * The name of the JMX operation. */ String name() default ""; /** * The human-readable description of the operation. */ String description() default ""; /** * Similar with {@link #description} but shorter. */ String displayName() default ""; }
966
25.135135
119
java
null
infinispan-main/build/component-annotations/src/main/java/org/infinispan/factories/scopes/package-info.java
/** * Scopes of components within the lifespan of a cache manager and its caches, and related * utilities. */ package org.infinispan.factories.scopes;
154
24.833333
90
java
null
infinispan-main/build/component-annotations/src/main/java/org/infinispan/factories/scopes/Scopes.java
package org.infinispan.factories.scopes; /** * The different scopes that can be declared for a component. * * <p>Must be kept in sync with {@code org.infinispan.factories.impl.Scopes}</p> * * @author Manik Surtani * @see Scope * @since 4.0 */ public enum Scopes { /** * A single instance of the component is shared by all the caches. */ GLOBAL, /** * Every cache uses a separate instance of the component. */ NAMED_CACHE, /** * The component is not cached between requests, but a subclass may be either {@code GLOBAL} or {@code NAMED_CACHE}. */ NONE }
605
20.642857
119
java
null
infinispan-main/build/component-annotations/src/main/java/org/infinispan/factories/scopes/Scope.java
package org.infinispan.factories.scopes; import java.lang.annotation.Inherited; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; /** * Defines the scope of a component in a cache system. If not specified, components default to the {@link * Scopes#NAMED_CACHE} scope. * * <p>Note: The {@code Scope} annotation is inherited so that the annotation processor can find subclasses. * Although annotating interfaces is allowed, it is preferable to annotate only classes.</p> * * @author Manik Surtani * @see Scopes * @since 4.0 */ @Retention(RetentionPolicy.CLASS) @Inherited public @interface Scope { Scopes value(); }
664
27.913043
107
java
null
infinispan-main/build/component-annotations/src/main/java/org/infinispan/factories/annotations/package-info.java
/** * Internal annotations to control the lifecycle of cache components. */ package org.infinispan.factories.annotations;
124
24
69
java
null
infinispan-main/build/component-annotations/src/main/java/org/infinispan/factories/annotations/DefaultFactoryFor.java
package org.infinispan.factories.annotations; import static java.lang.annotation.ElementType.TYPE; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * An annotation that is used internally, for defining a DEFAULT factory to be used when constructing components. This * annotation allows you to define which components can be constructed by the annotated factory. * * @author Manik Surtani (<a href="mailto:manik@jboss.org">manik@jboss.org</a>) * @since 4.0 */ @Target(TYPE) @Retention(RetentionPolicy.CLASS) public @interface DefaultFactoryFor { /** * Components that may be constructed by a factory annotated with this annotation. * * @return classes that can be constructed by this factory */ Class<?>[] classes() default {}; String[] names() default {}; }
869
30.071429
119
java
null
infinispan-main/build/component-annotations/src/main/java/org/infinispan/factories/annotations/ComponentName.java
package org.infinispan.factories.annotations; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Mechanism for specifying the name of components to retrieve * * @author Manik Surtani * @since 4.0 */ @Target({ ElementType.PARAMETER, ElementType.FIELD }) @Retention(RetentionPolicy.CLASS) public @interface ComponentName { String value(); }
465
23.526316
62
java
null
infinispan-main/build/component-annotations/src/main/java/org/infinispan/factories/annotations/InfinispanModule.java
package org.infinispan.factories.annotations; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Mechanism for specifying the name and dependencies of Infinispan modules. * <p> * There must be exactly one {@code InfinispanModule} annotation in each module, placed on an implementation of the * {@code org.infinispan.lifecycle.ModuleLifecycle} interface. * * <p>It would have been nice to put the annotation on a package, * but package-info.java source files are excluded from compilation * because of MCOMPILER-205.</p> * * @author Dan Berindei * @since 10.0 */ @Target(ElementType.TYPE) @Retention(RetentionPolicy.CLASS) public @interface InfinispanModule { /** * The unique name of the module. */ String name(); /** * The set of required dependencies (module names). */ String[] requiredModules() default {}; /** * The set of optional dependencies (module names). */ String[] optionalModules() default {}; }
1,085
26.15
115
java
null
infinispan-main/build/component-annotations/src/main/java/org/infinispan/factories/annotations/SurvivesRestarts.java
package org.infinispan.factories.annotations; import java.lang.annotation.ElementType; import java.lang.annotation.Inherited; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * This annotation is used for components that will be registered in the {@link org.infinispan.factories.ComponentRegistry}, * that are meant to be retained in the component registry even after the component registry is stopped. Components * annotated as such would not have to be recreated and rewired between stopping and starting a component registry. * <br /> * As a rule of thumb though, use of this annotation on components should be avoided, since resilient components are * retained even after a component registry is stopped and consume resources. Only components necessary for and critical * to bootstrapping and restarting the component registry should be annotated as such. * * @author Manik Surtani (<a href="mailto:manik@jboss.org">manik@jboss.org</a>) * @since 4.0 */ @Retention(RetentionPolicy.CLASS) @Target(ElementType.TYPE) @Inherited public @interface SurvivesRestarts { }
1,157
43.538462
124
java
null
infinispan-main/build/component-annotations/src/main/java/org/infinispan/factories/annotations/Inject.java
package org.infinispan.factories.annotations; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Used to annotate a method or field as an injection point. * * <p>The method or field must not be {@code private}, usually it's best to have it package-private.</p> * * <p>Usage example:</p> * <pre> * public class MyClass * { * private TransactionManager tm; * private BuddyManager bm; * private Notifier n; * * &amp;Inject * public void setTransactionManager(TransactionManager tm) * { * this.tm = tm; * } * * &amp;Inject * public void injectMoreStuff(BuddyManager bm, Notifier n) * { * this.bm = bm; * this.n = n; * } * } * </pre> * and an instance of this class can be constructed and wired using * <pre> * MyClass myClass = componentRegistry.getComponent(MyClass.class); * </pre> * * Methods annotated with this Inject annotation should *only* set class fields. They should do nothing else. * If you need to do some work to prepare the component for use, do it in a {@link Start} method since this is only * called once when a component starts. * * @author Manik Surtani * @since 4.0 */ // ensure this annotation is available at runtime. @Retention(RetentionPolicy.CLASS) @Target({ ElementType.METHOD, ElementType.FIELD }) public @interface Inject { }
1,567
29.153846
115
java
null
infinispan-main/build/component-annotations/src/main/java/org/infinispan/factories/annotations/Stop.java
package org.infinispan.factories.annotations; import static java.lang.annotation.ElementType.METHOD; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Method level annotation that indicates a (no-param) method to be called on a component registered in the * component registry when the registry stops. * <p/> * * @author Manik Surtani (<a href="mailto:manik@jboss.org">manik@jboss.org</a>) * @since 4.0 */ @Target(METHOD) @Retention(RetentionPolicy.CLASS) public @interface Stop { /** * Optional parameter which defines the order in which this method will be called when a component has more than * one method annotated with {@link Stop}. Defaults to 10. * * <p>A component's stop methods usually run only when the component registry is stopped, * and the component stop order is the reverse of their start order.</p> * <p>Stop methods defined (and annotated) in superclasses will run after the stop methods defined in derived classes.</p> * * <p>Note: Prior to 9.4, priority parameter allowed the stop methods of one component to run before or after * the stop methods of another component. * Since 9.4, the priority parameter is ignored unless the component has multiple stop methods.</p> * * @since 4.0 * @deprecated Since 10.0, will be removed in a future version. */ @Deprecated int priority() default 10; }
1,465
37.578947
125
java
null
infinispan-main/build/component-annotations/src/main/java/org/infinispan/factories/annotations/Start.java
package org.infinispan.factories.annotations; import static java.lang.annotation.ElementType.METHOD; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Method level annotation that indicates a (no-param) method to be called on a component registered in the * component registry when the registry starts. * <p/> * * @author Manik Surtani (<a href="mailto:manik@jboss.org">manik@jboss.org</a>) * @since 4.0 */ @Target(METHOD) @Retention(RetentionPolicy.CLASS) public @interface Start { /** * Optional parameter which defines the order in which this method will be called when a component has more than * one method annotated with {@link Start}. Defaults to 10. * * <p>A component's start methods will always run after the start methods of its eager dependencies.</p> * <p>Start methods defined (and annotated) in superclasses will run before the start methods defined in derived classes.</p> * * <p>Note: Prior to 9.4, priority parameter allowed the start methods of one component to run before or after * the start methods of another component. * Since 9.4, the priority parameter is ignored unless the component has multiple start methods.</p> * * @since 4.0 * @deprecated Since 10.0, will be removed in a future version. */ @Deprecated int priority() default 10; }
1,413
37.216216
128
java
null
infinispan-main/build/logging-annotations/src/main/java/org/infinispan/logging/annotations/Description.java
package org.infinispan.logging.annotations; import static java.lang.annotation.ElementType.METHOD; import static java.lang.annotation.RetentionPolicy.CLASS; import java.lang.annotation.Retention; import java.lang.annotation.Target; /** * Description. * * @author Durgesh Anaokar * @since 13.0 */ @Retention(CLASS) @Target(METHOD) public @interface Description { /** * * Return the Description for the log message. * * @return String */ String value(); }
494
16.068966
57
java
null
infinispan-main/build/checkstyle/src/main/java/org/infinispan/checkstyle/checks/ForbiddenMethodCheck.java
package org.infinispan.checkstyle.checks; import java.util.regex.Pattern; import com.puppycrawl.tools.checkstyle.api.AbstractCheck; import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.TokenTypes; /** * Checks that certain methods are not invoked * * The methodPattern argument is a regular expression, invocations of method names matching the pattern are forbidden. * Only method names are checked, the defining class doesn't matter. * * If the optional argumentCount argument is set, only overloads with that number of parameters are forbidden. * Forbidding only overloads with 0 arguments is not supported at this time. * * @author wburns * @since 10.0 */ public class ForbiddenMethodCheck extends AbstractCheck { private Pattern methodPattern = null; private int argumentCount = -1; @Override public int[] getDefaultTokens() { return new int[] { TokenTypes.METHOD_CALL }; } @Override public int[] getAcceptableTokens() { return getDefaultTokens(); } @Override public int[] getRequiredTokens() { return getDefaultTokens(); } @Override public void init() { if (methodPattern == null) { throw new IllegalStateException("The methodPattern attribute is required!"); } } public void setMethodPattern(String methodPatternString) { methodPattern = Pattern.compile(methodPatternString); } public void setArgumentCount(String argumentCountString) { argumentCount = Integer.parseInt(argumentCountString); if (argumentCount <= 0) { throw new IllegalArgumentException("Argument count " + argumentCount + " was 0 or negative"); } } @Override public void visitToken(DetailAST ast) { boolean nameMatches = false; for (DetailAST child = ast.getFirstChild(); child != null; child = child.getNextSibling()) { int childType = child.getType(); switch (childType) { // variable.method invocation case TokenTypes.DOT: DetailAST methodAST = child.getLastChild(); if (methodAST.getType() == TokenTypes.IDENT) { String methodName = methodAST.getText(); if (methodPattern.matcher(methodName).matches()) { if (argumentCount > 0) { nameMatches = true; } else { log(ast, "[not required for tests] Forbidden method invocation found that matches {0}", methodPattern.pattern()); } } } break; case TokenTypes.ELIST: if (nameMatches) { int count = child.getChildCount(TokenTypes.COMMA) + 1; if (argumentCount == count) { log(ast, "[not required for tests] Forbidden method invocation found that matches {0} with {1} number of arguments", methodPattern.pattern(), argumentCount); } } break; } } } }
3,121
32.934783
137
java
null
infinispan-main/build/checkstyle/src/main/java/org/infinispan/checkstyle/checks/regexp/IllegalImport.java
package org.infinispan.checkstyle.checks.regexp; import java.util.Arrays; import java.util.HashSet; import com.puppycrawl.tools.checkstyle.api.AbstractCheck; import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.FullIdent; import com.puppycrawl.tools.checkstyle.api.TokenTypes; /** * A simple CheckStyle checker to verify specific import statements are not being used. * * @author Sanne Grinovero */ public class IllegalImport extends AbstractCheck { private final HashSet<String> notAllowedImports = new HashSet<>(); private String message = ""; /** * Set the list of illegal import statements. * * @param importStatements * array of illegal packages */ public void setIllegalClassnames(String[] importStatements) { notAllowedImports.addAll(Arrays.asList(importStatements)); } public void setMessage(String message) { if (message != null) { this.message = message; } } @Override public int[] getDefaultTokens() { return new int[] { TokenTypes.IMPORT, TokenTypes.STATIC_IMPORT }; } @Override public int[] getAcceptableTokens() { return getDefaultTokens(); } @Override public int[] getRequiredTokens() { return getDefaultTokens(); } @Override public void visitToken(DetailAST aAST) { final FullIdent imp; if (aAST.getType() == TokenTypes.IMPORT) { imp = FullIdent.createFullIdentBelow(aAST); } else { // handle case of static imports of method names imp = FullIdent.createFullIdent(aAST.getFirstChild().getNextSibling()); } final String text = imp.getText(); if (isIllegalImport(text)) { final String message = buildError(text); log(aAST.getLineNo(), aAST.getColumnNo(), message, text); } } private String buildError(String importStatement) { return "Import statement violating a checkstyle rule: " + importStatement + ". " + message; } private boolean isIllegalImport(String importString) { return notAllowedImports.contains(importString); } }
2,147
26.896104
97
java
null
infinispan-main/build/checkstyle/src/main/java/org/infinispan/checkstyle/checks/interceptors/InterceptorDefinesAllReadWritesCheck.java
package org.infinispan.checkstyle.checks.interceptors; import java.util.Arrays; import java.util.HashSet; import java.util.Set; public class InterceptorDefinesAllReadWritesCheck extends AbstractInterceptorCheck { // WriteOnly* commands are not included because these don't ever read the previous value, // and therefore there are situations (like loading of data from cache store) where it does not make // sense to define them. private static final Set<String> WRITE_METHODS = new HashSet<>(Arrays.asList( "visitPutKeyValueCommand", "visitIracPutKeyValueCommand", "visitRemoveCommand", "visitReplaceCommand", "visitPutMapCommand", // PutMapCommand should load previous values unless IGNORE_RETURN_VALUE flag is set. "visitReadWriteKeyValueCommand", "visitReadWriteKeyCommand", "visitReadWriteManyCommand", "visitReadWriteManyEntriesCommand" )); @Override protected Set<String> methods() { return WRITE_METHODS; } }
1,030
35.821429
115
java
null
infinispan-main/build/checkstyle/src/main/java/org/infinispan/checkstyle/checks/interceptors/InterceptorDefinesAllReadsCheck.java
package org.infinispan.checkstyle.checks.interceptors; import java.util.Arrays; import java.util.HashSet; import java.util.Set; /** * Checks that if the interceptor handles one read command it handles all of them. */ public class InterceptorDefinesAllReadsCheck extends AbstractInterceptorCheck { private final static Set<String> READ_METHODS = new HashSet<>(Arrays.asList( "visitGetKeyValueCommand", "visitGetCacheEntryCommand", "visitGetAllCommand", "visitReadOnlyKeyCommand", "visitReadOnlyManyCommand")); @Override protected Set<String> methods() { return READ_METHODS; } }
647
26
82
java
null
infinispan-main/build/checkstyle/src/main/java/org/infinispan/checkstyle/checks/interceptors/AbstractInterceptorCheck.java
package org.infinispan.checkstyle.checks.interceptors; import static com.puppycrawl.tools.checkstyle.api.TokenTypes.ANNOTATION; import static com.puppycrawl.tools.checkstyle.api.TokenTypes.CLASS_DEF; import static com.puppycrawl.tools.checkstyle.api.TokenTypes.IDENT; import static com.puppycrawl.tools.checkstyle.api.TokenTypes.METHOD_DEF; import static com.puppycrawl.tools.checkstyle.api.TokenTypes.MODIFIERS; import static com.puppycrawl.tools.checkstyle.api.TokenTypes.OBJBLOCK; import java.util.HashSet; import java.util.Set; import java.util.stream.Stream; import com.puppycrawl.tools.checkstyle.api.AbstractCheck; import com.puppycrawl.tools.checkstyle.api.DetailAST; /** * Checks that if the interceptor handles one command it handles all conceptually similar ones. */ public abstract class AbstractInterceptorCheck extends AbstractCheck { protected static Stream<DetailAST> stream(DetailAST ast, int type) { Stream.Builder<DetailAST> builder = Stream.builder(); for (DetailAST child = ast.getFirstChild(); child != null; child = child.getNextSibling()) { if (child.getType() == type) { builder.accept(child); } } return builder.build(); } @Override public int[] getDefaultTokens() { return getAcceptableTokens(); } @Override public int[] getAcceptableTokens() { return new int[] { CLASS_DEF }; } @Override public int[] getRequiredTokens() { return getAcceptableTokens(); } @Override public void visitToken(DetailAST klass) { Set<String> containsMethods = new HashSet<>(); stream(klass, OBJBLOCK).flatMap(objblock -> stream(objblock, METHOD_DEF)).forEach(m -> { DetailAST identNode = m.findFirstToken(IDENT); if (identNode != null && methods().contains(identNode.getText())) { containsMethods.add(identNode.getText()); } }); if (!containsMethods.isEmpty() && containsMethods.size() != methods().size()) { DetailAST modifiers = klass.findFirstToken(MODIFIERS); if (modifiers != null) { if (stream(modifiers, ANNOTATION).anyMatch(annotation -> { DetailAST identNode = annotation.findFirstToken(IDENT); return identNode != null && "Deprecated".equals(identNode.getText()); })) { // Don't report deprecated classes return; } } Set<String> missingMethods = new HashSet<>(methods()); missingMethods.removeAll(containsMethods); log(klass.getLineNo(), klass.getColumnNo(), "Interceptor defines methods {0}" + " but does not define {1} [not required for tests]", containsMethods, missingMethods); } } protected abstract Set<String> methods(); }
2,809
35.493506
101
java
null
infinispan-main/build/checkstyle/src/main/java/org/infinispan/checkstyle/filters/ExcludeTestPackages.java
package org.infinispan.checkstyle.filters; import java.io.File; import com.puppycrawl.tools.checkstyle.api.AuditEvent; import com.puppycrawl.tools.checkstyle.api.Filter; /** * Allows disabling some rules for the test suite source. * * Any violation will be suppressed if it's generated by a source file having {@code /src/test/java} * included in its path and if the violation message contains the keyword * "[not required for tests]". * <p> * A SuppressionFilter is too generic, and requires per-module configuration. * * @author Sanne Grinovero &lt;sanne@hibernate.org&gt; */ public class ExcludeTestPackages implements Filter { private static final String SUB_PATH = File.separator + "src" + File.separator + "test" + File.separator + "java"; private static final String MESSAGE_DISABLE_KEYWORD = "[not required for tests]"; @Override public boolean accept(AuditEvent aEvent) { final String fileName = aEvent.getFileName(); if (fileName != null && fileName.contains(SUB_PATH)) { return acceptTestfileEvent(aEvent); } return true; } private boolean acceptTestfileEvent(AuditEvent aEvent) { final String message = aEvent.getMessage(); if (message != null && message.contains(MESSAGE_DISABLE_KEYWORD)) { return false; } return true; } }
1,340
31.707317
117
java
null
infinispan-main/build/checkstyle/src/main/java/org/infinispan/checkstyle/filters/HeadersNoCopyrightCheck.java
package org.infinispan.checkstyle.filters; import java.io.File; import com.puppycrawl.tools.checkstyle.api.AbstractFileSetCheck; import com.puppycrawl.tools.checkstyle.api.FileText; /** * Use a simple CheckStyle rule to make sure no copyright templates are being used: * Infinispan uses a single copyright file which can be found in the root of the project. * * @author Sanne Grinovero */ public class HeadersNoCopyrightCheck extends AbstractFileSetCheck { @Override protected void processFiltered(File file, FileText fileText) { final String fileName = file.getName(); if (fileName != null && !fileName.endsWith(".java")) { //Not a Java source file, skip it. return; } else if ("package-info.java".equals(fileName)) { //package-info files don't necessarily start with "package" return; } else if (fileText.size() != 0) { final String firstLine = fileText.get(0); if (firstLine!=null && !firstLine.startsWith("package ")) { log(1, "Java files should start with \''package \''. Infinispan doesn\''t use bulky copyright headers!"); } } } }
1,174
31.638889
117
java
null
infinispan-main/build/checkstyle/src/main/java/org/infinispan/checkstyle/filters/ExcludeGeneratedTestPackages.java
package org.infinispan.checkstyle.filters; import java.io.File; import com.puppycrawl.tools.checkstyle.api.AuditEvent; import com.puppycrawl.tools.checkstyle.api.Filter; /** * Excludes generated packages. */ public class ExcludeGeneratedTestPackages implements Filter { private static final String SUB_PATH = File.separator + "target" + File.separator + "generated-test-sources"; @Override public boolean accept(AuditEvent aEvent) { final String fileName = aEvent.getFileName(); return !fileName.contains(SUB_PATH); } }
551
25.285714
112
java
null
infinispan-main/build/logging-processor/src/main/java/org/infinispan/logging/processor/InfinispanLoggingProcessor.java
package org.infinispan.logging.processor; import java.io.BufferedWriter; import java.io.IOException; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import javax.annotation.processing.AbstractProcessor; import javax.annotation.processing.Processor; import javax.annotation.processing.RoundEnvironment; import javax.annotation.processing.SupportedAnnotationTypes; import javax.annotation.processing.SupportedSourceVersion; import javax.lang.model.SourceVersion; import javax.lang.model.element.Element; import javax.lang.model.element.TypeElement; import javax.tools.Diagnostic; import javax.tools.StandardLocation; import javax.xml.stream.XMLStreamException; import org.infinispan.logging.processor.report.XmlReportWriter; import org.kohsuke.MetaInfServices; /** * InfinispanLoggingProcessor. * * @author Durgesh Anaokar * @since 13.0 */ @SupportedSourceVersion(SourceVersion.RELEASE_8) @SupportedAnnotationTypes({InfinispanLoggingProcessor.DESCRIPTION}) @MetaInfServices(Processor.class) public class InfinispanLoggingProcessor extends AbstractProcessor { static final String DESCRIPTION = "org.infinispan.logging.annotations.Description"; @Override public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) { for (TypeElement annotation : annotations) { createReportXml(roundEnv, annotation); } return true; } private void createReportXml(RoundEnvironment roundEnv, TypeElement annotation) { Set<? extends Element> annotatedElements = roundEnv.getElementsAnnotatedWith(annotation); Map<String, List<Element>> mapWithQualifiedName = getMapWithQualifiedName(annotatedElements); for (Map.Entry<String, List<Element>> entry : mapWithQualifiedName.entrySet()) { Element e = entry.getValue().get(0); String qualifiedName = e.getEnclosingElement().toString(); Element enclosing = e.getEnclosingElement(); String packageName = processingEnv.getElementUtils().getPackageOf(enclosing).getQualifiedName().toString(); String simpleName = enclosing.getSimpleName().toString(); try (BufferedWriter bufferedWriter = createWriter(packageName, simpleName + ".xml"); XmlReportWriter reportWriter = new XmlReportWriter(bufferedWriter)) { reportWriter.writeHeader(qualifiedName); for (Element element : entry.getValue()) { reportWriter.writeDetail(element); } reportWriter.writeFooter(); } catch (XMLStreamException | IOException ex) { error(e, "Error encountered when writing the report: " + ex.getMessage(), e); break; } } } private BufferedWriter createWriter(final String packageName, final String fileName) throws IOException { return new BufferedWriter( processingEnv.getFiler().createResource(StandardLocation.CLASS_OUTPUT, packageName, fileName).openWriter()); } private void error(Element e, String format, Object... params) { String formatted = String.format(format, params); if (e != null) { processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, formatted, e); } else { processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, formatted); } } private Map<String, List<Element>> getMapWithQualifiedName(Set<? extends Element> annotatedElements) { Map<String, List<Element>> elementMap = new HashMap<>(); for (Element interfaceElement : annotatedElements) { List<Element> list = elementMap.get(interfaceElement.getEnclosingElement().toString()); if (list != null) { list.add(interfaceElement); } else { list = new LinkedList<Element>(); list.add(interfaceElement); elementMap.put(interfaceElement.getEnclosingElement().toString(), list); } } return elementMap; } }
4,018
40.43299
120
java
null
infinispan-main/build/logging-processor/src/main/java/org/infinispan/logging/processor/report/XmlReportWriter.java
package org.infinispan.logging.processor.report; import java.io.BufferedWriter; import java.io.IOException; import javax.lang.model.element.Element; import javax.xml.stream.XMLOutputFactory; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamWriter; import org.infinispan.logging.annotations.Description; import org.jboss.logging.annotations.LogMessage; import org.jboss.logging.annotations.Message; import org.jboss.logging.annotations.MessageLogger; /** * XmlReportWriter. * * @author Durgesh Anaokar * @since 13.0 */ public class XmlReportWriter implements AutoCloseable { private final XMLStreamWriter xmlWriter; public XmlReportWriter(final BufferedWriter writer) throws XMLStreamException { XMLOutputFactory factory = XMLOutputFactory.newInstance(); xmlWriter = new IndentingXmlWriter(factory.createXMLStreamWriter(writer)); } public void writeHeader(final String title) throws XMLStreamException { xmlWriter.writeStartDocument(); xmlWriter.writeStartElement("report"); if (title != null) { xmlWriter.writeAttribute("class", title); } xmlWriter.writeComment("DescriptionDocumentation"); xmlWriter.writeStartElement("logs"); } public void writeDetail(final Element element) throws XMLStreamException { Description description = element.getAnnotation(Description.class); Message message = element.getAnnotation(Message.class); LogMessage logMessage = element.getAnnotation(LogMessage.class); MessageLogger messageLogger = element.getEnclosingElement().getAnnotation(MessageLogger.class); String strMsgId = String.valueOf(message.id()); int padding = messageLogger.length() - strMsgId.length(); StringBuilder prjCode = new StringBuilder(messageLogger.projectCode()); for (int i = 0; i < padding; i++) { prjCode.append(0); } prjCode.append(strMsgId); xmlWriter.writeStartElement("log"); writeCharacters("id", prjCode.toString()); writeCharacters("message", message.value()); writeCharacters("description", description.value()); writeCharacters("level", logMessage == null ? "EXCEPTION" : logMessage.level().name()); xmlWriter.writeEndElement(); } private void writeCharacters(String elementName, String elementValue) throws XMLStreamException { xmlWriter.writeStartElement(elementName); xmlWriter.writeCharacters(elementValue); xmlWriter.writeEndElement(); } public void writeFooter() throws XMLStreamException { xmlWriter.writeEndElement(); // end <logs/> xmlWriter.writeEndElement(); // end <report/> xmlWriter.writeEndDocument(); } public void close() throws IOException { try { if (xmlWriter != null) xmlWriter.close(); } catch (XMLStreamException e) { throw new IOException(e); } } }
3,002
35.180723
104
java
null
infinispan-main/build/logging-processor/src/main/java/org/infinispan/logging/processor/report/IndentingXmlWriter.java
package org.infinispan.logging.processor.report; import java.util.Arrays; import javax.xml.namespace.NamespaceContext; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamWriter; /** * XMLStreamWriter that adds an indent for each open element. * * @author Durgesh Anaokar * @since 13.0 */ class IndentingXmlWriter implements XMLStreamWriter { private static final int INDENT_STEP = 2; private static final int MAX_INDENT = 64; private static final char[] INDENT = new char[MAX_INDENT + 1]; static { Arrays.fill(INDENT, ' '); INDENT[0] = '\n'; } private XMLStreamWriter writer; private int indent; private boolean skipIndent; IndentingXmlWriter(XMLStreamWriter writer) { this.writer = writer; } @Override public void writeStartElement(String localName) throws XMLStreamException { writeIndent(1); writer.writeStartElement(localName); } @Override public void writeStartElement(String namespaceURI, String localName) throws XMLStreamException { writeIndent(1); writer.writeStartElement(namespaceURI, localName); } @Override public void writeStartElement(String prefix, String localName, String namespaceURI) throws XMLStreamException { writeIndent(1); writer.writeStartElement(prefix, localName, namespaceURI); } @Override public void writeEmptyElement(String namespaceURI, String localName) throws XMLStreamException { writeIndent(0); writer.writeEmptyElement(namespaceURI, localName); } @Override public void writeEmptyElement(String prefix, String localName, String namespaceURI) throws XMLStreamException { writeIndent(0); writer.writeEmptyElement(prefix, localName, namespaceURI); } @Override public void writeEmptyElement(String localName) throws XMLStreamException { writeIndent(0); writer.writeEmptyElement(localName); } @Override public void writeEndElement() throws XMLStreamException { writeIndent(-1); writer.writeEndElement(); } @Override public void writeEndDocument() throws XMLStreamException { writer.writeEndDocument(); } @Override public void close() throws XMLStreamException { writer.close(); } @Override public void flush() throws XMLStreamException { writer.flush(); } @Override public void writeAttribute(String localName, String value) throws XMLStreamException { writer.writeAttribute(localName, value); } @Override public void writeAttribute(String prefix, String namespaceURI, String localName, String value) throws XMLStreamException { writer.writeAttribute(prefix, namespaceURI, localName, value); } @Override public void writeAttribute(String namespaceURI, String localName, String value) throws XMLStreamException { writer.writeAttribute(namespaceURI, localName, value); } @Override public void writeNamespace(String prefix, String namespaceURI) throws XMLStreamException { writer.writeNamespace(prefix, namespaceURI); } @Override public void writeDefaultNamespace(String namespaceURI) throws XMLStreamException { writer.writeDefaultNamespace(namespaceURI); } @Override public void writeComment(String data) throws XMLStreamException { writeIndent(0); writer.writeComment(data); } @Override public void writeProcessingInstruction(String target) throws XMLStreamException { writer.writeProcessingInstruction(target); } @Override public void writeProcessingInstruction(String target, String data) throws XMLStreamException { writer.writeProcessingInstruction(target, data); } @Override public void writeCData(String data) throws XMLStreamException { writeIndent(0); writer.writeCData(data); } @Override public void writeDTD(String dtd) throws XMLStreamException { writer.writeDTD(dtd); } @Override public void writeEntityRef(String name) throws XMLStreamException { writer.writeEntityRef(name); } @Override public void writeStartDocument() throws XMLStreamException { writer.writeStartDocument(); } @Override public void writeStartDocument(String version) throws XMLStreamException { writer.writeStartDocument(version); } @Override public void writeStartDocument(String encoding, String version) throws XMLStreamException { writer.writeStartDocument(encoding, version); } @Override public void writeCharacters(String text) throws XMLStreamException { skipIndent = true; writer.writeCharacters(text); } @Override public void writeCharacters(char[] text, int start, int len) throws XMLStreamException { skipIndent = true; writer.writeCharacters(text, start, len); } @Override public String getPrefix(String uri) throws XMLStreamException { return writer.getPrefix(uri); } @Override public void setPrefix(String prefix, String uri) throws XMLStreamException { writer.setPrefix(prefix, uri); } @Override public void setDefaultNamespace(String uri) throws XMLStreamException { writer.setDefaultNamespace(uri); } @Override public void setNamespaceContext(NamespaceContext context) throws XMLStreamException { writer.setNamespaceContext(context); } @Override public NamespaceContext getNamespaceContext() { return writer.getNamespaceContext(); } @Override public Object getProperty(String name) throws IllegalArgumentException { return writer.getProperty(name); } private void writeIndent(int increment) throws XMLStreamException { // Unindent before start element if (increment < 0) { indent += increment * INDENT_STEP; } if (skipIndent) { skipIndent = false; } else { writer.writeCharacters(INDENT, 0, Math.min(indent, MAX_INDENT) + 1); } // Indent after start element if (increment > 0) { indent += increment * INDENT_STEP; } } }
6,121
26.330357
114
java
null
infinispan-main/build/infinispan-defaults-maven-plugin/src/main/java/org/infinispan/plugins/maven/defaults/InfinispanDefaultsResolver.java
package org.infinispan.plugins.maven.defaults; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import org.infinispan.commons.configuration.attributes.Attribute; import org.infinispan.commons.configuration.attributes.AttributeDefinition; import org.infinispan.commons.configuration.attributes.AttributeSet; /** * {@link DefaultsResolver} implementation that extracts default values from ISPN {@link AttributeDefinition}s * * @author Ryan Emerson */ class InfinispanDefaultsResolver implements DefaultsResolver { @Override public boolean isValidClass(String className) { return className.endsWith("Configuration.class") && !className.contains("$"); } @Override public Map<String, String> extractDefaults(Set<Class> classes, String separator) { Map<String, String> map = new HashMap<>(); for (Class clazz : classes) { AttributeSet attributeSet = getAttributeSet(clazz); if (attributeSet == null) continue; attributeSet.attributes().stream() .map(Attribute::getAttributeDefinition) .filter(definition -> definition.getDefaultValue() != null) .forEach(definition -> map.put(getOutputKey(clazz, definition, separator), getOutputValue(definition))); } return map; } private AttributeSet getAttributeSet(Class clazz) { Field[] declaredFields = clazz.getDeclaredFields(); List<AttributeDefinition> attributeDefinitions = new ArrayList<>(); for (Field field : declaredFields) { if (Modifier.isStatic(field.getModifiers()) && AttributeDefinition.class.isAssignableFrom(field.getType())) { field.setAccessible(true); try { attributeDefinitions.add((AttributeDefinition) field.get(null)); } catch (IllegalAccessException ignore) { // Shouldn't happen as we have setAccessible == true } } } return new AttributeSet(clazz, attributeDefinitions.toArray(new AttributeDefinition[attributeDefinitions.size()])); } private String getOutputValue(AttributeDefinition definition) { // Remove @<hashcode> from toString of classes return definition.getDefaultValue().toString().split("@")[0]; } private String getOutputKey(Class clazz, AttributeDefinition attribute, String seperator) { String className = clazz.getSimpleName(); String root = className.startsWith("Configuration") ? className : className.replace("Configuration", ""); return root + seperator + attribute.name(); } }
2,717
37.828571
121
java
null
infinispan-main/build/infinispan-defaults-maven-plugin/src/main/java/org/infinispan/plugins/maven/defaults/DefaultsExtractorMojo.java
package org.infinispan.plugins.maven.defaults; import static org.twdata.maven.mojoexecutor.MojoExecutor.artifactId; import static org.twdata.maven.mojoexecutor.MojoExecutor.configuration; import static org.twdata.maven.mojoexecutor.MojoExecutor.element; import static org.twdata.maven.mojoexecutor.MojoExecutor.executeMojo; import static org.twdata.maven.mojoexecutor.MojoExecutor.executionEnvironment; import static org.twdata.maven.mojoexecutor.MojoExecutor.goal; import static org.twdata.maven.mojoexecutor.MojoExecutor.groupId; import static org.twdata.maven.mojoexecutor.MojoExecutor.plugin; import static org.twdata.maven.mojoexecutor.MojoExecutor.version; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.net.MalformedURLException; import java.net.URL; import java.net.URLClassLoader; import java.nio.file.FileSystem; import java.nio.file.FileSystems; import java.nio.file.Path; import java.nio.file.PathMatcher; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import org.apache.maven.artifact.DependencyResolutionRequiredException; import org.apache.maven.execution.MavenSession; import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugin.BuildPluginManager; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugins.annotations.Component; import org.apache.maven.plugins.annotations.LifecyclePhase; import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.plugins.annotations.Parameter; import org.apache.maven.plugins.annotations.ResolutionScope; import org.apache.maven.project.MavenProject; /** * A maven plugin to extract default values from various AtributeDefinitions, output them to a specified properties/asciidoc * file and process xsd files so that placeholders are replaced with the extracted defaults. * * @author Ryan Emerson */ @Mojo(name = "extract-defaults", defaultPhase = LifecyclePhase.PROCESS_CLASSES, requiresDependencyResolution = ResolutionScope.RUNTIME) public class DefaultsExtractorMojo extends AbstractMojo { private enum AttributeDefType { ISPN, ALL } @Parameter(required = true, defaultValue = "${project.build.directory}/defaults.properties") private String defaultsFile; @Parameter(defaultValue = "ISPN") private AttributeDefType attributeDefType; @Parameter(defaultValue = "false") private boolean outputAscii; @Parameter(defaultValue = "true") private boolean filterXsd; @Parameter(defaultValue = "${project.basedir}/src/main/resources/schema") private String xsdSrcPath; @Parameter(defaultValue = "${project.build.directory}/classes/schema") private String xsdTargetPath; @Parameter private List<String> jars = new ArrayList<>(); @Parameter(defaultValue = "${project}") private MavenProject mavenProject; @Parameter(defaultValue = "${session}") private MavenSession mavenSession; @Component private BuildPluginManager pluginManager; private DefaultsResolver ispnResolver = new InfinispanDefaultsResolver(); private List<String> classPaths; private ClassLoader classLoader; public void execute() throws MojoExecutionException { try { this.classPaths = mavenProject.getCompileClasspathElements(); URL[] classLoaderUrls = classPaths.stream() .map(strPath -> FileSystems.getDefault().getPath(strPath)) .map(this::pathToUrl) .toArray(URL[]::new); this.classLoader = new URLClassLoader(classLoaderUrls, Thread.currentThread().getContextClassLoader()); } catch (DependencyResolutionRequiredException e) { throw new MojoExecutionException("Exception encountered during class extraction", e); } Set<Class> configClasses = new HashSet<>(); getClassesFromClasspath(configClasses); jars.forEach(jar -> getClassesFromJar(jar, configClasses)); Map<String, String> defaults = extractDefaults(configClasses); writeDefaultsToFile(defaults); if (filterXsd) filterXsdSchemas(); } private boolean isValidClass(String className) { return ispnResolver.isValidClass(className); } private Map<String, String> extractDefaults(Set<Class> classes) { String separator = outputAscii ? "-" : "."; Map<String, String> defaults = new HashMap<>(); boolean extractAll = attributeDefType == AttributeDefType.ALL; if (extractAll || attributeDefType == AttributeDefType.ISPN) defaults.putAll(ispnResolver.extractDefaults(classes, separator)); return defaults; } private URL pathToUrl(Path path) { try { return path.toUri().toURL(); } catch (MalformedURLException ignore) { return null; } } private void getClassesFromClasspath(Set<Class> classes) throws MojoExecutionException { try { FileSystem fs = FileSystems.getDefault(); PathMatcher classDir = fs.getPathMatcher("glob:*/**/target/classes"); List<File> packageRoots = classPaths.stream() .map(fs::getPath) .filter(classDir::matches) .map(Path::toFile) .collect(Collectors.toList()); for (File packageRoot : packageRoots) getClassesInPackage(packageRoot, "", classes); } catch (ClassNotFoundException e) { throw new MojoExecutionException("Exception encountered during class extraction", e); } } private void getClassesInPackage(File packageDir, String packageName, Set<Class> classes) throws ClassNotFoundException { if (packageDir.exists()) { for (File file : packageDir.listFiles()) { String fileName = file.getName(); if (file.isDirectory()) { String subpackage = packageName.isEmpty() ? fileName : packageName + "." + fileName; getClassesInPackage(file, subpackage, classes); } else if (isValidClass(fileName)) { String className = fileName.substring(0, fileName.length() - 6); classes.add(Class.forName(packageName + "." + className, true, classLoader)); } } } } private void getClassesFromJar(String jarName, Set<Class> classes) { // Ignore version number, necessary as jar is loaded differently when sub module is installed in isolation Optional<String> jarPath = classPaths.stream().filter(str -> str.contains(jarName)).findFirst(); if (jarPath.isPresent()) { try { ZipInputStream jar = new ZipInputStream(new FileInputStream(jarPath.get())); for (ZipEntry entry = jar.getNextEntry(); entry != null; entry = jar.getNextEntry()) { if (!entry.isDirectory() && isValidClass(entry.getName())) { String className = entry.getName().replace("/", "."); classes.add(Class.forName(className.substring(0, className.length() - 6), true, classLoader)); } } } catch (IOException | ClassNotFoundException e) { getLog().error(String.format("Unable to process jar '%s'", jarName), e); } } else { // We just warn here, as jars are required for `mvn install`, but not for `mvn test` getLog().info("Skipping Jar '" + jarName + "' as it cannot be found on the classpath"); } } private void writeDefaultsToFile(Map<String, String> defaults) throws MojoExecutionException { File file = new File(defaultsFile); if (file.getParentFile() != null) file.getParentFile().mkdirs(); try (PrintWriter printWriter = new PrintWriter(new BufferedWriter(new FileWriter(file, true)))) { defaults.entrySet().stream() .map(this::formatOutput) .sorted() .forEach(printWriter::println); printWriter.flush(); } catch (IOException e) { throw new MojoExecutionException(String.format("Unable to write extracted defaults to the path '%s'", defaultsFile), e); } } private String formatOutput(Map.Entry<String, String> entry) { if (outputAscii) { return ":" + entry.getKey() + ": " + entry.getValue(); } return entry.getKey() + "=" + entry.getValue(); } private void filterXsdSchemas() throws MojoExecutionException { executeMojo( plugin( groupId("org.apache.maven.plugins"), artifactId("maven-resources-plugin"), version("3.1.0") ), goal("copy-resources"), configuration( element("overwrite", "true"), element("outputDirectory", defaultsFile), element("resources", element("resource", element("directory", xsdSrcPath), element("targetPath", xsdTargetPath), element("includes", element("include", "*.xsd") ), element("filtering", "true") ) ), element("filters", element("filter", defaultsFile) ) ), executionEnvironment( mavenProject, mavenSession, pluginManager ) ); } }
9,811
37.328125
129
java
null
infinispan-main/build/infinispan-defaults-maven-plugin/src/main/java/org/infinispan/plugins/maven/defaults/DefaultsResolver.java
package org.infinispan.plugins.maven.defaults; import java.util.Map; import java.util.Set; /** * Interface used by {@link org.infinispan.plugins.maven.defaults.DefaultsExtractorMojo} to extract default default * values from AttributeDefinitions. * * @author Ryan Emerson */ interface DefaultsResolver { boolean isValidClass(String className); Map<String, String> extractDefaults(Set<Class> classes, String separator); }
433
26.125
115
java
null
infinispan-main/counter/src/test/java/org/infinispan/counter/ExpirationStrongCounterTest.java
package org.infinispan.counter; import static org.infinispan.commons.test.Exceptions.expectException; import static org.infinispan.test.TestingUtil.replaceComponent; import static org.testng.AssertJUnit.assertEquals; import org.infinispan.commons.time.ControlledTimeService; import org.infinispan.commons.time.TimeService; import org.infinispan.counter.api.CounterConfiguration; import org.infinispan.counter.api.CounterManager; import org.infinispan.counter.api.CounterType; import org.infinispan.counter.api.SyncStrongCounter; import org.infinispan.counter.exception.CounterOutOfBoundsException; import org.infinispan.test.MultipleCacheManagersTest; import org.testng.annotations.Test; @Test(groups = "functional", testName = "counter.ExpirationStrongCounterTest") public class ExpirationStrongCounterTest extends MultipleCacheManagersTest { private static final long EXPIRATION_MILLISECONDS = 1000; private final ControlledTimeService timeService = new ControlledTimeService("expiring-strong-counter"); public void testUnboundedCounter() { CounterConfiguration config = CounterConfiguration.builder(CounterType.UNBOUNDED_STRONG) .lifespan(EXPIRATION_MILLISECONDS).build(); String counterName = "unbounded-counter"; CounterManager counterManager = counterManager(); counterManager.defineCounter(counterName, config); doTest(counterName, -1); } public void testBoundedCounter() { CounterConfiguration config = CounterConfiguration.builder(CounterType.BOUNDED_STRONG) .lifespan(EXPIRATION_MILLISECONDS) .upperBound(3).build(); String counterName = "bounded-counter"; CounterManager counterManager = counterManager(); counterManager.defineCounter(counterName, config); doTest(counterName, 3); } public void testBoundedCounterNeverReached() { CounterConfiguration config = CounterConfiguration.builder(CounterType.BOUNDED_STRONG) .lifespan(EXPIRATION_MILLISECONDS) .upperBound(30).build(); String counterName = "bounded-counter-2"; CounterManager counterManager = counterManager(); counterManager.defineCounter(counterName, config); doTest(counterName, 30); } private void doTest(String counterName, long upperBound) { SyncStrongCounter counter = counterManager().getStrongCounter(counterName).sync(); if (upperBound == -1) { incrementUnbound(counter, 0); } else { incrementBound(counter, 0, upperBound); } // expire the counter timeService.advance(EXPIRATION_MILLISECONDS + 1); // after the time expired, the counter should be in its initial value assertEquals(0, counter.getValue()); if (upperBound == -1) { incrementUnbound(counter, 0); } else { incrementBound(counter, 0, upperBound); } // this should not expire the counter timeService.advance(EXPIRATION_MILLISECONDS - 1); if (upperBound == -1) { assertEquals(5, counter.getValue()); incrementUnbound(counter, 5); } else { assertEquals(Math.min(5, upperBound), counter.getValue()); incrementBound(counter, Math.min(5, upperBound), upperBound); } // expire the counter timeService.advance(2); // after the time expired, the counter should be in its initial value assertEquals(0, counter.getValue()); } private void incrementUnbound(SyncStrongCounter counter, long expectedBaseValue) { for (int i = 0; i < 5; ++i) { incrementAndAssert(counter, expectedBaseValue + i + 1); } assertEquals(expectedBaseValue + 5, counter.getValue()); } private void incrementBound(SyncStrongCounter counter, long initialValue, long upperBound) { for (int i = 0; i < 5; ++i) { if (counter.getValue() == upperBound) { expectException(CounterOutOfBoundsException.class, counter::incrementAndGet); } else { incrementAndAssert(counter, initialValue + i + 1); } } } @Override protected void createCacheManagers() throws Throwable { createCluster(2); cacheManagers.forEach(m -> replaceComponent(m, TimeService.class, timeService, true)); } private CounterManager counterManager() { return EmbeddedCounterManagerFactory.asCounterManager(manager(0)); } private void incrementAndAssert(SyncStrongCounter counter, long expectedValue) { assertEquals(expectedValue, counter.incrementAndGet()); } }
4,557
36.360656
106
java
null
infinispan-main/counter/src/test/java/org/infinispan/counter/WeakCounterWithZeroCapacityNodesTest.java
package org.infinispan.counter; import org.infinispan.configuration.global.GlobalConfigurationBuilder; import org.infinispan.counter.api.WeakCounter; import org.testng.annotations.Test; /** * A simple consistency test for {@link WeakCounter} with zero capacity nodes. * * @author Katia Aresti, karesti@redhat.com * @since 9.4 */ @Test(groups = "functional", testName = "counter.WeakCounterWithZeroCapacityNodesTest") public class WeakCounterWithZeroCapacityNodesTest extends WeakCounterTest { @Override protected GlobalConfigurationBuilder configure(int nodeId) { return GlobalConfigurationBuilder.defaultClusteredBuilder().zeroCapacityNode(nodeId % 2 == 1); } }
686
31.714286
100
java
null
infinispan-main/counter/src/test/java/org/infinispan/counter/LocalWeakCounterNotificationTest.java
package org.infinispan.counter; import org.infinispan.configuration.global.GlobalConfigurationBuilder; import org.testng.annotations.Test; /** * A simple notification test for local {@link org.infinispan.counter.api.WeakCounter}. * * @author Pedro Ruivo * @since 9.2 */ @Test(groups = "functional", testName = "counter.LocalWeakCounterNotificationTest") public class LocalWeakCounterNotificationTest extends WeakCounterNotificationTest { @Override protected int clusterSize() { return 1; } @Override protected GlobalConfigurationBuilder configure(int nodeId) { return new GlobalConfigurationBuilder(); } }
645
24.84
87
java
null
infinispan-main/counter/src/test/java/org/infinispan/counter/LocalStrongCounterTest.java
package org.infinispan.counter; import org.infinispan.configuration.global.GlobalConfigurationBuilder; import org.testng.annotations.Test; /** * A simple consistency test for {@link org.infinispan.counter.api.StrongCounter}. * * @author Pedro Ruivo * @since 9.2 */ @Test(groups = "functional", testName = "counter.LocalStrongCounterTest") public class LocalStrongCounterTest extends StrongCounterTest { @Override protected int clusterSize() { return 1; } @Override protected GlobalConfigurationBuilder configure(int nodeId) { return new GlobalConfigurationBuilder(); } }
610
23.44
82
java
null
infinispan-main/counter/src/test/java/org/infinispan/counter/StrongCounterNotificationTest.java
package org.infinispan.counter; import org.infinispan.counter.api.CounterConfiguration; import org.infinispan.counter.api.CounterManager; import org.infinispan.counter.api.CounterType; import org.infinispan.counter.util.StrongTestCounter; import org.infinispan.counter.util.TestCounter; import org.testng.annotations.Test; /** * Notification test for {@link org.infinispan.counter.api.StrongCounter}. * * @author Pedro Ruivo * @since 9.0 */ @Test(groups = "functional", testName = "counter.StrongCounterNotificationTest") public class StrongCounterNotificationTest extends AbstractCounterNotificationTest { @Override protected TestCounter createCounter(CounterManager counterManager, String counterName) { counterManager.defineCounter(counterName, CounterConfiguration.builder(CounterType.UNBOUNDED_STRONG).build()); return new StrongTestCounter(counterManager.getStrongCounter(counterName)); } }
925
37.583333
116
java
null
infinispan-main/counter/src/test/java/org/infinispan/counter/ConfigurationTest.java
package org.infinispan.counter; import static org.infinispan.commons.test.CommonsTestingUtil.tmpDirectory; import static org.infinispan.commons.test.Exceptions.expectException; import static org.infinispan.counter.EmbeddedCounterManagerFactory.asCounterManager; import static org.infinispan.test.TestingUtil.withCacheManager; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertFalse; import static org.testng.AssertJUnit.assertTrue; import static org.testng.AssertJUnit.fail; import java.nio.file.Paths; import org.infinispan.commons.CacheConfigurationException; import org.infinispan.commons.IllegalLifecycleStateException; import org.infinispan.commons.util.Util; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.Configuration; import org.infinispan.configuration.global.GlobalConfiguration; import org.infinispan.configuration.global.GlobalConfigurationBuilder; import org.infinispan.counter.api.CounterConfiguration; import org.infinispan.counter.api.CounterManager; import org.infinispan.counter.api.CounterType; import org.infinispan.counter.api.Storage; import org.infinispan.counter.configuration.AbstractCounterConfiguration; import org.infinispan.counter.configuration.CounterManagerConfiguration; import org.infinispan.counter.configuration.CounterManagerConfigurationBuilder; import org.infinispan.counter.configuration.Reliability; import org.infinispan.counter.configuration.StrongCounterConfiguration; import org.infinispan.counter.configuration.WeakCounterConfiguration; import org.infinispan.counter.exception.CounterConfigurationException; import org.infinispan.counter.impl.CounterModuleLifecycle; import org.infinispan.manager.DefaultCacheManager; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.partitionhandling.PartitionHandling; import org.infinispan.test.AbstractCacheTest; import org.infinispan.test.TestingUtil; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.infinispan.transaction.TransactionMode; import org.testng.annotations.AfterMethod; import org.testng.annotations.Test; /** * Configuration test * * @author Pedro Ruivo * @since 9.0 */ @Test(groups = "unit", testName = "counter.ConfigurationTest") public class ConfigurationTest extends AbstractCacheTest { private static final String PERSISTENT_FOLDER = tmpDirectory(ConfigurationTest.class.getSimpleName()); private static final String TEMP_PERSISTENT_FOLDER = Paths.get(PERSISTENT_FOLDER, "temp").toString(); private static final String SHARED_PERSISTENT_FOLDER = Paths.get(PERSISTENT_FOLDER, "shared").toString(); private static GlobalConfigurationBuilder defaultGlobalConfigurationBuilder(boolean globalStateEnabled) { GlobalConfigurationBuilder builder = GlobalConfigurationBuilder.defaultClusteredBuilder(); builder.globalState().enabled(globalStateEnabled).persistentLocation(PERSISTENT_FOLDER) .temporaryLocation(TEMP_PERSISTENT_FOLDER) .sharedPersistentLocation(SHARED_PERSISTENT_FOLDER); return builder; } private static void assertCounterAndCacheConfiguration(CounterManagerConfiguration config, Configuration cacheConfig) { assertEquals(CacheMode.DIST_SYNC, cacheConfig.clustering().cacheMode()); assertEquals(config.numOwners(), cacheConfig.clustering().hash().numOwners()); assertEquals(config.reliability() == Reliability.CONSISTENT, cacheConfig.clustering().partitionHandling().whenSplit() == PartitionHandling.DENY_READ_WRITES); assertFalse(cacheConfig.clustering().l1().enabled()); assertEquals(TransactionMode.NON_TRANSACTIONAL, cacheConfig.transaction().transactionMode()); } @AfterMethod(alwaysRun = true) public void removeFiles() { Util.recursiveFileRemove(PERSISTENT_FOLDER); Util.recursiveFileRemove(TEMP_PERSISTENT_FOLDER); Util.recursiveFileRemove(SHARED_PERSISTENT_FOLDER); } private static Configuration getCounterCacheConfiguration(EmbeddedCacheManager cacheManager) { return cacheManager.getCache(CounterModuleLifecycle.COUNTER_CACHE_NAME).getCacheConfiguration(); } private static EmbeddedCacheManager buildCacheManager(GlobalConfigurationBuilder builder) { DefaultCacheManager cacheManager = new DefaultCacheManager(builder.build()); //result doesn't matter. isDefined will wait until the caches are started to avoid starting and killing //caches too fast asCounterManager(cacheManager).isDefined("some-counter"); return cacheManager; } public void testDefaultConfiguration() { TestingUtil.withCacheManager(() -> buildCacheManager(defaultGlobalConfigurationBuilder(false)), cacheManager -> { CounterManagerConfiguration configuration = CounterManagerConfigurationBuilder.defaultConfiguration(); Configuration cacheConfiguration = getCounterCacheConfiguration(cacheManager); assertCounterAndCacheConfiguration(configuration, cacheConfiguration); }); } public void testNumOwner() { final GlobalConfigurationBuilder builder = defaultGlobalConfigurationBuilder(false); final CounterManagerConfiguration config = builder.addModule(CounterManagerConfigurationBuilder.class) .numOwner(5).create(); TestingUtil.withCacheManager(() -> buildCacheManager(builder), cacheManager -> { Configuration cacheConfiguration = getCounterCacheConfiguration(cacheManager); assertCounterAndCacheConfiguration(config, cacheConfiguration); }); } public void testReliability() { final GlobalConfigurationBuilder builder = defaultGlobalConfigurationBuilder(false); final CounterManagerConfiguration config = builder.addModule(CounterManagerConfigurationBuilder.class) .reliability(Reliability.AVAILABLE).create(); TestingUtil.withCacheManager(() -> buildCacheManager(builder), cacheManager -> { Configuration cacheConfiguration = getCounterCacheConfiguration(cacheManager); assertCounterAndCacheConfiguration(config, cacheConfiguration); }); } public void testReliability2() { final GlobalConfigurationBuilder builder = defaultGlobalConfigurationBuilder(false); final CounterManagerConfiguration config = builder.addModule(CounterManagerConfigurationBuilder.class) .reliability(Reliability.CONSISTENT).create(); TestingUtil.withCacheManager(() -> buildCacheManager(builder), cacheManager -> { Configuration cacheConfiguration = getCounterCacheConfiguration(cacheManager); assertCounterAndCacheConfiguration(config, cacheConfiguration); }); } public void testInvalidReliability() { final GlobalConfigurationBuilder builder = defaultGlobalConfigurationBuilder(false); CounterManagerConfigurationBuilder counterBuilder = builder.addModule(CounterManagerConfigurationBuilder.class); counterBuilder.reliability(Reliability.AVAILABLE); builder.build(); counterBuilder.reliability(Reliability.CONSISTENT); builder.build(); counterBuilder.reliability(null); assertCounterConfigurationException(builder); } public void testInvalidNumOwner() { final GlobalConfigurationBuilder builder = defaultGlobalConfigurationBuilder(false); CounterManagerConfigurationBuilder counterBuilder = builder.addModule(CounterManagerConfigurationBuilder.class); counterBuilder.numOwner(0); assertCounterConfigurationException(builder); counterBuilder.numOwner(-1); assertCounterConfigurationException(builder); counterBuilder.numOwner(1); builder.build(); } public void testDuplicateCounterName() { final GlobalConfigurationBuilder builder = defaultGlobalConfigurationBuilder(false); CounterManagerConfigurationBuilder counterBuilder = builder.addModule(CounterManagerConfigurationBuilder.class); counterBuilder.addStrongCounter().name("aCounter"); counterBuilder.addWeakCounter().name("aCounter"); assertCounterConfigurationException(builder); counterBuilder.clearCounters(); counterBuilder.addStrongCounter().name("aCounter"); counterBuilder.addStrongCounter().name("aCounter"); assertCounterConfigurationException(builder); counterBuilder.clearCounters(); counterBuilder.addWeakCounter().name("aCounter"); counterBuilder.addWeakCounter().name("aCounter"); assertCounterConfigurationException(builder); } public void testMissingCounterName() { final GlobalConfigurationBuilder builder = defaultGlobalConfigurationBuilder(false); CounterManagerConfigurationBuilder counterBuilder = builder.addModule(CounterManagerConfigurationBuilder.class); counterBuilder.addStrongCounter(); assertCounterConfigurationException(builder); counterBuilder.clearCounters(); counterBuilder.addWeakCounter(); assertCounterConfigurationException(builder); } public void testStrongCounterUpperBound() { final GlobalConfigurationBuilder builder = defaultGlobalConfigurationBuilder(false); CounterManagerConfigurationBuilder counterBuilder = builder.addModule(CounterManagerConfigurationBuilder.class); counterBuilder.addStrongCounter().name("valid").initialValue(10).upperBound(10); builder.build(); //no exception! counterBuilder.clearCounters(); counterBuilder.addStrongCounter().name("valid").initialValue(10).upperBound(11); builder.build(); counterBuilder.clearCounters(); counterBuilder.addStrongCounter().name("invalid").initialValue(10).upperBound(9); assertCounterConfigurationException(builder); } public void testStringCounterLowerBound() { final GlobalConfigurationBuilder builder = defaultGlobalConfigurationBuilder(false); CounterManagerConfigurationBuilder counterBuilder = builder.addModule(CounterManagerConfigurationBuilder.class); counterBuilder.addStrongCounter().name("valid").initialValue(10).lowerBound(10); builder.build(); counterBuilder.clearCounters(); counterBuilder.addStrongCounter().name("valid").initialValue(10).lowerBound(9); builder.build(); counterBuilder.clearCounters(); counterBuilder.addStrongCounter().name("invalid").initialValue(10).lowerBound(11); assertCounterConfigurationException(builder); } public void testInvalidWeakCounterConcurrencyLevel() { final GlobalConfigurationBuilder builder = defaultGlobalConfigurationBuilder(false); CounterManagerConfigurationBuilder counterBuilder = builder.addModule(CounterManagerConfigurationBuilder.class); counterBuilder.addWeakCounter().name("invalid").concurrencyLevel(0); assertCounterConfigurationException(builder); counterBuilder.clearCounters(); counterBuilder.addWeakCounter().name("invalid").concurrencyLevel(-1); assertCounterConfigurationException(builder); counterBuilder.clearCounters(); counterBuilder.addWeakCounter().name("valid").concurrencyLevel(1); builder.build(); } public void testInvalidStorage() { final GlobalConfigurationBuilder builder = defaultGlobalConfigurationBuilder(true); CounterManagerConfigurationBuilder counterBuilder = builder.addModule(CounterManagerConfigurationBuilder.class); counterBuilder.addWeakCounter().name("valid").storage(Storage.VOLATILE); counterBuilder.addStrongCounter().name("valid2").storage(Storage.PERSISTENT); builder.build(); counterBuilder.clearCounters(); counterBuilder.addWeakCounter().name("valid").storage(Storage.PERSISTENT); counterBuilder.addStrongCounter().name("valid2").storage(Storage.VOLATILE); builder.build(); counterBuilder.clearCounters(); counterBuilder.addWeakCounter().name("invalid").storage(null); assertCounterConfigurationException(builder); counterBuilder.clearCounters(); counterBuilder.addStrongCounter().name("invalid").storage(null); assertCounterConfigurationException(builder); } public void testCounters() { final GlobalConfigurationBuilder builder = defaultGlobalConfigurationBuilder(true); CounterManagerConfigurationBuilder counterBuilder = builder.addModule(CounterManagerConfigurationBuilder.class); counterBuilder.addStrongCounter().name("unbounded-strong-1").initialValue(1).storage(Storage.VOLATILE) .addStrongCounter().name("lower-bounded-strong-2").initialValue(2).lowerBound(-10).lifespan(-1) .storage(Storage.PERSISTENT) .addStrongCounter().name("upper-bounded-strong-3").initialValue(3).upperBound(10).lifespan(1000) .storage(Storage.VOLATILE) .addStrongCounter().name("bounded-strong-4").initialValue(4).lowerBound(-20).upperBound(20).lifespan(2000) .storage(Storage.PERSISTENT) .addWeakCounter().name("weak-5").initialValue(5).concurrencyLevel(10).storage(Storage.VOLATILE); GlobalConfiguration config = builder.build(); CounterManagerConfiguration counterConfig = config.module(CounterManagerConfiguration.class); assertUnboundedStrongCounter(counterConfig); assertBoundedStrongCounter(counterConfig, "lower-bounded-strong-2", 2, -10, Long.MAX_VALUE, -1, Storage.PERSISTENT); assertBoundedStrongCounter(counterConfig, "upper-bounded-strong-3", 3, Long.MIN_VALUE, 10, 1000, Storage.VOLATILE); assertBoundedStrongCounter(counterConfig, "bounded-strong-4", 4, -20, 20, 2000, Storage.PERSISTENT); assertWeakCounter(counterConfig); TestingUtil.withCacheManager(() -> new DefaultCacheManager(builder.build()), cacheManager -> { CounterManager manager = asCounterManager(cacheManager); assertTrue(manager.isDefined("unbounded-strong-1")); assertTrue(manager.isDefined("lower-bounded-strong-2")); assertTrue(manager.isDefined("upper-bounded-strong-3")); assertTrue(manager.isDefined("bounded-strong-4")); assertTrue(manager.isDefined("weak-5")); assertFalse(manager.isDefined("not-defined-counter")); }); } public void testInvalidEqualsUpperAndLowerBound() { final GlobalConfigurationBuilder builder = defaultGlobalConfigurationBuilder(false); CounterManagerConfigurationBuilder counterBuilder = builder.addModule(CounterManagerConfigurationBuilder.class); counterBuilder.addStrongCounter().name("invalid").initialValue(10).lowerBound(10).upperBound(10); assertCounterConfigurationException(builder); } public void testInvalidEqualsUpperAndLowerBoundInManager() { TestingUtil.withCacheManager(DefaultCacheManager::new, cacheManager -> { CounterManager manager = asCounterManager(cacheManager); CounterConfiguration cfg = CounterConfiguration.builder(CounterType.BOUNDED_STRONG).initialValue(10) .lowerBound(10).upperBound(10).build(); expectException(CounterConfigurationException.class, () -> manager.defineCounter("invalid", cfg)); }); } private void assertUnboundedStrongCounter(CounterManagerConfiguration config) { for (AbstractCounterConfiguration counterConfig : config.counters().values()) { if (counterConfig.name().equals("unbounded-strong-1")) { assertTrue(counterConfig instanceof StrongCounterConfiguration); assertEquals(1, counterConfig.initialValue()); assertEquals(-1, ((StrongCounterConfiguration) counterConfig).lifespan()); assertEquals(Storage.VOLATILE, counterConfig.storage()); return; } } fail(); } private void assertWeakCounter(CounterManagerConfiguration config) { for (AbstractCounterConfiguration counterConfig : config.counters().values()) { if (counterConfig.name().equals("weak-5")) { assertTrue(counterConfig instanceof WeakCounterConfiguration); assertEquals(5, counterConfig.initialValue()); assertEquals(Storage.VOLATILE, counterConfig.storage()); assertEquals(10, ((WeakCounterConfiguration) counterConfig).concurrencyLevel()); return; } } fail(); } private void assertBoundedStrongCounter(CounterManagerConfiguration config, String name, long initialValue, long min, long max, long lifespan, Storage storage) { for (AbstractCounterConfiguration counterConfig : config.counters().values()) { if (counterConfig.name().equals(name)) { assertTrue(counterConfig instanceof StrongCounterConfiguration); assertEquals(initialValue, counterConfig.initialValue()); assertEquals(storage, counterConfig.storage()); assertTrue(((StrongCounterConfiguration) counterConfig).isBound()); assertEquals(min, ((StrongCounterConfiguration) counterConfig).lowerBound()); assertEquals(max, ((StrongCounterConfiguration) counterConfig).upperBound()); assertEquals(lifespan, ((StrongCounterConfiguration) counterConfig).lifespan()); return; } } fail(); } private void assertCounterConfigurationException(GlobalConfigurationBuilder builder) { try { builder.build(); fail("CacheConfigurationExpected"); } catch (CounterConfigurationException | CacheConfigurationException expected) { log.trace("Expected", expected); } } public void testLocalManagerNotStarted() { withCacheManager(TestCacheManagerFactory.createCacheManager(false), cm -> expectException(IllegalLifecycleStateException.class, () -> EmbeddedCounterManagerFactory.asCounterManager(cm))); } }
17,884
48.542936
131
java
null
infinispan-main/counter/src/test/java/org/infinispan/counter/LocalWeakCounterTest.java
package org.infinispan.counter; import org.infinispan.configuration.global.GlobalConfigurationBuilder; import org.testng.annotations.Test; /** * A simple consistency test for local {@link org.infinispan.counter.api.WeakCounter}. * * @author Pedro Ruivo * @since 9.2 */ @Test(groups = "functional", testName = "counter.LocalWeakCounterTest") public class LocalWeakCounterTest extends WeakCounterTest { @Override protected int clusterSize() { return 1; } @Override protected GlobalConfigurationBuilder configure(int nodeId) { return new GlobalConfigurationBuilder(); } }
608
23.36
86
java
null
infinispan-main/counter/src/test/java/org/infinispan/counter/BoundedCounterNotificationTest.java
package org.infinispan.counter; import static org.testng.AssertJUnit.assertTrue; import java.lang.reflect.Method; import org.infinispan.counter.api.CounterConfiguration; import org.infinispan.counter.api.CounterManager; import org.infinispan.counter.api.CounterState; import org.infinispan.counter.api.CounterType; import org.infinispan.counter.api.Handle; import org.infinispan.counter.api.StrongCounter; import org.infinispan.counter.util.StrongTestCounter; import org.infinispan.counter.util.TestCounter; import org.testng.annotations.Test; /** * Notification test for threshold aware counters. * * @author Pedro Ruivo * @since 9.0 */ @Test(groups = "functional", testName = "counter.BoundedCounterNotificationTest") public class BoundedCounterNotificationTest extends AbstractCounterNotificationTest { public void testThreshold(Method method) throws Exception { final String counterName = method.getName(); final StrongCounter[] counters = new StrongCounter[clusterSize()]; for (int i = 0; i < clusterSize(); ++i) { counters[i] = createCounter(counterManager(i), counterName, -2, 2); } Handle<ListenerQueue> l = counters[0].addListener(new ListenerQueue(counterName)); if (counters.length != CLUSTER_SIZE) { for (int i = 0; i < CLUSTER_SIZE; ++i) { counters[0].incrementAndGet(); } } else { for (StrongCounter counter : counters) { counter.incrementAndGet(); } } l.getCounterListener().assertEvent(0, CounterState.VALID, 1, CounterState.VALID); l.getCounterListener().assertEvent(1, CounterState.VALID, 2, CounterState.VALID); l.getCounterListener().assertEvent(2, CounterState.VALID, 2, CounterState.UPPER_BOUND_REACHED); //as soon as threshold is reached, no more events are triggered. assertTrue(l.getCounterListener().queue.isEmpty()); eventuallyEquals(2L, () -> counters[0].sync().getValue()); if (counters.length != CLUSTER_SIZE) { for (int i = 0; i < CLUSTER_SIZE; ++i) { counters[0].decrementAndGet(); } } else { for (StrongCounter counter : counters) { counter.decrementAndGet(); } } l.getCounterListener().assertEvent(2, CounterState.UPPER_BOUND_REACHED, 1, CounterState.VALID); l.getCounterListener().assertEvent(1, CounterState.VALID, 0, CounterState.VALID); l.getCounterListener().assertEvent(0, CounterState.VALID, -1, CounterState.VALID); l.getCounterListener().assertEvent(-1, CounterState.VALID, -2, CounterState.VALID); eventuallyEquals(-2L, () -> counters[0].sync().getValue()); counters[0].decrementAndGet(); counters[0].decrementAndGet(); l.getCounterListener().assertEvent(-2, CounterState.VALID, -2, CounterState.LOWER_BOUND_REACHED); //as soon as threshold is reached, no more events are triggered. assertTrue(l.getCounterListener().queue.isEmpty()); eventuallyEquals(-2L, () -> counters[0].sync().getValue()); //removes the listener l.remove(); counters[0].incrementAndGet(); counters[0].incrementAndGet(); assertTrue(l.getCounterListener().queue.isEmpty()); } protected TestCounter createCounter(CounterManager counterManager, String counterName) { return new StrongTestCounter(createCounter(counterManager, counterName, Long.MIN_VALUE, Long.MAX_VALUE)); } private StrongCounter createCounter(CounterManager counterManager, String counterName, long min, long max) { counterManager.defineCounter(counterName, CounterConfiguration.builder(CounterType.BOUNDED_STRONG).lowerBound(min).upperBound(max).build()); return counterManager.getStrongCounter(counterName); } }
3,793
38.113402
111
java
null
infinispan-main/counter/src/test/java/org/infinispan/counter/RestartCounterTest.java
package org.infinispan.counter; import static org.infinispan.commons.test.CommonsTestingUtil.tmpDirectory; import static org.testng.AssertJUnit.assertFalse; import static org.testng.AssertJUnit.assertTrue; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Collection; import java.util.stream.Collectors; import org.infinispan.commons.util.Util; import org.infinispan.configuration.global.GlobalConfigurationBuilder; import org.infinispan.counter.api.CounterConfiguration; import org.infinispan.counter.api.CounterManager; import org.infinispan.counter.api.CounterType; import org.infinispan.counter.api.Storage; import org.infinispan.counter.configuration.CounterManagerConfigurationBuilder; import org.infinispan.counter.impl.BaseCounterTest; import org.infinispan.counter.impl.CounterModuleLifecycle; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.test.fwk.CleanupAfterMethod; import org.testng.annotations.AfterMethod; import org.testng.annotations.Test; /** * @author Pedro Ruivo * @since 9.0 */ @Test(groups = "functional", testName = "counter.RestartCounterTest") @CleanupAfterMethod public class RestartCounterTest extends BaseCounterTest { private static final String PERSISTENT_FOLDER = tmpDirectory(RestartCounterTest.class.getSimpleName()); private static final String TEMP_PERSISTENT_FOLDER = Paths.get(PERSISTENT_FOLDER, "temp").toString(); private static final String SHARED_PERSISTENT_FOLDER = Paths.get(PERSISTENT_FOLDER, "shared").toString(); private static final int CLUSTER_SIZE = 4; private final Collection<CounterDefinition> defaultCounters = new ArrayList<>(6); private final Collection<CounterDefinition> otherCounters = new ArrayList<>(6); public RestartCounterTest() { defaultCounters.add(new CounterDefinition("v-bounded", CounterType.BOUNDED_STRONG, Storage.VOLATILE)); defaultCounters.add(new CounterDefinition("p-bounded", CounterType.BOUNDED_STRONG, Storage.PERSISTENT)); defaultCounters.add(new CounterDefinition("v-unbounded", CounterType.UNBOUNDED_STRONG, Storage.VOLATILE)); defaultCounters.add(new CounterDefinition("p-unbounded", CounterType.UNBOUNDED_STRONG, Storage.PERSISTENT)); defaultCounters.add(new CounterDefinition("v-weak", CounterType.WEAK, Storage.VOLATILE)); defaultCounters.add(new CounterDefinition("p-weak", CounterType.WEAK, Storage.PERSISTENT)); otherCounters.add(new CounterDefinition("o-v-bounded", CounterType.BOUNDED_STRONG, Storage.VOLATILE)); otherCounters.add(new CounterDefinition("o-p-bounded", CounterType.BOUNDED_STRONG, Storage.PERSISTENT)); otherCounters.add(new CounterDefinition("o-v-unbounded", CounterType.UNBOUNDED_STRONG, Storage.VOLATILE)); otherCounters.add(new CounterDefinition("o-p-unbounded", CounterType.UNBOUNDED_STRONG, Storage.PERSISTENT)); otherCounters.add(new CounterDefinition("o-v-weak", CounterType.WEAK, Storage.VOLATILE)); otherCounters.add(new CounterDefinition("o-p-weak", CounterType.WEAK, Storage.PERSISTENT)); } private static void incrementAll(Collection<CounterDefinition> counters, CounterManager counterManager) { counters.forEach(counterDefinition -> counterDefinition.incrementCounter(counterManager)); } @AfterMethod(alwaysRun = true) public void removeFiles() { Util.recursiveFileRemove(PERSISTENT_FOLDER); } public void testCountersInConfiguration() { assertDefined(defaultCounters); //while the retries during state transfer aren't fixed, we need to wait for the cache to start everywhere waitForClusterToForm(CounterModuleLifecycle.COUNTER_CACHE_NAME); incrementAll(defaultCounters, counterManager(0)); assertCounterValue(defaultCounters, counterManager(0), 1, 1); shutdownAndRestart(); assertDefined(defaultCounters); assertCounterValue(defaultCounters, counterManager(0), 0, 1); incrementAll(defaultCounters, counterManager(0)); assertCounterValue(defaultCounters, counterManager(0), 1, 2); } public void testRuntimeCounters() { final CounterManager counterManager = counterManager(0); //while the retries during state transfer aren't fixed, we need to wait for the cache to start everywhere waitForClusterToForm(CounterModuleLifecycle.COUNTER_CACHE_NAME); incrementAll(defaultCounters, counterManager); incrementAll(defaultCounters, counterManager); otherCounters.forEach(counterDefinition -> counterDefinition.define(counterManager)); incrementAll(otherCounters, counterManager); assertCounterValue(defaultCounters, counterManager, 2, 2); assertCounterValue(otherCounters, counterManager, 1, 1); shutdownAndRestart(); //recreate the counter manager. final CounterManager counterManager2 = counterManager(0); Collection<CounterDefinition> othersPersisted = otherCounters.stream() .filter(counterDefinition -> counterDefinition.storage == Storage.PERSISTENT).collect( Collectors.toList()); Collection<CounterDefinition> otherVolatile = otherCounters.stream() .filter(counterDefinition -> counterDefinition.storage == Storage.VOLATILE).collect( Collectors.toList()); assertDefined(defaultCounters); assertDefined(othersPersisted); assertNotDefined(otherVolatile); assertCounterValue(defaultCounters, counterManager2, 0, 2); assertCounterValue(othersPersisted, counterManager2, -1 /*doesn't mather*/, 1); incrementAll(defaultCounters, counterManager2); incrementAll(othersPersisted, counterManager2); assertCounterValue(defaultCounters, counterManager2, 1, 3); assertCounterValue(othersPersisted, counterManager2, -1 /*doesn't mather*/, 2); } @Override protected int clusterSize() { return CLUSTER_SIZE; } @Override protected GlobalConfigurationBuilder configure(int nodeId) { GlobalConfigurationBuilder builder = GlobalConfigurationBuilder.defaultClusteredBuilder(); builder.globalState().enable().persistentLocation(Paths.get(PERSISTENT_FOLDER, Integer.toString(nodeId)).toString()) .temporaryLocation(Paths.get(TEMP_PERSISTENT_FOLDER, Integer.toString(nodeId)).toString()) .sharedPersistentLocation(Paths.get(SHARED_PERSISTENT_FOLDER, Integer.toString(nodeId)).toString()); CounterManagerConfigurationBuilder counterBuilder = builder.addModule(CounterManagerConfigurationBuilder.class); defaultCounters.forEach(counterDefinition -> counterDefinition.define(counterBuilder)); return builder; } private void shutdownAndRestart() { cache(0, CounterModuleLifecycle.COUNTER_CACHE_NAME).shutdown(); log.debug("Shutdown caches"); cacheManagers.forEach(EmbeddedCacheManager::stop); cacheManagers.clear(); log.debug("Restart caches"); createCacheManagers(); } private void assertDefined(Collection<CounterDefinition> counters) { for (int i = 0; i < CLUSTER_SIZE; ++i) { CounterManager counterManager = counterManager(i); for (CounterDefinition definition : counters) { assertTrue("Configuration of " + definition.name + " is missing on manager " + i, counterManager.isDefined(definition.name)); } } } private void assertNotDefined(Collection<CounterDefinition> counters) { for (int i = 0; i < CLUSTER_SIZE; ++i) { CounterManager counterManager = counterManager(i); for (CounterDefinition definition : counters) { assertFalse("Configuration of " + definition.name + " is defined on manager " + i, counterManager.isDefined(definition.name)); } } } private void assertCounterValue(Collection<CounterDefinition> counters, CounterManager counterManager, long volatileValue, long persistentValue) { for (CounterDefinition definition : counters) { long expect = definition.storage == Storage.VOLATILE ? volatileValue : persistentValue; eventuallyEquals("Wrong value for counter " + definition.name, expect, () -> definition.getValue(counterManager)); } } private static class CounterDefinition { private final String name; private final CounterType type; private final Storage storage; private CounterDefinition(String name, CounterType type, Storage storage) { this.name = name; this.type = type; this.storage = storage; } private void define(CounterManagerConfigurationBuilder builder) { switch (type) { case UNBOUNDED_STRONG: builder.addStrongCounter().name(name).storage(storage); break; case BOUNDED_STRONG: builder.addStrongCounter().name(name).lowerBound(0).storage(storage); break; case WEAK: builder.addWeakCounter().name(name).storage(storage).concurrencyLevel(16); } } private void define(CounterManager manager) { //lower bound is ignored if the type is not bounded. manager.defineCounter(name, CounterConfiguration.builder(type).lowerBound(0).storage(storage).build()); } private void incrementCounter(CounterManager counterManager) { switch (type) { case UNBOUNDED_STRONG: case BOUNDED_STRONG: counterManager.getStrongCounter(name).sync().incrementAndGet(); break; case WEAK: counterManager.getWeakCounter(name).sync().increment(); break; } } private long getValue(CounterManager counterManager) { switch (type) { case WEAK: return counterManager.getWeakCounter(name).getValue(); case BOUNDED_STRONG: case UNBOUNDED_STRONG: return counterManager.getStrongCounter(name).sync().getValue(); } throw new IllegalStateException(); } } }
10,118
42.995652
122
java
null
infinispan-main/counter/src/test/java/org/infinispan/counter/LocalStrongCounterNotificationTest.java
package org.infinispan.counter; import org.infinispan.configuration.global.GlobalConfigurationBuilder; import org.testng.annotations.Test; /** * Notification test for local {@link org.infinispan.counter.api.StrongCounter}. * * @author Pedro Ruivo * @since 9.2 */ @Test(groups = "functional", testName = "counter.LocalStrongCounterNotificationTesta") public class LocalStrongCounterNotificationTest extends StrongCounterNotificationTest { @Override protected int clusterSize() { return 1; } @Override protected GlobalConfigurationBuilder configure(int nodeId) { return new GlobalConfigurationBuilder(); } }
645
24.84
87
java
null
infinispan-main/counter/src/test/java/org/infinispan/counter/AbstractCounterNotificationTest.java
package org.infinispan.counter; import static java.lang.String.format; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertNotNull; import static org.testng.AssertJUnit.assertTrue; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; import org.infinispan.counter.api.CounterEvent; import org.infinispan.counter.api.CounterListener; import org.infinispan.counter.api.CounterManager; import org.infinispan.counter.api.CounterState; import org.infinispan.counter.api.Handle; import org.infinispan.counter.impl.BaseCounterTest; import org.infinispan.counter.util.TestCounter; import org.infinispan.util.logging.Log; import org.infinispan.util.logging.LogFactory; import org.testng.annotations.Test; /** * A notification test for the counters. * * @author Pedro Ruivo * @since 9.0 */ @Test(groups = "functional") public abstract class AbstractCounterNotificationTest extends BaseCounterTest { static final int CLUSTER_SIZE = 4; private static void incrementInEachCounter(TestCounter[] counters) { if (counters.length != CLUSTER_SIZE) { for (int i = 0; i < CLUSTER_SIZE; ++i) { counters[0].increment(); } } else { for (TestCounter counter : counters) { counter.increment(); } } } private static void decrementInEachCounter(TestCounter[] counters) { if (counters.length != CLUSTER_SIZE) { for (int i = 0; i < CLUSTER_SIZE; ++i) { counters[0].decrement(); } } else { for (TestCounter counter : counters) { counter.decrement(); } } } public void testSimpleListener(Method method) throws Exception { final String counterName = method.getName(); final TestCounter[] counters = new TestCounter[clusterSize()]; for (int i = 0; i < clusterSize(); ++i) { counters[i] = createCounter(counterManager(i), counterName); } Handle<ListenerQueue> l = counters[0].addListener(new ListenerQueue(counterName)); incrementInEachCounter(counters); ListenerQueue lq = l.getCounterListener(); printQueue(lq); lq.assertEvent(0, CounterState.VALID, 1, CounterState.VALID); lq.assertEvent(1, CounterState.VALID, 2, CounterState.VALID); lq.assertEvent(2, CounterState.VALID, 3, CounterState.VALID); lq.assertEvent(3, CounterState.VALID, 4, CounterState.VALID); assertEquals(4L, counters[0].getValue()); l.remove(); incrementInEachCounter(counters); assertTrue(l.getCounterListener().queue.isEmpty()); } public void testMultipleListeners(Method method) throws InterruptedException { final String counterName = method.getName(); final TestCounter[] counters = new TestCounter[clusterSize()]; final List<Handle<ListenerQueue>> listeners = new ArrayList<>(clusterSize()); for (int i = 0; i < clusterSize(); ++i) { counters[i] = createCounter(counterManager(i), counterName); listeners.add(counters[i].addListener(new ListenerQueue(counterName + "-listener-" + i))); } incrementInEachCounter(counters); for (int i = 0; i < clusterSize(); ++i) { ListenerQueue lq = listeners.get(i).getCounterListener(); printQueue(lq); lq.assertEvent(0, CounterState.VALID, 1, CounterState.VALID); lq.assertEvent(1, CounterState.VALID, 2, CounterState.VALID); lq.assertEvent(2, CounterState.VALID, 3, CounterState.VALID); lq.assertEvent(3, CounterState.VALID, 4, CounterState.VALID); assertEquals(4L, counters[i].getValue()); } } public void testExceptionInListener(Method method) throws InterruptedException { final String counterName = method.getName(); final TestCounter[] counters = new TestCounter[clusterSize()]; for (int i = 0; i < clusterSize(); ++i) { counters[i] = createCounter(counterManager(i), counterName); } counters[0].addListener(event -> { throw new RuntimeException("expected 1"); }); final Handle<ListenerQueue> l1 = counters[0].addListener(new ListenerQueue(counterName + "-listener-1")); counters[0].addListener(event -> { throw new RuntimeException("expected 2"); }); final Handle<ListenerQueue> l2 = counters[0].addListener(new ListenerQueue(counterName + "-listener-2")); incrementInEachCounter(counters); ListenerQueue lq = l1.getCounterListener(); printQueue(lq); lq.assertEvent(0, CounterState.VALID, 1, CounterState.VALID); lq.assertEvent(1, CounterState.VALID, 2, CounterState.VALID); lq.assertEvent(2, CounterState.VALID, 3, CounterState.VALID); lq.assertEvent(3, CounterState.VALID, 4, CounterState.VALID); lq = l2.getCounterListener(); printQueue(lq); lq.assertEvent(0, CounterState.VALID, 1, CounterState.VALID); lq.assertEvent(1, CounterState.VALID, 2, CounterState.VALID); lq.assertEvent(2, CounterState.VALID, 3, CounterState.VALID); lq.assertEvent(3, CounterState.VALID, 4, CounterState.VALID); assertEquals(4L, counters[0].getValue()); decrementInEachCounter(counters); lq = l1.getCounterListener(); printQueue(lq); lq.assertEvent(4, CounterState.VALID, 3, CounterState.VALID); lq.assertEvent(3, CounterState.VALID, 2, CounterState.VALID); lq.assertEvent(2, CounterState.VALID, 1, CounterState.VALID); lq.assertEvent(1, CounterState.VALID, 0, CounterState.VALID); lq = l2.getCounterListener(); printQueue(lq); lq.assertEvent(4, CounterState.VALID, 3, CounterState.VALID); lq.assertEvent(3, CounterState.VALID, 2, CounterState.VALID); lq.assertEvent(2, CounterState.VALID, 1, CounterState.VALID); lq.assertEvent(1, CounterState.VALID, 0, CounterState.VALID); } @Override protected int clusterSize() { return CLUSTER_SIZE; } protected abstract TestCounter createCounter(CounterManager counterManager, String counterName); private void printQueue(ListenerQueue queue) { log.tracef("Queue is " + queue); } static class ListenerQueue implements CounterListener { private static final Log log = LogFactory.getLog(ListenerQueue.class); final BlockingQueue<CounterEvent> queue; final String name; ListenerQueue(String name) { queue = new LinkedBlockingQueue<>(); this.name = name; } @Override public void onUpdate(CounterEvent event) { try { queue.put(event); if (log.isTraceEnabled()) { log.tracef("[%s] add event %s", name, event); } } catch (InterruptedException e) { log.errorf(e, "[%s] interrupted while adding event %s", name, event); } } @Override public String toString() { return "ListenerQueue{" + "name=" + name + ", queue=" + queue + '}'; } void assertEvent(long oldValue, CounterState oldState, long newValue, CounterState newState) throws InterruptedException { CounterEvent event = queue.poll(30, TimeUnit.SECONDS); assertNotNull("[" + name + "] Event not found", event); assertEquals(format("[%s] Wrong old value for event: %s.", name, event), oldValue, event.getOldValue()); assertEquals(format("[%s] Wrong old state for event: %s.", name, event), oldState, event.getOldState()); assertEquals(format("[%s] Wrong new value for event: %s.", name, event), newValue, event.getNewValue()); assertEquals(format("[%s] Wrong new state for event: %s.", name, event), newState, event.getNewState()); } } }
7,948
36.14486
113
java
null
infinispan-main/counter/src/test/java/org/infinispan/counter/CounterStressTest.java
package org.infinispan.counter; import static org.infinispan.counter.EmbeddedCounterManagerFactory.asCounterManager; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.Callable; import java.util.concurrent.CyclicBarrier; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.counter.api.CounterConfiguration; import org.infinispan.counter.api.CounterManager; import org.infinispan.counter.api.CounterType; import org.infinispan.counter.util.StrongTestCounter; import org.infinispan.counter.util.TestCounter; import org.infinispan.counter.util.WeakTestCounter; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.test.MultipleCacheManagersTest; import org.testng.AssertJUnit; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; /** * Stress test for the multiple counter types. * * @author Pedro Ruivo * @since 9.0 */ @Test(groups = "stress", testName = "counter.CounterStressTest") public class CounterStressTest extends MultipleCacheManagersTest { private static final long TEST_DURATION_MILLIS = TimeUnit.MINUTES.toMillis(2); private static final double NANOS_TO_MILLIS = 0.000001; private static final double MILLIS_TO_SEC = 0.001; private static final int CLUSTER_SIZE = 8; private Reports report; //input(nanoseconds) => output(milliseconds) private static double[] awaitResults(List<Future<Long>> results) throws ExecutionException, InterruptedException { double[] millis = new double[results.size()]; int idx = 0; for (Future<Long> result : results) { millis[idx++] = result.get() * NANOS_TO_MILLIS; } return millis; } private static void printRow(int threads, Result result) { double sum = 0; double min = Double.MAX_VALUE; double max = Double.MIN_VALUE; for (double d : result.millis) { sum += d; min = Math.min(d, min); max = Math.max(d, max); } System.out.printf("%d | %s |", threads, result.factoryName); double avg = sum / result.millis.length; System.out.printf("avg=%,.2f, min=%,.2f, max=%,.2f |", avg, min, max); double avgSec = avg * MILLIS_TO_SEC; System.out.printf("%,.2f%n", result.operations / avgSec); } @BeforeClass(alwaysRun = true) public void init() { report = new Reports(); } @AfterClass(alwaysRun = true) public void report() { report.printReport(); } @Test(dataProvider = "threads") public void stress(final int threadsPerNode, final TestCounterFactory factory) throws ExecutionException, InterruptedException { final int threads = threadsPerNode * CLUSTER_SIZE; final CyclicBarrier barrier = new CyclicBarrier(threads); final List<Future<Long>> results = new ArrayList<>(threads); final String counterName = String.format("%s_%d", factory.factoryName(), threadsPerNode); final AtomicBoolean stop = new AtomicBoolean(false); System.out.println("== STRESS TEST STARTED =="); System.out.printf("Factory='%s'%nThreads/Node=%d%nCluster=%d%nCounter name='%s'%n", factory.factoryName(), threadsPerNode, CLUSTER_SIZE, counterName); for (int c = 0; c < CLUSTER_SIZE; ++c) { final TestCounter counter = factory.getCounter(manager(c), counterName); for (int t = 0; t < threadsPerNode; ++t) { results.add(fork(new StressCallable(counter, barrier, stop))); } } System.out.printf("== THREADS CREATED (%d/%d) ==%n", results.size(), threads); Thread.sleep(TEST_DURATION_MILLIS); stop.set(true); double[] millis = awaitResults(results); System.out.println("== STRESS TEST FINISHED =="); long[] countersValues = new long[CLUSTER_SIZE]; for (int c = 0; c < CLUSTER_SIZE; ++c) { countersValues[c] = factory.getCounter(manager(c), counterName).getValue(); } this.report.add(threads, factory, millis, countersValues[0]); for (int c = 1; c < CLUSTER_SIZE; ++c) { AssertJUnit.assertEquals("StrongCounter mismatch for manager " + c, countersValues[0], countersValues[c]); } } @Override protected void createCacheManagers() throws Throwable { ConfigurationBuilder builder = getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC); builder.clustering().hash().numOwners(2); createClusteredCaches(CLUSTER_SIZE, builder); } @DataProvider(name = "threads") private Object[][] threadPerNode() { return new Object[][]{ {2, Factories.ATOMIC}, {2, Factories.THRESHOLD}, {2, Factories.WEAK}, {4, Factories.ATOMIC}, {4, Factories.THRESHOLD}, {4, Factories.WEAK}, {8, Factories.ATOMIC}, {8, Factories.THRESHOLD}, {8, Factories.WEAK}, {16, Factories.ATOMIC}, {16, Factories.THRESHOLD}, {16, Factories.WEAK}}; } private enum Factories implements TestCounterFactory { ATOMIC { @Override public TestCounter getCounter(EmbeddedCacheManager manager, String counterName) { CounterManager counterManager = asCounterManager(manager); counterManager .defineCounter(counterName, CounterConfiguration.builder(CounterType.UNBOUNDED_STRONG).build()); return new StrongTestCounter(counterManager.getStrongCounter(counterName)); } }, THRESHOLD { @Override public TestCounter getCounter(EmbeddedCacheManager manager, String counterName) { CounterManager counterManager = asCounterManager(manager); counterManager.defineCounter(counterName, CounterConfiguration.builder(CounterType.BOUNDED_STRONG).upperBound(Long.MAX_VALUE) .lowerBound(Long.MIN_VALUE) .build()); return new StrongTestCounter(counterManager.getStrongCounter(counterName)); } }, WEAK { @Override public TestCounter getCounter(EmbeddedCacheManager manager, String counterName) { CounterManager counterManager = asCounterManager(manager); counterManager.defineCounter(counterName, CounterConfiguration.builder(CounterType.WEAK).build()); return new WeakTestCounter(asCounterManager(manager).getWeakCounter(counterName)); } }; @Override public String factoryName() { return name(); } } private interface TestCounterFactory { TestCounter getCounter(EmbeddedCacheManager manager, String counterName); String factoryName(); } private static class Reports { private final Map<Integer, List<Result>> reports; private Reports() { reports = new HashMap<>(); } void add(int threads, TestCounterFactory factory, double[] rawResultsMillis, long operations) { List<Result> resultList = reports.computeIfAbsent(threads, t -> new ArrayList<>(3)); resultList.add(new Result(factory.factoryName(), rawResultsMillis, operations)); } void printReport() { System.out.println("== RESULTS =="); System.out.println("Threads | Factory | Total Time (ms) | Throughput (op/sec)"); for (Map.Entry<Integer, List<Result>> entry : reports.entrySet()) { int threads = entry.getKey(); List<Result> results = entry.getValue(); for (Result result : results) { printRow(threads, result); } } System.out.println("== RESULTS =="); } } private static class Result { private final String factoryName; private final double[] millis; private final long operations; private Result(String factoryName, double[] millis, long operations) { this.factoryName = factoryName; this.millis = millis; this.operations = operations; } } private class StressCallable implements Callable<Long> { private final TestCounter counter; private final CyclicBarrier barrier; private final AtomicBoolean stop; private StressCallable(TestCounter counter, CyclicBarrier barrier, AtomicBoolean stop) { this.counter = counter; this.barrier = barrier; this.stop = stop; } @Override public Long call() throws Exception { try { barrier.await(); final long start = System.nanoTime(); while (!stop.get()) { try { counter.increment(); } catch (Exception e) { log.error("Error incrementing counter.", e); } } final long end = System.nanoTime(); barrier.await(); return end - start; } catch (Exception e) { log.error("Unexpected Exception", e); throw e; } } } }
9,421
33.767528
117
java
null
infinispan-main/counter/src/test/java/org/infinispan/counter/StrongCounterTest.java
package org.infinispan.counter; import static java.lang.String.format; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertFalse; import static org.testng.AssertJUnit.assertTrue; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Set; import java.util.concurrent.CyclicBarrier; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicIntegerArray; import org.infinispan.counter.api.CounterConfiguration; import org.infinispan.counter.api.CounterManager; import org.infinispan.counter.api.CounterType; import org.infinispan.counter.util.StrongTestCounter; import org.testng.annotations.Test; /** * A simple consistency test for {@link org.infinispan.counter.api.StrongCounter}. * * @author Pedro Ruivo * @since 9.0 */ @Test(groups = "functional", testName = "counter.StrongCounterTest") public class StrongCounterTest extends AbstractCounterTest<StrongTestCounter> { private static final int CLUSTER_SIZE = 4; public void testUniqueReturnValues(Method method) throws ExecutionException, InterruptedException, TimeoutException { //local mode will have 8 concurrent thread, cluster mode will have 8 concurrent threads (4 nodes, 2 threads per node) final int numThreadsPerNode = clusterSize() == 1 ? 8 : 2; final int totalThreads = clusterSize() * numThreadsPerNode; final List<Future<List<Long>>> workers = new ArrayList<>(totalThreads); final String counterName = method.getName(); final CyclicBarrier barrier = new CyclicBarrier(totalThreads); final long counterLimit = 1000; for (int i = 0; i < totalThreads; ++i) { final int cmIndex = i % clusterSize(); workers.add(fork(() -> { List<Long> retValues = new LinkedList<>(); CounterManager manager = counterManager(cmIndex); StrongTestCounter counter = createCounter(manager, counterName, 0); long lastRet = 0; barrier.await(); while (lastRet < counterLimit) { lastRet = counter.addAndGet(1); retValues.add(lastRet); } return retValues; })); } final Set<Long> uniqueValuesCheck = new HashSet<>(); for (Future<List<Long>> w : workers) { List<Long> returnValues = w.get(1, TimeUnit.MINUTES); for (Long l : returnValues) { assertTrue(format("Duplicated value %d", l), uniqueValuesCheck.add(l)); } } for (long l = 1; l < (counterLimit + 3); ++l) { assertTrue(format("Value %d does not exists!", l), uniqueValuesCheck.contains(l)); } } public void testCompareAndSet(Method method) { final String counterName = method.getName(); TestContext context = new TestContext(); context.printSeed(counterName); long expect = context.random.nextLong(); long value = context.random.nextLong(); StrongTestCounter counter = createCounter(counterManager(0), counterName, expect); for (int i = 0; i < 10; ++i) { assertTrue(counter.compareAndSet(expect, value)); assertEquals(value, counter.getValue()); expect = value; value = context.random.nextLong(); } for (int i = 0; i < 10; ++i) { long notExpected = context.random.nextLong(); while (expect == notExpected) { notExpected = context.random.nextLong(); } assertFalse(counter.compareAndSet(notExpected, value)); assertEquals(expect, counter.getValue()); } } public void testCompareAndSwap(Method method) { final String counterName = method.getName(); TestContext context = new TestContext(); context.printSeed(counterName); long expect = context.random.nextLong(); long value = context.random.nextLong(); StrongTestCounter counter = createCounter(counterManager(0), counterName, expect); for (int i = 0; i < 10; ++i) { assertEquals(expect, counter.compareAndSwap(expect, value)); assertEquals(value, counter.getValue()); expect = value; value = context.random.nextLong(); } for (int i = 0; i < 10; ++i) { long notExpected = context.random.nextLong(); while (expect == notExpected) { notExpected = context.random.nextLong(); } assertEquals(expect, counter.compareAndSwap(notExpected, value)); assertEquals(expect, counter.getValue()); } } @Test(groups = "unstable", description = "ISPN-8786") public void testCompareAndSetConcurrent(Method method) throws ExecutionException, InterruptedException, TimeoutException { //local mode will have 8 concurrent thread, cluster mode will have 8 concurrent threads (4 nodes, 2 threads per node) final int numThreadsPerNode = clusterSize() == 1 ? 8 : 2; final int totalThreads = clusterSize() * numThreadsPerNode; final List<Future<Boolean>> workers = new ArrayList<>(totalThreads); final String counterName = method.getName(); final CyclicBarrier barrier = new CyclicBarrier(totalThreads); final AtomicIntegerArray retValues = new AtomicIntegerArray(totalThreads); final long maxIterations = 100; for (int i = 0; i < totalThreads; ++i) { final int threadIndex = i; final int cmIndex = i % clusterSize(); workers.add(fork(() -> { long iteration = 0; final long initialValue = 0; long previousValue = initialValue; CounterManager manager = counterManager(cmIndex); StrongTestCounter counter = createCounter(manager, counterName, initialValue); while (iteration < maxIterations) { assertEquals(previousValue, counter.getValue()); long update = previousValue + 1; barrier.await(); //all threads calling compareAndSet at the same time, only one should succeed boolean ret = counter.compareAndSet(previousValue, update); if (ret) { previousValue = update; } else { previousValue = counter.getValue(); } retValues.set(threadIndex, ret ? 1 : 0); barrier.await(); assertUnique(retValues, iteration); ++iteration; } return true; })); } for (Future<?> w : workers) { w.get(1, TimeUnit.MINUTES); } } public void testCompareAndSwapConcurrent(Method method) throws ExecutionException, InterruptedException, TimeoutException { //local mode will have 8 concurrent thread, cluster mode will have 8 concurrent threads (4 nodes, 2 threads per node) final int numThreadsPerNode = clusterSize() == 1 ? 8 : 2; final int totalThreads = clusterSize() * numThreadsPerNode; final List<Future<Boolean>> workers = new ArrayList<>(totalThreads); final String counterName = method.getName(); final CyclicBarrier barrier = new CyclicBarrier(totalThreads); final AtomicIntegerArray retValues = new AtomicIntegerArray(totalThreads); final long maxIterations = 100; for (int i = 0; i < totalThreads; ++i) { final int threadIndex = i; final int cmIndex = i % clusterSize(); workers.add(fork(() -> { long iteration = 0; final long initialValue = 0; long previousValue = initialValue; CounterManager manager = counterManager(cmIndex); StrongTestCounter counter = createCounter(manager, counterName, initialValue); while (iteration < maxIterations) { assertEquals(previousValue, counter.getValue()); long update = previousValue + 1; barrier.await(); //all threads calling compareAndSet at the same time, only one should succeed long ret = counter.compareAndSwap(previousValue, update); boolean success = ret == previousValue; previousValue = success ? update : ret; retValues.set(threadIndex, success ? 1 : 0); barrier.await(); assertUnique(retValues, iteration); ++iteration; } return true; })); } for (Future<?> w : workers) { w.get(1, TimeUnit.MINUTES); } } public void testCompareAndSetMaxAndMinLong(Method method) { final String counterName = method.getName(); StrongTestCounter counter = createCounter(counterManager(0), counterName, 0); assertFalse(counter.compareAndSet(-1, Long.MAX_VALUE)); assertEquals(0, counter.getValue()); assertTrue(counter.compareAndSet(0, Long.MAX_VALUE)); assertEquals(Long.MAX_VALUE, counter.getValue()); counter.reset(); assertFalse(counter.compareAndSet(-1, Long.MIN_VALUE)); assertEquals(0, counter.getValue()); assertTrue(counter.compareAndSet(0, Long.MIN_VALUE)); assertEquals(Long.MIN_VALUE, counter.getValue()); } public void testCompareAndSwapMaxAndMinLong(Method method) { final String counterName = method.getName(); StrongTestCounter counter = createCounter(counterManager(0), counterName, 0); assertEquals(0, counter.compareAndSwap(-1, Long.MAX_VALUE)); assertEquals(0, counter.getValue()); assertEquals(0, counter.compareAndSwap(0, Long.MAX_VALUE)); assertEquals(Long.MAX_VALUE, counter.getValue()); counter.reset(); assertEquals(0, counter.compareAndSwap(-1, Long.MIN_VALUE)); assertEquals(0, counter.getValue()); assertEquals(0, counter.compareAndSwap(0, Long.MIN_VALUE)); assertEquals(Long.MIN_VALUE, counter.getValue()); } @Override protected StrongTestCounter createCounter(CounterManager counterManager, String counterName, long initialValue) { counterManager.defineCounter(counterName, CounterConfiguration.builder(CounterType.UNBOUNDED_STRONG).initialValue(initialValue).build()); return new StrongTestCounter(counterManager.getStrongCounter(counterName)); } @Override protected void assertMaxValueAfterMaxValue(StrongTestCounter counter, long delta) { assertEquals(Long.MAX_VALUE, counter.addAndGet(delta)); assertEquals(Long.MAX_VALUE, counter.getValue()); } @Override protected void addAndAssertResult(StrongTestCounter counter, long delta, long expected) { assertEquals(format("Wrong return value after adding %d", delta), expected, counter.addAndGet(delta)); assertEquals("Wrong return value of counter.getNewValue()", expected, counter.getValue()); } @Override protected StrongTestCounter createCounter(CounterManager counterManager, String counterName, CounterConfiguration configuration) { counterManager.defineCounter(counterName, configuration); return new StrongTestCounter(counterManager.getStrongCounter(counterName)); } @Override protected List<CounterConfiguration> configurationToTest() { return Arrays.asList( CounterConfiguration.builder(CounterType.UNBOUNDED_STRONG).initialValue(10).build(), CounterConfiguration.builder(CounterType.UNBOUNDED_STRONG).initialValue(20).build(), CounterConfiguration.builder(CounterType.UNBOUNDED_STRONG).build() ); } @Override protected void assertMinValueAfterMinValue(StrongTestCounter counter, long delta) { assertEquals(Long.MIN_VALUE, counter.addAndGet(delta)); assertEquals(Long.MIN_VALUE, counter.getValue()); } @Override protected int clusterSize() { return CLUSTER_SIZE; } private void assertUnique(AtomicIntegerArray retValues, long it) { int successCount = 0; for (int ix = 0; ix != retValues.length(); ++ix) { successCount += retValues.get(ix); } assertEquals("Multiple threads succeeded with update in iteration " + it, 1, successCount); } }
12,338
40.40604
123
java
null
infinispan-main/counter/src/test/java/org/infinispan/counter/LocalBoundedCounterTest.java
package org.infinispan.counter; import org.infinispan.configuration.global.GlobalConfigurationBuilder; import org.testng.annotations.Test; /** * A simple consistency test for local bounded {@link org.infinispan.counter.api.StrongCounter}. * * @author Pedro Ruivo * @since 9.2 */ @Test(groups = "functional", testName = "counter.LocalBoundedCounterTest") public class LocalBoundedCounterTest extends BoundedCounterTest { @Override protected int clusterSize() { return 1; } @Override protected GlobalConfigurationBuilder configure(int nodeId) { return new GlobalConfigurationBuilder(); } }
627
24.12
96
java
null
infinispan-main/counter/src/test/java/org/infinispan/counter/RemoveCounterTest.java
package org.infinispan.counter; import static org.infinispan.counter.api.CounterConfiguration.builder; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertFalse; import static org.testng.AssertJUnit.assertTrue; import java.lang.reflect.Method; import org.infinispan.counter.api.CounterManager; import org.infinispan.counter.api.CounterType; import org.infinispan.counter.impl.BaseCounterTest; import org.infinispan.counter.impl.CounterModuleLifecycle; import org.infinispan.counter.util.StrongTestCounter; import org.infinispan.counter.util.TestCounter; import org.infinispan.counter.util.WeakTestCounter; import org.testng.annotations.Test; /** * // TODO: Document this * * @author Pedro Ruivo * @since 9.2 */ @Test(groups = "functional", testName = "counter.RemoveCounterTest") public class RemoveCounterTest extends BaseCounterTest { public void testCounterManagerRemoveWithUnbounded(Method method) { testCounterManagerRemove(Factory.UNBOUNDED, method.getName()); } public void testCounterManagerRemoveWithBounded(Method method) { testCounterManagerRemove(Factory.BOUNDED, method.getName()); } public void testCounterManagerRemoveWithWeak(Method method) { testCounterManagerRemove(Factory.WEAK, method.getName()); } public void testCounterManagerRemoveNonExistingWithUnbounded(Method method) { testCounterManagerRemoveNonExisting(Factory.UNBOUNDED, method.getName()); } public void testCounterManagerNonExistingRemoveWithBounded(Method method) { testCounterManagerRemoveNonExisting(Factory.BOUNDED, method.getName()); } public void testCounterManagerNonExistingRemoveWithWeak(Method method) { testCounterManagerRemoveNonExisting(Factory.WEAK, method.getName()); } public void testCounterRemoveWithUnbounded(Method method) { testCounterRemove(Factory.UNBOUNDED, method.getName()); } public void testCounterRemoveWithBounded(Method method) { testCounterRemove(Factory.BOUNDED, method.getName()); } public void testCounterRemoveWithWeak(Method method) { testCounterRemove(Factory.BOUNDED, method.getName()); } @Override protected int clusterSize() { return 3; } private void testCounterRemove(Factory factory, String counterName) { CounterManager manager = counterManager(0); factory.define(manager, counterName); TestCounter counter = factory.get(manager, counterName); assertEquals(10, counter.getValue()); assertTrue(counter.isSame(factory.get(manager, counterName))); assertCounterRemove(counterName, counter, factory); counter.increment(); assertEquals(11, counter.getValue()); assertCounterRemove(counterName, counter, factory); counter.decrement(); assertEquals(9, counter.getValue()); assertCounterRemove(counterName, counter, factory); counter.reset(); assertEquals(10, counter.getValue()); } private void testCounterManagerRemove(Factory factory, String counterName) { CounterManager manager = counterManager(0); factory.define(manager, counterName); TestCounter counter = factory.get(manager, counterName); assertEquals(10, counter.getValue()); assertTrue(counter.isSame(factory.get(manager, counterName))); counter = assertCounterManagerRemove(counterName, counter, factory, 0); counter.increment(); assertEquals(11, counter.getValue()); counter = assertCounterManagerRemove(counterName, counter, factory, 0); counter.decrement(); assertEquals(9, counter.getValue()); counter = assertCounterManagerRemove(counterName, counter, factory, 0); counter.reset(); assertEquals(10, counter.getValue()); } private TestCounter assertCounterManagerRemove(String name, TestCounter counter, Factory factory, int index) { CounterManager manager = counterManager(index); manager.remove(name); assertTrue(cache(0, CounterModuleLifecycle.COUNTER_CACHE_NAME).isEmpty()); TestCounter anotherCounter = factory.get(manager, name); if (counter != null) { assertFalse(counter.isSame(anotherCounter)); } return anotherCounter; } private void assertCounterRemove(String name, TestCounter counter, Factory factory) { CounterManager manager = counterManager(0); counter.remove(); assertTrue(cache(0, CounterModuleLifecycle.COUNTER_CACHE_NAME).isEmpty()); TestCounter anotherCounter = factory.get(manager, name); assertTrue(counter.isSame(anotherCounter)); } private void testCounterManagerRemoveNonExisting(Factory factory, String counterName) { //similar to testCounterManagerRemove but the remove() will be invoked in the CounterManager where the counter instance doesn't exist, CounterManager manager = counterManager(0); factory.define(manager, counterName); TestCounter counter = factory.get(manager, counterName); assertEquals(10, counter.getValue()); assertTrue(counter.isSame(factory.get(manager, counterName))); counter = assertCounterManagerRemove(counterName, counter, factory, 1); counter.increment(); assertEquals(11, counter.getValue()); counter = assertCounterManagerRemove(counterName, counter, factory, 1); counter.decrement(); assertEquals(9, counter.getValue()); counter = assertCounterManagerRemove(counterName, counter, factory, 1); counter.reset(); assertEquals(10, counter.getValue()); } private enum Factory { UNBOUNDED { @Override void define(CounterManager manager, String name) { manager.defineCounter(name, builder(CounterType.UNBOUNDED_STRONG).initialValue(10).build()); } @Override TestCounter get(CounterManager manager, String name) { return new StrongTestCounter(manager.getStrongCounter(name)); } }, BOUNDED { @Override void define(CounterManager manager, String name) { manager.defineCounter(name, builder(CounterType.BOUNDED_STRONG).initialValue(10).lowerBound(0).upperBound(20).build()); } @Override TestCounter get(CounterManager manager, String name) { return new StrongTestCounter(manager.getStrongCounter(name)); } }, WEAK { @Override void define(CounterManager manager, String name) { manager.defineCounter(name, builder(CounterType.WEAK).initialValue(10).build()); } @Override TestCounter get(CounterManager manager, String name) { return new WeakTestCounter(manager.getWeakCounter(name)); } }; abstract void define(CounterManager manager, String name); abstract TestCounter get(CounterManager manager, String name); } }
6,928
35.468421
140
java
null
infinispan-main/counter/src/test/java/org/infinispan/counter/ConfigurationSerializerTest.java
package org.infinispan.counter; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertNotNull; import static org.testng.AssertJUnit.assertTrue; import java.io.IOException; import java.util.Map; import org.infinispan.commons.CacheConfigurationException; import org.infinispan.commons.test.Exceptions; 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.counter.api.Storage; import org.infinispan.counter.configuration.AbstractCounterConfiguration; import org.infinispan.counter.configuration.CounterManagerConfiguration; import org.infinispan.counter.configuration.Reliability; import org.infinispan.counter.configuration.StrongCounterConfiguration; import org.infinispan.counter.configuration.WeakCounterConfiguration; import org.infinispan.counter.exception.CounterConfigurationException; 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 = "counter.ConfigurationSerializerTest") @CleanupAfterMethod public class ConfigurationSerializerTest extends AbstractConfigurationSerializerTest { public void testParser() throws IOException { ConfigurationBuilderHolder holder = new ParserRegistry().parseFile("configs/all/counters.xml"); GlobalConfiguration globalConfiguration = holder.getGlobalConfigurationBuilder().build(); CounterManagerConfiguration counterManagerConfiguration = globalConfiguration .module(CounterManagerConfiguration.class); assertNotNull(counterManagerConfiguration); assertEquals(3, counterManagerConfiguration.numOwners()); assertEquals(Reliability.CONSISTENT, counterManagerConfiguration.reliability()); Map<String, AbstractCounterConfiguration> counters = counterManagerConfiguration.counters(); assertStrongCounter("c1", counters.get("c1"), 1, Storage.PERSISTENT, false, Long.MIN_VALUE, Long.MAX_VALUE, -1); assertStrongCounter("c2", counters.get("c2"), 2, Storage.VOLATILE, true, 0, Long.MAX_VALUE, -1); assertStrongCounter("c3", counters.get("c3"), 3, Storage.PERSISTENT, true, Long.MIN_VALUE, 5, 2000); assertStrongCounter("c4", counters.get("c4"), 4, Storage.VOLATILE, true, 0, 10, 0); assertWeakCounter(counters.get("c5")); } public void testInvalid() { Exceptions.expectException(CacheConfigurationException.class, CounterConfigurationException.class, () -> new ParserRegistry().parseFile("configs/invalid.xml")); } @Override protected void compareExtraGlobalConfiguration(GlobalConfiguration configurationBefore, GlobalConfiguration configurationAfter) { CounterManagerConfiguration configBefore = configurationBefore.module(CounterManagerConfiguration.class); CounterManagerConfiguration configAfter = configurationAfter.module(CounterManagerConfiguration.class); assertEquals(configBefore.numOwners(), configAfter.numOwners()); assertEquals(configBefore.reliability(), configAfter.reliability()); Map<String, AbstractCounterConfiguration> counterConfigBefore = configBefore.counters(); Map<String, AbstractCounterConfiguration> counterConfigAfter = configAfter.counters(); assertSameStrongCounterConfiguration(counterConfigBefore.get("c1"), counterConfigAfter.get("c1")); assertSameStrongCounterConfiguration(counterConfigBefore.get("c2"), counterConfigAfter.get("c2")); assertSameStrongCounterConfiguration(counterConfigBefore.get("c3"), counterConfigAfter.get("c3")); assertSameStrongCounterConfiguration(counterConfigBefore.get("c4"), counterConfigAfter.get("c4")); assertSameWeakCounterConfiguration(counterConfigBefore.get("c5"), counterConfigAfter.get("c5")); } private void assertSameStrongCounterConfiguration(AbstractCounterConfiguration c1, AbstractCounterConfiguration c2) { assertTrue(c1 instanceof StrongCounterConfiguration); assertTrue(c2 instanceof StrongCounterConfiguration); assertEquals(c1.name(), c2.name()); assertEquals(c1.initialValue(), c2.initialValue()); assertEquals(c1.storage(), c2.storage()); assertEquals(((StrongCounterConfiguration) c1).isBound(), ((StrongCounterConfiguration) c2).isBound()); assertEquals(((StrongCounterConfiguration) c1).lowerBound(), ((StrongCounterConfiguration) c2).lowerBound()); assertEquals(((StrongCounterConfiguration) c1).upperBound(), ((StrongCounterConfiguration) c2).upperBound()); } private void assertSameWeakCounterConfiguration(AbstractCounterConfiguration c1, AbstractCounterConfiguration c2) { assertTrue(c1 instanceof WeakCounterConfiguration); assertTrue(c2 instanceof WeakCounterConfiguration); assertEquals(c1.name(), c2.name()); assertEquals(c1.initialValue(), c2.initialValue()); assertEquals(c1.storage(), c2.storage()); assertEquals(((WeakCounterConfiguration) c1).concurrencyLevel(), ((WeakCounterConfiguration) c2).concurrencyLevel()); } private void assertWeakCounter(AbstractCounterConfiguration configuration) { assertTrue(configuration instanceof WeakCounterConfiguration); assertEquals("c5", configuration.name()); assertEquals(5, configuration.initialValue()); assertEquals(Storage.PERSISTENT, configuration.storage()); assertEquals(1, ((WeakCounterConfiguration) configuration).concurrencyLevel()); } private void assertStrongCounter(String name, AbstractCounterConfiguration configuration, long initialValue, Storage storage, boolean bound, long lowerBound, long upperBound, long lifespan) { assertTrue(configuration instanceof StrongCounterConfiguration); assertEquals(name, configuration.name()); assertEquals(initialValue, configuration.initialValue()); assertEquals(storage, configuration.storage()); assertEquals(bound, ((StrongCounterConfiguration) configuration).isBound()); assertEquals(lowerBound, ((StrongCounterConfiguration) configuration).lowerBound()); assertEquals(upperBound, ((StrongCounterConfiguration) configuration).upperBound()); assertEquals(lifespan, ((StrongCounterConfiguration) configuration).lifespan()); } }
6,625
54.680672
166
java
null
infinispan-main/counter/src/test/java/org/infinispan/counter/EagerCacheStartTest.java
package org.infinispan.counter; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertTrue; import org.infinispan.counter.api.CounterConfiguration; import org.infinispan.counter.api.CounterType; import org.infinispan.counter.impl.BaseCounterTest; import org.infinispan.counter.impl.CounterModuleLifecycle; import org.infinispan.manager.EmbeddedCacheManager; import org.testng.annotations.Test; /** * Tests the lazy cache creation * * @author Pedro Ruivo * @since 9.2 */ @Test(groups = "functional", testName = "counter.EagerCacheStartTest") public class EagerCacheStartTest extends BaseCounterTest { public void testLazyStart() { for (EmbeddedCacheManager manager : cacheManagers) { assertTrue(manager.isRunning(CounterModuleLifecycle.COUNTER_CACHE_NAME)); } counterManager(0).defineCounter("some-counter", CounterConfiguration.builder(CounterType.WEAK).build()); assertEquals(0, counterManager(0).getWeakCounter("some-counter").getValue()); } @Override protected int clusterSize() { return 3; } }
1,102
30.514286
110
java
null
infinispan-main/counter/src/test/java/org/infinispan/counter/StrongCounterWithZeroCapacityNodesTest.java
package org.infinispan.counter; import org.infinispan.configuration.global.GlobalConfigurationBuilder; import org.testng.annotations.Test; /** * A simple consistency test for {@link org.infinispan.counter.api.StrongCounter} where some nodes are capacity factor * 0. * * @author Katia Aresti, karesti@redhat.com * @since 9.4 */ @Test(groups = "functional", testName = "counter.StrongCounterWithZeroCapacityNodesTest") public class StrongCounterWithZeroCapacityNodesTest extends StrongCounterTest { @Override protected GlobalConfigurationBuilder configure(int nodeId) { return GlobalConfigurationBuilder.defaultClusteredBuilder().zeroCapacityNode(nodeId % 2 == 1); } }
691
31.952381
118
java
null
infinispan-main/counter/src/test/java/org/infinispan/counter/LocalBoundedCounterNotificationTest.java
package org.infinispan.counter; import org.infinispan.configuration.global.GlobalConfigurationBuilder; import org.testng.annotations.Test; /** * Notification test for threshold aware local counters. * * @author Pedro Ruivo * @since 9.2 */ @Test(groups = "functional", testName = "counter.LocalBoundedCounterNotificationTest") public class LocalBoundedCounterNotificationTest extends BoundedCounterNotificationTest { @Override protected int clusterSize() { return 1; } @Override protected GlobalConfigurationBuilder configure(int nodeId) { return new GlobalConfigurationBuilder(); } }
623
23.96
89
java
null
infinispan-main/counter/src/test/java/org/infinispan/counter/WeakCounterTest.java
package org.infinispan.counter; import static org.testng.AssertJUnit.assertEquals; import java.util.Arrays; import java.util.List; import java.util.concurrent.ExecutionException; import org.infinispan.counter.api.CounterConfiguration; import org.infinispan.counter.api.CounterManager; import org.infinispan.counter.api.CounterType; import org.infinispan.counter.api.WeakCounter; import org.infinispan.counter.util.WeakTestCounter; import org.testng.annotations.Test; /** * A simple consistency test for {@link org.infinispan.counter.api.WeakCounter}. * * @author Pedro Ruivo * @since 9.0 */ @Test(groups = "functional", testName = "counter.WeakCounterTest") public class WeakCounterTest extends AbstractCounterTest<WeakTestCounter> { private static final int CLUSTER_SIZE = 4; public void testSingleConcurrencyLevel() throws ExecutionException, InterruptedException { final CounterManager counterManager = EmbeddedCounterManagerFactory.asCounterManager(manager(0)); final String counterName = "c1-counter"; counterManager.defineCounter(counterName, CounterConfiguration.builder(CounterType.WEAK).concurrencyLevel(1).build()); WeakCounter wc = counterManager.getWeakCounter(counterName); wc.add(2).get(); assertEquals(2, wc.getValue()); } @Override protected void assertMaxValueAfterMaxValue(WeakTestCounter counter, long delta) { counter.add(delta); eventuallyEquals(Long.MAX_VALUE, counter::getValue); } @Override protected void addAndAssertResult(WeakTestCounter counter, long delta, long expected) { counter.add(delta); eventuallyEquals(expected, counter::getValue); } @Override protected WeakTestCounter createCounter(CounterManager counterManager, String counterName, CounterConfiguration configuration) { counterManager.defineCounter(counterName, configuration); return new WeakTestCounter(counterManager.getWeakCounter(counterName)); } @Override protected List<CounterConfiguration> configurationToTest() { return Arrays.asList( CounterConfiguration.builder(CounterType.WEAK).initialValue(10).concurrencyLevel(10).build(), CounterConfiguration.builder(CounterType.WEAK).initialValue(20).concurrencyLevel(20).build(), CounterConfiguration.builder(CounterType.WEAK).build() ); } @Override protected void assertMinValueAfterMinValue(WeakTestCounter counter, long delta) { counter.add(delta); eventuallyEquals(Long.MIN_VALUE, counter::getValue); } @Override protected int clusterSize() { return CLUSTER_SIZE; } @Override protected WeakTestCounter createCounter(CounterManager counterManager, String counterName, long initialValue) { counterManager.defineCounter(counterName, CounterConfiguration.builder(CounterType.WEAK).initialValue(initialValue).concurrencyLevel(4).build()); return new WeakTestCounter(counterManager.getWeakCounter(counterName)); } }
3,031
35.53012
115
java
null
infinispan-main/counter/src/test/java/org/infinispan/counter/WeakCounterNotificationTest.java
package org.infinispan.counter; import org.infinispan.counter.api.CounterConfiguration; import org.infinispan.counter.api.CounterManager; import org.infinispan.counter.api.CounterType; import org.infinispan.counter.util.TestCounter; import org.infinispan.counter.util.WeakTestCounter; import org.testng.annotations.Test; /** * A simple notification test for {@link org.infinispan.counter.api.WeakCounter}. * * @author Pedro Ruivo * @since 9.0 */ @Test(groups = "functional", testName = "counter.WeakCounterNotificationTest") public class WeakCounterNotificationTest extends AbstractCounterNotificationTest { protected TestCounter createCounter(CounterManager counterManager, String counterName) { counterManager.defineCounter(counterName, CounterConfiguration.builder(CounterType.WEAK).concurrencyLevel(4).build()); return new WeakTestCounter(counterManager.getWeakCounter(counterName)); } }
918
37.291667
124
java
null
infinispan-main/counter/src/test/java/org/infinispan/counter/WeakCounterKeyDistributionTest.java
package org.infinispan.counter; import static org.infinispan.counter.EmbeddedCounterManagerFactory.asCounterManager; import java.lang.reflect.Method; import java.util.HashSet; import java.util.Set; import org.infinispan.Cache; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.counter.api.CounterConfiguration; import org.infinispan.counter.api.CounterManager; import org.infinispan.counter.api.CounterType; import org.infinispan.counter.api.WeakCounter; import org.infinispan.counter.impl.BaseCounterTest; import org.infinispan.counter.impl.CounterModuleLifecycle; import org.infinispan.counter.impl.weak.WeakCounterImpl; import org.infinispan.counter.impl.weak.WeakCounterKey; import org.infinispan.distribution.DistributionManager; import org.infinispan.distribution.LocalizedCacheTopology; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.test.fwk.CleanupAfterMethod; import org.testng.AssertJUnit; import org.testng.annotations.Test; /** * Tests the key distribution for {@link WeakCounter}. * * @author Pedro Ruivo * @since 9.0 */ @Test(groups = "functional", testName = "counter.WeakCounterKeyDistributionTest") @CleanupAfterMethod public class WeakCounterKeyDistributionTest extends BaseCounterTest { private static final int CLUSTER_SIZE = 4; private static void assertKeyDistribution(Cache<?, ?> cache, String counterName) { WeakCounterImpl counter = getCounter(cache.getCacheManager(), counterName); DistributionManager distributionManager = cache.getAdvancedCache().getDistributionManager(); LocalizedCacheTopology topology = distributionManager.getCacheTopology(); Set<WeakCounterKey> preferredKeys = new HashSet<>(); WeakCounterKey[] keys = counter.getPreferredKeys(); if (keys != null) { for (WeakCounterKey key : keys) { AssertJUnit.assertTrue(topology.getDistribution(key).isPrimary()); AssertJUnit.assertTrue(preferredKeys.add(key)); } } for (WeakCounterKey key : counter.getKeys()) { if (!preferredKeys.remove(key)) { AssertJUnit.assertFalse(topology.getDistribution(key).isPrimary()); } } AssertJUnit.assertTrue(preferredKeys.isEmpty()); } private static WeakCounterImpl getCounter(EmbeddedCacheManager manager, String counterName) { CounterManager counterManager = asCounterManager(manager); counterManager .defineCounter(counterName, CounterConfiguration.builder(CounterType.WEAK).concurrencyLevel(128).build()); return (WeakCounterImpl) counterManager.getWeakCounter(counterName); } public void testKeyDistribution(Method method) { final String counterName = method.getName(); assertKeyDistributionInAllManagers(counterName); } public void testKeyDistributionAfterJoin(Method method) { final String counterName = method.getName(); assertKeyDistributionInAllManagers(counterName); addClusterEnabledCacheManager(configure(cacheManagers.size()), getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC)); waitForCounterCaches(); assertKeyDistributionInAllManagers(counterName); } public void testKeyDistributionAfterLeave(Method method) { final String counterName = method.getName(); assertKeyDistributionInAllManagers(counterName); killMember(1); waitForCounterCaches(); assertKeyDistributionInAllManagers(counterName); } @Override protected int clusterSize() { return CLUSTER_SIZE; } private void assertKeyDistributionInAllManagers(String counterName) { for (EmbeddedCacheManager manager : getCacheManagers()) { assertKeyDistribution(manager.getCache(CounterModuleLifecycle.COUNTER_CACHE_NAME), counterName); } } private void waitForCounterCaches() { waitForClusterToForm(CounterModuleLifecycle.COUNTER_CACHE_NAME); } }
3,933
35.425926
122
java
null
infinispan-main/counter/src/test/java/org/infinispan/counter/BoundedCounterTest.java
package org.infinispan.counter; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertFalse; import static org.testng.AssertJUnit.assertTrue; import static org.testng.AssertJUnit.fail; import java.lang.reflect.Method; import java.util.Arrays; import java.util.List; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeoutException; import org.infinispan.counter.api.CounterConfiguration; import org.infinispan.counter.api.CounterManager; import org.infinispan.counter.api.CounterType; import org.infinispan.counter.api.SyncStrongCounter; import org.infinispan.counter.exception.CounterOutOfBoundsException; import org.infinispan.counter.util.StrongTestCounter; import org.testng.annotations.Test; /** * A simple consistency test for bounded {@link org.infinispan.counter.api.StrongCounter}. * * @author Pedro Ruivo * @since 9.0 */ @Test(groups = "functional", testName = "counter.BoundedCounterTest") public class BoundedCounterTest extends StrongCounterTest { public void testSimpleThreshold(Method method) { CounterManager counterManager = counterManager(0); counterManager.defineCounter(method.getName(), CounterConfiguration.builder(CounterType.BOUNDED_STRONG).lowerBound(-1).upperBound(1).build()); StrongTestCounter counter = new StrongTestCounter(counterManager.getStrongCounter(method.getName())); addAndAssertResult(counter, 1, 1); assertOutOfBoundsAdd(counter, 1, 1); addAndAssertResult(counter, -1, 0); addAndAssertResult(counter, -1, -1); assertOutOfBoundsAdd(counter, -1, -1); counter.reset(); assertOutOfBoundsAdd(counter, 2, 1); assertOutOfBoundsAdd(counter, -3, -1); } public void testCompareAndSetBounds(Method method) { CounterManager counterManager = counterManager(0); counterManager.defineCounter(method.getName(), CounterConfiguration.builder(CounterType.BOUNDED_STRONG).lowerBound(-2).upperBound(2).build()); SyncStrongCounter counter = counterManager.getStrongCounter(method.getName()).sync(); assertTrue(counter.compareAndSet(0, 2)); assertEquals(2, counter.getValue()); assertOutOfBoundCompareAndSet(counter, 2, 3); counter.reset(); assertTrue(counter.compareAndSet(0, -2)); assertEquals(-2, counter.getValue()); assertOutOfBoundCompareAndSet(counter, -2, -3); counter.reset(); assertFalse(counter.compareAndSet(1, 3)); assertFalse(counter.compareAndSet(1, -3)); } public void testCompareAndSwapBounds(Method method) { CounterManager counterManager = counterManager(0); counterManager.defineCounter(method.getName(), CounterConfiguration.builder(CounterType.BOUNDED_STRONG).lowerBound(-2).upperBound(2).build()); SyncStrongCounter counter = counterManager.getStrongCounter(method.getName()).sync(); assertEquals(0, counter.compareAndSwap(0, 2)); assertEquals(2, counter.getValue()); assertOutOfBoundCompareAndSwap(counter, 2, 3); counter.reset(); assertEquals(0, counter.compareAndSwap(0, -2)); assertEquals(-2, counter.getValue()); assertOutOfBoundCompareAndSwap(counter, -2, -3); counter.reset(); assertEquals(0, counter.compareAndSwap(1, 3)); assertEquals(0, counter.compareAndSwap(1, -3)); } @Test(groups = "unstable", description = "ISPN-8786") @Override public void testCompareAndSetConcurrent(Method method) throws ExecutionException, InterruptedException, TimeoutException { super.testCompareAndSetConcurrent(method); } @Override protected StrongTestCounter createCounter(CounterManager counterManager, String counterName, long initialValue) { counterManager.defineCounter(counterName, CounterConfiguration.builder(CounterType.BOUNDED_STRONG).lowerBound(Long.MIN_VALUE) .upperBound(Long.MAX_VALUE).initialValue(initialValue).build()); return new StrongTestCounter(counterManager.getStrongCounter(counterName)); } @Override protected void assertMaxValueAfterMaxValue(StrongTestCounter counter, long delta) { assertOutOfBoundsAdd(counter, delta, Long.MAX_VALUE); } @Override protected void assertMinValueAfterMinValue(StrongTestCounter counter, long delta) { assertOutOfBoundsAdd(counter, delta, Long.MIN_VALUE); } @Override protected List<CounterConfiguration> configurationToTest() { return Arrays.asList( CounterConfiguration.builder(CounterType.BOUNDED_STRONG).initialValue(10).lowerBound(1).build(), CounterConfiguration.builder(CounterType.BOUNDED_STRONG).initialValue(-10).upperBound(1).build(), CounterConfiguration.builder(CounterType.BOUNDED_STRONG).initialValue(1).upperBound(2).upperBound(2) .build(), CounterConfiguration.builder(CounterType.BOUNDED_STRONG).build() ); } private void assertOutOfBoundsAdd(StrongTestCounter counter, long delta, long expected) { try { counter.add(delta); fail("Bound should have been reached!"); } catch (CounterOutOfBoundsException e) { log.debug("Expected exception.", e); } assertEquals("Wrong return value of counter.getNewValue()", expected, counter.getValue()); } private void assertOutOfBoundCompareAndSet(SyncStrongCounter counter, long expect, long value) { try { counter.compareAndSet(expect, value); fail("Threshold should have been reached!"); } catch (CounterOutOfBoundsException e) { log.debug("Expected exception", e); } assertEquals("Wrong return value of counter.getNewValue()", expect, counter.getValue()); } private void assertOutOfBoundCompareAndSwap(SyncStrongCounter counter, long expect, long value) { try { counter.compareAndSwap(expect, value); fail("Threshold should have been reached!"); } catch (CounterOutOfBoundsException e) { log.debug("Expected exception", e); } assertEquals("Wrong return value of counter.getNewValue()", expect, counter.getValue()); } }
6,197
40.878378
116
java
null
infinispan-main/counter/src/test/java/org/infinispan/counter/AbstractCounterTest.java
package org.infinispan.counter; import static java.lang.String.format; import static org.testng.AssertJUnit.assertEquals; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; import java.util.Random; import java.util.concurrent.ExecutionException; import org.infinispan.counter.api.CounterConfiguration; import org.infinispan.counter.api.CounterManager; import org.infinispan.counter.exception.CounterOutOfBoundsException; import org.infinispan.counter.impl.BaseCounterTest; import org.infinispan.counter.util.TestCounter; import org.testng.annotations.Test; /** * @author Pedro Ruivo * @since 9.0 */ @Test(groups = {"functional", "smoke"}) public abstract class AbstractCounterTest<T extends TestCounter> extends BaseCounterTest { public void testDiffInitValues(Method method) throws ExecutionException, InterruptedException { final TestContext context = new TestContext(); final String counterName = method.getName(); long initialValue = 0; context.printSeed(counterName); List<T> counters = new ArrayList<>(clusterSize()); for (int i = 0; i < clusterSize(); ++i) { long rndLong = context.random.nextLong(); if (i == 0) { initialValue = rndLong; } log.debug(context.message("StrongCounter #%d initial value is %d", i, rndLong)); counters.add(createCounter(counterManager(i), counterName, rndLong)); } for (int i = 0; i < clusterSize(); ++i) { final int index = i; eventuallyEquals(context.message("Wrong initial value for counter #%d", i), initialValue, () -> counters.get(index).getValue()); } } public void testReset(Method method) throws ExecutionException, InterruptedException { final String counterName = method.getName(); final TestContext context = new TestContext(); context.printSeed(counterName); final long initialValue = context.random.nextLong(); List<T> counters = new ArrayList<>(clusterSize()); for (int i = 0; i < clusterSize(); ++i) { counters.add(createCounter(counterManager(i), counterName, initialValue)); } for (int i = 0; i < clusterSize(); ++i) { long delta = context.random.nextLong(); addIgnoringBounds(counters.get(i), delta); log.debug(context.message("StrongCounter #%d, Add %d", i, delta)); counters.get(i).reset(); final int index = i; eventuallyEquals(context.message("Wrong initial value for counter #%d", i), initialValue, () -> counters.get(index).getValue()); } for (int i = 0; i < clusterSize(); ++i) { long delta = context.random.nextLong(); addIgnoringBounds(counters.get(i), delta); log.debug(context.message("StrongCounter #%d, Add %d", i, delta)); counters.get(0).reset(); final int index = i; eventuallyEquals(context.message("Wrong initial value for counter #%d", i), initialValue, () -> counters.get(index).getValue()); } } public void testMaxAndMinLong(Method method) throws ExecutionException, InterruptedException { final String counterName = method.getName(); T counter = createCounter(counterManager(0), counterName, 0); addAndAssertResult(counter, Long.MAX_VALUE - 1, Long.MAX_VALUE - 1); addAndAssertResult(counter, 1, Long.MAX_VALUE); assertMaxValueAfterMaxValue(counter, 1); assertMaxValueAfterMaxValue(counter, 1000); addAndAssertResult(counter, -1, Long.MAX_VALUE - 1); counter.reset(); addAndAssertResult(counter, Long.MIN_VALUE + 1, Long.MIN_VALUE + 1); addAndAssertResult(counter, -1, Long.MIN_VALUE); assertMinValueAfterMinValue(counter, -1); assertMinValueAfterMinValue(counter, -1000); addAndAssertResult(counter, 1, Long.MIN_VALUE + 1); } public void testGetConfigurationAndGetName(Method method) { final String counterNamePrefix = method.getName(); final CounterManager counterManager = counterManager(0); int suffix = 0; for (CounterConfiguration configuration : configurationToTest()) { T counter = createCounter(counterManager, counterNamePrefix + suffix, configuration); assertEquals(configuration, counter.getConfiguration()); assertEquals(counterNamePrefix + suffix, counter.getName()); suffix++; } } protected abstract void assertMinValueAfterMinValue(T counter, long delta); protected abstract T createCounter(CounterManager counterManager, String counterName, long initialValue); protected abstract void assertMaxValueAfterMaxValue(T counter, long delta); protected abstract void addAndAssertResult(T counter, long delta, long expected); protected abstract T createCounter(CounterManager counterManager, String counterName, CounterConfiguration configuration); /** * {@link CounterConfiguration} to be used by {@link #testGetConfigurationAndGetName(Method)} */ protected abstract List<CounterConfiguration> configurationToTest(); private void addIgnoringBounds(T counter, long delta) { try { counter.add(delta); } catch (CounterOutOfBoundsException e) { log.debug("ignored.", e); } } class TestContext { final Random random; private final long seed; TestContext() { this(System.nanoTime()); } //in case we need to test with specific seed private TestContext(long seed) { this.seed = seed; this.random = new Random(seed); } void printSeed(String testName) { log.infof("Test '%s' seed is %d", testName, seed); } String message(String format, Object... args) { return "[seed=" + seed + "] " + format(format, args); } } }
5,886
34.463855
108
java
null
infinispan-main/counter/src/test/java/org/infinispan/counter/util/WeakTestCounter.java
package org.infinispan.counter.util; import org.infinispan.counter.api.SyncWeakCounter; import org.infinispan.counter.api.CounterConfiguration; import org.infinispan.counter.api.CounterListener; import org.infinispan.counter.api.Handle; import org.infinispan.counter.api.WeakCounter; /** * @author Pedro Ruivo * @since 9.0 */ public class WeakTestCounter implements TestCounter { private final SyncWeakCounter syncCounter; private final WeakCounter counter; public WeakTestCounter(WeakCounter counter) { this.counter = counter; this.syncCounter = counter.sync(); } @Override public <T extends CounterListener> Handle<T> addListener(T listener) { return counter.addListener(listener); } @Override public void increment() { syncCounter.increment(); } @Override public void add(long delta) { syncCounter.add(delta); } @Override public void decrement() { syncCounter.decrement(); } @Override public long getValue() { return syncCounter.getValue(); } @Override public void reset() { syncCounter.reset(); } @Override public String getName() { return syncCounter.getName(); } @Override public CounterConfiguration getConfiguration() { return syncCounter.getConfiguration(); } @Override public boolean isSame(TestCounter other) { return other instanceof WeakTestCounter && counter == ((WeakTestCounter) other).counter; } @Override public void remove() { syncCounter.remove(); } }
1,563
20.424658
94
java
null
infinispan-main/counter/src/test/java/org/infinispan/counter/util/StrongTestCounter.java
package org.infinispan.counter.util; import org.infinispan.counter.api.SyncStrongCounter; import org.infinispan.counter.api.CounterConfiguration; import org.infinispan.counter.api.CounterListener; import org.infinispan.counter.api.Handle; import org.infinispan.counter.api.StrongCounter; /** * @author Pedro Ruivo * @since 9.0 */ public class StrongTestCounter implements TestCounter { private final SyncStrongCounter syncCounter; private final StrongCounter counter; public StrongTestCounter(StrongCounter counter) { this.counter = counter; this.syncCounter = counter.sync(); } @Override public <T extends CounterListener> Handle<T> addListener(T listener) { return counter.addListener(listener); } @Override public void increment() { syncCounter.incrementAndGet(); } @Override public void add(long delta) { syncCounter.addAndGet(delta); } public long addAndGet(long delta) { return syncCounter.addAndGet(delta); } @Override public void decrement() { syncCounter.decrementAndGet(); } @Override public long getValue() { return syncCounter.getValue(); } @Override public void reset() { syncCounter.reset(); } @Override public String getName() { return syncCounter.getName(); } @Override public CounterConfiguration getConfiguration() { return syncCounter.getConfiguration(); } @Override public boolean isSame(TestCounter other) { return other instanceof StrongTestCounter && counter == ((StrongTestCounter) other).counter; } @Override public void remove() { syncCounter.remove(); } public boolean compareAndSet(long expect, long value) { return syncCounter.compareAndSet(expect, value); } public long compareAndSwap(long expect, long value) { return syncCounter.compareAndSwap(expect, value); } }
1,926
21.670588
98
java
null
infinispan-main/counter/src/test/java/org/infinispan/counter/util/TestCounter.java
package org.infinispan.counter.util; import org.infinispan.counter.api.CounterConfiguration; import org.infinispan.counter.api.CounterListener; import org.infinispan.counter.api.Handle; /** * A common interface to use in tests for {@link org.infinispan.counter.api.StrongCounter} and {@link * org.infinispan.counter.api.WeakCounter}. * * @author Pedro Ruivo * @since 9.0 */ public interface TestCounter { <T extends CounterListener> Handle<T> addListener(T listener); void increment(); void add(long delta); void decrement(); long getValue(); void reset(); String getName(); CounterConfiguration getConfiguration(); boolean isSame(TestCounter other); void remove(); }
717
18.944444
102
java
null
infinispan-main/counter/src/test/java/org/infinispan/counter/jmx/CounterJmxTest.java
package org.infinispan.counter.jmx; import static org.infinispan.counter.api.CounterConfiguration.builder; import static org.infinispan.counter.impl.Util.awaitCounterOperation; import static org.infinispan.commons.test.Exceptions.expectException; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertTrue; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Optional; import java.util.Properties; import java.util.concurrent.CompletableFuture; import java.util.function.BiConsumer; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.IntFunction; import javax.management.InstanceNotFoundException; import javax.management.MBeanException; import javax.management.MBeanServer; import javax.management.ObjectName; import javax.management.ReflectionException; import org.infinispan.Cache; import org.infinispan.commons.jmx.MBeanServerLookup; import org.infinispan.commons.jmx.TestMBeanServerLookup; import org.infinispan.configuration.global.GlobalConfigurationBuilder; import org.infinispan.counter.api.CounterConfiguration; import org.infinispan.counter.api.CounterType; import org.infinispan.counter.api.PropertyFormatter; import org.infinispan.counter.exception.CounterOutOfBoundsException; import org.infinispan.counter.impl.BaseCounterTest; import org.infinispan.counter.impl.CounterModuleLifecycle; import org.infinispan.counter.impl.manager.EmbeddedCounterManager; import org.infinispan.globalstate.GlobalConfigurationManager; import org.infinispan.test.TestingUtil; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.testng.AssertJUnit; import org.testng.annotations.AfterMethod; import org.testng.annotations.Test; /** * JMX operations tests. * * @author Pedro Ruivo * @since 9.2 */ @Test(groups = "functional", testName = "counter.jmx.CounterJmxTest") public class CounterJmxTest extends BaseCounterTest { private final MBeanServerLookup mBeanServerLookup = TestMBeanServerLookup.create(); private static void assertCollection(Collection<String> expected, Collection<String> actual) { List<String> expectedList = new ArrayList<>(expected); Collections.sort(expectedList); List<String> actualList = new ArrayList<>(actual); Collections.sort(actualList); assertEquals(expectedList, actualList); } private static CounterConfiguration fromProperties(Properties properties) { return PropertyFormatter.getInstance().from(properties).build(); } public void testDefinedCounters() { final Collection<String> list = new ArrayList<>(3); assertJmxResult(list, this::executeCountersOperation, CounterJmxTest::assertCollection); addCounterAndCheckList(list, "A", builder(CounterType.WEAK).build()); addCounterAndCheckList(list, "B", builder(CounterType.BOUNDED_STRONG).build()); addCounterAndCheckList(list, "C", builder(CounterType.UNBOUNDED_STRONG).build()); } public void testGetValueAndReset() { checkValueAndReset("A", builder(CounterType.WEAK).initialValue(10).build(), 20, s -> addToWeakCounter(s, 10), this::resetWeakCounter); checkValueAndReset("B", builder(CounterType.UNBOUNDED_STRONG).initialValue(-10).build(), 5, s -> addToStrongCounter(s, 15, false), this::resetStrongCounter); checkValueAndReset("C", builder(CounterType.BOUNDED_STRONG).initialValue(1).lowerBound(0).upperBound(2).build(), 2, s -> addToStrongCounter(s, 3, true), this::resetStrongCounter); } public void testRemove() { checkRemove("A", builder(CounterType.WEAK).initialValue(10).build(), 121, 20, s -> addToWeakCounter(s, 111), s -> addToWeakCounter(s, 10), this::getWeakCounterValue); checkRemove("B", builder(CounterType.UNBOUNDED_STRONG).initialValue(-10).build(), -11, -9, s -> addToStrongCounter(s, -1, false), s -> addToStrongCounter(s, 1, false), this::getStrongCounterValue); } public void testGetConfiguration() { assertConfiguration("A", createWeakCounterProperties(), builder(CounterType.WEAK).initialValue(10).concurrencyLevel(1).build()); assertConfiguration("B", createUnboundedCounterProperties(), builder(CounterType.UNBOUNDED_STRONG).initialValue(5).build()); assertConfiguration("C", createBoundedCounterProperties(), builder(CounterType.BOUNDED_STRONG).initialValue(5).lowerBound(0).upperBound(10).build()); } @AfterMethod(alwaysRun = true) @Override protected void clearContent() throws Throwable { findCache(CounterModuleLifecycle.COUNTER_CACHE_NAME).ifPresent(Cache::clear); findCache(GlobalConfigurationManager.CONFIG_STATE_CACHE_NAME).ifPresent(Cache::clear); super.clearContent(); } @Override protected int clusterSize() { return 2; } @Override protected GlobalConfigurationBuilder configure(int nodeId) { GlobalConfigurationBuilder builder = GlobalConfigurationBuilder.defaultClusteredBuilder(); String jmxDomain = getClass().getSimpleName() + nodeId; TestCacheManagerFactory.configureJmx(builder, jmxDomain, mBeanServerLookup); return builder; } private long getStrongCounterValue(String name) { return awaitCounterOperation(counterManager(0).getStrongCounter(name).getValue()); } private long getWeakCounterValue(String name) { return counterManager(0).getWeakCounter(name).getValue(); } private void assertConfiguration(String name, Properties props, CounterConfiguration config) { assertTrue(counterManager(0).defineCounter(name, config)); assertJmxResult(props, i -> executeCounterNameArgOperation(i, "configuration", name), AssertJUnit::assertEquals); assertEquals(props, PropertyFormatter.getInstance().format(config)); assertEquals(config, fromProperties(props)); } private void resetStrongCounter(String name) { awaitCounterOperation(counterManager(0).getStrongCounter(name).reset()); } private void addToStrongCounter(String name, long delta, boolean exception) { CompletableFuture<Long> result = counterManager(0).getStrongCounter(name).addAndGet(delta); if (exception) { expectException(CounterOutOfBoundsException.class, () -> awaitCounterOperation(result)); } else { awaitCounterOperation(result); } } private void addToWeakCounter(String name, long delta) { awaitCounterOperation(counterManager(0).getWeakCounter(name).add(delta)); } private void resetWeakCounter(String name) { awaitCounterOperation(counterManager(0).getWeakCounter(name).reset()); } private void checkValueAndReset(String name, CounterConfiguration config, long addResult, Consumer<String> add, Consumer<String> reset) { assertTrue(counterManager(0).defineCounter(name, config)); assertJmxResult(config.initialValue(), i -> executeCounterNameArgOperation(i, "value", name), AssertJUnit::assertEquals); add.accept(name); assertJmxResult(addResult, i -> executeCounterNameArgOperation(i, "value", name), AssertJUnit::assertEquals); reset.accept(name); assertJmxResult(config.initialValue(), i -> executeCounterNameArgOperation(i, "value", name), AssertJUnit::assertEquals); } private void checkRemove(String name, CounterConfiguration config, long add1Result, long add2Result, Consumer<String> add1, Consumer<String> add2, Function<String, Long> getValue) { assertTrue(counterManager(0).defineCounter(name, config)); add1.accept(name); assertEquals(add1Result, (long) getValue.apply(name)); executeCounterNameArgOperation(0, "remove", name); assertEquals(config.initialValue(), (long) getValue.apply(name)); add2.accept(name); assertEquals(add2Result, (long) getValue.apply(name)); executeCounterNameArgOperation(1, "remove", name); assertEquals(config.initialValue(), (long) getValue.apply(name)); } private void addCounterAndCheckList(Collection<String> list, String name, CounterConfiguration config) { list.add(name); assertTrue(counterManager(0).defineCounter(name, config)); assertJmxResult(list, this::executeCountersOperation, CounterJmxTest::assertCollection); } private <T> void assertJmxResult(T expected, IntFunction<T> function, BiConsumer<T, T> assertFunction) { for (int i = 0; i < clusterSize(); ++i) { assertFunction.accept(expected, function.apply(i)); } } private Properties createWeakCounterProperties() { Properties properties = new Properties(); properties.setProperty("type", "WEAK"); properties.setProperty("storage", "VOLATILE"); properties.setProperty("initial-value", "10"); properties.setProperty("concurrency-level", "1"); return properties; } private Properties createUnboundedCounterProperties() { Properties properties = new Properties(); properties.setProperty("type", "UNBOUNDED_STRONG"); properties.setProperty("storage", "VOLATILE"); properties.setProperty("initial-value", "5"); return properties; } private Properties createBoundedCounterProperties() { Properties properties = new Properties(); properties.setProperty("type", "BOUNDED_STRONG"); properties.setProperty("storage", "VOLATILE"); properties.setProperty("initial-value", "5"); properties.setProperty("lower-bound", "0"); properties.setProperty("upper-bound", "10"); return properties; } private Optional<Cache<?, ?>> findCache(String cacheName) { return Optional.ofNullable(manager(0).getCache(cacheName, false)); } private Collection<String> executeCountersOperation(int index) { MBeanServer server = mBeanServerLookup.getMBeanServer(); try { //noinspection unchecked return (Collection<String>) server.invoke(counterObjectName(index), "counters", new Object[0], new String[0]); } catch (InstanceNotFoundException | MBeanException | ReflectionException e) { throw new RuntimeException(e); } } private <T> T executeCounterNameArgOperation(int index, String operationName, String arg) { MBeanServer server = mBeanServerLookup.getMBeanServer(); try { //noinspection unchecked return (T) server .invoke(counterObjectName(index), operationName, new Object[]{arg}, new String[]{String.class.getName()}); } catch (InstanceNotFoundException | MBeanException | ReflectionException e) { throw new RuntimeException(e); } } private ObjectName counterObjectName(int managerIndex) { final String domain = manager(managerIndex).getCacheManagerConfiguration().jmx().domain(); return TestingUtil.getCacheManagerObjectName(domain, "DefaultCacheManager", EmbeddedCounterManager.OBJECT_NAME); } }
11,166
40.981203
119
java
null
infinispan-main/counter/src/test/java/org/infinispan/counter/impl/BaseCounterTest.java
package org.infinispan.counter.impl; import static org.infinispan.test.fwk.TestCacheManagerFactory.getDefaultCacheConfiguration; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.global.GlobalConfigurationBuilder; import org.infinispan.counter.EmbeddedCounterManagerFactory; import org.infinispan.counter.api.CounterManager; import org.infinispan.test.MultipleCacheManagersTest; /** * @author Pedro Ruivo * @since 9.0 */ public abstract class BaseCounterTest extends MultipleCacheManagersTest { protected abstract int clusterSize(); protected GlobalConfigurationBuilder configure(int nodeId) { return GlobalConfigurationBuilder.defaultClusteredBuilder(); } @Override protected final void createCacheManagers() { final int size = clusterSize(); for (int i = 0; i < size; ++i) { if (size == 1) { addClusterEnabledCacheManager(configure(i), getDefaultCacheConfiguration(false)); } else { addClusterEnabledCacheManager(configure(i), getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC)); } } } protected final CounterManager counterManager(int index) { return EmbeddedCounterManagerFactory.asCounterManager(manager(index)); } }
1,277
31.769231
109
java
null
infinispan-main/counter/src/main/java/org/infinispan/counter/SyncStrongCounter.java
package org.infinispan.counter; import org.infinispan.counter.api.StrongCounter; import org.infinispan.counter.impl.SyncStrongCounterAdapter; /** * A {@link StrongCounter} decorator that waits for the operation to complete. * * @author Pedro Ruivo * @see StrongCounter * @since 9.0 * @deprecated since 9.2. Use {@link StrongCounter#sync()} instead. It will be removed in 10.0 */ @Deprecated public class SyncStrongCounter extends SyncStrongCounterAdapter { public SyncStrongCounter(StrongCounter counter) { super(counter); } }
550
24.045455
94
java
null
infinispan-main/counter/src/main/java/org/infinispan/counter/EmbeddedCounterManagerFactory.java
package org.infinispan.counter; import static java.util.Objects.requireNonNull; import org.infinispan.commons.IllegalLifecycleStateException; import org.infinispan.counter.api.CounterManager; import org.infinispan.factories.impl.BasicComponentRegistry; import org.infinispan.factories.impl.ComponentRef; import org.infinispan.lifecycle.ComponentStatus; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.security.actions.SecurityActions; /** * A {@link CounterManager} factory for embedded cached. * * @author Pedro Ruivo * @since 9.0 */ public final class EmbeddedCounterManagerFactory { private EmbeddedCounterManagerFactory() { } /** * @return the {@link CounterManager} associated to the {@link EmbeddedCacheManager}. * @throws IllegalLifecycleStateException if the cache manager is not running */ public static CounterManager asCounterManager(EmbeddedCacheManager cacheManager) { requireNonNull(cacheManager, "EmbeddedCacheManager can't be null."); if (cacheManager.getStatus() != ComponentStatus.RUNNING) throw new IllegalLifecycleStateException(); ComponentRef<CounterManager> component = SecurityActions.getGlobalComponentRegistry(cacheManager) .getComponent(BasicComponentRegistry.class) .getComponent(CounterManager.class); if (component == null) { return null; } return component.running(); } }
1,447
31.909091
103
java
null
infinispan-main/counter/src/main/java/org/infinispan/counter/SyncWeakCounter.java
package org.infinispan.counter; import org.infinispan.counter.api.WeakCounter; import org.infinispan.counter.impl.SyncWeakCounterAdapter; /** * A {@link WeakCounter} decorator that waits for the operation to complete. * * @author Pedro Ruivo * @see WeakCounter * @since 9.0 * @deprecated since 9.2. Use {@link WeakCounter#sync()} instead. It will be removed in 10.0 */ @Deprecated public class SyncWeakCounter extends SyncWeakCounterAdapter { public SyncWeakCounter(WeakCounter counter) { super(counter); } }
531
24.333333
92
java
null
infinispan-main/counter/src/main/java/org/infinispan/counter/configuration/StrongCounterConfiguration.java
package org.infinispan.counter.configuration; import org.infinispan.commons.configuration.attributes.AttributeDefinition; import org.infinispan.commons.configuration.attributes.AttributeSet; /** * {@link org.infinispan.counter.api.StrongCounter} configuration. * * @author Pedro Ruivo * @since 9.0 */ public class StrongCounterConfiguration extends AbstractCounterConfiguration { static final AttributeDefinition<Long> LOWER_BOUND = AttributeDefinition.builder(Attribute.LOWER_BOUND, Long.MIN_VALUE) .immutable() .build(); static final AttributeDefinition<Long> UPPER_BOUND = AttributeDefinition.builder(Attribute.UPPER_BOUND, Long.MAX_VALUE) .immutable() .build(); static final AttributeDefinition<Long> LIFESPAN = AttributeDefinition.builder(Attribute.LIFESPAN, -1L) .immutable() .build(); StrongCounterConfiguration(AttributeSet attributes) { super(attributes); } public static AttributeSet attributeDefinitionSet() { return new AttributeSet(StrongCounterConfiguration.class, AbstractCounterConfiguration.attributeDefinitionSet(), LOWER_BOUND, UPPER_BOUND, LIFESPAN); } /** * @return {@code true} if the counter is bounded (lower and/or upper bound has been set), {@code false} otherwise. */ public boolean isBound() { return attributes.attribute(LOWER_BOUND).isModified() || attributes.attribute(UPPER_BOUND).isModified(); } public long lowerBound() { return attributes.attribute(LOWER_BOUND).get(); } public long upperBound() { return attributes.attribute(UPPER_BOUND).get(); } public long lifespan() { return attributes.attribute(LIFESPAN).get(); } }
1,731
31.074074
122
java
null
infinispan-main/counter/src/main/java/org/infinispan/counter/configuration/CounterConfigurationSerializer.java
package org.infinispan.counter.configuration; import java.io.BufferedOutputStream; import java.io.OutputStream; import java.util.Collection; import java.util.List; import org.infinispan.commons.configuration.io.ConfigurationFormatFeature; import org.infinispan.commons.configuration.io.ConfigurationWriter; import org.infinispan.commons.util.Util; import org.infinispan.commons.util.Version; import org.infinispan.configuration.parsing.Attribute; import org.infinispan.configuration.serializing.ConfigurationSerializer; /** * Counters configuration serializer. * * @author Pedro Ruivo * @since 9.0 */ public class CounterConfigurationSerializer implements ConfigurationSerializer<CounterManagerConfiguration> { @Override public void serialize(ConfigurationWriter writer, CounterManagerConfiguration configuration) { if (writer.hasFeature(ConfigurationFormatFeature.MIXED_ELEMENTS)) { writer.writeStartMap(Element.COUNTERS); writer.writeDefaultNamespace(CounterConfigurationParser.NAMESPACE + Version.getMajorMinor()); configuration.attributes().write(writer); writeConfigurations(writer, configuration.counters().values()); writer.writeEndMap(); } else { writer.writeStartElement(Element.COUNTERS); writer.writeDefaultNamespace(CounterConfigurationParser.NAMESPACE + Version.getMajorMinor()); configuration.attributes().write(writer); writer.writeStartMap(Element.COUNTERS); writeConfigurations(writer, configuration.counters().values()); writer.writeEndMap(); writer.writeEndElement(); } } /** * It serializes a {@link List} of {@link AbstractCounterConfiguration} to an {@link OutputStream}. * @param os the {@link OutputStream} to write to. * @param configs the {@link List} if {@link AbstractCounterConfiguration}. */ public void serializeConfigurations(OutputStream os, Collection<AbstractCounterConfiguration> configs) { BufferedOutputStream output = new BufferedOutputStream(os); ConfigurationWriter writer = ConfigurationWriter.to(output).build(); writer.writeStartDocument(); writer.writeStartMap(Element.COUNTERS); writeConfigurations(writer, configs); writer.writeEndMap(); writer.writeEndDocument(); Util.close(writer); } /** * Serializes a single counter configuration * @param writer * @param c */ public void serializeConfiguration(ConfigurationWriter writer, AbstractCounterConfiguration c) { writer.writeStartDocument(); writeConfiguration(writer, c, true); writer.writeEndDocument(); } private void writeConfigurations(ConfigurationWriter writer, Collection<AbstractCounterConfiguration> configs) { for (AbstractCounterConfiguration c : configs) { writeConfiguration(writer, c, false); } } private void writeConfiguration(ConfigurationWriter writer, AbstractCounterConfiguration c, boolean unnamed) { if (c instanceof StrongCounterConfiguration) { writeStrongConfiguration((StrongCounterConfiguration) c, writer, unnamed); } else if (c instanceof WeakCounterConfiguration) { writeWeakConfiguration((WeakCounterConfiguration) c, writer, unnamed); } } private void writeWeakConfiguration(WeakCounterConfiguration configuration, ConfigurationWriter writer, boolean unnamed) { if (unnamed) { writer.writeStartElement(Element.WEAK_COUNTER); } else { writer.writeMapItem(Element.WEAK_COUNTER, Attribute.NAME, configuration.name()); } configuration.attributes().write(writer); if (unnamed) { writer.writeEndElement(); } else { writer.writeEndMapItem(); } } private void writeStrongConfiguration(StrongCounterConfiguration configuration, ConfigurationWriter writer, boolean unnamed) { if (unnamed) { writer.writeStartElement(Element.STRONG_COUNTER); } else { writer.writeMapItem(Element.STRONG_COUNTER, Attribute.NAME, configuration.name()); } configuration.attributes().write(writer); if (unnamed) { writer.writeEndElement(); } else { writer.writeEndMapItem(); } } }
4,281
37.576577
129
java
null
infinispan-main/counter/src/main/java/org/infinispan/counter/configuration/Element.java
package org.infinispan.counter.configuration; import java.util.HashMap; import java.util.Map; /** * @author Pedro Ruivo * @since 9.0 */ public enum Element { //must be first UNKNOWN(null), COUNTERS("counters"), LOWER_BOUND("lower-bound"), STRONG_COUNTER("strong-counter"), UPPER_BOUND("upper-bound"), WEAK_COUNTER("weak-counter"), ; private static final Map<String, Element> ELEMENTS; static { final Map<String, Element> map = new HashMap<>(8); for (Element element : values()) { final String name = element.name; if (name != null) { map.put(name, element); } } ELEMENTS = map; } private final String name; Element(final String name) { this.name = name; } public static Element forName(final String localName) { final Element element = ELEMENTS.get(localName); return element == null ? UNKNOWN : element; } @Override public String toString() { return name; } }
1,017
19.36
58
java
null
infinispan-main/counter/src/main/java/org/infinispan/counter/configuration/ConvertUtil.java
package org.infinispan.counter.configuration; import static org.infinispan.counter.api.CounterConfiguration.builder; import org.infinispan.counter.api.CounterConfiguration; import org.infinispan.counter.api.CounterType; /** * Utility methods to convert {@link CounterConfiguration} to and from {@link StrongCounterConfiguration} and {@link WeakCounterConfiguration} * * @author Pedro Ruivo * @since 9.2 */ public final class ConvertUtil { private ConvertUtil() { } public static CounterConfiguration parsedConfigToConfig(AbstractCounterConfiguration configuration) { if (configuration instanceof StrongCounterConfiguration) { return parsedConfigToConfig((StrongCounterConfiguration) configuration); } else if (configuration instanceof WeakCounterConfiguration) { return parsedConfigToConfig((WeakCounterConfiguration) configuration); } throw new IllegalStateException( "[should never happen] unknown CounterConfiguration class: " + configuration.getClass()); } public static AbstractCounterConfiguration configToParsedConfig(String name, CounterConfiguration configuration) { switch (configuration.type()) { case WEAK: WeakCounterConfigurationBuilder wBuilder = new WeakCounterConfigurationBuilder(null); wBuilder.concurrencyLevel(configuration.concurrencyLevel()); populateCommonAttributes(wBuilder, name, configuration); return wBuilder.create(); case BOUNDED_STRONG: StrongCounterConfigurationBuilder bBuilder = new StrongCounterConfigurationBuilder(null); bBuilder.upperBound(configuration.upperBound()); bBuilder.lowerBound(configuration.lowerBound()); bBuilder.lifespan(configuration.lifespan()); populateCommonAttributes(bBuilder, name, configuration); return bBuilder.create(); case UNBOUNDED_STRONG: StrongCounterConfigurationBuilder uBuilder = new StrongCounterConfigurationBuilder(null); uBuilder.lifespan(configuration.lifespan()); populateCommonAttributes(uBuilder, name, configuration); return uBuilder.create(); default: throw new IllegalStateException( "[should never happen] unknown CounterConfiguration class: " + configuration.getClass()); } } private static void populateCommonAttributes(AbstractCounterConfigurationBuilder<?, ?> builder, String name, CounterConfiguration config) { builder.name(name); builder.initialValue(config.initialValue()); builder.storage(config.storage()); } private static CounterConfiguration parsedConfigToConfig(StrongCounterConfiguration configuration) { return configuration.isBound() ? builder(CounterType.BOUNDED_STRONG) .initialValue(configuration.initialValue()) .lowerBound(configuration.lowerBound()) .upperBound(configuration.upperBound()) .lifespan(configuration.lifespan()) .storage(configuration.storage()) .build() : builder(CounterType.UNBOUNDED_STRONG) .initialValue(configuration.initialValue()) .lifespan(configuration.lifespan()) .storage(configuration.storage()) .build(); } private static CounterConfiguration parsedConfigToConfig(WeakCounterConfiguration configuration) { return builder(CounterType.WEAK) .initialValue(configuration.initialValue()) .storage(configuration.storage()) .concurrencyLevel(configuration.concurrencyLevel()) .build(); } }
3,774
41.897727
142
java
null
infinispan-main/counter/src/main/java/org/infinispan/counter/configuration/CounterManagerConfigurationBuilder.java
package org.infinispan.counter.configuration; import static org.infinispan.counter.logging.Log.CONTAINER; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.infinispan.commons.configuration.Builder; import org.infinispan.commons.configuration.Combine; import org.infinispan.commons.configuration.attributes.Attribute; import org.infinispan.commons.configuration.attributes.AttributeSet; import org.infinispan.configuration.global.GlobalConfigurationBuilder; /** * The {@link org.infinispan.counter.api.CounterManager} configuration builder. * <p> * It configures the number of owner and the {@link Reliability} mode. It allow to configure the default counter * available on startup. * * @author Pedro Ruivo * @since 9.0 */ public class CounterManagerConfigurationBuilder implements Builder<CounterManagerConfiguration> { private static final CounterManagerConfiguration DEFAULT = new CounterManagerConfigurationBuilder(null).create(); private final AttributeSet attributes = CounterManagerConfiguration.attributeDefinitionSet(); private final List<CounterConfigurationBuilder<?, ?>> defaultCounters; private final GlobalConfigurationBuilder builder; @SuppressWarnings("WeakerAccess") public CounterManagerConfigurationBuilder(GlobalConfigurationBuilder builder) { defaultCounters = new ArrayList<>(2); this.builder = builder; } @Override public AttributeSet attributes() { return attributes; } /** * @return the default {@link CounterManagerConfiguration}. */ public static CounterManagerConfiguration defaultConfiguration() { return DEFAULT; } /** * Sets the number of copies of the counter's value available in the cluster. * <p> * A higher value will provide better availability at the cost of more expensive updates. * <p> * Default value is 2. * * @param numOwners the number of copies. */ public CounterManagerConfigurationBuilder numOwner(int numOwners) { attributes.attribute(CounterManagerConfiguration.NUM_OWNERS).set(numOwners); return this; } /** * Sets the {@link Reliability} mode. * <p> * Default value is {@link Reliability#AVAILABLE}. * * @param reliability the {@link Reliability} mode. * @see Reliability */ public CounterManagerConfigurationBuilder reliability(Reliability reliability) { attributes.attribute(CounterManagerConfiguration.RELIABILITY).set(reliability); return this; } /** * @return a new {@link StrongCounterConfigurationBuilder} to configure a strong consistent counters. */ public StrongCounterConfigurationBuilder addStrongCounter() { StrongCounterConfigurationBuilder builder = new StrongCounterConfigurationBuilder(this); defaultCounters.add(builder); return builder; } /** * @return a new {@link WeakCounterConfigurationBuilder} to configure weak consistent counters. */ public WeakCounterConfigurationBuilder addWeakCounter() { WeakCounterConfigurationBuilder builder = new WeakCounterConfigurationBuilder(this); defaultCounters.add(builder); return builder; } @Override public void validate() { attributes.attributes().forEach(Attribute::validate); defaultCounters.forEach(CounterConfigurationBuilder::validate); Set<String> counterNames = new HashSet<>(); for (CounterConfigurationBuilder builder : defaultCounters) { if (!counterNames.add(builder.name())) { throw CONTAINER.duplicatedCounterName(builder.name()); } } } @Override public CounterManagerConfiguration create() { Map<String, AbstractCounterConfiguration> counters = new HashMap<>(defaultCounters.size()); for (CounterConfigurationBuilder<?, ?> builder : defaultCounters) { counters.put(builder.name(), builder.create()); } return new CounterManagerConfiguration(attributes.protect(), counters); } @Override public Builder<?> read(CounterManagerConfiguration template, Combine combine) { this.attributes.read(template.attributes(), combine); return this; } /** * Clears all the configured counters. */ public void clearCounters() { defaultCounters.clear(); } /** * @return {@code true} if global state is enabled, {@link false} otherwise. */ boolean isGlobalStateEnabled() { return builder.globalState().enabled(); } public List<CounterConfigurationBuilder<?,?>> counters() { return defaultCounters; } }
4,677
31.713287
116
java
null
infinispan-main/counter/src/main/java/org/infinispan/counter/configuration/Reliability.java
package org.infinispan.counter.configuration; /** * Reliability mode available for {@link org.infinispan.counter.api.CounterManager}. * * @author Pedro Ruivo * @since 9.0 */ public enum Reliability { /** * If the cluster splits in multiple partition, all of them are allowed to continue read/update the counter. * <p> * When the cluster merges back, one partition's updates are kept the others partition's updates are lost. */ AVAILABLE, /** * If the cluster splits in multiple partitions, the majority partition is allowed to read/update the counter if the * counter is available on that partition. * <p> * The minority partition is allowed to read if the counter is available on that partition. * <p> * When the cluster merges back, the partitions conciliates the counter's value. */ CONSISTENT }
861
32.153846
119
java
null
infinispan-main/counter/src/main/java/org/infinispan/counter/configuration/AbstractCounterConfiguration.java
package org.infinispan.counter.configuration; import static org.infinispan.counter.logging.Log.CONTAINER; import org.infinispan.commons.configuration.attributes.AttributeDefinition; import org.infinispan.commons.configuration.attributes.AttributeSet; import org.infinispan.counter.api.Storage; /** * Base counter configuration with its name, initial value and {@link Storage} mode. * * @author Pedro Ruivo * @since 9.0 */ public abstract class AbstractCounterConfiguration { static final AttributeDefinition<Long> INITIAL_VALUE = AttributeDefinition.builder(Attribute.INITIAL_VALUE, 0L) .immutable() .build(); static final AttributeDefinition<Storage> STORAGE = AttributeDefinition.builder(Attribute.STORAGE, Storage.VOLATILE) .validator(value -> { if (value == null) { throw CONTAINER.invalidStorageMode(); } }) .immutable() .build(); static final AttributeDefinition<String> NAME = AttributeDefinition.builder(Attribute.NAME, null, String.class) .validator(value -> { if (value == null) { throw CONTAINER.missingCounterName(); } }).autoPersist(false) .immutable() .build(); final AttributeSet attributes; AbstractCounterConfiguration(AttributeSet attributes) { this.attributes = attributes; } static AttributeSet attributeDefinitionSet() { return new AttributeSet(AbstractCounterConfiguration.class, NAME, INITIAL_VALUE, STORAGE); } public final AttributeSet attributes() { return attributes; } public String name() { return attributes.attribute(NAME).get(); } public long initialValue() { return attributes.attribute(INITIAL_VALUE).get(); } public Storage storage() { return attributes.attribute(STORAGE).get(); } }
1,887
28.968254
119
java
null
infinispan-main/counter/src/main/java/org/infinispan/counter/configuration/CounterConfigurationBuilder.java
package org.infinispan.counter.configuration; import org.infinispan.commons.configuration.Builder; import org.infinispan.commons.configuration.Self; import org.infinispan.counter.api.Storage; /** * Base counter configuration builder. * <p> * It allows to configure the name, initial value and the {@link Storage} mode. The counter's name is required. * * @author Pedro Ruivo * @since 9.0 */ public interface CounterConfigurationBuilder<T extends AbstractCounterConfiguration, S extends CounterConfigurationBuilder<T, S>> extends Builder<T>, Self<S> { /** * Sets the counter's name. * <p> * This attribute is required. * * @param name the counter's name. */ S name(String name); String name(); /** * Sets the counter's initial value. * <p> * Default value is zero. * * @param initialValue the counter's initial value. */ S initialValue(long initialValue); /** * Sets the counter's storage mode. * <p> * Default value is {@link Storage#VOLATILE}. * * @param mode the counter's storage mode. * @see Storage */ S storage(Storage mode); /** * @return a new builder to configure a strong counter. */ StrongCounterConfigurationBuilder addStrongCounter(); /** * @return a new builder to configure a weak counter. */ WeakCounterConfigurationBuilder addWeakCounter(); }
1,406
23.258621
129
java
null
infinispan-main/counter/src/main/java/org/infinispan/counter/configuration/StrongCounterConfigurationBuilder.java
package org.infinispan.counter.configuration; import static org.infinispan.counter.impl.Utils.validateStrongCounterBounds; import org.infinispan.commons.configuration.Builder; import org.infinispan.commons.configuration.Combine; import org.infinispan.commons.configuration.attributes.AttributeSet; /** * {@link org.infinispan.counter.api.StrongCounter} configuration builder. * * @author Pedro Ruivo * @since 9.0 */ public class StrongCounterConfigurationBuilder extends AbstractCounterConfigurationBuilder<StrongCounterConfiguration, StrongCounterConfigurationBuilder> { public StrongCounterConfigurationBuilder(CounterManagerConfigurationBuilder builder) { super(builder, StrongCounterConfiguration.attributeDefinitionSet()); } @Override public AttributeSet attributes() { return attributes; } /** * Sets the upper bound (inclusive) of the counter if a bounded counter is desired. * <p> * Default value is {@link Long#MAX_VALUE}. * * @param value the new counter's upper bound. */ public StrongCounterConfigurationBuilder upperBound(long value) { attributes.attribute(StrongCounterConfiguration.UPPER_BOUND).set(value); return self(); } /** * Sets the lower bound (inclusive) of the counter if a bounded counter is desired. * <p> * Default value is {@link Long#MIN_VALUE}. * * @param value the new counter's lower bound. */ public StrongCounterConfigurationBuilder lowerBound(long value) { attributes.attribute(StrongCounterConfiguration.LOWER_BOUND).set(value); return self(); } public StrongCounterConfigurationBuilder lifespan(long value) { attributes.attribute(StrongCounterConfiguration.LIFESPAN).set(value); return self(); } @Override public StrongCounterConfiguration create() { return new StrongCounterConfiguration(attributes); } @Override public Builder<?> read(StrongCounterConfiguration template, Combine combine) { this.attributes.read(template.attributes(), combine); return self(); } @Override public StrongCounterConfigurationBuilder self() { return this; } @Override public void validate() { super.validate(); if (attributes.attribute(StrongCounterConfiguration.LOWER_BOUND).isModified() || attributes.attribute( StrongCounterConfiguration.UPPER_BOUND).isModified()) { long min = attributes.attribute(StrongCounterConfiguration.LOWER_BOUND).get(); long max = attributes.attribute(StrongCounterConfiguration.UPPER_BOUND).get(); long init = attributes.attribute(StrongCounterConfiguration.INITIAL_VALUE).get(); validateStrongCounterBounds(min, init, max); } } }
2,763
31.904762
108
java
null
infinispan-main/counter/src/main/java/org/infinispan/counter/configuration/WeakCounterConfiguration.java
package org.infinispan.counter.configuration; import static org.infinispan.counter.logging.Log.CONTAINER; import org.infinispan.commons.configuration.attributes.AttributeDefinition; import org.infinispan.commons.configuration.attributes.AttributeSet; /** * {@link org.infinispan.counter.api.WeakCounter} configuration. * * @author Pedro Ruivo * @since 9.0 */ public class WeakCounterConfiguration extends AbstractCounterConfiguration { static final AttributeDefinition<Integer> CONCURRENCY_LEVEL = AttributeDefinition .builder(Attribute.CONCURRENCY_LEVEL, 16) .validator(value -> { if (value < 1) { throw CONTAINER.invalidConcurrencyLevel(value); } }) .immutable() .build(); WeakCounterConfiguration(AttributeSet attributes) { super(attributes); } public static AttributeSet attributeDefinitionSet() { return new AttributeSet(WeakCounterConfiguration.class, AbstractCounterConfiguration.attributeDefinitionSet(), CONCURRENCY_LEVEL); } public int concurrencyLevel() { return attributes.attribute(CONCURRENCY_LEVEL).get(); } }
1,172
29.076923
116
java
null
infinispan-main/counter/src/main/java/org/infinispan/counter/configuration/WeakCounterConfigurationBuilder.java
package org.infinispan.counter.configuration; import org.infinispan.commons.configuration.Builder; import org.infinispan.commons.configuration.Combine; import org.infinispan.commons.configuration.attributes.AttributeSet; /** * {@link org.infinispan.counter.api.WeakCounter} configuration builder. * * @author Pedro Ruivo * @since 9.0 */ public class WeakCounterConfigurationBuilder extends AbstractCounterConfigurationBuilder<WeakCounterConfiguration, WeakCounterConfigurationBuilder> { public WeakCounterConfigurationBuilder(CounterManagerConfigurationBuilder builder) { super(builder, WeakCounterConfiguration.attributeDefinitionSet()); } @Override public AttributeSet attributes() { return attributes; } @Override public WeakCounterConfiguration create() { return new WeakCounterConfiguration(attributes); } @Override public Builder<?> read(WeakCounterConfiguration template, Combine combine) { attributes.read(template.attributes(), combine); return this; } @Override public WeakCounterConfigurationBuilder self() { return this; } /** * Sets the counter's concurrency level. * <p> * It sets the number of concurrent updates in the counter. A higher value will support a higher number of updates * but it increases the read of the counter's value. * <p> * Default value is 16. * * @param level the new concurrency level. */ public WeakCounterConfigurationBuilder concurrencyLevel(int level) { attributes.attribute(WeakCounterConfiguration.CONCURRENCY_LEVEL).set(level); return self(); } }
1,646
28.410714
117
java
null
infinispan-main/counter/src/main/java/org/infinispan/counter/configuration/AbstractCounterConfigurationBuilder.java
package org.infinispan.counter.configuration; import static org.infinispan.counter.logging.Log.CONTAINER; import org.infinispan.commons.configuration.attributes.Attribute; import org.infinispan.commons.configuration.attributes.AttributeSet; import org.infinispan.counter.api.Storage; /** * Base counter configuration builder. * <p> * It allows to configure the counter's name, initial value and the {@link Storage} mode. * * @author Pedro Ruivo * @since 9.0 */ abstract class AbstractCounterConfigurationBuilder<T extends AbstractCounterConfiguration, S extends AbstractCounterConfigurationBuilder<T, S>> implements CounterConfigurationBuilder<T, S> { final AttributeSet attributes; private final CounterManagerConfigurationBuilder builder; AbstractCounterConfigurationBuilder(CounterManagerConfigurationBuilder builder, AttributeSet attributes) { this.builder = builder; this.attributes = attributes; } @Override public final S name(String name) { attributes.attribute(AbstractCounterConfiguration.NAME).set(name); return self(); } @Override public final S initialValue(long initialValue) { attributes.attribute(AbstractCounterConfiguration.INITIAL_VALUE).set(initialValue); return self(); } @Override public final S storage(Storage mode) { attributes.attribute(AbstractCounterConfiguration.STORAGE).set(mode); return self(); } @Override public void validate() { attributes.attributes().forEach(Attribute::validate); if (!builder.isGlobalStateEnabled() && attributes.attribute(AbstractCounterConfiguration.STORAGE).get() == Storage.PERSISTENT) { throw CONTAINER.invalidPersistentStorageMode(); } } public String name() { return attributes.attribute(AbstractCounterConfiguration.NAME).get(); } @Override public StrongCounterConfigurationBuilder addStrongCounter() { return builder.addStrongCounter(); } @Override public WeakCounterConfigurationBuilder addWeakCounter() { return builder.addWeakCounter(); } }
2,110
29.594203
143
java
null
infinispan-main/counter/src/main/java/org/infinispan/counter/configuration/Attribute.java
package org.infinispan.counter.configuration; import java.util.HashMap; import java.util.Map; /** * @author Pedro Ruivo * @since 9.0 */ public enum Attribute { // must be first UNKNOWN(null), CONCURRENCY_LEVEL("concurrency-level"), INITIAL_VALUE("initial-value"), LOWER_BOUND("lower-bound"), NAME("name"), NUM_OWNERS("num-owners"), RELIABILITY("reliability"), STORAGE("storage"), UPPER_BOUND("upper-bound"), VALUE("value"), LIFESPAN("lifespan"); private static final Map<String, Attribute> ATTRIBUTES; static { final Map<String, Attribute> map = new HashMap<>(64); for (Attribute attribute : values()) { final String name = attribute.name; if (name != null) { map.put(name, attribute); } } ATTRIBUTES = map; } private final String name; Attribute(final String name) { this.name = name; } public static Attribute forName(String localName) { final Attribute attribute = ATTRIBUTES.get(localName); return attribute == null ? UNKNOWN : attribute; } @Override public String toString() { return name; } }
1,166
21.018868
60
java
null
infinispan-main/counter/src/main/java/org/infinispan/counter/configuration/CounterParser.java
package org.infinispan.counter.configuration; import org.infinispan.commons.configuration.io.ConfigurationReader; import org.infinispan.commons.util.Version; 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.ParseUtils; import org.infinispan.configuration.parsing.Parser; import org.infinispan.configuration.parsing.Schema; import org.infinispan.counter.api.Storage; import org.kohsuke.MetaInfServices; /** * Counters configuration parser * * @author Pedro Ruivo * @since 9.0 */ @MetaInfServices @Namespace(root = "weak-counter") @Namespace(root = "strong-counter") @Namespace(uri = Parser.NAMESPACE + "*", root = "weak-counter") @Namespace(uri = Parser.NAMESPACE + "*", root = "strong-counter") public class CounterParser implements ConfigurationParser { static final String NAMESPACE = Parser.NAMESPACE + "counters:"; @Override public void readElement(ConfigurationReader reader, ConfigurationBuilderHolder holder) { GlobalConfigurationBuilder builder = holder.getGlobalConfigurationBuilder(); readElement(reader, builder.addModule(CounterManagerConfigurationBuilder.class), Element.forName(reader.getLocalName()), null); } public void readElement(ConfigurationReader reader, CounterManagerConfigurationBuilder builder, Element element, String name) { switch (element) { case STRONG_COUNTER: Schema schema = getSchema(reader); if (!schema.since(10, 0)) { parseStrongCounterLegacy(reader, builder.addStrongCounter().name(name)); } else { parseStrongCounter(reader, builder.addStrongCounter().name(name)); } break; case WEAK_COUNTER: parseWeakCounter(reader, builder.addWeakCounter().name(name)); break; default: throw ParseUtils.unexpectedElement(reader); } } @Override public Namespace[] getNamespaces() { return ParseUtils.getNamespaceAnnotations(getClass()); } private Schema getSchema(ConfigurationReader reader) { String namespaceURI = reader.getNamespace(); if (namespaceURI == null) return new Schema(NAMESPACE, Integer.parseInt(Version.getMajor()), Integer.parseInt(Version.getMinor())); return Schema.fromNamespaceURI(namespaceURI); } private void parseWeakCounter(ConfigurationReader reader, WeakCounterConfigurationBuilder 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)); if (attribute == Attribute.CONCURRENCY_LEVEL) { builder.concurrencyLevel(Integer.parseInt(value)); } else { parserCommonCounterAttributes(reader, builder, i, attribute, value); } } ParseUtils.requireNoContent(reader); } private void parseStrongCounterLegacy(ConfigurationReader reader, StrongCounterConfigurationBuilder 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)); parserCommonCounterAttributes(reader, builder, i, attribute, value); } while (reader.inTag()) { Element element = Element.forName(reader.getLocalName()); switch (element) { case UPPER_BOUND: parseUpperBound(reader, builder); break; case LOWER_BOUND: parseLowerBound(reader, builder); break; default: throw ParseUtils.unexpectedElement(reader); } } } private void parseUpperBound(ConfigurationReader reader, StrongCounterConfigurationBuilder 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)); if (attribute != Attribute.VALUE) { throw ParseUtils.unexpectedElement(reader); } builder.upperBound(Long.parseLong(value)); } ParseUtils.requireNoContent(reader); } private void parseLowerBound(ConfigurationReader reader, StrongCounterConfigurationBuilder 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)); if (attribute != Attribute.VALUE) { throw ParseUtils.unexpectedElement(reader); } builder.lowerBound(Long.parseLong(value)); } ParseUtils.requireNoContent(reader); } private void parseStrongCounter(ConfigurationReader reader, StrongCounterConfigurationBuilder 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 UPPER_BOUND: builder.upperBound(Long.parseLong(value)); break; case LOWER_BOUND: builder.lowerBound(Long.parseLong(value)); break; case LIFESPAN: builder.lifespan(Long.parseLong(value)); break; default: parserCommonCounterAttributes(reader, builder, i, attribute, value); } } ParseUtils.requireNoContent(reader); } private void parserCommonCounterAttributes(ConfigurationReader reader, CounterConfigurationBuilder<?,?> builder, int index, Attribute attribute, String value) { switch (attribute) { case NAME: // Already seen break; case INITIAL_VALUE: builder.initialValue(Long.parseLong(value)); break; case STORAGE: builder.storage(Storage.valueOf(value)); break; default: throw ParseUtils.unexpectedAttribute(reader, index); } } }
6,732
39.317365
133
java