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-dsl/src/main/java/org/infinispan/query/dsl/QueryResult.java
package org.infinispan.query.dsl; import java.util.List; import java.util.OptionalLong; /** * Represents the result of a {@link Query}. * <p> * If the query was executed using {@link Query#executeStatement()}, the list of results will be empty and * {@link #count()} will return the number of affected entries. * * @param <E> The type of the result. Queries having projections (a SELECT clause) will return an Object[] for each * result, with the field values. When not using SELECT, the results will contain instances of objects * corresponding to the cache values matching the query. * @since 11.0 */ public interface QueryResult<E> { /** * @return The number of hits from the query, ignoring pagination. When the query is non-indexed, for performance * reasons, the hit count is not calculated and will return {@link OptionalLong#empty()}. * * @deprecated replaced by {@link #count()} */ @Deprecated default OptionalLong hitCount() { TotalHitCount count = count(); return count.isExact() ? OptionalLong.of(count.value()) : OptionalLong.empty(); } /** * @return An object containing information about the number of hits from the query, ignoring pagination. */ TotalHitCount count(); /** * @return The results of the query as a List, respecting the bounds specified in {@link Query#startOffset(long)} and * {@link Query#maxResults(int)}. This never returns {@code null} but will always be an empty List for {@link Query#executeStatement}. */ List<E> list(); }
1,575
35.651163
137
java
null
infinispan-main/query-dsl/src/main/java/org/infinispan/query/dsl/RangeConditionContextQueryBuilder.java
package org.infinispan.query.dsl; /** * @since 9.0 * @deprecated since 10.1. See deprecation note on {@link QueryBuilder}. */ @Deprecated public interface RangeConditionContextQueryBuilder extends RangeConditionContext, QueryBuilder { }
241
23.2
96
java
null
infinispan-main/query-dsl/src/main/java/org/infinispan/query/dsl/ParameterContext.java
package org.infinispan.query.dsl; import java.util.Map; /** * @author anistor@redhat.com * @since 9.0 * @deprecated since 10.1. See deprecation note on {@link QueryBuilder}. */ @Deprecated public interface ParameterContext<Context extends ParameterContext> { /** * Returns the named parameters Map. * * @return the named parameters (unmodifiable) or {@code null} if the query does not have parameters */ Map<String, Object> getParameters(); /** * Sets the value of a named parameter. * * @param paramName the parameters name (non-empty and not null) * @param paramValue a non-null value * @return itself */ Context setParameter(String paramName, Object paramValue); /** * Sets multiple named parameters at once. Parameters names cannot be empty or {@code null}. Parameter values must * not be {@code null}. * * @param paramValues a Map of parameters * @return itself */ Context setParameters(Map<String, Object> paramValues); }
1,020
25.868421
117
java
null
infinispan-main/query-dsl/src/main/java/org/infinispan/query/dsl/Query.java
package org.infinispan.query.dsl; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; import org.infinispan.commons.util.CloseableIterator; import org.infinispan.query.SearchTimeoutException; //todo [anistor] We need to deprecate the 'always caching' behaviour and provide a clearCachedResults method /** * An immutable object representing both the query and the result. The result is obtained lazily when one of the methods * in this interface is executed first time. The query is executed only once. Further calls will just return the * previously cached results. If you intend to re-execute the query to obtain fresh data you need to build another * instance using a {@link QueryBuilder}. * * @author anistor@redhat.com * @since 6.0 */ public interface Query<T> extends Iterable<T>, PaginationContext<Query<T>>, ParameterContext<Query<T>> { /** * Returns the Ickle query string. */ String getQueryString(); /** * Returns the results of a search as a list. * * @return list of objects that were found from the search. */ List<T> list(); /** * Executes the query (a SELECT statement). Subsequent invocations cause the query to be re-executed. * <p> * Executing a DELETE is also allowed. No results will be returned in this case but the number of affected entries * will be returned as the hit count in the {@link QueryResult}. * * @return {@link QueryResult} with the results. * @since 11.0 */ QueryResult<T> execute(); /** * Executes a data modifying statement (typically a DELETE) that does not return results; instead it returns an * affected entries count. This method cannot be used to execute a SELECT. * <p> * <b>NOTE:</b> Paging params (firstResult/maxResults) are NOT allowed. * * @return the number of affected (deleted) entries */ int executeStatement(); /** * Gets the total number of results matching the query, ignoring pagination (startOffset, maxResults). * * @return total number of results. * @deprecated since 10.1. This will be removed in 12. It's closest replacement is {@link QueryResult#hitCount()} * which returns an optional long. */ @Deprecated int getResultSize(); /** * @return the values for query projections or {@code null} if the query does not have projections. * @deprecated since 11.0. This method will be removed in next major version. To find out if a query uses projections use {@link #hasProjections()} */ @Deprecated String[] getProjection(); /** * Indicates if the parsed query has projections (a SELECT clause) and consequently the returned results will * actually be {@code Object[]} containing the projected values rather than the target entity. * * @return {@code true} if it has projections, {@code false} otherwise. */ boolean hasProjections(); long getStartOffset(); Query<T> startOffset(long startOffset); int getMaxResults(); Query<T> maxResults(int maxResults); /** * @return current hitCountAccuracy if present * @see #hitCountAccuracy(int) */ Integer hitCountAccuracy(); /** * Limit the required accuracy of the hit count for the indexed queries to an upper-bound. * Setting the hit-count-accuracy could improve the performance of queries targeting large data sets. * * @param hitCountAccuracy The value to apply * @return <code>this</code>, for method chaining */ Query<T> hitCountAccuracy(int hitCountAccuracy); /** * Returns the named parameters Map. * * @return the named parameters (unmodifiable) or {@code null} if the query does not have parameters */ Map<String, Object> getParameters(); /** * Sets the value of a named parameter. * * @param paramName the parameters name (non-empty and not null) * @param paramValue a non-null value * @return itself */ Query<T> setParameter(String paramName, Object paramValue); /** * Sets multiple named parameters at once. Parameters names cannot be empty or {@code null}. Parameter values must * not be {@code null}. * * @param paramValues a Map of parameters * @return itself */ Query<T> setParameters(Map<String, Object> paramValues); /** * Returns a {@link CloseableIterator} over the results. Please close the iterator when you are done with processing * the results. * * @return the results of the query as an iterator. */ CloseableIterator<T> iterator(); /** * Returns a {@link CloseableIterator} over the results, including both key and value. Please close the iterator when * you are done with processing the results. The query cannot use projections. * * @return the results of the query as an iterator. */ <K> CloseableIterator<Map.Entry<K, T>> entryIterator(); /** * Set the timeout for this query. If the query hasn't finished processing before the timeout, * a {@link SearchTimeoutException} will be thrown. For queries that use the index, the timeout * is handled on a best effort basis, and the supplied time is rounded to the nearest millisecond. */ Query<T> timeout(long timeout, TimeUnit timeUnit); /** * Set the query execution scope * * @param local if true, query will be restricted to the data present in the local node, ignoring the other * members of the clusters */ Query<T> local(boolean local); }
5,539
33.625
150
java
null
infinispan-main/query-dsl/src/main/java/org/infinispan/query/dsl/FilterConditionContext.java
package org.infinispan.query.dsl; /** * The context of a complete filter. Provides operations to allow connecting multiple filters together with boolean * operators. * * @author anistor@redhat.com * @since 6.0 * @deprecated since 10.1. See deprecation note on {@link QueryBuilder}. */ @Deprecated public interface FilterConditionContext { /** * Creates a new context and connects it with the current one using boolean AND. The new context is added after the * current one. The two conditions are not grouped so operator precedence in the resulting condition might change. * <p/> * The effect is: a AND b * * @return the new context */ FilterConditionBeginContext and(); /** * Connects a given context with the current one using boolean AND. The new context is added after the current one * and is grouped. Operator precedence will be unaffected due to grouping. * <p/> * The effect is: a AND (b) * * @param rightCondition the second condition * @return the new context */ FilterConditionContextQueryBuilder and(FilterConditionContext rightCondition); /** * Creates a new context and connects it with the current one using boolean OR. The new context is added after the * current one. * <p/> * The effect is: a OR b * * @return the new context */ FilterConditionBeginContext or(); /** * Connects a given context with the current one using boolean OR. The new context is added after the current one and * is grouped. * <p/> * The effect is: a OR (b) * * @param rightCondition the second condition * @return the new context */ FilterConditionContextQueryBuilder or(FilterConditionContext rightCondition); /** * Get the {@link QueryBuilder} that created this context. As of Infinispan 9.0 this is no longer needed. * * @return the parent builder * @deprecated To be removed in Infinispan 10.0 without replacement. */ @Deprecated QueryBuilder toBuilder(); }
2,039
30.384615
120
java
null
infinispan-main/query-dsl/src/main/java/org/infinispan/query/dsl/RangeConditionContext.java
package org.infinispan.query.dsl; /** * A context for ranges. Allow specifying if the bounds are included or not. They are included by default. This context * is considered completed. * * @author anistor@redhat.com * @since 6.0 * @deprecated since 10.1. See deprecation note on {@link QueryBuilder}. */ @Deprecated public interface RangeConditionContext extends FilterConditionContext { RangeConditionContextQueryBuilder includeLower(boolean includeLower); RangeConditionContextQueryBuilder includeUpper(boolean includeUpper); }
545
29.333333
119
java
null
infinispan-main/query-dsl/src/main/java/org/infinispan/query/dsl/QueryBuilder.java
package org.infinispan.query.dsl; /** * A builder for {@link Query} objects. An instance of this class can be obtained from {@link QueryFactory}. * * @author anistor@redhat.com * @since 6.0 * @deprecated since 10.1. The Ickle query language is now preferred over the {@code QueryBuilder}. See {@link * QueryFactory#create}. The {@code QueryBuilder} and associated context interfaces will be removed in version 11.0. */ @Deprecated public interface QueryBuilder extends FilterConditionBeginContext, PaginationContext<QueryBuilder> { QueryBuilder orderBy(Expression expression); QueryBuilder orderBy(Expression expression, SortOrder sortOrder); QueryBuilder orderBy(String attributePath); QueryBuilder orderBy(String attributePath, SortOrder sortOrder); QueryBuilder select(Expression... projection); QueryBuilder select(String... attributePath); QueryBuilder groupBy(String... attributePath); /** * Builds the query object. Once built, the query is immutable (except for the named parameters). * * @return the Query */ <T> Query<T> build(); }
1,101
30.485714
116
java
null
infinispan-main/query-dsl/src/main/java/org/infinispan/query/dsl/PaginationContext.java
package org.infinispan.query.dsl; /** * @author anistor@redhat.com * @since 9.0 * @deprecated since 10.1. See deprecation note on {@link QueryBuilder}. */ @Deprecated public interface PaginationContext<Context extends PaginationContext> { Context startOffset(long startOffset); Context maxResults(int maxResults); }
329
21
72
java
null
infinispan-main/query-dsl/src/main/java/org/infinispan/query/dsl/SortOrder.java
package org.infinispan.query.dsl; /** * Enumeration of the available sort directions. * * @author anistor@redhat.com * @since 6.0 * @deprecated since 10.1. See deprecation note on {@link QueryBuilder}. */ @Deprecated public enum SortOrder { ASC, DESC }
263
17.857143
72
java
null
infinispan-main/query-dsl/src/main/java/org/infinispan/query/dsl/QueryFactory.java
package org.infinispan.query.dsl; /** * Factory for query DSL objects. Query construction starts here, usually by invoking the {@link #from} method which * returns a {@link QueryBuilder} capable of constructing {@link Query} objects. The other methods are use for creating * sub-conditions. * * <p><b>NOTE:</b> Most methods in this class are deprecated, except {@link #create(java.lang.String)}. Please do not * use any of the deprecated methods or else you will experience difficulties in porting your code to the new query API * that will be introduced by Infinispan 12. * * @author anistor@redhat.com * @since 6.0 */ public interface QueryFactory { /** * Creates a Query based on an Ickle query string. * * @return a query */ <T> Query<T> create(String queryString); /** * Creates a QueryBuilder for the given entity type. * * @param entityType the Class of the entity * @return a builder capable of creating queries for the specified entity type * @deprecated since 10.1. See deprecation note on {@link QueryBuilder}. */ @Deprecated QueryBuilder from(Class<?> entityType); /** * Creates a QueryBuilder for the given entity type. * * @param entityType fully qualified entity type name * @return a builder capable of creating queries for the specified entity type * @deprecated since 10.1. See deprecation note on {@link QueryBuilder}. */ @Deprecated QueryBuilder from(String entityType); /** * Creates a condition on the given attribute path that is to be completed later by using it as a sub-condition. * * @param expression a path Expression * @return the incomplete sub-condition * @deprecated since 10.1. See deprecation note on {@link QueryBuilder}. */ @Deprecated FilterConditionEndContext having(Expression expression); /** * Creates a condition on the given attribute path that is to be completed later by using it as a sub-condition. * * @param attributePath the attribute path * @return the incomplete sub-condition * @deprecated since 10.1. See deprecation note on {@link QueryBuilder}. */ @Deprecated FilterConditionEndContext having(String attributePath); /** * Creates a negated condition that is to be completed later by using it as a sub-condition. * * @return the incomplete sub-condition * @deprecated since 10.1. See deprecation note on {@link QueryBuilder}. */ @Deprecated FilterConditionBeginContext not(); /** * Creates a negated condition based on a given sub-condition. The negation is grouped. * * @return the incomplete sub-condition * @deprecated since 10.1. See deprecation note on {@link QueryBuilder}. */ @Deprecated FilterConditionContext not(FilterConditionContext fcc); }
2,839
33.634146
119
java
null
infinispan-main/query-dsl/src/main/java/org/infinispan/query/dsl/TotalHitCount.java
package org.infinispan.query.dsl; public class TotalHitCount { public static final TotalHitCount EMPTY = new TotalHitCount(0, true); private final int value; private final boolean exact; public TotalHitCount(int value, boolean exact) { this.value = value; this.exact = exact; } /** * This returned value could be exact or a lower-bound of the exact value. * <p> * When the query is non-indexed, for performance reasons, * the hit count is not calculated and will return -1. * * @return the total hit count value * @see #isExact() */ public int value() { return value; } /** * For efficiency reasons the computation of the hit count could be limited to some upper bound. * If the hit account accuracy is limited, the {@link #value()} here could be a lower-bound of the exact value, * and in this case this method will return {@code false}. * * @return whether the {@link #value()} is exact */ public boolean isExact() { return exact; } }
1,056
26.102564
114
java
null
infinispan-main/query-dsl/src/main/java/org/infinispan/query/dsl/FilterConditionEndContext.java
package org.infinispan.query.dsl; import java.util.Collection; /** * The context that ends a condition. Here we are expected to specify the right hand side of the filter condition, the * operator and the operand, in order to complete the filter. * * @author anistor@redhat.com * @since 6.0 * @deprecated since 10.1. See deprecation note on {@link QueryBuilder}. */ @Deprecated public interface FilterConditionEndContext { /** * Checks that the left operand is equal to one of the (fixed) list of values given as argument. * * @param values the list of values * @return the completed context */ FilterConditionContextQueryBuilder in(Object... values); /** * Checks that the left operand is equal to one of the elements from the Collection of values given as argument. * * @param values the collection of values * @return the completed context */ FilterConditionContextQueryBuilder in(Collection values); /** * Checks that the left argument (which is expected to be a String) matches a wildcard pattern that follows the JPA * rules. * * @param pattern the wildcard pattern * @return the completed context */ FilterConditionContextQueryBuilder like(String pattern); /** * Checks that the left argument (which is expected to be an array or a Collection) contains the given element. * * @param value the value to check * @return the completed context */ FilterConditionContextQueryBuilder contains(Object value); /** * Checks that the left argument (which is expected to be an array or a Collection) contains all of the the given * elements, in any order. * * @param values the list of elements to check * @return the completed context */ FilterConditionContextQueryBuilder containsAll(Object... values); /** * Checks that the left argument (which is expected to be an array or a Collection) contains all the elements of the * given collection, in any order. * * @param values the Collection of elements to check * @return the completed context */ FilterConditionContextQueryBuilder containsAll(Collection values); /** * Checks that the left argument (which is expected to be an array or a Collection) contains any of the the given * elements. * * @param values the list of elements to check * @return the completed context */ FilterConditionContextQueryBuilder containsAny(Object... values); /** * Checks that the left argument (which is expected to be an array or a Collection) contains any of the elements of * the given collection. * * @param values the Collection of elements to check * @return the completed context */ FilterConditionContextQueryBuilder containsAny(Collection values); /** * Checks that the left argument is null. * * @return the completed context */ FilterConditionContextQueryBuilder isNull(); /** * Checks that the left argument is equal to the given value. * * @param value the value to compare with * @return the completed context */ <T extends QueryBuilder & FilterConditionContext> T eq(Object value); /** * Alias for {@link #eq(Object)} */ FilterConditionContextQueryBuilder equal(Object value); /** * Checks that the left argument is less than the given value. * * @param value the value to compare with * @return the completed context */ FilterConditionContextQueryBuilder lt(Object value); /** * Checks that the left argument is less than or equal to the given value. * * @param value the value to compare with * @return the completed context */ FilterConditionContextQueryBuilder lte(Object value); /** * Checks that the left argument is greater than the given value. * * @param value the value to compare with * @return the completed context */ FilterConditionContextQueryBuilder gt(Object value); /** * Checks that the left argument is greater than or equal to the given value. * * @param value the value to compare with * @return the completed context */ FilterConditionContextQueryBuilder gte(Object value); /** * Checks that the left argument is between the given range limits. The limits are inclusive by default, but this can * be changed using the methods from the returned {@link RangeConditionContext} * * @param from the start of the range * @param to the end of the range * @return the RangeConditionContext context */ RangeConditionContextQueryBuilder between(Object from, Object to); }
4,685
30.877551
120
java
null
infinispan-main/query-dsl/src/main/java/org/infinispan/query/dsl/FilterConditionBeginContext.java
package org.infinispan.query.dsl; /** * The beginning context of an incomplete condition. It exposes methods for specifying the left hand side of the * condition. * * @author anistor@redhat.com * @since 6.0 * @deprecated since 10.1. See deprecation note on {@link QueryBuilder}. */ @Deprecated public interface FilterConditionBeginContext { FilterConditionEndContext having(String attributePath); FilterConditionEndContext having(Expression expression); FilterConditionContextQueryBuilder not(); FilterConditionContextQueryBuilder not(FilterConditionContext fcc); }
590
25.863636
112
java
null
infinispan-main/query-dsl/src/main/java/org/infinispan/query/dsl/FilterConditionContextQueryBuilder.java
package org.infinispan.query.dsl; /** * @since 9.0 * @deprecated since 10.1. See deprecation note on {@link QueryBuilder}. */ @Deprecated public interface FilterConditionContextQueryBuilder extends FilterConditionContext, QueryBuilder { }
243
23.4
98
java
null
infinispan-main/query-dsl/src/main/java/org/infinispan/query/dsl/impl/AttributeCondition.java
package org.infinispan.query.dsl.impl; import java.util.Collection; import org.infinispan.query.dsl.Expression; import org.infinispan.query.dsl.FilterConditionEndContext; import org.infinispan.query.dsl.QueryFactory; import org.infinispan.query.dsl.RangeConditionContextQueryBuilder; import org.infinispan.query.dsl.impl.logging.Log; import org.jboss.logging.Logger; /** * @author anistor@redhat.com * @since 6.0 */ final class AttributeCondition extends BaseCondition implements FilterConditionEndContext, RangeConditionContextQueryBuilder { private static final Log log = Logger.getMessageLogger(Log.class, AttributeCondition.class.getName()); private final Expression expression; private boolean isNegated; private OperatorAndArgument operatorAndArgument; public AttributeCondition(QueryFactory queryFactory, Expression expression) { super(queryFactory); this.expression = expression; } OperatorAndArgument getOperatorAndArgument() { return operatorAndArgument; } Expression getExpression() { return expression; } boolean isNegated() { return isNegated; } void setNegated(boolean negated) { isNegated = negated; } @Override public BaseCondition in(Object... values) { if (values == null || values.length == 0) { throw log.listOfValuesForInCannotBeNulOrEmpty(); } setOperatorAndArgument(new InOperator(this, values)); return this; } @Override public BaseCondition in(Collection values) { if (values == null || values.isEmpty()) { throw log.listOfValuesForInCannotBeNulOrEmpty(); } setOperatorAndArgument(new InOperator(this, values)); return this; } @Override public BaseCondition like(String pattern) { setOperatorAndArgument(new LikeOperator(this, pattern)); return this; } @Override public BaseCondition contains(Object value) { setOperatorAndArgument(new ContainsOperator(this, value)); return this; } @Override public BaseCondition containsAll(Object... values) { setOperatorAndArgument(new ContainsAllOperator(this, values)); return this; } @Override public BaseCondition containsAll(Collection values) { setOperatorAndArgument(new ContainsAllOperator(this, values)); return this; } @Override public BaseCondition containsAny(Object... values) { setOperatorAndArgument(new ContainsAnyOperator(this, values)); return this; } @Override public BaseCondition containsAny(Collection values) { setOperatorAndArgument(new ContainsAnyOperator(this, values)); return this; } @Override public BaseCondition isNull() { setOperatorAndArgument(new IsNullOperator(this)); return this; } @Override public BaseCondition eq(Object value) { setOperatorAndArgument(new EqOperator(this, value)); return this; } @Override public BaseCondition equal(Object value) { return eq(value); } @Override public BaseCondition lt(Object value) { setOperatorAndArgument(new LtOperator(this, value)); return this; } @Override public BaseCondition lte(Object value) { setOperatorAndArgument(new LteOperator(this, value)); return this; } @Override public BaseCondition gt(Object value) { setOperatorAndArgument(new GtOperator(this, value)); return this; } @Override public BaseCondition gte(Object value) { setOperatorAndArgument(new GteOperator(this, value)); return this; } @Override public AttributeCondition between(Object from, Object to) { setOperatorAndArgument(new BetweenOperator(this, new ValueRange(from, to))); return this; } @Override public AttributeCondition includeLower(boolean includeLower) { ValueRange valueRange = (ValueRange) operatorAndArgument.getArgument(); valueRange.setIncludeLower(includeLower); return this; } @Override public AttributeCondition includeUpper(boolean includeUpper) { ValueRange valueRange = (ValueRange) operatorAndArgument.getArgument(); valueRange.setIncludeUpper(includeUpper); return this; } private void setOperatorAndArgument(OperatorAndArgument operatorAndArgument) { operatorAndArgument.validate(); if (this.operatorAndArgument != null) { throw log.operatorWasAlreadySpecified(); } this.operatorAndArgument = operatorAndArgument; } @Override public <ReturnType> ReturnType accept(Visitor<ReturnType> visitor) { return visitor.visit(this); } @Override public String toString() { return "AttributeCondition{" + "isNegated=" + isNegated + ", expression='" + expression + '\'' + ", operatorAndArgument=" + operatorAndArgument + '}'; } }
4,918
25.446237
126
java
null
infinispan-main/query-dsl/src/main/java/org/infinispan/query/dsl/impl/BaseQueryFactory.java
package org.infinispan.query.dsl.impl; import org.infinispan.query.dsl.Expression; import org.infinispan.query.dsl.FilterConditionBeginContext; import org.infinispan.query.dsl.FilterConditionContext; import org.infinispan.query.dsl.FilterConditionEndContext; import org.infinispan.query.dsl.QueryFactory; import org.infinispan.query.dsl.impl.logging.Log; import org.jboss.logging.Logger; /** * @author anistor@redhat.com * @since 6.0 */ public abstract class BaseQueryFactory implements QueryFactory { private static final Log log = Logger.getMessageLogger(Log.class, BaseQueryFactory.class.getName()); @Override public FilterConditionEndContext having(String attributePath) { return having(Expression.property(attributePath)); } @Override public FilterConditionEndContext having(Expression expression) { return new AttributeCondition(this, expression); } @Override public FilterConditionBeginContext not() { return new IncompleteCondition(this).not(); } @Override public FilterConditionContext not(FilterConditionContext fcc) { if (fcc == null) { throw log.argumentCannotBeNull(); } BaseCondition baseCondition = ((BaseCondition) fcc).getRoot(); if (baseCondition.queryFactory != this) { throw log.conditionWasCreatedByAnotherFactory(); } if (baseCondition.queryBuilder != null) { throw log.conditionIsAlreadyInUseByAnotherBuilder(); } NotCondition notCondition = new NotCondition(this, baseCondition); baseCondition.setParent(notCondition); return notCondition; } }
1,623
30.230769
103
java
null
infinispan-main/query-dsl/src/main/java/org/infinispan/query/dsl/impl/Visitor.java
package org.infinispan.query.dsl.impl; /** * @author anistor@redhat.com * @since 6.0 */ interface Visitor<ReturnType> { ReturnType visit(EqOperator operator); ReturnType visit(GtOperator operator); ReturnType visit(GteOperator operator); ReturnType visit(LtOperator operator); ReturnType visit(LteOperator operator); ReturnType visit(BetweenOperator operator); ReturnType visit(LikeOperator operator); ReturnType visit(IsNullOperator operator); ReturnType visit(InOperator operator); ReturnType visit(ContainsOperator operator); ReturnType visit(ContainsAllOperator operator); ReturnType visit(ContainsAnyOperator operator); ReturnType visit(AttributeCondition attributeCondition); ReturnType visit(AndCondition booleanCondition); ReturnType visit(OrCondition booleanCondition); ReturnType visit(NotCondition notCondition); ReturnType visit(BaseQueryBuilder baseQueryBuilder); }
951
21.139535
59
java
null
infinispan-main/query-dsl/src/main/java/org/infinispan/query/dsl/impl/package-info.java
/** * Query builder DSL implementation for Ickle (a JP-QL subset). * * @author anistor@redhat.com * @since 6.0 * @deprecated since 10.1. This will be removed in 11. * @api.private */ package org.infinispan.query.dsl.impl;
229
22
63
java
null
infinispan-main/query-dsl/src/main/java/org/infinispan/query/dsl/impl/IsNullOperator.java
package org.infinispan.query.dsl.impl; /** * @author anistor@redhat.com * @since 6.0 */ class IsNullOperator extends OperatorAndArgument<Void> { protected IsNullOperator(AttributeCondition parentCondition) { super(parentCondition, null); } @Override public <ReturnType> ReturnType accept(Visitor<ReturnType> visitor) { return visitor.visit(this); } @Override void validate() { // no validation rules for 'isNull' } }
466
19.304348
71
java
null
infinispan-main/query-dsl/src/main/java/org/infinispan/query/dsl/impl/NotCondition.java
package org.infinispan.query.dsl.impl; import org.infinispan.query.dsl.QueryFactory; /** * @author anistor@redhat.com * @since 6.0 */ final class NotCondition extends BooleanCondition { NotCondition(QueryFactory queryFactory, BaseCondition condition) { super(queryFactory, condition, null); } @Override public <ReturnType> ReturnType accept(Visitor<ReturnType> visitor) { return visitor.visit(this); } @Override public String toString() { return "NOT (" + getFirstCondition() + ")"; } }
537
20.52
71
java
null
infinispan-main/query-dsl/src/main/java/org/infinispan/query/dsl/impl/OrCondition.java
package org.infinispan.query.dsl.impl; import org.infinispan.query.dsl.QueryFactory; /** * @author anistor@redhat.com * @since 6.0 */ final class OrCondition extends BooleanCondition { OrCondition(QueryFactory queryFactory, BaseCondition leftCondition, BaseCondition rightCondition) { super(queryFactory, leftCondition, rightCondition); } @Override public <ReturnType> ReturnType accept(Visitor<ReturnType> visitor) { return visitor.visit(this); } @Override public String toString() { return "(" + getFirstCondition() + ") OR (" + getSecondCondition() + ")"; } }
613
23.56
102
java
null
infinispan-main/query-dsl/src/main/java/org/infinispan/query/dsl/impl/ContainsAnyOperator.java
package org.infinispan.query.dsl.impl; /** * @author anistor@redhat.com * @since 6.0 */ class ContainsAnyOperator extends OperatorAndArgument<Object> { protected ContainsAnyOperator(AttributeCondition parentCondition, Object argument) { super(parentCondition, argument); } @Override public <ReturnType> ReturnType accept(Visitor<ReturnType> visitor) { return visitor.visit(this); } }
417
22.222222
87
java
null
infinispan-main/query-dsl/src/main/java/org/infinispan/query/dsl/impl/Visitable.java
package org.infinispan.query.dsl.impl; /** * @author anistor@redhat.com * @since 6.0 */ interface Visitable { <ReturnType> ReturnType accept(Visitor<ReturnType> visitor); }
181
15.545455
63
java
null
infinispan-main/query-dsl/src/main/java/org/infinispan/query/dsl/impl/ContainsOperator.java
package org.infinispan.query.dsl.impl; /** * @author anistor@redhat.com * @since 6.0 */ class ContainsOperator extends OperatorAndArgument<Object> { protected ContainsOperator(AttributeCondition parentCondition, Object argument) { super(parentCondition, argument); } @Override public <ReturnType> ReturnType accept(Visitor<ReturnType> visitor) { return visitor.visit(this); } }
411
21.888889
84
java
null
infinispan-main/query-dsl/src/main/java/org/infinispan/query/dsl/impl/GtOperator.java
package org.infinispan.query.dsl.impl; /** * @author anistor@redhat.com * @since 6.0 */ class GtOperator extends OperatorAndArgument<Object> { protected GtOperator(AttributeCondition parentCondition, Object argument) { super(parentCondition, argument); } @Override public <ReturnType> ReturnType accept(Visitor<ReturnType> visitor) { return visitor.visit(this); } }
399
21.222222
78
java
null
infinispan-main/query-dsl/src/main/java/org/infinispan/query/dsl/impl/PathExpression.java
package org.infinispan.query.dsl.impl; import org.infinispan.query.dsl.Expression; /** * Represents the path of a field, including the aggregation function if any. * * @author anistor@redhat.com * @since 8.0 */ public final class PathExpression implements Expression { public enum AggregationType { SUM, AVG, MIN, MAX, COUNT } /** * Optional aggregation type. */ private final AggregationType aggregationType; private final String path; public PathExpression(AggregationType aggregationType, String path) { this.aggregationType = aggregationType; this.path = path; } public AggregationType getAggregationType() { return aggregationType; } public String getPath() { return path; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || o.getClass() != PathExpression.class) return false; PathExpression that = (PathExpression) o; return aggregationType == that.aggregationType && path.equals(that.path); } @Override public int hashCode() { return 31 * (aggregationType != null ? aggregationType.hashCode() : 0) + path.hashCode(); } @Override public String toString() { return aggregationType != null ? aggregationType.name() + '(' + path + ')' : path; } }
1,339
23.363636
95
java
null
infinispan-main/query-dsl/src/main/java/org/infinispan/query/dsl/impl/EqOperator.java
package org.infinispan.query.dsl.impl; /** * @author anistor@redhat.com * @since 6.0 */ class EqOperator extends OperatorAndArgument<Object> { protected EqOperator(AttributeCondition parentCondition, Object argument) { super(parentCondition, argument); } @Override public <ReturnType> ReturnType accept(Visitor<ReturnType> visitor) { return visitor.visit(this); } }
399
21.222222
78
java
null
infinispan-main/query-dsl/src/main/java/org/infinispan/query/dsl/impl/ContainsAllOperator.java
package org.infinispan.query.dsl.impl; /** * @author anistor@redhat.com * @since 6.0 */ class ContainsAllOperator extends OperatorAndArgument<Object> { protected ContainsAllOperator(AttributeCondition parentCondition, Object argument) { super(parentCondition, argument); } @Override public <ReturnType> ReturnType accept(Visitor<ReturnType> visitor) { return visitor.visit(this); } }
417
22.222222
87
java
null
infinispan-main/query-dsl/src/main/java/org/infinispan/query/dsl/impl/IncompleteCondition.java
package org.infinispan.query.dsl.impl; import org.infinispan.query.dsl.Expression; import org.infinispan.query.dsl.FilterConditionBeginContext; import org.infinispan.query.dsl.FilterConditionContext; import org.infinispan.query.dsl.FilterConditionEndContext; import org.infinispan.query.dsl.QueryBuilder; import org.infinispan.query.dsl.QueryFactory; import org.infinispan.query.dsl.impl.logging.Log; import org.jboss.logging.Logger; /** * @author anistor@redhat.com * @since 6.0 */ final class IncompleteCondition extends BaseCondition implements FilterConditionBeginContext { private static final Log log = Logger.getMessageLogger(Log.class, IncompleteCondition.class.getName()); private boolean isNegated = false; private BaseCondition filterCondition; IncompleteCondition(QueryFactory queryFactory) { super(queryFactory); } @Override void setQueryBuilder(QueryBuilder queryBuilder) { super.setQueryBuilder(queryBuilder); if (filterCondition != null) { filterCondition.setQueryBuilder(queryBuilder); } } @Override public <ReturnType> ReturnType accept(Visitor<ReturnType> visitor) { if (filterCondition == null) { throw log.incompleteCondition(); } return filterCondition.accept(visitor); } @Override public FilterConditionEndContext having(Expression expression) { if (filterCondition != null) { throw log.cannotUseOperatorAgain("having(..)"); } AttributeCondition attributeCondition = new AttributeCondition(queryFactory, expression); attributeCondition.setNegated(isNegated); attributeCondition.setQueryBuilder(queryBuilder); attributeCondition.setParent(this); filterCondition = attributeCondition; return attributeCondition; } @Override public FilterConditionEndContext having(String attributePath) { return having(Expression.property(attributePath)); } @Override public BaseCondition not() { if (filterCondition != null) { throw log.cannotUseOperatorAgain("not()"); } isNegated = !isNegated; return this; } @Override public BaseCondition not(FilterConditionContext fcc) { if (fcc == null) { throw log.argumentCannotBeNull(); } if (filterCondition != null) { throw log.cannotUseOperatorAgain("not(..)"); } BaseCondition baseCondition = ((BaseCondition) fcc).getRoot(); if (baseCondition.queryFactory != queryFactory) { throw log.conditionWasCreatedByAnotherFactory(); } if (baseCondition.queryBuilder != null) { throw log.conditionIsAlreadyInUseByAnotherBuilder(); } isNegated = !isNegated; if (isNegated) { NotCondition notCondition = new NotCondition(queryFactory, baseCondition); notCondition.setQueryBuilder(queryBuilder); filterCondition = notCondition; } else { baseCondition.setQueryBuilder(queryBuilder); filterCondition = baseCondition; } return filterCondition; } }
3,094
29.048544
106
java
null
infinispan-main/query-dsl/src/main/java/org/infinispan/query/dsl/impl/OperatorAndArgument.java
package org.infinispan.query.dsl.impl; import org.infinispan.query.dsl.impl.logging.Log; import org.jboss.logging.Logger; /** * @author anistor@redhat.com * @since 6.0 */ abstract class OperatorAndArgument<ArgumentType> implements Visitable { private static final Log log = Logger.getMessageLogger(Log.class, OperatorAndArgument.class.getName()); protected final AttributeCondition attributeCondition; protected final ArgumentType argument; protected OperatorAndArgument(AttributeCondition attributeCondition, ArgumentType argument) { if (attributeCondition == null) { throw log.argumentCannotBeNull("attributeCondition"); } this.attributeCondition = attributeCondition; this.argument = argument; } AttributeCondition getAttributeCondition() { return attributeCondition; } ArgumentType getArgument() { return argument; } //todo [anistor] must also validate that the argument type is compatible with the operator void validate() { if (argument == null) { throw log.argumentCannotBeNull(); } } @Override public String toString() { return getClass().getSimpleName() + "{argument=" + argument + '}'; } }
1,230
25.76087
106
java
null
infinispan-main/query-dsl/src/main/java/org/infinispan/query/dsl/impl/BaseQueryBuilder.java
package org.infinispan.query.dsl.impl; import java.util.ArrayList; import java.util.List; import org.infinispan.query.dsl.Expression; import org.infinispan.query.dsl.FilterConditionContext; import org.infinispan.query.dsl.FilterConditionEndContext; import org.infinispan.query.dsl.QueryBuilder; import org.infinispan.query.dsl.QueryFactory; import org.infinispan.query.dsl.SortOrder; import org.infinispan.query.dsl.impl.logging.Log; import org.jboss.logging.Logger; /** * @author anistor@redhat.com * @since 6.0 */ public abstract class BaseQueryBuilder implements QueryBuilder, Visitable { private static final Log log = Logger.getMessageLogger(Log.class, BaseQueryBuilder.class.getName()); protected final QueryFactory queryFactory; /** * The fully qualified name of the entity being queried. It can be a Java Class name or a Protobuf message type * name. */ protected final String rootTypeName; /** * The attribute paths for the projection. */ protected Expression[] projection; protected String[] groupBy; protected BaseCondition filterCondition; protected BaseCondition whereFilterCondition; protected BaseCondition havingFilterCondition; protected List<SortCriteria> sortCriteria; protected long startOffset = -1; protected int maxResults = -1; protected BaseQueryBuilder(QueryFactory queryFactory, String rootTypeName) { if (rootTypeName == null) { throw log.argumentCannotBeNull("rootTypeName"); } this.queryFactory = queryFactory; this.rootTypeName = rootTypeName; } protected String getRootTypeName() { return rootTypeName; } @Override public QueryBuilder orderBy(Expression pathExpression) { return orderBy(pathExpression, SortOrder.ASC); } @Override public QueryBuilder orderBy(Expression pathExpression, SortOrder sortOrder) { if (sortCriteria == null) { sortCriteria = new ArrayList<>(); } sortCriteria.add(new SortCriteria(pathExpression, sortOrder)); return this; } @Override public QueryBuilder orderBy(String attributePath) { return orderBy(attributePath, SortOrder.ASC); } @Override public QueryBuilder orderBy(String attributePath, SortOrder sortOrder) { return orderBy(Expression.property(attributePath), sortOrder); } protected List<SortCriteria> getSortCriteria() { return sortCriteria; } @Override public QueryBuilder select(String... attributePath) { if (attributePath == null || attributePath.length == 0) { throw log.projectionCannotBeNullOrEmpty(); } Expression[] projection = new Expression[attributePath.length]; for (int i = 0; i < attributePath.length; i++) { projection[i] = Expression.property(attributePath[i]); } return select(projection); } @Override public QueryBuilder select(Expression... projection) { if (projection == null || projection.length == 0) { throw log.projectionCannotBeNullOrEmpty(); } if (this.projection != null) { throw log.projectionCanBeSpecifiedOnlyOnce(); } this.projection = projection; return this; } protected Expression[] getProjection() { return projection; } protected String[] getProjectionPaths() { if (projection == null) { return null; } String[] _projection = new String[projection.length]; for (int i = 0; i < projection.length; i++) { _projection[i] = projection[i].toString(); } return _projection; } @Override public QueryBuilder groupBy(String... groupBy) { if (groupBy == null || groupBy.length == 0) { throw log.groupingCannotBeNullOrEmpty(); } if (this.groupBy != null) { throw log.groupingCanBeSpecifiedOnlyOnce(); } this.groupBy = groupBy; // reset this so we can start a new filter for havingFilterCondition filterCondition = null; return this; } protected String[] getGroupBy() { return groupBy; } @Override public QueryBuilder startOffset(long startOffset) { if (startOffset < 0) { throw log.startOffsetCannotBeLessThanZero(); } this.startOffset = startOffset; return this; } @Override public QueryBuilder maxResults(int maxResults) { if (maxResults <= 0) { throw log.maxResultMustBeGreaterThanZero(); } this.maxResults = maxResults; return this; } protected BaseCondition getWhereFilterCondition() { return whereFilterCondition; } protected BaseCondition getHavingFilterCondition() { return havingFilterCondition; } @Override public FilterConditionEndContext having(Expression expression) { if (filterCondition != null) { throw log.cannotUseOperatorAgain("having(..)"); } AttributeCondition attributeCondition = new AttributeCondition(queryFactory, expression); attributeCondition.setQueryBuilder(this); setFilterCondition(attributeCondition); return attributeCondition; } @Override public FilterConditionEndContext having(String attributePath) { return having(Expression.property(attributePath)); } private void setFilterCondition(BaseCondition filterCondition) { this.filterCondition = filterCondition; if (groupBy == null) { whereFilterCondition = filterCondition; } else { havingFilterCondition = filterCondition; } } @Override public BaseCondition not() { if (filterCondition != null) { throw log.cannotUseOperatorAgain("not()"); } IncompleteCondition incompleteCondition = new IncompleteCondition(queryFactory); incompleteCondition.setQueryBuilder(this); setFilterCondition(incompleteCondition); return incompleteCondition.not(); } @Override public BaseCondition not(FilterConditionContext fcc) { if (fcc == null) { throw log.argumentCannotBeNull(); } if (filterCondition != null) { throw log.cannotUseOperatorAgain("not(..)"); } BaseCondition baseCondition = ((BaseCondition) fcc).getRoot(); if (baseCondition.queryFactory != queryFactory) { throw log.conditionWasCreatedByAnotherFactory(); } if (baseCondition.queryBuilder != null) { throw log.conditionIsAlreadyInUseByAnotherBuilder(); } NotCondition notCondition = new NotCondition(queryFactory, baseCondition); notCondition.setQueryBuilder(this); baseCondition.setParent(notCondition); setFilterCondition(notCondition); return filterCondition; } @Override public <ReturnType> ReturnType accept(Visitor<ReturnType> visitor) { return visitor.visit(this); } }
6,865
27.728033
114
java
null
infinispan-main/query-dsl/src/main/java/org/infinispan/query/dsl/impl/LikeOperator.java
package org.infinispan.query.dsl.impl; /** * @author anistor@redhat.com * @since 6.0 */ class LikeOperator extends OperatorAndArgument<String> { protected LikeOperator(AttributeCondition parentCondition, String argument) { super(parentCondition, argument); } @Override public <ReturnType> ReturnType accept(Visitor<ReturnType> visitor) { return visitor.visit(this); } }
403
21.444444
80
java
null
infinispan-main/query-dsl/src/main/java/org/infinispan/query/dsl/impl/LtOperator.java
package org.infinispan.query.dsl.impl; /** * @author anistor@redhat.com * @since 6.0 */ class LtOperator extends OperatorAndArgument<Object> { protected LtOperator(AttributeCondition parentCondition, Object argument) { super(parentCondition, argument); } @Override public <ReturnType> ReturnType accept(Visitor<ReturnType> visitor) { return visitor.visit(this); } }
399
21.222222
78
java
null
infinispan-main/query-dsl/src/main/java/org/infinispan/query/dsl/impl/GteOperator.java
package org.infinispan.query.dsl.impl; /** * @author anistor@redhat.com * @since 6.0 */ class GteOperator extends OperatorAndArgument<Object> { protected GteOperator(AttributeCondition parentCondition, Object argument) { super(parentCondition, argument); } @Override public <ReturnType> ReturnType accept(Visitor<ReturnType> visitor) { return visitor.visit(this); } }
401
21.333333
79
java
null
infinispan-main/query-dsl/src/main/java/org/infinispan/query/dsl/impl/AndCondition.java
package org.infinispan.query.dsl.impl; import org.infinispan.query.dsl.QueryFactory; /** * @author anistor@redhat.com * @since 6.0 */ final class AndCondition extends BooleanCondition { AndCondition(QueryFactory queryFactory, BaseCondition leftCondition, BaseCondition rightCondition) { super(queryFactory, leftCondition, rightCondition); } @Override public <ReturnType> ReturnType accept(Visitor<ReturnType> visitor) { return visitor.visit(this); } @Override public String toString() { return "(" + getFirstCondition() + ") AND (" + getSecondCondition() + ")"; } }
616
23.68
103
java
null
infinispan-main/query-dsl/src/main/java/org/infinispan/query/dsl/impl/BooleanCondition.java
package org.infinispan.query.dsl.impl; import org.infinispan.query.dsl.QueryBuilder; import org.infinispan.query.dsl.QueryFactory; import org.infinispan.query.dsl.impl.logging.Log; import org.jboss.logging.Logger; /** * Unary or binary boolean condition (NOT, AND, OR). * * @author anistor@redhat.com * @since 6.0 */ abstract class BooleanCondition extends BaseCondition { private static final Log log = Logger.getMessageLogger(Log.class, BooleanCondition.class.getName()); private BaseCondition leftCondition; private BaseCondition rightCondition; protected BooleanCondition(QueryFactory queryFactory, BaseCondition leftCondition, BaseCondition rightCondition) { super(queryFactory); if (leftCondition == rightCondition) { throw log.leftAndRightCannotBeTheSame(); } this.leftCondition = leftCondition; this.rightCondition = rightCondition; } public BaseCondition getFirstCondition() { return leftCondition; } public BaseCondition getSecondCondition() { return rightCondition; } public void replaceChildCondition(BaseCondition oldChild, BaseCondition newChild) { if (leftCondition == oldChild) { leftCondition = newChild; } else if (rightCondition == oldChild) { rightCondition = newChild; } else { throw log.conditionNotFoundInParent(); } newChild.setParent(this); } @Override void setQueryBuilder(QueryBuilder queryBuilder) { super.setQueryBuilder(queryBuilder); if (leftCondition != null) { leftCondition.setQueryBuilder(queryBuilder); } if (rightCondition != null) { rightCondition.setQueryBuilder(queryBuilder); } } }
1,736
27.47541
117
java
null
infinispan-main/query-dsl/src/main/java/org/infinispan/query/dsl/impl/QueryStringCreator.java
package org.infinispan.query.dsl.impl; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.time.Instant; import java.util.Arrays; import java.util.Collection; import java.util.Date; import java.util.HashMap; import java.util.Map; import java.util.TimeZone; import org.infinispan.query.dsl.Expression; import org.infinispan.query.dsl.impl.logging.Log; import org.jboss.logging.Logger; /** * Generates an Ickle query string to satisfy the condition created with the builder (by visiting it). * * @author anistor@redhat.com * @since 6.0 */ public class QueryStringCreator implements Visitor<String> { private static final Log log = Logger.getMessageLogger(Log.class, QueryStringCreator.class.getName()); public static final String DEFAULT_ALIAS = "_gen0"; private static final String DATE_FORMAT = "yyyyMMddHHmmssSSS"; private static final TimeZone GMT_TZ = TimeZone.getTimeZone("GMT"); protected Map<String, Object> namedParameters; private DateFormat dateFormat; public QueryStringCreator() { } public Map<String, Object> getNamedParameters() { return namedParameters; } @Override public String visit(BaseQueryBuilder baseQueryBuilder) { StringBuilder sb = new StringBuilder(); if (baseQueryBuilder.getProjection() != null && baseQueryBuilder.getProjection().length != 0) { sb.append("SELECT "); boolean isFirst = true; for (Expression projection : baseQueryBuilder.getProjection()) { if (isFirst) { isFirst = false; } else { sb.append(", "); } appendAttributePath(sb, projection); } sb.append(' '); } sb.append("FROM ").append(baseQueryBuilder.getRootTypeName()).append(' ').append(DEFAULT_ALIAS); if (baseQueryBuilder.getWhereFilterCondition() != null) { BaseCondition baseCondition = baseQueryBuilder.getWhereFilterCondition().getRoot(); String whereCondition = baseCondition.accept(this); if (!whereCondition.isEmpty()) { sb.append(" WHERE ").append(whereCondition); } } if (baseQueryBuilder.getGroupBy() != null && baseQueryBuilder.getGroupBy().length != 0) { sb.append(" GROUP BY "); boolean isFirst = true; for (String groupBy : baseQueryBuilder.getGroupBy()) { if (isFirst) { isFirst = false; } else { sb.append(", "); } sb.append(DEFAULT_ALIAS).append('.').append(groupBy); } sb.append(' '); } if (baseQueryBuilder.getHavingFilterCondition() != null) { BaseCondition baseCondition = baseQueryBuilder.getHavingFilterCondition().getRoot(); String havingCondition = baseCondition.accept(this); if (!havingCondition.isEmpty()) { sb.append(" HAVING ").append(havingCondition); } } if (baseQueryBuilder.getSortCriteria() != null && !baseQueryBuilder.getSortCriteria().isEmpty()) { sb.append(" ORDER BY "); boolean isFirst = true; for (SortCriteria sortCriteria : baseQueryBuilder.getSortCriteria()) { if (isFirst) { isFirst = false; } else { sb.append(", "); } appendAttributePath(sb, sortCriteria.getAttributePath()); sb.append(' ').append(sortCriteria.getSortOrder().name()); } } return sb.toString(); } protected <E extends Enum<E>> String renderEnum(E argument) { return '\'' + argument.name() + '\''; } @Override public String visit(AndCondition booleanCondition) { return generateBooleanCondition(booleanCondition, "AND"); } @Override public String visit(OrCondition booleanCondition) { return generateBooleanCondition(booleanCondition, "OR"); } private String generateBooleanCondition(BooleanCondition booleanCondition, String booleanOperator) { StringBuilder sb = new StringBuilder(); boolean wrap = parentIsNotOfClass(booleanCondition, booleanCondition.getClass()); if (wrap) { sb.append('('); } sb.append(booleanCondition.getFirstCondition().accept(this)); sb.append(' ').append(booleanOperator).append(' '); sb.append(booleanCondition.getSecondCondition().accept(this)); if (wrap) { sb.append(')'); } return sb.toString(); } @Override public String visit(NotCondition notCondition) { return "NOT " + notCondition.getFirstCondition().accept(this); } @Override public String visit(EqOperator operator) { return appendSingleCondition(new StringBuilder(), operator.getAttributeCondition(), operator.getArgument(), "=", "!=").toString(); } @Override public String visit(GtOperator operator) { return appendSingleCondition(new StringBuilder(), operator.getAttributeCondition(), operator.getArgument(), ">", "<=").toString(); } @Override public String visit(GteOperator operator) { return appendSingleCondition(new StringBuilder(), operator.getAttributeCondition(), operator.getArgument(), ">=", "<").toString(); } @Override public String visit(LtOperator operator) { return appendSingleCondition(new StringBuilder(), operator.getAttributeCondition(), operator.getArgument(), "<", ">=").toString(); } @Override public String visit(LteOperator operator) { return appendSingleCondition(new StringBuilder(), operator.getAttributeCondition(), operator.getArgument(), "<=", ">").toString(); } @Override public String visit(BetweenOperator operator) { StringBuilder sb = new StringBuilder(); ValueRange range = operator.getArgument(); if (!range.isIncludeLower() || !range.isIncludeUpper()) { // if any of the bounds are not included then we cannot use BETWEEN and need to resort to simple comparisons boolean wrap = parentIsNotOfClass(operator.getAttributeCondition(), operator.getAttributeCondition().isNegated() ? OrCondition.class : AndCondition.class); if (wrap) { sb.append('('); } appendAttributePath(sb, operator.getAttributeCondition()); sb.append(operator.getAttributeCondition().isNegated() ? (range.isIncludeLower() ? " < " : " <= ") : (range.isIncludeLower() ? " >= " : " > ")); appendArgument(sb, range.getFrom()); sb.append(operator.getAttributeCondition().isNegated() ? " OR " : " AND "); appendAttributePath(sb, operator.getAttributeCondition()); sb.append(operator.getAttributeCondition().isNegated() ? (range.isIncludeUpper() ? " > " : " >= ") : (range.isIncludeUpper() ? " <= " : " < ")); appendArgument(sb, range.getTo()); if (wrap) { sb.append(')'); } } else { // if the bounds are included then we can use BETWEEN if (operator.getAttributeCondition().isNegated()) { sb.append("NOT "); } appendAttributePath(sb, operator.getAttributeCondition()); sb.append(" BETWEEN "); appendArgument(sb, range.getFrom()); sb.append(" AND "); appendArgument(sb, range.getTo()); } return sb.toString(); } @Override public String visit(LikeOperator operator) { StringBuilder sb = new StringBuilder(); appendAttributePath(sb, operator.getAttributeCondition()); sb.append(' '); if (operator.getAttributeCondition().isNegated()) { sb.append("NOT "); } sb.append("LIKE "); appendArgument(sb, operator.getArgument()); return sb.toString(); } @Override public String visit(IsNullOperator operator) { StringBuilder sb = new StringBuilder(); appendAttributePath(sb, operator.getAttributeCondition()); sb.append(" IS "); if (operator.getAttributeCondition().isNegated()) { sb.append("NOT "); } sb.append("NULL"); return sb.toString(); } @Override public String visit(InOperator operator) { StringBuilder sb = new StringBuilder(); appendAttributePath(sb, operator.getAttributeCondition()); if (operator.getAttributeCondition().isNegated()) { sb.append(" NOT"); } sb.append(" IN "); appendArgument(sb, operator.getArgument()); return sb.toString(); } @Override public String visit(ContainsOperator operator) { return appendSingleCondition(new StringBuilder(), operator.getAttributeCondition(), operator.getArgument(), "=", "!=").toString(); } private StringBuilder appendSingleCondition(StringBuilder sb, AttributeCondition attributeCondition, Object argument, String op, String negativeOp) { appendAttributePath(sb, attributeCondition); sb.append(' '); sb.append(attributeCondition.isNegated() ? negativeOp : op); sb.append(' '); appendArgument(sb, argument); return sb; } /** * We check if the parent if of the expected class, hoping that if it is then we can avoid wrapping this condition in * parentheses and still maintain the same logic. * * @return {@code true} if wrapping is needed, {@code false} otherwise */ private boolean parentIsNotOfClass(BaseCondition condition, Class<? extends BooleanCondition> expectedParentClass) { BaseCondition parent = condition.getParent(); return parent != null && parent.getClass() != expectedParentClass; } @Override public String visit(ContainsAllOperator operator) { return generateMultipleBooleanCondition(operator, "AND", AndCondition.class); } @Override public String visit(ContainsAnyOperator operator) { return generateMultipleBooleanCondition(operator, "OR", OrCondition.class); } private String generateMultipleBooleanCondition(OperatorAndArgument operator, String booleanOperator, Class<? extends BooleanCondition> expectedParentClass) { Object argument = operator.getArgument(); Collection values; if (argument instanceof Collection) { values = (Collection) argument; } else if (argument instanceof Object[]) { values = Arrays.asList((Object[]) argument); } else { throw log.expectingCollectionOrArray(); } StringBuilder sb = new StringBuilder(); boolean wrap = parentIsNotOfClass(operator.getAttributeCondition(), expectedParentClass); if (wrap) { sb.append('('); } boolean isFirst = true; for (Object value : values) { if (isFirst) { isFirst = false; } else { sb.append(' ').append(booleanOperator).append(' '); } appendSingleCondition(sb, operator.getAttributeCondition(), value, "=", "!="); } if (wrap) { sb.append(')'); } return sb.toString(); } @Override public String visit(AttributeCondition attributeCondition) { if (attributeCondition.getExpression() == null || attributeCondition.getOperatorAndArgument() == null) { throw log.incompleteSentence(); } return attributeCondition.getOperatorAndArgument().accept(this); } private void appendAttributePath(StringBuilder sb, AttributeCondition attributeCondition) { appendAttributePath(sb, attributeCondition.getExpression()); } private void appendAttributePath(StringBuilder sb, Expression expression) { PathExpression pathExpression = (PathExpression) expression; if (pathExpression.getAggregationType() != null) { sb.append(pathExpression.getAggregationType().name()).append('('); } sb.append(DEFAULT_ALIAS).append('.').append(pathExpression.getPath()); if (pathExpression.getAggregationType() != null) { sb.append(')'); } } private void appendArgument(StringBuilder sb, Object argument) { if (argument instanceof String) { sb.append('\''); String stringLiteral = argument.toString(); for (int i = 0; i < stringLiteral.length(); i++) { char c = stringLiteral.charAt(i); if (c == '\'') { sb.append('\''); } sb.append(c); } sb.append('\''); return; } if (argument instanceof ParameterExpression) { ParameterExpression param = (ParameterExpression) argument; sb.append(':').append(param.getParamName()); if (namedParameters == null) { namedParameters = new HashMap<>(5); } namedParameters.put(param.getParamName(), null); return; } if (argument instanceof PathExpression) { appendAttributePath(sb, (PathExpression) argument); return; } if (argument instanceof Number) { sb.append(argument); return; } if (argument instanceof Enum) { sb.append(renderEnum((Enum) argument)); return; } if (argument instanceof Collection) { sb.append('('); boolean isFirstElement = true; for (Object o : (Collection) argument) { if (isFirstElement) { isFirstElement = false; } else { sb.append(", "); } appendArgument(sb, o); } sb.append(')'); return; } if (argument instanceof Object[]) { sb.append('('); boolean isFirstElement = true; for (Object o : (Object[]) argument) { if (isFirstElement) { isFirstElement = false; } else { sb.append(", "); } appendArgument(sb, o); } sb.append(')'); return; } if (argument instanceof Date) { sb.append('\'').append(renderDate((Date) argument)).append('\''); return; } if (argument instanceof Instant) { sb.append('\'').append(renderInstant((Instant) argument)).append('\''); return; } sb.append(argument); } protected String renderDate(Date argument) { return getDateFormatter().format(argument); } protected String renderInstant(Instant argument) { return argument.toString(); } private DateFormat getDateFormatter() { if (dateFormat == null) { dateFormat = new SimpleDateFormat(DATE_FORMAT); dateFormat.setTimeZone(GMT_TZ); } return dateFormat; } }
14,634
32.877315
164
java
null
infinispan-main/query-dsl/src/main/java/org/infinispan/query/dsl/impl/BaseCondition.java
package org.infinispan.query.dsl.impl; import org.infinispan.query.dsl.Expression; import org.infinispan.query.dsl.FilterConditionBeginContext; import org.infinispan.query.dsl.FilterConditionContext; import org.infinispan.query.dsl.FilterConditionContextQueryBuilder; import org.infinispan.query.dsl.FilterConditionEndContext; import org.infinispan.query.dsl.Query; import org.infinispan.query.dsl.QueryBuilder; import org.infinispan.query.dsl.QueryFactory; import org.infinispan.query.dsl.SortOrder; import org.infinispan.query.dsl.impl.logging.Log; import org.jboss.logging.Logger; /** * @author anistor@redhat.com * @since 6.0 */ abstract class BaseCondition implements FilterConditionContextQueryBuilder, Visitable { private static final Log log = Logger.getMessageLogger(Log.class, BaseCondition.class.getName()); protected BaseCondition parent = null; protected QueryBuilder queryBuilder; protected final QueryFactory queryFactory; protected BaseCondition(QueryFactory queryFactory) { this.queryFactory = queryFactory; } @SuppressWarnings("deprecation") @Override public QueryBuilder toBuilder() { return getQueryBuilder(); } QueryBuilder getQueryBuilder() { if (queryBuilder == null) { throw log.subQueryDoesNotBelongToAParentQueryBuilder(); } return queryBuilder; } void setQueryBuilder(QueryBuilder queryBuilder) { if (this.queryBuilder != null) { throw log.queryAlreadyBelongsToAnotherBuilder(); } this.queryBuilder = queryBuilder; } /** * Returns the topmost condition, never {@code null}. * * @return the topmost condition following up the parent chain or {@code this} if parent is {@code null}. */ public BaseCondition getRoot() { BaseCondition p = this; while (p.getParent() != null) { p = p.getParent(); } return p; } public BaseCondition getParent() { return parent; } public void setParent(BaseCondition parent) { this.parent = parent; } @Override public FilterConditionBeginContext and() { IncompleteCondition rightCondition = new IncompleteCondition(queryFactory); combine(true, rightCondition); return rightCondition; } @Override public FilterConditionContextQueryBuilder and(FilterConditionContext rightCondition) { combine(true, rightCondition); return this; } @Override public FilterConditionBeginContext or() { IncompleteCondition rightCondition = new IncompleteCondition(queryFactory); combine(false, rightCondition); return rightCondition; } @Override public BaseCondition or(FilterConditionContext rightCondition) { combine(false, rightCondition); return this; } private void combine(boolean isConjunction, FilterConditionContext fcc) { if (fcc == null) { throw log.argumentCannotBeNull(); } BaseCondition rightCondition = ((BaseCondition) fcc).getRoot(); if (rightCondition.queryFactory != queryFactory) { throw log.conditionWasCreatedByAnotherFactory(); } if (rightCondition.queryBuilder != null) { throw log.conditionIsAlreadyInUseByAnotherBuilder(); } if (isConjunction && parent instanceof OrCondition) { BooleanCondition p = new AndCondition(queryFactory, this, rightCondition); ((BooleanCondition) parent).replaceChildCondition(this, p); parent = p; rightCondition.setParent(p); } else { BaseCondition root = getRoot(); BooleanCondition p = isConjunction ? new AndCondition(queryFactory, root, rightCondition) : new OrCondition(queryFactory, root, rightCondition); root.setParent(p); rightCondition.setParent(p); } rightCondition.setQueryBuilder(queryBuilder); } //////////////////////////////// Delegate to parent QueryBuilder /////////////////////////// @Override public QueryBuilder startOffset(long startOffset) { return getQueryBuilder().startOffset(startOffset); } @Override public QueryBuilder maxResults(int maxResults) { return getQueryBuilder().maxResults(maxResults); } @Override public QueryBuilder select(Expression... projection) { return getQueryBuilder().select(projection); } @Override public QueryBuilder select(String... attributePath) { return getQueryBuilder().select(attributePath); } @Override public QueryBuilder groupBy(String... attributePath) { return getQueryBuilder().groupBy(attributePath); } @Override public QueryBuilder orderBy(Expression expression) { return getQueryBuilder().orderBy(expression); } @Override public QueryBuilder orderBy(Expression expression, SortOrder sortOrder) { return getQueryBuilder().orderBy(expression); } @Override public QueryBuilder orderBy(String attributePath) { return getQueryBuilder().orderBy(attributePath); } @Override public QueryBuilder orderBy(String attributePath, SortOrder sortOrder) { return getQueryBuilder().orderBy(attributePath, sortOrder); } @Override public FilterConditionEndContext having(String attributePath) { return getQueryBuilder().having(attributePath); } @Override public FilterConditionEndContext having(Expression expression) { return getQueryBuilder().having(expression); } @Override public FilterConditionContextQueryBuilder not() { return getQueryBuilder().not(); } @Override public FilterConditionContextQueryBuilder not(FilterConditionContext fcc) { return getQueryBuilder().not(fcc); } @Override public <T> Query<T> build() { return getQueryBuilder().build(); } }
5,809
27.905473
153
java
null
infinispan-main/query-dsl/src/main/java/org/infinispan/query/dsl/impl/ValueRange.java
package org.infinispan.query.dsl.impl; import org.infinispan.query.dsl.impl.logging.Log; import org.jboss.logging.Logger; /** * Represents a range of values starting from value {@code from} and ending at {@code to}, including or excluding * the interval ends as indicated by {@code includeLower} and {@code includeUpper} respectively. This is used to * represent an interval specified in the 'between' clause of the query DSL. * * @author anistor@redhat.com * @since 6.0 */ final class ValueRange { private static final Log log = Logger.getMessageLogger(Log.class, ValueRange.class.getName()); private final Object from; private final Object to; private boolean includeLower = true; private boolean includeUpper = true; public ValueRange(Object from, Object to) { if (!(from instanceof Comparable)) { throw log.argumentMustBeComparable("from"); } if (!(to instanceof Comparable)) { throw log.argumentMustBeComparable("to"); } this.from = from; this.to = to; } public Object getFrom() { return from; } public Object getTo() { return to; } public boolean isIncludeLower() { return includeLower; } public void setIncludeLower(boolean includeLower) { this.includeLower = includeLower; } public boolean isIncludeUpper() { return includeUpper; } public void setIncludeUpper(boolean includeUpper) { this.includeUpper = includeUpper; } @Override public String toString() { return (includeLower ? "[" : "(") + from + ", " + to + (includeUpper ? "]" : ")"); } }
1,636
23.80303
113
java
null
infinispan-main/query-dsl/src/main/java/org/infinispan/query/dsl/impl/BetweenOperator.java
package org.infinispan.query.dsl.impl; /** * @author anistor@redhat.com * @since 6.0 */ class BetweenOperator extends OperatorAndArgument<ValueRange> { protected BetweenOperator(AttributeCondition parentCondition, ValueRange argument) { super(parentCondition, argument); } @Override public <ReturnType> ReturnType accept(Visitor<ReturnType> visitor) { return visitor.visit(this); } }
417
22.222222
87
java
null
infinispan-main/query-dsl/src/main/java/org/infinispan/query/dsl/impl/LteOperator.java
package org.infinispan.query.dsl.impl; /** * @author anistor@redhat.com * @since 6.0 */ class LteOperator extends OperatorAndArgument<Object> { protected LteOperator(AttributeCondition parentCondition, Object argument) { super(parentCondition, argument); } @Override public <ReturnType> ReturnType accept(Visitor<ReturnType> visitor) { return visitor.visit(this); } }
401
21.333333
79
java
null
infinispan-main/query-dsl/src/main/java/org/infinispan/query/dsl/impl/ParameterExpression.java
package org.infinispan.query.dsl.impl; import org.infinispan.query.dsl.Expression; import org.infinispan.query.dsl.impl.logging.Log; import org.jboss.logging.Logger; /** * @author anistor@redhat.com * @since 8.0 */ public final class ParameterExpression implements Expression { private static final Log log = Logger.getMessageLogger(Log.class, ParameterExpression.class.getName()); private final String paramName; public ParameterExpression(String paramName) { if (paramName == null || paramName.isEmpty()) { throw log.parameterNameCannotBeNulOrEmpty(); } this.paramName = paramName; } public String getParamName() { return paramName; } }
699
24
106
java
null
infinispan-main/query-dsl/src/main/java/org/infinispan/query/dsl/impl/SortCriteria.java
package org.infinispan.query.dsl.impl; import org.infinispan.query.dsl.Expression; import org.infinispan.query.dsl.SortOrder; import org.infinispan.query.dsl.impl.logging.Log; import org.jboss.logging.Logger; /** * @author anistor@redhat.com * @since 6.0 */ final class SortCriteria { private static final Log log = Logger.getMessageLogger(Log.class, SortCriteria.class.getName()); private final Expression pathExpression; private final SortOrder sortOrder; SortCriteria(Expression pathExpression, SortOrder sortOrder) { if (pathExpression == null) { throw log.argumentCannotBeNull("pathExpression"); } if (sortOrder == null) { throw log.argumentCannotBeNull("sortOrder"); } this.pathExpression = pathExpression; this.sortOrder = sortOrder; } public Expression getAttributePath() { return pathExpression; } public SortOrder getSortOrder() { return sortOrder; } @Override public String toString() { return "SortCriteria{" + "pathExpression='" + pathExpression + '\'' + ", sortOrder=" + sortOrder + '}'; } }
1,162
23.744681
99
java
null
infinispan-main/query-dsl/src/main/java/org/infinispan/query/dsl/impl/InOperator.java
package org.infinispan.query.dsl.impl; /** * @author anistor@redhat.com * @since 6.0 */ class InOperator extends OperatorAndArgument<Object> { protected InOperator(AttributeCondition parentCondition, Object argument) { super(parentCondition, argument); } @Override public <ReturnType> ReturnType accept(Visitor<ReturnType> visitor) { return visitor.visit(this); } }
399
21.222222
78
java
null
infinispan-main/query-dsl/src/main/java/org/infinispan/query/dsl/impl/BaseQuery.java
package org.infinispan.query.dsl.impl; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; import org.infinispan.commons.util.CloseableIterator; import org.infinispan.query.dsl.Query; import org.infinispan.query.dsl.QueryFactory; import org.infinispan.query.dsl.impl.logging.Log; import org.jboss.logging.Logger; /** * @author anistor@redhat.com * @since 7.2 */ public abstract class BaseQuery<T> implements Query<T> { private static final Log log = Logger.getMessageLogger(Log.class, BaseQuery.class.getName()); protected final QueryFactory queryFactory; protected final String queryString; private final boolean paramsDefined; protected Map<String, Object> namedParameters; protected final String[] projection; protected int startOffset; protected int maxResults; protected Integer hitCountAccuracy; protected boolean local; /** * Optional timeout in nanoseconds. */ protected long timeout = -1; //todo [anistor] can startOffset really be a long or it really has to be int due to limitations in query module? protected BaseQuery(QueryFactory queryFactory, String queryString, Map<String, Object> namedParameters, String[] projection, long startOffset, int maxResults, boolean local) { this.paramsDefined = true; this.queryFactory = queryFactory; this.queryString = queryString; this.namedParameters = namedParameters; this.projection = projection != null && projection.length > 0 ? projection : null; this.startOffset = startOffset < 0 ? 0 : (int) startOffset; this.maxResults = maxResults; this.local = local; } protected BaseQuery(QueryFactory queryFactory, String queryString) { this.paramsDefined = false; this.queryFactory = queryFactory; this.queryString = queryString; this.projection = null; this.startOffset = 0; this.maxResults = -1; } /** * Returns the Ickle query string. * * @return the Ickle query string */ @Override public String getQueryString() { return queryString; } @Override public Map<String, Object> getParameters() { return namedParameters != null ? Collections.unmodifiableMap(namedParameters) : null; } @Override public Query<T> setParameter(String paramName, Object paramValue) { if (paramName == null || paramName.isEmpty()) { throw log.parameterNameCannotBeNulOrEmpty(); } if (paramsDefined) { if (namedParameters == null) { throw log.queryDoesNotHaveParameters(); } if (!namedParameters.containsKey(paramName)) { throw log.parameterNotFound(paramName); } } else if (namedParameters == null) { namedParameters = new HashMap<>(5); } namedParameters.put(paramName, paramValue); // reset the query to force a new execution resetQuery(); return this; } @Override public Query<T> setParameters(Map<String, Object> paramValues) { if (paramValues == null) { throw log.argumentCannotBeNull("paramValues"); } if (paramsDefined) { if (namedParameters == null) { throw log.queryDoesNotHaveParameters(); } List<String> unknownParams = null; for (String paramName : paramValues.keySet()) { if (paramName == null || paramName.isEmpty()) { throw log.parameterNameCannotBeNulOrEmpty(); } if (!namedParameters.containsKey(paramName)) { if (unknownParams == null) { unknownParams = new ArrayList<>(); } unknownParams.add(paramName); } } if (unknownParams != null) { throw log.parametersNotFound(unknownParams.toString()); } } else if (namedParameters == null) { namedParameters = new HashMap<>(5); } namedParameters.putAll(paramValues); // reset the query to force a new execution resetQuery(); return this; } /** * Reset internal state after pagination or query parameters are modified. This is needed to ensure the next * execution of the query uses the new values. */ public abstract void resetQuery(); /** * Ensure all named parameters have non-null values. */ public void validateNamedParameters() { if (namedParameters != null) { for (Map.Entry<String, Object> e : namedParameters.entrySet()) { if (e.getValue() == null) { throw log.queryParameterNotSet(e.getKey()); } } } } public String[] getProjection() { return projection; } @Override public boolean hasProjections() { return projection != null; } @Override public long getStartOffset() { return startOffset; } public int getMaxResults() { return maxResults; } @Override public Query<T> startOffset(long startOffset) { this.startOffset = (int) startOffset; //todo [anistor] why accept a long if cache size is int? resetQuery(); return this; } @Override public Query<T> maxResults(int maxResults) { this.maxResults = maxResults; resetQuery(); return this; } @Override public Integer hitCountAccuracy() { return hitCountAccuracy; } @Override public Query<T> hitCountAccuracy(int hitCountAccuracy) { this.hitCountAccuracy = hitCountAccuracy; return this; } @Override public Query<T> local(boolean local) { this.local = local; resetQuery(); return this; } public boolean isLocal() { return local; } @Override public Query<T> timeout(long timeout, TimeUnit timeUnit) { this.timeout = timeUnit.toNanos(timeout); return this; } @Override public <K> CloseableIterator<Map.Entry<K, T>> entryIterator() { throw new UnsupportedOperationException("Not implemented!"); } @Override public int executeStatement() { throw new UnsupportedOperationException("Not implemented!"); } }
6,313
25.982906
115
java
null
infinispan-main/query-dsl/src/main/java/org/infinispan/query/dsl/impl/logging/Log.java
package org.infinispan.query.dsl.impl.logging; import static org.jboss.logging.Logger.Level.WARN; import org.jboss.logging.BasicLogger; import org.jboss.logging.annotations.LogMessage; import org.jboss.logging.annotations.Message; import org.jboss.logging.annotations.MessageLogger; /** * Log abstraction for the query DSL. For this module, message ids ranging from 14801 to 15000 inclusively have been * reserved. * * @author anistor@redhat.com * @since 8.2 */ @MessageLogger(projectCode = "ISPN") public interface Log extends BasicLogger { @Message(value = "Argument cannot be null", id = 14801) IllegalArgumentException argumentCannotBeNull(); @Message(value = "'%s' must be an instance of java.lang.Comparable", id = 14802) IllegalArgumentException argumentMustBeComparable(String argName); @Message(value = "Parameter name cannot be null or empty", id = 14803) IllegalArgumentException parameterNameCannotBeNulOrEmpty(); @Message(value = "Query does not have parameters", id = 14804) IllegalStateException queryDoesNotHaveParameters(); @Message(value = "No parameter named '%s' was found", id = 14805) IllegalArgumentException parameterNotFound(String paramName); @Message(value = "No parameters named '%s' were found", id = 14806) IllegalArgumentException parametersNotFound(String unknownParams); @Message(value = "The list of values for 'in(..)' cannot be null or empty", id = 14807) IllegalArgumentException listOfValuesForInCannotBeNulOrEmpty(); @Message(value = "operator was already specified", id = 14808) IllegalStateException operatorWasAlreadySpecified(); @Message(value = "The given condition was created by another factory", id = 14809) IllegalArgumentException conditionWasCreatedByAnotherFactory(); @Message(value = "The given condition is already in use by another builder", id = 14810) IllegalArgumentException conditionIsAlreadyInUseByAnotherBuilder(); @Message(value = "Sentence already started. Cannot use '%s' again.", id = 14811) IllegalStateException cannotUseOperatorAgain(String operatorName); @Message(value = "%s cannot be null", id = 14812) IllegalArgumentException argumentCannotBeNull(String argName); @Message(value = "This query already belongs to another query builder", id = 14813) IllegalStateException queryAlreadyBelongsToAnotherBuilder(); @Message(value = "This sub-query does not belong to a parent query builder yet", id = 14814) IllegalStateException subQueryDoesNotBelongToAParentQueryBuilder(); @Message(value = "Grouping cannot be null or empty", id = 14815) IllegalArgumentException groupingCannotBeNullOrEmpty(); @Message(value = "Grouping can be specified only once", id = 14816) IllegalStateException groupingCanBeSpecifiedOnlyOnce(); @Message(value = "Expecting a java.lang.Collection or an array of java.lang.Object", id = 14817) IllegalArgumentException expectingCollectionOrArray(); @Message(value = "Incomplete sentence. Missing attribute path or operator.", id = 14818) IllegalStateException incompleteSentence(); @Message(value = "Cannot visit an incomplete condition.", id = 14819) IllegalStateException incompleteCondition(); @Message(value = "Old child condition not found in parent condition", id = 14820) IllegalStateException conditionNotFoundInParent(); @Message(value = "Projection cannot be null or empty", id = 14821) IllegalArgumentException projectionCannotBeNullOrEmpty(); @Message(value = "Projection can be specified only once", id = 14822) IllegalStateException projectionCanBeSpecifiedOnlyOnce(); @Message(value = "maxResults must be greater than 0", id = 14823) IllegalArgumentException maxResultMustBeGreaterThanZero(); @Message(value = "startOffset cannot be less than 0", id = 14824) IllegalArgumentException startOffsetCannotBeLessThanZero(); @Message(value = "Query parameter '%s' was not set", id = 14825) IllegalStateException queryParameterNotSet(String paramName); @Message(value = "Left and right condition cannot be the same", id = 14826) IllegalArgumentException leftAndRightCannotBeTheSame(); @LogMessage(level = WARN) @Message(value = "Distributed sort not supported for non-indexed query '%s'. Consider using an index for optimal performance.", id = 14827) void warnPerfSortedNonIndexed(String query); }
4,398
42.127451
142
java
null
infinispan-main/tasks/manager/src/test/java/org/infinispan/tasks/SecurityTaskManagerTest.java
package org.infinispan.tasks; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.fail; import java.util.Collection; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import javax.security.auth.Subject; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.global.GlobalConfigurationBuilder; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.security.AuthorizationPermission; import org.infinispan.security.Security; import org.infinispan.security.mappers.IdentityRoleMapper; import org.infinispan.tasks.impl.TaskManagerImpl; import org.infinispan.test.SingleCacheManagerTest; import org.infinispan.test.TestingUtil; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; /** * Tests verifying the tasks execution with cache security settings. * * @author amanukya */ @Test(groups = "functional", testName = "tasks.SecurityTaskManagerTest") public class SecurityTaskManagerTest extends SingleCacheManagerTest { static final Subject ADMIN = TestingUtil.makeSubject("admin", "admin"); static final Subject HACKER = TestingUtil.makeSubject("hacker", "hacker"); private TaskManagerImpl taskManager; private DummyTaskEngine taskEngine; @Override protected EmbeddedCacheManager createCacheManager() throws Exception { GlobalConfigurationBuilder global = new GlobalConfigurationBuilder(); global .security() .authorization().enable() .principalRoleMapper(new IdentityRoleMapper()) .role("admin").permission(AuthorizationPermission.ALL); ConfigurationBuilder config = new ConfigurationBuilder(); config.security().authorization().enable() .role("admin"); return TestCacheManagerFactory.createCacheManager(global, config); } @Override protected void setup() throws Exception { Security.doAs(ADMIN, () -> { try { SecurityTaskManagerTest.super.setup(); } catch (Exception e) { throw new RuntimeException(e); } taskManager = (TaskManagerImpl) cacheManager.getGlobalComponentRegistry().getComponent(TaskManager.class); taskEngine = new DummyTaskEngine(); taskManager.registerTaskEngine(taskEngine); }); } @Override protected void teardown() { Security.doAs(ADMIN, () -> SecurityTaskManagerTest.super.teardown()); } @Override protected void clearContent() { Security.doAs(ADMIN, () -> cacheManager.getCache().clear()); } @Test(dataProvider = "principalProvider") public void testTaskExecutionWithAuthorization(String principal, Subject subject) { Security.doAs(subject, () -> { CompletableFuture<Object> slowTask = taskManager.runTask(DummyTaskEngine.DummyTaskTypes.SLOW_TASK.name(), new TaskContext()) .toCompletableFuture(); Collection<TaskExecution> currentTasks = taskManager.getCurrentTasks(); assertEquals(1, currentTasks.size()); TaskExecution currentTask = currentTasks.iterator().next(); assertEquals(DummyTaskEngine.DummyTaskTypes.SLOW_TASK.name(), currentTask.getName()); assertEquals(principal, currentTask.getWho().get()); taskEngine.getSlowTask().complete("slow"); assertEquals(0, taskManager.getCurrentTasks().size()); try { assertEquals("slow", slowTask.get()); } catch (InterruptedException | ExecutionException e) { fail("Exception thrown while getting the slowTask. "); } taskEngine.setSlowTask(new CompletableFuture<>()); }); } @DataProvider(name = "principalProvider") private static Object[][] providePrincipals() { return new Object[][]{{"admin", ADMIN}, {"hacker", HACKER}}; } }
3,964
36.40566
133
java
null
infinispan-main/tasks/manager/src/test/java/org/infinispan/tasks/DummyTaskEngine.java
package org.infinispan.tasks; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.CompletableFuture; import org.infinispan.tasks.spi.TaskEngine; import org.infinispan.util.concurrent.BlockingManager; public class DummyTaskEngine implements TaskEngine { public enum DummyTaskTypes { SUCCESSFUL_TASK, PARAMETERIZED_TASK, FAILING_TASK, SLOW_TASK, CACHE_TASK } private final Set<String> tasks; private CompletableFuture<String> slow; public DummyTaskEngine() { tasks = new HashSet<>(); for (DummyTaskTypes type : DummyTaskTypes.values()) { tasks.add(type.toString()); } slow = new CompletableFuture<>(); } @Override public String getName() { return "Dummy"; } @Override public List<Task> getTasks() { List<Task> taskDetails = new ArrayList<>(); tasks.forEach(task -> { taskDetails.add(new DummyTask(task)); }); return taskDetails; } @Override public <T> CompletableFuture<T> runTask(String taskName, TaskContext context, BlockingManager blockingManager) { switch (DummyTaskTypes.valueOf(taskName)) { case SUCCESSFUL_TASK: return (CompletableFuture<T>) CompletableFuture.completedFuture("result"); case PARAMETERIZED_TASK: Map<String, ?> params = context.getParameters().get(); return (CompletableFuture<T>) CompletableFuture.completedFuture(params.get("parameter")); case FAILING_TASK: CompletableFuture<T> f = new CompletableFuture<>(); f.completeExceptionally(new Exception("exception")); return f; case SLOW_TASK: return (CompletableFuture<T>) slow; case CACHE_TASK: return (CompletableFuture<T>) CompletableFuture.completedFuture(context.getCache().get().getName()); } throw new IllegalArgumentException(); } public void setSlowTask(CompletableFuture<String> slow) { this.slow = slow; } public CompletableFuture<String> getSlowTask() { return slow; } @Override public boolean handles(String taskName) { return tasks.contains(taskName); } }
2,232
27.628205
115
java
null
infinispan-main/tasks/manager/src/test/java/org/infinispan/tasks/MemoryEventLogger.java
package org.infinispan.tasks; import java.time.Instant; import java.util.Collections; import java.util.List; import java.util.Optional; import java.util.Set; import java.util.concurrent.CompletionStage; import org.infinispan.commons.util.concurrent.CompletableFutures; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.commons.time.TimeService; import org.infinispan.util.logging.events.EventLog; import org.infinispan.util.logging.events.EventLogCategory; import org.infinispan.util.logging.events.EventLogLevel; import org.infinispan.util.logging.events.EventLogger; /** * @author Tristan Tarrant * @since 8.2 */ public class MemoryEventLogger implements EventLogger { EventLogCategory category; String context; String detail; EventLogLevel level; String message; String scope; String who; public MemoryEventLogger(EmbeddedCacheManager cacheManager, TimeService timeService) { reset(); } @Override public void log(EventLogLevel level, EventLogCategory category, String message) { this.level = level; this.category = category; this.message = message; } @Override public List<EventLog> getEvents(Instant start, int count, Optional<EventLogCategory> category, Optional<EventLogLevel> level) { return Collections.emptyList(); } @Override public EventLogger scope(String scope) { this.scope = scope; return this; } @Override public EventLogger context(String context) { this.context = context; return this; } @Override public EventLogger detail(String detail) { this.detail = detail; return this; } @Override public EventLogger who(String who) { this.who = who; return this; } void reset() { category = null; context = null; detail = null; level = null; message = null; scope = null; who = null; } public EventLogCategory getCategory() { return category; } public String getContext() { return context; } public String getDetail() { return detail; } public EventLogLevel getLevel() { return level; } public String getMessage() { return message; } public String getScope() { return scope; } public String getWho() { return who; } @Override public CompletionStage<Void> addListenerAsync(Object listener) { return CompletableFutures.completedNull(); } @Override public CompletionStage<Void> removeListenerAsync(Object listener) { return CompletableFutures.completedNull(); } @Override public Set<Object> getListeners() { return Collections.emptySet(); } }
2,845
21.951613
131
java
null
infinispan-main/tasks/manager/src/test/java/org/infinispan/tasks/TaskManagerTest.java
package org.infinispan.tasks; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertTrue; import java.util.Collection; import java.util.List; import java.util.concurrent.CompletionException; import java.util.concurrent.CompletionStage; import org.infinispan.commons.util.concurrent.CompletableFutures; import org.infinispan.factories.GlobalComponentRegistry; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.tasks.DummyTaskEngine.DummyTaskTypes; import org.infinispan.tasks.impl.TaskManagerImpl; import org.infinispan.tasks.logging.Messages; import org.infinispan.tasks.spi.TaskEngine; import org.infinispan.test.SingleCacheManagerTest; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.infinispan.util.concurrent.CompletionStages; import org.infinispan.util.logging.events.EventLogCategory; import org.infinispan.util.logging.events.EventLogLevel; import org.infinispan.util.logging.events.EventLogManager; import org.testng.annotations.Test; @Test(testName = "tasks.TaskManagerTest", groups = "functional") public class TaskManagerTest extends SingleCacheManagerTest { protected TaskManagerImpl taskManager; private DummyTaskEngine taskEngine; private MemoryEventLogger memoryLogger; @Override protected EmbeddedCacheManager createCacheManager() throws Exception { return TestCacheManagerFactory.createCacheManager(); } @Override protected void setup() throws Exception { super.setup(); GlobalComponentRegistry gcr = cacheManager.getGlobalComponentRegistry(); taskManager = (TaskManagerImpl) gcr.getComponent(TaskManager.class); taskEngine = new DummyTaskEngine(); taskManager.registerTaskEngine(taskEngine); memoryLogger = new MemoryEventLogger(cacheManager, gcr.getTimeService()); gcr.getComponent(EventLogManager.class).replaceEventLogger(memoryLogger); } @Test(expectedExceptions = IllegalArgumentException.class) public void testUnhandledTask() throws Throwable { try { CompletionStages.join(taskManager.runTask("UnhandledTask", new TaskContext())); } catch (CompletionException e) { throw CompletableFutures.extractException(e); } } public void testStoredEngines() { Collection<TaskEngine> engines = taskManager.getEngines(); assertEquals(1, engines.size()); assertEquals(taskEngine.getName(), engines.iterator().next().getName()); } public void testRunTask() { memoryLogger.reset(); CompletionStage<String> okTask = taskManager.<String>runTask(DummyTaskTypes.SUCCESSFUL_TASK.name(), new TaskContext().logEvent(true)); assertEquals("result", CompletionStages.join(okTask)); assertEquals(0, taskManager.getCurrentTasks().size()); assertEquals(Messages.MESSAGES.taskSuccess(DummyTaskTypes.SUCCESSFUL_TASK.name()), memoryLogger.getMessage()); assertEquals("result", memoryLogger.getDetail()); assertEquals(EventLogCategory.TASKS, memoryLogger.getCategory()); assertEquals(EventLogLevel.INFO, memoryLogger.getLevel()); memoryLogger.reset(); CompletionStage<String> paramTask = taskManager.<String>runTask(DummyTaskTypes.PARAMETERIZED_TASK.name(), new TaskContext().logEvent(true).addParameter("parameter", "Hello")); assertEquals("Hello", CompletionStages.join(paramTask)); assertEquals(0, taskManager.getCurrentTasks().size()); assertEquals(Messages.MESSAGES.taskSuccess(DummyTaskTypes.PARAMETERIZED_TASK.name()), memoryLogger.getMessage()); assertEquals("Hello", memoryLogger.getDetail()); assertEquals(EventLogCategory.TASKS, memoryLogger.getCategory()); assertEquals(EventLogLevel.INFO, memoryLogger.getLevel()); memoryLogger.reset(); CompletionStage<Object> koTask = taskManager.runTask(DummyTaskTypes.FAILING_TASK.name(), new TaskContext().logEvent(true)); String message = CompletionStages.join(koTask.handle((r, e) -> e.getCause().getMessage())); assertEquals(0, taskManager.getCurrentTasks().size()); assertEquals("exception", message); assertEquals(Messages.MESSAGES.taskFailure(DummyTaskTypes.FAILING_TASK.name()), memoryLogger.getMessage()); assertTrue(memoryLogger.getDetail().contains("java.lang.Exception: exception")); assertEquals(EventLogCategory.TASKS, memoryLogger.getCategory()); assertEquals(EventLogLevel.ERROR, memoryLogger.getLevel()); memoryLogger.reset(); CompletionStage<Object> slowTask = taskManager.runTask(DummyTaskTypes.SLOW_TASK.name(), new TaskContext().logEvent(true)); Collection<TaskExecution> currentTasks = taskManager.getCurrentTasks(); assertEquals(1, currentTasks.size()); TaskExecution execution = currentTasks.iterator().next(); assertEquals(DummyTaskTypes.SLOW_TASK.name(), execution.getName()); List<Task> tasks = taskManager.getTasks(); assertEquals(DummyTaskTypes.values().length, tasks.size()); Task task = tasks.get(4); assertEquals(DummyTaskTypes.SLOW_TASK.name(), task.getName()); assertEquals("Dummy", task.getType()); assertEquals(TaskExecutionMode.ONE_NODE, task.getExecutionMode()); taskEngine.getSlowTask().complete("slow"); assertEquals(0, taskManager.getCurrentTasks().size()); assertEquals("slow", CompletionStages.join(slowTask)); } }
5,390
46.289474
181
java
null
infinispan-main/tasks/manager/src/test/java/org/infinispan/tasks/DummyTask.java
package org.infinispan.tasks; import java.util.Collections; import java.util.Optional; import java.util.Set; public class DummyTask implements Task { private final String name; public DummyTask(String name) { this.name = name; } @Override public String getName() { return name; } @Override public String getType() { return "Dummy"; } @Override public TaskExecutionMode getExecutionMode() { return TaskExecutionMode.ONE_NODE; } @Override public Set<String> getParameters() { if (DummyTaskEngine.DummyTaskTypes.PARAMETERIZED_TASK.name().equals(name)) { return Collections.singleton("parameter"); } else { return Collections.emptySet(); } } @Override public Optional<String> getAllowedRole() { return Optional.of("DummyRole"); } }
857
18.5
82
java
null
infinispan-main/tasks/manager/src/main/java/org/infinispan/tasks/package-info.java
/** * Classes and interfaces related to task execution * * @api.public */ package org.infinispan.tasks;
108
14.571429
51
java
null
infinispan-main/tasks/manager/src/main/java/org/infinispan/tasks/TaskManager.java
package org.infinispan.tasks; import java.util.List; import java.util.concurrent.CompletionStage; import org.infinispan.tasks.spi.TaskEngine; /** * TaskManager. Allows executing tasks and retrieving the list of currently running tasks * * @author Tristan Tarrant * @since 8.1 */ public interface TaskManager { /** * Executes the named task, passing an optional cache and a map of named parameters. * * @param taskName * @param context * @return */ <T> CompletionStage<T> runTask(String taskName, TaskContext context); /** * Retrieves the currently executing tasks. If running in a cluster this operation * will return all of the tasks running on all nodes * * @return a list of {@link TaskExecution} elements */ List<TaskExecution> getCurrentTasks(); /** * Retrieves the installed task engines */ List<TaskEngine> getEngines(); /** * Retrieves the list of all available tasks * * @return a list of {@link Task} elements */ List<Task> getTasks(); /** * Same as {@link #getTasks()} except that the tasks are returned in a non * blocking fashion. * @return a stage that when complete contains all the tasks available */ CompletionStage<List<Task>> getTasksAsync(); /** * * @return Retrieves the list of all available tasks, excluding administrative tasks with names starting with '@@' */ List<Task> getUserTasks(); /** * Same as {@link #getTasks()} except that the user tasks are returned in a non * @return a stage that when complete contains all the user tasks available */ CompletionStage<List<Task>> getUserTasksAsync(); /** * Registers a new {@link TaskEngine} * * @param taskEngine an instance of the task engine that has to be registered with the task manager */ void registerTaskEngine(TaskEngine taskEngine); }
1,910
25.915493
117
java
null
infinispan-main/tasks/manager/src/main/java/org/infinispan/tasks/TaskExecution.java
package org.infinispan.tasks; import java.time.Instant; import java.util.Optional; /** * TaskExecution. Contains information about a running task * * @author Tristan Tarrant * @since 8.1 */ public interface TaskExecution { /** * Returns the name of the task */ String getName(); /** * Returns the time when the task was started */ Instant getStart(); /** * An optional name of the principal who has executed this task. If the task was triggered * internally, this method will return an empty {@link Optional} */ Optional<String> getWho(); /** * An optional context to which the task was applied. Usually the name of a cache */ Optional<String> getWhat(); /** * The node/address where the task was initiated */ String getWhere(); }
816
19.948718
93
java
null
infinispan-main/tasks/manager/src/main/java/org/infinispan/tasks/spi/TaskEngine.java
package org.infinispan.tasks.spi; import java.util.List; import java.util.concurrent.CompletionStage; import org.infinispan.tasks.Task; import org.infinispan.tasks.TaskContext; import org.infinispan.util.concurrent.BlockingManager; /** * TaskEngine. An implementation of an engine for executing tasks. How the tasks are implemented is * dependent on the engine itself. * * @author Tristan Tarrant * @since 8.1 */ public interface TaskEngine { /** * Returns the name of the engine */ String getName(); /** * Returns the list of tasks managed by this engine * * @return */ List<Task> getTasks(); /** * Executes the named task on the specified cache, passing a map of named parameters. * * @param taskName the name of the task * @param context a task context * @param blockingManager the handler for when a task is to be invoked that could block * @return */ <T> CompletionStage<T> runTask(String taskName, TaskContext context, BlockingManager blockingManager); /** * Returns whether this task engine knows about a specified named task * * @param taskName * @return */ boolean handles(String taskName); }
1,211
23.734694
105
java
null
infinispan-main/tasks/manager/src/main/java/org/infinispan/tasks/spi/NonBlockingTaskEngine.java
package org.infinispan.tasks.spi; import java.util.List; import java.util.concurrent.CompletionStage; import org.infinispan.tasks.Task; /** * Extends the {@link TaskEngine} interface to include additional methods allowing a task * engine to have non blocking methods where as the mirrored methods on {@link TaskEngine} * would block the invoking thread. */ public interface NonBlockingTaskEngine extends TaskEngine { /** * Returns the list of tasks managed by this engine. This method will return immediately and the returned stage * will now or some point in the future be completed with the list of tasks or an exception if something went wrong. * * @return stage containing the list of tasks when it is retrieved or an error */ CompletionStage<List<Task>> getTasksAsync(); /** * Returns whether this task engine knows about a specified named task. This method will return immediately and * the returned stage will now or some point in the future be completed with a Boolean whether this engine can * perform this task or an exception if something went wrong * * @param taskName the task to check * @return stage containing if the task can be handled or an error */ CompletionStage<Boolean> handlesAsync(String taskName); }
1,294
39.46875
119
java
null
infinispan-main/tasks/manager/src/main/java/org/infinispan/tasks/logging/Messages.java
package org.infinispan.tasks.logging; import static org.jboss.logging.Messages.getBundle; import org.jboss.logging.annotations.Message; import org.jboss.logging.annotations.MessageBundle; /** * Messages for the tasks module * * @author Tristan Tarrant * @since 8.2 */ @MessageBundle(projectCode = "ISPN") public interface Messages { Messages MESSAGES = getBundle(Messages.class); @Message(value = "Task %s completed successfully", id = 101000) String taskSuccess(String name); @Message(value = "Task %s completed with errors", id = 101001) String taskFailure(String name); }
605
24.25
67
java
null
infinispan-main/tasks/manager/src/main/java/org/infinispan/tasks/logging/Log.java
package org.infinispan.tasks.logging; import org.jboss.logging.BasicLogger; import org.jboss.logging.annotations.Message; import org.jboss.logging.annotations.MessageLogger; /** * Log abstraction for the Tasks module. For this module, message ids ranging from 27001 to * 27500 inclusively have been reserved. * * @author Tristan Tarrant * @since 8.1 */ @MessageLogger(projectCode = "ISPN") public interface Log extends BasicLogger { /*@Message(value = "Task Engine '%s' has already been registered", id = 27001) IllegalStateException duplicateTaskEngineRegistration(String taskEngineName);*/ @Message(value = "Unknown task '%s'", id = 27002) IllegalArgumentException unknownTask(String taskName); }
722
29.125
91
java
null
infinispan-main/tasks/manager/src/main/java/org/infinispan/tasks/impl/package-info.java
/** * Implementation of tasks management and execution * * @api.private */ package org.infinispan.tasks.impl;
114
15.428571
51
java
null
infinispan-main/tasks/manager/src/main/java/org/infinispan/tasks/impl/TaskManagerFactory.java
package org.infinispan.tasks.impl; import org.infinispan.factories.AbstractComponentFactory; import org.infinispan.factories.AutoInstantiableFactory; import org.infinispan.factories.annotations.DefaultFactoryFor; import org.infinispan.tasks.TaskManager; @DefaultFactoryFor(classes = TaskManager.class) public class TaskManagerFactory extends AbstractComponentFactory implements AutoInstantiableFactory { @Override public Object construct(String componentName) { return new TaskManagerImpl(); } }
514
31.1875
101
java
null
infinispan-main/tasks/manager/src/main/java/org/infinispan/tasks/impl/LifecycleCallbacks.java
package org.infinispan.tasks.impl; import org.infinispan.configuration.global.GlobalConfiguration; import org.infinispan.factories.GlobalComponentRegistry; import org.infinispan.factories.annotations.InfinispanModule; import org.infinispan.lifecycle.ModuleLifecycle; import org.infinispan.tasks.TaskManager; /** * LifecycleCallbacks. * * @author Tristan Tarrant * @since 8.1 */ @InfinispanModule(name = "tasks", requiredModules = "core") public class LifecycleCallbacks implements ModuleLifecycle { @Override public void cacheManagerStarting(GlobalComponentRegistry gcr, GlobalConfiguration gc) { if (gcr.getComponent(TaskManager.class) == null) gcr.registerComponent(new TaskManagerImpl(), TaskManager.class); } }
747
30.166667
90
java
null
infinispan-main/tasks/manager/src/main/java/org/infinispan/tasks/impl/TaskExecutionImpl.java
package org.infinispan.tasks.impl; import java.time.Instant; import java.util.Optional; import java.util.UUID; import org.infinispan.commons.marshall.SerializeWith; import org.infinispan.commons.util.Util; import org.infinispan.tasks.TaskContext; import org.infinispan.tasks.TaskExecution; /** * TaskExecutionImpl. A concrete representation of a {@link TaskExecution} * * @author Tristan Tarrant * @since 8.1 */ @SerializeWith(TaskExecutionImplExternalizer.class) public class TaskExecutionImpl implements TaskExecution { final UUID uuid; final String name; final Optional<String> what; final String where; final Optional<String> who; Instant start; TaskExecutionImpl(UUID uuid, String name, Optional<String> what, String where, Optional<String> who) { this.uuid = uuid; this.name = name; this.what = what; this.where = where; this.who = who; } TaskExecutionImpl(String name, Optional<String> what, String where, Optional<String> who) { this(Util.threadLocalRandomUUID(), name, what, where, who); } public TaskExecutionImpl(String name, String where, Optional<String> who, TaskContext context) { this.uuid = Util.threadLocalRandomUUID(); this.name = name; this.what = context.getCache().map(cache -> cache.getName()); this.where = where; this.who = who; } public UUID getUUID() { return uuid; } @Override public String getName() { return name; } @Override public Instant getStart() { return start; } @Override public Optional<String> getWhat() { return what; } @Override public String getWhere() { return where; } @Override public Optional<String> getWho() { return who; } public void setStart(Instant start) { this.start = start; } }
1,854
22.1875
105
java
null
infinispan-main/tasks/manager/src/main/java/org/infinispan/tasks/impl/TaskManagerImpl.java
package org.infinispan.tasks.impl; import static org.infinispan.tasks.logging.Messages.MESSAGES; import java.lang.invoke.MethodHandles; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Optional; import java.util.UUID; import java.util.concurrent.CompletionStage; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.stream.Collectors; import javax.security.auth.Subject; import org.infinispan.commons.time.TimeService; 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.manager.EmbeddedCacheManager; import org.infinispan.remoting.transport.Address; import org.infinispan.security.Security; import org.infinispan.security.actions.SecurityActions; import org.infinispan.tasks.Task; import org.infinispan.tasks.TaskContext; import org.infinispan.tasks.TaskExecution; import org.infinispan.tasks.TaskManager; import org.infinispan.tasks.logging.Log; import org.infinispan.tasks.spi.NonBlockingTaskEngine; import org.infinispan.tasks.spi.TaskEngine; import org.infinispan.util.concurrent.BlockingManager; import org.infinispan.util.logging.LogFactory; import org.infinispan.util.logging.events.EventLogCategory; import org.infinispan.util.logging.events.EventLogManager; import org.infinispan.util.logging.events.EventLogger; import io.reactivex.rxjava3.core.Flowable; import io.reactivex.rxjava3.core.Maybe; /** * TaskManagerImpl. * * @author Tristan Tarrant * @since 8.1 */ @Scope(Scopes.GLOBAL) public class TaskManagerImpl implements TaskManager { private static final Log log = LogFactory.getLog(MethodHandles.lookup().lookupClass(), Log.class); @Inject EmbeddedCacheManager cacheManager; @Inject TimeService timeService; @Inject BlockingManager blockingManager; @Inject EventLogManager eventLogManager; private List<TaskEngine> engines; private ConcurrentMap<UUID, TaskExecution> runningTasks; private boolean useSecurity; public TaskManagerImpl() { engines = new ArrayList<>(); runningTasks = new ConcurrentHashMap<>(); } @Start public void start() { this.useSecurity = SecurityActions.getCacheManagerConfiguration(cacheManager).security().authorization().enabled(); } @Override public synchronized void registerTaskEngine(TaskEngine engine) { if (!engines.contains(engine)) { engines.add(engine); } } @Override public <T> CompletionStage<T> runTask(String name, TaskContext context) { // This finds an engine that can accept the task CompletionStage<TaskEngine> engineStage = Flowable.fromIterable(engines) .concatMapMaybe(engine -> { if (engine instanceof NonBlockingTaskEngine) { return Maybe.fromCompletionStage(((NonBlockingTaskEngine) engine).handlesAsync(name)) .concatMap(canHandle -> canHandle ? Maybe.just(engine) : Maybe.empty()); } return engine.handles(name) ? Maybe.just(engine) : Maybe.empty(); }) .firstElement() .toCompletionStage(null); // Performs the actual task if an engine was found return engineStage.thenCompose(engine -> { if (engine == null) { throw log.unknownTask(name); } context.cacheManager(cacheManager); Address address = cacheManager.getAddress(); Subject subject = context.getSubject().orElseGet(() -> { if(useSecurity) { return Security.getSubject(); } else { return null; } }); Optional<String> who = Optional.ofNullable(subject == null ? null : Security.getSubjectUserPrincipal(subject).getName()); TaskExecutionImpl exec = new TaskExecutionImpl(name, address == null ? "local" : address.toString(), who, context); exec.setStart(timeService.instant()); runningTasks.put(exec.getUUID(), exec); CompletionStage<T> task = engine.runTask(name, context, blockingManager); return task.whenComplete((r, e) -> { if (context.isLogEvent()) { EventLogger eventLog = eventLogManager.getEventLogger().scope(cacheManager.getAddress()); who.ifPresent(eventLog::who); context.getCache().ifPresent(eventLog::context); if (e != null) { eventLog.detail(e) .error(EventLogCategory.TASKS, MESSAGES.taskFailure(name)); } else { eventLog.detail(String.valueOf(r)) .info(EventLogCategory.TASKS, MESSAGES.taskSuccess(name)); } } runningTasks.remove(exec.getUUID()); }); }); } @Override public List<TaskExecution> getCurrentTasks() { return new ArrayList<>(runningTasks.values()); } @Override public List<TaskEngine> getEngines() { return Collections.unmodifiableList(engines); } @Override public List<Task> getTasks() { List<Task> tasks = new ArrayList<>(); engines.forEach(engine -> tasks.addAll(engine.getTasks())); return tasks; } @Override public CompletionStage<List<Task>> getTasksAsync() { return taskFlowable() .collect(Collectors.toList()) .toCompletionStage(); } private Flowable<Task> taskFlowable() { return Flowable.fromIterable(engines) .flatMap(engine -> { if (engine instanceof NonBlockingTaskEngine) { return Flowable.fromCompletionStage(((NonBlockingTaskEngine) engine).getTasksAsync()) .flatMap(Flowable::fromIterable); } return Flowable.fromIterable(engine.getTasks()); }); } @Override public List<Task> getUserTasks() { return engines.stream().flatMap(engine -> engine.getTasks().stream()) .filter(t -> !t.getName().startsWith("@@")) .collect(Collectors.toList()); } @Override public CompletionStage<List<Task>> getUserTasksAsync() { return taskFlowable() .filter(t -> !t.getName().startsWith("@@")) .collect(Collectors.toList()) .toCompletionStage(); } }
6,467
34.734807
130
java
null
infinispan-main/tasks/manager/src/main/java/org/infinispan/tasks/impl/TaskExecutionImplExternalizer.java
package org.infinispan.tasks.impl; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.util.Optional; import java.util.UUID; import org.infinispan.commons.marshall.Externalizer; /** * TaskEventImplExternalizer. * * @author Tristan Tarrant * @since 8.1 */ public class TaskExecutionImplExternalizer implements Externalizer<TaskExecutionImpl> { @Override public void writeObject(ObjectOutput output, TaskExecutionImpl object) throws IOException { output.writeLong(object.uuid.getMostSignificantBits()); output.writeLong(object.uuid.getLeastSignificantBits()); output.writeUTF(object.name); output.writeObject(object.what); output.writeUTF(object.where); output.writeObject(object.who); } @Override public TaskExecutionImpl readObject(ObjectInput input) throws IOException, ClassNotFoundException { long uuidMSB = input.readLong(); long uuidLSB = input.readLong(); String name = input.readUTF(); Optional<String> what = (Optional<String>) input.readObject(); String where = input.readUTF(); Optional<String> who = (Optional<String>) input.readObject(); TaskExecutionImpl event = new TaskExecutionImpl(new UUID(uuidMSB, uuidLSB), name, what, where, who); return event; } }
1,329
29.227273
106
java
null
infinispan-main/tasks/api/src/main/java/org/infinispan/tasks/ServerTask.java
package org.infinispan.tasks; import java.util.concurrent.Callable; /** * An interface representing a deployed server task. * * The task will be accessible by the name returned by {@link #getName()} * Before the execution, {@link TaskContext} is injected into the task to provide * {@link org.infinispan.manager.EmbeddedCacheManager}, {@link org.infinispan.Cache}, * {@link org.infinispan.commons.marshall.Marshaller} and parameters. * * @author Michal Szynkiewicz &lt;michal.l.szynkiewicz@gmail.com&gt; */ public interface ServerTask<V> extends Callable<V>, Task { /** * Sets the task context * Store the value in your task implementation to be able to access caches and other resources in the task * Note that, if {@link Task#getInstantiationMode()} is {@link TaskInstantiationMode#SHARED} there will be single * instance of each ServerTask on each server so, if you expect concurrent invocations of a task, the * {@link TaskContext} should be stored in a {@link ThreadLocal} static field in your task. The TaskContext should * then be obtained during the task's {@link #call()} method and removed from the ThreadLocal. Alternatively use * {@link TaskInstantiationMode#ISOLATED}. * * @param taskContext task execution context */ void setTaskContext(TaskContext taskContext); default String getType() { return ServerTask.class.getSimpleName(); } }
1,420
40.794118
117
java
null
infinispan-main/tasks/api/src/main/java/org/infinispan/tasks/package-info.java
/** * Server tasks API. * * @api.public */ package org.infinispan.tasks;
77
10.142857
29
java
null
infinispan-main/tasks/api/src/main/java/org/infinispan/tasks/TaskInstantiationMode.java
package org.infinispan.tasks; public enum TaskInstantiationMode { /** * Creates a single instance that is reused for every task execution */ SHARED, /** * Creates a new instance for every invocation */ ISOLATED }
242
17.692308
71
java
null
infinispan-main/tasks/api/src/main/java/org/infinispan/tasks/TaskExecutionMode.java
package org.infinispan.tasks; public enum TaskExecutionMode { ONE_NODE, ALL_NODES }
91
12.142857
31
java
null
infinispan-main/tasks/api/src/main/java/org/infinispan/tasks/Task.java
package org.infinispan.tasks; import java.util.Collections; import java.util.Optional; import java.util.Set; import org.infinispan.commons.dataconversion.internal.Json; import org.infinispan.commons.dataconversion.internal.JsonSerialization; public interface Task extends JsonSerialization { /** * Provides a name for the task. This is the name by which the task will be executed. * Make sure the name is unique for each task. * * @return name of the task */ String getName(); /** * Returns the type of task. This is dependent on the specific implementation. */ String getType(); /** * Whether the task execution should be local - on one node or distributed - on all nodes. * * ONE_NODE execution is the default. * * @return {@link TaskExecutionMode#ONE_NODE} for single node execution, {@link TaskExecutionMode#ALL_NODES} for distributed execution, */ default TaskExecutionMode getExecutionMode() { return TaskExecutionMode.ONE_NODE; } /** * Whether tasks should reuse a single instance or create a new instance per execution. {@link TaskInstantiationMode#SHARED} is the default * * @return TaskInstantiationMode */ default TaskInstantiationMode getInstantiationMode() { return TaskInstantiationMode.SHARED; } /** * The named parameters accepted by this task * * @return a java.util.Set of parameter names */ default Set<String> getParameters() { return Collections.emptySet(); } /** * An optional role, for which the task is accessible. * If the task executor has the role in the set, the task will be executed. * * If the role is not provided - all users can invoke the task * * @return a user role, for which the task can be executed */ default Optional<String> getAllowedRole() { return Optional.empty(); } @Override default Json toJson() { return Json.object() .set("name", getName()) .set("type", getType()) .set("parameters", Json.make(getParameters())) .set("execution_mode", getExecutionMode().toString()) .set("instantiation_mode", getInstantiationMode().toString()) .set("allowed_role", getAllowedRole().orElse(null)); } }
2,315
29.473684
142
java
null
infinispan-main/tasks/api/src/main/java/org/infinispan/tasks/TaskContext.java
package org.infinispan.tasks; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Optional; import java.util.stream.Collectors; import javax.security.auth.Subject; import org.infinispan.Cache; import org.infinispan.commons.marshall.Marshaller; import org.infinispan.commons.marshall.ProtoStreamTypeIds; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.protostream.annotations.ProtoFactory; import org.infinispan.protostream.annotations.ProtoField; import org.infinispan.protostream.annotations.ProtoTypeId; import org.infinispan.security.Security; /** * TaskContext. Defines the execution context of a task by specifying parameters, cache and marshaller * * @author Tristan Tarrant * @since 8.1 */ @ProtoTypeId(ProtoStreamTypeIds.DISTRIBUTED_SERVER_TASK_CONTEXT) public class TaskContext { private transient EmbeddedCacheManager cacheManager; private transient Marshaller marshaller; private transient Cache<?, ?> cache; private Map<String, Object> parameters = Collections.emptyMap(); private Subject subject; private transient boolean logEvent; public TaskContext() { } public TaskContext(TaskContext other) { this.parameters = other.parameters; this.subject = other.subject; } @ProtoFactory TaskContext(Collection<TaskParameter> parameters, Subject subject) { this.parameters = parameters.stream().collect(Collectors.toMap(p -> p.key, p -> p.value)); this.subject = subject; } /** * The cache manager with which this task should be executed */ public TaskContext cacheManager(EmbeddedCacheManager cacheManager) { this.cacheManager = cacheManager; return this; } /** * The marshaller with which this task should be executed */ public TaskContext marshaller(Marshaller marshaller) { this.marshaller = marshaller; return this; } /** * The cache against which this task will be executed. This will be the task's default cache, but other caches can be * obtained from the cache manager */ public TaskContext cache(Cache<?, ?> cache) { this.cache = cache; return this; } /** * A map of named parameters that will be passed to the task. Invoking this method overwrites any previously set * parameters */ public TaskContext parameters(Map<String, ?> parameters) { this.parameters = (Map<String, Object>) parameters; return this; } /** * The subject to impersonate when running this task. If unspecified, the Subject (if any) will be retrieved via * {@link Security#getSubject()} */ public TaskContext subject(Subject subject) { this.subject = subject; return this; } /** * Adds a named parameter to the task context */ public TaskContext addParameter(String name, Object value) { if (parameters == Collections.EMPTY_MAP) { parameters = new HashMap<>(); } parameters.put(name, value); return this; } /** * Adds a named parameter to the task context only if it is non-null */ public TaskContext addOptionalParameter(String name, Object value) { if (value != null) { return addParameter(name, value); } else { return this; } } /** * Whether execution will generate an event in the event log */ public TaskContext logEvent(boolean logEvent) { this.logEvent = logEvent; return this; } /** * CacheManager for this task execution * * @return the cache manager */ public EmbeddedCacheManager getCacheManager() { return cacheManager; } /** * Marshaller for this task execution * * @return optional marshaller */ public Optional<Marshaller> getMarshaller() { return Optional.ofNullable(marshaller); } /** * The default cache. Other caches can be obtained from cache manager ({@link Cache#getCacheManager()}) * * @return optional cache */ public Optional<Cache<?, ?>> getCache() { return Optional.ofNullable(cache); } /** * Gets a map of named parameters for the task * * @return optional map of named parameters for the task */ public Optional<Map<String, Object>> getParameters() { return Optional.of(parameters); } /** * The optional {@link Subject} which is executing this task * * @return the {@link Subject} */ public Optional<Subject> getSubject() { return Optional.ofNullable(subject); } /** * Whether executing this task will generate an event in the event log * * @return true if an event will be logged, false otherwise */ public boolean isLogEvent() { return logEvent; } @Override public String toString() { return "TaskContext{" + "marshaller=" + marshaller + ", cache=" + cache + ", parameters=" + parameters + ", subject=" + subject + ", logEvent=" + logEvent + '}'; } @ProtoField(1) Collection<TaskParameter> parameters() { return parameters.entrySet().stream().map(e -> new TaskParameter(e.getKey(), e.getValue().toString())).collect(Collectors.toList()); } @ProtoField(2) public Subject subject() { return subject; } @ProtoTypeId(ProtoStreamTypeIds.DISTRIBUTED_SERVER_TASK_PARAMETER) static class TaskParameter { @ProtoField(1) String key; @ProtoField(2) String value; @ProtoFactory TaskParameter(String key, String value) { this.key = key; this.value = value; } } }
5,722
25.868545
138
java
null
infinispan-main/tasks/scripting/src/test/java/org/infinispan/scripting/ClusteredScriptingTest.java
package org.infinispan.scripting; import static org.infinispan.scripting.utils.ScriptingUtils.getScriptingManager; import static org.infinispan.scripting.utils.ScriptingUtils.loadData; import static org.infinispan.scripting.utils.ScriptingUtils.loadScript; import static org.infinispan.test.TestingUtil.waitForNoRebalance; import static org.infinispan.test.TestingUtil.withCacheManagers; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertTrue; import java.io.IOException; import java.util.ArrayList; import java.util.Map; import java.util.concurrent.CompletionStage; import java.util.concurrent.ExecutionException; import org.infinispan.Cache; import org.infinispan.commons.dataconversion.MediaType; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.Configuration; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.context.Flag; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.remoting.transport.jgroups.JGroupsAddress; import org.infinispan.tasks.TaskContext; import org.infinispan.test.AbstractInfinispanTest; import org.infinispan.test.MultiCacheManagerCallable; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.infinispan.util.concurrent.CompletionStages; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; @Test(groups = "functional", testName = "scripting.ClusteredScriptingTest") public class ClusteredScriptingTest extends AbstractInfinispanTest { private static final int EXPECTED_WORDS = 3202; @Test(dataProvider = "cacheModeProvider") public void testLocalScriptExecutionWithCache(final CacheMode cacheMode) { withCacheManagers(new MultiCacheManagerCallable( TestCacheManagerFactory.createCacheManager(cacheMode, false), TestCacheManagerFactory.createCacheManager(cacheMode, false)) { @Override public void call() throws IOException, ExecutionException, InterruptedException { ScriptingManager scriptingManager = getScriptingManager(cms[0]); Configuration configuration = new ConfigurationBuilder() .encoding().key().mediaType(MediaType.APPLICATION_OBJECT_TYPE) .encoding().value().mediaType(MediaType.APPLICATION_OBJECT_TYPE).build(); for (EmbeddedCacheManager cm : cms) { cm.defineConfiguration(ScriptingTest.CACHE_NAME, configuration); } loadScript(scriptingManager, "/test.js"); executeScriptOnManager("test.js", cms[0]); executeScriptOnManager("test.js", cms[1]); } }); } @Test(dataProvider = "cacheModeProvider") public void testLocalScriptExecutionWithCache1(final CacheMode cacheMode) { withCacheManagers(new MultiCacheManagerCallable(TestCacheManagerFactory.createCacheManager(cacheMode, false), TestCacheManagerFactory.createCacheManager(cacheMode, false)) { @Override public void call() throws Exception { Configuration configuration = new ConfigurationBuilder() .encoding().key().mediaType(MediaType.APPLICATION_OBJECT_TYPE) .encoding().value().mediaType(MediaType.APPLICATION_OBJECT_TYPE).build(); for (EmbeddedCacheManager cm : cms) { cm.defineConfiguration(ScriptingTest.CACHE_NAME, configuration); } Cache<Object, Object> cache = cms[0].getCache(ScriptingTest.CACHE_NAME); ScriptingManager scriptingManager = getScriptingManager(cms[0]); loadScript(scriptingManager, "/test1.js"); cache.put("a", "newValue"); executeScriptOnManager("test1.js", cms[0]); executeScriptOnManager("test1.js", cms[1]); } }); } @Test(dataProvider = "cacheModeProvider") public void testDistExecScriptWithCache(final CacheMode cacheMode) { withCacheManagers(new MultiCacheManagerCallable(TestCacheManagerFactory.createCacheManager(cacheMode, false), TestCacheManagerFactory.createCacheManager(cacheMode, false)) { public void call() throws Exception { Cache cache1 = cms[0].getCache(); Cache cache2 = cms[1].getCache(); ScriptingManager scriptingManager = getScriptingManager(cms[0]); loadScript(scriptingManager, "/distExec1.js"); waitForNoRebalance(cache1, cache2); CompletionStage<ArrayList<JGroupsAddress>> resultsFuture = scriptingManager.runScript("distExec1.js", new TaskContext().cache(cache1)); ArrayList<JGroupsAddress> results = CompletionStages.join(resultsFuture); assertEquals(2, results.size()); assertTrue(results.contains(cms[0].getAddress())); assertTrue(results.contains(cms[1].getAddress())); } }); } @Test(dataProvider = "cacheModeProvider") public void testDistExecScriptWithCacheManagerAndParams(final CacheMode cacheMode) { ConfigurationBuilder builder = new ConfigurationBuilder(); builder.clustering().cacheMode(cacheMode) .encoding().key().mediaType(MediaType.APPLICATION_OBJECT_TYPE) .encoding().value().mediaType(MediaType.APPLICATION_OBJECT_TYPE); withCacheManagers(new MultiCacheManagerCallable(TestCacheManagerFactory.createClusteredCacheManager(builder), TestCacheManagerFactory.createClusteredCacheManager(builder)) { public void call() throws Exception { Cache cache1 = cms[0].getCache(); Cache cache2 = cms[1].getCache(); ScriptingManager scriptingManager = getScriptingManager(cms[0]); loadScript(scriptingManager, "/distExec.js"); waitForNoRebalance(cache1, cache2); CompletionStage<ArrayList<JGroupsAddress>> resultsFuture = scriptingManager.runScript("distExec.js", new TaskContext().cache(cache1).addParameter("a", "value")); ArrayList<JGroupsAddress> results = CompletionStages.join(resultsFuture); assertEquals(2, results.size()); assertTrue(results.contains(cms[0].getAddress())); assertTrue(results.contains(cms[1].getAddress())); assertEquals("value", cache1.get("a")); assertEquals("value", cache2.get("a")); } }); } @Test(expectedExceptions = IllegalStateException.class, dataProvider = "cacheModeProvider", expectedExceptionsMessageRegExp = ".*without a cache binding.*") public void testDistributedScriptExecutionWithoutCacheBinding(final CacheMode cacheMode) { withCacheManagers(new MultiCacheManagerCallable(TestCacheManagerFactory.createCacheManager(cacheMode, false), TestCacheManagerFactory.createCacheManager(cacheMode, false)) { public void call() throws Exception { ScriptingManager scriptingManager = getScriptingManager(cms[0]); loadScript(scriptingManager, "/distExec.js"); CompletionStages.join(scriptingManager.runScript("distExec.js")); } }); } @Test(dataProvider = "cacheModeProvider") public void testDistributedMapReduceStreamWithFlag(final CacheMode cacheMode) { withCacheManagers(new MultiCacheManagerCallable(TestCacheManagerFactory.createCacheManager(cacheMode, false), TestCacheManagerFactory.createCacheManager(cacheMode, false)) { public void call() throws Exception { ScriptingManager scriptingManager = getScriptingManager(cms[0]); Cache cache1 = cms[0].getCache(); Cache cache2 = cms[1].getCache(); loadData(cache1, "/macbeth.txt"); loadScript(scriptingManager, "/wordCountStream.js"); waitForNoRebalance(cache1, cache2); Map<String, Long> resultsFuture = CompletionStages.join(scriptingManager.runScript( "wordCountStream.js", new TaskContext().cache(cache1.getAdvancedCache().withFlags(Flag.CACHE_MODE_LOCAL)))); assertEquals(EXPECTED_WORDS, resultsFuture.size()); assertEquals(resultsFuture.get("macbeth"), Long.valueOf(287)); resultsFuture = (Map<String, Long>) CompletionStages.join(scriptingManager.runScript( "wordCountStream.js", new TaskContext().cache(cache1.getAdvancedCache().withFlags(Flag.CACHE_MODE_LOCAL)))); assertEquals(EXPECTED_WORDS, resultsFuture.size()); assertEquals(resultsFuture.get("macbeth"), Long.valueOf(287)); } }); } @Test(enabled = false, dataProvider = "cacheModeProvider", description = "Disabled due to ISPN-6173.") public void testDistributedMapReduceStreamLocalMode(final CacheMode cacheMode) throws IOException, ExecutionException, InterruptedException { withCacheManagers(new MultiCacheManagerCallable(TestCacheManagerFactory.createCacheManager(cacheMode, false), TestCacheManagerFactory.createCacheManager(cacheMode, false)) { public void call() throws Exception { ScriptingManager scriptingManager = getScriptingManager(cms[0]); Cache cache1 = cms[0].getCache(); Cache cache2 = cms[1].getCache(); loadData(cache1, "/macbeth.txt"); loadScript(scriptingManager, "/wordCountStream_serializable.js"); waitForNoRebalance(cache1, cache2); ArrayList<Map<String, Long>> resultsFuture = CompletionStages.join(scriptingManager.runScript( "wordCountStream_serializable.js", new TaskContext().cache(cache1))); assertEquals(2, resultsFuture.size()); assertEquals(EXPECTED_WORDS, resultsFuture.get(0).size()); assertEquals(EXPECTED_WORDS, resultsFuture.get(1).size()); assertEquals(resultsFuture.get(0).get("macbeth"), Long.valueOf(287)); assertEquals(resultsFuture.get(1).get("macbeth"), Long.valueOf(287)); } }); } @Test(enabled = false, dataProvider = "cacheModeProvider", description = "Disabled due to ISPN-6173.") public void testDistributedMapReduceStreamLocalModeWithExecutors(final CacheMode cacheMode) throws IOException, ExecutionException, InterruptedException { withCacheManagers(new MultiCacheManagerCallable(TestCacheManagerFactory.createCacheManager(cacheMode, false), TestCacheManagerFactory.createCacheManager(cacheMode, false)) { public void call() throws Exception { ScriptingManager scriptingManager = getScriptingManager(cms[0]); Cache cache1 = cms[0].getCache(); Cache cache2 = cms[1].getCache(); loadData(cache1, "/macbeth.txt"); loadScript(scriptingManager, "/wordCountStream_Exec.js"); waitForNoRebalance(cache1, cache2); ArrayList<Map<String, Long>> resultsFuture = CompletionStages.join(scriptingManager.runScript( "wordCountStream_Exec.js", new TaskContext().cache(cache1))); assertEquals(2, resultsFuture.size()); assertEquals(EXPECTED_WORDS, resultsFuture.get(0).size()); assertEquals(EXPECTED_WORDS, resultsFuture.get(1).size()); assertEquals(resultsFuture.get(0).get("macbeth"), Long.valueOf(287)); assertEquals(resultsFuture.get(1).get("macbeth"), Long.valueOf(287)); } }); } @Test(enabled = false, dataProvider = "cacheModeProvider", description = "Disabled due to ISPN-6173.") public void testDistributedMapReduceStream(final CacheMode cacheMode) throws IOException, ExecutionException, InterruptedException { withCacheManagers(new MultiCacheManagerCallable(TestCacheManagerFactory.createCacheManager(cacheMode, false), TestCacheManagerFactory.createCacheManager(cacheMode, false)) { public void call() throws Exception { ScriptingManager scriptingManager = getScriptingManager(cms[0]); Cache cache1 = cms[0].getCache(); Cache cache2 = cms[1].getCache(); loadData(cache1, "/macbeth.txt"); loadScript(scriptingManager, "/wordCountStream_dist.js"); waitForNoRebalance(cache1, cache2); ArrayList<Map<String, Long>> resultsFuture = CompletionStages.join(scriptingManager.runScript( "wordCountStream_dist.js", new TaskContext().cache(cache1))); assertEquals(2, resultsFuture.size()); assertEquals(EXPECTED_WORDS, resultsFuture.get(0).size()); assertEquals(EXPECTED_WORDS, resultsFuture.get(1).size()); assertEquals(resultsFuture.get(0).get("macbeth"), Long.valueOf(287)); assertEquals(resultsFuture.get(1).get("macbeth"), Long.valueOf(287)); } }); } private void executeScriptOnManager(String scriptName, EmbeddedCacheManager cacheManager) throws InterruptedException, ExecutionException { ScriptingManager scriptingManager = getScriptingManager(cacheManager); String value = CompletionStages.join(scriptingManager.runScript(scriptName, new TaskContext().addParameter("a", "value"))); assertEquals(value, cacheManager.getCache(ScriptingTest.CACHE_NAME).get("a")); } @DataProvider(name = "cacheModeProvider") private static Object[][] provideCacheMode() { return new Object[][]{{CacheMode.REPL_SYNC}, {CacheMode.DIST_SYNC}}; } }
13,450
50.934363
159
java
null
infinispan-main/tasks/scripting/src/test/java/org/infinispan/scripting/AbstractScriptingTest.java
package org.infinispan.scripting; import static org.infinispan.commons.test.CommonsTestingUtil.loadFileAsString; import java.io.InputStream; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.test.SingleCacheManagerTest; import org.infinispan.test.fwk.TestCacheManagerFactory; /** * Abstract class providing all general methods. */ public abstract class AbstractScriptingTest extends SingleCacheManagerTest { protected ScriptingManager scriptingManager; @Override protected EmbeddedCacheManager createCacheManager() throws Exception { return TestCacheManagerFactory.createCacheManager(); } protected abstract String[] getScripts(); @Override protected void setup() throws Exception { super.setup(); scriptingManager = cacheManager.getGlobalComponentRegistry().getComponent(ScriptingManager.class); for (String scriptName : getScripts()) { try (InputStream is = this.getClass().getResourceAsStream("/" + scriptName)) { String script = loadFileAsString(is); scriptingManager.addScript(scriptName, script); } } } }
1,173
30.72973
106
java
null
infinispan-main/tasks/scripting/src/test/java/org/infinispan/scripting/ScriptMetadataTest.java
package org.infinispan.scripting; import static org.infinispan.commons.dataconversion.MediaType.TEXT_PLAIN; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertTrue; import java.nio.charset.StandardCharsets; import java.util.Arrays; import org.infinispan.commons.CacheException; import org.infinispan.scripting.impl.ScriptMetadata; import org.infinispan.scripting.impl.ScriptMetadataParser; import org.infinispan.test.AbstractInfinispanTest; import org.testng.annotations.Test; @Test(groups="functional", testName="scripting.ScriptMetadataTest") public class ScriptMetadataTest extends AbstractInfinispanTest { public void testDoubleSlashComment() throws Exception { ScriptMetadata metadata = ScriptMetadataParser.parse("test.js", "// name=test"); assertEquals("test", metadata.name()); } public void testDefaultScriptExtension() throws Exception { ScriptMetadata metadata = ScriptMetadataParser.parse("test", "// name=test"); assertEquals("test", metadata.name()); } public void testDefaultScriptExtension1() { ScriptMetadata metadata = ScriptMetadataParser.parse("test.", "/* name=exampleName */"); assertEquals("test.", metadata.name()); } public void testHashComment() throws Exception { ScriptMetadata metadata = ScriptMetadataParser.parse("test.js", "# name=test"); assertEquals("test", metadata.name()); } public void testDoublSemicolonComment() throws Exception { ScriptMetadata metadata = ScriptMetadataParser.parse("test.js", ";; name=test"); assertEquals("test", metadata.name()); } public void testMultiplePairs() throws Exception { ScriptMetadata metadata = ScriptMetadataParser.parse("test.scala", "// name=test,language=scala"); assertEquals("test", metadata.name()); assertEquals("scala", metadata.language().get()); } public void testDoubleQuotedValues() throws Exception { ScriptMetadata metadata = ScriptMetadataParser.parse("test.scala", "// name=\"te,st\",language=scala"); assertEquals("te,st", metadata.name()); assertEquals("scala", metadata.language().get()); } public void testSingleQuotedValues() throws Exception { ScriptMetadata metadata = ScriptMetadataParser.parse("test.scala", "// name='te,st',language=scala"); assertEquals("te,st", metadata.name()); assertEquals("scala", metadata.language().get()); } public void testSingleQuatedValuesWithProvidedExtension() throws Exception { ScriptMetadata metadata = ScriptMetadataParser.parse("test", "// name='te,st',language=scala,extension=scala"); assertEquals("te,st", metadata.name()); assertEquals("scala", metadata.language().get()); assertEquals("scala", metadata.extension()); } public void testDataTypeUtf8() throws Exception { ScriptMetadata metadata = ScriptMetadataParser.parse("test", "// name='test',language=javascript,datatype='text/plain; charset=utf-8'"); assertEquals("test", metadata.name()); assertEquals("javascript", metadata.language().get()); assertEquals("js", metadata.extension()); assertTrue(metadata.dataType().match(TEXT_PLAIN)); assertEquals(StandardCharsets.UTF_8, metadata.dataType().getCharset()); } public void testDataTypeOther() throws Exception { ScriptMetadata metadata = ScriptMetadataParser.parse("test", "// name='test',language=javascript,datatype='text/plain; charset=us-ascii'"); assertEquals("test", metadata.name()); assertEquals("javascript", metadata.language().get()); assertEquals("js", metadata.extension()); assertTrue(metadata.dataType().match(TEXT_PLAIN)); assertEquals(StandardCharsets.US_ASCII, metadata.dataType().getCharset()); } public void testArrayValues() throws Exception { ScriptMetadata metadata = ScriptMetadataParser.parse("test.scala", "// name=test,language=javascript,parameters=[a,b,c]"); assertEquals("test", metadata.name()); assertEquals("javascript", metadata.language().get()); assertTrue(metadata.parameters().containsAll(Arrays.asList("a", "b", "c"))); } public void testMultiLine() throws Exception { ScriptMetadata metadata = ScriptMetadataParser.parse("test.scala", "// name=test\n// language=scala"); assertEquals("test", metadata.name()); assertEquals("scala", metadata.language().get()); } @Test(expectedExceptions=IllegalArgumentException.class, expectedExceptionsMessageRegExp=".*Script parameters must be declared using.*") public void testBrokenParameters() throws Exception { ScriptMetadata metadata = ScriptMetadataParser.parse("test.scala", "// name=test,language=javascript,parameters=\"a,b,c\""); assertEquals("test", metadata.name()); assertEquals("javascript", metadata.language()); assertTrue(metadata.parameters().containsAll(Arrays.asList("a", "b", "c"))); } @Test(expectedExceptions=CacheException.class, expectedExceptionsMessageRegExp=".*Unknown script mode:.*") public void testUnknownScriptProperty() throws Exception { ScriptMetadata metadata = ScriptMetadataParser.parse("test.scala", "// name=test,language=javascript,parameters=[a,b,c],unknown=example"); assertEquals("test", metadata.name()); assertEquals("javascript", metadata.language()); assertTrue(metadata.parameters().containsAll(Arrays.asList("a", "b", "c"))); } }
5,466
46.12931
145
java
null
infinispan-main/tasks/scripting/src/test/java/org/infinispan/scripting/EntryComparator.java
package org.infinispan.scripting; import java.util.Comparator; import java.util.Map; import java.util.Map.Entry; public class EntryComparator implements Comparator<Map.Entry<String, Double>> { @Override public int compare(Entry<String, Double> o1, Entry<String, Double> o2) { return o1.getValue() < o2.getValue() ? 1 : o1.getValue() > o2.getValue() ? -1 : 0; } }
382
24.533333
88
java
null
infinispan-main/tasks/scripting/src/test/java/org/infinispan/scripting/ScriptCachePreserveStateAcrossRestarts.java
package org.infinispan.scripting; import static org.infinispan.commons.test.CommonsTestingUtil.loadFileAsString; import static org.testng.AssertJUnit.assertTrue; import java.io.InputStream; import org.infinispan.Cache; import org.infinispan.commons.test.CommonsTestingUtil; import org.infinispan.commons.util.Util; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.global.GlobalConfigurationBuilder; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.scripting.impl.ScriptingManagerImpl; import org.infinispan.test.AbstractInfinispanTest; import org.infinispan.test.CacheManagerCallable; import org.infinispan.test.TestingUtil; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.testng.annotations.Test; @Test(groups = "functional", testName = "scripting.ScriptCachePreserveStateAcrossRestarts") public class ScriptCachePreserveStateAcrossRestarts extends AbstractInfinispanTest { protected EmbeddedCacheManager createCacheManager(String persistentStateLocation) throws Exception { GlobalConfigurationBuilder global = new GlobalConfigurationBuilder(); global.globalState().enable().persistentLocation(persistentStateLocation); EmbeddedCacheManager cacheManager = TestCacheManagerFactory.createCacheManager(global, new ConfigurationBuilder()); cacheManager.getCache(); return cacheManager; } public void testStatePreserved() throws Exception { String persistentStateLocation = CommonsTestingUtil.tmpDirectory(this.getClass()); Util.recursiveFileRemove(persistentStateLocation); TestingUtil.withCacheManager(new CacheManagerCallable(createCacheManager(persistentStateLocation)) { @Override public void call() throws Exception { Cache<String, String> scriptCache = cm.getCache(ScriptingManagerImpl.SCRIPT_CACHE); try (InputStream is = this.getClass().getResourceAsStream("/test.js")) { String script = loadFileAsString(is); scriptCache.put("test.js", script); } } }); TestingUtil.withCacheManager(new CacheManagerCallable(createCacheManager(persistentStateLocation)) { @Override public void call() throws Exception { Cache<String, String> scriptCache = cm.getCache(ScriptingManagerImpl.SCRIPT_CACHE); assertTrue(scriptCache.containsKey("test.js")); } }); } }
2,476
42.45614
121
java
null
infinispan-main/tasks/scripting/src/test/java/org/infinispan/scripting/ScriptingTest.java
package org.infinispan.scripting; import static org.infinispan.commons.test.CommonsTestingUtil.loadFileAsString; import static org.infinispan.scripting.utils.ScriptingUtils.loadData; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertNotNull; import static org.testng.AssertJUnit.assertNull; import java.io.IOException; import java.io.InputStream; import java.util.Map; import java.util.concurrent.CompletionException; import java.util.concurrent.CompletionStage; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import org.infinispan.Cache; import org.infinispan.commons.CacheException; import org.infinispan.commons.dataconversion.MediaType; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.tasks.TaskContext; import org.infinispan.test.fwk.CleanupAfterMethod; import org.infinispan.util.concurrent.CompletionStages; import org.testng.annotations.Test; @Test(groups = "functional", testName = "scripting.ScriptingTest") @CleanupAfterMethod public class ScriptingTest extends AbstractScriptingTest { static final String CACHE_NAME = "script-exec"; protected String[] getScripts() { return new String[]{"test.js", "testMissingMetaProps.js", "testExecWithoutProp.js", "testInnerScriptCall.js"}; } @Override protected void setup() throws Exception { super.setup(); ConfigurationBuilder builder = new ConfigurationBuilder(); builder.encoding().key().mediaType(MediaType.APPLICATION_OBJECT_TYPE); builder.encoding().value().mediaType(MediaType.APPLICATION_OBJECT_TYPE); cacheManager.defineConfiguration(CACHE_NAME, builder.build()); } @Override protected void clearContent() { cacheManager.getCache().clear(); } public void testSimpleScript() throws Exception { String result = CompletionStages.join(scriptingManager.runScript("test.js", new TaskContext().addParameter("a", "a"))); assertEquals("a", result); } @Test(expectedExceptions = CacheException.class, expectedExceptionsMessageRegExp = ".*No script named.*") public void testScriptRemove() throws Exception { scriptingManager.getScript("testExecWithoutProp.js"); scriptingManager.removeScript("testExecWithoutProp.js"); scriptingManager.getScript("testExecWithoutProp.js"); } @Test(expectedExceptions = CacheException.class, expectedExceptionsMessageRegExp = ".*No script named.*") public void testRunNonExistentScript() throws Exception { String result = CompletionStages.join(scriptingManager.runScript("nonExistent.js", new TaskContext().addParameter("a", "a"))); assertEquals("a", result); } @Test(expectedExceptions = CacheException.class, expectedExceptionsMessageRegExp = ".*Script execution error.*") public void testSimpleScriptWitoutPassingParameter() throws Throwable { try { CompletionStages.join(scriptingManager.runScript("test.js")); } catch (CompletionException e) { throw e.getCause(); } } public void testSimpleScriptReplacementWithNew() throws ExecutionException, InterruptedException, IOException { String result = CompletionStages.join(scriptingManager.runScript("test.js", new TaskContext().addParameter("a", "a"))); assertEquals("a", result); //Replacing the existing script with new one. InputStream is = this.getClass().getResourceAsStream("/test1.js"); String script = loadFileAsString(is); scriptingManager.addScript("test.js", script); result = CompletionStages.join(scriptingManager.runScript("test.js")); assertEquals("a:modified", result); //Rolling back the replacement. is = this.getClass().getResourceAsStream("/test.js"); script = loadFileAsString(is); scriptingManager.addScript("test.js", script); } @Test(expectedExceptions = CacheException.class, expectedExceptionsMessageRegExp = ".*No script named.*") public void testScriptingCacheClear() throws Exception { String result = CompletionStages.join(scriptingManager.runScript("test.js", new TaskContext().addParameter("a", "a"))); assertEquals("a", result); cache(ScriptingManager.SCRIPT_CACHE).clear(); result = CompletionStages.join(scriptingManager.runScript("test.js", new TaskContext().addParameter("a", "a"))); assertEquals("a", result); } public void testScriptingCacheManualReplace() throws Exception { String result = CompletionStages.join(scriptingManager.runScript("test.js", new TaskContext().addParameter("a", "a"))); assertEquals("a", result); //Replacing the existing script with new one. InputStream is = this.getClass().getResourceAsStream("/test1.js"); String script = loadFileAsString(is); cache(ScriptingManager.SCRIPT_CACHE).replace("test.js", script); result = CompletionStages.join(scriptingManager.runScript("test.js")); assertEquals("a:modified", result); //Rolling back the replacement. is = this.getClass().getResourceAsStream("/test.js"); script = loadFileAsString(is); scriptingManager.addScript("test.js", script); } public void testSimpleScript1() throws Exception { String value = "javaValue"; String key = "processValue"; cacheManager.getCache(CACHE_NAME).put(key, value); CompletionStage<?> exec = scriptingManager.runScript("testExecWithoutProp.js"); exec.toCompletableFuture().get(1000, TimeUnit.MILLISECONDS); assertEquals(value + ":additionFromJavascript", cacheManager.getCache(CACHE_NAME).get(key)); } public void testScriptCallFromJavascript() throws Exception { String result = CompletionStages.join(scriptingManager.runScript("testInnerScriptCall.js", new TaskContext().cache(cacheManager.getCache(CACHE_NAME)).addParameter("a", "ahoj"))); assertEquals("script1:additionFromJavascript", result); assertEquals("ahoj", cacheManager.getCache(CACHE_NAME).get("a")); } public void testSimpleScriptWithMissingLanguageInMetaPropeties() throws Exception { String result = CompletionStages.join(scriptingManager.runScript("testMissingMetaProps.js", new TaskContext().addParameter("a", "a"))); assertEquals("a", result); } @Test(expectedExceptions = CacheException.class, expectedExceptionsMessageRegExp = ".*No script named.*") public void testRemovingNonExistentScript() { scriptingManager.removeScript("nonExistent"); } public void testRemovingScript() throws IOException, ExecutionException, InterruptedException { assertNotNull(scriptingManager.getScript("test.js")); scriptingManager.removeScript("test.js"); assertNull(cacheManager.getCache(ScriptingManager.SCRIPT_CACHE).get("test.js")); InputStream is = this.getClass().getResourceAsStream("/test.js"); String script = loadFileAsString(is); scriptingManager.addScript("test.js", script); assertNotNull(scriptingManager.getScript("test.js")); } @Test(expectedExceptions = CacheException.class, expectedExceptionsMessageRegExp = ".*Script execution error.*") public void testWrongJavaRef() throws Throwable { InputStream is = this.getClass().getResourceAsStream("/testWrongJavaRef.js"); String script = loadFileAsString(is); scriptingManager.addScript("testWrongJavaRef.js", script); try { CompletionStages.join(scriptingManager.runScript("testWrongJavaRef.js", new TaskContext().addParameter("a", "a"))); } catch (CompletionException e) { throw e.getCause(); } } @Test(expectedExceptions = CacheException.class, expectedExceptionsMessageRegExp = ".*Script execution error.*") public void testWrongPropertyRef() throws Throwable { InputStream is = this.getClass().getResourceAsStream("/testWrongPropertyRef.js"); String script = loadFileAsString(is); scriptingManager.addScript("testWrongPropertyRef.js", script); try { CompletionStages.join(scriptingManager.runScript("testWrongPropertyRef.js")); } catch (CompletionException e) { throw e.getCause(); } } @Test(expectedExceptions = CacheException.class, expectedExceptionsMessageRegExp = ".*Compiler error for script.*") public void testJsCompilationError() throws Exception { InputStream is = this.getClass().getResourceAsStream("/testJsCompilationError.js"); String script = loadFileAsString(is); scriptingManager.addScript("testJsCompilationError.js", script); String result = CompletionStages.join(scriptingManager.runScript("testJsCompilationError.js")); assertEquals("a", result); } @Test(expectedExceptions = CacheException.class, expectedExceptionsMessageRegExp = ".*No script named.*") public void testGetNonExistentScript() { scriptingManager.getScript("nonExistent.js"); } @Test(expectedExceptions = IllegalArgumentException.class, expectedExceptionsMessageRegExp = ".*Cannot find an appropriate script engine for script.*") public void testNonSupportedScript() { scriptingManager.addScript("Test.java", "//mode=local,language=nondescript\n" + "public class Test {\n" + " public static void main(String[] args) {\n" + " System.out.println(cache.get(\"test.js\"));\n" + " }\n" + " }"); scriptingManager.runScript("Test.java"); } public void testMapReduceScript() throws IOException, ExecutionException, InterruptedException { InputStream is = this.getClass().getResourceAsStream("/wordCountStream.js"); String script = loadFileAsString(is); Cache<String, String> cache = cache(CACHE_NAME); loadData(cache, "/macbeth.txt"); scriptingManager.addScript("wordCountStream.js", script); Map<String, Long> result = CompletionStages.join(scriptingManager.runScript("wordCountStream.js", new TaskContext().cache(cache))); assertEquals(3202, result.size()); assertEquals(Long.valueOf(287), result.get("macbeth")); } }
10,140
41.609244
154
java
null
infinispan-main/tasks/scripting/src/test/java/org/infinispan/scripting/ScriptingTaskManagerTest.java
package org.infinispan.scripting; import static org.infinispan.test.TestingUtil.extractGlobalComponent; import static org.testng.AssertJUnit.assertEquals; import java.util.List; import java.util.concurrent.CompletionException; import org.infinispan.commons.CacheException; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.scripting.impl.ScriptTask; import org.infinispan.scripting.utils.ScriptingUtils; import org.infinispan.tasks.Task; import org.infinispan.tasks.TaskContext; import org.infinispan.tasks.TaskExecutionMode; import org.infinispan.tasks.TaskManager; import org.infinispan.tasks.spi.TaskEngine; import org.infinispan.test.SingleCacheManagerTest; import org.infinispan.test.fwk.CleanupAfterMethod; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.infinispan.commons.util.concurrent.CompletableFutures; import org.infinispan.util.concurrent.CompletionStages; import org.testng.annotations.Test; @Test(groups="functional", testName="scripting.ScriptingTaskManagerTest") @CleanupAfterMethod public class ScriptingTaskManagerTest extends SingleCacheManagerTest { protected static final String TEST_SCRIPT = "test.js"; protected static final String BROKEN_SCRIPT = "brokenTest.js"; protected TaskManager taskManager; @Override protected EmbeddedCacheManager createCacheManager() throws Exception { return TestCacheManagerFactory.createCacheManager(); } @Override protected void setup() throws Exception { super.setup(); taskManager = extractGlobalComponent(cacheManager, TaskManager.class); cacheManager.defineConfiguration(ScriptingTest.CACHE_NAME, new ConfigurationBuilder().build()); } public void testTask() throws Exception { ScriptingManager scriptingManager = extractGlobalComponent(cacheManager, ScriptingManager.class); ScriptingUtils.loadScript(scriptingManager, TEST_SCRIPT); String result = CompletionStages.join(taskManager.runTask(TEST_SCRIPT, new TaskContext().addParameter("a", "a"))); assertEquals("a", result); List<Task> tasks = taskManager.getTasks(); assertEquals(1, tasks.size()); ScriptTask scriptTask = (ScriptTask) tasks.get(0); assertEquals("test.js", scriptTask.getName()); assertEquals(TaskExecutionMode.ONE_NODE, scriptTask.getExecutionMode()); assertEquals("Script", scriptTask.getType()); } public void testAvailableEngines() { List<TaskEngine> engines = taskManager.getEngines(); assertEquals(1, engines.size()); assertEquals("Script", engines.get(0).getName()); } @Test(expectedExceptions = CacheException.class, expectedExceptionsMessageRegExp = ".*Script execution error.*") public void testBrokenTask() throws Throwable { ScriptingManager scriptingManager = extractGlobalComponent(cacheManager, ScriptingManager.class); ScriptingUtils.loadScript(scriptingManager, BROKEN_SCRIPT); try { CompletionStages.join(taskManager.runTask(BROKEN_SCRIPT, new TaskContext())); } catch (CompletionException e) { throw CompletableFutures.extractException(e); } } }
3,212
40.192308
120
java
null
infinispan-main/tasks/scripting/src/test/java/org/infinispan/scripting/ScriptingDataStoresTest.java
package org.infinispan.scripting; import static org.testng.AssertJUnit.assertEquals; import java.util.concurrent.CompletionStage; import java.util.concurrent.TimeUnit; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.cache.StorageType; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.tasks.TaskContext; import org.infinispan.test.fwk.CleanupAfterMethod; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.testng.annotations.Factory; import org.testng.annotations.Test; /** * @author vjuranek * @since 9.2 */ @Test(groups = "functional", testName = "scripting.ScriptingDataStoresTest") @CleanupAfterMethod public class ScriptingDataStoresTest extends AbstractScriptingTest { static final String CACHE_NAME = "script-exec"; protected StorageType storageType; @Override protected String parameters() { return "[" + storageType + "]"; } @Factory public Object[] factory() { return new Object[]{ new ScriptingDataStoresTest().withStorageType(StorageType.OFF_HEAP), new ScriptingDataStoresTest().withStorageType(StorageType.BINARY), new ScriptingDataStoresTest().withStorageType(StorageType.OBJECT), }; } ScriptingDataStoresTest withStorageType(StorageType storageType) { this.storageType = storageType; return this; } protected String[] getScripts() { return new String[]{"test.js", "testExecWithoutProp.js"}; } @Override protected EmbeddedCacheManager createCacheManager() throws Exception { ConfigurationBuilder conf = new ConfigurationBuilder(); conf.memory().storageType(storageType); return TestCacheManagerFactory.createCacheManager(conf); } @Override protected void setup() throws Exception { super.setup(); ConfigurationBuilder builder = new ConfigurationBuilder(); builder.memory().storageType(this.storageType); cacheManager.defineConfiguration(CACHE_NAME, builder.build()); cacheManager.getCache(CACHE_NAME); } @Override protected void clearContent() { cacheManager.getCache().clear(); } public void testScriptWithParam() throws Exception { CompletionStage<String> scriptStage = scriptingManager.runScript("test.js", new TaskContext().addParameter("a", "a")); String result = scriptStage.toCompletableFuture().get(10, TimeUnit.SECONDS); assertEquals("a", result); assertEquals("a", cacheManager.getCache(CACHE_NAME).get("a")); } public void testScriptWithoutParam() throws Exception { String value = "javaValue"; String key = "processValue"; cacheManager.getCache(CACHE_NAME).put(key, value); CompletionStage<String> scriptStage = scriptingManager.runScript("testExecWithoutProp.js"); String result = scriptStage.toCompletableFuture().get(10, TimeUnit.SECONDS); assertEquals("javaValue", result); assertEquals(value + ":additionFromJavascript", cacheManager.getCache(CACHE_NAME).get(key)); } }
3,091
32.608696
98
java
null
infinispan-main/tasks/scripting/src/test/java/org/infinispan/scripting/ReplicatedSecuredScriptingTest.java
package org.infinispan.scripting; import static org.infinispan.scripting.utils.ScriptingUtils.getScriptingManager; import static org.infinispan.scripting.utils.ScriptingUtils.loadScript; import static org.testng.AssertJUnit.assertEquals; import java.io.IOException; import java.util.List; import javax.security.auth.Subject; import org.infinispan.Cache; import org.infinispan.commons.dataconversion.MediaType; import org.infinispan.commons.test.Exceptions; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.global.GlobalConfigurationBuilder; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.remoting.transport.jgroups.JGroupsAddress; import org.infinispan.security.AuthorizationPermission; import org.infinispan.security.Security; import org.infinispan.security.mappers.IdentityRoleMapper; import org.infinispan.tasks.TaskContext; import org.infinispan.test.MultipleCacheManagersTest; import org.infinispan.test.TestingUtil; import org.infinispan.test.fwk.CleanupAfterTest; import org.infinispan.util.concurrent.CompletionStages; import org.testng.annotations.AfterClass; import org.testng.annotations.AfterMethod; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; /** * Tests verifying the script execution in secured clustered ispn environment. * * @author Anna Manukyan */ @Test(groups = "functional", testName = "scripting.ReplicatedSecuredScriptingTest") @CleanupAfterTest public class ReplicatedSecuredScriptingTest extends MultipleCacheManagersTest { static final Subject ADMIN = TestingUtil.makeSubject("admin", ScriptingManager.SCRIPT_MANAGER_ROLE); static final Subject RUNNER = TestingUtil.makeSubject("runner", "runner"); static final Subject PHEIDIPPIDES = TestingUtil.makeSubject("pheidippides", "pheidippides"); @Override protected void createCacheManagers() throws Throwable { final GlobalConfigurationBuilder global = GlobalConfigurationBuilder.defaultClusteredBuilder(); final ConfigurationBuilder builder = getDefaultClusteredCacheConfig(CacheMode.REPL_SYNC); global.security().authorization().enable() .groupOnlyMapping(false) .principalRoleMapper(new IdentityRoleMapper()).role("admin").permission(AuthorizationPermission.ALL) .role("runner") .permission(AuthorizationPermission.EXEC) .permission(AuthorizationPermission.READ) .permission(AuthorizationPermission.WRITE) .permission(AuthorizationPermission.ADMIN) .role("pheidippides") .permission(AuthorizationPermission.EXEC) .permission(AuthorizationPermission.READ) .permission(AuthorizationPermission.WRITE); builder.security().authorization().enable().role("admin").role("runner").role("pheidippides"); builder.encoding().key().mediaType(MediaType.APPLICATION_OBJECT_TYPE) .encoding().value().mediaType(MediaType.APPLICATION_OBJECT_TYPE); Security.doAs(ADMIN, () -> { createCluster(global, builder, 2); defineConfigurationOnAllManagers(SecureScriptingTest.SECURE_CACHE_NAME, builder); for (EmbeddedCacheManager cm : cacheManagers) cm.getCache(SecureScriptingTest.SECURE_CACHE_NAME); waitForClusterToForm(); }); } @Override @AfterClass(alwaysRun = true) protected void destroy() { Security.doAs(ADMIN, () -> ReplicatedSecuredScriptingTest.super.destroy()); } @Override @AfterMethod(alwaysRun = true) protected void clearContent() throws Throwable { Security.doAs(ADMIN, () -> { try { ReplicatedSecuredScriptingTest.super.clearContent(); } catch (Throwable e) { throw new RuntimeException(e); } }); } public void testLocalScriptExecutionWithRole() { ScriptingManager scriptingManager = getScriptingManager(manager(0)); Security.doAs(ADMIN, () -> { try { loadScript(scriptingManager, "/testRole.js"); } catch (IOException e) { throw new RuntimeException(e); } }); Security.doAs(PHEIDIPPIDES, () -> { Cache cache = manager(0).getCache(SecureScriptingTest.SECURE_CACHE_NAME); String value = CompletionStages.join(scriptingManager.runScript("testRole.js", new TaskContext().cache(cache).addParameter("a", "value"))); assertEquals("value", value); assertEquals("value", cache.get("a")); }); } @Test(expectedExceptions = {SecurityException.class}) public void testLocalScriptExecutionWithAuthException() { ScriptingManager scriptingManager = getScriptingManager(manager(0)); Security.doAs(ADMIN, () -> { try { loadScript(scriptingManager, "/testRole.js"); } catch (IOException e) { throw new RuntimeException(e); } } ); Security.doAs(RUNNER, () -> { Cache cache = manager(0).getCache(); CompletionStages.join(scriptingManager.runScript("testRole.js", new TaskContext().cache(cache).addParameter("a", "value"))); return null; }); } @Test(enabled = false, description = "Enable when ISPN-6374 is fixed.") public void testDistributedScriptExecutionWithRole() { ScriptingManager scriptingManager = getScriptingManager(manager(0)); Security.doAs(ADMIN, () -> Exceptions.unchecked(() -> loadScript(scriptingManager, "/testRole_dist.js"))); Security.doAs(RUNNER, () -> { Cache cache = manager(0).getCache(); List<JGroupsAddress> value = CompletionStages.join(scriptingManager.runScript("testRole_dist.js", new TaskContext().cache(cache).addParameter("a", "value"))); assertEquals(value.get(0), manager(0).getAddress()); assertEquals(value.get(1), manager(1).getAddress()); assertEquals("value", cache.get("a")); assertEquals("value", manager(1).getCache().get("a")); }); } @Test(expectedExceptions = {SecurityException.class}) public void testDistributedScriptExecutionWithAuthException() { ScriptingManager scriptingManager = getScriptingManager(manager(0)); Security.doAs(ADMIN, () -> Exceptions.unchecked(() -> loadScript(scriptingManager, "/testRole_dist.js"))); Security.doAs(PHEIDIPPIDES, () -> { Cache cache = manager(0).getCache(); CompletionStages.join(scriptingManager.runScript("testRole_dist.js", new TaskContext().cache(cache).addParameter("a", "value"))); }); } @DataProvider(name = "cacheModeProvider") private static Object[][] providePrinciples() { return new Object[][]{{CacheMode.REPL_SYNC}, {CacheMode.DIST_SYNC}}; } }
6,925
39.982249
112
java
null
infinispan-main/tasks/scripting/src/test/java/org/infinispan/scripting/SecureScriptingTest.java
package org.infinispan.scripting; import static org.testng.AssertJUnit.assertEquals; import javax.security.auth.Subject; import org.infinispan.Cache; import org.infinispan.configuration.cache.AuthorizationConfigurationBuilder; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.global.GlobalAuthorizationConfigurationBuilder; import org.infinispan.configuration.global.GlobalConfigurationBuilder; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.security.AuthorizationPermission; import org.infinispan.security.Security; import org.infinispan.security.mappers.IdentityRoleMapper; import org.infinispan.tasks.TaskContext; import org.infinispan.test.TestingUtil; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.infinispan.util.concurrent.CompletionStages; import org.testng.annotations.Test; @Test(groups = "functional", testName = "scripting.SecureScriptingTest") public class SecureScriptingTest extends AbstractScriptingTest { static final Subject ADMIN = TestingUtil.makeSubject("admin", ScriptingManager.SCRIPT_MANAGER_ROLE); static final Subject RUNNER = TestingUtil.makeSubject("runner", "runner"); static final Subject PHEIDIPPIDES = TestingUtil.makeSubject("pheidippides", "pheidippides"); static final Subject ACHILLES = TestingUtil.makeSubject("achilles", "achilles"); static final String SECURE_CACHE_NAME = "secured-script-exec"; @Override protected EmbeddedCacheManager createCacheManager() throws Exception { GlobalConfigurationBuilder global = new GlobalConfigurationBuilder(); GlobalAuthorizationConfigurationBuilder globalRoles = global.security().authorization().enable().groupOnlyMapping(false).principalRoleMapper(new IdentityRoleMapper()); ConfigurationBuilder config = TestCacheManagerFactory.getDefaultCacheConfiguration(true); AuthorizationConfigurationBuilder authConfig = config.security().authorization().enable(); globalRoles .role("achilles") .permission(AuthorizationPermission.READ) .permission(AuthorizationPermission.WRITE) .role("runner") .permission(AuthorizationPermission.EXEC) .permission(AuthorizationPermission.READ) .permission(AuthorizationPermission.WRITE) .role("pheidippides") .permission(AuthorizationPermission.EXEC) .permission(AuthorizationPermission.READ) .permission(AuthorizationPermission.WRITE) .role("admin") .permission(AuthorizationPermission.ALL); authConfig.role("runner").role("pheidippides").role("admin"); EmbeddedCacheManager cm = TestCacheManagerFactory.createCacheManager(global, config); Security.doAs(ADMIN, () -> { cm.defineConfiguration(ScriptingTest.CACHE_NAME, cm.getDefaultCacheConfiguration()); cm.getCache(ScriptingTest.CACHE_NAME); cm.defineConfiguration(SecureScriptingTest.SECURE_CACHE_NAME, cm.getDefaultCacheConfiguration()); cm.getCache(SecureScriptingTest.SECURE_CACHE_NAME); cm.defineConfiguration("nonSecuredCache", TestCacheManagerFactory.getDefaultCacheConfiguration(true).build()); }); return cm; } @Override protected String[] getScripts() { return new String[] { "test.js", "testRole.js", "testRoleWithCache.js" }; } @Override protected void setup() throws Exception { Security.doAs(ADMIN, () -> { try { SecureScriptingTest.super.setup(); } catch (Exception e) { throw new RuntimeException(e); } }); } @Override protected void teardown() { Security.doAs(ADMIN, () -> SecureScriptingTest.super.teardown()); } @Override protected void clearContent() { Security.doAs(ADMIN, () -> cacheManager.getCache().clear()); } @Test(expectedExceptions = SecurityException.class) public void testSimpleScript() { String result = CompletionStages.join(scriptingManager.runScript("test.js", new TaskContext().addParameter("a", "a"))); assertEquals("a", result); } public void testSimpleScriptWithEXECPermissions() { String result = Security.doAs(RUNNER, () -> CompletionStages.join(scriptingManager.runScript("test.js", new TaskContext().addParameter("a", "a")))); assertEquals("a", result); } @Test(expectedExceptions = SecurityException.class) public void testSimpleScriptWithEXECPermissionsWrongRole() { String result = Security.doAs(RUNNER, () -> CompletionStages.join(scriptingManager.runScript("testRole.js", new TaskContext().addParameter("a", "a")))); assertEquals("a", result); } public void testSimpleScriptWithEXECPermissionsRightRole() { String result = Security.doAs(PHEIDIPPIDES, () -> CompletionStages.join(scriptingManager.runScript("testRole.js", new TaskContext().addParameter("a", "a")))); assertEquals("a", result); } @Test(expectedExceptions = SecurityException.class) public void testSimpleScriptWithoutEXEC() { Security.doAs(ACHILLES, () -> CompletionStages.join(scriptingManager.runScript("testRole.js", new TaskContext().addParameter("a", "a")))); } @Test(expectedExceptions = SecurityException.class) public void testUploadScriptWithEXECNotManager() { Security.doAs(PHEIDIPPIDES, () -> scriptingManager.addScript("my_script", "1+1")); } @Test(expectedExceptions = SecurityException.class) public void testUploadScriptWithoutEXECNotManager() { Security.doAs(ACHILLES, () -> scriptingManager.addScript("my_script", "1+1")); } @Test(expectedExceptions = SecurityException.class) public void testRemoveScriptWithEXECNotManager() { Security.doAs(PHEIDIPPIDES, () -> scriptingManager.removeScript("test.js")); } @Test(expectedExceptions = SecurityException.class) public void testUploadScriptDirectlyWithEXECNotManager() { Security.doAs(PHEIDIPPIDES, () -> cacheManager.getCache(ScriptingManager.SCRIPT_CACHE).put("my_script", "1+1")); } @Test(expectedExceptions = SecurityException.class) public void testRemoveScriptDirectlyWithEXECNotManager() { Security.doAs(PHEIDIPPIDES, () -> cacheManager.getCache(ScriptingManager.SCRIPT_CACHE).remove("test.js")); } @Test(expectedExceptions = SecurityException.class) public void testClearScriptDirectlyWithEXECNotManager() { Security.doAs(PHEIDIPPIDES, () -> cacheManager.getCache(ScriptingManager.SCRIPT_CACHE).clear()); } public void testScriptOnNonSecuredCache() { Cache<String, String> nonSecCache = cache("nonSecuredCache"); nonSecCache.put("a", "value"); assertEquals("value", nonSecCache.get("a")); String result = Security.doAs(PHEIDIPPIDES, () -> CompletionStages.join(scriptingManager.runScript("testRoleWithCache.js", new TaskContext().addParameter("a", "a").cache(nonSecCache)))); assertEquals("a", result); assertEquals("a", nonSecCache.get("a")); } @Test(expectedExceptions = SecurityException.class) public void testScriptOnNonSecuredCacheWrongRole() { Security.doAs(RUNNER, () -> CompletionStages.join(scriptingManager.runScript("testRoleWithCache.js", new TaskContext().addParameter("a", "a").cache(cache("nonSecuredCache"))))); } }
7,333
43.719512
192
java
null
infinispan-main/tasks/scripting/src/test/java/org/infinispan/scripting/SecureScriptingTaskManagerTest.java
package org.infinispan.scripting; import static org.infinispan.commons.test.CommonsTestingUtil.loadFileAsString; import static org.testng.AssertJUnit.assertEquals; import java.io.InputStream; import java.util.List; import javax.security.auth.Subject; import org.infinispan.Cache; import org.infinispan.configuration.cache.AuthorizationConfigurationBuilder; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.global.GlobalAuthorizationConfigurationBuilder; import org.infinispan.configuration.global.GlobalConfigurationBuilder; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.scripting.impl.ScriptTask; import org.infinispan.security.AuthorizationPermission; import org.infinispan.security.Security; import org.infinispan.security.mappers.IdentityRoleMapper; import org.infinispan.tasks.Task; import org.infinispan.tasks.TaskContext; import org.infinispan.tasks.TaskExecutionMode; import org.infinispan.tasks.TaskManager; import org.infinispan.tasks.spi.TaskEngine; import org.infinispan.test.SingleCacheManagerTest; import org.infinispan.test.TestingUtil; import org.infinispan.test.fwk.CleanupAfterMethod; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.infinispan.util.concurrent.CompletionStages; import org.testng.annotations.Test; /** * Verifying the script execution over task management with secured cache. * * @author amanukya */ @Test(groups = "functional", testName = "scripting.SecureScriptingTaskManagerTest") @CleanupAfterMethod public class SecureScriptingTaskManagerTest extends SingleCacheManagerTest { protected static final String SCRIPT_NAME = "testRole.js"; protected TaskManager taskManager; static final Subject ADMIN = TestingUtil.makeSubject("admin", ScriptingManager.SCRIPT_MANAGER_ROLE); static final Subject RUNNER = TestingUtil.makeSubject("runner", "runner"); static final Subject PHEIDIPPIDES = TestingUtil.makeSubject("pheidippides", "pheidippides"); @Override protected EmbeddedCacheManager createCacheManager() throws Exception { GlobalConfigurationBuilder global = new GlobalConfigurationBuilder(); GlobalAuthorizationConfigurationBuilder globalRoles = global.security().authorization().enable().groupOnlyMapping(false).principalRoleMapper(new IdentityRoleMapper()); ConfigurationBuilder config = TestCacheManagerFactory.getDefaultCacheConfiguration(true); AuthorizationConfigurationBuilder authConfig = config.security().authorization().enable(); globalRoles .role("runner") .permission(AuthorizationPermission.EXEC) .permission(AuthorizationPermission.READ) .permission(AuthorizationPermission.WRITE) .role("pheidippides") .permission(AuthorizationPermission.EXEC) .permission(AuthorizationPermission.READ) .permission(AuthorizationPermission.WRITE) .role("admin") .permission(AuthorizationPermission.ALL); authConfig.role("runner").role("pheidippides").role("admin"); return TestCacheManagerFactory.createCacheManager(global, config); } @Override protected void setup() throws Exception { Security.doAs(ADMIN, () -> { try { SecureScriptingTaskManagerTest.super.setup(); taskManager = cacheManager.getGlobalComponentRegistry().getComponent(TaskManager.class); Cache<String, String> scriptCache = cacheManager.getCache(ScriptingManager.SCRIPT_CACHE); try (InputStream is = this.getClass().getResourceAsStream("/testRole.js")) { String script = loadFileAsString(is); scriptCache.put(SCRIPT_NAME, script); } cacheManager.defineConfiguration(SecureScriptingTest.SECURE_CACHE_NAME, cacheManager.getDefaultCacheConfiguration()); cacheManager.getCache(SecureScriptingTest.SECURE_CACHE_NAME); } catch (Exception e) { throw new RuntimeException(e); } }); } @Override protected void teardown() { Security.doAs(ADMIN, () -> SecureScriptingTaskManagerTest.super.teardown()); } @Override protected void clearContent() { Security.doAs(ADMIN, () -> cacheManager.getCache().clear()); } public void testTask() throws Exception { Security.doAs(PHEIDIPPIDES, () -> { String result = CompletionStages.join(taskManager.runTask(SCRIPT_NAME, new TaskContext().addParameter("a", "a"))); assertEquals("a", result); }); List<Task> tasks = taskManager.getTasks(); assertEquals(1, tasks.size()); ScriptTask scriptTask = (ScriptTask) tasks.get(0); assertEquals(SCRIPT_NAME, scriptTask.getName()); assertEquals(TaskExecutionMode.ONE_NODE, scriptTask.getExecutionMode()); assertEquals("Script", scriptTask.getType()); } public void testAvailableEngines() { List<TaskEngine> engines = taskManager.getEngines(); assertEquals(1, engines.size()); assertEquals("Script", engines.get(0).getName()); } }
5,101
41.516667
173
java
null
infinispan-main/tasks/scripting/src/test/java/org/infinispan/scripting/utils/ScriptingUtils.java
package org.infinispan.scripting.utils; import static org.infinispan.commons.test.CommonsTestingUtil.loadFileAsString; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.stream.Collectors; import org.infinispan.commons.api.BasicCache; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.scripting.ScriptingManager; import org.infinispan.security.Security; /** * Utility class containing general methods for use. */ public class ScriptingUtils { public static ScriptingManager getScriptingManager(EmbeddedCacheManager manager) { return Security.doPrivileged(() -> manager.getGlobalComponentRegistry().getComponent(ScriptingManager.class)); } public static void loadData(BasicCache<String, String> cache, String fileName) throws IOException { try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader( ScriptingUtils.class.getResourceAsStream(fileName)))) { String value = null; int chunkId = 0; while (!(value = bufferedReader.lines().limit(400).collect(Collectors.joining(" "))).isEmpty()) { cache.put(fileName + (chunkId++), value); } } } public static void loadScript(ScriptingManager scriptingManager, String fileName) throws IOException { if (!fileName.startsWith("/")) { fileName = "/" + fileName; } try (InputStream is = ScriptingUtils.class.getResourceAsStream(fileName)) { String script = loadFileAsString(is); scriptingManager.addScript(fileName.replaceAll("\\/", ""), script); } } }
1,727
35.765957
117
java
null
infinispan-main/tasks/scripting/src/main/java/org/infinispan/scripting/ScriptingManager.java
package org.infinispan.scripting; import java.util.Set; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionStage; import org.infinispan.tasks.TaskContext; /** * ScriptingManager. Defines the operations that can be performed on scripts. Scripts are stored in * a dedicated cache. * * @author Tristan Tarrant * @since 7.2 */ public interface ScriptingManager { String SCRIPT_CACHE = "___script_cache"; /** * @deprecated since 12.1. Will be removed in 15.0. Use the CREATE permission instead. */ @Deprecated String SCRIPT_MANAGER_ROLE = "___script_manager"; /** * Adds a new named script. * * @param name * the name of the script. The name should contain an extension identifying its * language * @param script * the source of the script */ void addScript(String name, String script); /** * Removes a script. * * @param name * the name of the script ro remove */ void removeScript(String name); /** * Runs a named script * * @param scriptName The name of the script to run. Use {@link #addScript(String, String)} to add a script * @return a {@link CompletableFuture} which will return the result of the script execution */ <T> CompletionStage<T> runScript(String scriptName); /** * Runs a named script using the specified {@link TaskContext} * * @param scriptName The name of the script to run. Use {@link #addScript(String, String)} to add a script * @param context A {@link TaskContext} within which the script will be executed * @return a {@link CompletableFuture} which will return the result of the script execution */ <T> CompletionStage<T> runScript(String scriptName, TaskContext context); /** * Retrieves the source code of an existing script. * * @param scriptName The name of the script * @return the source code of the script */ String getScript(String scriptName); /** * Retrieves names of all available scripts. * * @return {@link Set<String>} containing names of available scripts. */ Set<String> getScriptNames(); }
2,208
28.065789
109
java
null
infinispan-main/tasks/scripting/src/main/java/org/infinispan/scripting/logging/Messages.java
package org.infinispan.scripting.logging; import org.jboss.logging.annotations.Message; import org.jboss.logging.annotations.MessageBundle; /** * Informational Scripting messages. These start from 21500 so as not to overlap with the logging * messages defined in {@link Log} Messages. * * @author Tristan Tarrant * @since 7.0 */ @MessageBundle(projectCode = "ISPN") public interface Messages { Messages MSG = org.jboss.logging.Messages.getBundle(Messages.class); @Message(value = "Executed script '%s' on cache '%s'", id = 21500) String executedScript(String scriptName, String cacheName); }
611
29.6
97
java
null
infinispan-main/tasks/scripting/src/main/java/org/infinispan/scripting/logging/Log.java
package org.infinispan.scripting.logging; import org.infinispan.commons.CacheException; import org.jboss.logging.BasicLogger; import org.jboss.logging.annotations.Cause; import org.jboss.logging.annotations.Message; import org.jboss.logging.annotations.MessageLogger; /** * Log abstraction for the Scripting module. For this module, message ids ranging from 27501 to * 28000 inclusively have been reserved. * * @author Tristan Tarrant * @since 7.2 */ @MessageLogger(projectCode = "ISPN") public interface Log extends BasicLogger { // @LogMessage(level = ERROR) // @Message(value = "Could not register interpreter MBean", id = 27501) // void jmxRegistrationFailed(); // @LogMessage(level = ERROR) // @Message(value = "Could not unregister interpreter MBean", id = 27502) // void jmxUnregistrationFailed(); @Message(value = "Script execution error", id = 27503) CacheException scriptExecutionError(@Cause Throwable t); @Message(value = "Compiler error for script '%s'", id = 27504) CacheException scriptCompilationException(@Cause Throwable t, String name); @Message(value = "No script named '%s'", id = 27505) CacheException noNamedScript(String name); @Message(value = "Unknown script mode: '%s'", id = 27506) CacheException unknownScriptProperty(String value); @Message(value = "Cannot find an appropriate script engine for '%s'", id = 27507) IllegalArgumentException noScriptEngineForScript(String name); @Message(value = "Script '%s' cannot be invoked directly since it specifies mode '%s'", id = 27508) IllegalArgumentException cannotInvokeScriptDirectly(String scriptName, String property); @Message(value = "Distributed script '%s' invoked without a cache binding", id = 27509) IllegalStateException distributedTaskNeedCacheInBinding(String scriptName); @Message(value = "Cannot find an appropriate script engine for script '%s'", id = 27510) IllegalArgumentException noEngineForScript(String name); @Message(value = "Script parameters must be declared using the array notation, e.g. [a,b,c]", id = 27511) IllegalArgumentException parametersNotArray(); @Message(value = "Scripts can only access named caches", id = 27512) IllegalArgumentException scriptsCanOnlyAccessNamedCaches(); }
2,282
39.052632
108
java
null
infinispan-main/tasks/scripting/src/main/java/org/infinispan/scripting/impl/package-info.java
/** * Scripting Implementation * @api.private */ package org.infinispan.scripting.impl;
91
14.333333
38
java
null
infinispan-main/tasks/scripting/src/main/java/org/infinispan/scripting/impl/PersistenceContextInitializer.java
package org.infinispan.scripting.impl; import org.infinispan.marshall.persistence.impl.PersistenceMarshallerImpl; import org.infinispan.protostream.SerializationContextInitializer; import org.infinispan.protostream.annotations.AutoProtoSchemaBuilder; /** * Interface used to initialise the {@link PersistenceMarshallerImpl}'s {@link org.infinispan.protostream.SerializationContext} * using the specified Pojos, Marshaller implementations and provided .proto schemas. * * @author Ryan Emerson * @since 10.0 */ @AutoProtoSchemaBuilder( dependsOn = org.infinispan.commons.marshall.PersistenceContextInitializer.class, includeClasses = { ExecutionMode.class, ScriptMetadata.class }, schemaFileName = "persistence.scripting.proto", schemaFilePath = "proto/generated", schemaPackageName = "org.infinispan.persistence.scripting", service = false ) interface PersistenceContextInitializer extends SerializationContextInitializer { }
999
36.037037
127
java
null
infinispan-main/tasks/scripting/src/main/java/org/infinispan/scripting/impl/CacheScriptBindings.java
package org.infinispan.scripting.impl; import java.util.Collection; import java.util.Map; import java.util.Set; import javax.script.Bindings; /** * CacheScriptBindings. * * @author Tristan Tarrant * @since 7.2 */ public class CacheScriptBindings implements Bindings { private final Bindings systemBindings; private final Bindings userBindings; public CacheScriptBindings(Bindings systemBindings, Bindings userBindings) { this.systemBindings = systemBindings; this.userBindings = userBindings; } @Override public boolean containsKey(Object key) { return systemBindings.containsKey(key) || userBindings.containsKey(key); } @Override public Object get(Object key) { if (systemBindings.containsKey(key)) { return systemBindings.get(key); } else { return userBindings.get(key); } } @Override public int size() { return userBindings.size() + systemBindings.size(); } @Override public boolean isEmpty() { return userBindings.isEmpty() && systemBindings.isEmpty(); } @Override public boolean containsValue(Object value) { return systemBindings.containsValue(value) || userBindings.containsValue(value); } @Override public void clear() { userBindings.clear(); } @Override public Set<String> keySet() { return userBindings.keySet();//TODO: join with systemBindings } @Override public Collection<Object> values() { return userBindings.values();//TODO: join with systemBindings } @Override public Set<java.util.Map.Entry<String, Object>> entrySet() { return userBindings.entrySet(); //TODO: join with systemBindings } @Override public Object put(String name, Object value) { if (systemBindings.containsKey(name)) { throw new IllegalArgumentException(); } else { return userBindings.put(name, value); } } @Override public void putAll(Map<? extends String, ? extends Object> toMerge) { //FIXME implement me } @Override public Object remove(Object key) { if (systemBindings.containsKey(key)) { throw new IllegalArgumentException(); } else { return userBindings.remove(key); } } }
2,280
22.760417
86
java
null
infinispan-main/tasks/scripting/src/main/java/org/infinispan/scripting/impl/ScriptingInterceptor.java
package org.infinispan.scripting.impl; import org.infinispan.commands.write.ClearCommand; import org.infinispan.commands.write.PutKeyValueCommand; import org.infinispan.commands.write.RemoveCommand; import org.infinispan.commands.write.ReplaceCommand; import org.infinispan.context.InvocationContext; import org.infinispan.factories.annotations.Inject; import org.infinispan.interceptors.BaseCustomAsyncInterceptor; import org.infinispan.scripting.ScriptingManager; /** * Intercepts updates to the script caches, extracts metadata and updates the compiled scripts * accordingly * * @author Tristan Tarrant * @since 7.2 */ public final class ScriptingInterceptor extends BaseCustomAsyncInterceptor { private ScriptingManagerImpl scriptingManager; @Inject public void init(ScriptingManager scriptingManager) { this.scriptingManager = (ScriptingManagerImpl) scriptingManager; } @Override public Object visitPutKeyValueCommand(InvocationContext ctx, PutKeyValueCommand command) throws Throwable { String name = (String) command.getKey(); String script = (String) command.getValue(); command.setMetadata(scriptingManager.compileScript(name, script)); return invokeNext(ctx, command); } @Override public Object visitClearCommand(InvocationContext ctx, ClearCommand command) throws Throwable { scriptingManager.compiledScripts.clear(); return invokeNext(ctx, command); } @Override public Object visitRemoveCommand(InvocationContext ctx, RemoveCommand command) throws Throwable { scriptingManager.compiledScripts.remove(command.getKey()); return invokeNext(ctx, command); } @Override public Object visitReplaceCommand(InvocationContext ctx, ReplaceCommand command) throws Throwable { String name = (String) command.getKey(); String script = (String) command.getNewValue(); command.setMetadata(scriptingManager.compileScript(name, script)); return invokeNext(ctx, command); } }
2,010
34.280702
110
java
null
infinispan-main/tasks/scripting/src/main/java/org/infinispan/scripting/impl/EnvironmentAware.java
package org.infinispan.scripting.impl; import org.infinispan.commons.marshall.Marshaller; import org.infinispan.manager.EmbeddedCacheManager; /** * EnvironmentAware. * * @author Tristan Tarrant * @since 7.2 */ public interface EnvironmentAware { void setEnvironment(EmbeddedCacheManager cacheManager, Marshaller marshaller); }
337
21.533333
81
java
null
infinispan-main/tasks/scripting/src/main/java/org/infinispan/scripting/impl/ScriptingManagerImpl.java
package org.infinispan.scripting.impl; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.concurrent.CompletionStage; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.function.BiFunction; import java.util.function.Function; import javax.script.Bindings; import javax.script.Compilable; import javax.script.CompiledScript; import javax.script.ScriptEngine; import javax.script.ScriptEngineManager; import javax.script.ScriptException; import javax.script.SimpleBindings; import org.infinispan.Cache; import org.infinispan.commons.dataconversion.MediaType; import org.infinispan.configuration.global.GlobalConfiguration; import org.infinispan.container.entries.CacheEntry; 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.manager.EmbeddedCacheManager; import org.infinispan.marshall.core.EncoderRegistry; import org.infinispan.scripting.ScriptingManager; import org.infinispan.scripting.logging.Log; import org.infinispan.scripting.utils.ScriptConversions; import org.infinispan.security.AuthorizationManager; import org.infinispan.security.AuthorizationPermission; import org.infinispan.security.actions.SecurityActions; import org.infinispan.security.impl.Authorizer; import org.infinispan.tasks.TaskContext; import org.infinispan.tasks.TaskManager; import org.infinispan.util.concurrent.BlockingManager; import org.infinispan.util.logging.LogFactory; /** * ScriptingManagerImpl. * * @author Tristan Tarrant * @since 7.2 */ @Scope(Scopes.GLOBAL) public class ScriptingManagerImpl implements ScriptingManager { private static final Log log = LogFactory.getLog(ScriptingManagerImpl.class, Log.class); @Inject EmbeddedCacheManager cacheManager; @Inject TaskManager taskManager; @Inject Authorizer authorizer; @Inject EncoderRegistry encoderRegistry; @Inject GlobalConfiguration globalConfiguration; @Inject BlockingManager blockingManager; private ScriptEngineManager scriptEngineManager; private ConcurrentMap<String, ScriptEngine> scriptEnginesByExtension = new ConcurrentHashMap<>(2); private ConcurrentMap<String, ScriptEngine> scriptEnginesByLanguage = new ConcurrentHashMap<>(2); private Cache<String, String> scriptCache; private ScriptConversions scriptConversions; ConcurrentMap<String, CompiledScript> compiledScripts = new ConcurrentHashMap<>(); private final Function<String, ScriptEngine> getEngineByName = this::getEngineByName; private final Function<String, ScriptEngine> getEngineByExtension = this::getEngineByExtension; public ScriptingManagerImpl() { } @Start public void start() { ClassLoader classLoader = globalConfiguration.classLoader(); this.scriptEngineManager = new ScriptEngineManager(classLoader); taskManager.registerTaskEngine(new ScriptingTaskEngine(this)); scriptConversions = new ScriptConversions(encoderRegistry); } Cache<String, String> getScriptCache() { if (scriptCache == null && cacheManager != null) { scriptCache = SecurityActions.getCache(cacheManager, SCRIPT_CACHE); } return scriptCache; } ScriptMetadata compileScript(String name, String script) { ScriptMetadata metadata = ScriptMetadataParser.parse(name, script); ScriptEngine engine = getEngineForScript(metadata); if (engine instanceof Compilable) { try { CompiledScript compiledScript = ((Compilable) engine).compile(script); compiledScripts.put(name, compiledScript); return metadata; } catch (ScriptException e) { throw log.scriptCompilationException(e, name); } } else { return null; } } @Override public void addScript(String name, String script) { ScriptMetadata metadata = ScriptMetadataParser.parse(name, script); ScriptEngine engine = getEngineForScript(metadata); if (engine == null) { throw log.noScriptEngineForScript(name); } getScriptCache().getAdvancedCache().put(name, script, metadata); } @Override public void removeScript(String name) { if (containsScript(name)) { getScriptCache().remove(name); } else { throw log.noNamedScript(name); } } @Override public String getScript(String name) { if (containsScript(name)) { return SecurityActions.getUnwrappedCache(getScriptCache()).get(name); } else { throw log.noNamedScript(name); } } @Override public Set<String> getScriptNames() { return SecurityActions.getUnwrappedCache(getScriptCache()).keySet(); } boolean containsScript(String taskName) { return SecurityActions.getUnwrappedCache(getScriptCache()).containsKey(taskName); } CompletionStage<Boolean> containsScriptAsync(String taskName) { return SecurityActions.getUnwrappedCache(getScriptCache()).getAsync(taskName) .thenApply(Objects::nonNull); } @Override public <T> CompletionStage<T> runScript(String scriptName) { return runScript(scriptName, new TaskContext()); } @Override public <T> CompletionStage<T> runScript(String scriptName, TaskContext context) { ScriptMetadata metadata = getScriptMetadata(scriptName); if (authorizer != null) { AuthorizationManager authorizationManager = context.getCache().isPresent() ? SecurityActions.getCacheAuthorizationManager(context.getCache().get().getAdvancedCache()) : null; if (authorizationManager != null) { // when the cache is secured authorizationManager.checkPermission(AuthorizationPermission.EXEC, metadata.role().orElse(null)); } else { if (context.getSubject().isPresent()) { authorizer.checkPermission(context.getSubject().get(), AuthorizationPermission.EXEC); } else { authorizer.checkPermission(AuthorizationPermission.EXEC, metadata.role().orElse(null)); } } } MediaType scriptMediaType = metadata.dataType(); MediaType requestMediaType = context.getCache().map(c -> c.getAdvancedCache().getValueDataConversion().getRequestMediaType()).orElse(MediaType.MATCH_ALL); Bindings userBindings = context.getParameters() .map(p -> { Map<String, ?> params = scriptConversions.convertParameters(context); return new SimpleBindings((Map<String, Object>) params); }) .orElse(new SimpleBindings()); SimpleBindings systemBindings = new SimpleBindings(); DataTypedCacheManager dataTypedCacheManager = new DataTypedCacheManager(scriptMediaType, cacheManager, context.getSubject().orElse(null)); systemBindings.put(SystemBindings.CACHE_MANAGER.toString(), dataTypedCacheManager); systemBindings.put(SystemBindings.SCRIPTING_MANAGER.toString(), this); context.getCache().ifPresent(cache -> { if (requestMediaType != null && !requestMediaType.equals(MediaType.MATCH_ALL)) { cache = cache.getAdvancedCache().withMediaType(scriptMediaType, scriptMediaType); } systemBindings.put(SystemBindings.CACHE.toString(), cache); }); context.getMarshaller().ifPresent(marshaller -> { systemBindings.put(SystemBindings.MARSHALLER.toString(), marshaller); }); CacheScriptBindings bindings = new CacheScriptBindings(systemBindings, userBindings); ScriptRunner runner = metadata.mode().getRunner(); return runner.runScript(this, metadata, bindings).thenApply(t -> (T) scriptConversions.convertToRequestType(t, metadata.dataType(), requestMediaType)); } ScriptMetadata getScriptMetadata(String scriptName) { CacheEntry<String, String> scriptEntry = SecurityActions.getCacheEntry(getScriptCache().getAdvancedCache(), scriptName); if (scriptEntry == null) { throw log.noNamedScript(scriptName); } return (ScriptMetadata) scriptEntry.getMetadata(); } <T> CompletionStage<T> execute(ScriptMetadata metadata, Bindings bindings) { return blockingManager.supplyBlocking(() -> { CompiledScript compiled = compiledScripts.get(metadata.name()); try { if (compiled != null) { return (T) compiled.eval(bindings); } else { ScriptEngine engine = getEngineForScript(metadata); String script = getScriptCache().get(metadata.name()); return (T) engine.eval(script, bindings); } } catch (ScriptException e) { throw log.scriptExecutionError(e); } }, "ScriptingManagerImpl - execute"); } ScriptEngine getEngineForScript(ScriptMetadata metadata) { ScriptEngine engine; if (metadata.language().isPresent()) { engine = scriptEnginesByLanguage.computeIfAbsent(metadata.language().get(), getEngineByName); } else { engine = scriptEnginesByExtension.computeIfAbsent(metadata.extension(), getEngineByExtension); } if (engine == null) { throw log.noEngineForScript(metadata.name()); } else { return engine; } } private ScriptEngine getEngineByName(String shortName) { return withClassLoader(ScriptingManagerImpl.class.getClassLoader(), scriptEngineManager, shortName, ScriptEngineManager::getEngineByName); } private ScriptEngine getEngineByExtension(String extension) { return withClassLoader(ScriptingManagerImpl.class.getClassLoader(), scriptEngineManager, extension, ScriptEngineManager::getEngineByExtension); } private static ScriptEngine withClassLoader(ClassLoader cl, ScriptEngineManager manager, String name, BiFunction<ScriptEngineManager, String, ScriptEngine> f) { ClassLoader curr = Thread.currentThread().getContextClassLoader(); try { Thread.currentThread().setContextClassLoader(cl); return f.apply(manager, name); } finally { Thread.currentThread().setContextClassLoader(curr); } } }
10,450
38.142322
160
java
null
infinispan-main/tasks/scripting/src/main/java/org/infinispan/scripting/impl/ScriptMetadata.java
package org.infinispan.scripting.impl; import static org.infinispan.commons.dataconversion.MediaType.APPLICATION_JSON_TYPE; import static org.infinispan.commons.dataconversion.MediaType.APPLICATION_XML_TYPE; import static org.infinispan.commons.dataconversion.MediaType.TEXT_PLAIN_TYPE; import java.util.Collections; import java.util.Optional; import java.util.Set; import java.util.concurrent.TimeUnit; import org.infinispan.commons.dataconversion.MediaType; import org.infinispan.commons.marshall.ProtoStreamTypeIds; import org.infinispan.commons.util.Util; import org.infinispan.container.versioning.EntryVersion; import org.infinispan.metadata.Metadata; import org.infinispan.protostream.annotations.ProtoFactory; import org.infinispan.protostream.annotations.ProtoField; import org.infinispan.protostream.annotations.ProtoTypeId; /** * ScriptMetadata. Holds meta information about a script obtained either implicitly by the script name and extension, or * explicitly by its header. See the "Script metadata" chapter in the User Guide for the syntax and format. * * @author Tristan Tarrant * @since 7.2 */ @ProtoTypeId(ProtoStreamTypeIds.SCRIPT_METADATA) public class ScriptMetadata implements Metadata { private final static Set<String> TEXT_BASED_MEDIA = Util.asSet(TEXT_PLAIN_TYPE, APPLICATION_JSON_TYPE, APPLICATION_XML_TYPE); private final String name; private final ExecutionMode mode; private final String extension; private final Set<String> parameters; private final MediaType dataType; private final String language; private final String role; @ProtoFactory ScriptMetadata(String name, String language, String extension, ExecutionMode mode, Set<String> parameters, String role, MediaType dataType) { this.name = name; this.language = language; this.extension = extension; this.mode = mode; this.parameters = Collections.unmodifiableSet(parameters); this.role = role; this.dataType = dataType; } @ProtoField(number = 1) public String name() { return name; } @ProtoField(number = 2) public ExecutionMode mode() { return mode; } @ProtoField(number = 3) public String extension() { return extension; } @ProtoField(number = 4) public Set<String> parameters() { return parameters; } @ProtoField(number = 5) public MediaType dataType() { if (TEXT_BASED_MEDIA.contains(dataType.getTypeSubtype())) { return dataType.withClassType(String.class); } return dataType; } @ProtoField(number = 6) public Optional<String> language() { return Optional.ofNullable(language); } @ProtoField(number = 7) public Optional<String> role() { return Optional.ofNullable(role); } @Override public long lifespan() { return -1; } @Override public long maxIdle() { return -1; } @Override public EntryVersion version() { return null; } @Override public Builder builder() { return new Builder().name(name).extension(extension).mode(mode).parameters(parameters); } @Override public String toString() { return "ScriptMetadata{" + "name='" + name + '\'' + ", mode=" + mode + ", extension='" + extension + '\'' + ", parameters=" + parameters + ", dataType=" + dataType + ", language=" + language + ", role=" + role + '}'; } public static class Builder implements Metadata.Builder { private String name; private String extension; private String language; private String role; private ExecutionMode mode; private Set<String> parameters = Collections.emptySet(); private MediaType dataType = MediaType.APPLICATION_OBJECT; public ScriptMetadata.Builder name(String name) { this.name = name; return this; } public ScriptMetadata.Builder mode(ExecutionMode mode) { this.mode = mode; return this; } public ScriptMetadata.Builder extension(String extension) { this.extension = extension; return this; } public ScriptMetadata.Builder language(String language) { this.language = language; return this; } public ScriptMetadata.Builder parameters(Set<String> parameters) { this.parameters = parameters; return this; } public ScriptMetadata.Builder role(String role) { this.role = role; return this; } public ScriptMetadata.Builder dataType(MediaType dataType) { this.dataType = dataType; return this; } @Override public ScriptMetadata.Builder lifespan(long time, TimeUnit unit) { return this; } @Override public ScriptMetadata.Builder lifespan(long time) { return this; } @Override public ScriptMetadata.Builder maxIdle(long time, TimeUnit unit) { return this; } @Override public ScriptMetadata.Builder maxIdle(long time) { return this; } @Override public ScriptMetadata.Builder version(EntryVersion version) { return this; } @Override public ScriptMetadata build() { return new ScriptMetadata(name, language, extension, mode, parameters, role, dataType); } @Override public ScriptMetadata.Builder merge(Metadata metadata) { return this; } } }
5,591
25.628571
128
java
null
infinispan-main/tasks/scripting/src/main/java/org/infinispan/scripting/impl/LifecycleCallbacks.java
package org.infinispan.scripting.impl; import static org.infinispan.commons.dataconversion.MediaType.APPLICATION_OBJECT_TYPE; import static org.infinispan.scripting.ScriptingManager.SCRIPT_CACHE; import static org.infinispan.scripting.ScriptingManager.SCRIPT_MANAGER_ROLE; import java.util.EnumSet; import org.infinispan.configuration.cache.AuthorizationConfigurationBuilder; import org.infinispan.configuration.cache.Configuration; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.global.GlobalAuthorizationConfiguration; import org.infinispan.configuration.global.GlobalConfiguration; import org.infinispan.factories.ComponentRegistry; import org.infinispan.factories.GlobalComponentRegistry; import org.infinispan.factories.annotations.InfinispanModule; import org.infinispan.factories.impl.BasicComponentRegistry; import org.infinispan.interceptors.AsyncInterceptorChain; import org.infinispan.interceptors.impl.CacheMgmtInterceptor; import org.infinispan.lifecycle.ModuleLifecycle; import org.infinispan.marshall.protostream.impl.SerializationContextRegistry; import org.infinispan.registry.InternalCacheRegistry; import org.infinispan.scripting.ScriptingManager; import org.infinispan.security.impl.CreatePermissionConfigurationBuilder; /** * LifecycleCallbacks. * * @author Tristan Tarrant * @since 7.2 */ @InfinispanModule(name = "scripting", requiredModules = "core") public class LifecycleCallbacks implements ModuleLifecycle { @Override public void cacheManagerStarting(GlobalComponentRegistry gcr, GlobalConfiguration gc) { ScriptingManagerImpl scriptingManager = new ScriptingManagerImpl(); gcr.registerComponent(scriptingManager, ScriptingManager.class); SerializationContextRegistry ctxRegistry = gcr.getComponent(SerializationContextRegistry.class); ctxRegistry.addContextInitializer(SerializationContextRegistry.MarshallerType.PERSISTENCE, new PersistenceContextInitializerImpl()); BasicComponentRegistry bcr = gcr.getComponent(BasicComponentRegistry.class); InternalCacheRegistry internalCacheRegistry = bcr.getComponent(InternalCacheRegistry.class).wired(); internalCacheRegistry.registerInternalCache(SCRIPT_CACHE, getScriptCacheConfiguration(gc).build(), EnumSet.of(InternalCacheRegistry.Flag.USER, InternalCacheRegistry.Flag.PROTECTED, InternalCacheRegistry.Flag.PERSISTENT, InternalCacheRegistry.Flag.GLOBAL)); } @Override public void cacheManagerStarted(GlobalComponentRegistry gcr) { ScriptingManagerImpl scriptingManager = (ScriptingManagerImpl) gcr.getComponent(ScriptingManager.class); scriptingManager.getScriptCache(); } @Override public void cacheStarting(ComponentRegistry cr, Configuration configuration, String cacheName) { if (SCRIPT_CACHE.equals(cacheName)) { BasicComponentRegistry bcr = cr.getComponent(BasicComponentRegistry.class); ScriptingInterceptor scriptingInterceptor = new ScriptingInterceptor(); bcr.registerComponent(ScriptingInterceptor.class, scriptingInterceptor, true); bcr.addDynamicDependency(AsyncInterceptorChain.class.getName(), ScriptingInterceptor.class.getName()); bcr.getComponent(AsyncInterceptorChain.class).wired() .addInterceptorAfter(scriptingInterceptor, CacheMgmtInterceptor.class); } } private ConfigurationBuilder getScriptCacheConfiguration(GlobalConfiguration globalConfiguration) { ConfigurationBuilder cfg = new ConfigurationBuilder(); cfg.encoding().key().mediaType(APPLICATION_OBJECT_TYPE); cfg.encoding().value().mediaType(APPLICATION_OBJECT_TYPE); GlobalAuthorizationConfiguration globalAuthz = globalConfiguration.security().authorization(); if (globalAuthz.enabled()) { globalAuthz.addRole(GlobalAuthorizationConfiguration.DEFAULT_ROLES.get(SCRIPT_MANAGER_ROLE)); AuthorizationConfigurationBuilder authorization = cfg.security().authorization().enable(); // Copy all global roles globalAuthz.roles().keySet().forEach(role -> authorization.role(role)); // Add a special module which translates permissions cfg.addModule(CreatePermissionConfigurationBuilder.class); } return cfg; } }
4,514
51.5
138
java
null
infinispan-main/tasks/scripting/src/main/java/org/infinispan/scripting/impl/ScriptRunner.java
package org.infinispan.scripting.impl; import java.util.concurrent.CompletionStage; /** * ScriptRunner. * * @author Tristan Tarrant * @since 7.2 */ public interface ScriptRunner { <T> CompletionStage<T> runScript(ScriptingManagerImpl scriptManager, ScriptMetadata metadata, CacheScriptBindings binding); }
316
21.642857
126
java
null
infinispan-main/tasks/scripting/src/main/java/org/infinispan/scripting/impl/LocalRunner.java
package org.infinispan.scripting.impl; import java.util.concurrent.CompletionStage; /** * LocalRunner. * * @author Tristan Tarrant * @since 7.2 */ public class LocalRunner implements ScriptRunner { public static final LocalRunner INSTANCE = new LocalRunner(); private LocalRunner() { } @Override public <T> CompletionStage<T> runScript(ScriptingManagerImpl scriptManager, ScriptMetadata metadata, CacheScriptBindings bindings) { return scriptManager.execute(metadata, bindings); } }
517
21.521739
135
java
null
infinispan-main/tasks/scripting/src/main/java/org/infinispan/scripting/impl/DistributedRunner.java
package org.infinispan.scripting.impl; import java.lang.invoke.MethodHandles; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.CompletableFuture; import org.infinispan.Cache; import org.infinispan.commons.CacheException; import org.infinispan.manager.ClusterExecutor; import org.infinispan.remoting.transport.Address; import org.infinispan.scripting.logging.Log; import org.infinispan.util.function.TriConsumer; import org.infinispan.util.logging.LogFactory; /** * DistributedRunner. * * @author Tristan Tarrant * @since 7.2 */ public class DistributedRunner implements ScriptRunner { private static final Log log = LogFactory.getLog(MethodHandles.lookup().lookupClass(), Log.class); public static final DistributedRunner INSTANCE = new DistributedRunner(); private DistributedRunner() { } @Override public <T> CompletableFuture<T> runScript(ScriptingManagerImpl scriptManager, ScriptMetadata metadata, CacheScriptBindings binding) { Cache<?, ?> masterCacheNode = (Cache<?, ?>) binding.get(SystemBindings.CACHE.toString()); if (masterCacheNode == null) { throw log.distributedTaskNeedCacheInBinding(metadata.name()); } Map<String, Object> ctxParams = extractContextParams(metadata, binding); ClusterExecutor clusterExecutor = masterCacheNode.getCacheManager().executor(); List<T> results = new ArrayList<>(); TriConsumer<Address, T, Throwable> triConsumer = (a, v, t) -> { if (t != null) { throw new CacheException(t); } synchronized (this) { results.add(v); } }; CompletableFuture<Void> future = clusterExecutor.submitConsumer(new DistributedScript<>(masterCacheNode.getName(), metadata, ctxParams), triConsumer); return (CompletableFuture<T>) future.thenApply(ignore -> results); } private Map<String, Object> extractContextParams(ScriptMetadata metadata, CacheScriptBindings binding) { Map<String, Object> params = new HashMap<>(); metadata.parameters().forEach(paramName -> params.put(paramName, binding.get(paramName))); return params; } }
2,210
35.85
156
java
null
infinispan-main/tasks/scripting/src/main/java/org/infinispan/scripting/impl/NullRunner.java
package org.infinispan.scripting.impl; import java.lang.invoke.MethodHandles; import java.util.concurrent.CompletableFuture; import org.infinispan.scripting.logging.Log; import org.infinispan.util.logging.LogFactory; /** * NullRunner. * * @author Tristan Tarrant * @since 7.2 */ public class NullRunner implements ScriptRunner { final static Log log = LogFactory.getLog(MethodHandles.lookup().lookupClass(), Log.class); public static final NullRunner INSTANCE = new NullRunner(); private NullRunner() { } @Override public <T> CompletableFuture<T> runScript(ScriptingManagerImpl scriptManager, ScriptMetadata metadata, CacheScriptBindings binding) { throw log.cannotInvokeScriptDirectly(metadata.name(), metadata.mode().toString()); } }
774
26.678571
136
java
null
infinispan-main/tasks/scripting/src/main/java/org/infinispan/scripting/impl/DistributedScript.java
package org.infinispan.scripting.impl; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.util.HashMap; import java.util.Map; import java.util.concurrent.CompletionException; import java.util.function.Function; import javax.script.Bindings; import javax.script.SimpleBindings; import org.infinispan.AdvancedCache; import org.infinispan.commons.CacheException; import org.infinispan.commons.dataconversion.MediaType; import org.infinispan.commons.marshall.MarshallUtil; import org.infinispan.commons.marshall.SerializeWith; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.scripting.ScriptingManager; import org.infinispan.security.actions.SecurityActions; import org.infinispan.util.concurrent.CompletionStages; /** * DistributedScript. * * @author Tristan Tarrant * @since 7.2 */ @SerializeWith(DistributedScript.Externalizer.class) class DistributedScript<T> implements Function<EmbeddedCacheManager, T> { private final String cacheName; private final ScriptMetadata metadata; private final Map<String, ?> ctxParams; DistributedScript(String cacheName, ScriptMetadata metadata, Map<String, ?> ctxParams) { this.cacheName = cacheName; this.metadata = metadata; this.ctxParams = ctxParams; } @Override public T apply(EmbeddedCacheManager embeddedCacheManager) { ScriptingManagerImpl scriptManager = (ScriptingManagerImpl) SecurityActions.getGlobalComponentRegistry(embeddedCacheManager).getComponent(ScriptingManager.class); Bindings bindings = new SimpleBindings(); MediaType scriptMediaType = metadata.dataType(); DataTypedCacheManager dataTypedCacheManager = new DataTypedCacheManager(scriptMediaType, embeddedCacheManager, null); bindings.put("cacheManager", dataTypedCacheManager); AdvancedCache<?, ?> cache = embeddedCacheManager.getCache(cacheName).getAdvancedCache(); bindings.put("cache", cache.withMediaType(scriptMediaType, scriptMediaType)); ctxParams.forEach(bindings::put); try { return CompletionStages.join(scriptManager.execute(metadata, bindings)); } catch (CompletionException e) { throw new CacheException(e.getCause()); } } /** * Externalizer required for serialization when jboss-marshalling is not present. Eventually {@link DistributedScript} * will be marshalled via protostream annotations once the GlobalMarshaller has been converted and this class can be * removed. */ public static class Externalizer implements org.infinispan.commons.marshall.Externalizer<DistributedScript> { @Override public void writeObject(ObjectOutput output, DistributedScript object) throws IOException { output.writeUTF(object.cacheName); output.writeObject(object.metadata); MarshallUtil.marshallMap(object.ctxParams, output); } @Override public DistributedScript readObject(ObjectInput input) throws IOException, ClassNotFoundException { String cacheName = input.readUTF(); ScriptMetadata metadata = (ScriptMetadata) input.readObject(); Map<String, ?> ctxParams = MarshallUtil.unmarshallMap(input, HashMap::new); return new DistributedScript<>(cacheName, metadata, ctxParams); } } }
3,326
39.084337
168
java
null
infinispan-main/tasks/scripting/src/main/java/org/infinispan/scripting/impl/SystemBindings.java
package org.infinispan.scripting.impl; /** * SystemBindings. * * @author Tristan Tarrant * @since 7.2 */ public enum SystemBindings { CACHE_MANAGER("cacheManager"), CACHE("cache"), SCRIPTING_MANAGER("scriptingManager"), MARSHALLER("marshaller"); private final String bindingName; private SystemBindings(String bindingName) { this.bindingName = bindingName; } @Override public String toString() { return bindingName; } }
462
19.130435
114
java
null
infinispan-main/tasks/scripting/src/main/java/org/infinispan/scripting/impl/DataTypedCacheManager.java
package org.infinispan.scripting.impl; import javax.security.auth.Subject; import org.infinispan.Cache; import org.infinispan.commons.dataconversion.MediaType; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.manager.impl.AbstractDelegatingEmbeddedCacheManager; import org.infinispan.scripting.logging.Log; import org.infinispan.util.logging.LogFactory; public final class DataTypedCacheManager extends AbstractDelegatingEmbeddedCacheManager { private static final Log log = LogFactory.getLog(DataTypedCacheManager.class, Log.class); private final MediaType scriptMediaType; private final Subject subject; DataTypedCacheManager(MediaType scriptMediaType, EmbeddedCacheManager cm, Subject subject) { super(cm); this.scriptMediaType = scriptMediaType; this.subject = subject; } @Override public <K, V> Cache<K, V> getCache() { throw log.scriptsCanOnlyAccessNamedCaches(); } @Override public <K, V> Cache<K, V> getCache(String cacheName) { Cache<K, V> cache = super.getCache(cacheName); return cache.getAdvancedCache().withSubject(subject).withMediaType(scriptMediaType, scriptMediaType); } }
1,193
31.27027
107
java