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/object-filter/src/main/java/org/infinispan/objectfilter/impl/syntax/parser/ReflectionEntityNamesResolver.java
package org.infinispan.objectfilter.impl.syntax.parser; /** * @author anistor@redhat.com * @since 7.0 */ public final class ReflectionEntityNamesResolver implements EntityNameResolver<Class<?>> { private final ClassLoader[] classLoaders; public ReflectionEntityNamesResolver(ClassLoader userClassLoader) { this.classLoaders = new ClassLoader[]{userClassLoader, ClassLoader.getSystemClassLoader(), Thread.currentThread().getContextClassLoader()}; } @Override public Class<?> resolve(String entityName) { for (ClassLoader cl : classLoaders) { try { return cl != null ? Class.forName(entityName, true, cl) : Class.forName(entityName); } catch (ClassNotFoundException | NoClassDefFoundError ex) { // ignore } } return null; } }
824
29.555556
145
java
null
infinispan-main/object-filter/src/main/java/org/infinispan/objectfilter/impl/syntax/parser/ProtobufPropertyHelper.java
package org.infinispan.objectfilter.impl.syntax.parser; import java.math.BigDecimal; import java.math.BigInteger; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.infinispan.objectfilter.impl.logging.Log; import org.infinispan.objectfilter.impl.syntax.IndexedFieldProvider; import org.infinispan.objectfilter.impl.syntax.parser.projection.CacheValuePropertyPath; import org.infinispan.objectfilter.impl.syntax.parser.projection.VersionPropertyPath; import org.infinispan.objectfilter.impl.util.StringHelper; import org.infinispan.protostream.SerializationContext; import org.infinispan.protostream.descriptors.Descriptor; import org.infinispan.protostream.descriptors.EnumDescriptor; import org.infinispan.protostream.descriptors.EnumValueDescriptor; import org.infinispan.protostream.descriptors.FieldDescriptor; import org.infinispan.protostream.descriptors.JavaType; import org.jboss.logging.Logger; /** * @author anistor@redhat.com * @since 7.0 */ public final class ProtobufPropertyHelper extends ObjectPropertyHelper<Descriptor> { private static final Log log = Logger.getMessageLogger(Log.class, ProtobufPropertyHelper.class.getName()); public static final String BIG_INTEGER_COMMON_TYPE = "org.infinispan.protostream.commons.BigInteger"; public static final String BIG_DECIMAL_COMMON_TYPE = "org.infinispan.protostream.commons.BigDecimal"; public static final String VERSION = VersionPropertyPath.VERSION_PROPERTY_NAME; public static final int VERSION_FIELD_ATTRIBUTE_ID = 150_000; public static final int MIN_METADATA_FIELD_ATTRIBUTE_ID = VERSION_FIELD_ATTRIBUTE_ID; public static final String VALUE = CacheValuePropertyPath.VALUE_PROPERTY_NAME; public static final int VALUE_FIELD_ATTRIBUTE_ID = 150_001; private final EntityNameResolver<Descriptor> entityNameResolver; private final IndexedFieldProvider<Descriptor> indexedFieldProvider; public ProtobufPropertyHelper(SerializationContext serializationContext, IndexedFieldProvider<Descriptor> indexedFieldProvider) { this(serializationContext::getMessageDescriptor, indexedFieldProvider); } public ProtobufPropertyHelper(EntityNameResolver<Descriptor> entityNameResolver, IndexedFieldProvider<Descriptor> indexedFieldProvider) { this.entityNameResolver = entityNameResolver; this.indexedFieldProvider = indexedFieldProvider != null ? indexedFieldProvider : super.getIndexedFieldProvider(); } @Override public IndexedFieldProvider<Descriptor> getIndexedFieldProvider() { return indexedFieldProvider; } @Override public Descriptor getEntityMetadata(String typeName) { return entityNameResolver.resolve(typeName); } @Override public List<?> mapPropertyNamePathToFieldIdPath(Descriptor messageDescriptor, String[] propertyPath) { if (propertyPath.length == 1) { if (propertyPath[0].equals(VERSION)) { return Arrays.asList(VERSION_FIELD_ATTRIBUTE_ID); } if (propertyPath[0].equals(VALUE)) { return Arrays.asList(VALUE_FIELD_ATTRIBUTE_ID); } } List<Integer> translatedPath = new ArrayList<>(propertyPath.length); Descriptor md = messageDescriptor; for (String prop : propertyPath) { FieldDescriptor fd = md.findFieldByName(prop); translatedPath.add(fd.getNumber()); if (fd.getJavaType() == JavaType.MESSAGE) { md = fd.getMessageType(); } else { md = null; // iteration is expected to stop here } } return translatedPath; } @Override public Class<?> getPrimitivePropertyType(Descriptor entityType, String[] propertyPath) { if (propertyPath.length == 1) { if (propertyPath[0].equals(VERSION)) { return Long.class; } if (propertyPath[0].equals(VALUE)) { return Object.class; } } FieldDescriptor field = getField(entityType, propertyPath); if (field == null) { throw log.getNoSuchPropertyException(entityType.getFullName(), StringHelper.join(propertyPath)); } switch (field.getJavaType()) { case INT: return Integer.class; case LONG: return Long.class; case FLOAT: return Float.class; case DOUBLE: return Double.class; case BOOLEAN: return Boolean.class; case STRING: return String.class; case BYTE_STRING: return byte[].class; case ENUM: return Integer.class; case MESSAGE: switch (field.getTypeName()) { case BIG_INTEGER_COMMON_TYPE: return BigInteger.class; case BIG_DECIMAL_COMMON_TYPE: return BigDecimal.class; } return null; } return null; } /** * @param entityType * @param propertyPath * @return the field descriptor or null if not found */ private FieldDescriptor getField(Descriptor entityType, String[] propertyPath) { Descriptor messageDescriptor = entityType; int i = 0; for (String p : propertyPath) { FieldDescriptor field = messageDescriptor.findFieldByName(p); if (field == null || ++i == propertyPath.length) { return field; } if (field.getJavaType() == JavaType.MESSAGE) { messageDescriptor = field.getMessageType(); } else { break; } } return null; } @Override public boolean hasProperty(Descriptor entityType, String[] propertyPath) { if (propertyPath.length == 1 && (propertyPath[0].equals(VERSION) || propertyPath[0].equals(VALUE))) { return true; } Descriptor messageDescriptor = entityType; int i = 0; for (String p : propertyPath) { i++; FieldDescriptor field = messageDescriptor.findFieldByName(p); if (field == null) { return false; } if (field.getJavaType() == JavaType.MESSAGE) { messageDescriptor = field.getMessageType(); } else { break; } } return i == propertyPath.length; } @Override public boolean hasEmbeddedProperty(Descriptor entityType, String[] propertyPath) { Descriptor messageDescriptor = entityType; for (String p : propertyPath) { FieldDescriptor field = messageDescriptor.findFieldByName(p); if (field == null) { return false; } if (field.getJavaType() == JavaType.MESSAGE) { messageDescriptor = field.getMessageType(); } else { return false; } } return true; } @Override public boolean isRepeatedProperty(Descriptor entityType, String[] propertyPath) { Descriptor messageDescriptor = entityType; for (String p : propertyPath) { FieldDescriptor field = messageDescriptor.findFieldByName(p); if (field == null) { break; } if (field.isRepeated()) { return true; } if (field.getJavaType() != JavaType.MESSAGE) { break; } messageDescriptor = field.getMessageType(); } return false; } @Override public Object convertToPropertyType(Descriptor entityType, String[] propertyPath, String value) { FieldDescriptor field = getField(entityType, propertyPath); if (field == null) { throw log.getNoSuchPropertyException(entityType.getFullName(), StringHelper.join(propertyPath)); } //todo [anistor] this is just for remote query because enums are handled as integers for historical reasons. if (field.getJavaType() == JavaType.BOOLEAN) { try { return Integer.parseInt(value) != 0; } catch (NumberFormatException e) { return super.convertToPropertyType(entityType, propertyPath, value); } } else if (field.getJavaType() == JavaType.ENUM) { EnumDescriptor enumType = field.getEnumType(); EnumValueDescriptor enumValue; try { enumValue = enumType.findValueByNumber(Integer.parseInt(value)); } catch (NumberFormatException e) { enumValue = enumType.findValueByName(value); } if (enumValue == null) { throw log.getInvalidEnumLiteralException(value, enumType.getFullName()); } return enumValue.getNumber(); } if (field.getJavaType() == JavaType.MESSAGE) { if (field.getTypeName().equals(BIG_INTEGER_COMMON_TYPE)) { return new BigInteger(value); } if (field.getTypeName().equals(BIG_DECIMAL_COMMON_TYPE)) { return new BigDecimal(value); } } return super.convertToPropertyType(entityType, propertyPath, value); } }
8,999
34.573123
140
java
null
infinispan-main/object-filter/src/main/java/org/infinispan/objectfilter/impl/syntax/parser/projection/CacheValuePropertyPath.java
package org.infinispan.objectfilter.impl.syntax.parser.projection; import java.util.Collections; import org.infinispan.objectfilter.impl.ql.PropertyPath; public class CacheValuePropertyPath<TypeDescriptor> extends PropertyPath<TypeDescriptor> { public static final String VALUE_PROPERTY_NAME = "__HSearch_This"; public CacheValuePropertyPath() { super(Collections.singletonList(new PropertyPath.PropertyReference<>(VALUE_PROPERTY_NAME, null, true))); } }
475
30.733333
110
java
null
infinispan-main/object-filter/src/main/java/org/infinispan/objectfilter/impl/syntax/parser/projection/VersionPropertyPath.java
package org.infinispan.objectfilter.impl.syntax.parser.projection; import java.util.Collections; import org.infinispan.objectfilter.impl.ql.PropertyPath; public class VersionPropertyPath<TypeDescriptor> extends PropertyPath<TypeDescriptor> { public static final String VERSION_PROPERTY_NAME = "__ISPN_Version"; public VersionPropertyPath() { super(Collections.singletonList(new PropertyPath.PropertyReference<>(VERSION_PROPERTY_NAME, null, true))); } }
473
30.6
112
java
null
infinispan-main/object-filter/src/main/java/org/infinispan/objectfilter/impl/aggregation/package-info.java
/** * Dealing with grouping and aggregation. * * @author anistor@redhat.com * @since 8.0 * * @api.private */ package org.infinispan.objectfilter.impl.aggregation;
170
16.1
53
java
null
infinispan-main/object-filter/src/main/java/org/infinispan/objectfilter/impl/aggregation/CountAccumulator.java
package org.infinispan.objectfilter.impl.aggregation; /** * Counts the encountered values and returns a {@code Long} greater or equal than 0. Null values are not counted. If * there are no non-null values to which COUNT can be applied, the result of the aggregate function is 0. * * @author anistor@redhat.com * @since 8.0 */ final class CountAccumulator extends FieldAccumulator { CountAccumulator(int inPos, int outPos) { super(inPos, outPos); } @Override public void init(Object[] accRow) { accRow[outPos] = new Counter(); } @Override protected void merge(Object[] accRow, Object value) { if (value instanceof Counter) { ((Counter) accRow[outPos]).add(((Counter) value).getValue()); } else if (value != null) { ((Counter) accRow[outPos]).add(1); } } @Override public void update(Object[] accRow, Object value) { if (value != null) { ((Counter) accRow[outPos]).inc(); } } @Override protected void finish(Object[] accRow) { accRow[outPos] = ((Counter) accRow[outPos]).getValue(); } }
1,114
25.547619
116
java
null
infinispan-main/object-filter/src/main/java/org/infinispan/objectfilter/impl/aggregation/MinAccumulator.java
package org.infinispan.objectfilter.impl.aggregation; /** * An accumulator that returns the smallest of the values it encounters. Values must be {@link Comparable}. The return * has the same type as the field to which it is applied. {@code Null} values are ignored. If there are no remaining * non-null values to compute then the result of the aggregate function is {@code null}. * * @author anistor@redhat.com * @since 8.0 */ final class MinAccumulator extends FieldAccumulator { MinAccumulator(int inPos, int outPos, Class<?> fieldType) { super(inPos, outPos); if (!Comparable.class.isAssignableFrom(fieldType)) { throw new IllegalStateException("Aggregation MIN cannot be applied to property of type " + fieldType.getName()); } } @Override public void update(Object[] accRow, Object value) { if (value != null) { Comparable min = (Comparable) accRow[outPos]; if (min == null || min.compareTo(value) > 0) { accRow[outPos] = value; } } } }
1,044
33.833333
121
java
null
infinispan-main/object-filter/src/main/java/org/infinispan/objectfilter/impl/aggregation/DoubleStat.java
package org.infinispan.objectfilter.impl.aggregation; /** * Computes the sum and average of doubles. The implementation uses compensated summation in order to reduce the error bound in the * numerical sum compared to a simple summation of {@code double} values, similar to the way {@link * java.util.DoubleSummaryStatistics} works. * * @author anistor@redhat.com * @since 8.1 */ final class DoubleStat { private long count; private double sum; private double sumCompensation; // Low order bits of sum private double simpleSum; // Used to compute right sum for non-finite inputs void update(double value) { update(value, 1); } void update(double value, long count) { this.count += count; simpleSum += value; // Incorporate a new double value using Kahan summation / compensated summation. double tmp = value - sumCompensation; double velvel = sum + tmp; // Little wolf of rounding error sumCompensation = (velvel - sum) - tmp; sum = velvel; } /** * Returns the sum of seen values. If any value is a NaN or the sum is at any point a NaN then the average will be * NaN. The average returned can vary depending upon the order in which values are seen. * * @return the sum of values */ Double getSum() { if (count == 0) { return null; } // Better error bounds to add both terms as the final sum double tmp = sum + sumCompensation; if (Double.isNaN(tmp) && Double.isInfinite(simpleSum)) { // If the compensated sum is spuriously NaN from // accumulating one or more same-signed infinite values, // return the correctly-signed infinity stored in simpleSum. return simpleSum; } else { return tmp; } } /** * Returns the arithmetic mean of seen values, or null if no values have been seen. If any value is a NaN or the sum * is at any point a NaN then the average will be NaN. The average returned can vary depending upon the order in * which values are seen. * * @return the arithmetic mean of values, or null if none */ Double getAvg() { return count == 0 ? null : getSum() / count; } long getCount() { return count; } }
2,283
31.169014
131
java
null
infinispan-main/object-filter/src/main/java/org/infinispan/objectfilter/impl/aggregation/MaxAccumulator.java
package org.infinispan.objectfilter.impl.aggregation; /** * An accumulator that returns the greatest of the values it encounters. Values must be {@link Comparable}. The return * has the same type as the field to which it is applied. {@code Null} values are ignored. If there are no remaining * non-null values to compute then the result of the aggregate function is {@code null}. * * @author anistor@redhat.com * @since 8.0 */ final class MaxAccumulator extends FieldAccumulator { MaxAccumulator(int inPos, int outPos, Class<?> fieldType) { super(inPos, outPos); if (!Comparable.class.isAssignableFrom(fieldType)) { throw new IllegalStateException("Aggregation MAX cannot be applied to property of type " + fieldType.getName()); } } @Override public void update(Object[] accRow, Object value) { if (value != null) { Comparable max = (Comparable) accRow[outPos]; if (max == null || max.compareTo(value) < 0) { accRow[outPos] = value; } } } }
1,044
33.833333
121
java
null
infinispan-main/object-filter/src/main/java/org/infinispan/objectfilter/impl/aggregation/FieldAccumulator.java
package org.infinispan.objectfilter.impl.aggregation; import org.infinispan.objectfilter.impl.ql.AggregationFunction; /** * An accumulator is a stateless object that operates on row data. * * @author anistor@redhat.com * @since 8.0 */ public abstract class FieldAccumulator { /** * Input column. */ protected final int inPos; /** * Output column. */ protected final int outPos; protected FieldAccumulator(int inPos, int outPos) { this.inPos = inPos; this.outPos = outPos; } public static void init(Object[] accRow, FieldAccumulator[] accumulators) { for (FieldAccumulator acc : accumulators) { acc.init(accRow); } } public static void update(Object[] srcRow, Object[] accRow, FieldAccumulator[] accumulators) { for (FieldAccumulator acc : accumulators) { acc.update(accRow, srcRow[acc.inPos]); } } public static void merge(Object[] srcRow, Object[] accRow, FieldAccumulator[] acc) { for (FieldAccumulator a : acc) { a.merge(accRow, srcRow[a.inPos]); } } public static void finish(Object[] accRow, FieldAccumulator[] accumulators) { for (FieldAccumulator acc : accumulators) { acc.finish(accRow); } } public void init(Object[] accRow) { } public abstract void update(Object[] accRow, Object value); protected void merge(Object[] accRow, Object value) { update(accRow, value); } protected void finish(Object[] accRow) { } public static FieldAccumulator makeAccumulator(AggregationFunction aggregationType, int inColumn, int outColumn, Class<?> propertyType) { switch (aggregationType) { case SUM: return new SumAccumulator(inColumn, outColumn, propertyType); case AVG: return new AvgAccumulator(inColumn, outColumn, propertyType); case MIN: return new MinAccumulator(inColumn, outColumn, propertyType); case MAX: return new MaxAccumulator(inColumn, outColumn, propertyType); case COUNT: return new CountAccumulator(inColumn, outColumn); default: throw new IllegalArgumentException("Aggregation " + aggregationType.name() + " is not supported"); } } public static Class<?> getOutputType(AggregationFunction aggregationType, Class<?> propertyType) { if (aggregationType == AggregationFunction.AVG) { return Double.class; } else if (aggregationType == AggregationFunction.COUNT) { return Long.class; } else if (aggregationType == AggregationFunction.SUM) { return SumAccumulator.getOutputType(propertyType); } return propertyType; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || o.getClass() != getClass()) return false; FieldAccumulator other = (FieldAccumulator) o; return inPos == other.inPos && outPos == other.outPos; } @Override public int hashCode() { return 31 * inPos + outPos; } }
3,087
28.409524
140
java
null
infinispan-main/object-filter/src/main/java/org/infinispan/objectfilter/impl/aggregation/RowGrouper.java
package org.infinispan.objectfilter.impl.aggregation; import java.util.Arrays; import java.util.Collections; import java.util.Iterator; import java.util.LinkedHashMap; /** * Groups rows by their grouping fields and computes aggregates. * * @author anistor@redhat.com * @since 8.0 */ public final class RowGrouper { /** * The number of columns at the beginning of the row that are used for grouping. */ private final int noOfGroupingColumns; private final FieldAccumulator[] accumulators; private final boolean twoPhaseAcc; private final int inRowLength; private final int outRowLength; /** * Store the a row for each group. This is used only if we have at least one grouping column. */ private final LinkedHashMap<GroupRowKey, Object[]> groups; /** * The single row used for computing global aggregations (the are no grouping columns defined). */ private final Object[] globalGroup; private final class GroupRowKey { private final Object[] row; GroupRowKey(Object[] row) { this.row = row; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; GroupRowKey other = (GroupRowKey) o; int n = noOfGroupingColumns > 0 ? noOfGroupingColumns : row.length; for (int i = 0; i < n; i++) { Object o1 = row[i]; Object o2 = other.row[i]; if (!(o1 == null ? o2 == null : o1.equals(o2))) { return false; } } return true; } @Override public int hashCode() { int result = 1; int n = noOfGroupingColumns > 0 ? noOfGroupingColumns : row.length; for (int i = 0; i < n; i++) { Object e = row[i]; result = 31 * result + (e == null ? 0 : e.hashCode()); } return result; } } /** * noOfGroupingColumns and accumulators must not have overlapping indices. */ public RowGrouper(int noOfGroupingColumns, FieldAccumulator[] accumulators, boolean twoPhaseAcc) { this.noOfGroupingColumns = noOfGroupingColumns; this.accumulators = accumulators != null && accumulators.length != 0 ? accumulators : null; this.twoPhaseAcc = twoPhaseAcc; inRowLength = findInRowLength(noOfGroupingColumns, accumulators); if (inRowLength == 0) { throw new IllegalArgumentException("Must have at least one grouping or aggregated column"); } outRowLength = noOfGroupingColumns + (accumulators != null ? accumulators.length : 0); if (noOfGroupingColumns > 0) { groups = new LinkedHashMap<>(); globalGroup = null; } else { groups = null; // we have global aggregations only globalGroup = new Object[outRowLength]; for (FieldAccumulator acc : accumulators) { acc.init(globalGroup); } } } private int findInRowLength(int noOfGroupingColumns, FieldAccumulator[] accumulators) { int l = noOfGroupingColumns; if (accumulators != null) { for (FieldAccumulator acc : accumulators) { if (acc.inPos + 1 > l) { l = acc.inPos + 1; } } } return l; } public void addRow(Object[] row) { if (row.length != inRowLength) { throw new IllegalArgumentException("Row length mismatch"); } if (noOfGroupingColumns > 0) { // compute grouping and aggregations GroupRowKey groupRowKey = new GroupRowKey(row); Object[] existingGroup = groups.get(groupRowKey); if (existingGroup == null) { existingGroup = new Object[outRowLength]; System.arraycopy(row, 0, existingGroup, 0, noOfGroupingColumns); if (accumulators != null) { FieldAccumulator.init(existingGroup, accumulators); for (FieldAccumulator acc : accumulators) { acc.init(existingGroup); } } groups.put(groupRowKey, existingGroup); } if (accumulators != null) { if (twoPhaseAcc) { FieldAccumulator.merge(row, existingGroup, accumulators); } else { FieldAccumulator.update(row, existingGroup, accumulators); } } } else { // we have global aggregations only if (twoPhaseAcc) { FieldAccumulator.merge(row, globalGroup, accumulators); } else { FieldAccumulator.update(row, globalGroup, accumulators); } } } public Iterator<Object[]> finish() { if (groups != null) { return new Iterator<Object[]>() { private final Iterator<Object[]> iterator = groups.values().iterator(); @Override public boolean hasNext() { return iterator.hasNext(); } @Override public Object[] next() { Object[] row = iterator.next(); if (accumulators != null) { FieldAccumulator.finish(row, accumulators); } return row; } }; } else { FieldAccumulator.finish(globalGroup, accumulators); return Collections.singleton(globalGroup).iterator(); } } @Override public String toString() { return "RowGrouper{" + "noOfGroupingColumns=" + noOfGroupingColumns + ", inRowLength=" + inRowLength + ", outRowLength=" + outRowLength + ", accumulators=" + Arrays.toString(accumulators) + ", number of groups=" + groups.size() + '}'; } }
5,812
30.421622
101
java
null
infinispan-main/object-filter/src/main/java/org/infinispan/objectfilter/impl/aggregation/Counter.java
package org.infinispan.objectfilter.impl.aggregation; /** * @author anistor@redhat.com * @since 8.2 */ public final class Counter { private long counter; public Counter() { } public void inc() { counter++; } public void add(long val) { counter += val; } public long getValue() { return counter; } @Override public String toString() { return "Counter(" + counter + ')'; } }
443
13.322581
53
java
null
infinispan-main/object-filter/src/main/java/org/infinispan/objectfilter/impl/aggregation/SumAccumulator.java
package org.infinispan.objectfilter.impl.aggregation; import java.math.BigDecimal; import java.math.BigInteger; /** * Computes the sum of {@link Number}s. Returns {@link Long} when applied to fields of integral types (other than * BigInteger); Double when applied to state-fields of floating point types; BigInteger when applied to state-fields of * type BigInteger; and BigDecimal when applied to state-fields of type BigDecimal. Nulls are excluded from the * computation. If there are no remaining non-null values to which the aggregate function can be applied, the result of * the aggregate function is {@code null}. * * @author anistor@redhat.com * @since 8.0 */ final class SumAccumulator extends FieldAccumulator { private final Class<? extends Number> fieldType; SumAccumulator(int inPos, int outPos, Class<?> fieldType) { super(inPos, outPos); if (!Number.class.isAssignableFrom(fieldType)) { throw new IllegalStateException("Aggregation SUM cannot be applied to property of type " + fieldType.getName()); } this.fieldType = (Class<? extends Number>) fieldType; } @Override public void init(Object[] accRow) { if (fieldType == Double.class || fieldType == Float.class) { accRow[outPos] = new DoubleStat(); } } @Override public void update(Object[] accRow, Object val) { if (val != null) { Number value = (Number) val; if (fieldType == Double.class || fieldType == Float.class) { ((DoubleStat) accRow[outPos]).update(value.doubleValue()); } else if (fieldType == Long.class || fieldType == Integer.class || fieldType == Byte.class || fieldType == Short.class) { value = value.longValue(); Number sum = (Number) accRow[outPos]; if (sum != null) { if (fieldType == Long.class) { value = sum.longValue() + value.longValue(); } else if (fieldType == BigInteger.class) { value = ((BigInteger) sum).add((BigInteger) value); } else if (fieldType == BigDecimal.class) { value = ((BigDecimal) sum).add((BigDecimal) value); } else { // byte, short, int value = sum.intValue() + value.intValue(); } } accRow[outPos] = value; } } } @Override protected void merge(Object[] accRow, Object value) { if (value instanceof DoubleStat) { value = ((DoubleStat) value).getSum(); } else if (value instanceof Counter) { value = ((Counter) value).getValue(); } update(accRow, value); } @Override protected void finish(Object[] accRow) { if (fieldType == Double.class || fieldType == Float.class) { accRow[outPos] = ((DoubleStat) accRow[outPos]).getSum(); } } /** * Determine the output type of this accumulator. */ static Class<?> getOutputType(Class<?> fieldType) { if (!Number.class.isAssignableFrom(fieldType)) { throw new IllegalStateException("Aggregation SUM cannot be applied to property of type " + fieldType.getName()); } if (fieldType == Double.class || fieldType == Float.class) { return Double.class; } if (fieldType == Long.class || fieldType == Integer.class || fieldType == Byte.class || fieldType == Short.class) { return Long.class; } return fieldType; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || o.getClass() != getClass()) return false; SumAccumulator other = (SumAccumulator) o; return inPos == other.inPos && outPos == other.outPos && fieldType == other.fieldType; } @Override public int hashCode() { return 31 * super.hashCode() + fieldType.hashCode(); } }
3,910
35.551402
131
java
null
infinispan-main/object-filter/src/main/java/org/infinispan/objectfilter/impl/aggregation/AvgAccumulator.java
package org.infinispan.objectfilter.impl.aggregation; import org.infinispan.objectfilter.impl.logging.Log; import org.jboss.logging.Logger; /** * Computes the average of {@link Number}s. The output type is always a {@link Double}. Nulls are excluded from the * computation. If there are no remaining non-null values to which the aggregate function can be applied, the result of * the aggregate function is {@code null}. * <p> * The implementation uses compensated summation in order to reduce the error bound in the numerical sum compared to a * simple summation of {@code double} values similar to the way {@link java.util.DoubleSummaryStatistics} works. * * @author anistor@redhat.com * @since 8.0 */ final class AvgAccumulator extends FieldAccumulator { private static final Log log = Logger.getMessageLogger(Log.class, AvgAccumulator.class.getName()); AvgAccumulator(int inPos, int outPos, Class<?> fieldType) { super(inPos, outPos); if (!Number.class.isAssignableFrom(fieldType)) { throw log.getAVGCannotBeAppliedToPropertyOfType(fieldType.getName()); } } @Override public void init(Object[] accRow) { accRow[outPos] = new DoubleStat(); } @Override public void update(Object[] accRow, Object value) { if (value != null) { ((DoubleStat) accRow[outPos]).update(((Number) value).doubleValue()); } } @Override protected void merge(Object[] accRow, Object value) { if (value instanceof DoubleStat) { DoubleStat avgVal = (DoubleStat) value; if (avgVal.getCount() > 0) { ((DoubleStat) accRow[outPos]).update(avgVal.getSum(), avgVal.getCount()); } } else { update(accRow, value); } } @Override protected void finish(Object[] accRow) { accRow[outPos] = ((DoubleStat) accRow[outPos]).getAvg(); } }
1,882
32.035088
119
java
null
infinispan-main/object-filter/src/main/java/org/infinispan/objectfilter/impl/predicateindex/Condition.java
package org.infinispan.objectfilter.impl.predicateindex; /** * @author anistor@redhat.com * @since 7.0 */ @FunctionalInterface interface Condition<AttributeDomain> { boolean match(AttributeDomain attributeValue); }
223
17.666667
56
java
null
infinispan-main/object-filter/src/main/java/org/infinispan/objectfilter/impl/predicateindex/Projections.java
package org.infinispan.objectfilter.impl.predicateindex; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.infinispan.objectfilter.impl.FilterSubscriptionImpl; /** * The projections of an attribute across multiple filters. * * @author anistor@redhat.com * @since 7.0 */ final class Projections { private List<ProjectionSubscription> subscriptions = new ArrayList<>(); private static class ProjectionSubscription { // the filter using this attribute subscription private final FilterSubscriptionImpl filterSubscription; // the position of the attribute in the projection private final int position; private ProjectionSubscription(FilterSubscriptionImpl filterSubscription, int position) { this.filterSubscription = filterSubscription; this.position = position; } } void addProjection(FilterSubscriptionImpl filterSubscription, int position) { subscriptions.add(new ProjectionSubscription(filterSubscription, position)); } void removeProjections(FilterSubscriptionImpl filterSubscription) { Iterator<ProjectionSubscription> it = subscriptions.iterator(); while (it.hasNext()) { ProjectionSubscription s = it.next(); if (s.filterSubscription == filterSubscription) { it.remove(); } } } void processProjections(MatcherEvalContext<?, ?, ?> ctx, Object attributeValue) { for (int i = 0; i < subscriptions.size(); i++) { ProjectionSubscription s = subscriptions.get(i); FilterEvalContext c = ctx.getFilterEvalContext(s.filterSubscription); c.processProjection(s.position, attributeValue); } } boolean hasProjections() { return !subscriptions.isEmpty(); } }
1,801
29.542373
95
java
null
infinispan-main/object-filter/src/main/java/org/infinispan/objectfilter/impl/predicateindex/IntervalCondition.java
package org.infinispan.objectfilter.impl.predicateindex; import org.infinispan.objectfilter.impl.util.Interval; /** * @author anistor@redhat.com * @since 7.0 */ public final class IntervalCondition<AttributeDomain extends Comparable<AttributeDomain>> implements Condition<AttributeDomain> { private final Interval<AttributeDomain> interval; public IntervalCondition(Interval<AttributeDomain> interval) { this.interval = interval; } @Override public boolean match(AttributeDomain attributeValue) { return attributeValue != null && interval.contains(attributeValue); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null || getClass() != obj.getClass()) return false; IntervalCondition other = (IntervalCondition) obj; return interval.equals(other.interval); } @Override public int hashCode() { return interval.hashCode(); } @Override public String toString() { return "IntervalCondition(" + interval + ')'; } }
1,055
24.756098
129
java
null
infinispan-main/object-filter/src/main/java/org/infinispan/objectfilter/impl/predicateindex/IsNullCondition.java
package org.infinispan.objectfilter.impl.predicateindex; /** * @author anistor@redhat.com * @since 7.0 */ public final class IsNullCondition implements Condition<Object> { public static final IsNullCondition INSTANCE = new IsNullCondition(); private IsNullCondition() { } @Override public boolean match(Object attributeValue) { return attributeValue == null; } @Override public String toString() { return "IsNullCondition"; } }
475
18.833333
72
java
null
infinispan-main/object-filter/src/main/java/org/infinispan/objectfilter/impl/predicateindex/package-info.java
/** * An efficient index for boolean expressions. * * @author anistor@redhat.com * @since 7.0 * * @api.private */ package org.infinispan.objectfilter.impl.predicateindex;
178
16.9
56
java
null
infinispan-main/object-filter/src/main/java/org/infinispan/objectfilter/impl/predicateindex/EqualsCondition.java
package org.infinispan.objectfilter.impl.predicateindex; /** * @author anistor@redhat.com * @since 7.0 */ public final class EqualsCondition<AttributeDomain> implements Condition<AttributeDomain> { private final AttributeDomain value; public EqualsCondition(AttributeDomain value) { if (value == null) { throw new IllegalArgumentException("value cannot be null"); } this.value = value; } @Override public boolean match(Object attributeValue) { return value.equals(attributeValue); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null || getClass() != obj.getClass()) return false; EqualsCondition other = (EqualsCondition) obj; return value.equals(other.value); } @Override public int hashCode() { return value.hashCode(); } @Override public String toString() { return "EqualsCondition(" + value + ')'; } }
973
22.190476
91
java
null
infinispan-main/object-filter/src/main/java/org/infinispan/objectfilter/impl/predicateindex/PredicateIndex.java
package org.infinispan.objectfilter.impl.predicateindex; import java.util.List; import org.infinispan.objectfilter.impl.FilterSubscriptionImpl; import org.infinispan.objectfilter.impl.MetadataAdapter; import org.infinispan.objectfilter.impl.predicateindex.be.PredicateNode; /** * Keeps track of all predicates and all projections from all filters of an entity type and determines efficiently which * predicates match a given entity instance. There is a single instance at most of this for class per each entity type. * The predicates are stored in an index-like structure to allow fast matching and are reference counted in order to * allow sharing of predicates between filters rather than duplicating them. * * @param <AttributeMetadata> is the type of the metadata attached to an AttributeNode * @param <AttributeId> is the type used to represent attribute IDs (usually String or Integer) * @author anistor@redhat.com * @since 7.0 */ public final class PredicateIndex<AttributeMetadata, AttributeId extends Comparable<AttributeId>> { private final AttributeNode<AttributeMetadata, AttributeId> root; public PredicateIndex(MetadataAdapter<?, AttributeMetadata, AttributeId> metadataAdapter) { root = new RootNode<>(metadataAdapter); } public AttributeNode<AttributeMetadata, AttributeId> getRoot() { return root; } public Predicates.Subscription<AttributeId> addSubscriptionForPredicate(PredicateNode<AttributeId> predicateNode, FilterSubscriptionImpl filterSubscription) { AttributeNode<AttributeMetadata, AttributeId> attributeNode = addAttributeNodeByPath(predicateNode.getAttributePath()); predicateNode.getPredicate().attributeNode = attributeNode; return attributeNode.addPredicateSubscription(predicateNode, filterSubscription); } public void removeSubscriptionForPredicate(Predicates.Subscription<AttributeId> subscription) { AttributeNode<AttributeMetadata, AttributeId> current = getAttributeNodeByPath(subscription.getPredicateNode().getAttributePath()); current.removePredicateSubscription(subscription); // remove the nodes that no longer have a purpose while (current != root) { if (current.getNumChildren() > 0 || current.hasPredicates() || current.hasProjections()) { break; } AttributeId childId = current.getAttribute(); current = current.getParent(); current.removeChild(childId); } } private AttributeNode<AttributeMetadata, AttributeId> getAttributeNodeByPath(List<AttributeId> attributePath) { AttributeNode<AttributeMetadata, AttributeId> node = root; for (AttributeId attribute : attributePath) { node = node.getChild(attribute); if (node == null) { throw new IllegalStateException("Child not found : " + attribute); } } return node; } private AttributeNode<AttributeMetadata, AttributeId> addAttributeNodeByPath(List<AttributeId> attributePath) { AttributeNode<AttributeMetadata, AttributeId> node = root; for (AttributeId attribute : attributePath) { node = node.addChild(attribute); } return node; } public int addProjections(FilterSubscriptionImpl<?, AttributeMetadata, AttributeId> filterSubscription, List<List<AttributeId>> projection, int i) { for (List<AttributeId> projectionPath : projection) { AttributeNode node = addAttributeNodeByPath(projectionPath); node.addProjection(filterSubscription, i++); } return i; } public void removeProjections(FilterSubscriptionImpl<?, AttributeMetadata, AttributeId> filterSubscription, List<List<AttributeId>> projection) { for (List<AttributeId> projectionPath : projection) { AttributeNode node = getAttributeNodeByPath(projectionPath); node.removeProjections(filterSubscription); } } }
3,923
43.590909
161
java
null
infinispan-main/object-filter/src/main/java/org/infinispan/objectfilter/impl/predicateindex/FilterEvalContext.java
package org.infinispan.objectfilter.impl.predicateindex; import java.util.Arrays; import org.infinispan.objectfilter.impl.FilterSubscriptionImpl; import org.infinispan.objectfilter.impl.aggregation.FieldAccumulator; import org.infinispan.objectfilter.impl.predicateindex.be.BENode; import org.infinispan.objectfilter.impl.predicateindex.be.BETree; /** * @author anistor@redhat.com * @since 7.0 */ public final class FilterEvalContext { private static final int[] FALSE_TREE = {BETree.EXPR_FALSE}; public final BETree beTree; public final int[] treeCounters; public final MatcherEvalContext<?, ?, ?> matcherContext; private final Object[] projection; private final Comparable[] sortProjection; public FieldAccumulator[] acc; public FilterEvalContext(MatcherEvalContext<?, ?, ?> matcherContext, FilterSubscriptionImpl filterSubscription) { this.matcherContext = matcherContext; this.beTree = filterSubscription.getBETree(); // check if event type is matching if (checkEventType(matcherContext.getEventType(), filterSubscription.getEventTypes())) { int[] childCounters = beTree.getChildCounters(); this.treeCounters = Arrays.copyOf(childCounters, childCounters.length); } else { this.treeCounters = FALSE_TREE; for (BENode node : beTree.getNodes()) { node.suspendSubscription(this); } } projection = filterSubscription.getProjection() != null ? new Object[filterSubscription.getProjection().length] : null; sortProjection = filterSubscription.getSortFields() != null ? new Comparable[filterSubscription.getSortFields().length] : null; } private boolean checkEventType(Object eventType, Object[] eventTypes) { if (eventTypes == null) { return true; } if (eventType == null) { return false; } for (Object t : eventTypes) { if (eventType.equals(t)) { return true; } } return false; } /** * Returns the result of the filter. This method should be called only after the evaluation of all predicates (except * the ones that were suspended). * * @return {@code true} if the filter matches the given input, {@code false} otherwise */ public boolean isMatching() { return treeCounters[0] == BETree.EXPR_TRUE; } public Object[] getProjection() { return projection; } public Comparable[] getSortProjection() { return sortProjection; } void processProjection(int position, Object value) { Object[] projection = this.projection; if (projection == null) { projection = this.sortProjection; } else { if (position >= projection.length) { position -= projection.length; projection = this.sortProjection; } } if (acc != null) { FieldAccumulator a = acc[position]; if (a != null) { a.update(projection, value); return; } } // if this is a repeated attribute and no accumulator is used then keep the first occurrence in order to be consistent with the Lucene based implementation if (projection[position] == null) { projection[position] = value; } } }
3,308
30.514286
161
java
null
infinispan-main/object-filter/src/main/java/org/infinispan/objectfilter/impl/predicateindex/AttributeNode.java
package org.infinispan.objectfilter.impl.predicateindex; import java.util.Collection; import java.util.HashMap; import java.util.Map; import org.infinispan.objectfilter.impl.FilterSubscriptionImpl; import org.infinispan.objectfilter.impl.MetadataAdapter; import org.infinispan.objectfilter.impl.predicateindex.be.PredicateNode; /** * An attribute node represents a single attribute and keeps track of subscribed predicates and projections. * * @author anistor@redhat.com * @since 7.0 */ public class AttributeNode<AttributeMetadata, AttributeId extends Comparable<AttributeId>> { public static final Object DUMMY_VALUE = new Object(); private static final AttributeNode[] EMPTY_CHILDREN = new AttributeNode[0]; // this is never null, except for the root node private final AttributeId attribute; // property metadata for an intermediate or leaf node. This is never null, except for the root node private final AttributeMetadata metadata; private final MetadataAdapter<?, AttributeMetadata, AttributeId> metadataAdapter; // this is never null, except for the root node private final AttributeNode<AttributeMetadata, AttributeId> parent; /** * Child attributes. */ private Map<AttributeId, AttributeNode<AttributeMetadata, AttributeId>> children; private AttributeNode<AttributeMetadata, AttributeId>[] childrenArray = EMPTY_CHILDREN; /** * Root node must not have predicates. This field is always null for root node. Non-leaf nodes can only have * 'isEmpty' or 'isNull' predicates. */ private Predicates predicates; /** * The list of all subscribed projections. This field is always null for root node. Only leaf nodes can have * projections. */ private Projections projections; /** * Constructor used only for the root node. */ protected AttributeNode(MetadataAdapter<?, AttributeMetadata, AttributeId> metadataAdapter) { this.attribute = null; this.parent = null; this.metadataAdapter = metadataAdapter; this.metadata = null; } private AttributeNode(AttributeId attribute, AttributeNode<AttributeMetadata, AttributeId> parent) { this.attribute = attribute; this.parent = parent; metadataAdapter = parent.metadataAdapter; metadata = metadataAdapter.makeChildAttributeMetadata(parent.metadata, attribute); } public AttributeId getAttribute() { return attribute; } public AttributeMetadata getMetadata() { return metadata; } public AttributeNode<AttributeMetadata, AttributeId> getParent() { return parent; } public AttributeNode<AttributeMetadata, AttributeId>[] getChildren() { return childrenArray; } /** * @param attribute * @return the child or null if not found */ public AttributeNode<AttributeMetadata, AttributeId> getChild(AttributeId attribute) { if (children != null) { return children.get(attribute); } return null; } public int getNumChildren() { return childrenArray.length; } public boolean hasPredicates() { return predicates != null && !predicates.isEmpty(); } public boolean hasProjections() { return projections != null && projections.hasProjections(); } public void processValue(Object attributeValue, MatcherEvalContext<?, AttributeMetadata, AttributeId> ctx) { if (projections != null && attributeValue != DUMMY_VALUE) { projections.processProjections(ctx, attributeValue); } if (predicates != null) { predicates.notifyMatchingSubscribers(ctx, attributeValue); } } /** * Add a child node. If the child already exists it just increments its usage counter and returns the existing * child. * * @param attribute * @return the added or existing child */ public AttributeNode<AttributeMetadata, AttributeId> addChild(AttributeId attribute) { AttributeNode<AttributeMetadata, AttributeId> child; if (children == null) { children = new HashMap<>(); child = new AttributeNode<>(attribute, this); children.put(attribute, child); rebuildChildrenArray(); } else { child = children.get(attribute); if (child == null) { child = new AttributeNode<>(attribute, this); children.put(attribute, child); rebuildChildrenArray(); } } return child; } /** * Decrement the usage counter of a child node and remove it if no usages remain. The removal works recursively up * the path to the root. * * @param attribute the attribute of the child to be removed */ public void removeChild(AttributeId attribute) { if (children == null) { throw new IllegalArgumentException("No child found : " + attribute); } AttributeNode<AttributeMetadata, AttributeId> child = children.get(attribute); if (child == null) { throw new IllegalArgumentException("No child found : " + attribute); } children.remove(attribute); rebuildChildrenArray(); } private void rebuildChildrenArray() { Collection<AttributeNode<AttributeMetadata, AttributeId>> childrenCollection = children.values(); childrenArray = childrenCollection.toArray(new AttributeNode[childrenCollection.size()]); } public Predicates.Subscription<AttributeId> addPredicateSubscription(PredicateNode<AttributeId> predicateNode, FilterSubscriptionImpl filterSubscription) { if (predicates == null) { predicates = new Predicates(filterSubscription.useIntervals() && metadataAdapter.isComparableProperty(metadata)); } return predicates.addPredicateSubscription(predicateNode, filterSubscription); } public void removePredicateSubscription(Predicates.Subscription<AttributeId> subscription) { if (predicates != null) { predicates.removePredicateSubscription(subscription); } else { throw new IllegalStateException("Reached illegal state"); } } public void addProjection(FilterSubscriptionImpl filterSubscription, int position) { if (projections == null) { projections = new Projections(); } projections.addProjection(filterSubscription, position); } public void removeProjections(FilterSubscriptionImpl filterSubscription) { if (projections != null) { projections.removeProjections(filterSubscription); } else { throw new IllegalStateException("Reached illegal state"); } } @Override public String toString() { return "AttributeNode(" + attribute + ')'; } public Object cacheMetadataProjection(Object key, AttributeId attribute) { if (!(this instanceof RootNode) || !(metadataAdapter instanceof MetadataProjectable)) { return null; } return ((MetadataProjectable) metadataAdapter).projection(key, attribute); } }
6,982
32.572115
158
java
null
infinispan-main/object-filter/src/main/java/org/infinispan/objectfilter/impl/predicateindex/MetadataProjectable.java
package org.infinispan.objectfilter.impl.predicateindex; public interface MetadataProjectable<AttributeValue> { Object projection(Object key, AttributeValue attribute); }
177
21.25
59
java
null
infinispan-main/object-filter/src/main/java/org/infinispan/objectfilter/impl/predicateindex/MatcherEvalContext.java
package org.infinispan.objectfilter.impl.predicateindex; import java.util.HashMap; import java.util.List; import java.util.Map; import org.infinispan.objectfilter.impl.FilterRegistry; import org.infinispan.objectfilter.impl.FilterSubscriptionImpl; import org.infinispan.objectfilter.impl.predicateindex.be.BETree; /** * Stores processing state during the matching process of all filters registered with a Matcher. * * @param <TypeMetadata> representation of entity type information, ie a Class object or anything that represents a * type * @param <AttributeMetadata> representation of attribute type information * @param <AttributeId> representation of attribute identifiers * @author anistor@redhat.com * @since 7.0 */ public abstract class MatcherEvalContext<TypeMetadata, AttributeMetadata, AttributeId extends Comparable<AttributeId>> { protected AttributeNode<AttributeMetadata, AttributeId> rootNode; /** * Current node during traversal of the attribute tree. */ protected AttributeNode<AttributeMetadata, AttributeId> currentNode; private final Object userContext; protected final Object key; private final Object instance; private final Object eventType; private FilterEvalContext singleFilterContext; /** * Each filter subscription has its own evaluation context, created on demand. */ private FilterEvalContext[] filterContexts; private List<FilterSubscriptionImpl> filterSubscriptions; private Map<Predicate<?>, Counter> suspendedPredicateSubscriptionCounts; protected MatcherEvalContext(Object userContext, Object eventType, Object key, Object instance) { if (instance == null) { throw new IllegalArgumentException("instance cannot be null"); } this.userContext = userContext; this.eventType = eventType; this.key = key; this.instance = instance; } public abstract TypeMetadata getEntityType(); /** * The instance being matched with the filters. */ public Object getInstance() { return instance; } public Object getUserContext() { return userContext; } public Object getEventType() { return eventType; } public void initMultiFilterContext(FilterRegistry<TypeMetadata, AttributeMetadata, AttributeId> filterRegistry) { rootNode = filterRegistry.getPredicateIndex().getRoot(); suspendedPredicateSubscriptionCounts = new HashMap<>(); filterSubscriptions = filterRegistry.getFilterSubscriptions(); filterContexts = new FilterEvalContext[filterRegistry.getFilterSubscriptions().size()]; } public FilterEvalContext initSingleFilterContext(FilterSubscriptionImpl filterSubscription) { singleFilterContext = new FilterEvalContext(this, filterSubscription); return singleFilterContext; } private boolean isSingleFilter() { return singleFilterContext != null; } public FilterEvalContext getFilterEvalContext(FilterSubscriptionImpl filterSubscription) { if (isSingleFilter()) { return singleFilterContext; } FilterEvalContext filterEvalContext = filterContexts[filterSubscription.index]; if (filterEvalContext == null) { filterEvalContext = new FilterEvalContext(this, filterSubscription); filterContexts[filterSubscription.index] = filterEvalContext; } return filterEvalContext; } public void addSuspendedSubscription(Predicate<?> predicate) { if (isSingleFilter()) { return; } Counter counter = suspendedPredicateSubscriptionCounts.computeIfAbsent(predicate, k -> new Counter()); counter.value++; } public int getSuspendedSubscriptionsCounter(Predicate<AttributeId> predicate) { if (isSingleFilter()) { return -1; } Counter counter = suspendedPredicateSubscriptionCounts.get(predicate); return counter == null ? 0 : counter.value; } public AttributeNode<AttributeMetadata, AttributeId> getRootNode() { return rootNode; } public void process(AttributeNode<AttributeMetadata, AttributeId> node) { currentNode = node; processAttributes(currentNode, instance); } public void notifySubscribers() { if (isSingleFilter()) { return; } for (int i = 0; i < filterContexts.length; i++) { FilterSubscriptionImpl s = filterSubscriptions.get(i); FilterEvalContext filterEvalContext = filterContexts[i]; if (filterEvalContext == null) { if (s.getBETree().getChildCounters()[0] == BETree.EXPR_TRUE) { // this filter is a tautology and since its FilterEvalContext was never activated that means it also does not have projections filterEvalContext = new FilterEvalContext(this, s); filterContexts[i] = filterEvalContext; } else { continue; } } if (filterEvalContext.isMatching()) { s.getCallback().onFilterResult(userContext, eventType, instance, filterEvalContext.getProjection(), filterEvalContext.getSortProjection()); } } } public void notifyDeltaSubscribers(MatcherEvalContext other, Object joiningEvent, Object updateEvent, Object leavingEvent) { if (isSingleFilter()) { throw new AssertionError("Single filters contexts do not support delta matching."); } for (int i = 0; i < filterContexts.length; i++) { FilterSubscriptionImpl s = filterSubscriptions.get(i); FilterEvalContext filterEvalContext1 = filterContexts[i]; if (filterEvalContext1 == null && s.getBETree().getChildCounters()[0] == BETree.EXPR_TRUE) { // this filter is a tautology and since its FilterEvalContext was never activated that means it also does not have projections filterEvalContext1 = new FilterEvalContext(this, s); filterContexts[i] = filterEvalContext1; } FilterEvalContext filterEvalContext2 = null; if (other != null) { filterEvalContext2 = other.filterContexts[i]; if (filterEvalContext2 == null && s.getBETree().getChildCounters()[0] == BETree.EXPR_TRUE) { // this filter is a tautology and since its FilterEvalContext was never activated that means it also does not have projections filterEvalContext2 = new FilterEvalContext(other, s); other.filterContexts[i] = filterEvalContext2; } } boolean before = filterEvalContext1 != null && filterEvalContext1.isMatching(); boolean after = filterEvalContext2 != null && filterEvalContext2.isMatching(); if (!before && after) { s.getCallback().onFilterResult(userContext, joiningEvent, other.instance, filterEvalContext2.getProjection(), filterEvalContext2.getSortProjection()); } else if (before && !after) { s.getCallback().onFilterResult(userContext, leavingEvent, instance, filterEvalContext1.getProjection(), filterEvalContext1.getSortProjection()); } else if (before && after) { s.getCallback().onFilterResult(userContext, updateEvent, other.instance, filterEvalContext2.getProjection(), filterEvalContext2.getSortProjection()); } } } protected abstract void processAttributes(AttributeNode<AttributeMetadata, AttributeId> node, Object instance); private static final class Counter { int value = 0; } }
7,526
37.015152
162
java
null
infinispan-main/object-filter/src/main/java/org/infinispan/objectfilter/impl/predicateindex/Predicate.java
package org.infinispan.objectfilter.impl.predicateindex; /** * A predicate attached to an attribute. It comes in two flavors: condition predicate or interval predicate. An interval * predicate represents a range of values (possibly infinite at one end but not both). It requires that the attribute * domain is Comparable, otherwise the notion of interval is meaningless. A condition predicate on the other hand can * have any arbitrary condition and does not require the attribute value to be Comparable. * * @author anistor@redhat.com * @since 7.0 */ public class Predicate<AttributeDomain> { protected AttributeNode attributeNode; /** * Indicates if this predicate is attached to a repeated attribute (one of the attribute path components is a * collection/array) and thus it will have multiple evaluations. */ private final boolean isRepeated; /** * The condition, never null. There is always an equivalent condition even for interval predicates. */ private final Condition<AttributeDomain> condition; public Predicate(boolean isRepeated, Condition<AttributeDomain> condition) { this.isRepeated = isRepeated; this.condition = condition; } public boolean isRepeated() { return isRepeated; } public boolean match(AttributeDomain attributeValue) { return condition.match(attributeValue); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null || getClass() != obj.getClass()) return false; Predicate other = (Predicate) obj; return attributeNode == other.attributeNode && isRepeated == other.isRepeated && condition.equals(other.condition); } @Override public int hashCode() { int i = condition.hashCode(); i = i + 31 * attributeNode.hashCode(); return 31 * i + (isRepeated ? 1 : 0); } @Override public String toString() { return "Predicate(" + attributeNode + ", isRepeated=" + isRepeated + ", " + condition + ")"; } }
2,054
31.619048
120
java
null
infinispan-main/object-filter/src/main/java/org/infinispan/objectfilter/impl/predicateindex/ProtobufMatcherEvalContext.java
package org.infinispan.objectfilter.impl.predicateindex; import java.io.IOException; import org.infinispan.objectfilter.impl.logging.Log; import org.infinispan.objectfilter.impl.syntax.parser.ProtobufPropertyHelper; import org.infinispan.protostream.MessageContext; import org.infinispan.protostream.ProtobufParser; import org.infinispan.protostream.SerializationContext; import org.infinispan.protostream.TagHandler; import org.infinispan.protostream.WrappedMessage; import org.infinispan.protostream.descriptors.Descriptor; import org.infinispan.protostream.descriptors.FieldDescriptor; import org.infinispan.protostream.descriptors.GenericDescriptor; import org.infinispan.protostream.descriptors.JavaType; import org.jboss.logging.Logger; /** * @author anistor@redhat.com * @since 7.0 */ public final class ProtobufMatcherEvalContext extends MatcherEvalContext<Descriptor, FieldDescriptor, Integer> implements TagHandler { private static final Log log = Logger.getMessageLogger(Log.class, ProtobufMatcherEvalContext.class.getName()); private boolean payloadStarted = false; private int skipping = 0; private byte[] payload; private String entityTypeName; private Descriptor payloadMessageDescriptor; private MessageContext messageContext; private final SerializationContext serializationContext; public ProtobufMatcherEvalContext(Object userContext, Object eventType, Object key, Object instance, Descriptor wrappedMessageDescriptor, SerializationContext serializationContext) { super(userContext, eventType, key, instance); this.serializationContext = serializationContext; try { ProtobufParser.INSTANCE.parse(this, wrappedMessageDescriptor, (byte[]) getInstance()); } catch (IOException e) { throw log.errorParsingProtobuf(e); } } @Override public Descriptor getEntityType() { return payloadMessageDescriptor; } @Override public void onStart(GenericDescriptor descriptor) { } //todo [anistor] missing tags need to be fired with default value defined in proto schema or null if they admit null; missing messages need to be fired with null at end of the nesting level. BTW, seems like this is better to be included in Protostream as a feature @Override public void onTag(int fieldNumber, FieldDescriptor fieldDescriptor, Object tagValue) { if (payloadStarted) { if (skipping == 0) { AttributeNode<FieldDescriptor, Integer> attrNode = currentNode.getChild(fieldNumber); if (attrNode != null) { // process only 'interesting' tags messageContext.markField(fieldNumber); attrNode.processValue(tagValue, this); } } } else { switch (fieldNumber) { case WrappedMessage.WRAPPED_DESCRIPTOR_FULL_NAME: entityTypeName = (String) tagValue; break; case WrappedMessage.WRAPPED_DESCRIPTOR_TYPE_ID: entityTypeName = serializationContext.getDescriptorByTypeId((Integer) tagValue).getFullName(); break; case WrappedMessage.WRAPPED_MESSAGE: payload = (byte[]) tagValue; break; case WrappedMessage.WRAPPED_DOUBLE: case WrappedMessage.WRAPPED_FLOAT: case WrappedMessage.WRAPPED_INT64: case WrappedMessage.WRAPPED_UINT64: case WrappedMessage.WRAPPED_INT32: case WrappedMessage.WRAPPED_FIXED64: case WrappedMessage.WRAPPED_FIXED32: case WrappedMessage.WRAPPED_BOOL: case WrappedMessage.WRAPPED_STRING: case WrappedMessage.WRAPPED_BYTES: case WrappedMessage.WRAPPED_UINT32: case WrappedMessage.WRAPPED_SFIXED32: case WrappedMessage.WRAPPED_SFIXED64: case WrappedMessage.WRAPPED_SINT32: case WrappedMessage.WRAPPED_SINT64: case WrappedMessage.WRAPPED_ENUM: break; // this is a primitive value, which we ignore for now due to lack of support for querying primitives default: throw new IllegalStateException("Unexpected field : " + fieldNumber); } } } @Override public void onStartNested(int fieldNumber, FieldDescriptor fieldDescriptor) { if (payloadStarted) { if (skipping == 0) { AttributeNode<FieldDescriptor, Integer> attrNode = currentNode.getChild(fieldNumber); if (attrNode != null) { // ignore 'uninteresting' tags messageContext.markField(fieldNumber); pushContext(fieldDescriptor, fieldDescriptor.getMessageType()); currentNode = attrNode; return; } } // found an uninteresting nesting level, start skipping from here on until this level ends skipping++; } else { throw new IllegalStateException("No nested message is supported"); } } @Override public void onEndNested(int fieldNumber, FieldDescriptor fieldDescriptor) { if (payloadStarted) { if (skipping == 0) { popContext(); currentNode = currentNode.getParent(); } else { skipping--; } } else { throw new IllegalStateException("No nested message is supported"); } } @Override public void onEnd() { if (payloadStarted) { processMissingFields(); } else { payloadStarted = true; if (payload != null) { if (entityTypeName == null) { throw new IllegalStateException("Descriptor name is missing"); } payloadMessageDescriptor = serializationContext.getMessageDescriptor(entityTypeName); messageContext = new MessageContext<>(null, null, payloadMessageDescriptor); } } } @Override protected void processAttributes(AttributeNode<FieldDescriptor, Integer> node, Object instance) { try { ProtobufParser.INSTANCE.parse(this, payloadMessageDescriptor, payload); for (AttributeNode<FieldDescriptor, Integer> childAttribute : node.getChildren()) { if (childAttribute.getAttribute() >= ProtobufPropertyHelper.MIN_METADATA_FIELD_ATTRIBUTE_ID) { Object attributeValue = node.cacheMetadataProjection(key, childAttribute.getAttribute()); childAttribute.processValue(attributeValue, this); } } } catch (IOException e) { throw new RuntimeException(e); // TODO [anistor] proper exception handling needed } } private void pushContext(FieldDescriptor fieldDescriptor, Descriptor messageDescriptor) { messageContext = new MessageContext<>(messageContext, fieldDescriptor, messageDescriptor); } private void popContext() { processMissingFields(); messageContext = messageContext.getParentContext(); } private void processMissingFields() { for (FieldDescriptor fd : messageContext.getMessageDescriptor().getFields()) { AttributeNode<FieldDescriptor, Integer> attributeNode = currentNode.getChild(fd.getNumber()); boolean fieldSeen = messageContext.isFieldMarked(fd.getNumber()); if (attributeNode != null && (fd.isRepeated() || !fieldSeen)) { if (fd.isRepeated()) { // Repeated fields can't have default values but we need to at least take care of IS [NOT] NULL predicates if (fieldSeen) { // Here we use a dummy value since it would not matter anyway for IS [NOT] NULL attributeNode.processValue(AttributeNode.DUMMY_VALUE, this); } else { processNullAttribute(attributeNode); } } else { if (fd.getJavaType() == JavaType.MESSAGE) { processNullAttribute(attributeNode); } else { Object defaultValue = fd.hasDefaultValue() ? fd.getDefaultValue() : null; attributeNode.processValue(defaultValue, this); } } } } } private void processNullAttribute(AttributeNode<FieldDescriptor, Integer> attributeNode) { attributeNode.processValue(null, this); for (AttributeNode<FieldDescriptor, Integer> childAttribute : attributeNode.getChildren()) { processNullAttribute(childAttribute); } } }
8,541
38.915888
267
java
null
infinispan-main/object-filter/src/main/java/org/infinispan/objectfilter/impl/predicateindex/RootNode.java
package org.infinispan.objectfilter.impl.predicateindex; import org.infinispan.objectfilter.impl.FilterSubscriptionImpl; import org.infinispan.objectfilter.impl.MetadataAdapter; import org.infinispan.objectfilter.impl.predicateindex.be.PredicateNode; /** * @author anistor@redhat.com * @since 7.0 */ final class RootNode<AttributeMetadata, AttributeId extends Comparable<AttributeId>> extends AttributeNode<AttributeMetadata, AttributeId> { RootNode(MetadataAdapter<?, AttributeMetadata, AttributeId> metadataAdapter) { super(metadataAdapter); } @Override public Predicates.Subscription<AttributeId> addPredicateSubscription(PredicateNode<AttributeId> predicateNode, FilterSubscriptionImpl filterSubscription) { throw new UnsupportedOperationException("Root node does not allow predicates"); } @Override public void removePredicateSubscription(Predicates.Subscription<AttributeId> subscription) { throw new UnsupportedOperationException("Root node does not allow predicates"); } @Override public void addProjection(FilterSubscriptionImpl filterSubscription, int position) { throw new UnsupportedOperationException("Root node does not allow projections"); } @Override public void removeProjections(FilterSubscriptionImpl filterSubscription) { throw new UnsupportedOperationException("Root node does not allow projections"); } @Override public String toString() { return "RootNode"; } }
1,483
34.333333
158
java
null
infinispan-main/object-filter/src/main/java/org/infinispan/objectfilter/impl/predicateindex/LikeCondition.java
package org.infinispan.objectfilter.impl.predicateindex; import java.util.BitSet; import java.util.regex.Pattern; import org.infinispan.objectfilter.impl.syntax.LikeExpr; /** * A condition that matches String values using a pattern containing the well known '%' and '_' wildcards. * * @author anistor@redhat.com * @since 7.0 */ public final class LikeCondition implements Condition<String> { /** * The actual match might be a regexp, or possibly a simpler degenerated case. */ private enum Type { Regexp, Contains, StartsWith, EndsWith, Equals } /** * The type of this matcher. */ private final Type type; /** * The original 'like' pattern. */ private final String likePattern; /** * The regexp. Only used if the match requires full regexp power. */ private final Pattern regexPattern; /** * The value to match against, or {@code null} if this is based on regexp. */ private final String value; /** * The expected length of the input value or {@code -1} if the expected length is not constant or if the match is * based on regexp. */ private final int length; public LikeCondition(String likePattern) { this(likePattern, LikeExpr.DEFAULT_ESCAPE_CHARACTER); } public LikeCondition(String likePattern, char escapeCharacter) { this.likePattern = likePattern; // before going the full-fledged regexp way we investigate to see if this can be turned into a simpler and less costly string match test StringBuilder sb = new StringBuilder(likePattern.length()); BitSet multi = new BitSet(likePattern.length()); int multiCount = 0; BitSet single = new BitSet(likePattern.length()); int singleCount = 0; boolean isEscaped = false; for (int i = 0; i < likePattern.length(); i++) { char c = likePattern.charAt(i); if (!isEscaped && c == escapeCharacter) { isEscaped = true; } else { if (isEscaped) { isEscaped = false; } else { if (c == LikeExpr.MULTIPLE_CHARACTERS_WILDCARD) { multi.set(sb.length()); multiCount++; } else if (c == LikeExpr.SINGLE_CHARACTER_WILDCARD) { single.set(sb.length()); singleCount++; } } sb.append(c); } } if (multiCount == 0 && singleCount == 0) { // no wildcards at all type = Type.Equals; value = sb.toString(); regexPattern = null; length = -1; } else { if (multi.get(0)) { if (singleCount == 0) { if (multiCount == 1) { type = Type.EndsWith; value = sb.substring(1); length = -1; regexPattern = null; return; } else if (multiCount == 2 && multi.get(sb.length() - 1)) { type = Type.Contains; value = sb.substring(1, sb.length() - 1); length = -1; regexPattern = null; return; } } } else if (single.get(0)) { if (multiCount == 0 && singleCount == 1) { type = Type.EndsWith; value = sb.substring(1); length = sb.length(); regexPattern = null; return; } } else if (multi.get(sb.length() - 1)) { if (multiCount == 1 && singleCount == 0) { type = Type.StartsWith; value = sb.substring(0, sb.length() - 1); length = -1; regexPattern = null; return; } } else if (single.get(sb.length() - 1)) { if (singleCount == 1 && multiCount == 0) { type = Type.StartsWith; value = sb.substring(0, sb.length() - 1); length = sb.length(); regexPattern = null; return; } } // could not turn it into a degenerated case, so go full regexp StringBuilder regexpPattern = new StringBuilder(sb.length() + 2); // we match the entire value, from start to end regexpPattern.append('^'); for (int i = 0; i < sb.length(); i++) { if (multi.get(i)) { regexpPattern.append(".*"); } else if (single.get(i)) { regexpPattern.append('.'); } else { // regexp special characters need to be escaped char c = sb.charAt(i); switch (c) { case '+': case '*': case '(': case ')': case '[': case ']': case '$': case '^': case '.': case '{': case '}': case '|': case '\\': regexpPattern.append('\\'); // intended fall through default: regexpPattern.append(c); } } } regexpPattern.append('$'); type = Type.Regexp; regexPattern = Pattern.compile(regexpPattern.toString()); value = null; length = -1; } } @Override public boolean match(String attributeValue) { if (attributeValue == null) { return false; } switch (type) { case Equals: return attributeValue.equals(value); case StartsWith: return (length == -1 || length == attributeValue.length()) && attributeValue.startsWith(value); case EndsWith: return (length == -1 || length == attributeValue.length()) && attributeValue.endsWith(value); case Contains: return attributeValue.contains(value); case Regexp: return regexPattern.matcher(attributeValue).matches(); default: throw new IllegalStateException("Unexpected type " + type); } } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null || getClass() != obj.getClass()) return false; LikeCondition other = (LikeCondition) obj; return likePattern.equals(other.likePattern); } @Override public int hashCode() { return likePattern.hashCode(); } @Override public String toString() { return "LikeCondition(" + likePattern + ')'; } }
6,705
29.903226
142
java
null
infinispan-main/object-filter/src/main/java/org/infinispan/objectfilter/impl/predicateindex/ReflectionMatcherEvalContext.java
package org.infinispan.objectfilter.impl.predicateindex; import java.util.Iterator; import org.infinispan.objectfilter.impl.util.ReflectionHelper; /** * @author anistor@redhat.com * @since 7.0 */ public final class ReflectionMatcherEvalContext extends MatcherEvalContext<Class<?>, ReflectionHelper.PropertyAccessor, String> { private final Class<?> entityType; public ReflectionMatcherEvalContext(Object userContext, Object eventType, Object key, Object instance) { super(userContext, eventType, key, instance); entityType = instance.getClass(); } @Override public Class<?> getEntityType() { return entityType; } @Override protected void processAttributes(AttributeNode<ReflectionHelper.PropertyAccessor, String> node, Object instance) { for (AttributeNode<ReflectionHelper.PropertyAccessor, String> childAttribute : node.getChildren()) { if (instance == null) { processAttribute(childAttribute, null); } else { ReflectionHelper.PropertyAccessor accessor = childAttribute.getMetadata(); if (accessor == null) { Object attributeValue = node.cacheMetadataProjection(key, childAttribute.getAttribute()); if (attributeValue != null) { processAttribute(childAttribute, attributeValue); } continue; } if (accessor.isMultiple()) { Iterator valuesIt = accessor.getValueIterator(instance); if (valuesIt == null) { // try to evaluate eventual 'is null' predicates for this null collection processAttribute(childAttribute, null); } else { while (valuesIt.hasNext()) { Object attributeValue = valuesIt.next(); processAttribute(childAttribute, attributeValue); } } } else { Object attributeValue = accessor.getValue(instance); processAttribute(childAttribute, attributeValue); } } } } private void processAttribute(AttributeNode<ReflectionHelper.PropertyAccessor, String> attributeNode, Object attributeValue) { attributeNode.processValue(attributeValue, this); processAttributes(attributeNode, attributeValue); } }
2,383
36.25
129
java
null
infinispan-main/object-filter/src/main/java/org/infinispan/objectfilter/impl/predicateindex/IntervalPredicate.java
package org.infinispan.objectfilter.impl.predicateindex; import org.infinispan.objectfilter.impl.util.Interval; /** * A predicate attached to an attribute. It comes in two flavors: condition predicate or interval predicate. An interval * predicate represents a range of values (possibly infinite at one end but not both). It requires that the attribute * domain is Comparable, otherwise the notion of interval is meaningless. A condition predicate on the other hand can * have any arbitrary condition and does not require the attribute value to be Comparable. * * @author anistor@redhat.com * @since 7.0 */ public final class IntervalPredicate<AttributeDomain extends Comparable<AttributeDomain>> extends Predicate<AttributeDomain> { /** * The interval. */ private final Interval<AttributeDomain> interval; public IntervalPredicate(boolean isRepeated, Interval<AttributeDomain> interval) { super(isRepeated, new IntervalCondition<>(interval)); this.interval = interval; } public Interval<AttributeDomain> getInterval() { return interval; } }
1,099
35.666667
126
java
null
infinispan-main/object-filter/src/main/java/org/infinispan/objectfilter/impl/predicateindex/RowMatcherEvalContext.java
package org.infinispan.objectfilter.impl.predicateindex; import org.infinispan.objectfilter.impl.syntax.parser.RowPropertyHelper; /** * @author anistor@redhat.com * @since 8.0 */ public final class RowMatcherEvalContext extends MatcherEvalContext<RowPropertyHelper.RowMetadata, RowPropertyHelper.ColumnMetadata, Integer> { private final RowPropertyHelper.RowMetadata rowMetadata; public RowMatcherEvalContext(Object userContext, Object eventType, Object key, Object instance, RowPropertyHelper.RowMetadata rowMetadata) { super(userContext, eventType, key, instance); this.rowMetadata = rowMetadata; } @Override public RowPropertyHelper.RowMetadata getEntityType() { return rowMetadata; } @Override protected void processAttributes(AttributeNode<RowPropertyHelper.ColumnMetadata, Integer> node, Object instance) { for (AttributeNode<RowPropertyHelper.ColumnMetadata, Integer> childAttribute : node.getChildren()) { Object attributeValue = null; if (instance != null) { attributeValue = childAttribute.getMetadata().getValue(instance); } childAttribute.processValue(attributeValue, this); } } }
1,207
34.529412
143
java
null
infinispan-main/object-filter/src/main/java/org/infinispan/objectfilter/impl/predicateindex/Predicates.java
package org.infinispan.objectfilter.impl.predicateindex; import java.util.ArrayList; import java.util.List; import org.infinispan.objectfilter.impl.FilterSubscriptionImpl; import org.infinispan.objectfilter.impl.predicateindex.be.PredicateNode; import org.infinispan.objectfilter.impl.util.IntervalTree; /** * Holds all predicates that are subscribed for a certain attribute. This class is not thread safe and leaves this * responsibility to the caller. * * @param <AttributeDomain> the type of the values of the attribute * @author anistor@redhat.com * @since 7.0 */ public final class Predicates<AttributeDomain extends Comparable<AttributeDomain>, AttributeId extends Comparable<AttributeId>> { /** * Holds all subscriptions for a single predicate. */ private static class Subscriptions { private final Predicate predicate; /** * The callbacks of the subscribed predicates. */ private final List<Subscription> subscriptions = new ArrayList<>(); private Subscriptions(Predicate predicate) { this.predicate = predicate; } void add(Subscription subscription) { subscriptions.add(subscription); } void remove(Subscription subscription) { subscriptions.remove(subscription); } boolean isEmpty() { return subscriptions.isEmpty(); } //todo [anistor] this is an improvement but still does not eliminate precessing of attributes that have only suspended subscribers boolean isActive(MatcherEvalContext<?, ?, ?> ctx) { return !predicate.isRepeated() || ctx.getSuspendedSubscriptionsCounter(predicate) < subscriptions.size(); } } public static final class Subscription<AttributeId extends Comparable<AttributeId>> { private final PredicateNode<AttributeId> predicateNode; private final FilterSubscriptionImpl filterSubscription; private Subscription(PredicateNode<AttributeId> predicateNode, FilterSubscriptionImpl filterSubscription) { this.predicateNode = predicateNode; this.filterSubscription = filterSubscription; } private void handleValue(MatcherEvalContext<?, ?, ?> ctx, boolean isMatching) { FilterEvalContext filterEvalContext = ctx.getFilterEvalContext(filterSubscription); if (!predicateNode.isEvaluationComplete(filterEvalContext)) { if (predicateNode.isNegated()) { isMatching = !isMatching; } if (isMatching || !predicateNode.getPredicate().isRepeated()) { predicateNode.handleChildValue(null, isMatching, filterEvalContext); } } } public PredicateNode<AttributeId> getPredicateNode() { return predicateNode; } } private final boolean useIntervals; /** * The predicates that have a condition based on an order relation (ie. intervals). This allows them to be * represented by an interval tree. */ private IntervalTree<AttributeDomain, Subscriptions> orderedPredicates; /** * The predicates that are based on an arbitrary condition that is not an order relation. */ private List<Subscriptions> unorderedPredicates; Predicates(boolean useIntervals) { this.useIntervals = useIntervals; } public void notifyMatchingSubscribers(final MatcherEvalContext<?, ?, ?> ctx, Object attributeValue) { if (orderedPredicates != null && attributeValue instanceof Comparable) { orderedPredicates.stab((AttributeDomain) attributeValue, node -> { Subscriptions subscriptions = node.value; if (subscriptions.isActive(ctx)) { for (Subscription s : subscriptions.subscriptions) { s.handleValue(ctx, true); } } }); } if (unorderedPredicates != null) { for (int k = unorderedPredicates.size() - 1; k >= 0; k--) { Subscriptions subscriptions = unorderedPredicates.get(k); if (subscriptions.isActive(ctx)) { boolean isMatching = subscriptions.predicate.match(attributeValue); List<Subscription> s = subscriptions.subscriptions; for (int i = s.size() - 1; i >= 0; i--) { s.get(i).handleValue(ctx, isMatching); } } } } } public Predicates.Subscription<AttributeId> addPredicateSubscription(PredicateNode predicateNode, FilterSubscriptionImpl filterSubscription) { Subscriptions subscriptions; Predicate<AttributeDomain> predicate = predicateNode.getPredicate(); if (useIntervals && predicate instanceof IntervalPredicate) { if (orderedPredicates == null) { // in this case AttributeDomain extends Comparable for sure orderedPredicates = new IntervalTree<>(); } IntervalTree.Node<AttributeDomain, Subscriptions> n = orderedPredicates.add(((IntervalPredicate) predicate).getInterval()); if (n.value == null) { subscriptions = new Subscriptions(predicate); n.value = subscriptions; } else { subscriptions = n.value; } } else { subscriptions = null; if (unorderedPredicates == null) { unorderedPredicates = new ArrayList<>(); } else { for (int i = 0; i < unorderedPredicates.size(); i++) { Subscriptions s = unorderedPredicates.get(i); if (s.predicate.equals(predicate)) { subscriptions = s; break; } } } if (subscriptions == null) { subscriptions = new Subscriptions(predicate); unorderedPredicates.add(subscriptions); } } Subscription<AttributeId> subscription = new Subscription<AttributeId>(predicateNode, filterSubscription); subscriptions.add(subscription); return subscription; } public void removePredicateSubscription(Subscription subscription) { Predicate<AttributeDomain> predicate = (Predicate<AttributeDomain>) subscription.predicateNode.getPredicate(); if (useIntervals && predicate instanceof IntervalPredicate) { if (orderedPredicates != null) { IntervalTree.Node<AttributeDomain, Subscriptions> n = orderedPredicates.findNode(((IntervalPredicate) predicate).getInterval()); if (n != null) { n.value.remove(subscription); if (n.value.isEmpty()) { orderedPredicates.remove(n); } } else { throwIllegalStateException(); } } else { throwIllegalStateException(); } } else { if (unorderedPredicates != null) { for (int i = 0; i < unorderedPredicates.size(); i++) { Predicates.Subscriptions subscriptions = unorderedPredicates.get(i); if (subscriptions.predicate.equals(predicate)) { subscriptions.remove(subscription); if (subscriptions.isEmpty()) { unorderedPredicates.remove(i); } break; } } } else { throwIllegalStateException(); } } } public boolean isEmpty() { return (unorderedPredicates == null || unorderedPredicates.isEmpty()) && (orderedPredicates == null || orderedPredicates.isEmpty()); } private static void throwIllegalStateException() throws IllegalStateException { // this is not expected to happen unless a programming error slipped through throw new IllegalStateException("Reached an invalid state"); } }
7,799
36.681159
145
java
null
infinispan-main/object-filter/src/main/java/org/infinispan/objectfilter/impl/predicateindex/be/package-info.java
/** * A compact representation for boolean expressions. * * @api.private */ package org.infinispan.objectfilter.impl.predicateindex.be;
140
19.142857
59
java
null
infinispan-main/object-filter/src/main/java/org/infinispan/objectfilter/impl/predicateindex/be/AndNode.java
package org.infinispan.objectfilter.impl.predicateindex.be; import org.infinispan.objectfilter.impl.predicateindex.FilterEvalContext; /** * @author anistor@redhat.com * @since 7.0 */ public final class AndNode extends BENode { public AndNode(BENode parent) { super(parent); } @Override public void handleChildValue(BENode child, boolean childValue, FilterEvalContext evalContext) { if (isEvaluationComplete(evalContext)) { throw new IllegalStateException("This should never be called again because the state of this node has been decided already."); } if (childValue) { if (--evalContext.treeCounters[startIndex] == 0) { // value of this node is decided: TRUE if (parent != null) { // propagate to the parent, if we have a parent parent.handleChildValue(this, true, evalContext); } else { // mark this node as 'satisfied' setState(BETree.EXPR_TRUE, evalContext); } } else { // value of this node cannot be decided yet, so we cannot propagate to the parent anything yet but let's at least mark down the child as 'satisfied' child.setState(BETree.EXPR_TRUE, evalContext); } } else { // value of this node is decided: FALSE if (parent != null) { // propagate to the parent, if we have a parent parent.handleChildValue(this, false, evalContext); } else { // mark this node as 'unsatisfied' setState(BETree.EXPR_FALSE, evalContext); } } } }
1,647
34.06383
160
java
null
infinispan-main/object-filter/src/main/java/org/infinispan/objectfilter/impl/predicateindex/be/BENode.java
package org.infinispan.objectfilter.impl.predicateindex.be; import org.infinispan.objectfilter.impl.predicateindex.FilterEvalContext; /** * Base boolean expression Node. * * @author anistor@redhat.com * @since 7.0 */ public abstract class BENode { /** * The parent node or null if this is the root; */ protected final BENode parent; /** * The index of this node in the tree's node array. */ protected int startIndex; /** * The index of the last child. */ protected int endIndex; protected BENode(BENode parent) { this.parent = parent; } void setLocation(int startIndex, int endIndex) { this.startIndex = startIndex; this.endIndex = endIndex; } public final boolean isEvaluationComplete(FilterEvalContext evalContext) { return evalContext.treeCounters[0] <= 0 || evalContext.treeCounters[startIndex] <= 0; } public abstract void handleChildValue(BENode child, boolean childValue, FilterEvalContext evalContext); public void suspendSubscription(FilterEvalContext evalContext) { // nothing to do here, subclasses must override appropriately } protected final void setState(int nodeValue, FilterEvalContext evalContext) { BENode[] nodes = evalContext.beTree.getNodes(); for (int i = startIndex; i < endIndex; i++) { if (evalContext.treeCounters[i] == 1) { // this may be a predicate node evalContext.treeCounters[i] = nodeValue; // this is not the real value, but any value less that 1 will do nodes[i].suspendSubscription(evalContext); } } evalContext.treeCounters[startIndex] = nodeValue; } }
1,690
27.661017
117
java
null
infinispan-main/object-filter/src/main/java/org/infinispan/objectfilter/impl/predicateindex/be/PredicateNode.java
package org.infinispan.objectfilter.impl.predicateindex.be; import java.util.List; import org.infinispan.objectfilter.impl.predicateindex.FilterEvalContext; import org.infinispan.objectfilter.impl.predicateindex.IntervalPredicate; import org.infinispan.objectfilter.impl.predicateindex.Predicate; /** * A PredicateNode is a leaf node in a BETree that holds a Predicate instance. A PredicateNode instance is never reused * inside the same BETree or shared between multiple BETrees, but an entire BETree could be shared by multiple filters. * Multiple PredicateNodes could share the same Predicate instance. * * @author anistor@redhat.com * @since 7.0 */ public final class PredicateNode<AttributeId extends Comparable<AttributeId>> extends BENode { // the predicate can be shared by multiple PredicateNodes private final Predicate<?> predicate; /** * Indicates if the Predicate's condition is negated. This can be true only for condition predicates, never for * interval predicates. */ private final boolean isNegated; private final List<AttributeId> attributePath; public PredicateNode(BENode parent, Predicate<?> predicate, boolean isNegated, List<AttributeId> attributePath) { super(parent); if (isNegated && predicate instanceof IntervalPredicate) { throw new IllegalArgumentException("Interval predicates should not be negated"); } this.predicate = predicate; this.isNegated = isNegated; this.attributePath = attributePath; } public Predicate<?> getPredicate() { return predicate; } public boolean isNegated() { return isNegated; } public List<AttributeId> getAttributePath() { return attributePath; } @Override public void handleChildValue(BENode child, boolean childValue, FilterEvalContext evalContext) { if (child != null) { throw new IllegalArgumentException("Predicates have value but do not have children"); } final int value = childValue ? BETree.EXPR_TRUE : BETree.EXPR_FALSE; if (isEvaluationComplete(evalContext)) { if (predicate.isRepeated() && evalContext.treeCounters[startIndex] == value) { // receiving the same value multiple times is fine if this is a repeated condition return; } throw new IllegalStateException("This should never be called again if the state of this node was previously decided."); } if (parent == null) { evalContext.treeCounters[startIndex] = value; suspendSubscription(evalContext); } else { parent.handleChildValue(this, childValue, evalContext); } } @Override public void suspendSubscription(FilterEvalContext ctx) { if (predicate.isRepeated()) { ctx.matcherContext.addSuspendedSubscription(predicate); } } @Override public String toString() { return "PredicateNode{" + "attributePath=" + attributePath + ", isNegated=" + isNegated + ", predicate=" + predicate + '}'; } }
3,092
32.619565
128
java
null
infinispan-main/object-filter/src/main/java/org/infinispan/objectfilter/impl/predicateindex/be/OrNode.java
package org.infinispan.objectfilter.impl.predicateindex.be; import org.infinispan.objectfilter.impl.predicateindex.FilterEvalContext; /** * @author anistor@redhat.com * @since 7.0 */ public final class OrNode extends BENode { public OrNode(BENode parent) { super(parent); } @Override public void handleChildValue(BENode child, boolean childValue, FilterEvalContext evalContext) { if (isEvaluationComplete(evalContext)) { throw new IllegalStateException("This should never be called again because the state of this node has been decided already."); } if (childValue) { // value of this node is decided: TRUE if (parent != null) { // propagate to the parent, if we have a parent parent.handleChildValue(this, true, evalContext); } else { // mark this node as satisfied setState(BETree.EXPR_TRUE, evalContext); } } else { if (--evalContext.treeCounters[startIndex] == 0) { // value of this node is decided: FALSE if (parent != null) { // propagate to the parent, if we have a parent parent.handleChildValue(this, false, evalContext); } else { // mark this node as 'unsatisfied' setState(BETree.EXPR_FALSE, evalContext); } } else { // value of this node cannot be decided yet, so we cannot propagate to the parent anything yet but let's at least mark down the child as 'unsatisfied' child.setState(BETree.EXPR_FALSE, evalContext); } } } }
1,646
34.042553
162
java
null
infinispan-main/object-filter/src/main/java/org/infinispan/objectfilter/impl/predicateindex/be/BETreeMaker.java
package org.infinispan.objectfilter.impl.predicateindex.be; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.infinispan.objectfilter.impl.MetadataAdapter; import org.infinispan.objectfilter.impl.predicateindex.EqualsCondition; import org.infinispan.objectfilter.impl.predicateindex.IntervalPredicate; import org.infinispan.objectfilter.impl.predicateindex.IsNullCondition; import org.infinispan.objectfilter.impl.predicateindex.LikeCondition; import org.infinispan.objectfilter.impl.predicateindex.Predicate; import org.infinispan.objectfilter.impl.syntax.AndExpr; import org.infinispan.objectfilter.impl.syntax.BooleanExpr; import org.infinispan.objectfilter.impl.syntax.BooleanOperatorExpr; import org.infinispan.objectfilter.impl.syntax.ComparisonExpr; import org.infinispan.objectfilter.impl.syntax.ConstantBooleanExpr; import org.infinispan.objectfilter.impl.syntax.ConstantValueExpr; import org.infinispan.objectfilter.impl.syntax.IsNullExpr; import org.infinispan.objectfilter.impl.syntax.LikeExpr; import org.infinispan.objectfilter.impl.syntax.NotExpr; import org.infinispan.objectfilter.impl.syntax.OrExpr; import org.infinispan.objectfilter.impl.syntax.PrimaryPredicateExpr; import org.infinispan.objectfilter.impl.syntax.PropertyValueExpr; import org.infinispan.objectfilter.impl.util.Interval; /** * Creates a BETree out of a BooleanExpr. * * @author anistor@redhat.com * @since 7.0 */ public final class BETreeMaker<AttributeId extends Comparable<AttributeId>> { private final MetadataAdapter<?, ?, AttributeId> metadataAdapter; private final boolean useIntervals; public BETreeMaker(MetadataAdapter<?, ?, AttributeId> metadataAdapter, boolean useIntervals) { this.metadataAdapter = metadataAdapter; this.useIntervals = useIntervals; } public BETree make(BooleanExpr booleanExpr, Map<String, Object> namedParameters) { List<BENode> nodes = new ArrayList<>(); List<Integer> treeCounters = new ArrayList<>(); if (booleanExpr == null) { treeCounters.add(BETree.EXPR_TRUE); } else if (booleanExpr instanceof ConstantBooleanExpr) { treeCounters.add(((ConstantBooleanExpr) booleanExpr).getValue() ? BETree.EXPR_TRUE : BETree.EXPR_FALSE); } else { preorderTraversal(null, booleanExpr, nodes, treeCounters, namedParameters); } int[] countersArray = new int[treeCounters.size()]; for (int i = 0; i < countersArray.length; i++) { countersArray[i] = treeCounters.get(i); } return new BETree(nodes.toArray(new BENode[nodes.size()]), countersArray); } private void preorderTraversal(BENode parent, BooleanExpr child, List<BENode> nodes, List<Integer> treeCounters, Map<String, Object> namedParameters) { if (child instanceof NotExpr) { PrimaryPredicateExpr condition = (PrimaryPredicateExpr) ((NotExpr) child).getChild(); makePredicateNode(parent, nodes, treeCounters, condition, true, namedParameters); } else if (child instanceof PrimaryPredicateExpr) { PrimaryPredicateExpr condition = (PrimaryPredicateExpr) child; makePredicateNode(parent, nodes, treeCounters, condition, false, namedParameters); } else if (child instanceof OrExpr) { makeBooleanOperatorNode((OrExpr) child, nodes, treeCounters, new OrNode(parent), namedParameters); } else if (child instanceof AndExpr) { makeBooleanOperatorNode((AndExpr) child, nodes, treeCounters, new AndNode(parent), namedParameters); } else { throw new IllegalStateException("Unexpected *Expr node type: " + child); } } private void makePredicateNode(BENode parent, List<BENode> nodes, List<Integer> treeCounters, PrimaryPredicateExpr condition, boolean isNegated, Map<String, Object> namedParameters) { final PropertyValueExpr pve = (PropertyValueExpr) condition.getChild(); final List<AttributeId> path = metadataAdapter.mapPropertyNamePathToFieldIdPath(pve.getPropertyPath().asArrayPath()); final boolean isRepeated = pve.isRepeated(); if (condition instanceof ComparisonExpr) { ComparisonExpr expr = (ComparisonExpr) condition; ConstantValueExpr right = (ConstantValueExpr) expr.getRightChild(); Comparable rightConstant = right.getConstantValueAs(pve.getPrimitiveType(), namedParameters); switch (expr.getComparisonType()) { case NOT_EQUAL: if (useIntervals) { if (!(parent instanceof OrNode)) { parent = new OrNode(parent); int size = nodes.size(); parent.setLocation(size, size + 4); nodes.add(parent); treeCounters.add(3); } // the special case of non-equality is transformed into two intervals, excluding the compared value, + an IS NULL predicate addPredicateNode(parent, nodes, treeCounters, isNegated, path, new IntervalPredicate(isRepeated, new Interval(Interval.getMinusInf(), false, rightConstant, false))); addPredicateNode(parent, nodes, treeCounters, isNegated, path, new IntervalPredicate(isRepeated, new Interval(rightConstant, false, Interval.getPlusInf(), false))); addPredicateNode(parent, nodes, treeCounters, isNegated, path, new Predicate<>(isRepeated, IsNullCondition.INSTANCE)); } else { addPredicateNode(parent, nodes, treeCounters, !isNegated, path, new Predicate<>(isRepeated, new EqualsCondition(rightConstant))); } break; case EQUAL: if (useIntervals) { addPredicateNode(parent, nodes, treeCounters, isNegated, path, new IntervalPredicate(isRepeated, new Interval(rightConstant, true, rightConstant, true))); } else { addPredicateNode(parent, nodes, treeCounters, isNegated, path, new Predicate<>(isRepeated, new EqualsCondition(rightConstant))); } break; case LESS: addPredicateNode(parent, nodes, treeCounters, isNegated, path, new IntervalPredicate(isRepeated, new Interval(Interval.getMinusInf(), false, rightConstant, false))); break; case LESS_OR_EQUAL: addPredicateNode(parent, nodes, treeCounters, isNegated, path, new IntervalPredicate(isRepeated, new Interval(Interval.getMinusInf(), false, rightConstant, true))); break; case GREATER: addPredicateNode(parent, nodes, treeCounters, isNegated, path, new IntervalPredicate(isRepeated, new Interval(rightConstant, false, Interval.getPlusInf(), false))); break; case GREATER_OR_EQUAL: addPredicateNode(parent, nodes, treeCounters, isNegated, path, new IntervalPredicate(isRepeated, new Interval(rightConstant, true, Interval.getPlusInf(), false))); break; default: throw new IllegalStateException("Unexpected comparison type: " + expr.getComparisonType()); } } else if (condition instanceof IsNullExpr) { addPredicateNode(parent, nodes, treeCounters, isNegated, path, new Predicate<>(isRepeated, IsNullCondition.INSTANCE)); } else if (condition instanceof LikeExpr) { LikeExpr likeExpr = (LikeExpr) condition; addPredicateNode(parent, nodes, treeCounters, isNegated, path, new Predicate<>(isRepeated, new LikeCondition(likeExpr.getPattern(namedParameters), likeExpr.getEscapeChar()))); } else { throw new IllegalStateException("Unexpected condition type (" + condition.getClass().getSimpleName() + "): " + condition); } } private void addPredicateNode(BENode parent, List<BENode> nodes, List<Integer> treeCounters, boolean isNegated, List<AttributeId> path, Predicate predicate) { PredicateNode predicateNode = new PredicateNode<>(parent, predicate, isNegated, path); int size = nodes.size(); predicateNode.setLocation(size, size + 1); nodes.add(predicateNode); treeCounters.add(1); } private void makeBooleanOperatorNode(BooleanOperatorExpr child, List<BENode> nodes, List<Integer> treeCounters, BENode node, Map<String, Object> namedParameters) { int index = nodes.size(); nodes.add(node); List<BooleanExpr> children = child.getChildren(); treeCounters.add(children.size()); for (BooleanExpr c : children) { preorderTraversal(node, c, nodes, treeCounters, namedParameters); } node.setLocation(index, nodes.size()); } }
8,675
54.261146
186
java
null
infinispan-main/object-filter/src/main/java/org/infinispan/objectfilter/impl/predicateindex/be/BETree.java
package org.infinispan.objectfilter.impl.predicateindex.be; /** * Boolean expression tree representation. A tree is immutable and could be shared by multiple filters. * * @author anistor@redhat.com * @since 7.0 */ public final class BETree { // Values 0 and -1 in the copy of childCounters used during evaluation are boolean, anything > 0 is undecided yet public static final int EXPR_TRUE = 0; public static final int EXPR_FALSE = -1; /** * The tree is represented by the array of its nodes listed in pre-order, thus the first node is always the root. A * valid tree must be non-empty. */ private final BENode[] nodes; /** * The number of direct children of each node. This array is not mutated. A copy of it is made during evaluation. * When evaluating the tree the number of children is decremented every time a child is found to have a definite * value. If the counter becomes 0 then the node is considered satisfied (TRUE). If during evaluation we find a node * to be unsatisfied we mark it and all children with -1 (FALSE). */ private final int[] childCounters; public BETree(BENode[] nodes, int[] childCounters) { this.nodes = nodes; this.childCounters = childCounters; } public BENode[] getNodes() { return nodes; } public int[] getChildCounters() { return childCounters; } }
1,391
32.142857
119
java
null
infinispan-main/object-filter/src/main/java/org/infinispan/objectfilter/impl/logging/Log.java
package org.infinispan.objectfilter.impl.logging; import java.util.List; import org.infinispan.objectfilter.ParsingException; import org.jboss.logging.BasicLogger; import org.jboss.logging.annotations.Cause; import org.jboss.logging.annotations.Message; import org.jboss.logging.annotations.MessageLogger; /** * Log messages for the object filter parser backend. For this module, message ids ranging * from 28501 to 29000 inclusively have been reserved. * * @author anistor@redhat.com * @since 7.0 */ @MessageLogger(projectCode = "ISPN") public interface Log extends BasicLogger { @Message(id = 28501, value = "The type %s does not have an accessible property named '%s'.") ParsingException getNoSuchPropertyException(String typeName, String propertyName); @Message(id = 28502, value = "Unknown alias: %s.") ParsingException getUnknownAliasException(String unknownAlias); @Message(id = 28503, value = "Property %2$s can not be selected from type %1$s since it is an embedded entity.") ParsingException getProjectionOfCompleteEmbeddedEntitiesNotSupportedException(String typeName, String propertyPath); @Message(id = 28504, value = "The property %s is an embedded entity and does not allow comparison predicates") ParsingException getPredicatesOnCompleteEmbeddedEntitiesNotAllowedException(String propertyPath); @Message(id = 28505, value = "Invalid numeric literal '%s'") ParsingException getInvalidNumericLiteralException(String value); @Message(id = 28506, value = "Invalid date literal '%s'") ParsingException getInvalidDateLiteralException(String value); @Message(id = 28507, value = "Invalid boolean literal '%s'") ParsingException getInvalidBooleanLiteralException(String value); @Message(id = 28508, value = "Invalid enum literal '%s' for enum type %s") ParsingException getInvalidEnumLiteralException(String value, String enumType); @Message(id = 28509, value = "Filters cannot use grouping or aggregations") ParsingException getFiltersCannotUseGroupingOrAggregationException(); @Message(id = 28510, value = "Unknown entity name %s") IllegalStateException getUnknownEntity(String entityType); @Message(id = 28511, value = "namedParameters cannot be null") IllegalArgumentException getNamedParametersCannotBeNull(); @Message(id = 28512, value = "Aggregation %s is not supported") IllegalStateException getAggregationTypeNotSupportedException(String aggregationType); @Message(id = 28513, value = "Aggregation AVG cannot be applied to property of type %s") IllegalStateException getAVGCannotBeAppliedToPropertyOfType(String typeName); @Message(id = 28514, value = "%s aggregation can only be applied to property references.") ParsingException getAggregationCanOnlyBeAppliedToPropertyReferencesException(String aggregationType); @Message(id = 28515, value = "Cannot have aggregate functions in the WHERE clause : %s.") ParsingException getNoAggregationsInWhereClauseException(String aggregationType); @Message(id = 28516, value = "Cannot have aggregate functions in the GROUP BY clause : %s.") ParsingException getNoAggregationsInGroupByClauseException(String aggregationType); @Message(id = 28517, value = "The predicate %s can not be added since there may be only one root predicate.") IllegalStateException getNotMoreThanOnePredicateInRootOfWhereClauseAllowedException(Object predicate); @Message(id = 28518, value = "The predicate %s can not be added since there may be only one sub-predicate in a NOT predicate.") IllegalStateException getNotMoreThanOnePredicateInNegationAllowedException(Object predicate); @Message(id = 28519, value = "Cannot apply predicates directly to an entity alias: %s") ParsingException getPredicatesOnEntityAliasNotAllowedException(String alias); @Message(id = 28520, value = "Full-text queries are not allowed in the HAVING clause") ParsingException getFullTextQueriesNotAllowedInHavingClauseException(); @Message(id = 28521, value = "Full-text queries cannot be applied to property '%2$s' in type %1$s unless the property is indexed and analyzed.") ParsingException getFullTextQueryOnNotAalyzedPropertyNotSupportedException(String typeName, String propertyName); @Message(id = 28522, value = "No relational queries can be applied to property '%2$s' in type %1$s since the property is analyzed.") ParsingException getQueryOnAnalyzedPropertyNotSupportedException(String typeName, String propertyName); @Message(id = 28523, value = "Filters cannot use full-text searches") ParsingException getFiltersCannotUseFullTextSearchException(); @Message(id = 28524, value = "Left side argument must be a property path") ParsingException getLeftSideMustBeAPropertyPath(); @Message(id = 28525, value = "Invalid query: %s") ParsingException getQuerySyntaxException(String query, @Cause Throwable cause); @Message(id = 28526, value = "Invalid query: %s; Parser error messages: %s.") ParsingException getQuerySyntaxException(String query, List<?> parserErrorMessages); @Message(id = 28527, value = "Full-text queries cannot be applied to property '%2$s' in type %1$s unless the property is indexed.") ParsingException getFullTextQueryOnNotIndexedPropertyNotSupportedException(String typeName, String propertyName); @Message(id = 28528, value = "Error parsing content. Data not stored as protobuf?") ParsingException errorParsingProtobuf(@Cause Exception e); }
5,487
51.266667
147
java
null
infinispan-main/object-filter/src/main/java/org/infinispan/objectfilter/impl/util/DateHelper.java
package org.infinispan.objectfilter.impl.util; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.TimeZone; /** * @author anistor@redhat.com * @since 8.1 */ public final class DateHelper { private static final String DATE_FORMAT = "yyyyMMddHHmmssSSS"; //todo [anistor] is there a standard jpa time format? private static final TimeZone GMT_TZ = TimeZone.getTimeZone("GMT"); private DateHelper() { } public static DateFormat getJpaDateFormat() { SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT); dateFormat.setTimeZone(GMT_TZ); return dateFormat; } }
642
23.730769
121
java
null
infinispan-main/object-filter/src/main/java/org/infinispan/objectfilter/impl/util/IntervalTree.java
package org.infinispan.objectfilter.impl.util; import java.util.ArrayList; import java.util.List; /** * An Interval tree is an ordered tree data structure to hold {@link Interval}s. Specifically, it allows one to * efficiently find all {@link Interval}s that contain any given value in O(log n) time * (http://en.wikipedia.org/wiki/Interval_tree). * <p/> * The implementation is based on red-black trees (http://en.wikipedia.org/wiki/Red–black_tree). Additions and removals * are efficient and require only minimal rebalancing of the tree as opposed to other implementation approaches that * perform a full rebuild after insertion. Duplicate intervals are not stored but are coped for. * * @author anistor@redhat.com * @since 7.0 */ public final class IntervalTree<K extends Comparable<K>, V> { public static final class Node<K extends Comparable<K>, V> { /** * The interval. The low value is the key of this node within the search tree. */ public final Interval<K> interval; //todo maybe it's wise to make it private and expose getter /** * A user payload value. */ public V value; //todo maybe it's wise to make it private and expose getter and setter /** * The maximum value of any Interval endpoint stored in the subtree rooted at this node. */ private K max; /** * The parent node. */ private Node<K, V> parent; /** * The left child. */ private Node<K, V> left; /** * The right child. */ private Node<K, V> right; /** * Indicates the color of this node (either red or black). */ private boolean isRed = false; private Node(Interval<K> interval) { this.interval = interval; this.max = interval.up; } private Node() { interval = null; } } private final Node<K, V> sentinel; /** * The root of the tree. */ private Node<K, V> root; public IntervalTree() { sentinel = new Node<>(); sentinel.left = sentinel; sentinel.right = sentinel; sentinel.parent = sentinel; root = sentinel; } private int compare(K k1, K k2) { if (k1 == Interval.getMinusInf() || k2 == Interval.getPlusInf()) return -1; if (k1 == Interval.getPlusInf() || k2 == Interval.getMinusInf()) return 1; return k1.compareTo(k2); } private K max(K k1, K k2) { return compare(k1, k2) >= 0 ? k1 : k2; } private boolean compareLowerBound(Interval<K> i1, Interval<K> i2) { int res = compare(i1.low, i2.low); return res < 0 || res == 0 && (i1.includeLower || !i2.includeUpper); } /** * Compare two {@link Interval}s. * * @return a negative integer, zero, or a positive integer depending if {@link Interval} i1 is to the left of i2, overlaps * with it, or is to the right of i2. */ private int compareIntervals(Interval<K> i1, Interval<K> i2) { int res1 = compare(i1.up, i2.low); if (res1 < 0 || res1 <= 0 && (!i1.includeUpper || !i2.includeLower)) { return -1; } int res2 = compare(i2.up, i1.low); if (res2 < 0 || res2 <= 0 && (!i2.includeUpper || !i1.includeLower)) { return 1; } return 0; } private void checkValidInterval(Interval<K> interval) { if (interval == null) { throw new IllegalArgumentException("Interval cannot be null"); } if (compare(interval.low, interval.up) > 0) { throw new IllegalArgumentException("Interval lower bound cannot be higher than the upper bound"); } } /** * Add the {@link Interval} into this {@link IntervalTree} and return the Node. Possible duplicates are found and the * existing Node is returned instead of adding a new one. * * @param i an {@link Interval} to be inserted */ public Node<K, V> add(Interval<K> i) { checkValidInterval(i); return add(new Node<>(i)); } private Node<K, V> add(Node<K, V> n) { n.left = n.right = sentinel; Node<K, V> y = root; Node<K, V> x = root != null ? root.left : null; while (x != sentinel) { y = x; if (n.interval.equals(x.interval)) { return x; } if (compareLowerBound(n.interval, y.interval)) { x = x.left; } else { x = x.right; } y.max = max(n.max, y.max); if (y.parent == root) { root.max = y.max; } } n.parent = y; if (root != null && y == root) { root.max = n.max; } if (y != null) { if (y == root || compareLowerBound(n.interval, y.interval)) { y.left = n; } else { y.right = n; } } rebalanceAfterAdd(n); return n; } private void rebalanceAfterAdd(Node<K, V> z) { z.isRed = true; while (z.parent.isRed) { if (z.parent == z.parent.parent.left) { Node<K, V> y = z.parent.parent.right; if (y.isRed) { z.parent.isRed = false; y.isRed = false; z.parent.parent.isRed = true; z = z.parent.parent; } else { if (z == z.parent.right) { z = z.parent; rotateLeft(z); } z.parent.isRed = false; z.parent.parent.isRed = true; rotateRight(z.parent.parent); } } else { Node<K, V> y = z.parent.parent.left; if (y.isRed) { z.parent.isRed = false; y.isRed = false; z.parent.parent.isRed = true; z = z.parent.parent; } else { if (z == z.parent.left) { z = z.parent; rotateRight(z); } z.parent.isRed = false; z.parent.parent.isRed = true; rotateLeft(z.parent.parent); } } } root.left.isRed = false; } private void rotateLeft(Node<K, V> x) { Node<K, V> y = x.right; x.right = y.left; if (y.left != sentinel) { y.left.parent = x; } y.parent = x.parent; if (x == x.parent.left) { x.parent.left = y; } else { x.parent.right = y; } y.left = x; x.parent = y; if (y.parent == root) { root.max = x.max; } y.max = x.max; x.max = max(x.interval.up, max(x.left.max, x.right.max)); } private void rotateRight(Node<K, V> x) { Node<K, V> y = x.left; x.left = y.right; if (y.right != sentinel) { y.right.parent = x; } y.parent = x.parent; if (x == x.parent.left) { x.parent.left = y; } else { x.parent.right = y; } y.right = x; x.parent = y; if (y.parent == root) { root.max = x.max; } y.max = x.max; x.max = max(x.interval.up, max(x.left.max, x.right.max)); } /** * Removes the {@link Interval}. * * @param i the interval to remove */ public boolean remove(Interval<K> i) { checkValidInterval(i); return remove(root.left, i); } private boolean remove(Node<K, V> n, Interval<K> i) { if (n == sentinel || compare(i.low, n.max) > 0) { return false; } if (n.interval.equals(i)) { remove(n); return true; } if (n.left != sentinel && remove(n.left, i)) { return true; } if (compareIntervals(i, n.interval) < 0) { return false; } return n.right != sentinel && remove(n.right, i); } public void remove(Node<K, V> n) { n.max = Interval.getMinusInf(); for (Node<K, V> i = n.parent; i != root; i = i.parent) { i.max = max(i.left.max, i.right.max); if (i.parent == root) { root.max = i.max; } } Node<K, V> y; Node<K, V> x; if (n.left == sentinel || n.right == sentinel) { y = n; } else { y = findSuccessor(n); } if (y.left == sentinel) { x = y.right; } else { x = y.left; } x.parent = y.parent; if (root == x.parent) { root.left = x; } else if (y == y.parent.left) { y.parent.left = x; } else { y.parent.right = x; } if (y != n) { if (!y.isRed) { rebalanceAfterRemove(x); } y.left = n.left; y.right = n.right; y.parent = n.parent; y.isRed = n.isRed; n.left.parent = n.right.parent = y; if (n == n.parent.left) { n.parent.left = y; } else { n.parent.right = y; } } else if (!y.isRed) { rebalanceAfterRemove(x); } } private Node<K, V> findSuccessor(Node<K, V> x) { Node<K, V> successor = x.right; if (successor != sentinel) { while (successor.left != sentinel) { successor = successor.left; } return successor; } successor = x.parent; while (x == successor.right) { x = successor; successor = successor.parent; } if (successor == root) { return sentinel; } return successor; } private void rebalanceAfterRemove(Node<K, V> x) { while (x != root.left && !x.isRed) { if (x == x.parent.left) { Node<K, V> w = x.parent.right; if (w.isRed) { w.isRed = false; x.parent.isRed = true; rotateLeft(x.parent); w = x.parent.right; } if (!w.left.isRed && !w.right.isRed) { w.isRed = true; x = x.parent; } else { if (!w.right.isRed) { w.left.isRed = false; w.isRed = true; rotateRight(w); w = x.parent.right; } w.isRed = x.parent.isRed; x.parent.isRed = false; w.right.isRed = false; rotateLeft(x.parent); x = root.left; } } else { Node<K, V> w = x.parent.left; if (w.isRed) { w.isRed = false; x.parent.isRed = true; rotateRight(x.parent); w = x.parent.left; } if (!w.right.isRed && !w.left.isRed) { w.isRed = true; x = x.parent; } else { if (!w.left.isRed) { w.right.isRed = false; w.isRed = true; rotateLeft(w); w = x.parent.left; } w.isRed = x.parent.isRed; x.parent.isRed = false; w.left.isRed = false; rotateRight(x.parent); x = root.left; } } } x.isRed = false; } /** * Checks if this {@link IntervalTree} does not have any Intervals. * * @return {@code true} if this {@link IntervalTree} is empty, {@code false} otherwise. */ public boolean isEmpty() { return root.left == sentinel; } /** * Find all {@link Interval}s that contain a given value. * * @param k the value to search for * @return a non-null List of intervals that contain the value */ public List<Node<K, V>> stab(K k) { Interval<K> i = new Interval<>(k, true, k, true); final List<Node<K, V>> nodes = new ArrayList<>(); findOverlap(root.left, i, node -> nodes.add(node)); return nodes; } public void stab(K k, NodeCallback<K, V> nodeCallback) { Interval<K> i = new Interval<>(k, true, k, true); findOverlap(root.left, i, nodeCallback); } private void findOverlap(Node<K, V> n, Interval<K> i, NodeCallback<K, V> nodeCallback) { if (n == sentinel || compare(i.low, n.max) > 0) { return; } if (n.left != sentinel) { findOverlap(n.left, i, nodeCallback); } if (compareIntervals(n.interval, i) == 0) { nodeCallback.handle(n); } if (compareIntervals(i, n.interval) < 0) { return; } if (n.right != sentinel) { findOverlap(n.right, i, nodeCallback); } } public Node<K, V> findNode(Interval<K> i) { checkValidInterval(i); return findNode(root.left, i); } private Node<K, V> findNode(Node<K, V> n, Interval<K> i) { if (n == sentinel || compare(i.low, n.max) > 0) { return null; } if (n.interval.equals(i)) { return n; } if (n.left != sentinel) { Node<K, V> w = findNode(n.left, i); if (w != null) { return w; } } if (compareIntervals(i, n.interval) < 0) { return null; } if (n.right != sentinel) { return findNode(n.right, i); } return null; } @FunctionalInterface public interface NodeCallback<K extends Comparable<K>, V> { void handle(Node<K, V> node); } public void inorderTraversal(NodeCallback<K, V> nodeCallback) { inorderTraversal(root.left, nodeCallback); } private void inorderTraversal(Node<K, V> n, NodeCallback<K, V> nodeCallback) { if (n != sentinel) { inorderTraversal(n.left, nodeCallback); nodeCallback.handle(n); inorderTraversal(n.right, nodeCallback); } } @Override public String toString() { StringBuilder sb = new StringBuilder(); inorderTraversal(n -> { if (sb.length() > 0) { sb.append(", "); } sb.append(n.interval).append("->{").append(n.value).append('}'); }); return sb.toString(); } }
14,061
25.887189
125
java
null
infinispan-main/object-filter/src/main/java/org/infinispan/objectfilter/impl/util/ArrayIterator.java
package org.infinispan.objectfilter.impl.util; import java.lang.reflect.Array; import java.util.Iterator; import java.util.NoSuchElementException; /** * An immutable {@link Iterator} for arrays. * * @author anistor@redhat.com * @since 7.0 */ final class ArrayIterator<T> implements Iterator<T> { /** * An array of whatever type. */ private final Object array; /** * Current position. */ private int pos = 0; ArrayIterator(Object array) { if (array == null) { throw new IllegalArgumentException("Argument cannot be null"); } if (!array.getClass().isArray()) { throw new IllegalArgumentException("Argument is expected to be an array"); } this.array = array; } @Override public boolean hasNext() { return pos < Array.getLength(array); } @Override public T next() { try { return (T) Array.get(array, pos++); } catch (ArrayIndexOutOfBoundsException e) { throw new NoSuchElementException(e.getMessage()); } } }
1,059
20.632653
83
java
null
infinispan-main/object-filter/src/main/java/org/infinispan/objectfilter/impl/util/StringHelper.java
package org.infinispan.objectfilter.impl.util; import java.util.Arrays; /** * @author anistor@redhat.com * @since 7.0 */ public final class StringHelper { private StringHelper() { } public static String join(String[] array) { return String.join(".", Arrays.asList(array)); } public static String[] split(String propertyPath) { return propertyPath.split("[.]"); } }
403
17.363636
54
java
null
infinispan-main/object-filter/src/main/java/org/infinispan/objectfilter/impl/util/ReflectionHelper.java
package org.infinispan.objectfilter.impl.util; import java.lang.reflect.Field; import java.lang.reflect.GenericArrayType; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.lang.reflect.TypeVariable; import java.util.Collection; import java.util.Iterator; import java.util.Map; /** * @author anistor@redhat.com * @since 7.0 */ public final class ReflectionHelper { public interface PropertyAccessor { //todo [anistor] use this info to validate the query uses the types correctly Class<?> getPropertyType(); /** * Indicates if this is a repeated property (ie. array or collection). */ boolean isMultiple(); Object getValue(Object instance); /** * Obtains an Iterator over the values of an array, collection or map attribute. * * @param instance the target instance for accessing the attribute * @return the Iterator or null if the attribute is null */ Iterator<Object> getValueIterator(Object instance); /** * Get the accessor of a nested property. * * @param propName the name of the nested property * @return the accessor of the nested property * @throws ReflectiveOperationException if the nested property was not found */ PropertyAccessor getAccessor(String propName) throws ReflectiveOperationException; } private abstract static class BasePropertyAccessor implements PropertyAccessor { @Override public PropertyAccessor getAccessor(String propName) throws ReflectiveOperationException { return ReflectionHelper.getAccessor(getPropertyType(), propName); } } private static class FieldPropertyAccessor extends BasePropertyAccessor { protected final Field field; FieldPropertyAccessor(Field field) { this.field = field; field.setAccessible(true); } @Override public Class<?> getPropertyType() { return field.getType(); } public boolean isMultiple() { return false; } public Object getValue(Object instance) { try { return field.get(instance); } catch (IllegalAccessException e) { throw new RuntimeException(e); } } public Iterator<Object> getValueIterator(Object instance) { throw new UnsupportedOperationException("This property cannot be iterated"); } } private static final class ArrayFieldPropertyAccessor extends FieldPropertyAccessor { ArrayFieldPropertyAccessor(Field field) { super(field); } public boolean isMultiple() { return true; } public Iterator<Object> getValueIterator(Object instance) { Object value = getValue(instance); return value == null ? null : new ArrayIterator<>(value); } @Override public Class<?> getPropertyType() { return determineElementType(field.getType(), field.getGenericType()); } } private static final class CollectionFieldPropertyAccessor extends FieldPropertyAccessor { CollectionFieldPropertyAccessor(Field field) { super(field); } public boolean isMultiple() { return true; } public Iterator<Object> getValueIterator(Object instance) { Object value = getValue(instance); return value == null ? null : ((Collection) value).iterator(); } @Override public Class<?> getPropertyType() { return determineElementType(field.getType(), field.getGenericType()); } } private static final class MapFieldPropertyAccessor extends FieldPropertyAccessor { MapFieldPropertyAccessor(Field field) { super(field); } public boolean isMultiple() { return true; } public Iterator<Object> getValueIterator(Object instance) { Object value = getValue(instance); return value == null ? null : ((Map<?, Object>) value).values().iterator(); } @Override public Class<?> getPropertyType() { return determineElementType(field.getType(), field.getGenericType()); } } private static class MethodPropertyAccessor extends BasePropertyAccessor { protected final Method method; MethodPropertyAccessor(Method method) { this.method = method; method.setAccessible(true); } @Override public Class<?> getPropertyType() { return method.getReturnType(); } public boolean isMultiple() { return false; } public Object getValue(Object instance) { try { return method.invoke(instance); } catch (IllegalAccessException | InvocationTargetException e) { throw new RuntimeException(e); } } public Iterator<Object> getValueIterator(Object instance) { throw new UnsupportedOperationException("This property cannot be iterated"); } } private static final class ArrayMethodPropertyAccessor extends MethodPropertyAccessor { ArrayMethodPropertyAccessor(Method method) { super(method); } public boolean isMultiple() { return true; } public Iterator<Object> getValueIterator(Object instance) { Object value = getValue(instance); return value == null ? null : new ArrayIterator<>(value); } @Override public Class<?> getPropertyType() { return determineElementType(method.getReturnType(), method.getGenericReturnType()); } } private static final class CollectionMethodPropertyAccessor extends MethodPropertyAccessor { CollectionMethodPropertyAccessor(Method method) { super(method); } public boolean isMultiple() { return true; } public Iterator<Object> getValueIterator(Object instance) { Object value = getValue(instance); return value == null ? null : ((Collection<Object>) value).iterator(); } @Override public Class<?> getPropertyType() { return determineElementType(method.getReturnType(), method.getGenericReturnType()); } } private static final class MapMethodPropertyAccessor extends MethodPropertyAccessor { MapMethodPropertyAccessor(Method method) { super(method); } public boolean isMultiple() { return true; } public Iterator<Object> getValueIterator(Object instance) { Object value = getValue(instance); return value == null ? null : ((Map<?, Object>) value).values().iterator(); } @Override public Class<?> getPropertyType() { return determineElementType(method.getReturnType(), method.getGenericReturnType()); } } private ReflectionHelper() { } public static PropertyAccessor getAccessor(Class<?> clazz, String propertyName) throws ReflectiveOperationException { if (propertyName == null || propertyName.length() == 0) { throw new IllegalArgumentException("Property name cannot be null or empty"); } if (propertyName.indexOf('.') != -1) { throw new IllegalArgumentException("The argument cannot be a nested property name"); } String propertyNameSuffix = Character.toUpperCase(propertyName.charAt(0)) + propertyName.substring(1); Class<?> c = clazz; while (c != null) { PropertyAccessor m = getAccessor(c, propertyName, propertyNameSuffix); if (m != null) { return m; } c = c.getSuperclass(); } throw new ReflectiveOperationException("Property not found: " + propertyName); } private static PropertyAccessor getAccessor(Class<?> clazz, String propertyName, String propertyNameSuffix) { // try getter method access // we need to find a no-arg public "getXyz" or "isXyz" method which has a suitable return type try { Method m = clazz.getDeclaredMethod("get" + propertyNameSuffix); if (Modifier.isPublic(m.getModifiers()) && !m.getReturnType().equals(Void.class)) { return getMethodAccessor(m); } } catch (NoSuchMethodException e) { try { Method m = clazz.getDeclaredMethod("is" + propertyNameSuffix); if (Modifier.isPublic(m.getModifiers()) && (boolean.class.equals(m.getReturnType()) || Boolean.class.equals(m.getReturnType()))) { return getMethodAccessor(m); } } catch (NoSuchMethodException e1) { // ignored, continue } } // try field access try { Field f = clazz.getDeclaredField(propertyName); if (f != null && !f.isSynthetic()) { return getFieldAccessor(f); } } catch (NoSuchFieldException e) { // ignored, continue } return null; } private static PropertyAccessor getFieldAccessor(Field f) { Class<?> fieldClass = f.getType(); if (fieldClass.isArray()) { return new ArrayFieldPropertyAccessor(f); } else if (Collection.class.isAssignableFrom(fieldClass)) { return new CollectionFieldPropertyAccessor(f); } else if (Map.class.isAssignableFrom(fieldClass)) { return new MapFieldPropertyAccessor(f); } return new FieldPropertyAccessor(f); } private static PropertyAccessor getMethodAccessor(Method m) { Class<?> fieldClass = m.getReturnType(); if (fieldClass.isArray()) { return new ArrayMethodPropertyAccessor(m); } else if (Collection.class.isAssignableFrom(fieldClass)) { return new CollectionMethodPropertyAccessor(m); } else if (Map.class.isAssignableFrom(fieldClass)) { return new MapMethodPropertyAccessor(m); } return new MethodPropertyAccessor(m); } private static Class determineElementType(Class<?> type, Type genericType) { if (type.isArray()) { if (genericType instanceof Class) { return type.getComponentType(); } GenericArrayType genericArrayType = (GenericArrayType) genericType; Type genericComponentType = genericArrayType.getGenericComponentType(); if (genericComponentType instanceof ParameterizedType) { return (Class) ((ParameterizedType) genericComponentType).getRawType(); } else { return (Class) ((TypeVariable) genericComponentType).getBounds()[0]; } } else if (Collection.class.isAssignableFrom(type)) { return determineCollectionElementType(genericType); } else if (Map.class.isAssignableFrom(type)) { return determineMapValueTypeParam(genericType); } return null; } private static Class determineMapValueTypeParam(Type genericType) { if (genericType instanceof ParameterizedType) { ParameterizedType type = (ParameterizedType) genericType; Type fieldArgType = type.getActualTypeArguments()[1]; if (fieldArgType instanceof TypeVariable) { TypeVariable genericComponentType = (TypeVariable) fieldArgType; return (Class) genericComponentType.getBounds()[0]; } else { return (Class) fieldArgType; } } else if (genericType instanceof Class) { Class c = (Class) genericType; if (c.getGenericSuperclass() != null && Map.class.isAssignableFrom(c.getSuperclass())) { Class x = determineMapValueTypeParam(c.getGenericSuperclass()); if (x != null) { return x; } } for (Type t : c.getGenericInterfaces()) { if (t instanceof Class && Map.class.isAssignableFrom((Class<?>) t) || t instanceof ParameterizedType && Map.class.isAssignableFrom((Class) ((ParameterizedType) t).getRawType())) { Class x = determineMapValueTypeParam(t); if (x != null) { return x; } } } } return null; } private static Class determineCollectionElementType(Type genericType) { if (genericType instanceof ParameterizedType) { ParameterizedType type = (ParameterizedType) genericType; Type fieldArgType = type.getActualTypeArguments()[0]; if (fieldArgType instanceof Class) { return (Class) fieldArgType; } return (Class) ((ParameterizedType) fieldArgType).getRawType(); } else if (genericType instanceof Class) { Class c = (Class) genericType; if (c.getGenericSuperclass() != null && Collection.class.isAssignableFrom(c.getSuperclass())) { Class x = determineCollectionElementType(c.getGenericSuperclass()); if (x != null) { return x; } } for (Type t : c.getGenericInterfaces()) { if (t instanceof Class && Map.class.isAssignableFrom((Class<?>) t) || t instanceof ParameterizedType && Collection.class.isAssignableFrom((Class) ((ParameterizedType) t).getRawType())) { Class x = determineCollectionElementType(t); if (x != null) { return x; } } } } return null; } }
13,506
32.186732
142
java
null
infinispan-main/object-filter/src/main/java/org/infinispan/objectfilter/impl/util/ComparableArrayComparator.java
package org.infinispan.objectfilter.impl.util; import java.util.Comparator; /** * @author anistor@redhat.com * @since 7.0 */ public final class ComparableArrayComparator implements Comparator<Comparable<?>[]> { private final boolean[] direction; /** * Constructs a comparator based on a direction boolean array. The length of the array must match the {@link * Comparable} arrays we are supposed to handle. * * @param direction an array of booleans indicating direction (true indicates ascending order) */ public ComparableArrayComparator(boolean[] direction) { if (direction == null) { throw new IllegalArgumentException("direction array cannot be null"); } this.direction = direction; } @Override public int compare(Comparable<?>[] array1, Comparable<?>[] array2) { if (array1 == null || array2 == null) { throw new IllegalArgumentException("arguments cannot be null"); } if (array1.length != direction.length || array2.length != direction.length) { throw new IllegalArgumentException("argument arrays must have the same size as the direction array"); } for (int i = 0; i < direction.length; i++) { int r = compareElements(array1[i], array2[i]); if (r != 0) { return direction[i] ? r : -r; } } return 0; } private static int compareElements(Comparable o1, Comparable o2) { if (o1 == null) { return o2 == null ? 0 : -1; } else if (o2 == null) { return 1; } return o1.compareTo(o2); } }
1,611
29.415094
111
java
null
infinispan-main/object-filter/src/main/java/org/infinispan/objectfilter/impl/util/Interval.java
package org.infinispan.objectfilter.impl.util; /** * Represents an interval of values of type K. K is not restricted to be a Comparable type here, but the IntervalTree * must be able to compare values of type K using its Comparator. * * @param <K> the key value type * @author anistor@redhat.com * @since 7.0 */ public final class Interval<K extends Comparable<K>> { public static <K extends Comparable<K>> K getMinusInf() { return (K) MINUS_INF; } public static <K extends Comparable<K>> K getPlusInf() { return (K) PLUS_INF; } /** * Placeholder for the smallest possible value. */ private static final Comparable MINUS_INF = new Comparable() { @Override public String toString() { return "-INF"; } @Override public int compareTo(Object obj) { return obj == this ? 0 : -1; } @Override public boolean equals(Object obj) { return obj == this; } }; /** * Placeholder for the greatest possible value. */ private static final Comparable PLUS_INF = new Comparable() { @Override public String toString() { return "+INF"; } @Override public int compareTo(Object obj) { return obj == this ? 0 : 1; } @Override public boolean equals(Object obj) { return obj == this; } }; /** * The lower bound. */ public final K low; /** * Indicates if the interval is closed in the lower bound. */ public final boolean includeLower; /** * The upper bound. */ public final K up; /** * Indicates if the interval is closed in the upper bound. */ public final boolean includeUpper; public Interval(K low, boolean includeLower, K up, boolean includeUpper) { if (low == null || up == null) { throw new IllegalArgumentException("arguments cannot be null"); } this.low = low; this.includeLower = includeLower; this.up = up; this.includeUpper = includeUpper; } public boolean contains(K value) { return (includeLower ? low.compareTo(value) <= 0 : low.compareTo(value) < 0) && (includeUpper ? up.compareTo(value) >= 0 : up.compareTo(value) > 0); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null || getClass() != obj.getClass()) return false; Interval other = (Interval) obj; return includeLower == other.includeLower && includeUpper == other.includeUpper && low.equals(other.low) && up.equals(other.up); } @Override public int hashCode() { int result = low.hashCode(); result = 31 * result + (includeLower ? 1 : 0); result = 31 * result + up.hashCode(); result = 31 * result + (includeUpper ? 1 : 0); return result; } @Override public String toString() { return (includeLower ? "[" : "(") + low + ", " + up + (includeUpper ? "]" : ")"); } }
3,040
24.132231
117
java
null
infinispan-main/object-filter/src/main/java/org/infinispan/objectfilter/impl/ql/QueryResolverDelegate.java
/* * Copyright 2016, Red Hat Inc. and/or its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.infinispan.objectfilter.impl.ql; import org.antlr.runtime.tree.Tree; /** * Defines hooks for implementing custom logic when walking the parse tree of a JPQL query. * * @author Gunnar Morling * @author anistor@redhat.com * @since 9.0 */ public interface QueryResolverDelegate<TypeDescriptor> { void registerPersisterSpace(String entityName, Tree alias); void registerJoinAlias(Tree alias, PropertyPath<TypeDescriptor> path); boolean isUnqualifiedPropertyReference(); PropertyPath.PropertyReference<TypeDescriptor> normalizeUnqualifiedPropertyReference(Tree propertyNameTree); boolean isPersisterReferenceAlias(); PropertyPath.PropertyReference<TypeDescriptor> normalizeUnqualifiedRoot(Tree aliasTree); PropertyPath.PropertyReference<TypeDescriptor> normalizeQualifiedRoot(Tree root); PropertyPath.PropertyReference<TypeDescriptor> normalizePropertyPathIntermediary(PropertyPath<TypeDescriptor> path, Tree propertyNameTree); PropertyPath.PropertyReference<TypeDescriptor> normalizeIntermediateIndexOperation(PropertyPath.PropertyReference<TypeDescriptor> propertyReference, Tree collectionProperty, Tree selector); void normalizeTerminalIndexOperation(PropertyPath.PropertyReference<TypeDescriptor> propertyReference, Tree collectionProperty, Tree selector); PropertyPath.PropertyReference<TypeDescriptor> normalizeUnqualifiedPropertyReferenceSource(Tree identifier); PropertyPath.PropertyReference<TypeDescriptor> normalizePropertyPathTerminus(PropertyPath<TypeDescriptor> path, Tree propertyNameTree); void activateFromStrategy(JoinType joinType, Tree associationFetchTree, Tree propertyFetchTree, Tree alias); void activateSelectStrategy(); void activateDeleteStrategy(); void deactivateStrategy(); /** * Notifies this delegate when parsing of a property path in the SELECT or WHERE is completed. * * @param path the completely parsed property path */ void propertyPathCompleted(PropertyPath<TypeDescriptor> path); }
2,645
37.911765
192
java
null
infinispan-main/object-filter/src/main/java/org/infinispan/objectfilter/impl/ql/package-info.java
/** * The Ickle query parser. This package handles parsing and provides hooks for semantic analysis but does not implements * them. * * @author anistor@redhat.com * @since 9.0 * @api.private */ package org.infinispan.objectfilter.impl.ql;
246
23.7
120
java
null
infinispan-main/object-filter/src/main/java/org/infinispan/objectfilter/impl/ql/QueryRendererDelegate.java
/* * Copyright 2016, Red Hat Inc. and/or its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.infinispan.objectfilter.impl.ql; import java.util.List; import org.antlr.runtime.tree.Tree; /** * Defines hooks for implementing custom logic when walking the parse tree of a JPQL query. * * @author Gunnar Morling * @author Adrian Nistor * @since 9.0 */ public interface QueryRendererDelegate<TypeDescriptor> { void registerPersisterSpace(String entityName, Tree aliasTree); void registerJoinAlias(Tree aliasTree, PropertyPath<TypeDescriptor> path); boolean isUnqualifiedPropertyReference(); boolean isPersisterReferenceAlias(); void activateFromStrategy(JoinType joinType, Tree associationFetchTree, Tree propertyFetchTree, Tree aliasTree); void activateSelectStrategy(); void activateDeleteStrategy(); void activateWhereStrategy(); void activateGroupByStrategy(); void activateHavingStrategy(); void activateOrderByStrategy(); void deactivateStrategy(); void activateOR(); void activateAND(); void activateNOT(); void deactivateBoolean(); void predicateLess(String value); void predicateLessOrEqual(String value); void predicateEquals(String value); void predicateNotEquals(String value); void predicateGreaterOrEqual(String value); void predicateGreater(String value); void predicateBetween(String lowerValue, String upperValue); void predicateIn(List<String> values); void predicateLike(String patternValue, Character escapeCharacter); void predicateIsNull(); void predicateConstantBoolean(boolean booleanConstant); void predicateFullTextTerm(String term, String fuzzyFlop); void predicateFullTextRegexp(String term); void predicateFullTextRange(boolean includeLower, String lower, String upper, boolean includeUpper); enum Occur { MUST("+"), FILTER("#"), SHOULD(""), MUST_NOT("-"); private final String operator; Occur(String operator) { this.operator = operator; } public String getOperator() { return operator; } } void activateFullTextOccur(Occur occur); void deactivateFullTextOccur(); void activateFullTextBoost(float boost); void deactivateFullTextBoost(); void activateAggregation(AggregationFunction aggregationFunction); void deactivateAggregation(); void projectVersion(); /** * @param collateName optional collation name */ void groupingValue(String collateName); /** * Sets the sort direction, either "asc" or "desc", for the current property. The property was previously * specified by {@link #setPropertyPath(PropertyPath)} * * @param collateName optional collation name * @param isAscending indicates if sorting is ascending or descending */ void sortSpecification(String collateName, boolean isAscending); /** * Sets a property path representing one property in the SELECT, GROUP BY, WHERE or HAVING clause of a given query. * * @param propertyPath the property path to set */ void setPropertyPath(PropertyPath<TypeDescriptor> propertyPath); }
3,705
24.916084
118
java
null
infinispan-main/object-filter/src/main/java/org/infinispan/objectfilter/impl/ql/PropertyPath.java
/* * Copyright 2016, Red Hat Inc. and/or its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.infinispan.objectfilter.impl.ql; import java.util.ArrayList; import java.util.Collections; import java.util.LinkedList; import java.util.List; /** * A property path (e.g. {@code foo.bar.baz}) represented by a {@link List} of {@link PropertyReference}s, used * in a SELECT, GROUP BY, ORDER BY, WHERE or HAVING clause. * * @author Gunnar Morling * @author anistor@redhat.com * @since 9.0 */ public class PropertyPath<TypeDescriptor> { public static final class PropertyReference<TypeDescriptor> { private final String propertyName; private final TypeDescriptor typeDescriptor; private final boolean isAlias; public PropertyReference(String propertyName, TypeDescriptor typeDescriptor, boolean isAlias) { this.propertyName = propertyName; this.typeDescriptor = typeDescriptor; this.isAlias = isAlias; } public String getPropertyName() { return propertyName; } public boolean isAlias() { return isAlias; } public TypeDescriptor getTypeDescriptor() { return typeDescriptor; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || o.getClass() != getClass()) return false; PropertyReference<?> that = (PropertyReference<?>) o; return isAlias == that.isAlias && propertyName.equals(that.propertyName) && (typeDescriptor != null ? typeDescriptor.equals(that.typeDescriptor) : that.typeDescriptor == null); } @Override public int hashCode() { int result = propertyName.hashCode(); result = 31 * result + (isAlias ? 1 : 0); result = 31 * result + (typeDescriptor != null ? typeDescriptor.hashCode() : 0); return result; } @Override public String toString() { return propertyName; } } private final LinkedList<PropertyReference<TypeDescriptor>> nodes; private List<PropertyReference<TypeDescriptor>> unmodifiableNodes; private String asStringPath; private String asStringPathWithoutAlias; private String[] asArrayPath; /** * Creates an empty path. */ public PropertyPath() { this.nodes = new LinkedList<>(); } /** * Creates an path with a given list of nodes. */ public PropertyPath(List<PropertyReference<TypeDescriptor>> nodes) { this.nodes = new LinkedList<>(nodes); } public boolean isAlias() { return getFirst().isAlias(); } public PropertyReference<TypeDescriptor> getFirst() { return nodes.getFirst(); } public PropertyReference<TypeDescriptor> getLast() { return nodes.getLast(); } public List<PropertyReference<TypeDescriptor>> getNodes() { if (unmodifiableNodes == null) { unmodifiableNodes = Collections.unmodifiableList(nodes); } return unmodifiableNodes; } public void append(PropertyReference<TypeDescriptor> propertyReference) { nodes.add(propertyReference); asArrayPath = null; asStringPath = null; asStringPathWithoutAlias = null; } public boolean isEmpty() { return nodes.isEmpty(); } public int getLength() { return nodes.size(); } public String asStringPath() { if (asStringPath == null) { StringBuilder sb = new StringBuilder(); boolean isFirst = true; for (PropertyReference node : nodes) { if (isFirst) { isFirst = false; } else { sb.append('.'); } sb.append(node.getPropertyName()); } asStringPath = sb.toString(); } return asStringPath; } public String asStringPathWithoutAlias() { if (asStringPathWithoutAlias == null) { StringBuilder sb = new StringBuilder(); boolean isFirst = true; for (PropertyReference node : nodes) { if (!node.isAlias()) { if (isFirst) { isFirst = false; } else { sb.append('.'); } sb.append(node.getPropertyName()); } } asStringPathWithoutAlias = sb.toString(); } return asStringPathWithoutAlias; } public String[] asArrayPath() { if (asArrayPath == null) { String[] arrayPath = new String[nodes.size()]; int i = 0; for (PropertyReference<?> pr : nodes) { arrayPath[i++] = pr.getPropertyName(); } asArrayPath = arrayPath; } return asArrayPath; } public List<String> getNodeNamesWithoutAlias() { List<String> list = new ArrayList<>(nodes.size()); for (PropertyReference<TypeDescriptor> node : nodes) { if (!node.isAlias()) { list.add(node.getPropertyName()); } } return list; } public List<PropertyReference<TypeDescriptor>> getNodesWithoutAlias() { List<PropertyReference<TypeDescriptor>> list = new ArrayList<>(nodes.size()); for (PropertyReference<TypeDescriptor> node : nodes) { if (!node.isAlias()) { list.add(node); } } return list; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || o.getClass() != getClass()) return false; PropertyPath<?> that = (PropertyPath<?>) o; return nodes.equals(that.nodes); } @Override public int hashCode() { return nodes.hashCode(); } @Override public String toString() { return asStringPath(); } public static <TypeDescriptor> PropertyPath<TypeDescriptor> make(String propertyPath) { String[] splinters = propertyPath.split("[.]"); List<PropertyReference<TypeDescriptor>> nodes = new ArrayList<>(splinters.length); for (String name : splinters) { nodes.add(new PropertyPath.PropertyReference<>(name, null, false)); } return new PropertyPath<>(nodes); } }
6,688
27.34322
118
java
null
infinispan-main/object-filter/src/main/java/org/infinispan/objectfilter/impl/ql/AggregationFunction.java
/* * Copyright 2016, Red Hat Inc. and/or its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.infinispan.objectfilter.impl.ql; /** * @author anistor@redhat.com * @since 9.0 */ public enum AggregationFunction { SUM, AVG, MIN, MAX, COUNT, COUNT_DISTINCT }
814
26.166667
75
java
null
infinispan-main/object-filter/src/main/java/org/infinispan/objectfilter/impl/ql/JoinType.java
/* * Copyright 2016, Red Hat Inc. and/or its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.infinispan.objectfilter.impl.ql; /** * Represents a canonical join type. * <p/> * Note that currently HQL really only supports inner and left outer joins * (though cross joins can also be achieved). This is because joins in HQL * are always defined in relation to a mapped association. However, when we * start allowing users to specify ad-hoc joins this may need to change to * allow the full spectrum of join types. Thus the others are provided here * currently just for completeness and for future expansion. * * @author Steve Ebersole * @since 9.0 */ public enum JoinType { /** * Represents an inner join. */ INNER("inner"), /** * Represents a left outer join. */ LEFT("left outer"), /** * Represents a right outer join. */ RIGHT("right outer"), /** * Represents a cross join (aka a cartesian product). */ CROSS("cross"), /** * Represents a full join. */ FULL("full"); private final String name; JoinType(String name) { this.name = name; } @Override public String toString() { return name; } }
1,754
24.434783
76
java
null
infinispan-main/object-filter/src/main/java/org/infinispan/objectfilter/impl/ql/QueryParser.java
/* * Copyright 2016, Red Hat Inc. and/or its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.infinispan.objectfilter.impl.ql; import org.antlr.runtime.ANTLRStringStream; import org.antlr.runtime.CommonTokenStream; import org.antlr.runtime.RecognitionException; import org.antlr.runtime.TokenStream; import org.antlr.runtime.tree.CommonTree; import org.antlr.runtime.tree.CommonTreeNodeStream; import org.infinispan.objectfilter.ParsingException; import org.infinispan.objectfilter.impl.logging.Log; import org.infinispan.objectfilter.impl.ql.parse.IckleLexer; import org.infinispan.objectfilter.impl.ql.parse.IckleParser; import org.infinispan.objectfilter.impl.ql.parse.QueryRenderer; import org.infinispan.objectfilter.impl.ql.parse.QueryResolver; import org.jboss.logging.Logger; /** * A parser for Ickle queries. Parsing comprises these steps: * <ul> * <li>lexing the query</li> * <li>parsing the query, building up an AST while doing so</li> * <li>transforming the resulting parse tree using a QueryResolverDelegate and QueryRendererDelegate</li> * </ul> * * @author Gunnar Morling * @author anistor@redhat.com * @since 9.0 */ public final class QueryParser { private static final Log log = Logger.getMessageLogger(Log.class, QueryParser.class.getName()); /** * Parses the given query string. * * @param queryString the query string to parse * @return the result of the parsing after being transformed by the processors * @throws ParsingException in case any exception occurs during parsing */ public CommonTree parseQuery(String queryString, QueryResolverDelegate<?> resolverDelegate, QueryRendererDelegate<?> rendererDelegate) throws ParsingException { IckleLexer lexer = new IckleLexer(new ANTLRStringStream(queryString)); CommonTokenStream tokens = new CommonTokenStream(lexer); IckleParser parser = new IckleParser(tokens); try { // parser.statement() is the entry point for evaluation of any kind of statement IckleParser.statement_return r = parser.statement(); if (parser.hasErrors()) { throw log.getQuerySyntaxException(queryString, parser.getErrorMessages()); } CommonTree tree = (CommonTree) r.getTree(); tree = resolve(tokens, tree, resolverDelegate); tree = render(tokens, tree, rendererDelegate); return tree; } catch (RecognitionException e) { throw log.getQuerySyntaxException(queryString, e); } } // resolves the elements in given source query into an output query, by invoking {@link QueryResolverDelegate} while traversing the given query tree private CommonTree resolve(TokenStream tokens, CommonTree tree, QueryResolverDelegate<?> resolverDelegate) throws RecognitionException { CommonTreeNodeStream treeNodeStream = new CommonTreeNodeStream(tree); treeNodeStream.setTokenStream(tokens); return new QueryResolver(treeNodeStream, resolverDelegate).statement().getTree(); } // render a given source query into an output query, by invoking {@link QueryRendererDelegate} while traversing the given query tree private CommonTree render(TokenStream tokens, CommonTree tree, QueryRendererDelegate<?> rendererDelegate) throws RecognitionException { CommonTreeNodeStream treeNodeStream = new CommonTreeNodeStream(tree); treeNodeStream.setTokenStream(tokens); return new QueryRenderer(treeNodeStream, rendererDelegate).statement().getTree(); } }
4,040
43.406593
163
java
null
infinispan-main/object-filter/src/main/java/org/infinispan/objectfilter/impl/ql/parse/LexerBase.java
package org.infinispan.objectfilter.impl.ql.parse; import java.io.PrintStream; import org.antlr.runtime.CharStream; import org.antlr.runtime.Lexer; import org.antlr.runtime.RecognizerSharedState; /** * Base class for the generated lexer. * * @author anistor@redhat.com * @since 13.0 */ public abstract class LexerBase extends Lexer { private PrintStream errStream; protected LexerBase() { } protected LexerBase(CharStream input, RecognizerSharedState state) { super(input, state); } public void setErrStream(PrintStream errStream) { this.errStream = errStream; } @Override public void emitErrorMessage(String msg) { if (errStream != null) { errStream.println(msg); } } }
747
19.216216
71
java
null
infinispan-main/object-filter/src/main/java/org/infinispan/objectfilter/impl/ql/parse/ConstantLiteralTree.java
/* * Copyright 2016, Red Hat Inc. and/or its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.infinispan.objectfilter.impl.ql.parse; import org.antlr.runtime.tree.CommonTree; /** * A {@link CommonTree} representing a constant literal. * * @since 9.0 */ public final class ConstantLiteralTree extends CommonTree { private final Object literal; public ConstantLiteralTree(int type, CommonTree node, Object literal) { super(node); this.literal = literal; } public Object getLiteral() { return literal; } }
1,083
27.526316
75
java
null
infinispan-main/object-filter/src/main/java/org/infinispan/objectfilter/impl/ql/parse/ParserBase.java
/* * Copyright 2016, Red Hat Inc. and/or its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.infinispan.objectfilter.impl.ql.parse; import java.io.PrintStream; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Deque; import java.util.LinkedList; import java.util.List; import org.antlr.runtime.CommonToken; import org.antlr.runtime.EarlyExitException; import org.antlr.runtime.FailedPredicateException; import org.antlr.runtime.MismatchedNotSetException; import org.antlr.runtime.MismatchedSetException; import org.antlr.runtime.MismatchedTokenException; import org.antlr.runtime.MismatchedTreeNodeException; import org.antlr.runtime.NoViableAltException; import org.antlr.runtime.Parser; import org.antlr.runtime.RecognitionException; import org.antlr.runtime.RecognizerSharedState; import org.antlr.runtime.Token; import org.antlr.runtime.TokenStream; import org.antlr.runtime.tree.CommonTree; import org.antlr.runtime.tree.Tree; import org.antlr.runtime.tree.TreeAdaptor; /** * Base class for the generated parser. This class is stateful, so it should not be reused for parsing multiple * statements. * * @author anistor@redhat.com * @since 9.0 */ abstract class ParserBase extends Parser { private PrintStream errStream; private final Deque<Boolean> enableParameterUsage = new ArrayDeque<>(); private final List<String> errorMessages = new LinkedList<>(); private int unaliasedCount = 0; protected ParserBase(TokenStream input, RecognizerSharedState state) { super(input, state); } protected abstract TreeAdaptor getTreeAdaptor(); protected final Tree generatePersisterSpacesTree(List<?> persisterSpaces) { TreeAdaptor adaptor = getTreeAdaptor(); List<Tree> persisterSpaceList = new ArrayList<>(); for (Tree persistenceSpaceData : (List<Tree>) persisterSpaces) { if (persistenceSpaceData.getType() == IckleLexer.PERSISTER_JOIN || persistenceSpaceData.getType() == IckleLexer.PROPERTY_JOIN) { adaptor.addChild(persisterSpaceList.get(persisterSpaceList.size() - 1), persistenceSpaceData); } else { Tree persistenceSpaceTree = (Tree) adaptor.becomeRoot(adaptor.create(IckleLexer.PERSISTER_SPACE, "PERSISTER_SPACE"), adaptor.nil()); adaptor.addChild(persistenceSpaceTree, persistenceSpaceData); persisterSpaceList.add(persistenceSpaceTree); } } Tree resultTree = (Tree) adaptor.nil(); for (Tree persistenceElement : persisterSpaceList) { adaptor.addChild(resultTree, persistenceElement); } return resultTree; } /** * Provides a tree representing the SELECT clause. Will be the given SELECT clause if it is not null, * otherwise a clause will be derived from the given FROM clause and aliases. */ protected final Tree generateImplicitSelectFrom(Tree selectClause, Tree fromClause, List<String> aliasList) { Tree result = new CommonTree(new CommonToken(IckleLexer.SELECT_FROM, "SELECT_FROM")); result.addChild(fromClause); Tree selectTree; if (selectClause == null && aliasList != null && aliasList.size() > 0) { selectTree = new CommonTree(new CommonToken(IckleLexer.SELECT, "SELECT")); Tree selectList = new CommonTree(new CommonToken(IckleLexer.SELECT_LIST, "SELECT_LIST")); for (String aliasName : aliasList) { Tree selectElement = new CommonTree(new CommonToken(IckleLexer.SELECT_ITEM, "SELECT_ITEM")); Tree aliasElement = new CommonTree(new CommonToken(IckleLexer.ALIAS_REF, aliasName)); selectElement.addChild(aliasElement); selectList.addChild(selectElement); } selectTree.addChild(selectList); } else { selectTree = selectClause; } result.addChild(selectTree); return result; } protected final String buildUniqueImplicitAlias() { return "<gen:" + unaliasedCount++ + ">"; } protected final boolean isParameterUsageEnabled() { return !enableParameterUsage.isEmpty() && enableParameterUsage.peek(); } protected final void pushEnableParameterUsage(boolean enable) { enableParameterUsage.push(enable); } protected final void popEnableParameterUsage() { enableParameterUsage.pop(); } protected final boolean validateSoftKeyword(String text) { return validateSoftKeyword(1, text); } protected final boolean validateSoftKeyword(int offset, String text) { if (input == null) { return false; } Token token = input.LT(offset); return token != null && text.equalsIgnoreCase(token.getText()); } public final boolean hasErrors() { return !errorMessages.isEmpty(); } public final List<String> getErrorMessages() { return errorMessages; } @Override public final void reportError(RecognitionException e) { errorMessages.add(generateErrorMessage(getRuleInvocationStack(e, getClass().getName()), getTokenNames(), e)); super.reportError(e); } public void setErrStream(PrintStream errStream) { this.errStream = errStream; } @Override public final void emitErrorMessage(String msg) { if (errStream != null) { errStream.println(msg); } } private String generateErrorMessage(List<?> invocationStack, String[] tokenNames, RecognitionException e) { String localization = invocationStack + ": line " + e.line + ":" + e.charPositionInLine + " "; return generateErrorMessage(localization, tokenNames, e); } private String generateErrorMessage(String localization, String[] tokenNames, RecognitionException e) { String message = ""; if (e instanceof MismatchedTokenException) { MismatchedTokenException mte = (MismatchedTokenException) e; String tokenName = "<unknown>"; if (mte.expecting == Token.EOF) { tokenName = "EOF"; } else { if (tokenNames != null) { tokenName = tokenNames[mte.expecting]; } } message = localization + "mismatched token: " + e.token + "; expecting type " + tokenName; } else if (e instanceof MismatchedTreeNodeException) { MismatchedTreeNodeException mtne = (MismatchedTreeNodeException) e; String tokenName = "<unknown>"; if (mtne.expecting == Token.EOF) { tokenName = "EOF"; } else { if (tokenNames != null) { tokenName = tokenNames[mtne.expecting]; } } message = localization + "mismatched tree node: " + mtne.node + "; expecting type " + tokenName; } else if (e instanceof NoViableAltException) { NoViableAltException nvae = (NoViableAltException) e; message = localization + "state " + nvae.stateNumber + " (decision=" + nvae.decisionNumber + ") no viable alt; token=" + e.token; } else if (e instanceof EarlyExitException) { EarlyExitException eee = (EarlyExitException) e; message = localization + "required (...)+ loop (decision=" + eee.decisionNumber + ") did not match anything; token=" + e.token; } else if (e instanceof MismatchedNotSetException) { MismatchedNotSetException mse = (MismatchedNotSetException) e; message = localization + "mismatched token: " + e.token + "; expecting set " + mse.expecting; } else if (e instanceof MismatchedSetException) { MismatchedSetException mse = (MismatchedSetException) e; message = localization + "mismatched token: " + e.token + "; expecting set " + mse.expecting; } else if (e instanceof FailedPredicateException) { FailedPredicateException fpe = (FailedPredicateException) e; message = localization + "rule " + fpe.ruleName + " failed predicate: {" + fpe.predicateText + "}?"; } return message; } }
8,456
39.271429
144
java
null
infinispan-main/object-filter/src/main/java/org/infinispan/objectfilter/impl/ql/parse/EntityNameTree.java
/* * Copyright 2016, Red Hat Inc. and/or its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.infinispan.objectfilter.impl.ql.parse; import org.antlr.runtime.CommonToken; import org.antlr.runtime.Token; import org.antlr.runtime.tree.CommonTree; import org.antlr.runtime.tree.Tree; /** * A {@link CommonTree} representing an entity name. * * @since 9.0 */ final class EntityNameTree extends CommonTree { private final String entityName; public EntityNameTree(int tokenType, Token token, String tokenText, Tree entityNameTree) { super(token); Token newToken = new CommonToken(token); newToken.setType(tokenType); newToken.setText(tokenText); this.token = newToken; this.entityName = toString(entityNameTree); } private static String toString(Tree tree) { switch (tree.getChildCount()) { case 0: // a single argument return tree.getText(); case 1: // an unary operator and the argument return tree.getText() + toString(tree.getChild(0)); case 2: // a binary operator and its arguments return toString(tree.getChild(0)) + tree.getText() + toString(tree.getChild(1)); default: throw new IllegalStateException("Only unary or binary operators expected."); } } public String getEntityName() { return entityName; } @Override public String toString() { return entityName; } }
2,025
29.69697
93
java
null
infinispan-main/object-filter/src/main/java/org/infinispan/objectfilter/impl/ql/parse/PropertyPathTree.java
/* * Copyright 2016, Red Hat Inc. and/or its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.infinispan.objectfilter.impl.ql.parse; import org.antlr.runtime.tree.CommonTree; import org.infinispan.objectfilter.impl.ql.PropertyPath; /** * A {@link CommonTree} representing one property path. * * @author Gunnar Morling * @since 9.0 */ final class PropertyPathTree<TypeDescriptor> extends CommonTree { private final PropertyPath<TypeDescriptor> propertyPath; public PropertyPathTree(int type, CommonTree node, PropertyPath<TypeDescriptor> propertyPath) { super(node); this.propertyPath = propertyPath; } public PropertyPath<TypeDescriptor> getPropertyPath() { return propertyPath; } }
1,264
30.625
98
java
null
infinispan-main/anchored-keys/src/test/java/org/infinispan/anchored/AnchoredKeysOperationsTest.java
package org.infinispan.anchored; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertFalse; import static org.testng.AssertJUnit.assertNull; import static org.testng.AssertJUnit.assertTrue; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingDeque; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; import org.infinispan.AdvancedCache; import org.infinispan.Cache; import org.infinispan.anchored.configuration.AnchoredKeysConfigurationBuilder; import org.infinispan.commons.util.IntSets; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.cache.StorageType; import org.infinispan.configuration.global.GlobalConfigurationBuilder; import org.infinispan.configuration.internal.PrivateGlobalConfigurationBuilder; import org.infinispan.distribution.MagicKey; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.notifications.Listener; import org.infinispan.notifications.cachelistener.annotation.CacheEntryCreated; import org.infinispan.notifications.cachelistener.annotation.CacheEntryModified; import org.infinispan.notifications.cachelistener.annotation.CacheEntryRemoved; import org.infinispan.notifications.cachelistener.event.CacheEntryCreatedEvent; import org.infinispan.notifications.cachelistener.event.CacheEntryEvent; import org.infinispan.notifications.cachelistener.event.CacheEntryModifiedEvent; import org.infinispan.notifications.cachelistener.event.CacheEntryRemovedEvent; import org.infinispan.remoting.transport.Address; import org.infinispan.test.AbstractInfinispanTest; import org.infinispan.test.TestDataSCI; import org.infinispan.test.op.TestWriteOperation; import org.infinispan.util.ControlledConsistentHashFactory; import org.infinispan.util.concurrent.CompletionStages; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import io.reactivex.rxjava3.core.Flowable; @Test(groups = "functional", testName = "anchored.AnchoredKeysOperationsTest") @AbstractInfinispanTest.FeatureCondition(feature = "anchored-keys") public class AnchoredKeysOperationsTest extends AbstractAnchoredKeysTest { public static final String CACHE_NAME = "testCache"; private StorageType storageType; private boolean serverMode; @Override public Object[] factory() { return new Object[]{ new AnchoredKeysOperationsTest().storageType(StorageType.OBJECT), new AnchoredKeysOperationsTest().storageType(StorageType.BINARY), new AnchoredKeysOperationsTest().storageType(StorageType.HEAP).serverMode(true), }; } @DataProvider public static Object[][] operations() { return new Object[][]{ {TestWriteOperation.PUT_CREATE}, {TestWriteOperation.PUT_OVERWRITE}, {TestWriteOperation.PUT_IF_ABSENT}, {TestWriteOperation.REPLACE}, {TestWriteOperation.REPLACE_EXACT}, {TestWriteOperation.REMOVE}, {TestWriteOperation.REMOVE_EXACT}, {TestWriteOperation.PUT_MAP_CREATE}, // TODO Add TestWriteOperation enum values for compute/computeIfAbsent/computeIfPresent/merge }; } public AnchoredKeysOperationsTest storageType(StorageType storageType) { this.storageType = storageType; return this; } private Object serverMode(boolean serverMode) { this.serverMode = serverMode; return this; } @Override protected void createCacheManagers() { addNode(); addNode(); addNode(); waitForClusterToForm(); } @Override protected String[] parameterNames() { return new String[]{"storage", "server"}; } @Override protected Object[] parameterValues() { return new Object[]{storageType, serverMode ? "y" : null}; } private Address addNode() { GlobalConfigurationBuilder managerBuilder = GlobalConfigurationBuilder.defaultClusteredBuilder(); managerBuilder.defaultCacheName(CACHE_NAME).serialization().addContextInitializer(TestDataSCI.INSTANCE); if (serverMode) { managerBuilder.addModule(PrivateGlobalConfigurationBuilder.class).serverMode(true); } ConfigurationBuilder cacheBuilder = new ConfigurationBuilder(); ControlledConsistentHashFactory.Replicated consistentHashFactory = new ControlledConsistentHashFactory.Replicated(new int[]{0, 1, 2}); cacheBuilder.clustering().cacheMode(CacheMode.REPL_SYNC) .hash().numSegments(3).consistentHashFactory(consistentHashFactory); cacheBuilder.clustering().stateTransfer().awaitInitialTransfer(false); cacheBuilder.memory().storage(storageType); cacheBuilder.addModule(AnchoredKeysConfigurationBuilder.class).enabled(true); EmbeddedCacheManager manager = addClusterEnabledCacheManager(managerBuilder, cacheBuilder); return manager.getAddress(); } @Test(dataProvider = "operations") public void testSingleKeyOperations(TestWriteOperation op) { AdvancedCache<Object, Object> originator = advancedCache(0); for (Cache<Object, Object> cache : caches()) { MagicKey key = new MagicKey(cache); op.insertPreviousValue(originator, key); Object returnValue = op.perform(originator, key); assertEquals(op.getReturnValue(), returnValue); assertValue(key, op.getValue()); if (op.getValue() != null) { assertLocation(key, address(2), op.getValue()); } } } public void testMultiKeyOperations() { List<MagicKey> keys = new ArrayList<>(); Map<MagicKey, Object> data = new HashMap<>(); for (int i = 0; i < caches().size(); i++) { MagicKey key = new MagicKey("key-" + i, cache(i)); String value = "value-" + i; keys.add(key); data.put(key, value); } for (int i = 0; i < caches().size(); i++) { MagicKey missingKey = new MagicKey("missingkey" + i, cache(i)); keys.add(missingKey); } for (Cache<Object, Object> cache : caches()) { cache.putAll(data); data.forEach(this::assertValue); data.forEach((key, value) -> assertLocation(key, address(2), value)); assertEquals(data, cache.getAdvancedCache().getAll(data.keySet())); assertEquals(data.keySet(), cache.keySet()); assertEquals(new HashSet<>(data.values()), new HashSet<>(cache.values())); assertEquals(data.size(), cache.size()); assertEquals(data.size(), (long) CompletionStages.join(cache.sizeAsync())); assertEquals(data, Flowable.fromPublisher(cache.entrySet().localPublisher(IntSets.immutableRangeSet(3))) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)) .blockingGet()); cache.clear(); } } public void testClusteredListener() throws InterruptedException { ClusteredListener listener = new ClusteredListener(); cache(0).addListener(listener); for (Cache<Object, Object> originator : caches()) { String key = "key_" + originator.getCacheManager().getAddress(); String value1 = "value-1"; String value2 = "value-2"; assertNull(originator.put(key, value1)); assertValue(key, value1); assertTrue(originator.replace(key, value1, value2)); assertValue(key, value2); assertEquals(value2, originator.remove(key)); CacheEntryEvent<Object, Object> createEvent = listener.pollEvent(); assertTrue(createEvent instanceof CacheEntryCreatedEvent); assertEquals(key, createEvent.getKey()); assertEquals(value1, createEvent.getValue()); CacheEntryEvent<Object, Object> replaceEvent = listener.pollEvent(); assertTrue(replaceEvent instanceof CacheEntryModifiedEvent); assertEquals(key, replaceEvent.getKey()); assertEquals(value2, replaceEvent.getValue()); CacheEntryEvent<Object, Object> removeEvent = listener.pollEvent(); assertTrue(removeEvent instanceof CacheEntryRemovedEvent); assertEquals(key, removeEvent.getKey()); assertNull(removeEvent.getValue()); // TODO The previous value is not always populated, because it's not stored in the context (see ISPN-5665) // Instead ReplicationLogic.commitSingleEntry reads the previous value directly from the data container // assertEquals(value2, ((CacheEntryRemovedEvent<Object, Object>) removeEvent).getOldValue()); assertFalse(listener.hasMoreEvents()); } } @Listener(clustered = true) public class ClusteredListener { private BlockingQueue<CacheEntryEvent<Object, Object>> events = new LinkedBlockingDeque<>(); @CacheEntryCreated @CacheEntryModified @CacheEntryRemoved public void onEntryEvent(CacheEntryEvent<Object, Object> e) { log.tracef("Received event %s", e); events.add(e); } public boolean hasMoreEvents() throws InterruptedException { return events.poll(10, TimeUnit.MILLISECONDS) != null; } public CacheEntryEvent<Object, Object> pollEvent() throws InterruptedException { return events.poll(10, TimeUnit.SECONDS); } } }
9,575
39.923077
115
java
null
infinispan-main/anchored-keys/src/test/java/org/infinispan/anchored/AnchoredKeysScalingTest.java
package org.infinispan.anchored; import org.infinispan.anchored.configuration.AnchoredKeysConfigurationBuilder; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.cache.StorageType; import org.infinispan.configuration.global.GlobalConfigurationBuilder; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.remoting.transport.Address; import org.infinispan.test.AbstractInfinispanTest; import org.infinispan.test.TestingUtil; import org.infinispan.test.fwk.CleanupAfterMethod; import org.testng.annotations.Test; @Test(groups = "functional", testName = "anchored.AnchoredKeysScalingTest") @CleanupAfterMethod @AbstractInfinispanTest.FeatureCondition(feature = "anchored-keys") public class AnchoredKeysScalingTest extends AbstractAnchoredKeysTest { public static final String CACHE_NAME = "testCache"; public static final String KEY_1 = "key1"; public static final String KEY_2 = "key2"; public static final String KEY_3 = "key3"; public static final String VALUE_1 = "value1"; public static final String VALUE_2 = "value2"; private StorageType storageType; @Override public Object[] factory() { return new Object[]{ new AnchoredKeysScalingTest().storageType(StorageType.OBJECT), new AnchoredKeysScalingTest().storageType(StorageType.BINARY), new AnchoredKeysScalingTest().storageType(StorageType.OFF_HEAP), }; } public AnchoredKeysScalingTest storageType(StorageType storageType) { this.storageType = storageType; return this; } @Override protected void createCacheManagers() { addNode(); } @Override protected String[] parameterNames() { return new String[]{"storage"}; } @Override protected Object[] parameterValues() { return new Object[]{storageType}; } private Address addNode() { GlobalConfigurationBuilder managerBuilder = GlobalConfigurationBuilder.defaultClusteredBuilder(); managerBuilder.defaultCacheName(CACHE_NAME); ConfigurationBuilder cacheBuilder = new ConfigurationBuilder(); cacheBuilder.clustering().cacheMode(CacheMode.REPL_SYNC).hash().numSegments(4); cacheBuilder.clustering().stateTransfer().awaitInitialTransfer(false); cacheBuilder.memory().storage(storageType); cacheBuilder.addModule(AnchoredKeysConfigurationBuilder.class).enabled(true); EmbeddedCacheManager manager = addClusterEnabledCacheManager(managerBuilder, cacheBuilder); return manager.getAddress(); } public void testMultipleJoinsAndLeave() { Address A = address(0); cache(0).put(KEY_1, VALUE_1); assertValue(KEY_1, VALUE_1); assertNoValue(KEY_2); assertLocation(KEY_1, A, VALUE_1); assertNoLocation(KEY_2); Address B = addNode(); waitForClusterToForm(); assertValue(KEY_1, VALUE_1); assertNoValue(KEY_2); cache(0).put(KEY_2, VALUE_1); assertValue(KEY_1, VALUE_1); assertValue(KEY_2, VALUE_1); assertNoValue(KEY_3); TestingUtil.waitForNoRebalance(caches()); assertLocation(KEY_1, A, VALUE_1); assertLocation(KEY_2, B, VALUE_1); assertNoLocation(KEY_3); Address C = addNode(); waitForClusterToForm(); assertValue(KEY_1, VALUE_1); assertValue(KEY_2, VALUE_1); assertNoValue(KEY_3); cache(0).put(KEY_3, VALUE_1); assertValue(KEY_1, VALUE_1); assertValue(KEY_2, VALUE_1); assertValue(KEY_3, VALUE_1); TestingUtil.waitForNoRebalance(caches()); assertLocation(KEY_1, A, VALUE_1); assertLocation(KEY_2, B, VALUE_1); assertLocation(KEY_3, C, VALUE_1); killMember(2); waitForClusterToForm(); assertNoValue(KEY_3); assertLocation(KEY_3, C, null); cache(0).put(KEY_3, VALUE_2); assertValue(KEY_3, VALUE_2); assertLocation(KEY_3, B, VALUE_2); cache(0).put(KEY_1, VALUE_2); assertValue(KEY_1, VALUE_2); assertLocation(KEY_1, A, VALUE_2); } }
4,130
29.828358
103
java
null
infinispan-main/anchored-keys/src/test/java/org/infinispan/anchored/AnchoredConfigurationSerializerTest.java
package org.infinispan.anchored; import static org.infinispan.test.TestingUtil.withCacheManager; import static org.infinispan.test.fwk.TestCacheManagerFactory.createClusteredCacheManager; import static org.testng.AssertJUnit.assertNotNull; import static org.testng.AssertJUnit.assertTrue; import static org.testng.AssertJUnit.fail; import java.io.IOException; import org.infinispan.Cache; import org.infinispan.anchored.configuration.AnchoredKeysConfiguration; import org.infinispan.commons.CacheConfigurationException; import org.infinispan.configuration.cache.Configuration; import org.infinispan.configuration.parsing.ConfigurationBuilderHolder; import org.infinispan.configuration.parsing.ParserRegistry; import org.infinispan.configuration.serializer.AbstractConfigurationSerializerTest; import org.infinispan.counter.exception.CounterConfigurationException; import org.infinispan.test.AbstractInfinispanTest; import org.infinispan.test.fwk.CleanupAfterMethod; import org.testng.annotations.Test; /** * Tests the configuration parser and serializer. * * @author Pedro Ruivo * @since 9.0 */ @Test(groups = "functional", testName = "anchored.AnchoredConfigurationSerializerTest") @CleanupAfterMethod @AbstractInfinispanTest.FeatureCondition(feature = "anchored-keys") public class AnchoredConfigurationSerializerTest extends AbstractConfigurationSerializerTest { public void testParser() throws IOException { ConfigurationBuilderHolder holder = new ParserRegistry().parseFile("configs/all/anchored.xml"); withCacheManager(() -> createClusteredCacheManager(holder), cacheManager -> { Cache<Object, Object> anchoredCache = cacheManager.getCache(); AnchoredKeysConfiguration anchoredKeysConfiguration = anchoredCache.getCacheConfiguration().module(AnchoredKeysConfiguration.class); assertTrue(anchoredKeysConfiguration.enabled()); }); } public void testInvalid() throws IOException { try { ConfigurationBuilderHolder holder = new ParserRegistry().parseFile("configs/invalid.xml"); fail("Expected exception. " + holder); } catch (CacheConfigurationException | CounterConfigurationException e) { log.debug("Expected exception", e); } } @Override protected void compareExtraConfiguration(String name, Configuration configurationBefore, Configuration configurationAfter) { AnchoredKeysConfiguration module = configurationAfter.module(AnchoredKeysConfiguration.class); assertNotNull(module); assertTrue(module.enabled()); } }
2,621
41.983607
101
java
null
infinispan-main/anchored-keys/src/test/java/org/infinispan/anchored/AbstractAnchoredKeysTest.java
package org.infinispan.anchored; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertFalse; import static org.testng.AssertJUnit.assertNull; import java.util.List; import org.infinispan.Cache; import org.infinispan.container.entries.InternalCacheEntry; import org.infinispan.container.entries.RemoteMetadata; import org.infinispan.metadata.Metadata; import org.infinispan.remoting.transport.Address; import org.infinispan.test.MultipleCacheManagersTest; public abstract class AbstractAnchoredKeysTest extends MultipleCacheManagersTest { protected void assertValue(Object key, Object expectedValue) { for (Cache<Object, Object> cache : caches()) { Address address = cache.getAdvancedCache().getRpcManager().getAddress(); Object value = cache.get(key); assertEquals("Wrong value for " + key + " on " + address, expectedValue, value); } } protected void assertNoValue(Object key) { for (Cache<Object, Object> cache : caches()) { Address address = cache.getAdvancedCache().getRpcManager().getAddress(); Object value = cache.get(key); assertNull("Extra value for " + key + " on " + address, value); } } protected void assertLocation(Object key, Address expectedAddress, Object expectedValue) { for (Cache<Object, Object> cache : caches()) { Address address = cache.getAdvancedCache().getRpcManager().getAddress(); Object storedKey = cache.getAdvancedCache().getKeyDataConversion().toStorage(key); InternalCacheEntry<Object, Object> entry = cache.getAdvancedCache().getDataContainer().peek(storedKey); if (address.equals(expectedAddress)) { Object storedValue = entry != null ? entry.getValue() : null; Object value = cache.getAdvancedCache().getValueDataConversion().fromStorage(storedValue); assertEquals("Wrong value for " + key + " on " + address, expectedValue, value); Metadata metadata = entry != null ? entry.getMetadata() : null; assertFalse("No location expected for " + key + " on " + address + ", got " + metadata, metadata instanceof RemoteMetadata); } else { assertNull("No value expected for key " + key + " on " + address, entry.getValue()); Address location = ((RemoteMetadata) entry.getMetadata()).getAddress(); assertEquals("Wrong location for " + key + " on " + address, expectedAddress, location); } } } protected void assertNoLocation(Object key) { List<Cache<Object, Object>> caches = caches(); for (Cache<Object, Object> cache : caches) { Object storageKey = cache.getAdvancedCache().getKeyDataConversion().toStorage(key); InternalCacheEntry<Object, Object> entry = cache.getAdvancedCache().getDataContainer().peek(storageKey); Address address = cache.getAdvancedCache().getRpcManager().getAddress(); assertNull("Expected no location on " + address, entry); } } }
3,076
45.621212
113
java
null
infinispan-main/anchored-keys/src/main/java/org/infinispan/anchored/AnchoredKeysModule.java
package org.infinispan.anchored; import static org.infinispan.commons.logging.Log.CONFIG; import org.infinispan.anchored.configuration.AnchoredKeysConfiguration; import org.infinispan.anchored.impl.AnchorManager; import org.infinispan.anchored.impl.AnchoredCacheNotifier; import org.infinispan.anchored.impl.AnchoredDistributionInterceptor; import org.infinispan.anchored.impl.AnchoredEntryFactory; import org.infinispan.anchored.impl.AnchoredFetchInterceptor; import org.infinispan.anchored.impl.AnchoredStateProvider; import org.infinispan.configuration.cache.Configuration; import org.infinispan.configuration.global.GlobalConfiguration; import org.infinispan.conflict.MergePolicy; import org.infinispan.container.impl.EntryFactory; 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.factories.impl.DynamicModuleMetadataProvider; import org.infinispan.factories.impl.ModuleMetadataBuilder; import org.infinispan.interceptors.AsyncInterceptorChain; import org.infinispan.interceptors.impl.ClusteringInterceptor; import org.infinispan.lifecycle.ModuleLifecycle; import org.infinispan.notifications.cachelistener.CacheNotifier; import org.infinispan.partitionhandling.PartitionHandling; import org.infinispan.statetransfer.StateProvider; /** * Install the required components for stable distribution caches. * * @author Dan Berindei * @since 11 */ @InfinispanModule(name = "anchored-keys", requiredModules = "core") public final class AnchoredKeysModule implements ModuleLifecycle, DynamicModuleMetadataProvider { public static final String ANCHORED_KEYS_FEATURE = "anchored-keys"; private GlobalConfiguration globalConfiguration; @Override public void registerDynamicMetadata(ModuleMetadataBuilder.ModuleBuilder moduleBuilder, GlobalConfiguration globalConfiguration) { } @Override public void cacheManagerStarting(GlobalComponentRegistry gcr, GlobalConfiguration globalConfiguration) { this.globalConfiguration = globalConfiguration; } @Override public void cacheStarting(ComponentRegistry cr, Configuration configuration, String cacheName) { BasicComponentRegistry bcr = cr.getComponent(BasicComponentRegistry.class); AnchoredKeysConfiguration anchoredKeysConfiguration = configuration.module(AnchoredKeysConfiguration.class); if (anchoredKeysConfiguration == null || !anchoredKeysConfiguration.enabled()) return; assert configuration.clustering().cacheMode().isReplicated(); assert !configuration.clustering().stateTransfer().awaitInitialTransfer(); assert configuration.clustering().partitionHandling().whenSplit() == PartitionHandling.ALLOW_READ_WRITES; assert configuration.clustering().partitionHandling().mergePolicy() == MergePolicy.PREFERRED_NON_NULL; if (!globalConfiguration.features().isAvailable(ANCHORED_KEYS_FEATURE)) throw CONFIG.featureDisabled(ANCHORED_KEYS_FEATURE); bcr.registerComponent(AnchorManager.class, new AnchorManager(), true); AsyncInterceptorChain interceptorChain = bcr.getComponent(AsyncInterceptorChain.class).wired(); // Replace the clustering interceptor with our custom interceptor ClusteringInterceptor oldDistInterceptor = interceptorChain.findInterceptorExtending(ClusteringInterceptor.class); AnchoredDistributionInterceptor distInterceptor = new AnchoredDistributionInterceptor(); bcr.registerComponent(AnchoredDistributionInterceptor.class, distInterceptor, true); boolean interceptorAdded = interceptorChain.addInterceptorBefore(distInterceptor, oldDistInterceptor.getClass()); assert interceptorAdded; interceptorChain.removeInterceptor(oldDistInterceptor.getClass()); // Add a separate interceptor to fetch the actual values // AnchoredDistributionInterceptor cannot do it because it extends NonTxDistributionInterceptor AnchoredFetchInterceptor<?, ?> fetchInterceptor = new AnchoredFetchInterceptor<>(); bcr.registerComponent(AnchoredFetchInterceptor.class, fetchInterceptor, true); interceptorAdded = interceptorChain.addInterceptorAfter(fetchInterceptor, AnchoredDistributionInterceptor.class); assert interceptorAdded; bcr.replaceComponent(StateProvider.class.getName(), new AnchoredStateProvider(), true); bcr.replaceComponent(EntryFactory.class.getName(), new AnchoredEntryFactory(), true); bcr.replaceComponent(CacheNotifier.class.getName(), new AnchoredCacheNotifier<>(), true); bcr.rewire(); } }
4,695
50.043478
132
java
null
infinispan-main/anchored-keys/src/main/java/org/infinispan/anchored/configuration/Element.java
package org.infinispan.anchored.configuration; import java.util.HashMap; import java.util.Map; /** * Element. * * @author Dan Berindei * @since 11 */ public enum Element { // must be first UNKNOWN(null), ANCHORED_KEYS("anchored-keys"); private final String name; Element(final String name) { this.name = name; } /** * Get the local name of this element. * * @return the local name */ public String getLocalName() { return name; } private static final Map<String, Element> MAP; static { final Map<String, Element> map = new HashMap<String, Element>(8); for (Element element : values()) { final String name = element.getLocalName(); if (name != null) { map.put(name, element); } } MAP = map; } public static Element forName(final String localName) { final Element element = MAP.get(localName); return element == null ? UNKNOWN : element; } }
999
18.607843
71
java
null
infinispan-main/anchored-keys/src/main/java/org/infinispan/anchored/configuration/AnchoredKeysConfiguration.java
package org.infinispan.anchored.configuration; import org.infinispan.commons.configuration.BuiltBy; import org.infinispan.commons.configuration.attributes.AttributeDefinition; import org.infinispan.commons.configuration.attributes.AttributeSet; import org.infinispan.commons.util.Experimental; import org.infinispan.configuration.serializing.SerializedWith; /** * Configuration module to transform an {@link org.infinispan.configuration.cache.CacheMode#INVALIDATION_SYNC} * cache into an anchored-key cache. * * <p>Anchored keys caches always write new entries to the newest member of the cache. * The administrator is supposed to add a new node when the current writer is close to full.</p> * * @since 11 * @author Dan Berindei */ @Experimental @SerializedWith(AnchoredKeysConfigurationSerializer.class) @BuiltBy(AnchoredKeysConfigurationBuilder.class) public class AnchoredKeysConfiguration { static final AttributeDefinition<Boolean> ENABLED = AttributeDefinition.builder("enabled", false).immutable().build(); private final AttributeSet attributes; public AnchoredKeysConfiguration(AttributeSet attributes) { this.attributes = attributes; } public static AttributeSet attributeSet() { return new AttributeSet(AnchoredKeysConfiguration.class, ENABLED); } public AttributeSet attributes() { return attributes; } public boolean enabled() { return attributes.attribute(ENABLED).get(); } @Override public String toString() { return "AnchoredKeysConfiguration" + attributes.toString(null); } }
1,587
31.408163
110
java
null
infinispan-main/anchored-keys/src/main/java/org/infinispan/anchored/configuration/AnchoredKeysConfigurationBuilder.java
package org.infinispan.anchored.configuration; import static org.infinispan.anchored.impl.Log.CONFIG; import org.infinispan.commons.configuration.Builder; import org.infinispan.commons.configuration.Combine; import org.infinispan.commons.configuration.attributes.Attribute; import org.infinispan.commons.configuration.attributes.AttributeSet; import org.infinispan.commons.util.Experimental; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.cache.PartitionHandlingConfiguration; import org.infinispan.configuration.cache.StateTransferConfiguration; import org.infinispan.conflict.EntryMergePolicy; import org.infinispan.conflict.MergePolicy; import org.infinispan.partitionhandling.PartitionHandling; /** * Configuration module builder to transform an {@link CacheMode#INVALIDATION_SYNC} cache into an "anchored keys" cache. * * <p>Usage: * <pre> * ConfigurationBuilder cacheBuilder = new ConfigurationBuilder(); * cacheBuilder.clustering().cacheMode(CacheMode.INVALIDATION_SYNC); * cacheBuilder.addModule(AnchoredKeysConfigurationBuilder.class).enabled(true); * </pre> * </p> * @see AnchoredKeysConfiguration * * @since 11 * @author Dan Berindei */ @Experimental public class AnchoredKeysConfigurationBuilder implements Builder<AnchoredKeysConfiguration> { private final AttributeSet attributes; private final ConfigurationBuilder rootBuilder; public AnchoredKeysConfigurationBuilder(ConfigurationBuilder builder) { rootBuilder = builder; this.attributes = AnchoredKeysConfiguration.attributeSet(); } @Override public AttributeSet attributes() { return attributes; } /** * Enable or disable anchored keys. */ public void enabled(boolean enabled) { attributes.attribute(AnchoredKeysConfiguration.ENABLED).set(enabled); } @Override public void validate() { if (!rootBuilder.clustering().cacheMode().isReplicated()) { throw CONFIG.replicationModeRequired(); } if (rootBuilder.transaction().transactionMode() != null && rootBuilder.transaction().transactionMode().isTransactional()) { throw CONFIG.transactionsNotSupported(); } Attribute<Boolean> stateTransferEnabledAttribute = rootBuilder.clustering().stateTransfer().attributes() .attribute(StateTransferConfiguration.FETCH_IN_MEMORY_STATE); if (!stateTransferEnabledAttribute.get()) { throw CONFIG.stateTransferRequired(); } Attribute<Boolean> awaitStateTransferAttribute = rootBuilder.clustering().stateTransfer().attributes() .attribute(StateTransferConfiguration.AWAIT_INITIAL_TRANSFER); if (awaitStateTransferAttribute.get() && awaitStateTransferAttribute.isModified()) { throw CONFIG.awaitInitialTransferNotSupported(); } rootBuilder.clustering().stateTransfer().awaitInitialTransfer(false); Attribute<PartitionHandling> whenSplitAttribute = rootBuilder.clustering().partitionHandling().attributes() .attribute(PartitionHandlingConfiguration.WHEN_SPLIT); if (whenSplitAttribute.get() != PartitionHandling.ALLOW_READ_WRITES && whenSplitAttribute.isModified()) { throw CONFIG.whenSplitNotSupported(); } rootBuilder.clustering().partitionHandling().whenSplit(PartitionHandling.ALLOW_READ_WRITES); Attribute<EntryMergePolicy> mergePolicyAttribute = rootBuilder.clustering().partitionHandling().attributes() .attribute(PartitionHandlingConfiguration.MERGE_POLICY); if (mergePolicyAttribute.get() != MergePolicy.PREFERRED_NON_NULL && mergePolicyAttribute.isModified()) { throw CONFIG.mergePolicyNotSupported(); } rootBuilder.clustering().partitionHandling().mergePolicy(MergePolicy.PREFERRED_NON_NULL); } @Override public AnchoredKeysConfiguration create() { return new AnchoredKeysConfiguration(attributes); } @Override public Builder<?> read(AnchoredKeysConfiguration template, Combine combine) { attributes.read(template.attributes(), combine); return this; } }
4,270
38.915888
120
java
null
infinispan-main/anchored-keys/src/main/java/org/infinispan/anchored/configuration/AnchoredKeysConfigurationParser.java
package org.infinispan.anchored.configuration; import static org.infinispan.anchored.configuration.AnchoredKeysConfigurationParser.NAMESPACE; import org.infinispan.commons.configuration.io.ConfigurationReader; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.parsing.ConfigurationBuilderHolder; import org.infinispan.configuration.parsing.ConfigurationParser; import org.infinispan.configuration.parsing.Namespace; import org.infinispan.configuration.parsing.ParseUtils; import org.infinispan.configuration.parsing.Parser; import org.infinispan.configuration.parsing.ParserScope; import org.kohsuke.MetaInfServices; /** * Anchored keys parser extension. * * This extension parses elements in the "urn:infinispan:config:anchored-keys" namespace * * @author Dan Berindei * @since 11 */ @MetaInfServices @Namespace(root = "anchored-keys") @Namespace(uri = NAMESPACE + "*", root = "anchored-keys", since = "11.0") public class AnchoredKeysConfigurationParser implements ConfigurationParser { static final String PREFIX = "anchored-keys"; static final String NAMESPACE = Parser.NAMESPACE + PREFIX + ":"; @Override public void readElement(ConfigurationReader reader, ConfigurationBuilderHolder holder) { if (!holder.inScope(ParserScope.CACHE) && !holder.inScope(ParserScope.CACHE_TEMPLATE)) { throw new IllegalStateException("WRONG SCOPE"); } ConfigurationBuilder builder = holder.getCurrentConfigurationBuilder(); Element element = Element.forName(reader.getLocalName()); switch (element) { case ANCHORED_KEYS: { AnchoredKeysConfigurationBuilder anchoredBuilder = builder.addModule(AnchoredKeysConfigurationBuilder.class); // Do not require an explicit enabled="true" attribute anchoredBuilder.enabled(true); parseAnchoredKeys(reader, anchoredBuilder); break; } default: { throw ParseUtils.unexpectedElement(reader); } } } private void parseAnchoredKeys(ConfigurationReader reader, AnchoredKeysConfigurationBuilder builder) { for (int i = 0; i < reader.getAttributeCount(); i++) { ParseUtils.requireNoNamespaceAttribute(reader, i); String value = reader.getAttributeValue(i); Attribute attribute = Attribute.forName(reader.getAttributeName(i)); switch (attribute) { case ENABLED: { builder.enabled(Boolean.parseBoolean(value)); break; } default: { throw ParseUtils.unexpectedAttribute(reader, i); } } } ParseUtils.requireNoContent(reader); } @Override public Namespace[] getNamespaces() { return ParseUtils.getNamespaceAnnotations(getClass()); } }
2,807
35.467532
118
java
null
infinispan-main/anchored-keys/src/main/java/org/infinispan/anchored/configuration/AnchoredKeysConfigurationSerializer.java
package org.infinispan.anchored.configuration; import static org.infinispan.anchored.configuration.AnchoredKeysConfigurationParser.NAMESPACE; import static org.infinispan.anchored.configuration.AnchoredKeysConfigurationParser.PREFIX; import org.infinispan.commons.configuration.io.ConfigurationWriter; import org.infinispan.commons.util.Version; import org.infinispan.configuration.serializing.ConfigurationSerializer; public class AnchoredKeysConfigurationSerializer implements ConfigurationSerializer<AnchoredKeysConfiguration> { @Override public void serialize(ConfigurationWriter writer, AnchoredKeysConfiguration configuration) { String xmlns = NAMESPACE + Version.getMajorMinor(); writer.writeStartElement(PREFIX, xmlns, Element.ANCHORED_KEYS.getLocalName()); writer.writeNamespace(PREFIX, xmlns); configuration.attributes().write(writer); writer.writeEndElement(); } }
925
41.090909
95
java
null
infinispan-main/anchored-keys/src/main/java/org/infinispan/anchored/configuration/Attribute.java
package org.infinispan.anchored.configuration; import java.util.HashMap; import java.util.Map; /** * Attribute. * * @author Dan Berindei * @since 11 */ public enum Attribute { // must be first UNKNOWN(null), ENABLED("enabled"), ; private final String name; Attribute(final String name) { this.name = name; } /** * Get the local name of this element. * * @return the local name */ public String getLocalName() { return name; } private static final Map<String, Attribute> attributes; static { Map<String, Attribute> map = new HashMap<>(); for (Attribute attribute : values()) { final String name = attribute.getLocalName(); if (name != null) { map.put(name, attribute); } } attributes = map; } public static Attribute forName(final String localName) { final Attribute attribute = attributes.get(localName); return attribute == null ? UNKNOWN : attribute; } }
1,020
18.264151
60
java
null
infinispan-main/anchored-keys/src/main/java/org/infinispan/anchored/impl/AnchoredFetchInterceptor.java
package org.infinispan.anchored.impl; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.concurrent.CompletionStage; import org.infinispan.Cache; import org.infinispan.CacheSet; import org.infinispan.InternalCacheSet; import org.infinispan.commands.CommandsFactory; import org.infinispan.commands.DataCommand; import org.infinispan.commands.FlagAffectedCommand; import org.infinispan.commands.VisitableCommand; import org.infinispan.commands.read.EntrySetCommand; import org.infinispan.commands.read.GetAllCommand; import org.infinispan.commands.read.GetCacheEntryCommand; import org.infinispan.commands.read.GetKeyValueCommand; import org.infinispan.commands.read.KeySetCommand; import org.infinispan.commands.read.SizeCommand; import org.infinispan.commands.remote.ClusteredGetCommand; import org.infinispan.commands.write.ClearCommand; import org.infinispan.commands.write.IracPutKeyValueCommand; import org.infinispan.commands.write.PutKeyValueCommand; import org.infinispan.commands.write.PutMapCommand; import org.infinispan.commands.write.RemoveCommand; import org.infinispan.commands.write.ReplaceCommand; import org.infinispan.commons.util.IntSet; import org.infinispan.container.entries.CacheEntry; import org.infinispan.container.entries.InternalCacheValue; import org.infinispan.container.entries.NullCacheEntry; import org.infinispan.container.entries.RemoteMetadata; import org.infinispan.container.impl.EntryFactory; import org.infinispan.context.InvocationContext; import org.infinispan.context.impl.FlagBitSets; import org.infinispan.context.impl.SingleKeyNonTxInvocationContext; import org.infinispan.distribution.DistributionInfo; import org.infinispan.distribution.DistributionManager; import org.infinispan.factories.annotations.Inject; import org.infinispan.factories.impl.ComponentRef; import org.infinispan.factories.scopes.Scope; import org.infinispan.factories.scopes.Scopes; import org.infinispan.interceptors.impl.BaseRpcInterceptor; import org.infinispan.notifications.Listener; import org.infinispan.remoting.responses.ValidResponse; import org.infinispan.remoting.transport.Address; import org.infinispan.remoting.transport.ValidSingleResponseCollector; import org.infinispan.util.concurrent.AggregateCompletionStage; import org.infinispan.commons.util.concurrent.CompletableFutures; import org.infinispan.util.concurrent.CompletionStages; import org.infinispan.util.logging.Log; import org.infinispan.util.logging.LogFactory; import org.reactivestreams.Publisher; import io.reactivex.rxjava3.core.Flowable; import io.reactivex.rxjava3.core.Maybe; /** * Fetch the real value from the anchor owner in an anchored cache. * * @author Dan Berindei * @since 11 */ @Listener @Scope(Scopes.NAMED_CACHE) public class AnchoredFetchInterceptor<K, V> extends BaseRpcInterceptor { private static final Log log = LogFactory.getLog(AnchoredFetchInterceptor.class); @Inject CommandsFactory cf; @Inject EntryFactory entryFactory; @Inject DistributionManager distributionManager; @Inject ComponentRef<Cache<K, V>> cache; @Inject AnchorManager anchorManager; @Override protected Log getLog() { return log; } @Override public Object visitGetKeyValueCommand(InvocationContext ctx, GetKeyValueCommand command) { return asyncInvokeNext(ctx, command, fetchSingleContextValue(ctx, command, false)); } @Override public Object visitGetCacheEntryCommand(InvocationContext ctx, GetCacheEntryCommand command) { return asyncInvokeNext(ctx, command, fetchSingleContextValue(ctx, command, false)); } @Override public Object visitPutKeyValueCommand(InvocationContext ctx, PutKeyValueCommand command) { return asyncInvokeNext(ctx, command, fetchSingleContextValue(ctx, command, true)); } @Override public Object visitReplaceCommand(InvocationContext ctx, ReplaceCommand command) { return asyncInvokeNext(ctx, command, fetchSingleContextValue(ctx, command, true)); } @Override public Object visitRemoveCommand(InvocationContext ctx, RemoveCommand command) { return asyncInvokeNext(ctx, command, fetchSingleContextValue(ctx, command, true)); } @Override public Object visitPutMapCommand(InvocationContext ctx, PutMapCommand command) { return asyncInvokeNext(ctx, command, fetchAllContextValues(ctx, command, true)); } @Override public Object visitIracPutKeyValueCommand(InvocationContext ctx, IracPutKeyValueCommand command) { return asyncInvokeNext(ctx, command, fetchSingleContextValue(ctx, command, true)); } @Override public Object visitGetAllCommand(InvocationContext ctx, GetAllCommand command) { return asyncInvokeNext(ctx, command, fetchAllContextValues(ctx, command, false)); } @Override public Object visitKeySetCommand(InvocationContext ctx, KeySetCommand command) { return invokeNext(ctx, command); } @Override public Object visitEntrySetCommand(InvocationContext ctx, EntrySetCommand command) { // TODO The BackingEntrySet may have to move to an AnchoredBulkInterceptor, // so that it intercepts RemoteMetadata entries loaded from the store // TODO LocalPublisherManagerImpl always uses CACHE_MODE_LOCAL, so we can't skip remote lookups // Moving this to an AnchoredBulkInterceptor may also help with that problem // if (command.hasAnyFlag(FlagBitSets.CACHE_MODE_LOCAL | FlagBitSets.SKIP_REMOTE_LOOKUP)) // return invokeNext(ctx, command); if (command.hasAnyFlag(FlagBitSets.STATE_TRANSFER_PROGRESS)) { return invokeNext(ctx, command); } return new BackingEntrySet((CacheSet<CacheEntry<K,V>>) invokeNext(ctx, command)); } @Override public Object visitSizeCommand(InvocationContext ctx, SizeCommand command) { return invokeNext(ctx, command); } @Override public Object visitClearCommand(InvocationContext ctx, ClearCommand command) { return invokeNext(ctx, command); } @Override protected Object handleDefault(InvocationContext ctx, VisitableCommand command) { throw new IllegalStateException("Command " + command.getClass().getName() + " is not yet supported"); } private CompletionStage<Void> fetchSingleContextValue(InvocationContext ctx, DataCommand command, boolean isWrite) { K key = (K) command.getKey(); CacheEntry<?, ?> ctxEntry = ((SingleKeyNonTxInvocationContext) ctx).getCacheEntry(); CompletionStage<CacheEntry<K, V>> stage = fetchContextValue(ctx, command, key, ctxEntry, command.getSegment(), isWrite); if (stage == null) return CompletableFutures.completedNull(); return stage.thenAccept(externalEntry -> { entryFactory.wrapExternalEntry(ctx, key, externalEntry, true, isWrite); }); } private CompletionStage<Void> fetchAllContextValues(InvocationContext ctx, FlagAffectedCommand command, boolean isWrite) { if (command.hasAnyFlag(FlagBitSets.CACHE_MODE_LOCAL | FlagBitSets.SKIP_REMOTE_LOOKUP)) return CompletableFutures.completedNull(); AggregateCompletionStage<Void> fetchStage = CompletionStages.aggregateCompletionStage(); List<CompletionStage<CacheEntry<K, V>>> stages = new ArrayList<>(ctx.lookedUpEntriesCount()); ctx.forEachEntry((key, ctxEntry) -> { // TODO Group keys by anchor location and use ClusteredGetAllCommand DistributionInfo distributionInfo = distributionManager.getCacheTopology().getDistribution(key); CompletionStage<CacheEntry<K, V>> stage; stage = fetchContextValue(ctx, command, (K) key, ctxEntry, distributionInfo.segmentId(), isWrite); stages.add(stage); if (stage != null) { fetchStage.dependsOn(stage); } }); return fetchStage.freeze().thenAccept(__ -> { // The context iteration order is the same, and each entry has a (possibly null) stage Iterator<CompletionStage<CacheEntry<K, V>>> iterator = stages.iterator(); ctx.forEachEntry((key, ctxEntry) -> { CompletionStage<CacheEntry<K, V>> stage = iterator.next(); if (stage != null) { CacheEntry<?, ?> ownerEntry = CompletionStages.join(stage); entryFactory.wrapExternalEntry(ctx, key, ownerEntry, true, isWrite); } }); }); } private CompletionStage<CacheEntry<K, V>> fetchContextValue(InvocationContext ctx, FlagAffectedCommand command, K key, CacheEntry<?, ?> ctxEntry, int segment, boolean isWrite) { if (ctxEntry.getValue() != null) { // The key exists and the anchor location is the local node // Note: CacheEntry.isNull() cannot be used, some InternalCacheEntry impls always return false return null; } else if (ctxEntry.getMetadata() instanceof RemoteMetadata) { // The key exists and the anchor location is a remote node RemoteMetadata remoteMetadata = (RemoteMetadata) ctxEntry.getMetadata(); Address keyLocation = remoteMetadata.getAddress(); if (isWrite && !isLocalModeForced(command)) { // Store the location for later, the remote fetch will overwrite the metadata // Update the key location if the remote node is no longer available Address newLocation = anchorManager.updateLocation(keyLocation); ((AnchoredReadCommittedEntry) ctxEntry).setLocation(newLocation); } DistributionInfo distributionInfo = distributionManager.getCacheTopology().getSegmentDistribution(segment); // Some writes don't need to fetch the previous value on the backup owners and/or the originator if (isWrite && !shouldLoad(ctx, command, distributionInfo)) { return null; } return getRemoteValue(keyLocation, key, segment, isWrite); } else { // The key does not exist in the cache if (isWrite && !isLocalModeForced(command)) { // Assign the location now, because AnchoredDistributionInterceptor does not see the RemoteMetadata Address currentWriter = anchorManager.getCurrentWriter(); ((AnchoredReadCommittedEntry) ctxEntry).setLocation(currentWriter); } return null; } } private CompletionStage<CacheEntry<K, V>> getRemoteValue(Address keyLocation, K key, Integer segment, boolean isWrite) { ClusteredGetCommand getCommand = cf.buildClusteredGetCommand(key, segment, FlagBitSets.SKIP_OWNERSHIP_CHECK); getCommand.setTopologyId(0); getCommand.setWrite(isWrite); FetchResponseCollector<K, V> collector = new FetchResponseCollector<>(key); return rpcManager.invokeCommand(keyLocation, getCommand, collector, rpcManager.getSyncRpcOptions()); } private static class FetchResponseCollector<K, V> extends ValidSingleResponseCollector<CacheEntry<K, V>> { private final K key; public FetchResponseCollector(K key) { this.key = key; } @Override protected CacheEntry<K, V> withValidResponse(Address sender, ValidResponse response) { Object responseValue = response.getResponseValue(); if (responseValue == null) { return NullCacheEntry.getInstance(); } else { return ((InternalCacheValue<V>) responseValue).toInternalCacheEntry(key); } } @Override protected CacheEntry<K, V> targetNotFound(Address sender) { // The entry was lost return NullCacheEntry.getInstance(); } } private class BackingEntrySet extends InternalCacheSet<CacheEntry<K, V>> { protected final CacheSet<CacheEntry<K, V>> next; public BackingEntrySet(CacheSet<CacheEntry<K, V>> next) { this.next = next; } @Override public Publisher<CacheEntry<K, V>> localPublisher(int segment) { return fixPublisher(next.localPublisher(segment), segment); } @Override public Publisher<CacheEntry<K, V>> localPublisher(IntSet segments) { return fixPublisher(next.localPublisher(segments), null); } private Flowable<CacheEntry<K, V>> fixPublisher(Publisher<CacheEntry<K, V>> nextPublisher, Integer segment) { return Flowable.fromPublisher(nextPublisher) .groupBy(entry -> entry.getMetadata() instanceof RemoteMetadata) .flatMap(gf -> { if (!gf.getKey()) { return gf; } return gf.concatMapMaybe(incompleteEntry -> fixPublisherEntry(segment, incompleteEntry)); }, 2); } private Maybe<CacheEntry<K, V>> fixPublisherEntry(Integer segment, CacheEntry<K, V> localEntry) { // The key exists and the anchor location is a remote node RemoteMetadata remoteMetadata = (RemoteMetadata) localEntry.getMetadata(); Address keyLocation = remoteMetadata.getAddress(); return Maybe.fromCompletionStage(getRemoteValue(keyLocation, localEntry.getKey(), segment, false)); } } }
13,431
42.469256
119
java
null
infinispan-main/anchored-keys/src/main/java/org/infinispan/anchored/impl/Log.java
package org.infinispan.anchored.impl; import org.infinispan.commons.CacheConfigurationException; import org.jboss.logging.BasicLogger; import org.jboss.logging.Logger; import org.jboss.logging.annotations.Message; import org.jboss.logging.annotations.MessageLogger; /** * This module reserves range 30001 - 30500 */ @MessageLogger(projectCode = "ISPN") public interface Log extends BasicLogger { Log CONFIG = Logger.getMessageLogger(Log.class, org.infinispan.util.logging.Log.LOG_ROOT + "CONFIG"); @Message(value = "Anchored keys requires cache to be in replication mode", id = 30001) CacheConfigurationException replicationModeRequired(); @Message(value = "Anchored keys do not support transactions, please remove the <transaction> element from your configuration", id = 30002) CacheConfigurationException transactionsNotSupported(); @Message(value = "Anchored keys caches must have state transfer enabled", id = 30003) CacheConfigurationException stateTransferRequired(); @Message(value = "Anchored keys do not support awaiting for state transfer when starting a cache, please remove " + "the await-initial-transfer attribute from your configuration", id = 30004) CacheConfigurationException awaitInitialTransferNotSupported(); @Message(value = "Anchored keys only support partition handling mode ALLOW_READ_WRITES, please remove the " + "when-split attribute from your configuration", id = 30005) CacheConfigurationException whenSplitNotSupported(); @Message(value = "Anchored keys only support merge policy PREFERRED_NON_NULL, please remove the merge-policy " + "attribute from your configuration", id = 30006) CacheConfigurationException mergePolicyNotSupported(); }
1,781
47.162162
141
java
null
infinispan-main/anchored-keys/src/main/java/org/infinispan/anchored/impl/AnchoredStateProvider.java
package org.infinispan.anchored.impl; import org.infinispan.commons.util.IntSet; import org.infinispan.container.entries.InternalCacheEntry; import org.infinispan.container.entries.RemoteMetadata; import org.infinispan.container.impl.InternalEntryFactory; import org.infinispan.factories.annotations.Inject; import org.infinispan.factories.scopes.Scope; import org.infinispan.factories.scopes.Scopes; import org.infinispan.reactive.publisher.impl.Notifications; import org.infinispan.reactive.publisher.impl.SegmentPublisherSupplier; import org.infinispan.statetransfer.StateProvider; import org.infinispan.statetransfer.StateProviderImpl; import org.infinispan.util.logging.Log; import org.infinispan.util.logging.LogFactory; import io.reactivex.rxjava3.core.Flowable; /** * State provider that replaces the entry values with the node address. * * @author Dan Berindei * @since 11 */ @Scope(Scopes.NAMED_CACHE) public class AnchoredStateProvider extends StateProviderImpl implements StateProvider { private static final Log log = LogFactory.getLog(AnchoredStateProvider.class); @Inject InternalEntryFactory internalEntryFactory; @Override protected Flowable<SegmentPublisherSupplier.Notification<InternalCacheEntry<?, ?>>> readEntries(IntSet segments) { return super.readEntries(segments) .map(notification -> { if (notification.isValue()) { InternalCacheEntry<Object, Object> ice = (InternalCacheEntry<Object, Object>) notification.value(); return Notifications.value(replaceValueWithLocation(ice), notification.valueSegment()); } return notification; }); } private InternalCacheEntry<Object, Object> replaceValueWithLocation(InternalCacheEntry<Object, Object> ice) { if (ice.getMetadata() instanceof RemoteMetadata) { return ice; } else { if (log.isTraceEnabled()) log.tracef("Replaced state transfer value for key %s: %s", ice.getKey(), rpcManager.getAddress()); RemoteMetadata metadata = new RemoteMetadata(rpcManager.getAddress(), null); return internalEntryFactory.create(ice.getKey(), null, metadata); } } }
2,213
40.773585
133
java
null
infinispan-main/anchored-keys/src/main/java/org/infinispan/anchored/impl/AbstractDelegatingWriteManyCommandHelper.java
package org.infinispan.anchored.impl; import java.util.Collection; import org.infinispan.commands.write.WriteCommand; import org.infinispan.commons.util.IntSet; import org.infinispan.distribution.LocalizedCacheTopology; import org.infinispan.interceptors.distribution.WriteManyCommandHelper; import org.infinispan.remoting.transport.Address; public abstract class AbstractDelegatingWriteManyCommandHelper<C extends WriteCommand, Item, Container> extends WriteManyCommandHelper<C, Item, Container> { protected final WriteManyCommandHelper<C, Item, Container> helper; public AbstractDelegatingWriteManyCommandHelper(WriteManyCommandHelper<C, Item, Container> helper) { super(h -> helper.getRemoteCallback()); this.helper = helper; } @Override public C copyForLocal(C cmd, Item item) { return helper.copyForLocal(cmd, item); } @Override public C copyForPrimary(C cmd, LocalizedCacheTopology topology, IntSet segments) { return helper.copyForPrimary(cmd, topology, segments); } @Override public C copyForBackup(C cmd, LocalizedCacheTopology topology, Address target, IntSet segments) { return helper.copyForBackup(cmd, topology, target, segments); } @Override public Collection<Container> getItems(C cmd) { return helper.getItems(cmd); } @Override public Object item2key(Container container) { return helper.item2key(container); } @Override public Item newContainer() { return helper.newContainer(); } @Override public void accumulate(Item item, Container container) { helper.accumulate(item, container); } @Override public int containerSize(Item item) { return helper.containerSize(item); } @Override public Iterable<Object> toKeys(Item item) { return helper.toKeys(item); } @Override public boolean shouldRegisterRemoteCallback(C cmd) { return helper.shouldRegisterRemoteCallback(cmd); } @Override public Object transformResult(Object[] results) { return helper.transformResult(results); } }
2,221
28.236842
148
java
null
infinispan-main/anchored-keys/src/main/java/org/infinispan/anchored/impl/AnchorManager.java
package org.infinispan.anchored.impl; import static org.infinispan.factories.scopes.Scopes.NAMED_CACHE; import java.util.List; import org.infinispan.distribution.DistributionManager; import org.infinispan.distribution.LocalizedCacheTopology; import org.infinispan.factories.annotations.Inject; import org.infinispan.factories.scopes.Scope; import org.infinispan.remoting.transport.Address; /** * Holds the current writer in an anchored cache. * * @author Dan Berindei * @since 11 */ @Scope(NAMED_CACHE) public class AnchorManager { @Inject DistributionManager distributionManager; // @Inject CacheNotifier cacheNotifier; // private volatile Address currentWriter; // @GuardedBy("this") // int currentTopologyId = -1; // // @Start // public void start() { // cacheNotifier.addListener(this); // updateWriter(distributionManager.getCacheTopology()); // } // // @TopologyChanged // public void onTopologyChange(TopologyChangedEvent<?, ?> event) { // updateWriter(distributionManager.getCacheTopology()); // } // // private void updateWriter(CacheTopology cacheTopology) { // synchronized (this) { // if (cacheTopology.getTopologyId() > currentTopologyId) { // currentTopologyId = cacheTopology.getTopologyId(); // List<Address> readMembers = cacheTopology.getReadConsistentHash().getMembers(); // currentWriter = (readMembers.get(readMembers.size() - 1)); // } // } // } public Address getCurrentWriter() { LocalizedCacheTopology cacheTopology = distributionManager.getCacheTopology(); List<Address> members = cacheTopology.getReadConsistentHash().getMembers(); if (members.size() == 1) return null; Address newestMember = members.get(members.size() - 1); if (newestMember.equals(cacheTopology.getLocalAddress())) return null; return newestMember; } public boolean isCurrentWriter() { return getCurrentWriter() == null; } public Address updateLocation(Address address) { if (address != null && distributionManager.getCacheTopology().getMembersSet().contains(address)) { return address; } return getCurrentWriter(); } }
2,237
29.657534
104
java
null
infinispan-main/anchored-keys/src/main/java/org/infinispan/anchored/impl/AnchoredCacheNotifier.java
package org.infinispan.anchored.impl; import java.util.concurrent.CompletionStage; import org.infinispan.notifications.cachelistener.CacheNotifierImpl; /** * Adjust notifications for anchored keys caches. * * <ul> * <li>Invoke clustered listeners from the primary owner</li> * <li>Skip notifications for entries that only store a location.</li> * </ul> * * * @author Dan Berindei * @since 11 */ public class AnchoredCacheNotifier<K, V> extends CacheNotifierImpl<K, V> { @Override protected boolean clusterListenerOnPrimaryOnly() { return true; } @Override public CompletionStage<Void> addListenerAsync(Object listener) { // TODO Skip notification if value is null and metadata is a RemoteMetadata (see ISPN-12289) return super.addListenerAsync(listener); } }
816
25.354839
98
java
null
infinispan-main/anchored-keys/src/main/java/org/infinispan/anchored/impl/AnchoredEntryFactory.java
package org.infinispan.anchored.impl; import org.infinispan.container.entries.CacheEntry; import org.infinispan.container.entries.MVCCEntry; import org.infinispan.container.impl.EntryFactoryImpl; import org.infinispan.metadata.Metadata; import org.infinispan.metadata.impl.PrivateMetadata; /** * Store the key location in context entries. * * @author Dan Berindei * @since 11 */ public class AnchoredEntryFactory extends EntryFactoryImpl { @Override protected MVCCEntry<?, ?> createWrappedEntry(Object key, CacheEntry<?, ?> cacheEntry) { Object value = null; Metadata metadata = null; PrivateMetadata internalMetadata = null; if (cacheEntry != null) { value = cacheEntry.getValue(); metadata = cacheEntry.getMetadata(); internalMetadata = cacheEntry.getInternalMetadata(); } MVCCEntry<?, ?> mvccEntry; mvccEntry = new AnchoredReadCommittedEntry(key, value, metadata); mvccEntry.setInternalMetadata(internalMetadata); if (cacheEntry != null) { mvccEntry.setCreated(cacheEntry.getCreated()); mvccEntry.setLastUsed(cacheEntry.getLastUsed()); } return mvccEntry; } }
1,191
31.216216
90
java
null
infinispan-main/anchored-keys/src/main/java/org/infinispan/anchored/impl/AnchoredReadCommittedEntry.java
package org.infinispan.anchored.impl; import static org.infinispan.commons.util.Util.toStr; import java.util.concurrent.CompletionStage; import org.infinispan.commons.util.Util; import org.infinispan.container.DataContainer; import org.infinispan.container.entries.CacheEntry; import org.infinispan.container.entries.ReadCommittedEntry; import org.infinispan.container.entries.RemoteMetadata; import org.infinispan.container.impl.InternalDataContainer; import org.infinispan.metadata.Metadata; import org.infinispan.remoting.transport.Address; import org.infinispan.commons.util.concurrent.CompletableFutures; /** * Extend a {@link ReadCommittedEntry} with the key location. * * @author Dan Berindei * @since 11 */ public class AnchoredReadCommittedEntry<K, V> extends ReadCommittedEntry<K, V> { private Address location; public AnchoredReadCommittedEntry(K key, V value, Metadata metadata) { super(key, value, metadata); } /** * @return The anchor location of the key, or {@code null} if the local node is the anchor location. */ public Address getLocation() { return location; } /** * Save the anchor location of the key outside the regular metadata. * * That way the primary can use the regular metadata for notifications/indexing and still store the location */ public void setLocation(Address location) { this.location = location; } public static void setMissingLocation(CacheEntry<?, ?> cacheEntry, Address location) { if (cacheEntry instanceof AnchoredReadCommittedEntry) { AnchoredReadCommittedEntry<?, ?> anchoredEntry = (AnchoredReadCommittedEntry<?, ?>) cacheEntry; if (anchoredEntry.getLocation() == null) { anchoredEntry.setLocation(location); } } } @Override public void commit(DataContainer<K,V> container) { if (isChanged() && !isRemoved()) { // Entry created/modified: only store the key location V newValue = location != null ? null : value; Metadata newMetadata = location != null ? new RemoteMetadata(location, null) : metadata; container.put(key, newValue, newMetadata); } else { super.commit(container); } } @Override public CompletionStage<Void> commit(int segment, InternalDataContainer<K, V> container) { if (isChanged() && !isRemoved()) { // Entry created/modified: only store the key location V newValue = location != null ? null : value; Metadata newMetadata = location != null ? new RemoteMetadata(location, null) : metadata; container.put(segment, key, newValue, newMetadata, internalMetadata, created, lastUsed); return CompletableFutures.completedNull(); } else { return super.commit(segment, container); } } @Override public String toString() { return getClass().getSimpleName() + "(" + Util.hexIdHashCode(this) + "){" + "key=" + toStr(key) + ", value=" + toStr(value) + ", isCreated=" + isCreated() + ", isChanged=" + isChanged() + ", isRemoved=" + isRemoved() + ", isExpired=" + isExpired() + ", skipLookup=" + skipLookup() + ", metadata=" + metadata + ", internalMetadata=" + internalMetadata + ", location=" + location + '}'; } }
3,420
34.635417
111
java
null
infinispan-main/anchored-keys/src/main/java/org/infinispan/anchored/impl/AnchoredDistributionInterceptor.java
package org.infinispan.anchored.impl; import java.util.Collection; import java.util.HashMap; import java.util.Map; import java.util.concurrent.CompletionStage; import java.util.function.Function; import org.infinispan.commands.AbstractVisitor; import org.infinispan.commands.CommandsFactory; import org.infinispan.commands.ReplicableCommand; import org.infinispan.commands.VisitableCommand; import org.infinispan.commands.write.AbstractDataWriteCommand; import org.infinispan.commands.write.DataWriteCommand; import org.infinispan.commands.write.PutKeyValueCommand; import org.infinispan.commands.write.PutMapCommand; import org.infinispan.commands.write.RemoveCommand; import org.infinispan.commands.write.ReplaceCommand; import org.infinispan.commands.write.ValueMatcher; import org.infinispan.commands.write.WriteCommand; import org.infinispan.commons.CacheException; import org.infinispan.commons.util.IntSet; import org.infinispan.container.entries.CacheEntry; import org.infinispan.container.entries.RemoteMetadata; import org.infinispan.context.InvocationContext; import org.infinispan.distribution.DistributionInfo; import org.infinispan.distribution.LocalizedCacheTopology; import org.infinispan.factories.annotations.Inject; import org.infinispan.interceptors.distribution.NonTxDistributionInterceptor; import org.infinispan.interceptors.distribution.WriteManyCommandHelper; import org.infinispan.metadata.Metadata; import org.infinispan.remoting.RemoteException; import org.infinispan.remoting.responses.Response; import org.infinispan.remoting.rpc.RpcOptions; import org.infinispan.remoting.transport.Address; import org.infinispan.remoting.transport.impl.MapResponseCollector; import org.infinispan.commons.util.concurrent.CompletableFutures; import org.infinispan.util.CacheTopologyUtil; import org.infinispan.util.logging.Log; import org.infinispan.util.logging.LogFactory; /** * A {@link NonTxDistributionInterceptor} replacement for anchored caches. * * <p>The interceptor behaves mostly like {@link NonTxDistributionInterceptor}, * but when the primary sends the command to the backups it only sends the actual value * to the key's anchor owner.</p> * * <p>If the key is new, the anchor owner is the last member of the read CH. * If the key already exists in the cache, the anchor owner is preserved.</p> * * @author Dan Berindei * @since 11 */ public class AnchoredDistributionInterceptor extends NonTxDistributionInterceptor { // TODO Investigate extending TriangleDistributionInterceptor instead of NonTxDistributionInterceptor private static final Log log = LogFactory.getLog(AnchoredDistributionInterceptor.class); @Inject CommandsFactory commandsFactory; @Inject AnchorManager anchorManager; @Override protected Object primaryReturnHandler(InvocationContext ctx, AbstractDataWriteCommand command, Object localResult) { if (!command.isSuccessful()) { if (log.isTraceEnabled()) log.tracef( "Skipping the replication of the conditional command as it did not succeed on primary owner (%s).", command); return localResult; } LocalizedCacheTopology cacheTopology = CacheTopologyUtil.checkTopology(command, distributionManager.getCacheTopology()); DistributionInfo distributionInfo = cacheTopology.getSegmentDistribution(command.getSegment()); Collection<Address> owners = distributionInfo.writeOwners(); if (owners.size() == 1) { // There are no backups, skip the replication part. return localResult; } // Match always on the backups, but save the original matcher for retries ValueMatcher originalMatcher = command.getValueMatcher(); command.setValueMatcher(ValueMatcher.MATCH_ALWAYS); CommandCopier commandCopier = new CommandCopier(ctx, command); // Ignore the previous value on the backup owners assert isSynchronous(command); MapResponseCollector collector = MapResponseCollector.ignoreLeavers(isReplicated, owners.size()); RpcOptions rpcOptions = rpcManager.getSyncRpcOptions(); CompletionStage<Map<Address, Response>> remoteInvocation = rpcManager.invokeCommands(distributionInfo.writeBackups(), commandCopier, collector, rpcOptions); return asyncValue(remoteInvocation.handle((responses, t) -> { // Switch to the retry policy, in case the primary owner changed // and the write already succeeded on the new primary command.setValueMatcher(originalMatcher.matcherForRetry()); CompletableFutures.rethrowExceptionIfPresent(t instanceof RemoteException ? t.getCause() : t); return localResult; })); } @Override protected <C extends WriteCommand, Container, Item> Object handleReadWriteManyCommand(InvocationContext ctx, C command, WriteManyCommandHelper<C, Item, Container> helper) throws Exception { WriteManyCommandHelper wrappedHelper = new AbstractDelegatingWriteManyCommandHelper(helper) { @Override public WriteCommand copyForBackup(WriteCommand cmd, LocalizedCacheTopology topology, Address target, IntSet segments) { WriteCommand backupCommand = helper.copyForBackup(cmd, topology, target, segments); CommandCopier commandCopier = new CommandCopier(ctx, backupCommand); return (WriteCommand) commandCopier.apply(target); } }; return super.handleReadWriteManyCommand(ctx, command, wrappedHelper); } @Override public Object visitPutMapCommand(InvocationContext ctx, PutMapCommand command) throws Throwable { if (command.isForwarded()) { assert command.getMetadata() == null || command.getMetadata().version() == null; HashMap<Object, Object> valueMap = new HashMap<>(); for (Map.Entry<?, ?> entry : command.getMap().entrySet()) { Object key = entry.getKey(); CacheEntry ctxEntry = ctx.lookupEntry(key); if (ctxEntry != null && entry.getValue() instanceof RemoteMetadata) { RemoteMetadata entryMetadata = (RemoteMetadata) entry.getValue(); ctxEntry.setMetadata(entryMetadata); valueMap.put(key, null); } else { valueMap.put(key, entry.getValue()); } } command.setMap(valueMap); } return super.visitPutMapCommand(ctx, command); } Address getKeyWriter(CacheEntry<?, ?> contextEntry) { // Use the existing location, or the one set by AnchoredFetchInterceptor Address location = ((AnchoredReadCommittedEntry) contextEntry).getLocation(); return location != null ? location : rpcManager.getAddress(); } /** * Replaces the value with null and the metadata with a RemoteMetadata instance containing the anchor location. * * <p>It is used only on the primary owner to copy the command for the backups.</p> * <p>Does not replace the value if the target is the anchor location.</p> * <p>Assumes the value matcher is already set to MATCH_ALWAYS.</p> */ class CommandCopier extends AbstractVisitor implements Function<Address, ReplicableCommand> { private final InvocationContext ctx; private final VisitableCommand command; private Address target; CommandCopier(InvocationContext ctx, VisitableCommand command) { this.ctx = ctx; this.command = command; } @Override public ReplicableCommand apply(Address address) { this.target = address; try { return (ReplicableCommand) command.acceptVisitor(ctx, this); } catch (Throwable throwable) { throw new CacheException(throwable); } } @Override public Object visitPutKeyValueCommand(InvocationContext ctx, PutKeyValueCommand command) { return replaceWithPutRemoteMetadata(ctx, command); } @Override public Object visitReplaceCommand(InvocationContext ctx, ReplaceCommand command) { return replaceWithPutRemoteMetadata(ctx, command); } @Override public Object visitRemoveCommand(InvocationContext ctx, RemoveCommand command) { return command; } private VisitableCommand replaceWithPutRemoteMetadata(InvocationContext ctx, DataWriteCommand command) { Object key = command.getKey(); Address keyWriter = getKeyWriter(ctx.lookupEntry(key)); if (target.equals(keyWriter)) { // This is the real owner, send the proper value and metadata return command; } Metadata metadata = new RemoteMetadata(keyWriter, null); PutKeyValueCommand copy = new PutKeyValueCommand(key, null, false, false, metadata, command.getSegment(), command.getFlagsBitSet(), command.getCommandInvocationId()); copy.setValueMatcher(command.getValueMatcher()); copy.setTopologyId(command.getTopologyId()); return copy; } @Override public Object visitPutMapCommand(InvocationContext ctx, PutMapCommand command) { Map<Object, Object> mapCopy = new HashMap<>(command.getMap().size() * 2); for (Map.Entry<Object, Object> entry : command.getMap().entrySet()) { Object key = entry.getKey(); Address keyWriter = getKeyWriter(ctx.lookupEntry(key)); Metadata metadata = new RemoteMetadata(keyWriter, null); if (!target.equals(keyWriter)) { // There's a single metadata instance for each PutMapCommand, so we store the location in the value instead mapCopy.put(key, metadata); } else { mapCopy.put(key, entry.getValue()); } } // WriteManyCommandHelper already copied the command, so we can modify it in-place command.setMap(mapCopy); return command; } @Override protected Object handleDefault(InvocationContext ctx, VisitableCommand command) { throw new UnsupportedOperationException( "Command type " + command.getClass() + " is not yet supported in anchored caches"); } } }
10,367
43.307692
126
java
null
infinispan-main/quarkus/cli/src/main/java/org/infinispan/cli/quarkus/CliQuarkus.java
package org.infinispan.cli.quarkus; import java.io.IOException; import org.infinispan.cli.commands.CLI; import io.quarkus.runtime.annotations.QuarkusMain; /** * @author Tristan Tarrant &lt;tristan@infinispan.org&gt; * @since 12.0 **/ @QuarkusMain public class CliQuarkus { public static void main(String[] args) throws IOException { CLI.main(args); } }
372
18.631579
62
java
null
infinispan-main/quarkus/cli/src/main/java/org/infinispan/cli/quarkus/SubstituteStoreMigratorHelper.java
package org.infinispan.cli.quarkus; import java.util.Properties; import org.infinispan.cli.impl.StoreMigratorHelper; import com.oracle.svm.core.annotate.Substitute; import com.oracle.svm.core.annotate.TargetClass; /** * @since 15.0 **/ @TargetClass(StoreMigratorHelper.class) @Substitute public final class SubstituteStoreMigratorHelper { @Substitute public static void run(Properties props, boolean verbose) throws Exception { throw new UnsupportedOperationException("The native CLI doesn't implement store migration. Use the JVM version instead."); } }
577
25.272727
128
java
null
infinispan-main/quarkus/embedded/runtime/src/main/java/org/infinispan/quarkus/embedded/runtime/InfinispanEmbeddedRuntimeConfig.java
package org.infinispan.quarkus.embedded.runtime; import java.util.Optional; import io.quarkus.runtime.annotations.ConfigItem; import io.quarkus.runtime.annotations.ConfigPhase; import io.quarkus.runtime.annotations.ConfigRoot; /** * @author wburns */ @ConfigRoot(name = "infinispan-embedded", phase = ConfigPhase.RUN_TIME) public class InfinispanEmbeddedRuntimeConfig { /** * The configured Infinispan embedded xml file which is used by the managed EmbeddedCacheManager and its Caches */ @ConfigItem public Optional<String> xmlConfig; @Override public String toString() { return "InfinispanEmbeddedRuntimeConfig{" + "xmlConfig=" + xmlConfig + '}'; } }
733
25.214286
115
java
null
infinispan-main/quarkus/embedded/runtime/src/main/java/org/infinispan/quarkus/embedded/runtime/InfinispanRecorder.java
package org.infinispan.quarkus.embedded.runtime; import io.quarkus.arc.Arc; import io.quarkus.runtime.annotations.Recorder; @Recorder public class InfinispanRecorder { public void configureRuntimeProperties(InfinispanEmbeddedRuntimeConfig infinispanEmbeddedRuntimeConfig) { InfinispanEmbeddedProducer iep = Arc.container().instance(InfinispanEmbeddedProducer.class).get(); iep.setRuntimeConfig(infinispanEmbeddedRuntimeConfig); } }
459
31.857143
109
java
null
infinispan-main/quarkus/embedded/runtime/src/main/java/org/infinispan/quarkus/embedded/runtime/InfinispanEmbeddedProducer.java
package org.infinispan.quarkus.embedded.runtime; import java.io.IOException; import java.io.InputStream; import java.util.Map; import org.infinispan.commons.CacheConfigurationException; import org.infinispan.commons.configuration.attributes.Attribute; import org.infinispan.commons.configuration.attributes.AttributeSet; import org.infinispan.commons.configuration.io.ConfigurationResourceResolvers; import org.infinispan.commons.dataconversion.MediaType; import org.infinispan.commons.tx.lookup.TransactionManagerLookup; import org.infinispan.commons.util.FileLookupFactory; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.cache.TransactionConfiguration; import org.infinispan.configuration.cache.TransactionConfigurationBuilder; import org.infinispan.configuration.parsing.ConfigurationBuilderHolder; import org.infinispan.configuration.parsing.ParserRegistry; import org.infinispan.manager.DefaultCacheManager; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.transaction.lookup.JBossStandaloneJTAManagerLookup; import jakarta.enterprise.context.ApplicationScoped; import jakarta.enterprise.inject.Produces; import jakarta.inject.Singleton; @ApplicationScoped public class InfinispanEmbeddedProducer { private volatile InfinispanEmbeddedRuntimeConfig config; public void setRuntimeConfig(InfinispanEmbeddedRuntimeConfig config) { this.config = config; } @Singleton @Produces EmbeddedCacheManager manager() { if (config.xmlConfig.isPresent()) { String configurationFile = config.xmlConfig.get(); try { InputStream configurationStream = FileLookupFactory.newInstance().lookupFileStrict(configurationFile, Thread.currentThread().getContextClassLoader()); ConfigurationBuilderHolder configHolder = new ParserRegistry().parse(configurationStream, ConfigurationResourceResolvers.DEFAULT, MediaType.APPLICATION_XML); verifyTransactionConfiguration(configHolder.getDefaultConfigurationBuilder(), "default"); for (Map.Entry<String, ConfigurationBuilder> entry : configHolder.getNamedConfigurationBuilders().entrySet()) { verifyTransactionConfiguration(entry.getValue(), entry.getKey()); } return new DefaultCacheManager(configHolder, true); } catch (IOException e) { throw new RuntimeException(e); } } return new DefaultCacheManager(); } /** * Verifies that if a configuration has transactions enabled that it only uses the lookup that uses the * JBossStandaloneJTAManager, which looks up the transaction manager used by Quarkus * * @param configurationBuilder the current configuration * @param cacheName the cache for the configuration */ private void verifyTransactionConfiguration(ConfigurationBuilder configurationBuilder, String cacheName) { TransactionConfigurationBuilder transactionConfigurationBuilder = configurationBuilder.transaction(); if (transactionConfigurationBuilder.transactionMode() != null && transactionConfigurationBuilder.transactionMode().isTransactional()) { AttributeSet attributes = transactionConfigurationBuilder.attributes(); Attribute<TransactionManagerLookup> managerLookup = attributes .attribute(TransactionConfiguration.TRANSACTION_MANAGER_LOOKUP); if (managerLookup.isModified() && !(managerLookup.get() instanceof JBossStandaloneJTAManagerLookup)) { throw new CacheConfigurationException( "Only JBossStandaloneJTAManagerLookup transaction manager lookup is supported. Cache " + cacheName + " is misconfigured!"); } managerLookup.set(new JBossStandaloneJTAManagerLookup()); } } }
3,995
48.95
173
java
null
infinispan-main/quarkus/embedded/deployment/src/main/java/org/infinispan/quarkus/embedded/deployment/InfinispanReflectionExcludedBuildItem.java
package org.infinispan.quarkus.embedded.deployment; import org.jboss.jandex.DotName; import io.quarkus.builder.item.MultiBuildItem; /** * BuildItem that is used by extensions on top of Infinispan Embedded that can * dictate what classes should not be added to reflection list. This can be * used when an extension has additional classes that implement a given interface * that embedded looks for, but doesn't want it added to via Reflection. The end * result is that the classes are not loaded as reachable and can eliminate many * code paths if necessary. An example may be if indexing is disabled they may want * to remove indexing based classes from reflection list. */ public final class InfinispanReflectionExcludedBuildItem extends MultiBuildItem { private final DotName excludedClass; public InfinispanReflectionExcludedBuildItem(DotName excludedClass) { this.excludedClass = excludedClass; } public DotName getExcludedClass() { return excludedClass; } }
1,012
35.178571
83
java
null
infinispan-main/quarkus/embedded/deployment/src/main/java/org/infinispan/quarkus/embedded/deployment/InfinispanEmbeddedProcessor.java
package org.infinispan.quarkus.embedded.deployment; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.ServiceLoader; import java.util.Set; import org.infinispan.commons.marshall.AbstractExternalizer; import org.infinispan.commons.marshall.AdvancedExternalizer; import org.infinispan.configuration.parsing.ConfigurationParser; import org.infinispan.factories.impl.ModuleMetadataBuilder; import org.infinispan.interceptors.AsyncInterceptor; import org.infinispan.notifications.Listener; import org.infinispan.persistence.spi.CacheWriter; import org.infinispan.persistence.spi.NonBlockingStore; import org.infinispan.quarkus.embedded.runtime.InfinispanEmbeddedProducer; import org.infinispan.quarkus.embedded.runtime.InfinispanEmbeddedRuntimeConfig; import org.infinispan.quarkus.embedded.runtime.InfinispanRecorder; import org.jboss.jandex.AnnotationInstance; import org.jboss.jandex.AnnotationTarget; import org.jboss.jandex.ClassInfo; import org.jboss.jandex.DotName; import org.jboss.jandex.Index; import org.jboss.jandex.IndexView; import com.github.benmanes.caffeine.cache.CacheLoader; import io.quarkus.arc.deployment.AdditionalBeanBuildItem; import io.quarkus.deployment.annotations.BuildProducer; import io.quarkus.deployment.annotations.BuildStep; import io.quarkus.deployment.annotations.ExecutionTime; import io.quarkus.deployment.annotations.Record; import io.quarkus.deployment.builditem.ApplicationIndexBuildItem; import io.quarkus.deployment.builditem.CombinedIndexBuildItem; import io.quarkus.deployment.builditem.IndexDependencyBuildItem; import io.quarkus.deployment.builditem.nativeimage.ReflectiveClassBuildItem; import io.quarkus.deployment.builditem.nativeimage.ServiceProviderBuildItem; class InfinispanEmbeddedProcessor { @BuildStep void addInfinispanDependencies(BuildProducer<IndexDependencyBuildItem> indexDependency) { indexDependency.produce(new IndexDependencyBuildItem("org.jgroups", "jgroups")); indexDependency.produce(new IndexDependencyBuildItem("org.infinispan", "infinispan-commons")); indexDependency.produce(new IndexDependencyBuildItem("org.infinispan", "infinispan-core")); } @BuildStep void setup(BuildProducer<ReflectiveClassBuildItem> reflectiveClass, BuildProducer<ServiceProviderBuildItem> serviceProvider, BuildProducer<AdditionalBeanBuildItem> additionalBeans, CombinedIndexBuildItem combinedIndexBuildItem, List<InfinispanReflectionExcludedBuildItem> excludedReflectionClasses, ApplicationIndexBuildItem applicationIndexBuildItem) { additionalBeans.produce(AdditionalBeanBuildItem.unremovableOf(InfinispanEmbeddedProducer.class)); for (Class<?> serviceLoadedInterface : Arrays.asList(ModuleMetadataBuilder.class, ConfigurationParser.class)) { // Need to register all the modules as service providers so they can be picked up at runtime ServiceLoader<?> serviceLoader = ServiceLoader.load(serviceLoadedInterface); List<String> interfaceImplementations = new ArrayList<>(); serviceLoader.forEach(mmb -> interfaceImplementations.add(mmb.getClass().getName())); if (!interfaceImplementations.isEmpty()) { serviceProvider .produce(new ServiceProviderBuildItem(serviceLoadedInterface.getName(), interfaceImplementations)); } } Set<DotName> excludedClasses = new HashSet<>(); excludedReflectionClasses.forEach(excludedBuildItem -> { excludedClasses.add(excludedBuildItem.getExcludedClass()); }); // This contains parts from the index from the app itself Index appOnlyIndex = applicationIndexBuildItem.getIndex(); // Persistence SPIs IndexView combinedIndex = combinedIndexBuildItem.getIndex(); // We need to use the CombinedIndex for these interfaces in order to discover implementations of the various // subclasses. addReflectionForClass(CacheLoader.class, combinedIndex, reflectiveClass, excludedClasses); addReflectionForClass(CacheWriter.class, combinedIndex, reflectiveClass, excludedClasses); addReflectionForClass(NonBlockingStore.class, combinedIndex, reflectiveClass, excludedClasses); addReflectionForName(AsyncInterceptor.class.getName(), true, combinedIndex, reflectiveClass, false, true, excludedClasses); // Add user listeners Collection<AnnotationInstance> listenerInstances = combinedIndex.getAnnotations( DotName.createSimple(Listener.class.getName()) ); for (AnnotationInstance instance : listenerInstances) { AnnotationTarget target = instance.target(); if (target.kind() == AnnotationTarget.Kind.CLASS) { DotName targetName = target.asClass().name(); if (!excludedClasses.contains(targetName)) { reflectiveClass.produce( ReflectiveClassBuildItem.builder(target.toString()).methods().build() ); } } } // We only register the app advanced externalizers as all of the Infinispan ones are explicitly defined addReflectionForClass(AdvancedExternalizer.class, appOnlyIndex, reflectiveClass, Collections.emptySet()); // Due to the index not containing AbstractExternalizer it doesn't know that it implements AdvancedExternalizer // thus we also have to include classes that extend AbstractExternalizer addReflectionForClass(AbstractExternalizer.class, appOnlyIndex, reflectiveClass, Collections.emptySet()); } private void addReflectionForClass(Class<?> classToUse, IndexView indexView, BuildProducer<ReflectiveClassBuildItem> reflectiveClass, Set<DotName> excludedClasses) { addReflectionForName(classToUse.getName(), classToUse.isInterface(), indexView, reflectiveClass, false, false, excludedClasses); } private void addReflectionForName(String className, boolean isInterface, IndexView indexView, BuildProducer<ReflectiveClassBuildItem> reflectiveClass, boolean methods, boolean fields, Set<DotName> excludedClasses) { Collection<ClassInfo> classInfos; if (isInterface) { classInfos = indexView.getAllKnownImplementors(DotName.createSimple(className)); } else { classInfos = indexView.getAllKnownSubclasses(DotName.createSimple(className)); } classInfos.removeIf(ci -> excludedClasses.contains(ci.name())); if (!classInfos.isEmpty()) { String[] classNames = classInfos.stream().map(ClassInfo::toString).toArray(String[]::new); reflectiveClass.produce( ReflectiveClassBuildItem.builder(classNames) .methods(methods) .fields(fields) .build() ); } } @Record(ExecutionTime.RUNTIME_INIT) @BuildStep void configureRuntimeProperties(InfinispanRecorder recorder, InfinispanEmbeddedRuntimeConfig runtimeConfig) { recorder.configureRuntimeProperties(runtimeConfig); } }
7,462
49.087248
131
java
null
infinispan-main/quarkus/server-runner/src/main/java/org/infininspan/quarkus/server/InfinispanQuarkusServer.java
package org.infininspan.quarkus.server; import org.infinispan.server.Bootstrap; import io.quarkus.runtime.QuarkusApplication; import io.quarkus.runtime.annotations.QuarkusMain; @QuarkusMain public class InfinispanQuarkusServer implements QuarkusApplication { @Override public int run(String... args) { Bootstrap.main(args); return 0; } }
363
20.411765
68
java
null
infinispan-main/quarkus/integration-tests/embedded/src/test/java/org/infinispan/quarkus/embedded/InfinispanEmbeddedTestResource.java
package org.infinispan.quarkus.embedded; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Collections; import java.util.Map; import java.util.stream.Stream; import org.infinispan.commons.util.Util; import io.quarkus.test.common.QuarkusTestResourceLifecycleManager; public class InfinispanEmbeddedTestResource implements QuarkusTestResourceLifecycleManager { @Override public Map<String, String> start() { String xmlLocation = Paths.get("src", "main", "resources", "embedded.xml").toString(); return Collections.singletonMap("quarkus.infinispan-embedded.xml-config", xmlLocation); } @Override public void stop() { // Need to clean up persistent file - so tests dont' leak between each other String tmpDir = System.getProperty("java.io.tmpdir"); try (Stream<Path> files = Files.walk(Paths.get(tmpDir), 1)) { files.filter(Files::isDirectory) .filter(p -> p.getFileName().toString().startsWith("quarkus-")) .map(Path::toFile) .forEach(Util::recursiveFileRemove); } catch (IOException e) { throw new RuntimeException(e); } } }
1,270
34.305556
95
java
null
infinispan-main/quarkus/integration-tests/embedded/src/test/java/org/infinispan/quarkus/embedded/InfinispanEmbeddedFunctionalityTest.java
package org.infinispan.quarkus.embedded; import static org.hamcrest.Matchers.is; import org.junit.jupiter.api.Test; import io.quarkus.test.junit.QuarkusTest; import io.restassured.RestAssured; /** * @author William Burns */ @QuarkusTest public class InfinispanEmbeddedFunctionalityTest { @Test public void testCache() { // This cache also has persistence testCache("local"); } @Test public void testOffHeapCache() { testCache("off-heap-memory"); } @Test public void testTransactionRolledBack() { String cacheName = "quarkus-transaction"; System.out.println("Running cache test for " + cacheName); RestAssured.when().get("/test/GET/" + cacheName + "/key").then().body(is("null")); // This should throw an exception and NOT commit the value RestAssured.when().get("/test/PUT/" + cacheName + "/key/something?shouldFail=true") .then() .statusCode(500); // Entry shouldn't have been committed RestAssured.when().get("/test/GET/" + cacheName + "/key").then().body(is("null")); } @Test public void testPutWithoutTransactionNotRolledBack() { String cacheName = "simple-cache"; System.out.println("Running cache test for " + cacheName); RestAssured.when().get("/test/GET/" + cacheName + "/key").then().body(is("null")); // This should throw an exception - but cache did put before RestAssured.when().get("/test/PUT/" + cacheName + "/key/something?shouldFail=true") .then() .statusCode(500); // Entry should be available RestAssured.when().get("/test/GET/" + cacheName + "/key").then().body(is("something")); } private void testCache(String cacheName) { System.out.println("Running cache test for " + cacheName); RestAssured.when().get("/test/GET/" + cacheName + "/key").then().body(is("null")); RestAssured.when().get("/test/PUT/" + cacheName + "/key/something").then().body(is("null")); RestAssured.when().get("/test/GET/" + cacheName + "/key").then().body(is("something")); RestAssured.when().get("/test/REMOVE/" + cacheName + "/key").then().body(is("something")); RestAssured.when().get("/test/GET/" + cacheName + "/key").then().body(is("null")); } @Test public void testSimpleCluster() { System.out.println("Running cluster test"); RestAssured.when().get("/test/CLUSTER").then().body(is("Success")); } }
2,546
34.873239
100
java
null
infinispan-main/quarkus/integration-tests/embedded/src/test/java/org/infinispan/quarkus/embedded/InfinispanEmbeddedFunctionalityInGraalITCase.java
package org.infinispan.quarkus.embedded; import io.quarkus.test.common.QuarkusTestResource; import io.quarkus.test.junit.QuarkusIntegrationTest; /** * @author William Burns */ @QuarkusTestResource(InfinispanEmbeddedTestResource.class) @QuarkusIntegrationTest public class InfinispanEmbeddedFunctionalityInGraalITCase extends InfinispanEmbeddedFunctionalityTest { }
370
25.5
103
java
null
infinispan-main/quarkus/integration-tests/embedded/src/main/java/org/infinispan/quarkus/embedded/TestAdvancedExternalizer.java
package org.infinispan.quarkus.embedded; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.util.Date; import java.util.Set; import org.infinispan.commons.marshall.AbstractExternalizer; import org.infinispan.commons.marshall.AdvancedExternalizer; import org.infinispan.commons.util.Util; /** * Contains various AdvancedExternalizers implementations to test with XML configuration */ public class TestAdvancedExternalizer { public static class IdViaConfigObj { String name; public IdViaConfigObj setName(String name) { this.name = name; return this; } public static class Externalizer implements AdvancedExternalizer<IdViaConfigObj> { @Override public void writeObject(ObjectOutput output, IdViaConfigObj object) throws IOException { output.writeUTF(object.name); } @Override public IdViaConfigObj readObject(ObjectInput input) throws IOException, ClassNotFoundException { return new IdViaConfigObj().setName(input.readUTF()); } @Override public Set<Class<? extends IdViaConfigObj>> getTypeClasses() { return Util.asSet(IdViaConfigObj.class); } @Override public Integer getId() { return null; } } } public static class IdViaAnnotationObj { Date date; public IdViaAnnotationObj setDate(Date date) { this.date = date; return this; } public static class Externalizer extends AbstractExternalizer<IdViaAnnotationObj> { @Override public void writeObject(ObjectOutput output, IdViaAnnotationObj object) throws IOException { output.writeObject(object.date); } @Override public IdViaAnnotationObj readObject(ObjectInput input) throws IOException, ClassNotFoundException { return new IdViaAnnotationObj().setDate((Date) input.readObject()); } @Override public Integer getId() { return 5678; } @Override public Set<Class<? extends IdViaAnnotationObj>> getTypeClasses() { return Util.asSet(IdViaAnnotationObj.class); } } } }
2,436
29.4625
112
java
null
infinispan-main/quarkus/integration-tests/embedded/src/main/java/org/infinispan/quarkus/embedded/CustomMBeanServerLookup.java
package org.infinispan.quarkus.embedded; import java.lang.management.ManagementFactory; import java.util.Properties; import javax.management.MBeanServer; import org.infinispan.commons.jmx.MBeanServerLookup; // Here to test a custom mbean lookup configured via XML // Note this class will not be used during native as JMX is not supported public class CustomMBeanServerLookup implements MBeanServerLookup { @Override public MBeanServer getMBeanServer(Properties properties) { return ManagementFactory.getPlatformMBeanServer(); } }
555
28.263158
73
java
null
infinispan-main/quarkus/integration-tests/embedded/src/main/java/org/infinispan/quarkus/embedded/TestCacheLoader.java
package org.infinispan.quarkus.embedded; import java.util.concurrent.Executor; import java.util.function.Predicate; import org.infinispan.persistence.spi.AdvancedLoadWriteStore; import org.infinispan.persistence.spi.InitializationContext; import org.infinispan.persistence.spi.MarshallableEntry; import org.reactivestreams.Publisher; // Here to test a custom cache loader configured via XML public class TestCacheLoader implements AdvancedLoadWriteStore { @Override public int size() { return 0; } @Override public Publisher<MarshallableEntry> entryPublisher(Predicate filter, boolean fetchValue, boolean fetchMetadata) { return null; } @Override public void clear() { } @Override public void purge(Executor threadPool, PurgeListener listener) { } @Override public void init(InitializationContext ctx) { } @Override public void write(MarshallableEntry entry) { } @Override public MarshallableEntry loadEntry(Object key) { return null; } @Override public boolean delete(Object key) { return false; } @Override public boolean contains(Object key) { return false; } @Override public void start() { } @Override public void stop() { } }
1,323
18.470588
117
java
null
infinispan-main/quarkus/integration-tests/embedded/src/main/java/org/infinispan/quarkus/embedded/EventListener.java
package org.infinispan.quarkus.embedded; import jakarta.enterprise.context.ApplicationScoped; import jakarta.enterprise.event.Observes; import jakarta.inject.Inject; import org.infinispan.manager.EmbeddedCacheManager; import io.quarkus.runtime.StartupEvent; /** * This class is here solely to ensure that if you have more than 1 application scoped bean that references the cache * manager that it works properly and doesn't create a new one (the second cache manager would fail to start if not fixed) */ @ApplicationScoped public class EventListener { @Inject EmbeddedCacheManager cacheManager; public void onStartup(@Observes StartupEvent event) { // do something on startup System.out.println("Starting test application"); } }
770
28.653846
122
java
null
infinispan-main/quarkus/integration-tests/embedded/src/main/java/org/infinispan/quarkus/embedded/TestServlet.java
package org.infinispan.quarkus.embedded; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import java.util.concurrent.TimeUnit; import jakarta.enterprise.event.Observes; import jakarta.inject.Inject; import jakarta.transaction.Transactional; import jakarta.ws.rs.GET; import jakarta.ws.rs.Path; import jakarta.ws.rs.PathParam; import jakarta.ws.rs.Produces; import jakarta.ws.rs.QueryParam; import jakarta.ws.rs.core.MediaType; import org.infinispan.Cache; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.manager.DefaultCacheManager; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.util.logging.Log; import org.infinispan.util.logging.LogFactory; import io.quarkus.runtime.StartupEvent; @Path("/test") public class TestServlet { private static final Log log = LogFactory.getLog(TestServlet.class); @Inject EmbeddedCacheManager emc; // Having on start method will eagerly initialize the cache manager which in turn starts up clustered cache void onStart(@Observes StartupEvent ev) { log.info("The application is starting..."); } @Path("GET/{cacheName}/{id}") @GET @Produces(MediaType.TEXT_PLAIN) public String get(@PathParam("cacheName") String cacheName, @PathParam("id") String id) { log.info("Retrieving " + id + " from " + cacheName); Cache<byte[], byte[]> cache = emc.getCache(cacheName); byte[] result = cache.get(id.getBytes(StandardCharsets.UTF_8)); return result == null ? "null" : new String(result, StandardCharsets.UTF_8); } @Transactional @Path("PUT/{cacheName}/{id}/{value}") @GET @Produces(MediaType.TEXT_PLAIN) public String put(@PathParam("cacheName") String cacheName, @PathParam("id") String id, @PathParam("value") String value, @QueryParam("shouldFail") String shouldFail) { log.info("Putting " + id + " with value: " + value + " into " + cacheName); Cache<byte[], byte[]> cache = emc.getCache(cacheName); byte[] result = cache.put(id.getBytes(StandardCharsets.UTF_8), value.getBytes(StandardCharsets.UTF_8)); if (Boolean.parseBoolean(shouldFail)) { throw new RuntimeException("Forced Exception!"); } return result == null ? "null" : new String(result, StandardCharsets.UTF_8); } @Path("REMOVE/{cacheName}/{id}") @GET @Produces(MediaType.TEXT_PLAIN) public String remove(@PathParam("cacheName") String cacheName, @PathParam("id") String id) { log.info("Removing " + id + " from " + cacheName); Cache<byte[], byte[]> cache = emc.getCache(cacheName); byte[] result = cache.remove(id.getBytes(StandardCharsets.UTF_8)); return result == null ? "null" : new String(result, StandardCharsets.UTF_8); } @Path("CLUSTER") @GET @Produces(MediaType.TEXT_PLAIN) public String simpleCluster() throws IOException { ConfigurationBuilder configurationBuilder = new ConfigurationBuilder(); configurationBuilder.clustering().cacheMode(CacheMode.DIST_SYNC); List<EmbeddedCacheManager> managers = new ArrayList<>(3); try { // Force TCP to connect to loopback, which our TCPPING in dist.xml connects to for discovery String oldProperty = System.setProperty("jgroups.tcp.address", "127.0.0.1"); for (int i = 0; i < 3; i++) { EmbeddedCacheManager ecm = new DefaultCacheManager( Paths.get("src", "main", "resources", "dist.xml").toString()); ecm.start(); managers.add(ecm); // Start the default cache ecm.getCache(); } if (oldProperty != null) { System.setProperty("jgroups.tcp.address", oldProperty); } long failureTime = System.nanoTime() + TimeUnit.SECONDS.toNanos(10); int sizeMatched = 0; while (sizeMatched < 3) { // reset the size every time sizeMatched = 0; for (EmbeddedCacheManager ecm : managers) { int size = ecm.getMembers().size(); if (size == 3) { sizeMatched++; } } if (failureTime - System.nanoTime() < 0) { return "Timed out waiting for caches to have joined together!"; } } } finally { managers.forEach(EmbeddedCacheManager::stop); } return "Success"; } }
4,762
37.723577
125
java
null
infinispan-main/quarkus/integration-tests/embedded/src/main/java/org/infinispan/quarkus/embedded/CustomInterceptor.java
package org.infinispan.quarkus.embedded; import org.infinispan.interceptors.BaseCustomAsyncInterceptor; // Here to test a custom intereceptor configured via XML public class CustomInterceptor extends BaseCustomAsyncInterceptor { String foo; // configured via XML }
271
29.222222
67
java
null
infinispan-main/quarkus/integration-tests/server/src/test/java/org/infinispan/quarkus/server/NativeCliIT.java
package org.infinispan.quarkus.server; import static org.infinispan.server.test.core.Common.sync; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.fail; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.nio.file.Paths; import java.util.concurrent.TimeUnit; import org.infinispan.client.rest.RestCacheManagerClient; import org.infinispan.client.rest.RestClient; import org.infinispan.client.rest.RestResponse; import org.infinispan.server.test.junit5.InfinispanServerExtension; import org.infinispan.server.test.junit5.InfinispanServerExtensionBuilder; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; /** * Test to ensure that the native quarkus CLI is able to execute. * * @author Ryan Emerson * @since 12.1 */ public class NativeCliIT { @RegisterExtension public static final InfinispanServerExtension SERVERS = InfinispanServerExtensionBuilder.config("configuration/ClusteredServerTest.xml") .numServers(1) .build(); @Test public void testCliBatch() throws Exception { RestClient client = SERVERS.rest().create(); RestCacheManagerClient cm = client.cacheManager("default"); RestResponse restResponse = sync(cm.healthStatus()); assertEquals(200, restResponse.getStatus()); assertEquals("HEALTHY", restResponse.getBody()); String cliPath = resource("ispn-cli"); String batchFile = resource("batch.file"); String hostname = SERVERS.getTestServer().getDriver().getServerAddress(0).getHostAddress() + ":11222"; String cliCmd = String.format("%s --connect %s --file=%s", cliPath, hostname, batchFile); ProcessBuilder pb = new ProcessBuilder("bash", "-c", cliCmd); pb.redirectOutput(ProcessBuilder.Redirect.INHERIT); Process p = pb.start(); StringBuilder sb = new StringBuilder(); new Thread(() -> { try (BufferedReader reader = new BufferedReader(new InputStreamReader(p.getErrorStream()))) { String line; while ((line = reader.readLine()) != null) { sb.append(line); } } catch (IOException e) { throw new RuntimeException(e); } }).start(); p.waitFor(5, TimeUnit.SECONDS); String stderr = sb.toString(); if (!stderr.isEmpty()) { System.err.println(stderr); fail("Unexpected CLI output in stderr"); } assertEquals(0, p.exitValue()); restResponse = sync(client.cache("mybatch").exists()); assertEquals(204, restResponse.getStatus()); } private String resource(String name) throws Exception { return Paths.get(NativeCliIT.class.getClassLoader().getResource(name).toURI()).toString(); } }
2,860
36.155844
108
java
null
infinispan-main/quarkus/integration-tests/server/src/test/java/org/infinispan/quarkus/server/RestCacheManagerResource.java
package org.infinispan.quarkus.server; import static org.infinispan.server.test.core.AbstractInfinispanServerDriver.abbreviate; import static org.infinispan.server.test.core.Common.sync; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; import org.infinispan.client.rest.RestCacheManagerClient; import org.infinispan.client.rest.RestClient; import org.infinispan.client.rest.RestResponse; import org.infinispan.server.test.junit5.InfinispanServerExtension; import org.infinispan.server.test.junit5.InfinispanServerExtensionBuilder; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ArrayNode; /** * @author Ryan Emerson * @since 11.0 */ public class RestCacheManagerResource { @RegisterExtension public static final InfinispanServerExtension SERVERS = InfinispanServerExtensionBuilder.config("configuration/ClusteredServerTest.xml") .numServers(2) .property("infinispan.bind.address", "0.0.0.0") .build(); private final ObjectMapper mapper = new ObjectMapper(); @Test public void testHealthStatus() throws Exception { RestResponse restResponse = sync(client().healthStatus()); assertEquals(200, restResponse.getStatus()); assertEquals("HEALTHY", restResponse.getBody()); } @Test public void testHealthInfo() throws Exception { RestResponse restResponse = sync(client().health()); assertEquals(200, restResponse.getStatus()); JsonNode root = mapper.readTree(restResponse.getBody()); JsonNode clusterHealth = root.get("cluster_health"); assertEquals(abbreviate(RestCacheManagerResource.class.getName()), clusterHealth.get("cluster_name").asText()); assertEquals("HEALTHY", clusterHealth.get("health_status").asText()); assertEquals(2, clusterHealth.get("number_of_nodes").asInt()); assertEquals(2, clusterHealth.withArray("node_names").size()); ArrayNode cacheHealth = root.withArray("cache_health"); cacheHealth.forEach(cache -> { assertEquals("HEALTHY", cache.get("status").asText()); assertNotNull(cache.get("cache_name")); }); } @Test public void testNamedCacheConfiguration() throws Exception { RestResponse restResponse = sync(client().cacheConfigurations()); assertEquals(200, restResponse.getStatus()); ArrayNode configArray = (ArrayNode) mapper.readTree(restResponse.getBody()); configArray.forEach(config -> { assertNotNull(config.get("name")); assertNotNull(config.get("configuration")); }); } @Test public void testCacheInfo() throws Exception { RestClient client = SERVERS.rest().create(); String cacheName = "test"; RestResponse restResponse = sync(client.cache(cacheName).createWithTemplate("org.infinispan.LOCAL")); assertEquals(200, restResponse.getStatus()); restResponse = sync(client.raw().get("/rest/v2/cache-managers/default/caches")); assertEquals(200, restResponse.getStatus()); ArrayNode cacheArray = (ArrayNode) mapper.readTree(restResponse.getBody()); assertNotNull(cacheArray); cacheArray.forEach(cache -> { assertEquals("RUNNING", cache.get("status").asText()); assertEquals("HEALTHY", cache.get("health").asText()); if (cacheName.equals(cache.get("name").asText())) { assertEquals("local-cache", cache.get("type").asText()); assertFalse(cache.get("simple_cache").asBoolean()); assertFalse(cache.get("transactional").asBoolean()); assertFalse(cache.get("persistent").asBoolean()); assertFalse(cache.get("bounded").asBoolean()); assertFalse(cache.get("indexed").asBoolean()); assertFalse(cache.get("secured").asBoolean()); assertFalse(cache.get("has_remote_backup").asBoolean()); } }); } private RestCacheManagerClient client() { return SERVERS.rest().create().cacheManager("default"); } }
4,307
39.641509
117
java
null
infinispan-main/quarkus/integration-tests/server/src/test/java/org/infinispan/quarkus/server/NativeClusteredIT.java
package org.infinispan.quarkus.server; import org.infinispan.server.functional.ClusteredIT; import org.infinispan.server.functional.hotrod.HotRodCacheOperations; import org.infinispan.server.functional.hotrod.HotRodCounterOperations; import org.infinispan.server.functional.hotrod.HotRodMultiMapOperations; import org.infinispan.server.functional.hotrod.HotRodTransactionalCacheOperations; import org.infinispan.server.functional.rest.RestOperations; import org.infinispan.server.functional.rest.RestRouter; import org.junit.platform.suite.api.SelectClasses; import org.junit.platform.suite.api.Suite; /** * We must extend {@link ClusteredIT} so that we can specify the test classes required in the suite. All of these tests * rely on {@code InfinispanServerRule SERVERS = ClusteredIT.SERVERS;}, so it's not possible to simply execute them * outside of a suite as the containers are shutdown after the first test class has completed. * * @author Ryan Emerson * @since 11.0 */ @Suite @SelectClasses({ HotRodCacheOperations.class, HotRodCounterOperations.class, HotRodMultiMapOperations.class, HotRodTransactionalCacheOperations.class, RestOperations.class, RestRouter.class, }) public class NativeClusteredIT extends ClusteredIT { }
1,277
38.9375
119
java