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/cdi/common/src/main/java/org/infinispan/cdi/common/util/Reflections.java
package org.infinispan.cdi.common.util; import java.io.Serializable; import java.lang.annotation.Annotation; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.lang.reflect.TypeVariable; import java.lang.reflect.WildcardType; import java.util.HashSet; import java.util.Set; import jakarta.enterprise.inject.spi.Annotated; import jakarta.enterprise.inject.spi.BeanManager; /** * Utility class for working with JDK Reflection and also CDI's * {@link Annotated} metadata. * * @author Stuart Douglas * @author Pete Muir */ public class Reflections { /** * An empty array of type {@link Annotation}, useful converting lists to * arrays. */ public static final Annotation[] EMPTY_ANNOTATION_ARRAY = new Annotation[0]; /** * An empty array of type {@link Object}, useful for converting lists to * arrays. */ public static final Object[] EMPTY_OBJECT_ARRAY = new Object[0]; public static final Type[] EMPTY_TYPES = {}; public static final Class<?>[] EMPTY_CLASSES = new Class<?>[0]; /** * <p> * Perform a runtime cast. Similar to {@link Class#cast(Object)}, but useful * when you do not have a {@link Class} object for type you wish to cast to. * </p> * <p/> * <p> * {@link Class#cast(Object)} should be used if possible * </p> * * @param <T> the type to cast to * @param obj the object to perform the cast on * @return the casted object * @throws ClassCastException if the type T is not a subtype of the object * @see Class#cast(Object) */ @SuppressWarnings("unchecked") public static <T> T cast(Object obj) { return (T) obj; } /** * Get all the declared methods on the class hierarchy. This <b>will</b> * return overridden methods. * * @param clazz The class to search * @return the set of all declared methods or an empty set if there are none */ public static Set<Method> getAllDeclaredMethods(Class<?> clazz) { HashSet<Method> methods = new HashSet<Method>(); for (Class<?> c = clazz; c != null && c != Object.class; c = c.getSuperclass()) { for (Method a : c.getDeclaredMethods()) { methods.add(a); } } return methods; } private static String buildInvokeMethodErrorMessage(Method method, Object obj, Object... args) { StringBuilder message = new StringBuilder(String.format("Exception invoking method [%s] on object [%s], using arguments [", method.getName(), obj)); if (args != null) for (int i = 0; i < args.length; i++) message.append((i > 0 ? "," : "") + args[i]); message.append("]"); return message.toString(); } /** * <p> * Invoke the specified method on the provided instance, passing any additional * arguments included in this method as arguments to the specified method. * </p> * <p/> * <p> * This method attempts to set the accessible flag of the method before invoking the method if the first argument * is true. * </p> * <p/> * <p>This method provides the same functionality and throws the same exceptions as * {@link Reflections#invokeMethod(boolean, Method, Class, Object, Object...)}, with the * expected return type set to {@link Object}.</p> * * @see Reflections#invokeMethod(boolean, Method, Class, Object, Object...) * @see Method#invoke(Object, Object...) */ public static Object invokeMethod(boolean setAccessible, Method method, Object instance, Object... args) { return invokeMethod(setAccessible, method, Object.class, instance, args); } /** * <p> * Invoke the specified method on the provided instance, passing any additional * arguments included in this method as arguments to the specified method. * </p> * <p/> * <p>This method provides the same functionality and throws the same exceptions as * {@link Reflections#invokeMethod(boolean, Method, Class, Object, Object...)}, with the * expected return type set to {@link Object} and honoring the accessibility of * the method.</p> * * @see Reflections#invokeMethod(boolean, Method, Class, Object, Object...) * @see Method#invoke(Object, Object...) */ public static <T> T invokeMethod(Method method, Class<T> expectedReturnType, Object instance, Object... args) { return invokeMethod(false, method, expectedReturnType, instance, args); } /** * <p> * Invoke the method on the instance, with any arguments specified, casting * the result of invoking the method to the expected return type. * </p> * <p/> * <p> * This method wraps {@link Method#invoke(Object, Object...)}, converting the * checked exceptions that {@link Method#invoke(Object, Object...)} specifies * to runtime exceptions. * </p> * <p/> * <p> * If instructed, this method attempts to set the accessible flag of the method before invoking the method. * </p> * * @param setAccessible flag indicating whether method should first be set as * accessible * @param method the method to invoke * @param instance the instance to invoke the method * @param args the arguments to the method * @return the result of invoking the method, or null if the method's return * type is void * @throws RuntimeException if this <code>Method</code> object enforces Java * language access control and the underlying method is * inaccessible or if the underlying method throws an exception or * if the initialization provoked by this method fails. * @throws IllegalArgumentException if the method is an instance method and * the specified <code>instance</code> argument is not an instance * of the class or interface declaring the underlying method (or * of a subclass or implementor thereof); if the number of actual * and formal parameters differ; if an unwrapping conversion for * primitive arguments fails; or if, after possible unwrapping, a * parameter value cannot be converted to the corresponding formal * parameter type by a method invocation conversion. * @throws NullPointerException if the specified <code>instance</code> is * null and the method is an instance method. * @throws ClassCastException if the result of invoking the method cannot be * cast to the expectedReturnType * @throws ExceptionInInitializerError if the initialization provoked by this * method fails. * @see Method#invoke(Object, Object...) */ public static <T> T invokeMethod(boolean setAccessible, Method method, Class<T> expectedReturnType, Object instance, Object... args) { if (setAccessible && !method.isAccessible()) { method.setAccessible(true); } try { return expectedReturnType.cast(method.invoke(instance, args)); } catch (IllegalAccessException ex) { throw new RuntimeException(buildInvokeMethodErrorMessage(method, instance, args), ex); } catch (IllegalArgumentException ex) { throw new IllegalArgumentException(buildInvokeMethodErrorMessage(method, instance, args), ex); } catch (InvocationTargetException ex) { throw new RuntimeException(buildInvokeMethodErrorMessage(method, instance, args), ex.getCause()); } catch (NullPointerException ex) { NullPointerException ex2 = new NullPointerException(buildInvokeMethodErrorMessage(method, instance, args)); ex2.initCause(ex.getCause()); throw ex2; } catch (ExceptionInInitializerError e) { ExceptionInInitializerError e2 = new ExceptionInInitializerError(buildInvokeMethodErrorMessage(method, instance, args)); e2.initCause(e.getCause()); throw e2; } } private static String buildGetFieldValueErrorMessage(Field field, Object obj) { return String.format("Exception reading [%s] field from object [%s].", field.getName(), obj); } /** * <p> * Get the value of the field, on the specified instance, casting the value * of the field to the expected type. * </p> * <p/> * <p> * This method wraps {@link Field#get(Object)}, converting the checked * exceptions that {@link Field#get(Object)} specifies to runtime exceptions. * </p> * * @param <T> the type of the field's value * @param field the field to operate on * @param instance the instance from which to retrieve the value * @param expectedType the expected type of the field's value * @return the value of the field * @throws RuntimeException if the underlying field is inaccessible. * @throws IllegalArgumentException if the specified <code>instance</code> is not an * instance of the class or interface declaring the underlying * field (or a subclass or implementor thereof). * @throws NullPointerException if the specified <code>instance</code> is null and the field * is an instance field. * @throws ExceptionInInitializerError if the initialization provoked by this * method fails. */ public static <T> T getFieldValue(Field field, Object instance, Class<T> expectedType) { try { return Reflections.cast(field.get(instance)); } catch (IllegalAccessException e) { throw new RuntimeException(buildGetFieldValueErrorMessage(field, instance), e); } catch (NullPointerException ex) { NullPointerException ex2 = new NullPointerException(buildGetFieldValueErrorMessage(field, instance)); ex2.initCause(ex.getCause()); throw ex2; } catch (ExceptionInInitializerError e) { ExceptionInInitializerError e2 = new ExceptionInInitializerError(buildGetFieldValueErrorMessage(field, instance)); e2.initCause(e.getCause()); throw e2; } } /** * Extract the raw type, given a type. * * @param <T> the type * @param type the type to extract the raw type from * @return the raw type, or null if the raw type cannot be determined. */ @SuppressWarnings("unchecked") public static <T> Class<T> getRawType(Type type) { if (type instanceof Class<?>) { return (Class<T>) type; } else if (type instanceof ParameterizedType) { if (((ParameterizedType) type).getRawType() instanceof Class<?>) { return (Class<T>) ((ParameterizedType) type).getRawType(); } } return null; } /** * Check if a class is serializable. * * @param clazz The class to check * @return true if the class implements serializable or is a primitive */ public static boolean isSerializable(Class<?> clazz) { return clazz.isPrimitive() || Serializable.class.isAssignableFrom(clazz); } /** * Check the assignability of one type to another, taking into account the * actual type arguements * * @param rawType1 the raw type of the class to check * @param actualTypeArguments1 the actual type arguements to check, or an * empty array if not a parameterized type * @param rawType2 the raw type of the class to check * @param actualTypeArguments2 the actual type arguements to check, or an * empty array if not a parameterized type * @return */ public static boolean isAssignableFrom(Class<?> rawType1, Type[] actualTypeArguments1, Class<?> rawType2, Type[] actualTypeArguments2) { return Types.boxedClass(rawType1).isAssignableFrom(Types.boxedClass(rawType2)) && isAssignableFrom(actualTypeArguments1, actualTypeArguments2); } public static boolean matches(Class<?> rawType1, Type[] actualTypeArguments1, Class<?> rawType2, Type[] actualTypeArguments2) { return Types.boxedClass(rawType1).equals(Types.boxedClass(rawType2)) && isAssignableFrom(actualTypeArguments1, actualTypeArguments2); } public static boolean isAssignableFrom(Type[] actualTypeArguments1, Type[] actualTypeArguments2) { for (int i = 0; i < actualTypeArguments1.length; i++) { Type type1 = actualTypeArguments1[i]; Type type2 = Object.class; if (actualTypeArguments2.length > i) { type2 = actualTypeArguments2[i]; } if (!isAssignableFrom(type1, type2)) { return false; } } return true; } public static boolean matches(Type type1, Set<? extends Type> types2) { for (Type type2 : types2) { if (matches(type1, type2)) { return true; } } return false; } public static boolean isAssignableFrom(Type type1, Type[] types2) { for (Type type2 : types2) { if (isAssignableFrom(type1, type2)) { return true; } } return false; } public static boolean isAssignableFrom(Type type1, Type type2) { if (type1 instanceof Class<?>) { Class<?> clazz = (Class<?>) type1; if (isAssignableFrom(clazz, EMPTY_TYPES, type2)) { return true; } } if (type1 instanceof ParameterizedType) { ParameterizedType parameterizedType1 = (ParameterizedType) type1; if (parameterizedType1.getRawType() instanceof Class<?>) { if (isAssignableFrom((Class<?>) parameterizedType1.getRawType(), parameterizedType1.getActualTypeArguments(), type2)) { return true; } } } if (type1 instanceof WildcardType) { WildcardType wildcardType = (WildcardType) type1; if (isTypeBounded(type2, wildcardType.getLowerBounds(), wildcardType.getUpperBounds())) { return true; } } if (type2 instanceof WildcardType) { WildcardType wildcardType = (WildcardType) type2; if (isTypeBounded(type1, wildcardType.getUpperBounds(), wildcardType.getLowerBounds())) { return true; } } if (type1 instanceof TypeVariable<?>) { TypeVariable<?> typeVariable = (TypeVariable<?>) type1; if (isTypeBounded(type2, EMPTY_TYPES, typeVariable.getBounds())) { return true; } } if (type2 instanceof TypeVariable<?>) { TypeVariable<?> typeVariable = (TypeVariable<?>) type2; if (isTypeBounded(type1, typeVariable.getBounds(), EMPTY_TYPES)) { return true; } } return false; } public static boolean matches(Type type1, Type type2) { if (type1 instanceof Class<?>) { Class<?> clazz = (Class<?>) type1; if (matches(clazz, EMPTY_TYPES, type2)) { return true; } } if (type1 instanceof ParameterizedType) { ParameterizedType parameterizedType1 = (ParameterizedType) type1; if (parameterizedType1.getRawType() instanceof Class<?>) { if (matches((Class<?>) parameterizedType1.getRawType(), parameterizedType1.getActualTypeArguments(), type2)) { return true; } } } if (type1 instanceof WildcardType) { WildcardType wildcardType = (WildcardType) type1; if (isTypeBounded(type2, wildcardType.getLowerBounds(), wildcardType.getUpperBounds())) { return true; } } if (type2 instanceof WildcardType) { WildcardType wildcardType = (WildcardType) type2; if (isTypeBounded(type1, wildcardType.getUpperBounds(), wildcardType.getLowerBounds())) { return true; } } if (type1 instanceof TypeVariable<?>) { TypeVariable<?> typeVariable = (TypeVariable<?>) type1; if (isTypeBounded(type2, EMPTY_TYPES, typeVariable.getBounds())) { return true; } } if (type2 instanceof TypeVariable<?>) { TypeVariable<?> typeVariable = (TypeVariable<?>) type2; if (isTypeBounded(type1, typeVariable.getBounds(), EMPTY_TYPES)) { return true; } } return false; } public static boolean isTypeBounded(Type type, Type[] lowerBounds, Type[] upperBounds) { if (lowerBounds.length > 0) { if (!isAssignableFrom(type, lowerBounds)) { return false; } } if (upperBounds.length > 0) { if (!isAssignableFrom(upperBounds, type)) { return false; } } return true; } public static boolean isAssignableFrom(Class<?> rawType1, Type[] actualTypeArguments1, Type type2) { if (type2 instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType) type2; if (parameterizedType.getRawType() instanceof Class<?>) { if (isAssignableFrom(rawType1, actualTypeArguments1, (Class<?>) parameterizedType.getRawType(), parameterizedType.getActualTypeArguments())) { return true; } } } else if (type2 instanceof Class<?>) { Class<?> clazz = (Class<?>) type2; if (isAssignableFrom(rawType1, actualTypeArguments1, clazz, EMPTY_TYPES)) { return true; } } else if (type2 instanceof TypeVariable<?>) { TypeVariable<?> typeVariable = (TypeVariable<?>) type2; if (isTypeBounded(rawType1, actualTypeArguments1, typeVariable.getBounds())) { return true; } } return false; } public static boolean matches(Class<?> rawType1, Type[] actualTypeArguments1, Type type2) { if (type2 instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType) type2; if (parameterizedType.getRawType() instanceof Class<?>) { if (matches(rawType1, actualTypeArguments1, (Class<?>) parameterizedType.getRawType(), parameterizedType.getActualTypeArguments())) { return true; } } } else if (type2 instanceof Class<?>) { Class<?> clazz = (Class<?>) type2; if (matches(rawType1, actualTypeArguments1, clazz, EMPTY_TYPES)) { return true; } } return false; } /** * Check whether whether any of the types1 matches a type in types2 * * @param types1 * @param types2 * @return */ public static boolean matches(Set<Type> types1, Set<Type> types2) { for (Type type : types1) { if (matches(type, types2)) { return true; } } return false; } public static boolean isAssignableFrom(Type[] types1, Type type2) { for (Type type : types1) { if (isAssignableFrom(type, type2)) { return true; } } return false; } private Reflections() { } /** * Inspects an annotated element for the given meta annotation. This should * only be used for user defined meta annotations, where the annotation must * be physically present. * * @param element The element to inspect * @param annotationType The meta annotation to search for * @return The annotation instance found on this element or null if no * matching annotation was found. */ public static <A extends Annotation> A getMetaAnnotation(Annotated element, final Class<A> annotationType) { for (Annotation annotation : element.getAnnotations()) { if (annotation.annotationType().isAnnotationPresent(annotationType)) { return annotation.annotationType().getAnnotation(annotationType); } } return null; } /** * Extract the qualifiers from a set of annotations. * * @param beanManager the beanManager to use to determine if an annotation is * a qualifier * @param annotations the annotations to check * @return any qualifiers present in <code>annotations</code> */ @SuppressWarnings("unchecked") public static Set<Annotation> getQualifiers(BeanManager beanManager, Iterable<Annotation> annotations) { return getQualifiers(beanManager, new Iterable[]{annotations}); } /** * Extract the qualifiers from a set of annotations. * * @param beanManager the beanManager to use to determine if an annotation is * a qualifier * @param annotations the annotations to check * @return any qualifiers present in <code>annotations</code> */ public static Set<Annotation> getQualifiers(BeanManager beanManager, Iterable<Annotation>... annotations) { Set<Annotation> qualifiers = new HashSet<Annotation>(); for (Iterable<Annotation> annotationSet : annotations) { for (Annotation annotation : annotationSet) { if (beanManager.isQualifier(annotation.annotationType())) { qualifiers.add(annotation); } } } return qualifiers; } /** * Get all the declared fields on the class hierarchy. This <b>will</b> * return overridden fields. * * @param clazz The class to search * @return the set of all declared fields or an empty set if there are none */ public static Set<Field> getAllDeclaredFields(Class<?> clazz) { HashSet<Field> fields = new HashSet<Field>(); for (Class<?> c = clazz; c != null && c != Object.class; c = c.getSuperclass()) { for (Field a : c.getDeclaredFields()) { fields.add(a); } } return fields; } }
23,237
40.570662
158
java
null
infinispan-main/cdi/common/src/main/java/org/infinispan/cdi/common/util/logging/package-info.java
/** * This package contains the logging classes. */ package org.infinispan.cdi.common.util.logging;
102
19.6
47
java
null
infinispan-main/cdi/common/src/main/java/org/infinispan/cdi/common/util/logging/Log.java
package org.infinispan.cdi.common.util.logging; import static org.jboss.logging.Logger.Level.INFO; import org.jboss.logging.BasicLogger; import org.jboss.logging.annotations.LogMessage; import org.jboss.logging.annotations.Message; import org.jboss.logging.annotations.MessageLogger; /** * The JBoss Logging interface which defined the logging methods for the CDI integration. The id range for the CDI * integration is 17001-18000 * * @author Kevin Pollet &lt;kevin.pollet@serli.com&gt; (C) 2011 SERLI */ @MessageLogger(projectCode = "ISPN") public interface Log extends BasicLogger { @LogMessage(level = INFO) @Message(value = "Infinispan CDI extension version: %s", id = 17001) void version(String version); @Message(value = "%s parameter must not be null", id = 17003) IllegalArgumentException parameterMustNotBeNull(String parameterName); }
871
31.296296
114
java
null
infinispan-main/cdi/common/src/main/java/org/infinispan/cdi/common/util/annotatedtypebuilder/AnnotatedTypeImpl.java
package org.infinispan.cdi.common.util.annotatedtypebuilder; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Type; import java.util.Collections; import java.util.HashSet; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import jakarta.enterprise.inject.spi.AnnotatedConstructor; import jakarta.enterprise.inject.spi.AnnotatedField; import jakarta.enterprise.inject.spi.AnnotatedMethod; import jakarta.enterprise.inject.spi.AnnotatedType; /** * AnnotatedType implementation for adding beans in the BeforeBeanDiscovery * event * * @author Stuart Douglas */ class AnnotatedTypeImpl<X> extends AnnotatedImpl implements AnnotatedType<X> { private final Set<AnnotatedConstructor<X>> constructors; private final Set<AnnotatedField<? super X>> fields; private final Set<AnnotatedMethod<? super X>> methods; private final Class<X> javaClass; /** * We make sure that there is a NewAnnotatedMember for every public * method/field/constructor * <p/> * If annotation have been added to other methods as well we add them to */ AnnotatedTypeImpl(Class<X> clazz, AnnotationStore typeAnnotations, Map<Field, AnnotationStore> fieldAnnotations, Map<Method, AnnotationStore> methodAnnotations, Map<Method, Map<Integer, AnnotationStore>> methodParameterAnnotations, Map<Constructor<?>, AnnotationStore> constructorAnnotations, Map<Constructor<?>, Map<Integer, AnnotationStore>> constructorParameterAnnotations, Map<Field, Type> fieldTypes, Map<Method, Map<Integer, Type>> methodParameterTypes, Map<Constructor<?>, Map<Integer, Type>> constructorParameterTypes) { super(clazz, typeAnnotations, null, null); this.javaClass = clazz; this.constructors = new HashSet<AnnotatedConstructor<X>>(); Set<Constructor<?>> cset = new HashSet<Constructor<?>>(); Set<Method> mset = new HashSet<Method>(); Set<Field> fset = new HashSet<Field>(); for (Constructor<?> c : clazz.getConstructors()) { AnnotatedConstructor<X> nc = new AnnotatedConstructorImpl<X>(this, c, constructorAnnotations.get(c), constructorParameterAnnotations.get(c), constructorParameterTypes.get(c)); constructors.add(nc); cset.add(c); } for (Entry<Constructor<?>, AnnotationStore> c : constructorAnnotations.entrySet()) { if (!cset.contains(c.getKey())) { AnnotatedConstructor<X> nc = new AnnotatedConstructorImpl<X>(this, c.getKey(), c.getValue(), constructorParameterAnnotations.get(c.getKey()), constructorParameterTypes.get(c.getKey())); constructors.add(nc); } } this.methods = new HashSet<AnnotatedMethod<? super X>>(); for (Method m : clazz.getMethods()) { if (!m.getDeclaringClass().equals(Object.class)) { AnnotatedMethodImpl<X> met = new AnnotatedMethodImpl<X>(this, m, methodAnnotations.get(m), methodParameterAnnotations.get(m), methodParameterTypes.get(m)); methods.add(met); mset.add(m); } } for (Entry<Method, AnnotationStore> c : methodAnnotations.entrySet()) { if (!c.getKey().getDeclaringClass().equals(Object.class) && !mset.contains(c.getKey())) { AnnotatedMethodImpl<X> nc = new AnnotatedMethodImpl<X>(this, c.getKey(), c.getValue(), methodParameterAnnotations.get(c.getKey()), methodParameterTypes.get(c.getKey())); methods.add(nc); } } this.fields = new HashSet<AnnotatedField<? super X>>(); for (Field f : clazz.getFields()) { AnnotatedField<X> b = new AnnotatedFieldImpl<X>(this, f, fieldAnnotations.get(f), fieldTypes.get(f)); fields.add(b); fset.add(f); } for (Entry<Field, AnnotationStore> e : fieldAnnotations.entrySet()) { if (!fset.contains(e.getKey())) { fields.add(new AnnotatedFieldImpl<X>(this, e.getKey(), e.getValue(), fieldTypes.get(e.getKey()))); } } } public Set<AnnotatedConstructor<X>> getConstructors() { return Collections.unmodifiableSet(constructors); } public Set<AnnotatedField<? super X>> getFields() { return Collections.unmodifiableSet(fields); } public Class<X> getJavaClass() { return javaClass; } public Set<AnnotatedMethod<? super X>> getMethods() { return Collections.unmodifiableSet(methods); } }
4,440
43.41
531
java
null
infinispan-main/cdi/common/src/main/java/org/infinispan/cdi/common/util/annotatedtypebuilder/AnnotatedConstructorImpl.java
package org.infinispan.cdi.common.util.annotatedtypebuilder; import java.lang.reflect.Constructor; import java.lang.reflect.Type; import java.util.Map; import jakarta.enterprise.inject.spi.AnnotatedConstructor; /** * @author Stuart Douglas */ class AnnotatedConstructorImpl<X> extends AnnotatedCallableImpl<X, Constructor<X>> implements AnnotatedConstructor<X> { AnnotatedConstructorImpl(AnnotatedTypeImpl<X> type, Constructor<?> constructor, AnnotationStore annotations, Map<Integer, AnnotationStore> parameterAnnotations, Map<Integer, Type> typeOverrides) { super(type, (Constructor<X>) constructor, constructor.getDeclaringClass(), constructor.getParameterTypes(), getGenericArray(constructor), annotations, parameterAnnotations, null, typeOverrides); } private static Type[] getGenericArray(Constructor<?> constructor) { Type[] genericTypes = constructor.getGenericParameterTypes(); // for inner classes genericTypes and parameterTypes can be different // length, this is a hack to fix this. // TODO: investigate this behavior further, on different JVM's and // compilers if (genericTypes.length + 1 == constructor.getParameterCount()) { genericTypes = new Type[constructor.getGenericParameterTypes().length + 1]; genericTypes[0] = constructor.getParameterTypes()[0]; for (int i = 0; i < constructor.getGenericParameterTypes().length; ++i) { genericTypes[i + 1] = constructor.getGenericParameterTypes()[i]; } } return genericTypes; } }
1,562
43.657143
200
java
null
infinispan-main/cdi/common/src/main/java/org/infinispan/cdi/common/util/annotatedtypebuilder/AnnotatedCallableImpl.java
package org.infinispan.cdi.common.util.annotatedtypebuilder; import java.lang.reflect.Member; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import jakarta.enterprise.inject.spi.AnnotatedCallable; import jakarta.enterprise.inject.spi.AnnotatedParameter; import jakarta.enterprise.inject.spi.AnnotatedType; /** * @author Stuart Douglas */ abstract class AnnotatedCallableImpl<X, Y extends Member> extends AnnotatedMemberImpl<X, Y> implements AnnotatedCallable<X> { private final List<AnnotatedParameter<X>> parameters; protected AnnotatedCallableImpl(AnnotatedType<X> declaringType, Y member, Class<?> memberType, Class<?>[] parameterTypes, Type[] genericTypes, AnnotationStore annotations, Map<Integer, AnnotationStore> parameterAnnotations, Type genericType, Map<Integer, Type> parameterTypeOverrides) { super(declaringType, member, memberType, annotations, genericType, null); this.parameters = getAnnotatedParameters(this, parameterTypes, genericTypes, parameterAnnotations, parameterTypeOverrides); } public List<AnnotatedParameter<X>> getParameters() { return Collections.unmodifiableList(parameters); } private static <X, Y extends Member> List<AnnotatedParameter<X>> getAnnotatedParameters(AnnotatedCallableImpl<X, Y> callable, Class<?>[] parameterTypes, Type[] genericTypes, Map<Integer, AnnotationStore> parameterAnnotations, Map<Integer, Type> parameterTypeOverrides) { List<AnnotatedParameter<X>> parameters = new ArrayList<AnnotatedParameter<X>>(); int len = parameterTypes.length; for (int i = 0; i < len; ++i) { AnnotationBuilder builder = new AnnotationBuilder(); if (parameterAnnotations != null && parameterAnnotations.containsKey(i)) { builder.addAll(parameterAnnotations.get(i)); } Type over = null; if (parameterTypeOverrides != null) { over = parameterTypeOverrides.get(i); } AnnotatedParameterImpl<X> p = new AnnotatedParameterImpl<X>(callable, parameterTypes[i], i, builder.create(), genericTypes[i], over); parameters.add(p); } return parameters; } }
2,237
44.673469
289
java
null
infinispan-main/cdi/common/src/main/java/org/infinispan/cdi/common/util/annotatedtypebuilder/AnnotationBuilder.java
package org.infinispan.cdi.common.util.annotatedtypebuilder; import java.lang.annotation.Annotation; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Set; import org.infinispan.cdi.common.util.Reflections; import org.infinispan.cdi.common.util.logging.Log; import org.infinispan.commons.logging.LogFactory; /** * Helper class used to build annotation stores * * @author Stuart Douglas */ public class AnnotationBuilder { private static final Log log = LogFactory.getLog(AnnotationBuilder.class, Log.class); private final Map<Class<? extends Annotation>, Annotation> annotationMap; private final Set<Annotation> annotationSet; AnnotationBuilder() { this.annotationMap = new HashMap<Class<? extends Annotation>, Annotation>(); this.annotationSet = new HashSet<Annotation>(); } public AnnotationBuilder add(Annotation annotation) { if (annotation == null) { throw log.parameterMustNotBeNull("annotation"); } annotationSet.add(annotation); annotationMap.put(annotation.annotationType(), annotation); return this; } public AnnotationBuilder remove(Class<? extends Annotation> annotationType) { if (annotationType == null) { throw log.parameterMustNotBeNull("annotationType"); } Iterator<Annotation> it = annotationSet.iterator(); while (it.hasNext()) { Annotation an = it.next(); if (annotationType.isAssignableFrom(an.annotationType())) { it.remove(); } } annotationMap.remove(annotationType); return this; } AnnotationStore create() { return new AnnotationStore(annotationMap, annotationSet); } public AnnotationBuilder addAll(AnnotationStore annotations) { for (Annotation annotation : annotations.getAnnotations()) { add(annotation); } return this; } public <T extends Annotation> T getAnnotation(Class<T> anType) { return Reflections.cast(annotationMap.get(anType)); } public boolean isAnnotationPresent(Class<?> annotationType) { return annotationMap.containsKey(annotationType); } @Override public String toString() { return annotationSet.toString(); } }
2,297
27.37037
88
java
null
infinispan-main/cdi/common/src/main/java/org/infinispan/cdi/common/util/annotatedtypebuilder/AnnotatedParameterImpl.java
package org.infinispan.cdi.common.util.annotatedtypebuilder; import java.lang.reflect.Type; import jakarta.enterprise.inject.spi.AnnotatedCallable; import jakarta.enterprise.inject.spi.AnnotatedParameter; /** * @author Stuart Douglas */ class AnnotatedParameterImpl<X> extends AnnotatedImpl implements AnnotatedParameter<X> { private final int position; private final AnnotatedCallable<X> declaringCallable; AnnotatedParameterImpl(AnnotatedCallable<X> declaringCallable, Class<?> type, int position, AnnotationStore annotations, Type genericType, Type typeOverride) { super(type, annotations, genericType, typeOverride); this.declaringCallable = declaringCallable; this.position = position; } public AnnotatedCallable<X> getDeclaringCallable() { return declaringCallable; } public int getPosition() { return position; } }
886
27.612903
162
java
null
infinispan-main/cdi/common/src/main/java/org/infinispan/cdi/common/util/annotatedtypebuilder/AnnotatedMemberImpl.java
package org.infinispan.cdi.common.util.annotatedtypebuilder; import java.lang.reflect.Member; import java.lang.reflect.Modifier; import java.lang.reflect.Type; import jakarta.enterprise.inject.spi.AnnotatedMember; import jakarta.enterprise.inject.spi.AnnotatedType; /** * @author Stuart Douglas */ abstract class AnnotatedMemberImpl<X, M extends Member> extends AnnotatedImpl implements AnnotatedMember<X> { private final AnnotatedType<X> declaringType; private final M javaMember; protected AnnotatedMemberImpl(AnnotatedType<X> declaringType, M member, Class<?> memberType, AnnotationStore annotations, Type genericType, Type overridenType) { super(memberType, annotations, genericType, overridenType); this.declaringType = declaringType; this.javaMember = member; } public AnnotatedType<X> getDeclaringType() { return declaringType; } public M getJavaMember() { return javaMember; } public boolean isStatic() { return Modifier.isStatic(javaMember.getModifiers()); } }
1,047
27.324324
164
java
null
infinispan-main/cdi/common/src/main/java/org/infinispan/cdi/common/util/annotatedtypebuilder/AnnotatedImpl.java
package org.infinispan.cdi.common.util.annotatedtypebuilder; import java.lang.annotation.Annotation; import java.lang.reflect.Type; import java.util.Collections; import java.util.HashSet; import java.util.Set; import jakarta.enterprise.inject.spi.Annotated; import org.infinispan.cdi.common.util.HierarchyDiscovery; /** * The base class for all New Annotated types. * * @author Stuart Douglas */ abstract class AnnotatedImpl implements Annotated { private final Type type; private final Set<Type> typeClosure; private final AnnotationStore annotations; protected AnnotatedImpl(Class<?> type, AnnotationStore annotations, Type genericType, Type overridenType) { if (overridenType == null) { if (genericType != null) { typeClosure = new HierarchyDiscovery(genericType).getTypeClosure(); this.type = genericType; } else { typeClosure = new HierarchyDiscovery(type).getTypeClosure(); this.type = type; } } else { this.type = overridenType; this.typeClosure = Collections.singleton(overridenType); } if (annotations == null) { this.annotations = new AnnotationStore(); } else { this.annotations = annotations; } } public <T extends Annotation> T getAnnotation(Class<T> annotationType) { return annotations.getAnnotation(annotationType); } public Set<Annotation> getAnnotations() { return annotations.getAnnotations(); } public boolean isAnnotationPresent(Class<? extends Annotation> annotationType) { return annotations.isAnnotationPresent(annotationType); } public Set<Type> getTypeClosure() { return new HashSet<Type>(typeClosure); } public Type getBaseType() { return type; } }
1,816
26.119403
110
java
null
infinispan-main/cdi/common/src/main/java/org/infinispan/cdi/common/util/annotatedtypebuilder/AnnotatedFieldImpl.java
package org.infinispan.cdi.common.util.annotatedtypebuilder; import java.lang.reflect.Field; import java.lang.reflect.Type; import jakarta.enterprise.inject.spi.AnnotatedField; import jakarta.enterprise.inject.spi.AnnotatedType; /** * @author Stuart Douglas */ class AnnotatedFieldImpl<X> extends AnnotatedMemberImpl<X, Field> implements AnnotatedField<X> { AnnotatedFieldImpl(AnnotatedType<X> declaringType, Field field, AnnotationStore annotations, Type overridenType) { super(declaringType, field, field.getType(), annotations, field.getGenericType(), overridenType); } }
598
30.526316
118
java
null
infinispan-main/cdi/common/src/main/java/org/infinispan/cdi/common/util/annotatedtypebuilder/AnnotatedTypeBuilder.java
package org.infinispan.cdi.common.util.annotatedtypebuilder; import java.lang.annotation.Annotation; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Type; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import jakarta.enterprise.inject.spi.Annotated; import jakarta.enterprise.inject.spi.AnnotatedConstructor; import jakarta.enterprise.inject.spi.AnnotatedField; import jakarta.enterprise.inject.spi.AnnotatedMethod; import jakarta.enterprise.inject.spi.AnnotatedParameter; import jakarta.enterprise.inject.spi.AnnotatedType; import org.infinispan.cdi.common.util.Reflections; import org.infinispan.cdi.common.util.logging.Log; import org.infinispan.commons.logging.LogFactory; /** * <p> Class for constructing a new AnnotatedType. A new instance of builder * should be used for each annotated type. </p> <p/> <p> {@link * AnnotatedTypeBuilder} is not thread-safe. </p> * * @author Stuart Douglas * @author Pete Muir * @see AnnotatedType */ public class AnnotatedTypeBuilder<X> { private static final Log log = LogFactory.getLog(AnnotatedTypeBuilder.class, Log.class); private Class<X> javaClass; private final AnnotationBuilder typeAnnotations; private final Map<Constructor<?>, AnnotationBuilder> constructors; private final Map<Constructor<?>, Map<Integer, AnnotationBuilder>> constructorParameters; private final Map<Constructor<?>, Map<Integer, Type>> constructorParameterTypes; private final Map<Field, AnnotationBuilder> fields; private final Map<Field, Type> fieldTypes; private final Map<Method, AnnotationBuilder> methods; private final Map<Method, Map<Integer, AnnotationBuilder>> methodParameters; private final Map<Method, Map<Integer, Type>> methodParameterTypes; /** * Create a new builder. A new builder has no annotations and no members. * * @see #readFromType(AnnotatedType) * @see #readFromType(Class) * @see #readFromType(AnnotatedType, boolean) * @see #readFromType(Class, boolean) */ public AnnotatedTypeBuilder() { this.typeAnnotations = new AnnotationBuilder(); this.constructors = new HashMap<Constructor<?>, AnnotationBuilder>(); this.constructorParameters = new HashMap<Constructor<?>, Map<Integer, AnnotationBuilder>>(); this.constructorParameterTypes = new HashMap<Constructor<?>, Map<Integer, Type>>(); this.fields = new HashMap<Field, AnnotationBuilder>(); this.fieldTypes = new HashMap<Field, Type>(); this.methods = new HashMap<Method, AnnotationBuilder>(); this.methodParameters = new HashMap<Method, Map<Integer, AnnotationBuilder>>(); this.methodParameterTypes = new HashMap<Method, Map<Integer, Type>>(); } /** * Add an annotation to the type declaration. * * @param annotation the annotation instance to add * @throws IllegalArgumentException if the annotation is null */ public AnnotatedTypeBuilder<X> addToClass(Annotation annotation) { typeAnnotations.add(annotation); return this; } /** * Reads in from an existing AnnotatedType. Any elements not present are * added. The javaClass will be read in. If the annotation already exists on * that element in the builder the read annotation will be used. * * @param type the type to read from * @throws IllegalArgumentException if type is null */ public AnnotatedTypeBuilder<X> readFromType(AnnotatedType<X> type) { return readFromType(type, true); } /** * Reads in from an existing AnnotatedType. Any elements not present are * added. The javaClass will be read in if overwrite is true. If the * annotation already exists on that element in the builder, overwrite * determines whether the original or read annotation will be used. * * @param type the type to read from * @param overwrite if true, the read annotation will replace any existing * annotation * @throws IllegalArgumentException if type is null */ public AnnotatedTypeBuilder<X> readFromType(AnnotatedType<X> type, boolean overwrite) { if (type == null) { throw log.parameterMustNotBeNull("type"); } if (javaClass == null || overwrite) { this.javaClass = type.getJavaClass(); } mergeAnnotationsOnElement(type, overwrite, typeAnnotations); for (AnnotatedField<? super X> field : type.getFields()) { if (fields.get(field.getJavaMember()) == null) { fields.put(field.getJavaMember(), new AnnotationBuilder()); } mergeAnnotationsOnElement(field, overwrite, fields.get(field.getJavaMember())); } for (AnnotatedMethod<? super X> method : type.getMethods()) { if (methods.get(method.getJavaMember()) == null) { methods.put(method.getJavaMember(), new AnnotationBuilder()); } mergeAnnotationsOnElement(method, overwrite, methods.get(method.getJavaMember())); for (AnnotatedParameter<? super X> p : method.getParameters()) { if (methodParameters.get(method.getJavaMember()) == null) { methodParameters.put(method.getJavaMember(), new HashMap<Integer, AnnotationBuilder>()); } if (methodParameters.get(method.getJavaMember()).get(p.getPosition()) == null) { methodParameters.get(method.getJavaMember()).put(p.getPosition(), new AnnotationBuilder()); } mergeAnnotationsOnElement(p, overwrite, methodParameters.get(method.getJavaMember()).get(p.getPosition())); } } for (AnnotatedConstructor<? super X> constructor : type.getConstructors()) { if (constructors.get(constructor.getJavaMember()) == null) { constructors.put(constructor.getJavaMember(), new AnnotationBuilder()); } mergeAnnotationsOnElement(constructor, overwrite, constructors.get(constructor.getJavaMember())); for (AnnotatedParameter<? super X> p : constructor.getParameters()) { if (constructorParameters.get(constructor.getJavaMember()) == null) { constructorParameters.put(constructor.getJavaMember(), new HashMap<Integer, AnnotationBuilder>()); } if (constructorParameters.get(constructor.getJavaMember()).get(p.getPosition()) == null) { constructorParameters.get(constructor.getJavaMember()).put(p.getPosition(), new AnnotationBuilder()); } mergeAnnotationsOnElement(p, overwrite, constructorParameters.get(constructor.getJavaMember()).get(p.getPosition())); } } return this; } /** * Reads the annotations from an existing java type. Annotations already * present will be overwritten * * @param type the type to read from * @throws IllegalArgumentException if type is null */ public AnnotatedTypeBuilder<X> readFromType(Class<X> type) { return readFromType(type, true); } /** * Reads the annotations from an existing java type. If overwrite is true * then existing annotations will be overwritten * * @param type the type to read from * @param overwrite if true, the read annotation will replace any existing * annotation */ public AnnotatedTypeBuilder<X> readFromType(Class<X> type, boolean overwrite) { if (type == null) { throw log.parameterMustNotBeNull("type"); } if (javaClass == null || overwrite) { this.javaClass = type; } for (Annotation annotation : type.getAnnotations()) { if (overwrite || !typeAnnotations.isAnnotationPresent(annotation.annotationType())) { typeAnnotations.add(annotation); } } for (Field field : Reflections.getAllDeclaredFields(type)) { AnnotationBuilder annotationBuilder = fields.get(field); if (annotationBuilder == null) { annotationBuilder = new AnnotationBuilder(); fields.put(field, annotationBuilder); } field.setAccessible(true); for (Annotation annotation : field.getAnnotations()) { if (overwrite || !annotationBuilder.isAnnotationPresent(annotation.annotationType())) { annotationBuilder.add(annotation); } } } for (Method method : Reflections.getAllDeclaredMethods(type)) { AnnotationBuilder annotationBuilder = methods.get(method); if (annotationBuilder == null) { annotationBuilder = new AnnotationBuilder(); methods.put(method, annotationBuilder); } method.setAccessible(true); for (Annotation annotation : method.getAnnotations()) { if (overwrite || !annotationBuilder.isAnnotationPresent(annotation.annotationType())) { annotationBuilder.add(annotation); } } Map<Integer, AnnotationBuilder> parameters = methodParameters.get(method); if (parameters == null) { parameters = new HashMap<Integer, AnnotationBuilder>(); methodParameters.put(method, parameters); } for (int i = 0; i < method.getParameterCount(); ++i) { AnnotationBuilder parameterAnnotationBuilder = parameters.get(i); if (parameterAnnotationBuilder == null) { parameterAnnotationBuilder = new AnnotationBuilder(); parameters.put(i, parameterAnnotationBuilder); } for (Annotation annotation : method.getParameterAnnotations()[i]) { if (overwrite || !parameterAnnotationBuilder.isAnnotationPresent(annotation.annotationType())) { parameterAnnotationBuilder.add(annotation); } } } } for (Constructor<?> constructor : type.getDeclaredConstructors()) { AnnotationBuilder annotationBuilder = constructors.get(constructor); if (annotationBuilder == null) { annotationBuilder = new AnnotationBuilder(); constructors.put(constructor, annotationBuilder); } constructor.setAccessible(true); for (Annotation annotation : constructor.getAnnotations()) { if (overwrite || !annotationBuilder.isAnnotationPresent(annotation.annotationType())) { annotationBuilder.add(annotation); } } Map<Integer, AnnotationBuilder> mparams = constructorParameters.get(constructor); if (mparams == null) { mparams = new HashMap<Integer, AnnotationBuilder>(); constructorParameters.put(constructor, mparams); } for (int i = 0; i < constructor.getParameterCount(); ++i) { AnnotationBuilder parameterAnnotationBuilder = mparams.get(i); if (parameterAnnotationBuilder == null) { parameterAnnotationBuilder = new AnnotationBuilder(); mparams.put(i, parameterAnnotationBuilder); } for (Annotation annotation : constructor.getParameterAnnotations()[i]) { if (overwrite || !parameterAnnotationBuilder.isAnnotationPresent(annotation.annotationType())) { annotationBuilder.add(annotation); } } } } return this; } protected void mergeAnnotationsOnElement(Annotated annotated, boolean overwriteExisting, AnnotationBuilder typeAnnotations) { for (Annotation annotation : annotated.getAnnotations()) { if (typeAnnotations.getAnnotation(annotation.annotationType()) != null) { if (overwriteExisting) { typeAnnotations.remove(annotation.annotationType()); typeAnnotations.add(annotation); } } else { typeAnnotations.add(annotation); } } } /** * Create an {@link AnnotatedType}. Any public members present on the * underlying class and not overridden by the builder will be automatically * added. */ public AnnotatedType<X> create() { Map<Constructor<?>, Map<Integer, AnnotationStore>> constructorParameterAnnnotations = new HashMap<Constructor<?>, Map<Integer, AnnotationStore>>(); Map<Constructor<?>, AnnotationStore> constructorAnnotations = new HashMap<Constructor<?>, AnnotationStore>(); Map<Method, Map<Integer, AnnotationStore>> methodParameterAnnnotations = new HashMap<Method, Map<Integer, AnnotationStore>>(); Map<Method, AnnotationStore> methodAnnotations = new HashMap<Method, AnnotationStore>(); Map<Field, AnnotationStore> fieldAnnotations = new HashMap<Field, AnnotationStore>(); for (Entry<Field, AnnotationBuilder> field : fields.entrySet()) { fieldAnnotations.put(field.getKey(), field.getValue().create()); } for (Entry<Method, AnnotationBuilder> method : methods.entrySet()) { methodAnnotations.put(method.getKey(), method.getValue().create()); } for (Entry<Method, Map<Integer, AnnotationBuilder>> parameters : methodParameters.entrySet()) { Map<Integer, AnnotationStore> parameterAnnotations = new HashMap<Integer, AnnotationStore>(); methodParameterAnnnotations.put(parameters.getKey(), parameterAnnotations); for (Entry<Integer, AnnotationBuilder> parameter : parameters.getValue().entrySet()) { parameterAnnotations.put(parameter.getKey(), parameter.getValue().create()); } } for (Entry<Constructor<?>, AnnotationBuilder> constructor : constructors.entrySet()) { constructorAnnotations.put(constructor.getKey(), constructor.getValue().create()); } for (Entry<Constructor<?>, Map<Integer, AnnotationBuilder>> parameters : constructorParameters.entrySet()) { Map<Integer, AnnotationStore> parameterAnnotations = new HashMap<Integer, AnnotationStore>(); constructorParameterAnnnotations.put(parameters.getKey(), parameterAnnotations); for (Entry<Integer, AnnotationBuilder> parameter : parameters.getValue().entrySet()) { parameterAnnotations.put(parameter.getKey(), parameter.getValue().create()); } } return new AnnotatedTypeImpl<X>(javaClass, typeAnnotations.create(), fieldAnnotations, methodAnnotations, methodParameterAnnnotations, constructorAnnotations, constructorParameterAnnnotations, fieldTypes, methodParameterTypes, constructorParameterTypes); } /** * Remove an annotation from the type * * @param annotationType the annotation type to remove * @throws IllegalArgumentException if the annotationType */ public AnnotatedTypeBuilder<X> removeFromClass(Class<? extends Annotation> annotationType) { typeAnnotations.remove(annotationType); return this; } /** * Remove an annotation from the specified method. * * @param method the method to remove the annotation from * @param annotationType the annotation type to remove * @throws IllegalArgumentException if the annotationType is null or if the * method is not currently declared on the type */ public AnnotatedTypeBuilder<X> removeFromMethod(Method method, Class<? extends Annotation> annotationType) { if (methods.get(method) == null) { throw new IllegalArgumentException("Method not present " + method.toString() + " on " + javaClass); } else { methods.get(method).remove(annotationType); } return this; } /** * Remove an annotation from the specified method. * * @param method the method to remove the annotation from * @param annotationType the annotation type to remove * @throws IllegalArgumentException if the annotationType is null or if the * method is not currently declared on the type */ public AnnotatedTypeBuilder<X> removeFromMethod(AnnotatedMethod<? super X> method, Class<? extends Annotation> annotationType) { return removeFromMethod(method.getJavaMember(), annotationType); } /** * Add an annotation to the specified method. If the method is not already * present, it will be added. * * @param method the method to add the annotation to * @param annotation the annotation to add * @throws IllegalArgumentException if the annotation is null */ public AnnotatedTypeBuilder<X> addToMethod(Method method, Annotation annotation) { if (methods.get(method) == null) { methods.put(method, new AnnotationBuilder()); } methods.get(method).add(annotation); return this; } /** * Add an annotation to the specified method. If the method is not already * present, it will be added. * * @param method the method to add the annotation to * @param annotation the annotation to add * @throws IllegalArgumentException if the annotation is null */ public AnnotatedTypeBuilder<X> addToMethod(AnnotatedMethod<? super X> method, Annotation annotation) { return addToMethod(method.getJavaMember(), annotation); } /** * Add an annotation to the specified method parameter. If the method is not * already present, it will be added. If the method parameter is not already * present, it will be added. * * @param method the method to add the annotation to * @param position the position of the parameter to add * @param annotation the annotation to add * @throws IllegalArgumentException if the annotation is null */ public AnnotatedTypeBuilder<X> addToMethodParameter(Method method, int position, Annotation annotation) { if (!methods.containsKey(method)) { methods.put(method, new AnnotationBuilder()); } if (methodParameters.get(method) == null) { methodParameters.put(method, new HashMap<Integer, AnnotationBuilder>()); } if (methodParameters.get(method).get(position) == null) { methodParameters.get(method).put(position, new AnnotationBuilder()); } methodParameters.get(method).get(position).add(annotation); return this; } /** * Remove an annotation from the specified method parameter. * * @param method the method to remove the annotation from * @param position the position of the parameter to remove * @param annotationType the annotation type to remove * @throws IllegalArgumentException if the annotationType is null, if the * method is not currently declared on the type or if the * parameter is not declared on the method */ public AnnotatedTypeBuilder<X> removeFromMethodParameter(Method method, int position, Class<? extends Annotation> annotationType) { if (methods.get(method) == null) { throw new IllegalArgumentException("Method not present " + method + " on " + javaClass); } else { if (methodParameters.get(method).get(position) == null) { throw new IllegalArgumentException("Method parameter " + position + " not present on " + method + " on " + javaClass); } else { methodParameters.get(method).get(position).remove(annotationType); } } return this; } /** * Add an annotation to the specified field. If the field is not already * present, it will be added. * * @param field the field to add the annotation to * @param annotation the annotation to add * @throws IllegalArgumentException if the annotation is null */ public AnnotatedTypeBuilder<X> addToField(Field field, Annotation annotation) { if (fields.get(field) == null) { fields.put(field, new AnnotationBuilder()); } fields.get(field).add(annotation); return this; } /** * Add an annotation to the specified field. If the field is not already * present, it will be added. * * @param field the field to add the annotation to * @param annotation the annotation to add * @throws IllegalArgumentException if the annotation is null */ public AnnotatedTypeBuilder<X> addToField(AnnotatedField<? super X> field, Annotation annotation) { return addToField(field.getJavaMember(), annotation); } /** * Remove an annotation from the specified field. * * @param field the field to remove the annotation from * @param annotationType the annotation type to remove * @throws IllegalArgumentException if the annotationType is null or if the * field is not currently declared on the type */ public AnnotatedTypeBuilder<X> removeFromField(Field field, Class<? extends Annotation> annotationType) { if (fields.get(field) == null) { throw new IllegalArgumentException("Field not present " + field + " on " + javaClass); } else { fields.get(field).remove(annotationType); } return this; } /** * Remove an annotation from the specified field. * * @param field the field to remove the annotation from * @param annotationType the annotation type to remove * @throws IllegalArgumentException if the annotationType is null or if the * field is not currently declared on the type */ public AnnotatedTypeBuilder<X> removeFromField(AnnotatedField<? super X> field, Class<? extends Annotation> annotationType) { return removeFromField(field.getJavaMember(), annotationType); } }
21,776
43.533742
260
java
null
infinispan-main/cdi/common/src/main/java/org/infinispan/cdi/common/util/annotatedtypebuilder/AnnotatedMethodImpl.java
package org.infinispan.cdi.common.util.annotatedtypebuilder; import java.lang.reflect.Method; import java.lang.reflect.Type; import java.util.Map; import jakarta.enterprise.inject.spi.AnnotatedMethod; import jakarta.enterprise.inject.spi.AnnotatedType; /** * @author Stuart Douglas */ class AnnotatedMethodImpl<X> extends AnnotatedCallableImpl<X, Method> implements AnnotatedMethod<X> { AnnotatedMethodImpl(AnnotatedType<X> type, Method method, AnnotationStore annotations, Map<Integer, AnnotationStore> parameterAnnotations, Map<Integer, Type> parameterTypeOverrides) { super(type, method, method.getReturnType(), method.getParameterTypes(), method.getGenericParameterTypes(), annotations, parameterAnnotations, method.getGenericReturnType(), parameterTypeOverrides); } }
792
38.65
203
java
null
infinispan-main/cdi/common/src/main/java/org/infinispan/cdi/common/util/annotatedtypebuilder/AnnotationStore.java
package org.infinispan.cdi.common.util.annotatedtypebuilder; import static java.util.Collections.emptyMap; import static java.util.Collections.emptySet; import static java.util.Collections.unmodifiableSet; import java.lang.annotation.Annotation; import java.util.Map; import java.util.Set; /** * A helper class used to hold annotations on a type or member. * * @author Stuart Douglas */ class AnnotationStore { private final Map<Class<? extends Annotation>, Annotation> annotationMap; private final Set<Annotation> annotationSet; AnnotationStore(Map<Class<? extends Annotation>, Annotation> annotationMap, Set<Annotation> annotationSet) { this.annotationMap = annotationMap; this.annotationSet = unmodifiableSet(annotationSet); } AnnotationStore() { this.annotationMap = emptyMap(); this.annotationSet = emptySet(); } <T extends Annotation> T getAnnotation(Class<T> annotationType) { return annotationType.cast(annotationMap.get(annotationType)); } Set<Annotation> getAnnotations() { return annotationSet; } boolean isAnnotationPresent(Class<? extends Annotation> annotationType) { return annotationMap.containsKey(annotationType); } }
1,228
26.931818
111
java
null
infinispan-main/cdi/remote/src/test/java/org/infinispan/cdi/embedded/test/Deployments.java
package org.infinispan.cdi.embedded.test; import org.infinispan.cdi.remote.Remote; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.jboss.shrinkwrap.api.spec.WebArchive; /** * Arquillian deployment utility class. * * @author Kevin Pollet &lt;kevin.pollet@serli.com&gt; (C) 2011 SERLI */ public final class Deployments { /** * The base deployment web archive. The CDI extension is packaged as an individual jar. */ public static WebArchive baseDeployment() { return ShrinkWrap.create(WebArchive.class, "test.war") .addAsWebInfResource(Deployments.class.getResource("/META-INF/beans.xml"), "beans.xml") .addAsLibrary( ShrinkWrap.create(JavaArchive.class, "infinispan-cdi-remote.jar") .addPackage(Remote.class.getPackage()) .addAsManifestResource(Remote.class.getResource("/META-INF/beans.xml"), "beans.xml") .addAsManifestResource(Remote.class.getResource("/META-INF/services/jakarta.enterprise.inject.spi.Extension"), "services/jakarta.enterprise.inject.spi.Extension") ); } }
1,187
41.428571
186
java
null
infinispan-main/cdi/remote/src/test/java/org/infinispan/cdi/embedded/test/cachemanager/remote/DefaultCacheManagerOverrideTest.java
package org.infinispan.cdi.embedded.test.cachemanager.remote; import static org.testng.Assert.assertEquals; import java.util.Properties; import jakarta.enterprise.context.ApplicationScoped; import jakarta.enterprise.inject.Disposes; import jakarta.enterprise.inject.Produces; import jakarta.inject.Inject; import org.infinispan.cdi.embedded.test.Deployments; import org.infinispan.client.hotrod.RemoteCacheManager; import org.infinispan.client.hotrod.test.HotRodClientTestingUtil; import org.infinispan.commons.test.ThreadLeakChecker; import org.infinispan.commons.test.TestResourceTrackingListener; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.testng.Arquillian; import org.jboss.shrinkwrap.api.Archive; import org.testng.annotations.Listeners; import org.testng.annotations.Test; /** * Tests that the default remote cache manager can be overridden. * * @author Kevin Pollet &lt;kevin.pollet@serli.com&gt; (C) 2011 SERLI */ @Listeners(TestResourceTrackingListener.class) @Test(groups = "functional", testName = "cdi.test.cachemanager.remote.DefaultCacheManagerOverrideTest") public class DefaultCacheManagerOverrideTest extends Arquillian { private static final String SERVER_LIST_KEY = "infinispan.client.hotrod.server_list"; private static final String SERVER_LIST_VALUE = "foo:15444"; @Deployment public static Archive<?> deployment() { return Deployments.baseDeployment() .addClass(DefaultCacheManagerOverrideTest.class); } @Inject private RemoteCacheManager remoteCacheManager; public void testDefaultRemoteCacheManagerOverride() { // RemoteCacheProducer leaks thread, see ISPN-9935 ThreadLeakChecker.ignoreThreadsContaining("HotRod-client-async-pool-"); final Properties properties = remoteCacheManager.getConfiguration().properties(); assertEquals(properties.getProperty(SERVER_LIST_KEY), SERVER_LIST_VALUE); } /** * The default remote cache manager producer. This producer will override the default remote cache manager producer * provided by the CDI extension. */ @Produces @ApplicationScoped public RemoteCacheManager defaultRemoteCacheManager() { org.infinispan.client.hotrod.configuration.ConfigurationBuilder clientBuilder = HotRodClientTestingUtil.newRemoteConfigurationBuilder(); clientBuilder.addServers(SERVER_LIST_VALUE); return new RemoteCacheManager(clientBuilder.build()); } static void stopRemoteCacheManager(@Disposes RemoteCacheManager remoteCacheManager) { remoteCacheManager.stop(); } }
2,608
36.271429
118
java
null
infinispan-main/cdi/remote/src/test/java/org/infinispan/cdi/embedded/test/cachemanager/remote/DefaultCacheManagerTest.java
package org.infinispan.cdi.embedded.test.cachemanager.remote; import static org.testng.Assert.assertEquals; import java.util.Properties; import jakarta.inject.Inject; import org.infinispan.cdi.embedded.test.Deployments; import org.infinispan.client.hotrod.RemoteCacheManager; import org.infinispan.commons.test.ThreadLeakChecker; import org.infinispan.commons.test.TestResourceTrackingListener; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.testng.Arquillian; import org.jboss.shrinkwrap.api.Archive; import org.testng.annotations.Listeners; import org.testng.annotations.Test; /** * Test the default remote cache manager injection. * * @author Kevin Pollet &lt;kevin.pollet@serli.com&gt; (C) 2011 SERLI */ @Listeners(TestResourceTrackingListener.class) @Test(groups = "functional", testName = "cdi.test.cachemanager.remote.DefaultCacheManagerTest") public class DefaultCacheManagerTest extends Arquillian { private static final String SERVER_LIST_KEY = "infinispan.client.hotrod.server_list"; private static final String DEFAULT_SERVER_LIST_VALUE = "127.0.0.1:11222"; @Deployment public static Archive<?> deployment() { return Deployments.baseDeployment() .addClass(DefaultCacheManagerTest.class); } @Inject private RemoteCacheManager remoteCacheManager; public void testDefaultRemoteCacheManagerInjection() { // RemoteCacheProducer leaks thread, see ISPN-9935 ThreadLeakChecker.ignoreThreadsContaining("HotRod-client-async-pool-"); final Properties properties = remoteCacheManager.getConfiguration().properties(); assertEquals(properties.getProperty(SERVER_LIST_KEY), DEFAULT_SERVER_LIST_VALUE); } }
1,727
34.265306
95
java
null
infinispan-main/cdi/remote/src/test/java/org/infinispan/cdi/embedded/test/cache/remote/SpecificCacheManagerTest.java
package org.infinispan.cdi.embedded.test.cache.remote; import static org.infinispan.client.hotrod.test.HotRodClientTestingUtil.startHotRodServer; import static org.infinispan.server.hotrod.test.HotRodTestingUtil.hotRodCacheConfiguration; import static org.testng.Assert.assertEquals; import jakarta.enterprise.context.ApplicationScoped; import jakarta.enterprise.inject.Any; import jakarta.enterprise.inject.Disposes; import jakarta.enterprise.inject.Produces; import jakarta.inject.Inject; import org.infinispan.cdi.embedded.test.Deployments; import org.infinispan.client.hotrod.RemoteCache; import org.infinispan.client.hotrod.RemoteCacheManager; import org.infinispan.client.hotrod.test.HotRodClientTestingUtil; import org.infinispan.commons.test.ThreadLeakChecker; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.server.hotrod.HotRodServer; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.infinispan.commons.test.TestResourceTrackingListener; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.testng.Arquillian; import org.jboss.shrinkwrap.api.Archive; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Listeners; import org.testng.annotations.Test; /** * Tests that the use of a specific cache manager for one cache. * * @author Kevin Pollet &lt;kevin.pollet@serli.com&gt; (C) 2011 SERLI */ @Listeners(TestResourceTrackingListener.class) @Test(groups = "functional", testName = "cdi.test.cache.remote.SpecificCacheManagerTest") public class SpecificCacheManagerTest extends Arquillian { private static final String SERVER_LIST_KEY = "infinispan.client.hotrod.server_list"; @Deployment public static Archive<?> deployment() { return Deployments.baseDeployment() .addClass(SpecificCacheManagerTest.class) .addClass(Small.class); } private static HotRodServer hotRodServer; private static EmbeddedCacheManager embeddedCacheManager; @Inject @Small private RemoteCache<String, String> cache; @BeforeClass public void beforeMethod() { embeddedCacheManager = TestCacheManagerFactory.createCacheManager( hotRodCacheConfiguration(TestCacheManagerFactory .getDefaultCacheConfiguration(false))); embeddedCacheManager.defineConfiguration("small", embeddedCacheManager.getDefaultCacheConfiguration()); embeddedCacheManager.getCache("small"); hotRodServer = startHotRodServer(embeddedCacheManager); } @AfterClass(alwaysRun = true) public void afterMethod() { if (hotRodServer != null) hotRodServer.stop(); if (embeddedCacheManager != null) embeddedCacheManager.stop(); // RemoteCacheProducer leaks thread, see ISPN-9935 ThreadLeakChecker.ignoreThreadsContaining("HotRod-client-async-pool-"); } public void testSpecificCacheManager() { cache.put("pete", "British"); cache.put("manik", "Sri Lankan"); assertEquals(cache.getName(), "small"); assertEquals(cache.get("pete"), "British"); assertEquals(cache.get("manik"), "Sri Lankan"); } /** * Produces a specific cache manager for the small cache. * * @see Small */ @Small @Produces @ApplicationScoped public static RemoteCacheManager smallRemoteCacheManager() { return new RemoteCacheManager( HotRodClientTestingUtil.newRemoteConfigurationBuilder(hotRodServer).build()); } static void stopRemoteCacheManager(@Disposes @Any RemoteCacheManager remoteCacheManager) { remoteCacheManager.stop(); } }
3,649
35.5
109
java
null
infinispan-main/cdi/remote/src/test/java/org/infinispan/cdi/embedded/test/cache/remote/NamedCacheTest.java
package org.infinispan.cdi.embedded.test.cache.remote; import static org.infinispan.cdi.embedded.test.Deployments.baseDeployment; import static org.infinispan.client.hotrod.test.HotRodClientTestingUtil.startHotRodServer; import static org.infinispan.server.hotrod.test.HotRodTestingUtil.hotRodCacheConfiguration; import static org.testng.Assert.assertEquals; import jakarta.enterprise.context.ApplicationScoped; import jakarta.enterprise.inject.Disposes; import jakarta.enterprise.inject.Produces; import jakarta.inject.Inject; import org.infinispan.cdi.remote.Remote; import org.infinispan.client.hotrod.RemoteCache; import org.infinispan.client.hotrod.RemoteCacheManager; import org.infinispan.client.hotrod.test.HotRodClientTestingUtil; import org.infinispan.commons.test.ThreadLeakChecker; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.server.hotrod.HotRodServer; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.infinispan.commons.test.TestResourceTrackingListener; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.testng.Arquillian; import org.jboss.shrinkwrap.api.Archive; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Listeners; import org.testng.annotations.Test; /** * Tests the named cache injection. * * @author Kevin Pollet &lt;kevin.pollet@serli.com&gt; (C) 2011 SERLI */ @Listeners(TestResourceTrackingListener.class) @Test(groups = {"functional", "smoke"}, testName = "cdi.test.cache.remote.NamedCacheTest") public class NamedCacheTest extends Arquillian { private static final String SERVER_LIST_KEY = "infinispan.client.hotrod.server_list"; @Deployment public static Archive<?> deployment() { return baseDeployment() .addClass(NamedCacheTest.class) .addClass(Small.class); } private static HotRodServer hotRodServer; private static EmbeddedCacheManager embeddedCacheManager; @Inject @Remote("small") private RemoteCache<String, String> cache; @Inject @Small private RemoteCache<String, String> cacheWithQualifier; @BeforeClass public void beforeMethod() { embeddedCacheManager = TestCacheManagerFactory.createCacheManager( hotRodCacheConfiguration(TestCacheManagerFactory .getDefaultCacheConfiguration(false))); embeddedCacheManager.defineConfiguration("small", embeddedCacheManager.getDefaultCacheConfiguration()); embeddedCacheManager.getCache("small"); hotRodServer = startHotRodServer(embeddedCacheManager); } @AfterClass(alwaysRun = true) public void afterClass() { if (hotRodServer != null) hotRodServer.stop(); if (embeddedCacheManager != null) embeddedCacheManager.stop(); // RemoteCacheProducer leaks thread, see ISPN-9935 ThreadLeakChecker.ignoreThreadsContaining("HotRod-client-async-pool-"); } public void testNamedCache() { cache.put("pete", "British"); cache.put("manik", "Sri Lankan"); assertEquals(cache.getName(), "small"); assertEquals(cache.get("pete"), "British"); assertEquals(cache.get("manik"), "Sri Lankan"); // here we check that the cache injection with the @Small qualifier works // like the injection with the @Remote qualifier assertEquals(cacheWithQualifier.getName(), "small"); assertEquals(cacheWithQualifier.get("pete"), "British"); assertEquals(cacheWithQualifier.get("manik"), "Sri Lankan"); } /** * Overrides the default remote cache manager. */ @Produces @ApplicationScoped public static RemoteCacheManager defaultRemoteCacheManager() { return new RemoteCacheManager( HotRodClientTestingUtil.newRemoteConfigurationBuilder(hotRodServer).build()); } static void stopRemoteCacheManager(@Disposes RemoteCacheManager remoteCacheManager) { remoteCacheManager.stop(); } }
3,973
35.796296
109
java
null
infinispan-main/cdi/remote/src/test/java/org/infinispan/cdi/embedded/test/cache/remote/Small.java
package org.infinispan.cdi.embedded.test.cache.remote; import static java.lang.annotation.ElementType.FIELD; import static java.lang.annotation.ElementType.METHOD; import static java.lang.annotation.ElementType.PARAMETER; import static java.lang.annotation.ElementType.TYPE; import static java.lang.annotation.RetentionPolicy.RUNTIME; import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.Target; import jakarta.inject.Qualifier; import org.infinispan.cdi.remote.Remote; /** * @author Kevin Pollet &lt;kevin.pollet@serli.com&gt; (C) 2011 SERLI */ @Remote("small") @Qualifier @Target({TYPE, METHOD, PARAMETER, FIELD}) @Retention(RUNTIME) @Documented public @interface Small { }
737
26.333333
69
java
null
infinispan-main/cdi/remote/src/test/java/org/infinispan/cdi/embedded/test/cache/remote/DefaultCacheTest.java
package org.infinispan.cdi.embedded.test.cache.remote; import static org.infinispan.cdi.embedded.test.Deployments.baseDeployment; import static org.infinispan.client.hotrod.test.HotRodClientTestingUtil.startHotRodServer; import static org.infinispan.server.hotrod.test.HotRodTestingUtil.hotRodCacheConfiguration; import static org.testng.Assert.assertEquals; import jakarta.enterprise.context.ApplicationScoped; import jakarta.enterprise.inject.Disposes; import jakarta.enterprise.inject.Produces; import jakarta.inject.Inject; import org.infinispan.cdi.remote.Remote; import org.infinispan.client.hotrod.RemoteCache; import org.infinispan.client.hotrod.RemoteCacheManager; import org.infinispan.client.hotrod.test.HotRodClientTestingUtil; import org.infinispan.commons.test.ThreadLeakChecker; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.server.core.test.ServerTestingUtil; import org.infinispan.server.hotrod.HotRodServer; import org.infinispan.test.TestingUtil; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.infinispan.commons.test.TestResourceTrackingListener; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.testng.Arquillian; import org.jboss.shrinkwrap.api.Archive; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Listeners; import org.testng.annotations.Test; /** * Tests the default cache injection. * * @author Kevin Pollet &lt;kevin.pollet@serli.com&gt; (C) 2011 SERLI */ @Listeners(TestResourceTrackingListener.class) @Test(groups = "functional", testName = "cdi.test.cache.remote.DefaultCacheTest") public class DefaultCacheTest extends Arquillian { private static final String SERVER_LIST_KEY = "infinispan.client.hotrod.server_list"; @Deployment public static Archive<?> deployment() { return baseDeployment() .addClass(DefaultCacheTest.class); } private static HotRodServer hotRodServer; private static EmbeddedCacheManager embeddedCacheManager; @Inject @Remote private RemoteCache<String, String> cache; @Inject private RemoteCache<String, String> remoteCache; @BeforeClass public void beforeMethod() { embeddedCacheManager = TestCacheManagerFactory.createCacheManager( hotRodCacheConfiguration(TestCacheManagerFactory .getDefaultCacheConfiguration(false))); hotRodServer = startHotRodServer(embeddedCacheManager); } @AfterClass(alwaysRun = true) public void afterMethod() { TestingUtil.killCacheManagers(embeddedCacheManager); ServerTestingUtil.killServer(hotRodServer); // RemoteCacheProducer leaks thread, see ISPN-9935 ThreadLeakChecker.ignoreThreadsContaining("HotRod-client-async-pool-"); } public void testDefaultCache() { cache.put("pete", "British"); cache.put("manik", "Sri Lankan"); assertEquals(cache.get("pete"), "British"); assertEquals(cache.get("manik"), "Sri Lankan"); assertEquals(remoteCache.get("pete"), "British"); assertEquals(remoteCache.get("manik"), "Sri Lankan"); } /** * Overrides the default remote cache manager. */ @Produces @ApplicationScoped public static RemoteCacheManager defaultRemoteCacheManager() { return new RemoteCacheManager( HotRodClientTestingUtil.newRemoteConfigurationBuilder(hotRodServer).build()); } static void stopRemoteCacheManager(@Disposes RemoteCacheManager remoteCacheManager) { remoteCacheManager.stop(); } }
3,585
34.86
91
java
null
infinispan-main/cdi/remote/src/main/java/org/infinispan/cdi/remote/InfinispanExtensionRemote.java
package org.infinispan.cdi.remote; import java.lang.annotation.Annotation; import java.lang.reflect.Type; import java.util.HashMap; import java.util.Map; import java.util.Set; import jakarta.enterprise.context.ApplicationScoped; import jakarta.enterprise.context.spi.CreationalContext; import jakarta.enterprise.event.Observes; import jakarta.enterprise.inject.Default; import jakarta.enterprise.inject.spi.AfterBeanDiscovery; import jakarta.enterprise.inject.spi.Annotated; import jakarta.enterprise.inject.spi.AnnotatedMember; import jakarta.enterprise.inject.spi.Bean; import jakarta.enterprise.inject.spi.BeanManager; import jakarta.enterprise.inject.spi.Extension; import jakarta.enterprise.inject.spi.InjectionPoint; import jakarta.enterprise.inject.spi.InjectionTarget; import jakarta.enterprise.inject.spi.ProcessInjectionTarget; import jakarta.enterprise.inject.spi.ProcessProducer; import jakarta.enterprise.inject.spi.Producer; import jakarta.enterprise.util.AnnotationLiteral; import org.infinispan.cdi.common.util.AnyLiteral; import org.infinispan.cdi.common.util.BeanBuilder; import org.infinispan.cdi.common.util.ContextualLifecycle; import org.infinispan.cdi.common.util.DefaultLiteral; import org.infinispan.cdi.common.util.Reflections; import org.infinispan.cdi.remote.logging.RemoteLog; import org.infinispan.client.hotrod.RemoteCache; import org.infinispan.client.hotrod.RemoteCacheManager; import org.infinispan.client.hotrod.configuration.ConfigurationBuilder; import org.infinispan.commons.logging.LogFactory; public class InfinispanExtensionRemote implements Extension { private static final RemoteLog LOGGER = LogFactory.getLog(InfinispanExtensionRemote.class, RemoteLog.class); private final Map<Type, Set<Annotation>> remoteCacheInjectionPoints; private Producer<RemoteCache<?, ?>> remoteCacheProducer; public InfinispanExtensionRemote() { new ConfigurationBuilder(); // Attempt to initialize a hotrod client class this.remoteCacheInjectionPoints = new HashMap<Type, Set<Annotation>>(); } void processProducers(@Observes ProcessProducer<?, ?> event) { AnnotatedMember<?> member = event.getAnnotatedMember(); if (RemoteCacheProducer.class.equals(member.getDeclaringType().getBaseType())) { remoteCacheProducer = (Producer<RemoteCache<?, ?>>) event.getProducer(); } } <T> void saveRemoteInjectionPoints(@Observes ProcessInjectionTarget<T> event, BeanManager beanManager) { final InjectionTarget<T> injectionTarget = event.getInjectionTarget(); for (InjectionPoint injectionPoint : injectionTarget.getInjectionPoints()) { final Annotated annotated = injectionPoint.getAnnotated(); final Type type = annotated.getBaseType(); final Class<?> rawType = Reflections.getRawType(annotated.getBaseType()); final Set<Annotation> qualifiers = Reflections.getQualifiers(beanManager, annotated.getAnnotations()); if (rawType.equals(RemoteCache.class) && qualifiers.isEmpty()) { qualifiers.add(new AnnotationLiteral<Default>() { }); addRemoteCacheInjectionPoint(type, qualifiers); } else if (!annotated.isAnnotationPresent(Remote.class) && Reflections.getMetaAnnotation(annotated, Remote.class) != null && rawType.isAssignableFrom(RemoteCache.class)) { addRemoteCacheInjectionPoint(type, qualifiers); } } } private void addRemoteCacheInjectionPoint(Type type, Set<Annotation> qualifiers) { final Set<Annotation> currentQualifiers = remoteCacheInjectionPoints.get(type); if (currentQualifiers == null) { remoteCacheInjectionPoints.put(type, qualifiers); } else { currentQualifiers.addAll(qualifiers); } } @SuppressWarnings("unchecked") <T, X> void registerBeans(@Observes AfterBeanDiscovery event, final BeanManager beanManager) { if (beanManager.getBeans(RemoteCacheManager.class).isEmpty()) { LOGGER.addDefaultRemoteCacheManager(); event.addBean(createDefaultRemoteCacheManagerBean(beanManager)); } for (Map.Entry<Type, Set<Annotation>> entry : remoteCacheInjectionPoints.entrySet()) { event.addBean(new BeanBuilder(beanManager) .readFromType(beanManager.createAnnotatedType(Reflections.getRawType(entry.getKey()))) .addType(entry.getKey()) .addQualifiers(entry.getValue()) .passivationCapable(true) .id(InfinispanExtensionRemote.class.getSimpleName() + "#" + RemoteCache.class.getSimpleName()) .beanLifecycle(new ContextualLifecycle<RemoteCache<?, ?>>() { @Override public RemoteCache<?, ?> create(Bean<RemoteCache<?, ?>> bean, CreationalContext<RemoteCache<?, ?>> ctx) { return remoteCacheProducer.produce(ctx); } @Override public void destroy(Bean<RemoteCache<?, ?>> bean, RemoteCache<?, ?> instance, CreationalContext<RemoteCache<?, ?>> ctx) { remoteCacheProducer.dispose(instance); } }).create()); } } /** * The default remote cache manager can be overridden by creating a producer which produces the new default remote * cache manager. The remote cache manager produced must have the scope {@link ApplicationScoped} and the * {@linkplain jakarta.enterprise.inject.Default Default} qualifier. * * @param beanManager * @return a custom bean */ private Bean<RemoteCacheManager> createDefaultRemoteCacheManagerBean(BeanManager beanManager) { return new BeanBuilder<RemoteCacheManager>(beanManager) .beanClass(InfinispanExtensionRemote.class) .addTypes(Object.class, RemoteCacheManager.class) .scope(ApplicationScoped.class) .qualifiers(DefaultLiteral.INSTANCE, AnyLiteral.INSTANCE) .passivationCapable(true) .id(InfinispanExtensionRemote.class.getSimpleName() + "#" + RemoteCacheManager.class.getSimpleName()) .beanLifecycle(new ContextualLifecycle<RemoteCacheManager>() { @Override public RemoteCacheManager create(Bean<RemoteCacheManager> bean, CreationalContext<RemoteCacheManager> creationalContext) { return new RemoteCacheManager(); } @Override public void destroy(Bean<RemoteCacheManager> bean, RemoteCacheManager instance, CreationalContext<RemoteCacheManager> creationalContext) { instance.stop(); } }).create(); } }
7,093
45.366013
145
java
null
infinispan-main/cdi/remote/src/main/java/org/infinispan/cdi/remote/Remote.java
package org.infinispan.cdi.remote; import static java.lang.annotation.ElementType.FIELD; import static java.lang.annotation.ElementType.METHOD; import static java.lang.annotation.ElementType.PARAMETER; import static java.lang.annotation.ElementType.TYPE; import static java.lang.annotation.RetentionPolicy.RUNTIME; import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.Target; import jakarta.enterprise.util.Nonbinding; import jakarta.inject.Qualifier; /** * Qualifier used to specify which remote cache will be injected. * * @author Kevin Pollet &lt;kevin.pollet@serli.com&gt; (C) 2011 SERLI */ @Target({METHOD, FIELD, PARAMETER, TYPE}) @Retention(RUNTIME) @Documented @Qualifier public @interface Remote { /** * The remote cache name. If no value is provided the default cache is assumed. */ @Nonbinding String value() default ""; }
910
28.387097
82
java
null
infinispan-main/cdi/remote/src/main/java/org/infinispan/cdi/remote/RemoteCacheProducer.java
package org.infinispan.cdi.remote; import static org.infinispan.cdi.common.util.Reflections.getMetaAnnotation; import java.lang.annotation.Annotation; import java.util.Set; import jakarta.enterprise.context.ApplicationScoped; import jakarta.enterprise.inject.Any; import jakarta.enterprise.inject.Instance; import jakarta.enterprise.inject.Produces; import jakarta.enterprise.inject.spi.Annotated; import jakarta.enterprise.inject.spi.InjectionPoint; import jakarta.inject.Inject; import org.infinispan.client.hotrod.RemoteCache; import org.infinispan.client.hotrod.RemoteCacheManager; /** * The {@link RemoteCache} producer. * * @author Kevin Pollet &lt;kevin.pollet@serli.com&gt; (C) 2011 SERLI */ @ApplicationScoped public class RemoteCacheProducer { @Inject private RemoteCacheManager defaultRemoteCacheManager; @Any @Inject private Instance<RemoteCacheManager> cacheManagers; /** * Produces the remote cache. * * @param injectionPoint the injection point. * @param <K> the type of the key. * @param <V> the type of the value. * @return the remote cache instance. */ @Remote @Produces public <K, V> RemoteCache<K, V> getRemoteCache(InjectionPoint injectionPoint) { final Set<Annotation> qualifiers = injectionPoint.getQualifiers(); final RemoteCacheManager cacheManager = getRemoteCacheManager(qualifiers.toArray(new Annotation[0])); final Remote remote = getRemoteAnnotation(injectionPoint.getAnnotated()); if (remote != null && !remote.value().isEmpty()) { return cacheManager.getCache(remote.value()); } return cacheManager.getCache(); } /** * Retrieves the {@link RemoteCacheManager} bean with the following qualifiers. * * @param qualifiers the qualifiers. * @return the {@link RemoteCacheManager} qualified or the default one if no bean with the given qualifiers has been * found. */ private RemoteCacheManager getRemoteCacheManager(Annotation[] qualifiers) { final Instance<RemoteCacheManager> specificCacheManager = cacheManagers.select(qualifiers); if (specificCacheManager.isUnsatisfied()) { return defaultRemoteCacheManager; } return specificCacheManager.get(); } /** * Retrieves the {@link Remote} annotation instance on the given annotated element. * * @param annotated the annotated element. * @return the {@link Remote} annotation instance or {@code null} if not found. */ private Remote getRemoteAnnotation(Annotated annotated) { Remote remote = annotated.getAnnotation(Remote.class); if (remote == null) { remote = getMetaAnnotation(annotated, Remote.class); } return remote; } }
2,779
31.325581
119
java
null
infinispan-main/cdi/remote/src/main/java/org/infinispan/cdi/remote/logging/package-info.java
/** * This package contains the logging classes. */ package org.infinispan.cdi.remote.logging;
97
18.6
45
java
null
infinispan-main/cdi/remote/src/main/java/org/infinispan/cdi/remote/logging/RemoteLog.java
package org.infinispan.cdi.remote.logging; import static org.jboss.logging.Logger.Level.INFO; import org.jboss.logging.BasicLogger; import org.jboss.logging.annotations.LogMessage; import org.jboss.logging.annotations.Message; import org.jboss.logging.annotations.MessageLogger; /** * The JBoss Logging interface which defined the logging methods for the CDI integration. The id range for the CDI * integration is 17001-18000 * * @author Kevin Pollet &lt;kevin.pollet@serli.com&gt; (C) 2011 SERLI */ @MessageLogger(projectCode = "ISPN") public interface RemoteLog extends BasicLogger { @LogMessage(level = INFO) @Message(value = "Overriding default remote cache manager not found - adding default implementation", id = 17004) void addDefaultRemoteCacheManager(); }
784
31.708333
116
java
null
infinispan-main/cdi/embedded/src/test/java/org/infinispan/cdi/embedded/test/ServiceLoaderTest.java
package org.infinispan.cdi.embedded.test; import static org.testng.AssertJUnit.fail; import java.util.ServiceLoader; import jakarta.enterprise.inject.spi.Extension; import org.infinispan.cdi.embedded.InfinispanExtensionEmbedded; import org.testng.annotations.Test; @Test(groups="functional", testName="cdi.test.ServiceLoaderTest") public class ServiceLoaderTest { public void testServiceLoaderExtension() { ServiceLoader<Extension> extensions = ServiceLoader.load(Extension.class); for(Extension extension : extensions) { if (extension instanceof InfinispanExtensionEmbedded) return; } fail("Could not load Infinispan CDI Extension"); } }
699
24.925926
80
java
null
infinispan-main/cdi/embedded/src/test/java/org/infinispan/cdi/embedded/test/DefaultTestEmbeddedCacheManagerProducer.java
package org.infinispan.cdi.embedded.test; import static org.infinispan.test.fwk.TestCacheManagerFactory.createClusteredCacheManager; import jakarta.enterprise.context.ApplicationScoped; import jakarta.enterprise.inject.Disposes; import jakarta.enterprise.inject.Produces; import org.infinispan.configuration.cache.Configuration; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.global.GlobalConfigurationBuilder; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.test.TestingUtil; import org.infinispan.commons.test.TestResourceTracker; /** * <p>The alternative default {@link EmbeddedCacheManager} producer for the test environment.</p> * * @author Galder Zamarreño */ public class DefaultTestEmbeddedCacheManagerProducer { /** * Produces the default embedded cache manager. * * @param defaultConfiguration the default configuration produced by the {@link DefaultTestEmbeddedCacheManagerProducer}. * @return the default embedded cache manager used by the application. */ @Produces @ApplicationScoped public EmbeddedCacheManager getDefaultEmbeddedCacheManager(Configuration defaultConfiguration) { // Sometimes we're called from a remote thread that doesn't have the test name set // We don't have the test name here, either, but we can use a dummy one TestResourceTracker.setThreadTestNameIfMissing("DefaultTestEmbeddedCacheManagerProducer"); ConfigurationBuilder builder = new ConfigurationBuilder(); GlobalConfigurationBuilder globalConfigurationBuilder = new GlobalConfigurationBuilder(); builder.read(defaultConfiguration); EmbeddedCacheManager manager = createClusteredCacheManager(globalConfigurationBuilder, builder); // Defie a wildcard configuration for the CDI integration tests manager.defineConfiguration("org.infinispan.integrationtests.cdijcache.interceptor.service.Cache*Service*", new ConfigurationBuilder().template(true).build()); return manager; } /** * Stops the default embedded cache manager when the corresponding instance is released. * * @param defaultEmbeddedCacheManager the default embedded cache manager. */ private void stopCacheManager(@Disposes EmbeddedCacheManager defaultEmbeddedCacheManager) { TestingUtil.killCacheManagers(defaultEmbeddedCacheManager); } }
2,441
42.607143
124
java
null
infinispan-main/cdi/embedded/src/test/java/org/infinispan/cdi/embedded/test/cachemanager/DefaultConfigurationTest.java
package org.infinispan.cdi.embedded.test.cachemanager; import static org.infinispan.cdi.embedded.test.testutil.Deployments.baseDeployment; import static org.testng.Assert.assertEquals; import jakarta.enterprise.context.ApplicationScoped; import jakarta.enterprise.inject.Produces; import jakarta.inject.Inject; import org.infinispan.Cache; import org.infinispan.cdi.embedded.test.DefaultTestEmbeddedCacheManagerProducer; import org.infinispan.configuration.cache.Configuration; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.testng.Arquillian; import org.jboss.shrinkwrap.api.Archive; import org.testng.annotations.Test; /** * Tests that the default embedded cache configuration can be overridden. * * @author Kevin Pollet &lt;kevin.pollet@serli.com&gt; (C) 2011 SERLI */ @Test(groups = "functional", testName = "cdi.test.cachemanager.embedded.DefaultConfigurationTest") public class DefaultConfigurationTest extends Arquillian { @Deployment public static Archive<?> deployment() { return baseDeployment() .addClass(DefaultConfigurationTest.class) .addClass(DefaultTestEmbeddedCacheManagerProducer.class); } @Inject private Cache<?, ?> cache; public void testDefaultConfiguration() { assertEquals(cache.getCacheConfiguration().memory().size(), 16); assertEquals(cache.getName(), TestCacheManagerFactory.DEFAULT_CACHE_NAME); } /** * Overrides the default embedded cache configuration used for the initialization of the default embedded cache * manager. */ @ApplicationScoped public static class Config { @Produces public Configuration customDefaultConfiguration() { return new ConfigurationBuilder() .memory().size(16) .build(); } } }
1,950
33.22807
114
java
null
infinispan-main/cdi/embedded/src/test/java/org/infinispan/cdi/embedded/test/cachemanager/external/Large.java
package org.infinispan.cdi.embedded.test.cachemanager.external; import static java.lang.annotation.ElementType.FIELD; import static java.lang.annotation.ElementType.METHOD; import static java.lang.annotation.ElementType.PARAMETER; import static java.lang.annotation.ElementType.TYPE; import static java.lang.annotation.RetentionPolicy.RUNTIME; import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.Target; import jakarta.inject.Qualifier; /** * @author Pete Muir */ @Qualifier @Target({TYPE, METHOD, PARAMETER, FIELD}) @Retention(RUNTIME) @Documented public @interface Large { }
639
24.6
63
java
null
infinispan-main/cdi/embedded/src/test/java/org/infinispan/cdi/embedded/test/cachemanager/external/Quick.java
package org.infinispan.cdi.embedded.test.cachemanager.external; import static java.lang.annotation.ElementType.FIELD; import static java.lang.annotation.ElementType.METHOD; import static java.lang.annotation.ElementType.PARAMETER; import static java.lang.annotation.ElementType.TYPE; import static java.lang.annotation.RetentionPolicy.RUNTIME; import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.Target; import jakarta.inject.Qualifier; /** * @author Pete Muir */ @Qualifier @Target({TYPE, METHOD, PARAMETER, FIELD}) @Retention(RUNTIME) @Documented public @interface Quick { }
639
24.6
63
java
null
infinispan-main/cdi/embedded/src/test/java/org/infinispan/cdi/embedded/test/cachemanager/external/ExternalCacheContainerTest.java
package org.infinispan.cdi.embedded.test.cachemanager.external; import static org.infinispan.cdi.embedded.test.testutil.Deployments.baseDeployment; import static org.testng.Assert.assertEquals; import jakarta.inject.Inject; import org.infinispan.AdvancedCache; import org.infinispan.commons.test.TestResourceTrackingListener; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.testng.Arquillian; import org.jboss.shrinkwrap.api.Archive; import org.testng.annotations.Listeners; import org.testng.annotations.Test; /** * Tests for a cache container defined by some external mechanism. * * @author Pete Muir * @see Config */ @Listeners(TestResourceTrackingListener.class) @Test(groups = "functional", testName = "cdi.test.cachemanager.embedded.external.ExternalCacheContainerTest") public class ExternalCacheContainerTest extends Arquillian { @Deployment public static Archive<?> deployment() { return baseDeployment() .addPackage(ExternalCacheContainerTest.class.getPackage()); } @Inject @Large private AdvancedCache<?, ?> largeCache; @Inject @Quick private AdvancedCache<?, ?> quickCache; public void testLargeCache() { assertEquals(largeCache.getCacheConfiguration().memory().size(), 100); } public void testQuickCache() { assertEquals(quickCache.getCacheConfiguration().expiration().wakeUpInterval(), 1); } }
1,431
28.22449
109
java
null
infinispan-main/cdi/embedded/src/test/java/org/infinispan/cdi/embedded/test/cachemanager/external/Config.java
package org.infinispan.cdi.embedded.test.cachemanager.external; import jakarta.enterprise.context.ApplicationScoped; import jakarta.enterprise.inject.Disposes; import jakarta.enterprise.inject.Produces; import org.infinispan.cdi.embedded.ConfigureCache; import org.infinispan.configuration.cache.Configuration; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.test.TestingUtil; import org.infinispan.test.fwk.TestCacheManagerFactory; /** * Creates a number of caches, based on some external mechanism. * * @author Pete Muir * @author Kevin Pollet &lt;kevin.pollet@serli.com&gt; (C) 2011 SERLI */ public class Config { /** * Associates the externally defined "large" cache with the qualifier {@link Large}. */ @Large @ConfigureCache("large") @Produces @SuppressWarnings("unused") public Configuration largeConfiguration; /** * Associates the externally defined "quick" cache with the qualifier {@link Quick}. */ @Quick @ConfigureCache("quick") @Produces @SuppressWarnings("unused") public Configuration quickConfiguration; /** * Overrides the default embedded cache manager to define the quick and large cache configurations externally. */ @Produces @ApplicationScoped @SuppressWarnings("unused") public EmbeddedCacheManager defaultCacheManager() { EmbeddedCacheManager externalCacheContainerManager = TestCacheManagerFactory.createCacheManager(false); // define large configuration externalCacheContainerManager.defineConfiguration("large", new ConfigurationBuilder() .memory().size(100) .build()); // define quick configuration externalCacheContainerManager.defineConfiguration("quick", new ConfigurationBuilder() .expiration().wakeUpInterval(1l) .build()); return externalCacheContainerManager; } /** * Stops cache manager. * * @param cacheManager to be stopped */ @SuppressWarnings("unused") public void killCacheManager(@Disposes EmbeddedCacheManager cacheManager) { TestingUtil.killCacheManagers(cacheManager); } }
2,220
29.847222
113
java
null
infinispan-main/cdi/embedded/src/test/java/org/infinispan/cdi/embedded/test/cachemanager/xml/VeryLarge.java
package org.infinispan.cdi.embedded.test.cachemanager.xml; import static java.lang.annotation.ElementType.FIELD; import static java.lang.annotation.ElementType.METHOD; import static java.lang.annotation.ElementType.PARAMETER; import static java.lang.annotation.ElementType.TYPE; import static java.lang.annotation.RetentionPolicy.RUNTIME; import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.Target; import jakarta.inject.Qualifier; /** * @author Pete Muir */ @Qualifier @Target({TYPE, METHOD, PARAMETER, FIELD}) @Retention(RUNTIME) @Documented public @interface VeryLarge { }
638
24.56
59
java
null
infinispan-main/cdi/embedded/src/test/java/org/infinispan/cdi/embedded/test/cachemanager/xml/XMLConfiguredCacheContainerTest.java
package org.infinispan.cdi.embedded.test.cachemanager.xml; import static org.infinispan.cdi.embedded.test.testutil.Deployments.baseDeployment; import static org.testng.AssertJUnit.assertEquals; import jakarta.inject.Inject; import org.infinispan.AdvancedCache; import org.infinispan.commons.test.TestResourceTrackingListener; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.testng.Arquillian; import org.jboss.shrinkwrap.api.Archive; import org.testng.annotations.Listeners; import org.testng.annotations.Test; /** * Test that a cache configured in XML is available, and that it can be overridden. * * @author Pete Muir * @see Config */ @Listeners(TestResourceTrackingListener.class) @Test(groups = "functional", testName = "cdi.test.cachemanager.embedded.xml.XMLConfiguredCacheContainerTest") public class XMLConfiguredCacheContainerTest extends Arquillian { @Deployment public static Archive<?> deployment() { return baseDeployment() .addPackage(XMLConfiguredCacheContainerTest.class.getPackage()); } @Inject @VeryLarge private AdvancedCache<?, ?> largeCache; @Inject @Quick private AdvancedCache<?, ?> quickCache; public void testVeryLargeCache() { assertEquals(largeCache.getCacheConfiguration().memory().size(), 1000); } public void testQuickCache() { assertEquals(quickCache.getCacheConfiguration().memory().size(), 1000); assertEquals(quickCache.getCacheConfiguration().expiration().wakeUpInterval(), 1); } }
1,544
30.530612
109
java
null
infinispan-main/cdi/embedded/src/test/java/org/infinispan/cdi/embedded/test/cachemanager/xml/Quick.java
package org.infinispan.cdi.embedded.test.cachemanager.xml; import static java.lang.annotation.ElementType.FIELD; import static java.lang.annotation.ElementType.METHOD; import static java.lang.annotation.ElementType.PARAMETER; import static java.lang.annotation.ElementType.TYPE; import static java.lang.annotation.RetentionPolicy.RUNTIME; import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.Target; import jakarta.inject.Qualifier; /** * @author Pete Muir */ @Qualifier @Target({TYPE, METHOD, PARAMETER, FIELD}) @Retention(RUNTIME) @Documented public @interface Quick { }
634
24.4
59
java
null
infinispan-main/cdi/embedded/src/test/java/org/infinispan/cdi/embedded/test/cachemanager/xml/Config.java
package org.infinispan.cdi.embedded.test.cachemanager.xml; import java.io.IOException; import jakarta.enterprise.context.ApplicationScoped; import jakarta.enterprise.inject.Disposes; import jakarta.enterprise.inject.Produces; import org.infinispan.cdi.embedded.ConfigureCache; import org.infinispan.configuration.cache.Configuration; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.test.TestingUtil; import org.infinispan.test.fwk.TestCacheManagerFactory; /** * Creates a number of caches, based on some external mechanism. * * @author Pete Muir * @author Kevin Pollet &lt;kevin.pollet@serli.com&gt; (C) 2011 SERLI */ public class Config { /** * <p>Associates the "very-large" cache (configured below) with the qualifier {@link VeryLarge}.</p> * * <p>The default configuration defined in "infinispan.xml" will be used.</p> */ @VeryLarge @ConfigureCache("very-large") @Produces @SuppressWarnings("unused") public Configuration veryLargeConfiguration; /** * Associates the "quick-very-large" cache (configured below) with the qualifier {@link Quick}. */ @Quick @ConfigureCache("quick-very-large") @Produces @SuppressWarnings("unused") public Configuration quickVeryLargeConfiguration; /** * Overrides the default embedded cache manager. */ @Produces @ApplicationScoped @SuppressWarnings("unused") public EmbeddedCacheManager defaultCacheManager() throws IOException { EmbeddedCacheManager externalCacheContainerManager = TestCacheManagerFactory.fromXml("infinispan.xml"); externalCacheContainerManager.defineConfiguration("quick-very-large", new ConfigurationBuilder() .read(externalCacheContainerManager.getDefaultCacheConfiguration()) .expiration().wakeUpInterval(1l) .build()); return externalCacheContainerManager; } /** * Stops cache manager. * * @param cacheManager to be stopped */ @SuppressWarnings("unused") public void killCacheManager(@Disposes EmbeddedCacheManager cacheManager) { TestingUtil.killCacheManagers(cacheManager); } }
2,219
30.267606
109
java
null
infinispan-main/cdi/embedded/src/test/java/org/infinispan/cdi/embedded/test/cachemanager/registration/VeryLarge.java
package org.infinispan.cdi.embedded.test.cachemanager.registration; import static java.lang.annotation.ElementType.FIELD; import static java.lang.annotation.ElementType.METHOD; import static java.lang.annotation.ElementType.PARAMETER; import static java.lang.annotation.ElementType.TYPE; import static java.lang.annotation.RetentionPolicy.RUNTIME; import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.Target; import jakarta.inject.Qualifier; /** * @author Kevin Pollet &lt;kevin.pollet@serli.com&gt; (C) 2011 SERLI */ @Qualifier @Target({TYPE, METHOD, PARAMETER, FIELD}) @Retention(RUNTIME) @Documented public @interface VeryLarge { }
696
26.88
69
java
null
infinispan-main/cdi/embedded/src/test/java/org/infinispan/cdi/embedded/test/cachemanager/registration/Large.java
package org.infinispan.cdi.embedded.test.cachemanager.registration; import static java.lang.annotation.ElementType.FIELD; import static java.lang.annotation.ElementType.METHOD; import static java.lang.annotation.ElementType.PARAMETER; import static java.lang.annotation.ElementType.TYPE; import static java.lang.annotation.RetentionPolicy.RUNTIME; import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.Target; import jakarta.inject.Qualifier; /** * @author Kevin Pollet &lt;kevin.pollet@serli.com&gt; (C) 2011 SERLI */ @Qualifier @Target({TYPE, METHOD, PARAMETER, FIELD}) @Retention(RUNTIME) @Documented public @interface Large { }
692
26.72
69
java
null
infinispan-main/cdi/embedded/src/test/java/org/infinispan/cdi/embedded/test/cachemanager/registration/Small.java
package org.infinispan.cdi.embedded.test.cachemanager.registration; import static java.lang.annotation.ElementType.FIELD; import static java.lang.annotation.ElementType.METHOD; import static java.lang.annotation.ElementType.PARAMETER; import static java.lang.annotation.ElementType.TYPE; import static java.lang.annotation.RetentionPolicy.RUNTIME; import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.Target; import jakarta.inject.Qualifier; /** * @author Kevin Pollet &lt;kevin.pollet@serli.com&gt; (C) 2011 SERLI */ @Qualifier @Target({TYPE, METHOD, PARAMETER, FIELD}) @Retention(RUNTIME) @Documented public @interface Small { }
692
26.72
69
java
null
infinispan-main/cdi/embedded/src/test/java/org/infinispan/cdi/embedded/test/cachemanager/registration/Config.java
package org.infinispan.cdi.embedded.test.cachemanager.registration; import jakarta.enterprise.context.ApplicationScoped; import jakarta.enterprise.inject.Produces; import org.infinispan.cdi.embedded.ConfigureCache; import org.infinispan.configuration.cache.Configuration; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.test.fwk.TestCacheManagerFactory; /** * @author Kevin Pollet &lt;kevin.pollet@serli.com&gt; (C) 2011 SERLI */ public class Config { /** * <p>Defines the "small" cache configuration.</p> * * <p>This cache will be registered with the default configuration of the default cache manager.</p> */ @Small @ConfigureCache("small") @Produces @SuppressWarnings("unused") public Configuration smallConfiguration; /** * <p>Defines the "large" cache configuration.</p> * * <p>This cache will be registered with the produced configuration in the default cache manager.</p> */ @Large @ConfigureCache("large") @Produces @SuppressWarnings("unused") public Configuration largeConfiguration() { return new ConfigurationBuilder() .memory().size(1024) .build(); } /** * <p>Defines the "very-large" cache configuration.</p> * * <p>This cache will be registered with the produced configuration in the specific cache manager.</p> */ @VeryLarge @ConfigureCache("very-large") @Produces @SuppressWarnings("unused") public Configuration veryLargeConfiguration() { return new ConfigurationBuilder() .memory().size(4096) .build(); } /** * <p>Produces the specific cache manager.</p> * * <p>The "very-large" cache is associated to the specific cache manager with the cache qualifier.</p> */ @VeryLarge @Produces @ApplicationScoped @SuppressWarnings("unused") public EmbeddedCacheManager specificCacheManager() { return TestCacheManagerFactory.createCacheManager(); } }
2,067
28.542857
105
java
null
infinispan-main/cdi/embedded/src/test/java/org/infinispan/cdi/embedded/test/cachemanager/registration/CacheRegistrationTest.java
package org.infinispan.cdi.embedded.test.cachemanager.registration; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertTrue; import java.util.Arrays; import java.util.Set; import jakarta.inject.Inject; import org.infinispan.Cache; import org.infinispan.cdi.embedded.test.DefaultTestEmbeddedCacheManagerProducer; import org.infinispan.cdi.embedded.test.testutil.Deployments; import org.infinispan.commons.test.TestResourceTrackingListener; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.testng.Arquillian; import org.jboss.shrinkwrap.api.Archive; import org.testng.annotations.Listeners; import org.testng.annotations.Test; /** * Tests that configured caches are registered in the corresponding cache manager. * * @author Kevin Pollet &lt;kevin.pollet@serli.com&gt; (C) 2011 SERLI */ @Listeners(TestResourceTrackingListener.class) @Test(groups = "functional", testName = "cdi.test.cachemanager.embedded.registration.CacheRegistrationTest") public class CacheRegistrationTest extends Arquillian { @Deployment public static Archive<?> deployment() { return Deployments.baseDeployment() .addPackage(CacheRegistrationTest.class.getPackage()) .addClass(DefaultTestEmbeddedCacheManagerProducer.class); } @Inject private EmbeddedCacheManager defaultCacheManager; @Inject private Cache<String, String> cache; @VeryLarge @Inject private EmbeddedCacheManager specificCacheManager; public void testCacheRegistrationInDefaultCacheManager() { // Make sure the cache is registered cache.put("foo", "bar"); final Set<String> cacheNames = defaultCacheManager.getCacheNames(); assertEquals(cacheNames.size(), 3); assertTrue(cacheNames.containsAll(Arrays.asList("small", "large", TestCacheManagerFactory.DEFAULT_CACHE_NAME))); } public void testCacheRegistrationInSpecificCacheManager() { // Make sure the cache is registered cache.put("foo", "bar"); final Set<String> cacheNames = specificCacheManager.getCacheConfigurationNames(); assertEquals(cacheNames.size(), 1); assertTrue(cacheNames.containsAll(Arrays.asList("very-large"))); } }
2,351
33.588235
118
java
null
infinispan-main/cdi/embedded/src/test/java/org/infinispan/cdi/embedded/test/cachemanager/programmatic/ProgrammaticCacheContainerTest.java
package org.infinispan.cdi.embedded.test.cachemanager.programmatic; import static org.testng.Assert.assertEquals; import jakarta.inject.Inject; import jakarta.inject.Named; import org.infinispan.AdvancedCache; import org.infinispan.cdi.embedded.test.testutil.Deployments; import org.infinispan.commons.test.TestResourceTrackingListener; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.testng.Arquillian; import org.jboss.shrinkwrap.api.Archive; import org.testng.annotations.Listeners; import org.testng.annotations.Test; /** * Tests for a cache container defined programmatically. * * @author Pete Muir * @see Config */ @Listeners(TestResourceTrackingListener.class) @Test(groups = {"functional", "smoke"}, testName = "cdi.test.cachemanager.embedded.programmatic.ProgrammaticCacheContainerTest") public class ProgrammaticCacheContainerTest extends Arquillian { @Deployment public static Archive<?> deployment() { return Deployments.baseDeployment() .addPackage(ProgrammaticCacheContainerTest.class.getPackage()); } @Inject @Small private AdvancedCache<?, ?> smallCache; @Inject @Named("large") private AdvancedCache<?, ?> largeCache; @Inject @Named("super-large") private AdvancedCache<?, ?> superLargeCache; @Inject private SmallCacheObservers observers; public void testSmallCache() { assertEquals(smallCache.getCacheConfiguration().memory().size(), 7); assertEquals(observers.getCacheStartedEventCount(), 1); } public void testLargeCache() { assertEquals(largeCache.getCacheConfiguration().memory().size(), 10); } public void testSuperLargeCache() { assertEquals(superLargeCache.getCacheConfiguration().memory().size(), 20); } }
1,792
27.919355
128
java
null
infinispan-main/cdi/embedded/src/test/java/org/infinispan/cdi/embedded/test/cachemanager/programmatic/SmallCacheObservers.java
package org.infinispan.cdi.embedded.test.cachemanager.programmatic; import jakarta.enterprise.context.ApplicationScoped; import jakarta.enterprise.event.Observes; import org.infinispan.notifications.cachemanagerlistener.event.CacheStartedEvent; /** * @author Pete Muir */ @ApplicationScoped public class SmallCacheObservers { private CacheStartedEvent cacheStartedEvent; private int cacheStartedEventCount; /** * Observe the cache started event for the cache associated with @Cache1 */ void observeCacheStarted(@Observes @Small CacheStartedEvent event) { this.cacheStartedEventCount++; this.cacheStartedEvent = event; } public CacheStartedEvent getCacheStartedEvent() { return cacheStartedEvent; } public int getCacheStartedEventCount() { return cacheStartedEventCount; } }
842
24.545455
81
java
null
infinispan-main/cdi/embedded/src/test/java/org/infinispan/cdi/embedded/test/cachemanager/programmatic/Small.java
package org.infinispan.cdi.embedded.test.cachemanager.programmatic; import static java.lang.annotation.ElementType.FIELD; import static java.lang.annotation.ElementType.METHOD; import static java.lang.annotation.ElementType.PARAMETER; import static java.lang.annotation.ElementType.TYPE; import static java.lang.annotation.RetentionPolicy.RUNTIME; import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.Target; import jakarta.inject.Qualifier; /** * @author Pete Muir */ @Qualifier @Target({TYPE, METHOD, PARAMETER, FIELD}) @Retention(RUNTIME) @Documented public @interface Small { }
643
24.76
67
java
null
infinispan-main/cdi/embedded/src/test/java/org/infinispan/cdi/embedded/test/cachemanager/programmatic/Config.java
package org.infinispan.cdi.embedded.test.cachemanager.programmatic; import jakarta.enterprise.context.ApplicationScoped; import jakarta.enterprise.inject.Disposes; import jakarta.enterprise.inject.Produces; import jakarta.inject.Named; import org.infinispan.cdi.embedded.ConfigureCache; import org.infinispan.configuration.cache.Configuration; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.test.TestingUtil; import org.infinispan.test.fwk.TestCacheManagerFactory; /** * Creates a cache, based on some external mechanism. * * @author Pete Muir * @author Kevin Pollet &lt;kevin.pollet@serli.com&gt; (C) 2011 SERLI */ public class Config { /** * <p>Associates the "large" cache with qualifier "large"</p> * * Note that {@link Named} works as a string-based qualifier, so it is necessary to support also {@link ConfigureCache}. * * @see Named * @see ConfigureCache */ @Named("large") @ConfigureCache("large") @Produces public Configuration largeConfiguration = new ConfigurationBuilder().memory().size(10).build(); /** * The same as the above. The intention here is to check whether we can use 2 Configurations with <code>@Named</code> * annotations. */ @Named("super-large") @ConfigureCache("super-large") @Produces public Configuration superLargeConfiguration = new ConfigurationBuilder().memory().size(20).build(); /** * <p>Associates the "small" cache with the qualifier {@link Small}.</p> * * <p>The default configuration will be used.</p> */ @Small @ConfigureCache("small") @Produces @SuppressWarnings("unused") public Configuration smallConfiguration; /** * Overrides the default embedded cache manager. */ @Produces @ApplicationScoped @SuppressWarnings("unused") public EmbeddedCacheManager defaultCacheManager() { ConfigurationBuilder builder = new ConfigurationBuilder(); builder.memory().size(7); return TestCacheManagerFactory.createCacheManager(builder); } /** * Stops cache manager. * * @param cacheManager to be stopped */ @SuppressWarnings("unused") public void killCacheManager(@Disposes EmbeddedCacheManager cacheManager) { TestingUtil.killCacheManagers(cacheManager); } }
2,375
29.075949
123
java
null
infinispan-main/cdi/embedded/src/test/java/org/infinispan/cdi/embedded/test/cache/DefaultCacheTest.java
package org.infinispan.cdi.embedded.test.cache; import static org.infinispan.cdi.embedded.test.testutil.Deployments.baseDeployment; import static org.testng.Assert.assertEquals; import jakarta.inject.Inject; import org.infinispan.AdvancedCache; import org.infinispan.Cache; import org.infinispan.cdi.embedded.test.DefaultTestEmbeddedCacheManagerProducer; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.testng.Arquillian; import org.jboss.shrinkwrap.api.Archive; import org.testng.annotations.Test; /** * Tests that the default cache is available and can be injected with no configuration. * * @author Pete Muir * @author Kevin Pollet &lt;kevin.pollet@serli.com&gt; (C) 2011 SERLI */ @Test(groups = {"functional", "smoke"}, testName = "cdi.test.cache.embedded.DefaultCacheTest") public class DefaultCacheTest extends Arquillian { @Deployment public static Archive<?> deployment() { return baseDeployment() .addClass(DefaultCacheTest.class) .addClass(DefaultTestEmbeddedCacheManagerProducer.class); } @Inject private Cache<String, String> cache; @Inject private AdvancedCache<String, String> advancedCache; public void testDefaultCache() { // Simple test to make sure the default cache works cache.put("pete", "British"); cache.put("manik", "Sri Lankan"); assertEquals(cache.get("pete"), "British"); assertEquals(cache.get("manik"), "Sri Lankan"); assertEquals(cache.getName(), TestCacheManagerFactory.DEFAULT_CACHE_NAME); /* * Check that the advanced cache contains the same data as the simple * cache. As we can inject either Cache or AdvancedCache, this is double * checking that they both refer to the same underlying impl and Seam * Clouds isn't returning the wrong thing. */ assertEquals(advancedCache.get("pete"), "British"); assertEquals(advancedCache.get("manik"), "Sri Lankan"); assertEquals(advancedCache.getName(), TestCacheManagerFactory.DEFAULT_CACHE_NAME); } }
2,135
36.473684
94
java
null
infinispan-main/cdi/embedded/src/test/java/org/infinispan/cdi/embedded/test/cache/configured/ConfiguredCacheTest.java
package org.infinispan.cdi.embedded.test.cache.configured; import static org.testng.Assert.assertEquals; import jakarta.inject.Inject; import org.infinispan.AdvancedCache; import org.infinispan.cdi.embedded.test.DefaultTestEmbeddedCacheManagerProducer; import org.infinispan.cdi.embedded.test.testutil.Deployments; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.testng.Arquillian; import org.jboss.shrinkwrap.api.Archive; import org.testng.annotations.Test; /** * Tests that the simple form of configuration works. * * @author Pete Muir * @author Kevin Pollet &lt;kevin.pollet@serli.com&gt; (C) 2011 SERLI * @see Config */ @Test(groups = {"functional", "smoke"}, testName = "cdi.test.cache.embedded.configured.ConfiguredCacheTest") public class ConfiguredCacheTest extends Arquillian { @Deployment public static Archive<?> deployment() { return Deployments.baseDeployment() .addPackage(ConfiguredCacheTest.class.getPackage()) .addClass(DefaultTestEmbeddedCacheManagerProducer.class); } @Inject @Tiny private AdvancedCache<?, ?> tinyCache; @Inject @Small private AdvancedCache<?, ?> smallCache; public void testTinyCache() { // Check that we have the correctly configured cache assertEquals(tinyCache.getCacheConfiguration().memory().size(), 1); } public void testSmallCache() { // Check that we have the correctly configured cache assertEquals(smallCache.getCacheConfiguration().memory().size(), 10); } }
1,553
30.08
108
java
null
infinispan-main/cdi/embedded/src/test/java/org/infinispan/cdi/embedded/test/cache/configured/Tiny.java
package org.infinispan.cdi.embedded.test.cache.configured; import static java.lang.annotation.ElementType.FIELD; import static java.lang.annotation.ElementType.METHOD; import static java.lang.annotation.ElementType.PARAMETER; import static java.lang.annotation.ElementType.TYPE; import static java.lang.annotation.RetentionPolicy.RUNTIME; import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.Target; import jakarta.inject.Qualifier; /** * @author Kevin Pollet &lt;kevin.pollet@serli.com&gt; (C) 2011 SERLI */ @Qualifier @Target({TYPE, METHOD, PARAMETER, FIELD}) @Retention(RUNTIME) @Documented public @interface Tiny { }
682
26.32
69
java
null
infinispan-main/cdi/embedded/src/test/java/org/infinispan/cdi/embedded/test/cache/configured/Small.java
package org.infinispan.cdi.embedded.test.cache.configured; import static java.lang.annotation.ElementType.FIELD; import static java.lang.annotation.ElementType.METHOD; import static java.lang.annotation.ElementType.PARAMETER; import static java.lang.annotation.ElementType.TYPE; import static java.lang.annotation.RetentionPolicy.RUNTIME; import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.Target; import jakarta.inject.Qualifier; /** * @author Kevin Pollet &lt;kevin.pollet@serli.com&gt; (C) 2011 SERLI */ @Qualifier @Target({TYPE, METHOD, PARAMETER, FIELD}) @Retention(RUNTIME) @Documented public @interface Small { }
683
26.36
69
java
null
infinispan-main/cdi/embedded/src/test/java/org/infinispan/cdi/embedded/test/cache/configured/Config.java
package org.infinispan.cdi.embedded.test.cache.configured; import jakarta.enterprise.inject.Produces; import org.infinispan.cdi.embedded.ConfigureCache; import org.infinispan.configuration.cache.Configuration; import org.infinispan.configuration.cache.ConfigurationBuilder; /** * @author Kevin Pollet &lt;kevin.pollet@serli.com&gt; (C) 2011 SERLI */ public class Config { /** * <p>Configures a "tiny" cache (with a very low number of entries), and associates it with the qualifier {@link * Tiny}.</p> * * <p>This will use the default cache container.</p> */ @Tiny @ConfigureCache("tiny") @Produces public Configuration tinyConfiguration() { return new ConfigurationBuilder() .memory().size(1) .build(); } /** * <p>Configures a "small" cache (with a pretty low number of entries), and associates it with the qualifier {@link * Small}.</p> * * <p>This will use the default cache container.</p> */ @Small @ConfigureCache("small") @Produces public Configuration smallConfiguration() { return new ConfigurationBuilder() .memory().size(10) .build(); } }
1,190
26.697674
118
java
null
infinispan-main/cdi/embedded/src/test/java/org/infinispan/cdi/embedded/test/cache/specific/Large.java
package org.infinispan.cdi.embedded.test.cache.specific; import static java.lang.annotation.ElementType.FIELD; import static java.lang.annotation.ElementType.METHOD; import static java.lang.annotation.ElementType.PARAMETER; import static java.lang.annotation.ElementType.TYPE; import static java.lang.annotation.RetentionPolicy.RUNTIME; import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.Target; import jakarta.inject.Qualifier; /** * @author Kevin Pollet &lt;kevin.pollet@serli.com&gt; (C) 2011 SERLI */ @Qualifier @Target({TYPE, METHOD, PARAMETER, FIELD}) @Retention(RUNTIME) @Documented public @interface Large { }
681
26.28
69
java
null
infinispan-main/cdi/embedded/src/test/java/org/infinispan/cdi/embedded/test/cache/specific/SpecificCacheManagerTest.java
package org.infinispan.cdi.embedded.test.cache.specific; import static org.infinispan.cdi.embedded.test.testutil.Deployments.baseDeployment; import static org.testng.Assert.assertEquals; import static org.testng.AssertJUnit.assertFalse; import static org.testng.AssertJUnit.assertTrue; import jakarta.enterprise.inject.spi.BeanManager; import jakarta.inject.Inject; import org.infinispan.Cache; import org.infinispan.cdi.embedded.InfinispanExtensionEmbedded; import org.infinispan.cdi.embedded.test.DefaultTestEmbeddedCacheManagerProducer; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.testng.Arquillian; import org.jboss.shrinkwrap.api.Archive; import org.testng.annotations.Test; /** * Tests that a specific cache manager can be used for one or more caches. * * @author Kevin Pollet &lt;kevin.pollet@serli.com&gt; (C) 2011 SERLI * @see Config */ @Test(groups = "functional", testName = "cdi.test.cache.embedded.specific.SpecificCacheManagerTest") public class SpecificCacheManagerTest extends Arquillian { @Deployment public static Archive<?> deployment() { return baseDeployment() .addPackage(SpecificCacheManagerTest.class.getPackage()) .addClass(DefaultTestEmbeddedCacheManagerProducer.class); } @Inject private Cache<?, ?> cache; @Inject @Large private Cache<?, ?> largeCache; @Inject @Small private Cache<?, ?> smallCache; @Inject private InfinispanExtensionEmbedded infinispanExtension; @Inject private BeanManager beanManager; public void testCorrectCacheManagersRegistered() { assertEquals(infinispanExtension.getInstalledEmbeddedCacheManagers(beanManager).size(), 2); } public void testSpecificCacheManager() throws Exception { assertEquals(largeCache.getCacheConfiguration().memory().size(), 2000); assertEquals(largeCache.getCacheManager().getDefaultCacheConfiguration().memory().size(), 4000); assertEquals(smallCache.getCacheConfiguration().memory().size(), 20); assertEquals(smallCache.getCacheManager().getDefaultCacheConfiguration().memory().size(), 4000); // asserts that the small and large cache are defined in the same cache manager assertTrue(smallCache.getCacheManager().equals(largeCache.getCacheManager())); assertFalse(smallCache.getCacheManager().equals(cache.getCacheManager())); // check that the default configuration has not been modified assertEquals(cache.getCacheConfiguration().memory().size(), -1); } }
2,553
34.971831
102
java
null
infinispan-main/cdi/embedded/src/test/java/org/infinispan/cdi/embedded/test/cache/specific/Small.java
package org.infinispan.cdi.embedded.test.cache.specific; import static java.lang.annotation.ElementType.FIELD; import static java.lang.annotation.ElementType.METHOD; import static java.lang.annotation.ElementType.PARAMETER; import static java.lang.annotation.ElementType.TYPE; import static java.lang.annotation.RetentionPolicy.RUNTIME; import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.Target; import jakarta.inject.Qualifier; /** * @author Kevin Pollet &lt;kevin.pollet@serli.com&gt; (C) 2011 SERLI */ @Qualifier @Target({TYPE, METHOD, PARAMETER, FIELD}) @Retention(RUNTIME) @Documented public @interface Small { }
681
26.28
69
java
null
infinispan-main/cdi/embedded/src/test/java/org/infinispan/cdi/embedded/test/cache/specific/Config.java
package org.infinispan.cdi.embedded.test.cache.specific; import jakarta.enterprise.context.ApplicationScoped; import jakarta.enterprise.inject.Disposes; import jakarta.enterprise.inject.Produces; import org.infinispan.cdi.embedded.ConfigureCache; import org.infinispan.configuration.cache.Configuration; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.parsing.ConfigurationBuilderHolder; import org.infinispan.manager.DefaultCacheManager; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.test.TestingUtil; /** * @author Kevin Pollet &lt;kevin.pollet@serli.com&gt; (C) 2011 SERLI */ public class Config { /** * Associates the "large" cache with the qualifier {@link Large}. * * @param cacheManager the specific cache manager associated to this cache. This cache manager is used to get the * default cache configuration. */ @Large @ConfigureCache("large") @Produces @SuppressWarnings("unused") public Configuration largeConfiguration(@Large EmbeddedCacheManager cacheManager) { return new ConfigurationBuilder() .read(cacheManager.getDefaultCacheConfiguration()) .memory().size(2000) .build(); } /** * Associates the "small" cache with the qualifier {@link Small}. * * @param cacheManager the specific cache manager associated to this cache. This cache manager is used to get the * default cache configuration. */ @Small @ConfigureCache("small") @Produces @SuppressWarnings("unused") public Configuration smallConfiguration(@Small EmbeddedCacheManager cacheManager) { return new ConfigurationBuilder() .read(cacheManager.getDefaultCacheConfiguration()) .memory().size(20) .build(); } /** * Associates the "small" and "large" caches with this specific cache manager. */ @Large @Small @Produces @ApplicationScoped @SuppressWarnings("unused") public EmbeddedCacheManager specificCacheManager() { ConfigurationBuilderHolder holder = new ConfigurationBuilderHolder(); holder.getGlobalConfigurationBuilder().defaultCacheName("default"); ConfigurationBuilder builder = new ConfigurationBuilder(); builder.memory().size(4000); holder.getNamedConfigurationBuilders().put("default", builder); return new DefaultCacheManager(holder, true); } /** * Stops cache manager. * * @param cacheManager to be stopped */ @SuppressWarnings("unused") public void killCacheManager(@Disposes @Small @Large EmbeddedCacheManager cacheManager) { TestingUtil.killCacheManagers(cacheManager); } }
2,761
31.880952
116
java
null
infinispan-main/cdi/embedded/src/test/java/org/infinispan/cdi/embedded/test/util/ContractsTest.java
package org.infinispan.cdi.embedded.test.util; import org.infinispan.cdi.common.util.Contracts; import org.testng.annotations.Test; /** * @author Kevin Pollet &lt;kevin.pollet@serli.com&gt; (C) 2011 SERLI */ @Test(groups = "unit", testName = "cdi.test.util.ContractsTest") public class ContractsTest { @Test(expectedExceptions = NullPointerException.class, expectedExceptionsMessageRegExp = "This parameter cannot be null") public void testAssertNotNullOnNullParameter() { Contracts.assertNotNull(null, "This parameter cannot be null"); } public void testAssertNotNullOnNotNullParameter() { Contracts.assertNotNull("not null", "This parameter cannot be null"); } }
707
31.181818
75
java
null
infinispan-main/cdi/embedded/src/test/java/org/infinispan/cdi/embedded/test/assertions/ObserverAssertion.java
package org.infinispan.cdi.embedded.test.assertions; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertTrue; import java.util.List; import org.infinispan.cdi.embedded.test.event.CacheObserver; import org.infinispan.distribution.ch.ConsistentHash; import org.infinispan.notifications.cachelistener.event.CacheEntriesEvictedEvent; import org.infinispan.notifications.cachelistener.event.CacheEntryActivatedEvent; import org.infinispan.notifications.cachelistener.event.CacheEntryCreatedEvent; import org.infinispan.notifications.cachelistener.event.CacheEntryExpiredEvent; import org.infinispan.notifications.cachelistener.event.CacheEntryInvalidatedEvent; import org.infinispan.notifications.cachelistener.event.CacheEntryLoadedEvent; import org.infinispan.notifications.cachelistener.event.CacheEntryModifiedEvent; import org.infinispan.notifications.cachelistener.event.CacheEntryPassivatedEvent; import org.infinispan.notifications.cachelistener.event.CacheEntryRemovedEvent; import org.infinispan.notifications.cachelistener.event.CacheEntryVisitedEvent; import org.infinispan.notifications.cachelistener.event.DataRehashedEvent; import org.infinispan.notifications.cachelistener.event.TopologyChangedEvent; import org.infinispan.notifications.cachelistener.event.TransactionCompletedEvent; import org.infinispan.notifications.cachelistener.event.TransactionRegisteredEvent; import org.infinispan.notifications.cachemanagerlistener.event.CacheStartedEvent; import org.infinispan.notifications.cachemanagerlistener.event.CacheStoppedEvent; import org.infinispan.notifications.cachemanagerlistener.event.ViewChangedEvent; import org.infinispan.remoting.transport.Address; /** * Observer custom assertion. * * @author Sebastian Laskawiec */ public class ObserverAssertion { private CacheObserver observer; private Class<?> cacheAnnotation; private ObserverAssertion(CacheObserver observer, Class<?> cacheAnnotation) { this.cacheAnnotation = cacheAnnotation; this.observer = observer; } public static ObserverAssertion assertThat(CacheObserver observer, Class<?> cacheAnnotation) { return new ObserverAssertion(observer, cacheAnnotation); } private <T> List<T> getNonEmptyListOfEvents(Class<T> eventClass) { List<T> events = observer.getEventsMap().getEvents(cacheAnnotation, eventClass); assertTrue(events.size() > 0); return events; } public ObserverAssertion hasProperName(String cacheName) { assertEquals(getNonEmptyListOfEvents(CacheStartedEvent.class).get(0).getCacheName(), cacheName); return this; } public ObserverAssertion hasStartedEvent() { getNonEmptyListOfEvents(CacheStartedEvent.class); return this; } public ObserverAssertion hasStoppedEvent() { getNonEmptyListOfEvents(CacheStoppedEvent.class); return this; } public ObserverAssertion hasEntryCreatedEvent(String key) { assertEquals(getNonEmptyListOfEvents(CacheEntryCreatedEvent.class).get(0).getKey(), key); return this; } public ObserverAssertion hasEntryRemovedEvent(String key) { assertEquals(getNonEmptyListOfEvents(CacheEntryRemovedEvent.class).get(0).getKey(), key); return this; } public ObserverAssertion hasEntryActivatedEvent(String key) { assertEquals(getNonEmptyListOfEvents(CacheEntryActivatedEvent.class).get(0).getKey(), key); return this; } public ObserverAssertion hasEntriesEvictedEvent(String key) { assertTrue(getNonEmptyListOfEvents(CacheEntriesEvictedEvent.class).get(0).getEntries().containsKey(key)); return this; } public ObserverAssertion hasEntryExpiredEvent(String key) { assertEquals(getNonEmptyListOfEvents(CacheEntryExpiredEvent.class).get(0).getKey(), key); return this; } public ObserverAssertion hasEntryModifiedEvent(String key) { assertEquals(getNonEmptyListOfEvents(CacheEntryModifiedEvent.class).get(0).getKey(), key); return this; } public ObserverAssertion hasEntryInvalidatedEvent(String key) { assertEquals(getNonEmptyListOfEvents(CacheEntryInvalidatedEvent.class).get(0).getKey(), key); return this; } public ObserverAssertion hasEntryLoadedEvent(String key) { assertEquals(getNonEmptyListOfEvents(CacheEntryLoadedEvent.class).get(0).getKey(), key); return this; } public ObserverAssertion hasEntryPassivatedEvent(String key) { assertEquals(getNonEmptyListOfEvents(CacheEntryPassivatedEvent.class).get(0).getKey(), key); return this; } public ObserverAssertion hasEntryVisitedEvent(String key) { assertEquals(getNonEmptyListOfEvents(CacheEntryVisitedEvent.class).get(0).getKey(), key); return this; } public ObserverAssertion hasDataRehashEvent(ConsistentHash newHash) { assertEquals(getNonEmptyListOfEvents(DataRehashedEvent.class).get(0).getConsistentHashAtEnd(), newHash); return this; } public ObserverAssertion hasTransactionCompletedEvent(boolean isSuccesful) { assertEquals(getNonEmptyListOfEvents(TransactionCompletedEvent.class).get(0).isTransactionSuccessful(), isSuccesful); return this; } public ObserverAssertion hasTransactionRegisteredEvent(boolean isOriginLocal) { assertEquals(getNonEmptyListOfEvents(TransactionRegisteredEvent.class).get(0).isOriginLocal(), isOriginLocal); return this; } public ObserverAssertion hasViewChangedEvent(Address myAddress) { assertEquals(getNonEmptyListOfEvents(ViewChangedEvent.class).get(0).getLocalAddress(), myAddress); return this; } public ObserverAssertion hasTopologyChangedEvent(int topologyId) { assertEquals(getNonEmptyListOfEvents(TopologyChangedEvent.class).get(0).getNewTopologyId(), topologyId); return this; } }
5,836
39.534722
123
java
null
infinispan-main/cdi/embedded/src/test/java/org/infinispan/cdi/embedded/test/event/Cache1.java
package org.infinispan.cdi.embedded.test.event; import static java.lang.annotation.ElementType.FIELD; import static java.lang.annotation.ElementType.METHOD; import static java.lang.annotation.ElementType.PARAMETER; import static java.lang.annotation.ElementType.TYPE; import static java.lang.annotation.RetentionPolicy.RUNTIME; import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.Target; import jakarta.inject.Qualifier; /** * Qualifier for Cache1 * * @author Pete Muir * @author Sebastian Laskawiec */ @Qualifier @Target({TYPE, METHOD, PARAMETER, FIELD}) @Retention(RUNTIME) @Documented public @interface Cache1 { }
682
23.392857
59
java
null
infinispan-main/cdi/embedded/src/test/java/org/infinispan/cdi/embedded/test/event/CacheEventTest.java
package org.infinispan.cdi.embedded.test.event; import static org.infinispan.cdi.embedded.test.testutil.Deployments.baseDeployment; import static org.mockito.Mockito.mock; import java.util.Arrays; import jakarta.inject.Inject; import org.infinispan.AdvancedCache; import org.infinispan.cdi.embedded.test.DefaultTestEmbeddedCacheManagerProducer; import org.infinispan.cdi.embedded.test.assertions.ObserverAssertion; import org.infinispan.context.impl.NonTxInvocationContext; import org.infinispan.distribution.ch.ConsistentHash; import org.infinispan.notifications.cachelistener.CacheNotifier; import org.infinispan.notifications.cachemanagerlistener.CacheManagerNotifier; import org.infinispan.remoting.transport.Address; import org.infinispan.topology.CacheTopology; import org.infinispan.transaction.xa.GlobalTransaction; import org.infinispan.util.concurrent.CompletionStages; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.testng.Arquillian; import org.jboss.shrinkwrap.api.Archive; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; /** * Tests if event mechanism works correctly in Weld implementation (with Arquillian). * <p> * Note this class depends indirectly on configuration provided in {@link Config} * class. * </p> * * @author Pete Muir * @author Sebastian Laskawiec * @see Config */ @Test(groups = "functional", testName = "cdi.test.event.CacheEventTest") public class CacheEventTest extends Arquillian { private final NonTxInvocationContext invocationContext = new NonTxInvocationContext(null); @Inject @Cache1 private AdvancedCache<String, String> cache1; @Inject @Cache2 private AdvancedCache<String, String> cache2; @Inject private CacheObserver cacheObserver; private CacheNotifier<String, String> cache1Notifier; private CacheManagerNotifier cache1ManagerNotifier; @Deployment public static Archive<?> deployment() { return baseDeployment() .addPackage(CacheEventTest.class.getPackage()) .addClass(DefaultTestEmbeddedCacheManagerProducer.class); } @AfterMethod public void afterMethod() { cache1.clear(); cache2.clear(); cacheObserver.clear(); } @BeforeMethod public void beforeMethod() { cache1Notifier = cache1.getComponentRegistry().getComponent(CacheNotifier.class); cache1ManagerNotifier = cache1.getComponentRegistry().getComponent(CacheManagerNotifier.class); } public void testFiringStartedEventOnNewlyStartedCache() throws Exception { //when cache1.stop(); cache1.start(); //then ObserverAssertion.assertThat(cacheObserver, Cache1.class).hasProperName("cache1").hasStartedEvent(); } public void testFiringStoppedEventWhenStoppingCache() throws Exception { //when cache1.stop(); cache1.start(); //then ObserverAssertion.assertThat(cacheObserver, Cache1.class).hasProperName("cache1").hasStoppedEvent(); } public void testFiringEntryCreatedEventWhenPuttingDataIntoCache() throws Exception { //when cache1.put("pete", "Edinburgh"); //then ObserverAssertion.assertThat(cacheObserver, Cache1.class).hasEntryCreatedEvent("pete"); } public void testFiringEntryRemovedEventWhenRemovingDataFromCache() throws Exception { //given cache1.put("pete", "Edinburgh"); //when cache1.remove("pete"); //then ObserverAssertion.assertThat(cacheObserver, Cache1.class).hasEntryRemovedEvent("pete"); } public void testFiringEntryActivatedEventWhenUsingCacheNotifier() throws Exception { //when CompletionStages.join(cache1Notifier.notifyCacheEntryActivated("pete", "Edinburgh", true, invocationContext, null)); //then ObserverAssertion.assertThat(cacheObserver, Cache1.class).hasEntryActivatedEvent("pete"); } public void testFiringEntriesEvictedWhenEvictingDataInCache() throws Exception { //given cache1.put("pete", "Edinburgh"); //when cache1.evict("pete"); //then ObserverAssertion.assertThat(cacheObserver, Cache1.class).hasEntriesEvictedEvent("pete"); } public void testFiringEntryEvictedWhenEvictingDataInCache() throws Exception { //given cache1.put("pete", "Edinburgh"); //when cache1.evict("pete"); //then ObserverAssertion.assertThat(cacheObserver, Cache1.class).hasEntriesEvictedEvent("pete"); } public void testFiringEntryModifiedEventWhenModifyingEntryInCache() throws Exception { //given cache1.put("pete", "Edinburgh"); //when cache1.put("pete", "Edinburgh2"); //then ObserverAssertion.assertThat(cacheObserver, Cache1.class).hasEntryModifiedEvent("pete"); } public void testFiringEntryInvalidatedWhenUsingCacheNotifier() throws Exception { //when CompletionStages.join(cache1Notifier.notifyCacheEntryInvalidated("pete", "Edinburgh", null, true, invocationContext, null)); //then ObserverAssertion.assertThat(cacheObserver, Cache1.class).hasEntryInvalidatedEvent("pete"); } public void testFiringEntryLoadedWhenUsingCacheNotifier() throws Exception { //when CompletionStages.join(cache1Notifier.notifyCacheEntryLoaded("pete", "Edinburgh", true, invocationContext, null)); //then ObserverAssertion.assertThat(cacheObserver, Cache1.class).hasEntryLoadedEvent("pete"); } public void testFiringEntryPassivatedWhenUsingCacheNotifier() throws Exception { //when CompletionStages.join(cache1Notifier.notifyCacheEntryPassivated("pete", "Edinburgh", true, invocationContext, null)); //then ObserverAssertion.assertThat(cacheObserver, Cache1.class).hasEntryPassivatedEvent("pete"); } public void testFiringEntryVisitedWhenUsingCacheNotifier() throws Exception { //when CompletionStages.join(cache1Notifier.notifyCacheEntryVisited("pete", "Edinburgh", true, invocationContext, null)); //then ObserverAssertion.assertThat(cacheObserver, Cache1.class).hasEntryVisitedEvent("pete"); } public void testFiringDataRehashedWhenUsingCacheNotifier() throws Exception { //given ConsistentHash mockOldHash = mock(ConsistentHash.class); ConsistentHash mockNewHash = mock(ConsistentHash.class); ConsistentHash mockUnionHash = mock(ConsistentHash.class); //when CompletionStages.join(cache1Notifier.notifyDataRehashed(mockOldHash, mockNewHash, mockUnionHash, 0, true)); //then ObserverAssertion.assertThat(cacheObserver, Cache1.class).hasDataRehashEvent(mockNewHash); } public void testFiringTransactionCompletedWhenUsingCacheNotifier() throws Exception { //given GlobalTransaction mockGlobalTransaction = mock(GlobalTransaction.class); //when CompletionStages.join(cache1Notifier.notifyTransactionCompleted(mockGlobalTransaction, true, invocationContext)); //then ObserverAssertion.assertThat(cacheObserver, Cache1.class).hasTransactionCompletedEvent(true); } public void testFiringTransactionRegisteredWhenUsingCacheNotifier() throws Exception { //given GlobalTransaction mockGlobalTransaction = mock(GlobalTransaction.class); //when CompletionStages.join(cache1Notifier.notifyTransactionRegistered(mockGlobalTransaction, true)); //then ObserverAssertion.assertThat(cacheObserver, Cache1.class).hasTransactionRegisteredEvent(true); } public void testFiringViewChangedWhenUsingCacheManagerNotifier() throws Exception { //given Address mockMyAddress = mock(Address.class); //when CompletionStages.join(cache1ManagerNotifier.notifyViewChange(Arrays.asList(mockMyAddress), Arrays.asList(mockMyAddress), mockMyAddress, 0)); //then ObserverAssertion.assertThat(cacheObserver, Cache1.class).hasViewChangedEvent(mockMyAddress); } public void testFiringTopologyChangedWhenUsingCacheManagerNotifier() throws Exception { //given CacheTopology mockCacheTopology = mock(CacheTopology.class); //when CompletionStages.join(cache1Notifier.notifyTopologyChanged(mockCacheTopology, mockCacheTopology, 0, true)); //then ObserverAssertion.assertThat(cacheObserver, Cache1.class).hasTopologyChangedEvent(0); } public void testSendingEventToProperEventObservers() throws Exception { //given cache1.put("cache1", "for cache1"); cache2.put("cache2", "for cache2"); //when cache1.remove("cache1"); //then ObserverAssertion.assertThat(cacheObserver, Cache1.class).hasEntryCreatedEvent("cache1").hasEntryRemovedEvent("cache1"); ObserverAssertion.assertThat(cacheObserver, Cache2.class).hasEntryCreatedEvent("cache2"); } }
8,902
33.374517
146
java
null
infinispan-main/cdi/embedded/src/test/java/org/infinispan/cdi/embedded/test/event/CacheEventHolder.java
package org.infinispan.cdi.embedded.test.event; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.infinispan.notifications.cachemanagerlistener.event.Event; /** * Collects all events from observer and allows to extract them. * * @author Sebastian Laskawiec */ public class CacheEventHolder { /** * Main data structure of this event holder. * <p> * From top to bottom: * <ul> * <li><code>Map<Class, Map></code> - holds Cache annotation as keys and event map as value</li> * <li><code>Map<Class, List></code> - holds Event class as keys and a list of occurred event as value</li> * <li><code>List</code> - holds list of occurred events</li> * </ul> * </p> */ private Map<Class<?>, Map<Class<?>, List<Object>>> eventMap = new HashMap<>(); private void addEventClass(Class<?> cacheAnnotationClass, Class<?> eventClass) { if(!eventMap.containsKey(cacheAnnotationClass)) { eventMap.put(cacheAnnotationClass, new HashMap<>()); } if(!eventMap.get(cacheAnnotationClass).containsKey(eventClass)) { eventMap.get(cacheAnnotationClass).put(eventClass, new ArrayList<>()); } } /** * Adds event to this holder. * * @param cacheAnnotationClass CDI Cache qualifier annotation (like <code>@Cache1</code>). * @param eventStaticClass Event static class information (event have generic type information). * @param event Event itself. * @param <T> Generic information about event type. */ public synchronized <T extends org.infinispan.notifications.cachelistener.event.Event> void addEvent (Class<?> cacheAnnotationClass, Class<T> eventStaticClass, T event) { addEventClass(cacheAnnotationClass, eventStaticClass); eventMap.get(cacheAnnotationClass).get(eventStaticClass).add(event); } /** * Adds event to this holder. * * @param cacheAnnotationClass CDI Cache qualifier annotation (like <code>@Cache1</code>). * @param eventStaticClass Event static class information (event have generic type information). * @param event Event itself. * @param <T> Generic information about event type. */ public synchronized <T extends Event> void addEvent(Class<?> cacheAnnotationClass, Class<T> eventStaticClass, T event) { addEventClass(cacheAnnotationClass,eventStaticClass); eventMap.get(cacheAnnotationClass).get(eventStaticClass).add(event); } public synchronized void clear() { eventMap.clear(); } /** * Gets all events based on Cache annotation and class of events. * * @param cacheAnnotationClass CDI Cache qualifier annotation (like <code>@Cache1</code>). * @param eventClass Event class. * @param <T> Generic information about event type. * @return List of events occurred. Empty list if there was no events. */ public synchronized <T> List<T> getEvents(Class<?> cacheAnnotationClass, Class<T> eventClass) { ArrayList<T> toBeReturned = new ArrayList<>(); Map<Class<?>, List<Object>> eventsMapForGivenCache = eventMap.get(cacheAnnotationClass); if(eventsMapForGivenCache == null) { return toBeReturned; } List<Object> events = eventsMapForGivenCache.get(eventClass); if(events != null) { for (Object event : events) { toBeReturned.add(eventClass.cast(event)); } } return toBeReturned; } }
3,500
36.645161
123
java
null
infinispan-main/cdi/embedded/src/test/java/org/infinispan/cdi/embedded/test/event/Cache2.java
package org.infinispan.cdi.embedded.test.event; import static java.lang.annotation.ElementType.FIELD; import static java.lang.annotation.ElementType.METHOD; import static java.lang.annotation.ElementType.PARAMETER; import static java.lang.annotation.ElementType.TYPE; import static java.lang.annotation.RetentionPolicy.RUNTIME; import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.Target; import jakarta.inject.Qualifier; /** * Qualifier for Cache2 * * @author Pete Muir * @author Sebastian Laskawiec */ @Qualifier @Target({TYPE, METHOD, PARAMETER, FIELD}) @Retention(RUNTIME) @Documented public @interface Cache2 { }
682
23.392857
59
java
null
infinispan-main/cdi/embedded/src/test/java/org/infinispan/cdi/embedded/test/event/CacheObserver.java
package org.infinispan.cdi.embedded.test.event; import jakarta.enterprise.context.ApplicationScoped; import jakarta.enterprise.event.Observes; import org.infinispan.notifications.cachelistener.event.CacheEntriesEvictedEvent; import org.infinispan.notifications.cachelistener.event.CacheEntryActivatedEvent; import org.infinispan.notifications.cachelistener.event.CacheEntryCreatedEvent; import org.infinispan.notifications.cachelistener.event.CacheEntryExpiredEvent; import org.infinispan.notifications.cachelistener.event.CacheEntryInvalidatedEvent; import org.infinispan.notifications.cachelistener.event.CacheEntryLoadedEvent; import org.infinispan.notifications.cachelistener.event.CacheEntryModifiedEvent; import org.infinispan.notifications.cachelistener.event.CacheEntryPassivatedEvent; import org.infinispan.notifications.cachelistener.event.CacheEntryRemovedEvent; import org.infinispan.notifications.cachelistener.event.CacheEntryVisitedEvent; import org.infinispan.notifications.cachelistener.event.DataRehashedEvent; import org.infinispan.notifications.cachelistener.event.TopologyChangedEvent; import org.infinispan.notifications.cachelistener.event.TransactionCompletedEvent; import org.infinispan.notifications.cachelistener.event.TransactionRegisteredEvent; import org.infinispan.notifications.cachemanagerlistener.event.CacheStartedEvent; import org.infinispan.notifications.cachemanagerlistener.event.CacheStoppedEvent; import org.infinispan.notifications.cachemanagerlistener.event.ViewChangedEvent; /** * {@link Cache1} and {@link Cache2} events observer. * * @author Pete Muir * @author Sebastian Laskawiec * @see Cache1 * @see Cache2 */ @ApplicationScoped public class CacheObserver { private CacheEventHolder eventsMap = new CacheEventHolder(); private void observeCache1CacheStatedEvent(@Observes @Cache1 CacheStartedEvent event) { eventsMap.addEvent(Cache1.class, CacheStartedEvent.class, event); } private void observeCache2CacheStatedEvent(@Observes @Cache2 CacheStartedEvent event) { eventsMap.addEvent(Cache2.class, CacheStartedEvent.class, event); } private void observeCache1CacheEntryCreatedEvent(@Observes @Cache1 CacheEntryCreatedEvent event) { eventsMap.addEvent(Cache1.class, CacheEntryCreatedEvent.class, event); } private void observeCache2CacheEntryCreatedEvent(@Observes @Cache2 CacheEntryCreatedEvent event) { eventsMap.addEvent(Cache2.class, CacheEntryCreatedEvent.class, event); } private void observeCache1CacheEntryRemovedEvent(@Observes @Cache1 CacheEntryRemovedEvent event) { eventsMap.addEvent(Cache1.class, CacheEntryRemovedEvent.class, event); } private void observeCache2CacheEntryRemovedEvent(@Observes @Cache2 CacheEntryRemovedEvent event) { eventsMap.addEvent(Cache2.class, CacheEntryRemovedEvent.class, event); } private void observeCache1CacheEntryActivatedEvent(@Observes @Cache1 CacheEntryActivatedEvent event) { eventsMap.addEvent(Cache1.class, CacheEntryActivatedEvent.class, event); } private void observeCache2CacheEntryActivatedEvent(@Observes @Cache2 CacheEntryActivatedEvent event) { eventsMap.addEvent(Cache2.class, CacheEntryActivatedEvent.class, event); } private void observeCache1CacheEntriesEvictedEvent(@Observes @Cache1 CacheEntriesEvictedEvent event) { eventsMap.addEvent(Cache1.class, CacheEntriesEvictedEvent.class, event); } private void observeCache2CacheEntriesEvictedEvent(@Observes @Cache2 CacheEntriesEvictedEvent event) { eventsMap.addEvent(Cache2.class, CacheEntriesEvictedEvent.class, event); } private void observeCache1CacheEntryModifiedEvent(@Observes @Cache1 CacheEntryModifiedEvent event) { eventsMap.addEvent(Cache1.class, CacheEntryModifiedEvent.class, event); } private void observeCache2CacheEntryModifiedEvent(@Observes @Cache2 CacheEntryModifiedEvent event) { eventsMap.addEvent(Cache2.class, CacheEntryModifiedEvent.class, event); } private void observeCache1CacheEntryInvalidatedEvent(@Observes @Cache1 CacheEntryInvalidatedEvent event) { eventsMap.addEvent(Cache1.class, CacheEntryInvalidatedEvent.class, event); } private void observeCache2CacheEntryInvalidatedEvent(@Observes @Cache2 CacheEntryInvalidatedEvent event) { eventsMap.addEvent(Cache2.class, CacheEntryInvalidatedEvent.class, event); } private void observeCache1CacheEntryLoadedEvent(@Observes @Cache1 CacheEntryLoadedEvent event) { eventsMap.addEvent(Cache1.class, CacheEntryLoadedEvent.class, event); } private void observeCache2CacheEntryLoadedEvent(@Observes @Cache2 CacheEntryLoadedEvent event) { eventsMap.addEvent(Cache2.class, CacheEntryLoadedEvent.class, event); } private void observeCache1CacheEntryPassivatedEvent(@Observes @Cache1 CacheEntryPassivatedEvent event) { eventsMap.addEvent(Cache1.class, CacheEntryPassivatedEvent.class, event); } private void observeCache2CacheEntryPassivatedEvent(@Observes @Cache2 CacheEntryPassivatedEvent event) { eventsMap.addEvent(Cache2.class, CacheEntryPassivatedEvent.class, event); } private void observeCache1CacheEntryVisitedEvent(@Observes @Cache1 CacheEntryVisitedEvent event) { eventsMap.addEvent(Cache1.class, CacheEntryVisitedEvent.class, event); } private void observeCache2CacheEntryVisitedEvent(@Observes @Cache2 CacheEntryVisitedEvent event) { eventsMap.addEvent(Cache2.class, CacheEntryVisitedEvent.class, event); } private void observeCache1DataRehashEvent(@Observes @Cache1 DataRehashedEvent event) { eventsMap.addEvent(Cache1.class, DataRehashedEvent.class, event); } private void observeCache2DataRehashEvent(@Observes @Cache2 DataRehashedEvent event) { eventsMap.addEvent(Cache1.class, DataRehashedEvent.class, event); } private void observeCache1CacheStoppedEvent(@Observes @Cache1 CacheStoppedEvent event) { eventsMap.addEvent(Cache1.class, CacheStoppedEvent.class, event); } private void observeCache2CacheStoppedEvent(@Observes @Cache2 CacheStoppedEvent event) { eventsMap.addEvent(Cache2.class, CacheStoppedEvent.class, event); } private void observeCache1TransactionCompletedEvent(@Observes @Cache1 TransactionCompletedEvent event) { eventsMap.addEvent(Cache1.class, TransactionCompletedEvent.class, event); } private void observeCache2TransactionCompletedEvent(@Observes @Cache2 TransactionCompletedEvent event) { eventsMap.addEvent(Cache2.class, TransactionCompletedEvent.class, event); } private void observeCache1TransactionRegisteredEvent(@Observes @Cache1 TransactionRegisteredEvent event) { eventsMap.addEvent(Cache1.class, TransactionRegisteredEvent.class, event); } private void observeCache2TransactionRegisteredEvent(@Observes @Cache2 TransactionRegisteredEvent event) { eventsMap.addEvent(Cache2.class, TransactionRegisteredEvent.class, event); } private void observeCache1ViewChangedEvent(@Observes @Cache1 ViewChangedEvent event) { eventsMap.addEvent(Cache1.class, ViewChangedEvent.class, event); } private void observeCache2ViewChangedEvent(@Observes @Cache2 ViewChangedEvent event) { eventsMap.addEvent(Cache2.class, ViewChangedEvent.class, event); } private void observeCache1TopologyChangedEvent(@Observes @Cache1 TopologyChangedEvent event) { eventsMap.addEvent(Cache1.class, TopologyChangedEvent.class, event); } private void observeCache2TopologyChangedEvent(@Observes @Cache2 TopologyChangedEvent event) { eventsMap.addEvent(Cache2.class, TopologyChangedEvent.class, event); } private void observeCache1CacheEntryExpiredEvent(@Observes @Cache1 CacheEntryExpiredEvent event) { eventsMap.addEvent(Cache1.class, CacheEntryExpiredEvent.class, event); } private void observeCache2CacheEntryExpiredEvent(@Observes @Cache2 CacheEntryExpiredEvent event) { eventsMap.addEvent(Cache2.class, CacheEntryExpiredEvent.class, event); } /** * @return Gets events map */ public CacheEventHolder getEventsMap() { return eventsMap; } /** * Clears all event from events map. */ public void clear() { eventsMap.clear(); } }
8,266
43.208556
109
java
null
infinispan-main/cdi/embedded/src/test/java/org/infinispan/cdi/embedded/test/event/Config.java
package org.infinispan.cdi.embedded.test.event; import jakarta.enterprise.inject.Produces; import org.infinispan.cdi.embedded.ConfigureCache; import org.infinispan.configuration.cache.Configuration; /** * Configures two default caches - we will use both caches to check that events for one don't spill over to the other. * * @author Pete Muir * @author Kevin Pollet &lt;kevin.pollet@serli.com&gt; (C) 2011 SERLI */ public class Config { /** * <p>Associates the "cache1" cache with the qualifier {@link Cache1}.</p> * * <p>The default configuration will be used.</p> */ @Cache1 @ConfigureCache("cache1") @Produces public Configuration cache1Configuration; /** * <p>Associates the "cache2" cache with the qualifier {@link Cache2}.</p> * * <p>The default configuration will be used.</p> */ @Cache2 @ConfigureCache("cache2") @Produces public Configuration cache2Configuration; }
946
26.057143
118
java
null
infinispan-main/cdi/embedded/src/test/java/org/infinispan/cdi/embedded/test/testutil/Deployments.java
package org.infinispan.cdi.embedded.test.testutil; import org.infinispan.cdi.embedded.ConfigureCache; import org.infinispan.cdi.embedded.event.AbstractEventBridge; import org.infinispan.cdi.embedded.event.cache.CacheEventBridge; import org.infinispan.cdi.embedded.event.cachemanager.CacheManagerEventBridge; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.jboss.shrinkwrap.api.spec.WebArchive; /** * Arquillian deployment utility class. * * @author Kevin Pollet &lt;kevin.pollet@serli.com&gt; (C) 2011 SERLI */ public final class Deployments { /** * The base deployment web archive. The CDI extension is packaged as an individual jar. */ public static WebArchive baseDeployment() { return ShrinkWrap.create(WebArchive.class, "test.war") .addAsWebInfResource(Deployments.class.getResource("/META-INF/beans.xml"), "beans.xml") .addAsLibrary( ShrinkWrap.create(JavaArchive.class, "infinispan-cdi-embedded.jar") .addPackage(ConfigureCache.class.getPackage()) .addPackage(AbstractEventBridge.class.getPackage()) .addPackage(CacheEventBridge.class.getPackage()) .addPackage(CacheManagerEventBridge.class.getPackage()) .addAsManifestResource(ConfigureCache.class.getResource("/META-INF/beans.xml"), "beans.xml") .addAsManifestResource(ConfigureCache.class.getResource("/META-INF/services/jakarta.enterprise.inject.spi.Extension"), "services/jakarta.enterprise.inject.spi.Extension") ); } }
1,667
48.058824
194
java
null
infinispan-main/cdi/embedded/src/main/java/org/infinispan/cdi/embedded/ConfigureCache.java
package org.infinispan.cdi.embedded; import static java.lang.annotation.ElementType.FIELD; import static java.lang.annotation.ElementType.METHOD; import static java.lang.annotation.ElementType.PARAMETER; import static java.lang.annotation.ElementType.TYPE; import static java.lang.annotation.RetentionPolicy.RUNTIME; import java.lang.annotation.Retention; import java.lang.annotation.Target; /** * This annotation is used to define a cache {@link Configuration}. * * @author Pete Muir * @author Kevin Pollet &lt;kevin.pollet@serli.com&gt; (C) 2011 SERLI */ @Retention(RUNTIME) @Target({METHOD, FIELD, PARAMETER, TYPE}) public @interface ConfigureCache { /** * The name of the cache to configure. If no value is provided the configured cache is the default one. */ String value() default ""; }
815
30.384615
106
java
null
infinispan-main/cdi/embedded/src/main/java/org/infinispan/cdi/embedded/InfinispanExtensionEmbedded.java
package org.infinispan.cdi.embedded; import java.lang.annotation.Annotation; import java.util.HashSet; import java.util.Set; import jakarta.enterprise.context.ApplicationScoped; import jakarta.enterprise.context.Dependent; import jakarta.enterprise.context.spi.CreationalContext; import jakarta.enterprise.event.Observes; import jakarta.enterprise.inject.Instance; import jakarta.enterprise.inject.spi.AfterBeanDiscovery; import jakarta.enterprise.inject.spi.Bean; import jakarta.enterprise.inject.spi.BeanManager; import jakarta.enterprise.inject.spi.Extension; import jakarta.enterprise.inject.spi.ProcessBean; import jakarta.enterprise.inject.spi.ProcessProducer; import jakarta.enterprise.inject.spi.Producer; import jakarta.enterprise.util.TypeLiteral; import org.infinispan.AdvancedCache; import org.infinispan.Cache; import org.infinispan.cdi.common.util.AnyLiteral; import org.infinispan.cdi.common.util.Arrays2; import org.infinispan.cdi.common.util.BeanBuilder; import org.infinispan.cdi.common.util.Beans; import org.infinispan.cdi.common.util.ContextualLifecycle; import org.infinispan.cdi.common.util.ContextualReference; import org.infinispan.cdi.common.util.DefaultLiteral; import org.infinispan.cdi.common.util.Reflections; import org.infinispan.cdi.embedded.event.cachemanager.CacheManagerEventBridge; import org.infinispan.cdi.embedded.util.logging.EmbeddedLog; import org.infinispan.commons.logging.LogFactory; import org.infinispan.configuration.cache.Configuration; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.parsing.ConfigurationBuilderHolder; import org.infinispan.manager.DefaultCacheManager; import org.infinispan.manager.EmbeddedCacheManager; /** * The Infinispan CDI extension for embedded caches * * @author Pete Muir * @author Kevin Pollet &lt;kevin.pollet@serli.com&gt; (C) 2011 SERLI */ public class InfinispanExtensionEmbedded implements Extension { private static final String CACHE_NAME = "CDIExtensionDefaultCacheManager"; private static final EmbeddedLog LOGGER = LogFactory.getLog(InfinispanExtensionEmbedded.class, EmbeddedLog.class); private final Set<ConfigurationHolder> configurations; private volatile boolean registered = false; private final Object registerLock = new Object(); private final Set<Set<Annotation>> installedEmbeddedCacheManagers = new HashSet<>(); public InfinispanExtensionEmbedded() { new ConfigurationBuilder(); // Attempt to initialize a core class this.configurations = new HashSet<>(); } @SuppressWarnings("unchecked") void observeConfigurationProducers(@Observes ProcessProducer<?, Configuration> event, BeanManager beanManager) { final ConfigureCache annotation = event.getAnnotatedMember().getAnnotation(ConfigureCache.class); String configurationName = ""; if (annotation != null) { configurationName = annotation.value(); } configurations.add(new ConfigurationHolder(event.getProducer(), configurationName, Reflections.getQualifiers(beanManager, event.getAnnotatedMember().getAnnotations()))); } public void observeEmbeddedCacheManagerBean(@Observes ProcessBean<?> processBean) { if (processBean.getBean().getTypes().contains(EmbeddedCacheManager.class)) { installedEmbeddedCacheManagers.add(processBean.getBean().getQualifiers()); } } @SuppressWarnings("unchecked") <T, X> void registerBeans(@Observes AfterBeanDiscovery event, final BeanManager beanManager) { if (beanManager.getBeans(Configuration.class).isEmpty()) { LOGGER.addDefaultEmbeddedConfiguration(); final Configuration defaultConfiguration = new ConfigurationBuilder().build(); // Must be added after AdvancedCache producer registration - see also AdvancedCacheProducer.getDefaultAdvancedCache() configurations.add(new ConfigurationHolder(defaultConfiguration, "", defaultQualifiers())); event.addBean(createDefaultEmbeddedConfigurationBean(beanManager, defaultConfiguration)); } for (final ConfigurationHolder holder : configurations) { // register a AdvancedCache producer for each configuration Bean<?> advancedCacheBean = new BeanBuilder(beanManager) .readFromType(beanManager.createAnnotatedType(AdvancedCache.class)) .qualifiers(Beans.buildQualifiers(holder.getQualifiers())) .addType(new TypeLiteral<AdvancedCache<T, X>>() {}.getType()) .addType(new TypeLiteral<Cache<T, X>>() {}.getType()) .passivationCapable(true) .id(InfinispanExtensionEmbedded.class.getSimpleName() + "#" + AdvancedCache.class.getSimpleName() + "#" + Cache.class.getSimpleName()) .beanLifecycle(new ContextualLifecycle<AdvancedCache<?, ?>>() { @Override public AdvancedCache<?, ?> create(Bean<AdvancedCache<?, ?>> bean, CreationalContext<AdvancedCache<?, ?>> creationalContext) { return new ContextualReference<AdvancedCacheProducer>(beanManager, AdvancedCacheProducer.class).create(Reflections.cast(creationalContext)).get().getAdvancedCache(holder.getName(), holder.getQualifiers()); } }).create(); event.addBean(advancedCacheBean); } if (beanManager.getBeans(EmbeddedCacheManager.class).isEmpty()) { LOGGER.addDefaultEmbeddedCacheManager(); event.addBean(createDefaultEmbeddedCacheManagerBean(beanManager)); } } public Set<InstalledCacheManager> getInstalledEmbeddedCacheManagers(BeanManager beanManager) { Set<InstalledCacheManager> installedCacheManagers = new HashSet<>(); for (Set<Annotation> qualifiers : installedEmbeddedCacheManagers) { Bean<?> b = beanManager.resolve(beanManager.getBeans(EmbeddedCacheManager.class, qualifiers.toArray(Reflections.EMPTY_ANNOTATION_ARRAY))); EmbeddedCacheManager cm = (EmbeddedCacheManager) beanManager.getReference(b, EmbeddedCacheManager.class, beanManager.createCreationalContext(b)); installedCacheManagers.add(new InstalledCacheManager(cm, qualifiers.contains(DefaultLiteral.INSTANCE))); } return installedCacheManagers; } public void registerCacheConfigurations(CacheManagerEventBridge eventBridge, Instance<EmbeddedCacheManager> cacheManagers, BeanManager beanManager) { if (!registered) { synchronized (registerLock) { if (!registered) { final CreationalContext<Configuration> ctx = beanManager.createCreationalContext(null); final EmbeddedCacheManager defaultCacheManager = cacheManagers.select(DefaultLiteral.INSTANCE).get(); for (ConfigurationHolder holder : configurations) { final String cacheName = holder.getName(); final Configuration cacheConfiguration = holder.getConfiguration(ctx); final Set<Annotation> cacheQualifiers = holder.getQualifiers(); // if a specific cache manager is defined for this cache we use it final Instance<EmbeddedCacheManager> specificCacheManager = cacheManagers.select(cacheQualifiers.toArray(new Annotation[cacheQualifiers.size()])); final EmbeddedCacheManager cacheManager = specificCacheManager.isUnsatisfied() ? defaultCacheManager : specificCacheManager.get(); // the default configuration is registered by the default cache manager producer if (!cacheName.trim().isEmpty()) { if (cacheConfiguration != null) { cacheManager.defineConfiguration(cacheName, cacheConfiguration); LOGGER.cacheConfigurationDefined(cacheName, cacheManager); } else if (!cacheManager.getCacheNames().contains(cacheName)) { cacheManager.defineConfiguration(cacheName, cacheManager.getDefaultCacheConfiguration()); LOGGER.cacheConfigurationDefined(cacheName, cacheManager); } } // register cache manager observers eventBridge.registerObservers(cacheQualifiers, cacheName, cacheManager); } // only set registered to true at the end to keep other threads waiting until we have finished registration registered = true; } } } } /** * The default embedded cache configuration can be overridden by creating a producer which * produces the new default configuration. The configuration produced must have the scope * {@linkplain jakarta.enterprise.context.Dependent Dependent} and the * {@linkplain jakarta.enterprise.inject.Default Default} qualifier. * * @param beanManager * @return a custom bean */ private Bean<Configuration> createDefaultEmbeddedConfigurationBean(BeanManager beanManager, final Configuration configuration) { return new BeanBuilder<Configuration>(beanManager).beanClass(InfinispanExtensionEmbedded.class) .addTypes(Object.class, Configuration.class) .scope(Dependent.class) .qualifiers(defaultQualifiers()) .passivationCapable(true) .id(InfinispanExtensionEmbedded.class.getSimpleName() + "#" + Configuration.class.getSimpleName()) .beanLifecycle(new ContextualLifecycle<Configuration>() { @Override public Configuration create(Bean<Configuration> bean, CreationalContext<Configuration> creationalContext) { return configuration; } }).create(); } /** * The default cache manager is an instance of {@link DefaultCacheManager} initialized with the * default configuration (either produced by * {@link #createDefaultEmbeddedConfigurationBean(BeanManager, Configuration)} or provided by user). The default * cache manager can be overridden by creating a producer which produces the new default cache * manager. The cache manager produced must have the scope {@link ApplicationScoped} and the * {@linkplain jakarta.enterprise.inject.Default Default} qualifier. * * @param beanManager * @return a custom bean */ private Bean<EmbeddedCacheManager> createDefaultEmbeddedCacheManagerBean(BeanManager beanManager) { return new BeanBuilder<EmbeddedCacheManager>(beanManager).beanClass(InfinispanExtensionEmbedded.class) .addTypes(Object.class, EmbeddedCacheManager.class) .scope(ApplicationScoped.class) .qualifiers(defaultQualifiers()) .passivationCapable(true) .id(InfinispanExtensionEmbedded.class.getSimpleName() + "#" + EmbeddedCacheManager.class.getSimpleName()) .beanLifecycle(new ContextualLifecycle<EmbeddedCacheManager>() { @Override public EmbeddedCacheManager create(Bean<EmbeddedCacheManager> bean, CreationalContext<EmbeddedCacheManager> creationalContext) { ConfigurationBuilderHolder holder = new ConfigurationBuilderHolder(); holder.getGlobalConfigurationBuilder().cacheManagerName(CACHE_NAME).defaultCacheName("default"); @SuppressWarnings("unchecked") Bean<Configuration> configurationBean = (Bean<Configuration>) beanManager .resolve(beanManager.getBeans(Configuration.class)); Configuration defaultConfiguration = (Configuration) beanManager.getReference(configurationBean, Configuration.class, beanManager.createCreationalContext(configurationBean)); ConfigurationBuilder builder = new ConfigurationBuilder(); builder.read(defaultConfiguration); holder.getNamedConfigurationBuilders().put("default", builder); return new DefaultCacheManager(holder, true); } @Override public void destroy(Bean<EmbeddedCacheManager> bean, EmbeddedCacheManager instance, CreationalContext<EmbeddedCacheManager> creationalContext) { instance.stop(); } }).create(); } private Set<Annotation> defaultQualifiers() { return Arrays2.asSet(DefaultLiteral.INSTANCE, AnyLiteral.INSTANCE); } static class ConfigurationHolder { private final Producer<Configuration> producer; private final Set<Annotation> qualifiers; private final String name; private final Configuration configuration; ConfigurationHolder(Producer<Configuration> producer, String name, Set<Annotation> qualifiers) { this(producer, qualifiers, name, null); } ConfigurationHolder(Configuration configuration, String name, Set<Annotation> qualifiers) { this(null, qualifiers, name, configuration); } private ConfigurationHolder(Producer<Configuration> producer, Set<Annotation> qualifiers, String name, Configuration configuration) { this.producer = producer; this.qualifiers = qualifiers; this.name = name; this.configuration = configuration; } public Producer<Configuration> getProducer() { return producer; } public String getName() { return name; } public Set<Annotation> getQualifiers() { return qualifiers; } Configuration getConfiguration(CreationalContext<Configuration> ctx) { return configuration != null ? configuration : producer.produce(ctx); } } public static class InstalledCacheManager { final EmbeddedCacheManager cacheManager; final boolean isDefault; InstalledCacheManager(EmbeddedCacheManager cacheManager, boolean aDefault) { this.cacheManager = cacheManager; isDefault = aDefault; } public EmbeddedCacheManager getCacheManager() { return cacheManager; } public boolean isDefault() { return isDefault; } } }
14,248
46.182119
222
java
null
infinispan-main/cdi/embedded/src/main/java/org/infinispan/cdi/embedded/AdvancedCacheProducer.java
package org.infinispan.cdi.embedded; import java.lang.annotation.Annotation; import java.util.Set; import jakarta.enterprise.context.ApplicationScoped; import jakarta.enterprise.inject.Any; import jakarta.enterprise.inject.Instance; import jakarta.enterprise.inject.spi.BeanManager; import jakarta.inject.Inject; import org.infinispan.AdvancedCache; import org.infinispan.Cache; import org.infinispan.cdi.common.util.Reflections; import org.infinispan.cdi.embedded.event.cache.CacheEventBridge; import org.infinispan.cdi.embedded.event.cachemanager.CacheManagerEventBridge; import org.infinispan.manager.CacheContainer; import org.infinispan.manager.EmbeddedCacheManager; /** * This class is responsible to produce the {@link Cache} and {@link AdvancedCache}. This class use the * <a href="http://docs.jboss.org/seam/3/solder/latest/reference/en-US/html_single/#genericbeans">Generic Beans</a> * mechanism provided by Seam Solder. * * @author Pete Muir * @author Kevin Pollet &lt;kevin.pollet@serli.com&gt; (C) 2011 SERLI */ @ApplicationScoped public class AdvancedCacheProducer { @Inject private EmbeddedCacheManager defaultCacheContainer; @Inject private CacheEventBridge cacheEventBridge; @Inject private InfinispanExtensionEmbedded infinispanExtension; @Inject @Any private Instance<EmbeddedCacheManager> cacheManagers; @Inject private BeanManager beanManager; @Inject private CacheManagerEventBridge eventBridge; private CacheContainer getCacheContainer(Set<Annotation> qualifiers) { Instance<EmbeddedCacheManager> cacheContainer = cacheManagers.select(qualifiers.toArray(Reflections.EMPTY_ANNOTATION_ARRAY)); if (cacheContainer.isUnsatisfied()) { return defaultCacheContainer; } else { return cacheContainer.get(); } } public <K, V> AdvancedCache<K, V> getAdvancedCache(String name, Set<Annotation> qualifiers) { // lazy register stuff infinispanExtension.registerCacheConfigurations(eventBridge, cacheManagers, beanManager); Cache<K, V> cache; CacheContainer container = getCacheContainer(qualifiers); if (name.isEmpty()) { cache = container.getCache(); } else { cache = container.getCache(name); } cacheEventBridge.registerObservers( qualifiers, cache ); return cache.getAdvancedCache(); } }
2,415
29.582278
131
java
null
infinispan-main/cdi/embedded/src/main/java/org/infinispan/cdi/embedded/util/logging/package-info.java
/** * This package contains the logging classes. */ package org.infinispan.cdi.embedded.util.logging;
104
20
49
java
null
infinispan-main/cdi/embedded/src/main/java/org/infinispan/cdi/embedded/util/logging/EmbeddedLog.java
package org.infinispan.cdi.embedded.util.logging; import static org.jboss.logging.Logger.Level.INFO; import org.infinispan.manager.EmbeddedCacheManager; import org.jboss.logging.BasicLogger; import org.jboss.logging.annotations.LogMessage; import org.jboss.logging.annotations.Message; import org.jboss.logging.annotations.MessageLogger; /** * The JBoss Logging interface which defined the logging methods for the CDI integration. The id range for the CDI * integration is 17001-18000 * * @author Kevin Pollet &lt;kevin.pollet@serli.com&gt; (C) 2011 SERLI */ @MessageLogger(projectCode = "ISPN") public interface EmbeddedLog extends BasicLogger { @LogMessage(level = INFO) @Message(value = "Configuration for cache '%s' has been defined in cache manager '%s'", id = 17002) void cacheConfigurationDefined(String cacheName, EmbeddedCacheManager cacheManager); @LogMessage(level = INFO) @Message(value = "Overriding default embedded configuration not found - adding default implementation", id = 17003) void addDefaultEmbeddedConfiguration(); @LogMessage(level = INFO) @Message(value = "Overriding default embedded cache manager not found - adding default implementation", id = 17004) void addDefaultEmbeddedCacheManager(); }
1,262
37.272727
118
java
null
infinispan-main/cdi/embedded/src/main/java/org/infinispan/cdi/embedded/event/package-info.java
/** * This package contains the event bridge implementation between Infinispan and CDI. */ package org.infinispan.cdi.embedded.event;
136
26.4
84
java
null
infinispan-main/cdi/embedded/src/main/java/org/infinispan/cdi/embedded/event/AbstractEventBridge.java
package org.infinispan.cdi.embedded.event; import java.lang.annotation.Annotation; import jakarta.enterprise.event.Event; import jakarta.enterprise.inject.spi.BeanManager; import jakarta.inject.Inject; /** * @author Pete Muir */ public abstract class AbstractEventBridge<T> { @Inject private Event<T> baseEvent; @Inject private BeanManager beanManager; protected Event<T> getBaseEvent() { return baseEvent; } protected boolean hasObservers(T event, Annotation[] qualifiers) { return !beanManager.resolveObserverMethods(event, qualifiers).isEmpty(); } }
598
20.392857
78
java
null
infinispan-main/cdi/embedded/src/main/java/org/infinispan/cdi/embedded/event/cachemanager/CacheStartedAdapter.java
package org.infinispan.cdi.embedded.event.cachemanager; import jakarta.enterprise.event.Event; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.notifications.Listener; import org.infinispan.notifications.cachemanagerlistener.annotation.CacheStarted; import org.infinispan.notifications.cachemanagerlistener.event.CacheStartedEvent; /** * @author Pete Muir */ @Listener public class CacheStartedAdapter extends AbstractAdapter<CacheStartedEvent> { public static final CacheStartedEvent EMPTY = new CacheStartedEvent() { @Override public Type getType() { return null; } @Override public EmbeddedCacheManager getCacheManager() { return null; } @Override public String getCacheName() { return null; } }; private final String cacheName; public CacheStartedAdapter(Event<CacheStartedEvent> event, String cacheName) { super(event); this.cacheName = cacheName; } @Override @CacheStarted public void fire(CacheStartedEvent payload) { if (payload.getCacheName().equals(cacheName)) { super.fire(payload); } } }
1,178
23.061224
81
java
null
infinispan-main/cdi/embedded/src/main/java/org/infinispan/cdi/embedded/event/cachemanager/package-info.java
/** * This package contains the adapters making the bridge between Infinispan cache manager events and CDI. */ package org.infinispan.cdi.embedded.event.cachemanager;
169
33
104
java
null
infinispan-main/cdi/embedded/src/main/java/org/infinispan/cdi/embedded/event/cachemanager/ViewChangedAdapter.java
package org.infinispan.cdi.embedded.event.cachemanager; import java.util.Collections; import java.util.List; import jakarta.enterprise.event.Event; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.notifications.Listener; import org.infinispan.notifications.cachemanagerlistener.annotation.ViewChanged; import org.infinispan.notifications.cachemanagerlistener.event.ViewChangedEvent; import org.infinispan.remoting.transport.Address; /** * @author Pete Muir */ @Listener public class ViewChangedAdapter extends AbstractAdapter<ViewChangedEvent> { public static final ViewChangedEvent EMPTY = new ViewChangedEvent() { @Override public Type getType() { return null; } @Override public EmbeddedCacheManager getCacheManager() { return null; } @Override public List<Address> getNewMembers() { return Collections.emptyList(); } @Override public List<Address> getOldMembers() { return Collections.emptyList(); } @Override public Address getLocalAddress() { return null; } public boolean isNeedsToRejoin() { return false; } @Override public int getViewId() { return 0; } @Override public boolean isMergeView() { return false; } }; public ViewChangedAdapter(Event<ViewChangedEvent> event) { super(event); } @Override @ViewChanged public void fire(ViewChangedEvent payload) { super.fire(payload); } }
1,578
20.930556
80
java
null
infinispan-main/cdi/embedded/src/main/java/org/infinispan/cdi/embedded/event/cachemanager/AbstractAdapter.java
package org.infinispan.cdi.embedded.event.cachemanager; import jakarta.enterprise.event.Event; /** * @author Pete Muir */ public abstract class AbstractAdapter<T extends org.infinispan.notifications.cachemanagerlistener.event.Event> { private final Event<T> event; public AbstractAdapter(Event<T> event) { this.event = event; } public void fire(T payload) { this.event.fire(payload); } }
422
20.15
112
java
null
infinispan-main/cdi/embedded/src/main/java/org/infinispan/cdi/embedded/event/cachemanager/CacheManagerEventBridge.java
package org.infinispan.cdi.embedded.event.cachemanager; import java.lang.annotation.Annotation; import java.util.Set; import jakarta.enterprise.context.Dependent; import org.infinispan.cdi.embedded.event.AbstractEventBridge; import org.infinispan.notifications.Listenable; import org.infinispan.notifications.cachemanagerlistener.event.CacheStartedEvent; import org.infinispan.notifications.cachemanagerlistener.event.CacheStoppedEvent; import org.infinispan.notifications.cachemanagerlistener.event.Event; import org.infinispan.notifications.cachemanagerlistener.event.ViewChangedEvent; /** * @author Pete Muir */ @Dependent public class CacheManagerEventBridge extends AbstractEventBridge<Event> { public void registerObservers(Set<Annotation> qualifierSet, String cacheName, Listenable listenable) { Annotation[] qualifiers = qualifierSet .toArray(new Annotation[qualifierSet.size()]); if (hasObservers(CacheStartedAdapter.EMPTY, qualifiers)) { listenable.addListener(new CacheStartedAdapter(getBaseEvent().select( CacheStartedEvent.class, qualifiers), cacheName)); } if (hasObservers(CacheStoppedAdapter.EMPTY, qualifiers)) { listenable.addListener(new CacheStoppedAdapter(getBaseEvent().select( CacheStoppedEvent.class, qualifiers), cacheName)); } if (hasObservers(ViewChangedAdapter.EMPTY, qualifiers)) { listenable.addListener(new ViewChangedAdapter(getBaseEvent().select( ViewChangedEvent.class, qualifiers))); } } }
1,597
39.974359
81
java
null
infinispan-main/cdi/embedded/src/main/java/org/infinispan/cdi/embedded/event/cachemanager/CacheStoppedAdapter.java
package org.infinispan.cdi.embedded.event.cachemanager; import jakarta.enterprise.event.Event; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.notifications.Listener; import org.infinispan.notifications.cachemanagerlistener.annotation.CacheStopped; import org.infinispan.notifications.cachemanagerlistener.event.CacheStoppedEvent; /** * @author Pete Muir */ @Listener public class CacheStoppedAdapter extends AbstractAdapter<CacheStoppedEvent> { public static final CacheStoppedEvent EMPTY = new CacheStoppedEvent() { @Override public Type getType() { return null; } @Override public EmbeddedCacheManager getCacheManager() { return null; } @Override public String getCacheName() { return null; } }; private final String cacheName; public CacheStoppedAdapter(Event<CacheStoppedEvent> event, String cacheName) { super(event); this.cacheName = cacheName; } @Override @CacheStopped public void fire(CacheStoppedEvent payload) { if (payload.getCacheName().equals(cacheName)) { super.fire(payload); } } }
1,178
23.061224
81
java
null
infinispan-main/cdi/embedded/src/main/java/org/infinispan/cdi/embedded/event/cache/package-info.java
/** * This package contains the adapters making the bridge between Infinispan cache events and CDI. */ package org.infinispan.cdi.embedded.event.cache;
154
30
96
java
null
infinispan-main/cdi/embedded/src/main/java/org/infinispan/cdi/embedded/event/cache/CacheEntryCreatedAdapter.java
package org.infinispan.cdi.embedded.event.cache; import jakarta.enterprise.event.Event; import jakarta.enterprise.util.TypeLiteral; import org.infinispan.Cache; import org.infinispan.metadata.Metadata; import org.infinispan.notifications.Listener; import org.infinispan.notifications.cachelistener.annotation.CacheEntryCreated; import org.infinispan.notifications.cachelistener.event.CacheEntryCreatedEvent; import org.infinispan.transaction.xa.GlobalTransaction; /** * Event bridge for {@link org.infinispan.notifications.cachelistener.annotation.CacheEntryCreated}. * * @author Pete Muir * @author Sebastian Laskawiec * @see org.infinispan.notifications.Listener * @see org.infinispan.notifications.cachelistener.annotation.CacheEntryCreated */ @Listener public class CacheEntryCreatedAdapter<K, V> extends AbstractAdapter<CacheEntryCreatedEvent<K, V>> { /** * CDI does not allow parametrized type for events (like <code><K,V></code>). This is why this wrapped needs to be * introduced. To ensure type safety, this needs to be linked to parent class (in other words this class can not * be static). */ private class CDICacheEntryCreatedEvent implements CacheEntryCreatedEvent<K, V> { private CacheEntryCreatedEvent<K, V> decoratedEvent; private CDICacheEntryCreatedEvent(CacheEntryCreatedEvent<K, V> decoratedEvent) { this.decoratedEvent = decoratedEvent; } @Override public V getValue() { return decoratedEvent.getValue(); } @Override public boolean isCommandRetried() { return decoratedEvent.isCommandRetried(); } @Override public K getKey() { return decoratedEvent.getKey(); } @Override public Metadata getMetadata() { return decoratedEvent.getMetadata(); } @Override public GlobalTransaction getGlobalTransaction() { return decoratedEvent.getGlobalTransaction(); } @Override public boolean isOriginLocal() { return decoratedEvent.isOriginLocal(); } @Override public Type getType() { return decoratedEvent.getType(); } @Override public boolean isPre() { return decoratedEvent.isPre(); } @Override public Cache getCache() { return decoratedEvent.getCache(); } } public static final CacheEntryCreatedEvent<?, ?> EMPTY = new CacheEntryCreatedEvent<Object, Object>() { @Override public Type getType() { return null; } @Override public Object getKey() { return null; } @Override public GlobalTransaction getGlobalTransaction() { return null; } @Override public boolean isOriginLocal() { return false; } @Override public boolean isPre() { return false; } @Override public Cache<Object, Object> getCache() { return null; } @Override public Object getValue() { return null; } @Override public Metadata getMetadata() { return null; } @Override public boolean isCommandRetried() { return false; } }; /** * Events which will be selected (including generic type information (<code><?, ?></code>). */ @SuppressWarnings("serial") public static final TypeLiteral<CacheEntryCreatedEvent<?, ?>> WILDCARD_TYPE = new TypeLiteral<CacheEntryCreatedEvent<?, ?>>() { }; /** * Needed for creating event bridge. */ public CacheEntryCreatedAdapter(Event<CacheEntryCreatedEvent<K, V>> event) { super(event); } @Override @CacheEntryCreated public void fire(CacheEntryCreatedEvent<K, V> payload) { super.fire(new CDICacheEntryCreatedEvent(payload)); } }
3,870
24.635762
130
java
null
infinispan-main/cdi/embedded/src/main/java/org/infinispan/cdi/embedded/event/cache/AbstractAdapter.java
package org.infinispan.cdi.embedded.event.cache; import jakarta.enterprise.event.Event; /** * @author Pete Muir */ public abstract class AbstractAdapter<T extends org.infinispan.notifications.cachelistener.event.Event<?, ?>> { private final Event<T> event; public AbstractAdapter(Event<T> event) { this.event = event; } public void fire(T payload) { this.event.fire(payload); } }
414
19.75
111
java
null
infinispan-main/cdi/embedded/src/main/java/org/infinispan/cdi/embedded/event/cache/CacheEntryLoadedAdapter.java
package org.infinispan.cdi.embedded.event.cache; import jakarta.enterprise.event.Event; import jakarta.enterprise.util.TypeLiteral; import org.infinispan.Cache; import org.infinispan.metadata.Metadata; import org.infinispan.notifications.Listener; import org.infinispan.notifications.cachelistener.annotation.CacheEntryLoaded; import org.infinispan.notifications.cachelistener.event.CacheEntryLoadedEvent; import org.infinispan.transaction.xa.GlobalTransaction; /** * Event bridge for {@link org.infinispan.notifications.cachelistener.annotation.CacheEntryLoaded}. * * @author Pete Muir * @author Sebastian Laskawiec * @see org.infinispan.notifications.Listener * @see org.infinispan.notifications.cachelistener.annotation.CacheEntryLoaded */ @Listener public class CacheEntryLoadedAdapter<K, V> extends AbstractAdapter<CacheEntryLoadedEvent<K, V>> { /** * CDI does not allow parametrized type for events (like <code><K,V></code>). This is why this wrapped needs to be * introduced. To ensure type safety, this needs to be linked to parent class (in other words this class can not * be static). */ private class CDICacheEntryLoadedEvent implements CacheEntryLoadedEvent<K, V> { private CacheEntryLoadedEvent<K, V> decoratedEvent; private CDICacheEntryLoadedEvent(CacheEntryLoadedEvent<K, V> decoratedEvent) { this.decoratedEvent = decoratedEvent; } @Override public V getValue() { return decoratedEvent.getValue(); } @Override public K getKey() { return decoratedEvent.getKey(); } @Override public Metadata getMetadata() { return decoratedEvent.getMetadata(); } @Override public GlobalTransaction getGlobalTransaction() { return decoratedEvent.getGlobalTransaction(); } @Override public boolean isOriginLocal() { return decoratedEvent.isOriginLocal(); } @Override public Type getType() { return decoratedEvent.getType(); } @Override public boolean isPre() { return decoratedEvent.isPre(); } @Override public Cache<K, V> getCache() { return decoratedEvent.getCache(); } } /** * Needed for creating event bridge. */ public static final CacheEntryLoadedEvent<?, ?> EMPTY = new CacheEntryLoadedEvent<Object, Object>() { @Override public Type getType() { return null; } @Override public Object getKey() { return null; } @Override public GlobalTransaction getGlobalTransaction() { return null; } @Override public boolean isOriginLocal() { return false; } @Override public boolean isPre() { return false; } @Override public Cache<Object, Object> getCache() { return null; } @Override public Object getValue() { return null; } @Override public Metadata getMetadata() { return null; } }; /** * Events which will be selected (including generic type information (<code><?, ?></code>). */ @SuppressWarnings("serial") public static final TypeLiteral<CacheEntryLoadedEvent<?, ?>> WILDCARD_TYPE = new TypeLiteral<CacheEntryLoadedEvent<?, ?>>() { }; public CacheEntryLoadedAdapter(Event<CacheEntryLoadedEvent<K, V>> event) { super(event); } @Override @CacheEntryLoaded public void fire(CacheEntryLoadedEvent<K, V> payload) { super.fire(new CDICacheEntryLoadedEvent(payload)); } }
3,647
25.057143
128
java
null
infinispan-main/cdi/embedded/src/main/java/org/infinispan/cdi/embedded/event/cache/CacheEntryVisitedAdapter.java
package org.infinispan.cdi.embedded.event.cache; import jakarta.enterprise.event.Event; import jakarta.enterprise.util.TypeLiteral; import org.infinispan.Cache; import org.infinispan.metadata.Metadata; import org.infinispan.notifications.Listener; import org.infinispan.notifications.cachelistener.annotation.CacheEntryVisited; import org.infinispan.notifications.cachelistener.event.CacheEntryVisitedEvent; import org.infinispan.transaction.xa.GlobalTransaction; /** * Event bridge for {@link org.infinispan.notifications.cachelistener.annotation.CacheEntryVisited}. * * @author Pete Muir * @author Sebastian Laskawiec * @see org.infinispan.notifications.Listener * @see org.infinispan.notifications.cachelistener.annotation.CacheEntryVisited */ @Listener public class CacheEntryVisitedAdapter<K, V> extends AbstractAdapter<CacheEntryVisitedEvent<K, V>> { /** * CDI does not allow parametrized type for events (like <code><K,V></code>). This is why this wrapped needs to be * introduced. To ensure type safety, this needs to be linked to parent class (in other words this class can not * be static). */ private class CDICacheEntryVisitedEvent implements CacheEntryVisitedEvent<K, V> { private CacheEntryVisitedEvent<K, V> decoratedEvent; private CDICacheEntryVisitedEvent(CacheEntryVisitedEvent<K, V> decoratedEvent) { this.decoratedEvent = decoratedEvent; } @Override public V getValue() { return decoratedEvent.getValue(); } @Override public K getKey() { return decoratedEvent.getKey(); } @Override public Metadata getMetadata() { return decoratedEvent.getMetadata(); } @Override public GlobalTransaction getGlobalTransaction() { return decoratedEvent.getGlobalTransaction(); } @Override public boolean isOriginLocal() { return decoratedEvent.isOriginLocal(); } @Override public Type getType() { return decoratedEvent.getType(); } @Override public boolean isPre() { return decoratedEvent.isPre(); } @Override public Cache<K, V> getCache() { return decoratedEvent.getCache(); } } /** * Needed for creating event bridge. */ public static final CacheEntryVisitedEvent<?, ?> EMPTY = new CacheEntryVisitedEvent<Object, Object>() { @Override public Type getType() { return null; } @Override public Object getKey() { return null; } @Override public GlobalTransaction getGlobalTransaction() { return null; } @Override public boolean isOriginLocal() { return false; } @Override public boolean isPre() { return false; } @Override public Cache<Object, Object> getCache() { return null; } @Override public Object getValue() { return null; } @Override public Metadata getMetadata() { return null; } }; /** * Events which will be selected (including generic type information (<code><?, ?></code>). */ @SuppressWarnings("serial") public static final TypeLiteral<CacheEntryVisitedEvent<?, ?>> WILDCARD_TYPE = new TypeLiteral<CacheEntryVisitedEvent<?, ?>>() { }; public CacheEntryVisitedAdapter(Event<CacheEntryVisitedEvent<K, V>> event) { super(event); } @Override @CacheEntryVisited public void fire(CacheEntryVisitedEvent<K, V> payload) { super.fire(new CDICacheEntryVisitedEvent(payload)); } }
3,667
25.2
130
java
null
infinispan-main/cdi/embedded/src/main/java/org/infinispan/cdi/embedded/event/cache/TransactionCompletedAdapter.java
package org.infinispan.cdi.embedded.event.cache; import jakarta.enterprise.event.Event; import jakarta.enterprise.util.TypeLiteral; import org.infinispan.Cache; import org.infinispan.notifications.Listener; import org.infinispan.notifications.cachelistener.annotation.TransactionCompleted; import org.infinispan.notifications.cachelistener.event.TransactionCompletedEvent; import org.infinispan.transaction.xa.GlobalTransaction; /** * Event bridge for {@link org.infinispan.notifications.cachelistener.annotation.TransactionCompleted}. * * @author Pete Muir * @author Sebastian Laskawiec * @see org.infinispan.notifications.Listener * @see org.infinispan.notifications.cachelistener.annotation.TransactionCompleted */ @Listener public class TransactionCompletedAdapter<K, V> extends AbstractAdapter<TransactionCompletedEvent<K, V>> { /** * CDI does not allow parametrized type for events (like <code><K,V></code>). This is why this wrapped needs to be * introduced. To ensure type safety, this needs to be linked to parent class (in other words this class can not * be static). */ private class CDITransactionCompletedEvent implements TransactionCompletedEvent<K, V> { private TransactionCompletedEvent<K, V> decoratedEvent; private CDITransactionCompletedEvent(TransactionCompletedEvent<K, V> decoratedEvent) { this.decoratedEvent = decoratedEvent; } @Override public boolean isTransactionSuccessful() { return decoratedEvent.isTransactionSuccessful(); } @Override public GlobalTransaction getGlobalTransaction() { return decoratedEvent.getGlobalTransaction(); } @Override public boolean isOriginLocal() { return decoratedEvent.isOriginLocal(); } @Override public Type getType() { return decoratedEvent.getType(); } @Override public boolean isPre() { return decoratedEvent.isPre(); } @Override public Cache<K, V> getCache() { return decoratedEvent.getCache(); } } /** * Needed for creating event bridge. */ public static final TransactionCompletedEvent<?, ?> EMPTY = new TransactionCompletedEvent<Object, Object>() { @Override public Type getType() { return null; } @Override public GlobalTransaction getGlobalTransaction() { return null; } @Override public boolean isOriginLocal() { return false; } @Override public boolean isPre() { return false; } @Override public Cache<Object, Object> getCache() { return null; } @Override public boolean isTransactionSuccessful() { return false; } }; /** * Events which will be selected (including generic type information (<code><?, ?></code>). */ @SuppressWarnings("serial") public static final TypeLiteral<TransactionCompletedEvent<?, ?>> WILDCARD_TYPE = new TypeLiteral<TransactionCompletedEvent<?, ?>>() { }; public TransactionCompletedAdapter(Event<TransactionCompletedEvent<K, V>> event) { super(event); } @Override @TransactionCompleted public void fire(TransactionCompletedEvent<K, V> payload) { super.fire(new CDITransactionCompletedEvent(payload)); } }
3,376
27.141667
136
java
null
infinispan-main/cdi/embedded/src/main/java/org/infinispan/cdi/embedded/event/cache/CacheEntryExpiredAdapter.java
package org.infinispan.cdi.embedded.event.cache; import jakarta.enterprise.event.Event; import jakarta.enterprise.util.TypeLiteral; import org.infinispan.Cache; import org.infinispan.metadata.Metadata; import org.infinispan.notifications.Listener; import org.infinispan.notifications.cachelistener.annotation.CacheEntryExpired; import org.infinispan.notifications.cachelistener.event.CacheEntryExpiredEvent; import org.infinispan.transaction.xa.GlobalTransaction; /** * Event bridge for {@link org.infinispan.notifications.cachelistener.annotation.CacheEntryExpired}. * * @author William Burns * @see org.infinispan.notifications.Listener * @see org.infinispan.notifications.cachelistener.annotation.CacheEntryExpired */ @Listener public class CacheEntryExpiredAdapter<K, V> extends AbstractAdapter<CacheEntryExpiredEvent<K, V>> { /** * CDI does not allow parametrized type for events (like <code><K,V></code>). This is why this wrapped needs to be * introduced. To ensure type safety, this needs to be linked to parent class (in other words this class can not * be static). */ private class CDICacheEntriesEvictedEvent implements CacheEntryExpiredEvent<K, V> { private CacheEntryExpiredEvent<K, V> decoratedEvent; private CDICacheEntriesEvictedEvent(CacheEntryExpiredEvent<K, V> decoratedEvent) { this.decoratedEvent = decoratedEvent; } @Override public V getValue() { return decoratedEvent.getValue(); } @Override public K getKey() { return decoratedEvent.getKey(); } @Override public Metadata getMetadata() { return decoratedEvent.getMetadata(); } @Override public GlobalTransaction getGlobalTransaction() { return decoratedEvent.getGlobalTransaction(); } @Override public boolean isOriginLocal() { return decoratedEvent.isOriginLocal(); } @Override public Type getType() { return decoratedEvent.getType(); } @Override public boolean isPre() { return decoratedEvent.isPre(); } @Override public Cache<K, V> getCache() { return decoratedEvent.getCache(); } } /** * Needed for creating event bridge. */ public static final CacheEntryExpiredEvent<?, ?> EMPTY = new CacheEntryExpiredEvent<Object, Object>() { @Override public Object getKey() { return null; } @Override public Object getValue() { return null; } @Override public Metadata getMetadata() { return null; } @Override public GlobalTransaction getGlobalTransaction() { return null; } @Override public boolean isOriginLocal() { return false; } @Override public Type getType() { return null; } @Override public boolean isPre() { return false; } @Override public Cache<Object, Object> getCache() { return null; } }; /** * Events which will be selected (including generic type information (<code><?, ?></code>). */ @SuppressWarnings("serial") public static final TypeLiteral<CacheEntryExpiredEvent<?, ?>> WILDCARD_TYPE = new TypeLiteral<CacheEntryExpiredEvent<?, ?>>() { }; public CacheEntryExpiredAdapter(Event<CacheEntryExpiredEvent<K, V>> event) { super(event); } @Override @CacheEntryExpired public void fire(CacheEntryExpiredEvent<K, V> payload) { super.fire(new CDICacheEntriesEvictedEvent(payload)); } }
3,646
25.23741
130
java
null
infinispan-main/cdi/embedded/src/main/java/org/infinispan/cdi/embedded/event/cache/CacheEventBridge.java
package org.infinispan.cdi.embedded.event.cache; import java.lang.annotation.Annotation; import java.util.Set; import jakarta.enterprise.context.Dependent; import org.infinispan.cdi.embedded.event.AbstractEventBridge; import org.infinispan.notifications.Listenable; import org.infinispan.notifications.cachelistener.event.Event; /** * Bridges Infinispan with CDI events. * * @author Pete Muir * @author Sebastian Laskawiec */ @Dependent public class CacheEventBridge extends AbstractEventBridge<Event<?, ?>> { public void registerObservers(Set<Annotation> qualifierSet, Listenable listenable) { Annotation[] qualifiers = qualifierSet .toArray(new Annotation[qualifierSet.size()]); if (hasObservers(CacheEntryActivatedAdapter.EMPTY, qualifiers)) { listenable.addListener(new CacheEntryActivatedAdapter(getBaseEvent() .select(CacheEntryActivatedAdapter.WILDCARD_TYPE, qualifiers))); } if (hasObservers(CacheEntryCreatedAdapter.EMPTY, qualifiers)) { listenable.addListener(new CacheEntryCreatedAdapter(getBaseEvent() .select(CacheEntryCreatedAdapter.WILDCARD_TYPE, qualifiers))); } if (hasObservers(CacheEntriesEvictedAdapter.EMPTY, qualifiers)) { listenable.addListener(new CacheEntriesEvictedAdapter(getBaseEvent() .select(CacheEntriesEvictedAdapter.WILDCARD_TYPE, qualifiers))); } if (hasObservers(CacheEntryExpiredAdapter.EMPTY, qualifiers)) { listenable.addListener(new CacheEntryExpiredAdapter(getBaseEvent() .select(CacheEntryExpiredAdapter.WILDCARD_TYPE, qualifiers))); } if (hasObservers(CacheEntryInvalidatedAdapter.EMPTY, qualifiers)) { listenable.addListener(new CacheEntryInvalidatedAdapter(getBaseEvent() .select(CacheEntryInvalidatedAdapter.WILDCARD_TYPE, qualifiers))); } if (hasObservers(CacheEntryLoadedAdapter.EMPTY, qualifiers)) { listenable.addListener(new CacheEntryLoadedAdapter(getBaseEvent() .select(CacheEntryLoadedAdapter.WILDCARD_TYPE, qualifiers))); } if (hasObservers(CacheEntryModifiedAdapter.EMPTY, qualifiers)) { listenable.addListener(new CacheEntryModifiedAdapter(getBaseEvent() .select(CacheEntryModifiedAdapter.WILDCARD_TYPE, qualifiers))); } if (hasObservers(CacheEntryPassivatedAdapter.EMPTY, qualifiers)) { listenable.addListener(new CacheEntryPassivatedAdapter(getBaseEvent() .select(CacheEntryPassivatedAdapter.WILDCARD_TYPE, qualifiers))); } if (hasObservers(CacheEntryRemovedAdapter.EMPTY, qualifiers)) { listenable.addListener(new CacheEntryRemovedAdapter(getBaseEvent() .select(CacheEntryRemovedAdapter.WILDCARD_TYPE, qualifiers))); } if (hasObservers(CacheEntryVisitedAdapter.EMPTY, qualifiers)) { listenable.addListener(new CacheEntryVisitedAdapter(getBaseEvent() .select(CacheEntryVisitedAdapter.WILDCARD_TYPE, qualifiers))); } if (hasObservers(TransactionCompletedAdapter.EMPTY, qualifiers)) { listenable.addListener(new TransactionCompletedAdapter(getBaseEvent() .select(TransactionCompletedAdapter.WILDCARD_TYPE, qualifiers))); } if (hasObservers(TransactionRegisteredAdapter.EMPTY, qualifiers)) { listenable.addListener(new TransactionRegisteredAdapter(getBaseEvent() .select(TransactionRegisteredAdapter.WILDCARD_TYPE, qualifiers))); } if (hasObservers(DataRehashedAdapter.EMPTY, qualifiers)) { listenable.addListener(new DataRehashedAdapter(getBaseEvent() .select(DataRehashedAdapter.WILDCARD_TYPE, qualifiers))); } if (hasObservers(TopologyChangedAdapter.EMPTY, qualifiers)) { listenable.addListener(new TopologyChangedAdapter(getBaseEvent() .select(TopologyChangedAdapter.WILDCARD_TYPE, qualifiers))); } } }
4,035
47.626506
81
java
null
infinispan-main/cdi/embedded/src/main/java/org/infinispan/cdi/embedded/event/cache/TopologyChangedAdapter.java
package org.infinispan.cdi.embedded.event.cache; import jakarta.enterprise.event.Event; import jakarta.enterprise.util.TypeLiteral; import org.infinispan.Cache; import org.infinispan.distribution.ch.ConsistentHash; import org.infinispan.notifications.Listener; import org.infinispan.notifications.cachelistener.annotation.TopologyChanged; import org.infinispan.notifications.cachelistener.event.TopologyChangedEvent; import org.infinispan.notifications.cachelistener.event.TransactionRegisteredEvent; import org.infinispan.transaction.xa.GlobalTransaction; /** * @author Pete Muir */ @Listener public class TopologyChangedAdapter<K, V> extends AbstractAdapter<TopologyChangedEvent<K, V>> { /** * CDI does not allow parametrized type for events (like <code><K,V></code>). This is why this wrapped needs to be * introduced. To ensure type safety, this needs to be linked to parent class (in other words this class can not * be static). */ private class CDITopologyChangedEvent implements TopologyChangedEvent<K, V> { private TopologyChangedEvent<K, V> decoratedEvent; private CDITopologyChangedEvent(TopologyChangedEvent<K, V> decoratedEvent) { this.decoratedEvent = decoratedEvent; } @Override public ConsistentHash getReadConsistentHashAtStart() { return decoratedEvent.getReadConsistentHashAtStart(); } @Override public ConsistentHash getWriteConsistentHashAtStart() { return decoratedEvent.getWriteConsistentHashAtStart(); } @Override public ConsistentHash getReadConsistentHashAtEnd() { return decoratedEvent.getReadConsistentHashAtEnd(); } @Override public ConsistentHash getWriteConsistentHashAtEnd() { return decoratedEvent.getWriteConsistentHashAtEnd(); } @Override public int getNewTopologyId() { return decoratedEvent.getNewTopologyId(); } @Override public Type getType() { return decoratedEvent.getType(); } @Override public boolean isPre() { return decoratedEvent.isPre(); } @Override public Cache<K, V> getCache() { return decoratedEvent.getCache(); } } /** * Needed for creating event bridge. */ public static final TransactionRegisteredEvent<?, ?> EMPTY = new TransactionRegisteredEvent<Object, Object>() { @Override public Type getType() { return null; } @Override public GlobalTransaction getGlobalTransaction() { return null; } @Override public boolean isOriginLocal() { return false; } @Override public boolean isPre() { return false; } @Override public Cache<Object, Object> getCache() { return null; } }; /** * Events which will be selected (including generic type information (<code><?, ?></code>). */ @SuppressWarnings("serial") public static final TypeLiteral<TopologyChangedEvent<?, ?>> WILDCARD_TYPE = new TypeLiteral<TopologyChangedEvent<?, ?>>() { }; public TopologyChangedAdapter(Event<TopologyChangedEvent<K, V>> event) { super(event); } @Override @TopologyChanged public void fire(TopologyChangedEvent<K, V> payload) { super.fire(new CDITopologyChangedEvent(payload)); } }
3,398
26.860656
126
java
null
infinispan-main/cdi/embedded/src/main/java/org/infinispan/cdi/embedded/event/cache/CacheEntryPassivatedAdapter.java
package org.infinispan.cdi.embedded.event.cache; import jakarta.enterprise.event.Event; import jakarta.enterprise.util.TypeLiteral; import org.infinispan.Cache; import org.infinispan.metadata.Metadata; import org.infinispan.notifications.Listener; import org.infinispan.notifications.cachelistener.annotation.CacheEntryPassivated; import org.infinispan.notifications.cachelistener.event.CacheEntryPassivatedEvent; import org.infinispan.transaction.xa.GlobalTransaction; /** * Event bridge for {@link org.infinispan.notifications.cachelistener.annotation.CacheEntryPassivated}. * * @author Pete Muir * @author Sebastian Laskawiec * @see org.infinispan.notifications.Listener * @see org.infinispan.notifications.cachelistener.annotation.CacheEntryPassivated */ @Listener public class CacheEntryPassivatedAdapter<K, V> extends AbstractAdapter<CacheEntryPassivatedEvent<K, V>> { /** * CDI does not allow parametrized type for events (like <code><K,V></code>). This is why this wrapped needs to be * introduced. To ensure type safety, this needs to be linked to parent class (in other words this class can not * be static). */ private class CDICacheEntryPassivatedEvent implements CacheEntryPassivatedEvent<K, V> { private CacheEntryPassivatedEvent<K, V> decoratedEvent; private CDICacheEntryPassivatedEvent(CacheEntryPassivatedEvent<K, V> decoratedEvent) { this.decoratedEvent = decoratedEvent; } @Override public V getValue() { return decoratedEvent.getValue(); } @Override public K getKey() { return decoratedEvent.getKey(); } @Override public Metadata getMetadata() { return decoratedEvent.getMetadata(); } @Override public GlobalTransaction getGlobalTransaction() { return decoratedEvent.getGlobalTransaction(); } @Override public boolean isOriginLocal() { return decoratedEvent.isOriginLocal(); } @Override public Type getType() { return decoratedEvent.getType(); } @Override public boolean isPre() { return decoratedEvent.isPre(); } @Override public Cache<K, V> getCache() { return decoratedEvent.getCache(); } } /** * Needed for creating event bridge. */ public static final CacheEntryPassivatedEvent<?, ?> EMPTY = new CacheEntryPassivatedEvent<Object, Object>() { @Override public Type getType() { return null; } @Override public Object getKey() { return null; } @Override public GlobalTransaction getGlobalTransaction() { return null; } @Override public boolean isOriginLocal() { return false; } @Override public boolean isPre() { return false; } @Override public Cache<Object, Object> getCache() { return null; } @Override public Object getValue() { return null; } @Override public Metadata getMetadata() { return null; } }; /** * Events which will be selected (including generic type information (<code><?, ?></code>). */ @SuppressWarnings("serial") public static final TypeLiteral<CacheEntryPassivatedEvent<?, ?>> WILDCARD_TYPE = new TypeLiteral<CacheEntryPassivatedEvent<?, ?>>() { }; public CacheEntryPassivatedAdapter(Event<CacheEntryPassivatedEvent<K, V>> event) { super(event); } @Override @CacheEntryPassivated public void fire(CacheEntryPassivatedEvent<K, V> payload) { super.fire(new CDICacheEntryPassivatedEvent(payload)); } }
3,727
25.628571
136
java
null
infinispan-main/cdi/embedded/src/main/java/org/infinispan/cdi/embedded/event/cache/CacheEntryRemovedAdapter.java
package org.infinispan.cdi.embedded.event.cache; import jakarta.enterprise.event.Event; import jakarta.enterprise.util.TypeLiteral; import org.infinispan.Cache; import org.infinispan.metadata.Metadata; import org.infinispan.notifications.Listener; import org.infinispan.notifications.cachelistener.annotation.CacheEntryRemoved; import org.infinispan.notifications.cachelistener.event.CacheEntryRemovedEvent; import org.infinispan.transaction.xa.GlobalTransaction; /** * Event bridge for {@link org.infinispan.notifications.cachelistener.annotation.CacheEntryRemoved}. * * @author Pete Muir * @author Sebastian Laskawiec * @see org.infinispan.notifications.Listener * @see org.infinispan.notifications.cachelistener.annotation.CacheEntryRemoved */ @Listener public class CacheEntryRemovedAdapter<K, V> extends AbstractAdapter<CacheEntryRemovedEvent<K, V>> { /** * CDI does not allow parametrized type for events (like <code><K,V></code>). This is why this wrapped needs to be * introduced. To ensure type safety, this needs to be linked to parent class (in other words this class can not * be static). */ private class CDICacheEntryRemovedEvent implements CacheEntryRemovedEvent<K, V> { private CacheEntryRemovedEvent<K, V> decoratedEvent; private CDICacheEntryRemovedEvent(CacheEntryRemovedEvent<K, V> decoratedEvent) { this.decoratedEvent = decoratedEvent; } @Override public V getValue() { return decoratedEvent.getValue(); } @Override public V getOldValue() { return decoratedEvent.getOldValue(); } @Override public boolean isCommandRetried() { return decoratedEvent.isCommandRetried(); } @Override public K getKey() { return decoratedEvent.getKey(); } @Override public Metadata getMetadata() { return decoratedEvent.getMetadata(); } @Override public Metadata getOldMetadata() { return decoratedEvent.getOldMetadata(); } @Override public GlobalTransaction getGlobalTransaction() { return decoratedEvent.getGlobalTransaction(); } @Override public boolean isOriginLocal() { return decoratedEvent.isOriginLocal(); } @Override public Type getType() { return decoratedEvent.getType(); } @Override public boolean isPre() { return decoratedEvent.isPre(); } @Override public Cache<K, V> getCache() { return decoratedEvent.getCache(); } } /** * Needed for creating event bridge. */ public static final CacheEntryRemovedEvent<?, ?> EMPTY = new CacheEntryRemovedEvent<Object, Object>() { @Override public Type getType() { return null; } @Override public Object getKey() { return null; } @Override public GlobalTransaction getGlobalTransaction() { return null; } @Override public boolean isOriginLocal() { return false; } @Override public boolean isPre() { return false; } @Override public Cache<Object, Object> getCache() { return null; } @Override public Object getValue() { return null; } @Override public Metadata getMetadata() { return null; } @Override public Metadata getOldMetadata() { return null; } @Override public Object getOldValue() { return null; } @Override public boolean isCommandRetried() { return false; } }; /** * Events which will be selected (including generic type information (<code><?, ?></code>). */ @SuppressWarnings("serial") public static final TypeLiteral<CacheEntryRemovedEvent<?, ?>> WILDCARD_TYPE = new TypeLiteral<CacheEntryRemovedEvent<?, ?>>() { }; public CacheEntryRemovedAdapter(Event<CacheEntryRemovedEvent<K, V>> event) { super(event); } @Override @CacheEntryRemoved public void fire(CacheEntryRemovedEvent<K, V> payload) { super.fire(new CDICacheEntryRemovedEvent(payload)); } }
4,264
23.94152
130
java
null
infinispan-main/cdi/embedded/src/main/java/org/infinispan/cdi/embedded/event/cache/CacheEntryActivatedAdapter.java
package org.infinispan.cdi.embedded.event.cache; import jakarta.enterprise.event.Event; import jakarta.enterprise.util.TypeLiteral; import org.infinispan.Cache; import org.infinispan.metadata.Metadata; import org.infinispan.notifications.Listener; import org.infinispan.notifications.cachelistener.annotation.CacheEntryActivated; import org.infinispan.notifications.cachelistener.event.CacheEntryActivatedEvent; import org.infinispan.transaction.xa.GlobalTransaction; /** * Event bridge for {@link org.infinispan.notifications.cachelistener.annotation.CacheEntryActivated}. * * @author Pete Muir * @author Sebastian Laskawiec * @see org.infinispan.notifications.Listener * @see org.infinispan.notifications.cachelistener.annotation.CacheEntryActivated */ @Listener public class CacheEntryActivatedAdapter<K, V> extends AbstractAdapter<CacheEntryActivatedEvent<K, V>> { /** * CDI does not allow parametrized type for events (like <code><K,V></code>). This is why this wrapped needs to be * introduced. To ensure type safety, this needs to be linked to parent class (in other words this class can not * be static). */ private class CDICacheEntryActivatedEvent implements CacheEntryActivatedEvent<K, V> { private CacheEntryActivatedEvent<K, V> decoratedEvent; private CDICacheEntryActivatedEvent(CacheEntryActivatedEvent<K, V> decoratedEvent) { this.decoratedEvent = decoratedEvent; } @Override public V getValue() { return decoratedEvent.getValue(); } @Override public K getKey() { return decoratedEvent.getKey(); } @Override public Metadata getMetadata() { return decoratedEvent.getMetadata(); } @Override public GlobalTransaction getGlobalTransaction() { return decoratedEvent.getGlobalTransaction(); } @Override public boolean isOriginLocal() { return decoratedEvent.isOriginLocal(); } @Override public Type getType() { return decoratedEvent.getType(); } @Override public boolean isPre() { return decoratedEvent.isPre(); } @Override public Cache<K, V> getCache() { return decoratedEvent.getCache(); } } /** * Needed for creating event bridge. */ public static final CacheEntryActivatedEvent<?, ?> EMPTY = new CacheEntryActivatedEvent<Object, Object>() { @Override public Type getType() { return null; } @Override public Object getKey() { return null; } @Override public GlobalTransaction getGlobalTransaction() { return null; } @Override public boolean isOriginLocal() { return false; } @Override public boolean isPre() { return false; } @Override public Cache<Object, Object> getCache() { return null; } @Override public Object getValue() { return null; } @Override public Metadata getMetadata() { return null; } }; /** * Events which will be selected (including generic type information (<code><?, ?></code>). */ @SuppressWarnings("serial") public static final TypeLiteral<CacheEntryActivatedEvent<?, ?>> WILDCARD_TYPE = new TypeLiteral<CacheEntryActivatedEvent<?, ?>>() { }; public CacheEntryActivatedAdapter(Event<CacheEntryActivatedEvent<K, V>> event) { super(event); } @Override @CacheEntryActivated public void fire(CacheEntryActivatedEvent<K, V> payload) { super.fire(new CDICacheEntryActivatedEvent(payload)); } }
3,707
25.485714
134
java
null
infinispan-main/cdi/embedded/src/main/java/org/infinispan/cdi/embedded/event/cache/CacheEntryInvalidatedAdapter.java
package org.infinispan.cdi.embedded.event.cache; import jakarta.enterprise.event.Event; import jakarta.enterprise.util.TypeLiteral; import org.infinispan.Cache; import org.infinispan.metadata.Metadata; import org.infinispan.notifications.Listener; import org.infinispan.notifications.cachelistener.annotation.CacheEntryInvalidated; import org.infinispan.notifications.cachelistener.event.CacheEntryInvalidatedEvent; import org.infinispan.transaction.xa.GlobalTransaction; /** * Event bridge for {@link org.infinispan.notifications.cachelistener.annotation.CacheEntryInvalidated}. * * @author Pete Muir * @author Sebastian Laskawiec * @see org.infinispan.notifications.Listener * @see org.infinispan.notifications.cachelistener.annotation.CacheEntryInvalidated */ @Listener public class CacheEntryInvalidatedAdapter<K, V> extends AbstractAdapter<CacheEntryInvalidatedEvent<K, V>> { /** * CDI does not allow parametrized type for events (like <code><K,V></code>). This is why this wrapped needs to be * introduced. To ensure type safety, this needs to be linked to parent class (in other words this class can not * be static). */ private class CDICacheEntryInvalidatedEvent implements CacheEntryInvalidatedEvent<K, V> { private CacheEntryInvalidatedEvent<K, V> decoratedEvent; private CDICacheEntryInvalidatedEvent(CacheEntryInvalidatedEvent<K, V> decoratedEvent) { this.decoratedEvent = decoratedEvent; } @Override public V getValue() { return decoratedEvent.getValue(); } @Override public K getKey() { return decoratedEvent.getKey(); } @Override public Metadata getMetadata() { return decoratedEvent.getMetadata(); } @Override public GlobalTransaction getGlobalTransaction() { return decoratedEvent.getGlobalTransaction(); } @Override public boolean isOriginLocal() { return decoratedEvent.isOriginLocal(); } @Override public Type getType() { return decoratedEvent.getType(); } @Override public boolean isPre() { return decoratedEvent.isPre(); } @Override public Cache<K, V> getCache() { return decoratedEvent.getCache(); } } public static final CacheEntryInvalidatedEvent<?, ?> EMPTY = new CacheEntryInvalidatedEvent<Object, Object>() { @Override public Type getType() { return null; } @Override public Object getKey() { return null; } @Override public GlobalTransaction getGlobalTransaction() { return null; } @Override public boolean isOriginLocal() { return false; } @Override public boolean isPre() { return false; } @Override public Cache<Object, Object> getCache() { return null; } @Override public Object getValue() { return null; } @Override public Metadata getMetadata() { return null; } }; /** * Events which will be selected (including generic type information (<code><?, ?></code>). */ @SuppressWarnings("serial") public static final TypeLiteral<CacheEntryInvalidatedEvent<?, ?>> WILDCARD_TYPE = new TypeLiteral<CacheEntryInvalidatedEvent<?, ?>>() { }; /** * Needed for creating event bridge. */ public CacheEntryInvalidatedAdapter(Event<CacheEntryInvalidatedEvent<K, V>> event) { super(event); } @Override @CacheEntryInvalidated public void fire(CacheEntryInvalidatedEvent<K, V> payload) { super.fire(new CDICacheEntryInvalidatedEvent(payload)); } }
3,747
25.771429
138
java
null
infinispan-main/cdi/embedded/src/main/java/org/infinispan/cdi/embedded/event/cache/CacheEntryModifiedAdapter.java
package org.infinispan.cdi.embedded.event.cache; import jakarta.enterprise.event.Event; import jakarta.enterprise.util.TypeLiteral; import org.infinispan.Cache; import org.infinispan.metadata.Metadata; import org.infinispan.notifications.Listener; import org.infinispan.notifications.cachelistener.annotation.CacheEntryModified; import org.infinispan.notifications.cachelistener.event.CacheEntryModifiedEvent; import org.infinispan.transaction.xa.GlobalTransaction; /** * Event bridge for {@link org.infinispan.notifications.cachelistener.annotation.CacheEntryModified}. * * @author Pete Muir * @author Sebastian Laskawiec * @see org.infinispan.notifications.Listener * @see org.infinispan.notifications.cachelistener.annotation.CacheEntryModified */ @Listener public class CacheEntryModifiedAdapter<K, V> extends AbstractAdapter<CacheEntryModifiedEvent<K, V>> { /** * CDI does not allow parametrized type for events (like <code><K,V></code>). This is why this wrapped needs to be * introduced. To ensure type safety, this needs to be linked to parent class (in other words this class can not * be static). */ private class CDICacheEntryModifiedEvent implements CacheEntryModifiedEvent<K, V> { private CacheEntryModifiedEvent<K, V> decoratedEvent; private CDICacheEntryModifiedEvent(CacheEntryModifiedEvent<K, V> decoratedEvent) { this.decoratedEvent = decoratedEvent; } @Override public V getValue() { return decoratedEvent.getValue(); } @Override public V getOldValue() { return decoratedEvent.getOldValue(); } @Override public V getNewValue() { return decoratedEvent.getNewValue(); } @Override public Metadata getOldMetadata() { return decoratedEvent.getOldMetadata(); } @Override public boolean isCreated() { return decoratedEvent.isCreated(); } @Override public boolean isCommandRetried() { return decoratedEvent.isCommandRetried(); } @Override public K getKey() { return decoratedEvent.getKey(); } @Override public Metadata getMetadata() { return decoratedEvent.getMetadata(); } @Override public GlobalTransaction getGlobalTransaction() { return decoratedEvent.getGlobalTransaction(); } @Override public boolean isOriginLocal() { return decoratedEvent.isOriginLocal(); } @Override public Type getType() { return decoratedEvent.getType(); } @Override public boolean isPre() { return decoratedEvent.isPre(); } @Override public Cache<K, V> getCache() { return decoratedEvent.getCache(); } } /** * Needed for creating event bridge. */ public static final CacheEntryModifiedEvent<?, ?> EMPTY = new CacheEntryModifiedEvent<Object, Object>() { @Override public Type getType() { return null; } @Override public Object getKey() { return null; } @Override public GlobalTransaction getGlobalTransaction() { return null; } @Override public boolean isOriginLocal() { return false; } @Override public boolean isPre() { return false; } @Override public Cache<Object, Object> getCache() { return null; } @Override public Object getValue() { return null; } @Override public Object getOldValue() { return null; } @Override public Object getNewValue() { return null; } @Override public Metadata getOldMetadata() { return null; } @Override public Metadata getMetadata() { return null; } @Override public boolean isCreated() { return false; } @Override public boolean isCommandRetried() { return false; } }; /** * Events which will be selected (including generic type information (<code><?, ?></code>). */ @SuppressWarnings("serial") public static final TypeLiteral<CacheEntryModifiedEvent<?, ?>> WILDCARD_TYPE = new TypeLiteral<CacheEntryModifiedEvent<?, ?>>() { }; public CacheEntryModifiedAdapter(Event<CacheEntryModifiedEvent<K, V>> event) { super(event); } @Override @CacheEntryModified public void fire(CacheEntryModifiedEvent<K, V> payload) { super.fire(new CDICacheEntryModifiedEvent(payload)); } }
4,656
23.382199
132
java
null
infinispan-main/cdi/embedded/src/main/java/org/infinispan/cdi/embedded/event/cache/CacheEntriesEvictedAdapter.java
package org.infinispan.cdi.embedded.event.cache; import java.util.Map; import jakarta.enterprise.event.Event; import jakarta.enterprise.util.TypeLiteral; import org.infinispan.Cache; import org.infinispan.notifications.Listener; import org.infinispan.notifications.cachelistener.annotation.CacheEntriesEvicted; import org.infinispan.notifications.cachelistener.event.CacheEntriesEvictedEvent; /** * Event bridge for {@link org.infinispan.notifications.cachelistener.annotation.CacheEntriesEvicted}. * * @author Pete Muir * @author Sebastian Laskawiec * @see org.infinispan.notifications.Listener * @see org.infinispan.notifications.cachelistener.annotation.CacheEntriesEvicted */ @Listener public class CacheEntriesEvictedAdapter<K, V> extends AbstractAdapter<CacheEntriesEvictedEvent<K, V>> { /** * CDI does not allow parametrized type for events (like <code><K,V></code>). This is why this wrapped needs to be * introduced. To ensure type safety, this needs to be linked to parent class (in other words this class can not * be static). */ private class CDICacheEntriesEvictedEvent implements CacheEntriesEvictedEvent<K, V> { private CacheEntriesEvictedEvent<K, V> decoratedEvent; private CDICacheEntriesEvictedEvent(CacheEntriesEvictedEvent<K, V> decoratedEvent) { this.decoratedEvent = decoratedEvent; } @Override public Map<K, V> getEntries() { return decoratedEvent.getEntries(); } @Override public Type getType() { return decoratedEvent.getType(); } @Override public boolean isPre() { return decoratedEvent.isPre(); } @Override public Cache<K, V> getCache() { return decoratedEvent.getCache(); } } /** * Needed for creating event bridge. */ public static final CacheEntriesEvictedEvent<?, ?> EMPTY = new CacheEntriesEvictedEvent<Object, Object>() { @Override public Map<Object, Object> getEntries() { return null; } @Override public Type getType() { return null; } @Override public boolean isPre() { return false; } @Override public Cache<Object, Object> getCache() { return null; } }; /** * Events which will be selected (including generic type information (<code><?, ?></code>). */ @SuppressWarnings("serial") public static final TypeLiteral<CacheEntriesEvictedEvent<?, ?>> WILDCARD_TYPE = new TypeLiteral<CacheEntriesEvictedEvent<?, ?>>() { }; public CacheEntriesEvictedAdapter(Event<CacheEntriesEvictedEvent<K, V>> event) { super(event); } @Override @CacheEntriesEvicted public void fire(CacheEntriesEvictedEvent<K, V> payload) { super.fire(new CDICacheEntriesEvictedEvent(payload)); } }
2,857
27.868687
134
java
null
infinispan-main/cdi/embedded/src/main/java/org/infinispan/cdi/embedded/event/cache/TransactionRegisteredAdapter.java
package org.infinispan.cdi.embedded.event.cache; import jakarta.enterprise.event.Event; import jakarta.enterprise.util.TypeLiteral; import org.infinispan.Cache; import org.infinispan.notifications.Listener; import org.infinispan.notifications.cachelistener.annotation.TransactionRegistered; import org.infinispan.notifications.cachelistener.event.TransactionRegisteredEvent; import org.infinispan.transaction.xa.GlobalTransaction; /** * Event bridge for {@link org.infinispan.notifications.cachelistener.annotation.TransactionRegistered}. * * @author Pete Muir * @author Sebastian Laskawiec * @see org.infinispan.notifications.Listener * @see org.infinispan.notifications.cachelistener.annotation.TransactionRegistered */ @Listener public class TransactionRegisteredAdapter<K, V> extends AbstractAdapter<TransactionRegisteredEvent<K, V>> { /** * CDI does not allow parametrized type for events (like <code><K,V></code>). This is why this wrapped needs to be * introduced. To ensure type safety, this needs to be linked to parent class (in other words this class can not * be static). */ private class CDITransactionRegisteredEvent implements TransactionRegisteredEvent<K, V> { private TransactionRegisteredEvent<K, V> decoratedEvent; private CDITransactionRegisteredEvent(TransactionRegisteredEvent<K, V> decoratedEvent) { this.decoratedEvent = decoratedEvent; } @Override public GlobalTransaction getGlobalTransaction() { return decoratedEvent.getGlobalTransaction(); } @Override public boolean isOriginLocal() { return decoratedEvent.isOriginLocal(); } @Override public Type getType() { return decoratedEvent.getType(); } @Override public boolean isPre() { return decoratedEvent.isPre(); } @Override public Cache<K, V> getCache() { return decoratedEvent.getCache(); } } /** * Needed for creating event bridge. */ public static final TransactionRegisteredEvent<?, ?> EMPTY = new TransactionRegisteredEvent<Object, Object>() { @Override public Type getType() { return null; } @Override public GlobalTransaction getGlobalTransaction() { return null; } @Override public boolean isOriginLocal() { return false; } @Override public boolean isPre() { return false; } @Override public Cache<Object, Object> getCache() { return null; } }; /** * Events which will be selected (including generic type information (<code><?, ?></code>). */ @SuppressWarnings("serial") public static final TypeLiteral<TransactionRegisteredEvent<?, ?>> WILDCARD_TYPE = new TypeLiteral<TransactionRegisteredEvent<?, ?>>() { }; public TransactionRegisteredAdapter(Event<TransactionRegisteredEvent<K, V>> event) { super(event); } @Override @TransactionRegistered public void fire(TransactionRegisteredEvent<K, V> payload) { super.fire(new CDITransactionRegisteredEvent(payload)); } }
3,167
27.8
138
java
null
infinispan-main/cdi/embedded/src/main/java/org/infinispan/cdi/embedded/event/cache/DataRehashedAdapter.java
package org.infinispan.cdi.embedded.event.cache; import java.util.Collection; import jakarta.enterprise.event.Event; import jakarta.enterprise.util.TypeLiteral; import org.infinispan.Cache; import org.infinispan.distribution.ch.ConsistentHash; import org.infinispan.notifications.Listener; import org.infinispan.notifications.cachelistener.annotation.DataRehashed; import org.infinispan.notifications.cachelistener.event.DataRehashedEvent; import org.infinispan.remoting.transport.Address; /** * Event bridge for {@link org.infinispan.notifications.cachelistener.annotation.DataRehashed}. * * @author Pete Muir * @author Sebastian Laskawiec * @see org.infinispan.notifications.Listener * @see org.infinispan.notifications.cachelistener.annotation.DataRehashed */ @Listener public class DataRehashedAdapter<K, V> extends AbstractAdapter<DataRehashedEvent<K, V>> { /** * CDI does not allow parametrized type for events (like <code><K,V></code>). This is why this wrapped needs to be * introduced. To ensure type safety, this needs to be linked to parent class (in other words this class can not * be static). */ private class CDIDataRehashedEvent implements DataRehashedEvent<K, V> { private DataRehashedEvent<K, V> decoratedEvent; private CDIDataRehashedEvent(DataRehashedEvent<K, V> decoratedEvent) { this.decoratedEvent = decoratedEvent; } @Override public Collection<Address> getMembersAtStart() { return decoratedEvent.getMembersAtStart(); } @Override public Collection<Address> getMembersAtEnd() { return decoratedEvent.getMembersAtEnd(); } @Override public ConsistentHash getConsistentHashAtStart() { return decoratedEvent.getConsistentHashAtStart(); } @Override public ConsistentHash getConsistentHashAtEnd() { return decoratedEvent.getConsistentHashAtEnd(); } @Override public ConsistentHash getUnionConsistentHash() { return decoratedEvent.getUnionConsistentHash(); } @Override public int getNewTopologyId() { return decoratedEvent.getNewTopologyId(); } @Override public Type getType() { return decoratedEvent.getType(); } @Override public boolean isPre() { return decoratedEvent.isPre(); } @Override public Cache<K, V> getCache() { return decoratedEvent.getCache(); } } public static final DataRehashedEvent<?, ?> EMPTY = new DataRehashedEvent<Object, Object>() { @Override public Collection<Address> getMembersAtStart() { return null; } @Override public Collection<Address> getMembersAtEnd() { return null; } @Override public ConsistentHash getConsistentHashAtStart() { return null; } @Override public ConsistentHash getConsistentHashAtEnd() { return null; } @Override public ConsistentHash getUnionConsistentHash() { return null; } @Override public int getNewTopologyId() { return 0; } @Override public Type getType() { return null; } @Override public boolean isPre() { return false; } @Override public Cache<Object, Object> getCache() { return null; } }; /** * Events which will be selected (including generic type information (<code><?, ?></code>). */ @SuppressWarnings("serial") public static final TypeLiteral<DataRehashedEvent<?, ?>> WILDCARD_TYPE = new TypeLiteral<DataRehashedEvent<?, ?>>() { }; public DataRehashedAdapter(Event<DataRehashedEvent<K, V>> event) { super(event); } @Override @DataRehashed public void fire(DataRehashedEvent<K, V> payload) { super.fire(new CDIDataRehashedEvent(payload)); } }
3,953
25.536913
120
java
null
infinispan-main/commons-test/src/main/java/org/infinispan/commons/logging/log4j/CompressedFileAppender.java
package org.infinispan.commons.logging.log4j; import java.io.Serializable; import java.util.HashMap; import java.util.Map; import java.util.concurrent.TimeUnit; import org.apache.logging.log4j.core.Filter; import org.apache.logging.log4j.core.Layout; import org.apache.logging.log4j.core.appender.AbstractOutputStreamAppender; import org.apache.logging.log4j.core.appender.FileManager; import org.apache.logging.log4j.core.config.Configuration; import org.apache.logging.log4j.core.config.plugins.Plugin; import org.apache.logging.log4j.core.config.plugins.PluginAttribute; import org.apache.logging.log4j.core.config.plugins.PluginConfiguration; import org.apache.logging.log4j.core.config.plugins.PluginElement; import org.apache.logging.log4j.core.config.plugins.PluginFactory; import org.apache.logging.log4j.core.layout.PatternLayout; import org.apache.logging.log4j.core.net.Advertiser; import org.apache.logging.log4j.core.util.Booleans; import org.apache.logging.log4j.core.util.Integers; /** * CompressedFile Appender. */ @Plugin(name = "CompressedFile", category = "Core", elementType = "appender", printObject = true) public final class CompressedFileAppender extends AbstractOutputStreamAppender<FileManager> { private static final int DEFAULT_BUFFER_SIZE = 8192; private final String fileName; private final Advertiser advertiser; private Object advertisement; private CompressedFileAppender(final String name, final Layout<? extends Serializable> layout, final Filter filter, final FileManager manager, final String filename, final boolean ignoreExceptions, final boolean immediateFlush, final Advertiser advertiser) { super(name, layout, filter, ignoreExceptions, immediateFlush, manager); if (advertiser != null) { final Map<String, String> configuration = new HashMap<>(layout.getContentFormat()); configuration.putAll(manager.getContentFormat()); configuration.put("contentType", layout.getContentType()); configuration.put("name", name); advertisement = advertiser.advertise(configuration); } this.fileName = filename; this.advertiser = advertiser; } @Override public boolean stop(long timeout, TimeUnit timeUnit, boolean changeLifeCycleState) { super.stop(timeout, timeUnit, false); if (advertiser != null) { advertiser.unadvertise(advertisement); } if (changeLifeCycleState) { setStopped(); } return true; } /** * Returns the file name this appender is associated with. * * @return The File name. */ public String getFileName() { return this.fileName; } /** * Create a File Appender. * * @param fileName The name and path of the file. * @param append "True" if the file should be appended to, "false" if it should be overwritten. * The default is "true". * @param locking "True" if the file should be locked. The default is "false". * @param name The name of the Appender. * @param immediateFlush "true" if the contents should be flushed on every write, "false" otherwise. The default * is "true". * @param ignore If {@code "true"} (default) exceptions encountered when appending events are logged; * otherwise * they are propagated to the caller. * @param bufferedIo "true" if I/O should be buffered, "false" otherwise. The default is "true". * @param bufferSizeStr buffer size for buffered IO (default is 8192). * @param layout The layout to use to format the event. If no layout is provided the default PatternLayout * will be used. * @param filter The filter, if any, to use. * @param advertise "true" if the appender configuration should be advertised, "false" otherwise. * @param advertiseUri The advertised URI which can be used to retrieve the file contents. * @param config The Configuration * @return The FileAppender. */ @PluginFactory public static CompressedFileAppender createAppender( // @formatter:off @PluginAttribute("fileName") final String fileName, @PluginAttribute("append") final String append, @PluginAttribute("locking") final String locking, @PluginAttribute("name") final String name, @PluginAttribute("immediateFlush") final String immediateFlush, @PluginAttribute("ignoreExceptions") final String ignore, @PluginAttribute("bufferedIo") final String bufferedIo, @PluginAttribute("bufferSize") final String bufferSizeStr, @PluginElement("Layout") Layout<? extends Serializable> layout, @PluginElement("Filter") final Filter filter, @PluginAttribute("advertise") final String advertise, @PluginAttribute("advertiseUri") final String advertiseUri, @PluginAttribute(value = "compressionLevel", defaultInt = 3) final int compressionLevel, @PluginConfiguration final Configuration config) { // @formatter:on final boolean isAppend = Booleans.parseBoolean(append, true); final boolean isLocking = Boolean.parseBoolean(locking); boolean isBuffered = Booleans.parseBoolean(bufferedIo, true); final boolean isAdvertise = Boolean.parseBoolean(advertise); if (isLocking && isBuffered) { if (bufferedIo != null) { LOGGER.warn("Locking and buffering are mutually exclusive. No buffering will occur for " + fileName); } isBuffered = false; } final int bufferSize = Integers.parseInt(bufferSizeStr, DEFAULT_BUFFER_SIZE); if (!isBuffered && bufferSize > 0) { LOGGER.warn("The bufferSize is set to {} but bufferedIO is not true: {}", bufferSize, bufferedIo); } final boolean isFlush = Booleans.parseBoolean(immediateFlush, true); final boolean ignoreExceptions = Booleans.parseBoolean(ignore, true); if (name == null) { LOGGER.error("No name provided for CompressedFileAppender"); return null; } if (fileName == null) { LOGGER.error("No filename provided for CompressedFileAppender with name {}", name); return null; } if (!fileName.endsWith(".gz")) { LOGGER.error("Filename {} does not end in .gz for CompressedFileAppender with name {}", fileName, name); return null; } if (layout == null) { layout = PatternLayout.createDefaultLayout(); } if (compressionLevel < 1 || 9 < compressionLevel) { LOGGER.error("compressionLevel {} is not between 1..9 for CompressedFileAppender with name {}", compressionLevel, name); return null; } final CompressedFileManager manager = CompressedFileManager.getFileManager(fileName, isAppend, isLocking, isBuffered, advertiseUri, layout, bufferSize, compressionLevel); if (manager == null) { return null; } return new CompressedFileAppender(name, layout, filter, manager, fileName, ignoreExceptions, isFlush, isAdvertise ? config.getAdvertiser() : null); } }
7,518
45.41358
119
java
null
infinispan-main/commons-test/src/main/java/org/infinispan/commons/logging/log4j/CompressedFileManager.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.commons.logging.log4j; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.io.Serializable; import java.util.zip.GZIPOutputStream; import org.apache.logging.log4j.core.Layout; import org.apache.logging.log4j.core.appender.FileManager; import org.apache.logging.log4j.core.appender.ManagerFactory; /** * Manages actual File I/O for the CompressedFileAppender. */ public class CompressedFileManager extends FileManager { protected CompressedFileManager(String fileName, OutputStream os, boolean append, boolean locking, String advertiseURI, Layout<? extends Serializable> layout, int bufferSize, boolean writerHeader) { super(fileName, os, append, locking, advertiseURI, layout, bufferSize, writerHeader); } private static final CompressedFileManagerFactory FACTORY = new CompressedFileManagerFactory(); /** * Returns the FileManager. * * @param fileName * The name of the file to manage. * @param append * true if the file should be appended to, false if it should be overwritten. * @param locking * true if the file should be locked while writing, false otherwise. * @param bufferedIo * true if the contents should be buffered as they are written. * @param advertiseUri * the URI to use when advertising the file * @param layout * The layout * @param bufferSize * buffer size for buffered IO * @param compressionLevel * gzip compression level * @return A FileManager for the File. */ public static CompressedFileManager getFileManager(final String fileName, final boolean append, boolean locking, final boolean bufferedIo, final String advertiseUri, final Layout<? extends Serializable> layout, final int bufferSize, int compressionLevel) { if (locking && bufferedIo) { locking = false; } return (CompressedFileManager) getManager(fileName, new FactoryData(append, locking, bufferedIo, bufferSize, advertiseUri, layout, compressionLevel), FACTORY); } /** * Factory Data. */ private static class FactoryData { private final boolean append; private final boolean locking; private final boolean bufferedIO; private final int bufferSize; private final String advertiseURI; private final Layout<? extends Serializable> layout; public final int compressionLevel; /** * Constructor. * @param append * Append status. * @param locking * Locking status. * @param bufferedIO * Buffering flag. * @param bufferSize * Buffer size. * @param advertiseURI * @param compressionLevel * gzip compression level */ public FactoryData(final boolean append, final boolean locking, final boolean bufferedIO, final int bufferSize, final String advertiseURI, final Layout<? extends Serializable> layout, int compressionLevel) { this.append = append; this.locking = locking; this.bufferedIO = bufferedIO; this.bufferSize = bufferSize; this.advertiseURI = advertiseURI; this.layout = layout; this.compressionLevel = compressionLevel; } } /** * Factory to create a FileManager. */ private static class CompressedFileManagerFactory implements ManagerFactory<CompressedFileManager, FactoryData> { /** * Create a FileManager. * * @param name * The name of the File. * @param data * The FactoryData * @return The FileManager for the File. */ @Override public CompressedFileManager createManager(final String name, final FactoryData data) { final File file = new File(name); final File parent = file.getParentFile(); if (null != parent && !parent.exists()) { parent.mkdirs(); } OutputStream os; try { os = new FileOutputStream(name, data.append); int bufferSize = data.bufferSize; os = new GZIPOutputStream(os, bufferSize, false) {{ def.setLevel(data.compressionLevel); }}; boolean writeHeader = !data.append || !file.exists(); return new CompressedFileManager(name, os, data.append, data.locking, data.advertiseURI, data.layout, bufferSize, writeHeader); } catch (final IOException ex) { LOGGER.error("FileManager (" + name + ") " + ex); } return null; } } }
5,910
37.135484
201
java
null
infinispan-main/commons-test/src/main/java/org/infinispan/commons/logging/log4j/ThreadNameFilter.java
package org.infinispan.commons.logging.log4j; import java.util.regex.Pattern; import org.apache.logging.log4j.Level; import org.apache.logging.log4j.Marker; import org.apache.logging.log4j.core.Filter; import org.apache.logging.log4j.core.LogEvent; import org.apache.logging.log4j.core.Logger; import org.apache.logging.log4j.core.config.plugins.Plugin; import org.apache.logging.log4j.core.config.plugins.PluginAttribute; import org.apache.logging.log4j.core.config.plugins.PluginFactory; import org.apache.logging.log4j.core.filter.AbstractFilter; import org.apache.logging.log4j.message.Message; /** * Log4j {@link Filter} that only allow events from threads matching a regular expression. * Events with a level greater than {@code threshold} are always logged. * * @author Dan Berindei * @since 5.2 */ @Plugin(name = "ThreadNameFilter", category = "Core", elementType = Filter.ELEMENT_TYPE, printObject = true) public final class ThreadNameFilter extends AbstractFilter { private final Level level; private final Pattern includePattern; private ThreadNameFilter(Level level, String includeRegex) { this.level = level == null ? Level.DEBUG : level; this.includePattern = Pattern.compile(includeRegex == null ? ".*" : includeRegex); } @Override public Result filter(Logger logger, Level level, Marker marker, String msg, Object... params) { return filter(level, Thread.currentThread().getName()); } @Override public Result filter(Logger logger, Level level, Marker marker, Object msg, Throwable t) { return filter(level, Thread.currentThread().getName()); } @Override public Result filter(Logger logger, Level level, Marker marker, Message msg, Throwable t) { return filter(level, Thread.currentThread().getName()); } @Override public Result filter(LogEvent event) { return filter(event.getLevel(), event.getThreadName()); } private Result filter(Level level, String threadName) { if (level.isMoreSpecificThan(this.level)) { return Result.NEUTRAL; } else if (includePattern == null || includePattern.matcher(threadName).find()) { return Result.NEUTRAL; } else { return Result.DENY; } } @Override public String toString() { return "ThreadNameFilter{level=" + level + ", include=" + includePattern.pattern() + '}'; } /** * Create a ThreadNameFilter. * * @param level The log Level. * @param include The regex * @return The created filter. */ @PluginFactory public static ThreadNameFilter createFilter(@PluginAttribute("level") Level level, @PluginAttribute("include") String include) { return new ThreadNameFilter(level, include); } }
2,800
33.158537
108
java
null
infinispan-main/commons-test/src/main/java/org/infinispan/commons/logging/log4j/BoundedPurgePolicy.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.commons.logging.log4j; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.Map; import java.util.concurrent.TimeUnit; import org.apache.logging.log4j.core.AbstractLifeCycle; import org.apache.logging.log4j.core.Core; import org.apache.logging.log4j.core.LogEvent; import org.apache.logging.log4j.core.appender.routing.PurgePolicy; import org.apache.logging.log4j.core.appender.routing.RoutingAppender; import org.apache.logging.log4j.core.config.plugins.Plugin; import org.apache.logging.log4j.core.config.plugins.PluginAttribute; import org.apache.logging.log4j.core.config.plugins.PluginFactory; /** * Policy is purging appenders that were not in use specified time, or sooner if there are too many active appenders */ @Plugin(name = "BoundedPurgePolicy", category = Core.CATEGORY_NAME, printObject = true) public class BoundedPurgePolicy extends AbstractLifeCycle implements PurgePolicy { public static final String VALUE = ""; private final int maxSize; private final Map<String, String> appendersUsage; private String excludePrefix; private RoutingAppender routingAppender; public BoundedPurgePolicy(final int maxSize, String excludePrefix) { this.maxSize = maxSize; this.appendersUsage = new LinkedHashMap<>((int) (maxSize * 0.75f), 0.75f, true); this.excludePrefix = excludePrefix; } @Override public void initialize(@SuppressWarnings("hiding") final RoutingAppender routingAppender) { this.routingAppender = routingAppender; } @Override public boolean stop(final long timeout, final TimeUnit timeUnit) { setStopped(); return true; } /** * Delete the oldest appenders (sorted by their last access time) until there are maxSize appenders or less. */ @Override public void purge() { synchronized (this) { Iterator<String> iterator = appendersUsage.keySet().iterator(); while (appendersUsage.size() > maxSize) { String key = iterator.next(); LOGGER.debug("Removing appender " + key); iterator.remove(); routingAppender.getAppenders().get(key).getAppender().stop(); routingAppender.deleteAppender(key); } } } @Override public void update(final String key, final LogEvent event) { if (key != null && key.startsWith(excludePrefix)) { return; } synchronized (this) { String previous = appendersUsage.putIfAbsent(key, VALUE); if (previous == null) { purge(); } } } /** * Create the PurgePolicy * * @param size the maximum number of appenders to keep active at any moment * @param excludePrefix a prefix to exclude from eviction, defaults to "${" for missing key. * @return The Routes container. */ @PluginFactory public static PurgePolicy createPurgePolicy( @PluginAttribute("size") final int size, @PluginAttribute(value = "excludePrefix", defaultString = "${") final String excludePrefix) { return new BoundedPurgePolicy(size, excludePrefix); } @Override public String toString() { return "size=" + maxSize; } }
4,019
34.892857
116
java
null
infinispan-main/commons-test/src/main/java/org/infinispan/commons/logging/log4j/TestNameLookup.java
package org.infinispan.commons.logging.log4j; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.logging.log4j.core.LogEvent; import org.apache.logging.log4j.core.config.plugins.Plugin; import org.apache.logging.log4j.core.lookup.StrLookup; @Plugin(name = "testName", category = "Lookup") public class TestNameLookup implements StrLookup { Map<String, String> cache = new ConcurrentHashMap<>(); Pattern pattern = Pattern.compile("\\b(\\w+Test)\\b"); public static final String TEST_NAME = "testName"; public String lookup(String key) { return TEST_NAME; } public String lookup(LogEvent event, String key) { String testName = cache.computeIfAbsent(event.getThreadName(), threadName -> { Matcher matcher = pattern.matcher(event.getThreadName()); return matcher.find() ? matcher.group(1) : null; }); return testName; } }
987
30.870968
84
java
null
infinispan-main/commons-test/src/main/java/org/infinispan/commons/test/RunningTestsRegistry.java
package org.infinispan.commons.test; import static java.util.concurrent.TimeUnit.SECONDS; import java.io.BufferedReader; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.StringWriter; import java.lang.management.LockInfo; import java.lang.management.ManagementFactory; import java.lang.management.MonitorInfo; import java.lang.management.ThreadInfo; import java.lang.management.ThreadMXBean; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import org.infinispan.commons.test.skip.OS; /** * Keep track of running tests and interrupt them if they take more than {@link #MAX_TEST_SECONDS} seconds. * * @author Dan Berindei * @since 9.2 */ class RunningTestsRegistry { private static final long MAX_TEST_SECONDS = Long.parseUnsignedLong(System.getProperty("infinispan.test.maxTestSeconds", "300")); private static final ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor( r -> new Thread(r, "RunningTestsRegistry-Worker")); private static final Map<Thread, ScheduledFuture<?>> scheduledTasks = new ConcurrentHashMap<>(); static void unregisterThreadWithTest() { ScheduledFuture<?> killTask = scheduledTasks.remove(Thread.currentThread()); if (killTask != null) { killTask.cancel(false); } } static void registerThreadWithTest(String testName, String simpleName) { Thread testThread = Thread.currentThread(); ScheduledFuture<?> future = executor.schedule( () -> killLongTest(testThread, testName, simpleName), MAX_TEST_SECONDS, SECONDS); scheduledTasks.put(testThread, future); } private static void killLongTest(Thread testThread, String testName, String simpleName) { RuntimeException exception = new RuntimeException(String.format("Test timed out after %d seconds", MAX_TEST_SECONDS)); exception.setStackTrace(testThread.getStackTrace()); TestSuiteProgress.fakeTestFailure(testName, exception); writeJUnitReport(testName, exception); List<String> pids = collectChildProcesses(); String safeTestName = simpleName.replaceAll("[^a-zA-Z0-9=]", "_"); dumpThreads(safeTestName, pids); killTest(testThread, pids); } private static void writeJUnitReport(String testName, RuntimeException exception) { try { File reportsDir = new File("target/surefire-reports"); if (!reportsDir.exists() && !reportsDir.mkdirs()) { throw new IOException("Cannot create report directory " + reportsDir.getAbsolutePath()); } PolarionJUnitXMLWriter writer = new PolarionJUnitXMLWriter( new File(reportsDir, "TEST-" + testName + "-Timeout.xml")); String property = System.getProperty("infinispan.modulesuffix"); String moduleName = property != null ? property.substring(1) : ""; writer.start(moduleName, 1, 0, 1, 0, false); StringWriter exceptionWriter = new StringWriter(); exception.printStackTrace(new PrintWriter(exceptionWriter)); writer.writeTestCase("Timeout", testName, 0, PolarionJUnitXMLWriter.Status.FAILURE, exceptionWriter.toString(), exception.getClass().getName(), exception.getMessage()); writer.close(); } catch (Exception e) { throw new RuntimeException("Error reporting thread leaks", e); } } private static List<String> collectChildProcesses() { try { String jvmName = ManagementFactory.getRuntimeMXBean().getName(); String ppid = jvmName.split("@")[0]; List<String> pids = new ArrayList<>(Collections.singletonList(ppid)); int index = 0; while (index < pids.size()) { String pid = pids.get(index); if (OS.getCurrentOs() != OS.WINDOWS) { // List pid and command name of child processes Process ps = new ProcessBuilder() .command("ps", "-o", "pid=,comm=", "--ppid", pid) .start(); try (BufferedReader psOutput = new BufferedReader(new InputStreamReader(ps.getInputStream()))) { psOutput.lines().forEach(line -> { // Add children to the list excluding the ps command we just ran String[] pidAndCommand = line.trim().split("\\s+"); if (!"ps".equals(pidAndCommand[1])) { pids.add(pidAndCommand[0]); } }); } ps.waitFor(10, SECONDS); } index++; } return pids; } catch (Exception e) { System.err.println("Error collecting child processes:"); e.printStackTrace(System.err); return Collections.emptyList(); } } private static void dumpThreads(String safeTestName, List<String> pids) { try { String extension = OS.getCurrentOs() == OS.WINDOWS ? ".exe" : ""; String javaHome = System.getProperty("java.home"); File jstackFile = new File(javaHome, "bin/jstack" + extension); if (!jstackFile.canExecute()) { jstackFile = new File(javaHome, "../bin/jstack" + extension); } LocalDateTime now = LocalDateTime.now(); if (jstackFile.canExecute() && !pids.isEmpty()) { for (String pid : pids) { File dumpFile = new File(String.format("threaddump-%1$s-%2$tY%2$tm%2$td-%2$tH%2$tM-%3$s.log", safeTestName, now, pid)); System.err.printf("Dumping threads of process %s to %s%n", pid, dumpFile.getAbsolutePath()); Process jstack = new ProcessBuilder() .command(jstackFile.getAbsolutePath(), "-l", pid) .redirectOutput(dumpFile) .start(); jstack.waitFor(10, SECONDS); } } else { File dumpFile = new File(String.format("threaddump-%1$s-%2$tY%2$tm%2$td-%2$tH%2$tM.log", safeTestName, now)); System.err.printf("Cannot find jstack in %s, programmatically dumping thread stacks of testsuite process to %s%n", javaHome, dumpFile.getAbsolutePath()); ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean(); try (PrintWriter writer = new PrintWriter(new FileWriter(dumpFile))) { // 2019-02-05 14:03:11 writer.printf("%1$tF %1$tT\nTest thread dump:%n%n", now); ThreadInfo[] threads = threadMXBean.dumpAllThreads(true, true); for (ThreadInfo thread : threads) { dumpThread(writer, thread); } } } } catch (Exception e) { System.err.println("Error dumping threads:"); e.printStackTrace(System.err); } } private static void killTest(Thread testThread, List<String> pids) { try { // Interrupt the test thread testThread.interrupt(); System.err.printf("Interrupted thread %s (%d).%n", testThread.getName(), testThread.getId()); testThread.join(SECONDS.toMillis(1)); if (testThread.isAlive()) { // Thread.interrupt() doesn't work if the thread is waiting to enter a synchronized block or in lock() // Thread.stop() works for lock(), but not if the thread is waiting to enter a synchronized block // So we just kill the fork and its children instead Process kill; List<String> command; if (OS.getCurrentOs() == OS.WINDOWS) { command = new ArrayList<>(Arrays.asList("taskkill", "/t", "/f")); for (String pid : pids) { command.add("/pid"); command.add(pid); } kill = new ProcessBuilder() .command(command) .start(); } else { command = new ArrayList<>(Collections.singletonList("kill")); command.addAll(pids); kill = new ProcessBuilder() .command(command) .start(); } kill.waitFor(10, SECONDS); if (kill.exitValue() == 0) { System.err.printf("Killed processes %s%n", String.join(" ", pids)); } else { System.err.printf("Failed to kill processes, exit code %d from command %s\n", kill.exitValue(), command); } } } catch (Exception e) { System.err.println("Error killing test:"); e.printStackTrace(System.err); } } private static void dumpThread(PrintWriter writer, ThreadInfo thread) { // "management I/O-2" tid=0x00007fe6a8134000 runnable // [0x00007fe64e4db000] // java.lang.Thread.State:RUNNABLE // - waiting to lock <0x00007fa12e5a5d40> (a java.lang.Object) // - waiting on <0x00007fb2c4017ba0> (a java.util.LinkedList) // - parking to wait for <0x00007fc96bd87cf0> (a java.util.concurrent.CompletableFuture$Signaller) // - locked <0x00007fb34c037e20> (a com.arjuna.ats.arjuna.coordinator.TransactionReaper) writer.printf("\"%s\" #%s prio=0 tid=0x%x nid=NA %s%n", thread.getThreadName(), thread.getThreadId(), thread.getThreadId(), thread.getThreadState().toString().toLowerCase()); writer.printf(" java.lang.Thread.State: %s%n", thread.getThreadState()); LockInfo blockedLock = thread.getLockInfo(); StackTraceElement[] s = thread.getStackTrace(); MonitorInfo[] monitors = thread.getLockedMonitors(); for (int i = 0; i < s.length; i++) { StackTraceElement ste = s[i]; writer.printf("\tat %s\n", ste); if (i == 0 && blockedLock != null) { boolean parking = ste.isNativeMethod() && ste.getMethodName().equals("park"); writer.printf("\t- %s <0x%x> (a %s)%n", blockedState(thread, blockedLock, parking), blockedLock.getIdentityHashCode(), blockedLock.getClassName()); } if (monitors != null) { for (MonitorInfo monitor : monitors) { if (monitor.getLockedStackDepth() == i) { writer.printf("\t- locked <0x%x> (a %s)%n", monitor.getIdentityHashCode(), monitor.getClassName()); } } } } writer.println(); LockInfo[] synchronizers = thread.getLockedSynchronizers(); if (synchronizers != null && synchronizers.length > 0) { writer.print("\n Locked ownable synchronizers:\n"); for (LockInfo synchronizer : synchronizers) { writer.printf("\t- <0x%x> (a %s)%n", synchronizer.getIdentityHashCode(), synchronizer.getClassName()); } writer.println(); } } private static String blockedState(ThreadInfo thread, LockInfo blockedLock, boolean parking) { String state; if (blockedLock != null) { if (thread.getThreadState().equals(Thread.State.BLOCKED)) { state = "waiting to lock"; } else if (parking) { state = "parking to wait for"; } else { state = "waiting on"; } } else { state = null; } return state; } }
11,888
42.549451
165
java