org.atteo.classindex.ClassIndex Java Examples

The following examples show how to use org.atteo.classindex.ClassIndex. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: AbstractGlobalJsonParsableRegistry.java    From ditto with Eclipse Public License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked") //Suppressed because the cast of cls is ensured by the two filters before.
private static <T, A extends Annotation> Map<String, JsonParsable<T>> initAnnotationBasedParseStrategies(
        final Class<T> baseClass,
        final Class<A> annotationClass,
        final AbstractAnnotationBasedJsonParsableFactory<T, A> annotationBasedJsonParsableFactory) {

    final Map<String, JsonParsable<T>> parseRegistries = new HashMap<>();
    final Iterable<Class<?>> annotatedClasses = ClassIndex.getAnnotated(annotationClass);

    StreamSupport.stream(annotatedClasses.spliterator(), false)
            .filter(baseClass::isAssignableFrom)
            .filter(cls -> !baseClass.equals(cls))
            .map(cls -> (Class<? extends T>) cls)
            .forEach(classToParse -> {
                final A fromJsonAnnotation = classToParse.getAnnotation(annotationClass);

                final AnnotationBasedJsonParsable<T> strategy =
                        annotationBasedJsonParsableFactory.fromAnnotation(fromJsonAnnotation, classToParse);
                parseRegistries.put(strategy.getKey(), strategy);
                parseRegistries.put(strategy.getV1FallbackKey(), strategy);
            });

    return parseRegistries;
}
 
Example #2
Source File: SiddhiExtensionLoader.java    From siddhi with Apache License 2.0 6 votes vote down vote up
private void removeExtensions(Bundle bundle) {
    bundleExtensions.entrySet().stream().filter(entry -> entry.getValue() ==
            bundle.getBundleId()).forEachOrdered(entry -> {
        siddhiExtensionsMap.remove(entry.getKey());
    });
    bundleExtensions.entrySet().removeIf(entry -> entry.getValue() ==
            bundle.getBundleId());
    BundleWiring bundleWiring = bundle.adapt(BundleWiring.class);
    if (bundleWiring != null) {
        ClassLoader classLoader = bundleWiring.getClassLoader();
        Iterable<Class<?>> extensions = ClassIndex.getAnnotated(Extension.class, classLoader);
        for (Class extension : extensions) {
            Extension siddhiExtensionAnnotation = (Extension) extension.getAnnotation(Extension.class);
            if (!siddhiExtensionAnnotation.namespace().isEmpty()) {
                String key = siddhiExtensionAnnotation.namespace() + SiddhiConstants.EXTENSION_SEPARATOR +
                        siddhiExtensionAnnotation.name();
                removeFromExtensionHolderMap(key, extension, extensionHolderConcurrentHashMap);
            }
        }
    }
}
 
Example #3
Source File: GlobalErrorRegistryTestCases.java    From ditto with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void allExceptionsRegistered() {
    final Iterable<Class<? extends DittoRuntimeException>> subclassesOfDRE =
            ClassIndex.getSubclasses(DittoRuntimeException.class);

    for (Class<? extends DittoRuntimeException> subclassOfDRE : subclassesOfDRE) {
        if (DittoJsonException.class.equals(subclassOfDRE)) {
            //DittoJsonException is another concept than the rest of DittoRuntimeExceptions
            continue;
        }

        assertThat(subclassOfDRE.isAnnotationPresent(JsonParsableException.class))
                .as("Check that '%s' is annotated with JsonParsableException.", subclassOfDRE.getName())
                .isTrue();
    }
}
 
Example #4
Source File: SiddhiExtensionLoader.java    From siddhi with Apache License 2.0 6 votes vote down vote up
/**
 * Load Siddhi extensions in java non OSGi environment.
 *
 * @param siddhiExtensionsMap reference map for the Siddhi extension
 * @param extensionHolderMap reference map for the Siddhi extension holder
 */
private static void loadLocalExtensions(Map<String, Class> siddhiExtensionsMap,
                                        ConcurrentHashMap<Class, AbstractExtensionHolder> extensionHolderMap) {
    Iterable<Class<?>> extensions = ClassIndex.getAnnotated(Extension.class);
    for (Class extension : extensions) {
        addExtensionToMap(extension, siddhiExtensionsMap, extensionHolderMap);
    }

    // load extensions related to incremental aggregation
    addExtensionToMap("incrementalAggregator:startTimeEndTime",
            IncrementalStartTimeEndTimeFunctionExecutor.class, siddhiExtensionsMap);
    addExtensionToMap("incrementalAggregator:timestampInMilliseconds",
            IncrementalUnixTimeFunctionExecutor.class, siddhiExtensionsMap);
    addExtensionToMap("incrementalAggregator:getTimeZone",
            IncrementalTimeGetTimeZone.class, siddhiExtensionsMap);
    addExtensionToMap("incrementalAggregator:getAggregationStartTime",
            IncrementalAggregateBaseTimeFunctionExecutor.class, siddhiExtensionsMap);
    addExtensionToMap("incrementalAggregator:shouldUpdate",
            IncrementalShouldUpdateFunctionExecutor.class, siddhiExtensionsMap);
}
 
Example #5
Source File: GlobalEventRegistryTestCases.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
private static List<Class<? extends Event>> getEventSubclasses() {
    return StreamSupport.stream(ClassIndex.getSubclasses(Event.class).spliterator(), true)
            .filter(c -> {
                final int m = c.getModifiers();
                return !(Modifier.isAbstract(m) || Modifier.isInterface(m));
            }).collect(Collectors.toList());
}
 
Example #6
Source File: ConfigSerializer.java    From git-as-svn with GNU General Public License v2.0 5 votes vote down vote up
@NotNull
private static Map<String, Class<?>> configTypes() {
  final Map<String, Class<?>> result = new TreeMap<>();
  for (Class<?> type : ClassIndex.getAnnotated(ConfigType.class)) {
    ConfigType annotation = type.getAnnotation(ConfigType.class);
    final String name = annotation.value();
    if (result.put(TAG_PREFIX + name, type) != null) {
      throw new IllegalStateException("Found duplicate type name: " + name);
    }
  }
  return result;
}
 
Example #7
Source File: SiddhiExtensionLoader.java    From siddhi with Apache License 2.0 5 votes vote down vote up
private void addExtensions(Bundle bundle) {
    ClassLoader classLoader = bundle.adapt(BundleWiring.class).getClassLoader();
    Iterable<Class<?>> extensions = ClassIndex.getAnnotated(Extension.class, classLoader);
    for (Class extension : extensions) {
        addExtensionToMap(extension, siddhiExtensionsMap, extensionHolderConcurrentHashMap);
        bundleExtensions.put(extension, (int) bundle.getBundleId());
    }
}
 
Example #8
Source File: ResourcesLoader.java    From panda with Apache License 2.0 5 votes vote down vote up
public void load(ModulePath modulePath, TypeLoader typeLoader) {
    for (Class<?> annotatedClass : ClassIndex.getAnnotated(InternalModuleInfo.class)) {
        try {
            load(modulePath, typeLoader, annotatedClass);
        } catch (Exception e) {
            throw new PandaFrameworkException("Cannot load internal module", e);
        }
    }
}
 
Example #9
Source File: DefaultMessageMapperFactory.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
private static Map<String, Class<?>> tryToLoadPayloadMappers() {
    try {
        final Iterable<Class<?>> payloadMappers = ClassIndex.getAnnotated(PayloadMapper.class);
        final Map<String, Class<?>> mappers = new HashMap<>();
        for (final Class<?> payloadMapper : payloadMappers) {
            if (!MessageMapper.class.isAssignableFrom(payloadMapper)) {
                throw new IllegalStateException("The class " + payloadMapper.getName() + " does not implement " +
                        MessageMapper.class.getName());
            }
            final PayloadMapper annotation = payloadMapper.getAnnotation(PayloadMapper.class);
            if (annotation == null) {
                throw new IllegalStateException("The mapper " + payloadMapper.getName() + " is not annotated with" +
                        " @PayloadMapper.");
            }
            final String[] aliases = annotation.alias();
            if (aliases.length == 0) {
                throw new IllegalStateException("No alias configured for " + payloadMapper.getName());
            }

            Stream.of(aliases).forEach(alias -> {
                if (null != mappers.get(alias)) {
                    throw new IllegalStateException("Mapper alias <" + alias + "> was already registered and is " +
                            "tried to register again for " + payloadMapper.getName());
                }
                mappers.put(alias, payloadMapper);
            });
        }
        return mappers;
    } catch (final Exception e) {
        final String message = e.getClass().getCanonicalName() + ": " + e.getMessage();
        throw MessageMapperConfigurationFailedException.newBuilder(message).build();
    }
}
 
Example #10
Source File: GlobalCommandRegistryTestCases.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void allCommandsRegistered() {
    StreamSupport.stream(ClassIndex.getSubclasses(Command.class).spliterator(), true)
            .filter(c -> {
                final int m = c.getModifiers();
                return !(Modifier.isAbstract(m) || Modifier.isInterface(m) || isExcluded(c));
            })
            .forEach(c -> assertThat(c.isAnnotationPresent(JsonParsableCommand.class))
                    .as("Check that '%s' is annotated with JsonParsableCommand.", c.getName())
                    .isTrue());
}
 
Example #11
Source File: ElideAutoConfiguration.java    From elide-spring-boot with Apache License 2.0 5 votes vote down vote up
/**
 * Side effect: populate checks.
 */
private void scanChecks(ConcurrentHashMap<String, Class<? extends Check>> checks) {
  for (Class<?> clazz : ClassIndex.getAnnotated(ElideCheck.class)) {
    ElideCheck elideCheck = clazz.getAnnotation(ElideCheck.class);
    if (Check.class.isAssignableFrom(clazz)) {
      logger.debug("Register Elide Check [{}] with expression [{}]",
          clazz.getCanonicalName(), elideCheck.value());
      checks.put(elideCheck.value(), clazz.asSubclass(Check.class));
    } else {
      throw new RuntimeException("The class[" + clazz.getCanonicalName()
          + "] being annotated with @ElideCheck must be a Check.");
    }
  }
}
 
Example #12
Source File: GlobalCommandResponseRegistryTestCases.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void allCommandResponsesRegistered() {
    StreamSupport.stream(ClassIndex.getSubclasses(CommandResponse.class).spliterator(), true)
            .filter(c -> {
                final int m = c.getModifiers();
                return !(Modifier.isAbstract(m) || Modifier.isInterface(m));
            })
            .filter(c -> !Acknowledgements.class.isAssignableFrom(c)) // exclude implementations of this very special CommandResponse -> it is registered differently
            .filter(c -> !Acknowledgement.class.isAssignableFrom(c)) // exclude implementations of this very special CommandResponse -> it is registered differently
            .forEach(c -> assertThat(c.isAnnotationPresent(JsonParsableCommandResponse.class))
                    .as("Check that '%s' is annotated with JsonParsableCommandResponse.", c.getName())
                    .isTrue());
}
 
Example #13
Source File: GlobalCommandResponseRegistryTestCases.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
@Before
public void setup() {
    jsonParsableCommandResponses =
            StreamSupport.stream(ClassIndex.getAnnotated(JsonParsableCommandResponse.class).spliterator(), true)
                    .filter(c -> !"TestCommandResponse".equals(c.getSimpleName()))
                    .collect(Collectors.toList());
}
 
Example #14
Source File: GlobalErrorRegistryTestCases.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void allRegisteredExceptionsContainAMethodToParseFromJson() throws NoSuchMethodException {
    final Iterable<Class<?>> jsonParsableExceptions = ClassIndex.getAnnotated(JsonParsableException.class);

    for (Class<?> jsonParsableException : jsonParsableExceptions) {
        final JsonParsableException annotation = jsonParsableException.getAnnotation(JsonParsableException.class);
        assertAnnotationIsValid(annotation, jsonParsableException);
    }
}
 
Example #15
Source File: GlobalErrorRegistryTestCases.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * This test should enforce to keep {@code samples} up to date.
 * If this test fails add an exception of each missing package to samples.
 */
@Test
public void ensureSamplesAreComplete() {
    final Set<Package> packagesOfAnnotated =
            getPackagesDistinct(ClassIndex.getAnnotated(JsonParsableException.class));
    final Set<Package> packagesOfSamples = getPackagesDistinct(samples);

    assertThat(packagesOfSamples).containsAll(packagesOfAnnotated);
}
 
Example #16
Source File: ElideAutoConfiguration.java    From elide-spring-boot with Apache License 2.0 5 votes vote down vote up
/**
 * Side effect: bind triggers on entityDictionary.
 */
private void scanLifeCycleHook(EntityDictionary entityDictionary, ApplicationContext context) {
  for (Class<?> clazz : ClassIndex.getAnnotated(ElideHook.class)) {
    if (LifeCycleHook.class.isAssignableFrom(clazz)) {
      ElideHook elideHook = clazz.getAnnotation(ElideHook.class);
      // get generic entity type
      Class<?> entity = null;
      for (Type genericInterface : clazz.getGenericInterfaces()) {
        if (genericInterface instanceof ParameterizedType
            && ((ParameterizedType) genericInterface).getRawType().equals(LifeCycleHook.class)) {
          Type[] genericTypes = ((ParameterizedType) genericInterface).getActualTypeArguments();
          entity = (Class<?>) genericTypes[0];
        }
      }
      if (entity == null) {
        throw new RuntimeException("entity is null, this should not be thrown");
      }

      if (elideHook.fieldOrMethodName().equals("")) {
        entityDictionary.bindTrigger(entity, elideHook.lifeCycle(),
            (LifeCycleHook) context.getBean(clazz));
      } else {
        entityDictionary.bindTrigger(entity, elideHook.lifeCycle(),
            elideHook.fieldOrMethodName(), (LifeCycleHook) context.getBean(clazz));
      }

      logger.debug("Register Elide Function Hook: bindTrigger({}, {}, \"{}\", {})",
          entity.getCanonicalName(),
          elideHook.lifeCycle().getSimpleName(),
          elideHook.fieldOrMethodName(),
          clazz.getCanonicalName());

    } else {
      throw new RuntimeException("The class[" + clazz.getCanonicalName()
          + "] being annotated with @ElideHook must implements LifeCycleHook<T>.");
    }
  }
}
 
Example #17
Source File: GlobalCommandRegistryTestCases.java    From ditto with Eclipse Public License 2.0 4 votes vote down vote up
@Before
public void setup() {
    jsonParsableCommands = StreamSupport.stream(ClassIndex.getAnnotated(JsonParsableCommand.class).spliterator(), true)
            .filter(c -> !c.getSimpleName().equals("TestCommand"))
            .collect(Collectors.toList());
}
 
Example #18
Source File: GlobalEventRegistryTestCases.java    From ditto with Eclipse Public License 2.0 4 votes vote down vote up
@Before
public void setup() {
    jsonParsableEvents = StreamSupport.stream(ClassIndex.getAnnotated(JsonParsableEvent.class).spliterator(), true)
            .filter(c -> !"TestEvent".equals(c.getSimpleName()))
            .collect(Collectors.toList());
}
 
Example #19
Source File: DefaultMessageMapperFactory.java    From ditto with Eclipse Public License 2.0 4 votes vote down vote up
private static List<Class<? extends MessageMapperExtension>> loadMessageMapperExtensionClasses() {
    return StreamSupport.stream(ClassIndex.getSubclasses(MessageMapperExtension.class).spliterator(), false)
            .collect(Collectors.toList());
}
 
Example #20
Source File: ClasspathFunctionResolver.java    From metron with Apache License 2.0 4 votes vote down vote up
protected Iterable<Class<?>> getStellarClasses(ClassLoader cl) {
  return ClassIndex.getAnnotated(Stellar.class, cl);
}
 
Example #21
Source File: GlobalErrorRegistryTestCases.java    From ditto with Eclipse Public License 2.0 4 votes vote down vote up
/**
 * This test should verify that all modules containing exceptions that need to be deserialized
 * in this service are still in the classpath. Therefore one sample of each module is placed in {@code samples}.
 */
@Test
public void sampleCheckForExceptionFromEachModule() {
    assertThat(ClassIndex.getAnnotated(JsonParsableException.class)).containsAll(samples);
}