org.apache.xbean.finder.AnnotationFinder Java Examples

The following examples show how to use org.apache.xbean.finder.AnnotationFinder. 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: NestedJarArchiveTest.java    From component-runtime with Apache License 2.0 6 votes vote down vote up
@Test
void xbeanNestedScanning(final TestInfo info, @TempDir final File temporaryFolder) throws IOException {
    final File jar = createPlugin(temporaryFolder, info.getTestMethod().get().getName());
    final ConfigurableClassLoader configurableClassLoader = new ConfigurableClassLoader("", new URL[0],
            new URLClassLoader(new URL[] { jar.toURI().toURL() }, Thread.currentThread().getContextClassLoader()),
            n -> true, n -> true, new String[] { "com/foo/bar/1.0/bar-1.0.jar" }, new String[0]);
    try (final JarInputStream jis = new JarInputStream(
            configurableClassLoader.getResourceAsStream("MAVEN-INF/repository/com/foo/bar/1.0/bar-1.0.jar"))) {
        assertNotNull(jis, "test is wrongly setup, no nested jar, fix the createPlugin() method please");
        final AnnotationFinder finder =
                new AnnotationFinder(new NestedJarArchive(null, jis, configurableClassLoader));
        final List<Class<?>> annotatedClasses = finder.findAnnotatedClasses(Processor.class);
        assertEquals(1, annotatedClasses.size());
        assertEquals("org.talend.test.generated." + info.getTestMethod().get().getName() + ".Components",
                annotatedClasses.iterator().next().getName());
    } finally {
        URLClassLoader.class.cast(configurableClassLoader.getParent()).close();
    }
}
 
Example #2
Source File: FinderFactory.java    From tomee with Apache License 2.0 6 votes vote down vote up
public static Map<String, String> urlByClass(final IAnnotationFinder finder) {
    final IAnnotationFinder limitedFinder;
    if (finder instanceof FinderFactory.ModuleLimitedFinder) {
        limitedFinder = ((FinderFactory.ModuleLimitedFinder) finder).getDelegate();
    } else {
        limitedFinder = finder;
    }
    if (limitedFinder instanceof AnnotationFinder) {
        final Archive archive = ((AnnotationFinder) limitedFinder).getArchive();
        if (archive instanceof WebappAggregatedArchive) {
            final Map<URL, List<String>> index = ((WebappAggregatedArchive) archive).getClassesMap();
            final Map<String, String> urlByClasses = new HashMap<>();
            for (final Map.Entry<URL, List<String>> entry : index.entrySet()) {
                final String url = entry.getKey().toExternalForm();
                for (final String current : entry.getValue()) {
                    urlByClasses.put(current, url);
                }
            }
            return urlByClasses;
        }
    }
    return Collections.emptyMap();
}
 
Example #3
Source File: FinderFactory.java    From tomee with Apache License 2.0 6 votes vote down vote up
private RuntimeException handleException(final TypeNotPresentException tnpe, final Class<? extends Annotation> annotation) {
    try {
        final Method mtd = AnnotationFinder.class.getDeclaredMethod("getAnnotationInfos", String.class);
        mtd.setAccessible(true);
        final List<?> infos = (List<?>) mtd.invoke(delegate);
        for (final Object info : infos) {
            if (info instanceof AnnotationFinder.ClassInfo) {
                final AnnotationFinder.ClassInfo classInfo = (AnnotationFinder.ClassInfo) info;
                try {
                    // can throw the exception
                    classInfo.get().isAnnotationPresent(annotation);
                } catch (final TypeNotPresentException tnpe2) {
                    throw new OpenEJBRuntimeException("Missing type for annotation " + annotation.getName() + " on class " + classInfo.getName(), tnpe2);
                } catch (final ThreadDeath ignored) {
                    // no-op
                }
            }
        }
    } catch (final Throwable th) {
        // no-op
    }
    return tnpe;
}
 
Example #4
Source File: ComponentValidator.java    From component-runtime with Apache License 2.0 6 votes vote down vote up
private void validateDocumentationWording(final AnnotationFinder finder, final List<Class<?>> components,
        final Set<String> errors) {
    final Predicate<String> isIncorrectWording = s -> !s.matches("^[A-Z0-9]+.*\\.$");
    final String error = "@Documentation on '%s' is empty or is not capitalized or ends not by a dot.";
    errors
            .addAll(components
                    .stream()
                    .filter(c -> c.isAnnotationPresent(Documentation.class))
                    .filter(c -> isIncorrectWording.test(c.getAnnotation(Documentation.class).value()))
                    .map(c -> String.format(error, c.getName()))
                    .sorted()
                    .collect(toSet()));
    errors
            .addAll(findOptions(finder)
                    .filter(field -> field.isAnnotationPresent(Documentation.class))
                    .filter(c -> isIncorrectWording.test(c.getAnnotation(Documentation.class).value()))
                    .map(c -> String.format(error, c.getName()))
                    .sorted()
                    .collect(toSet()));
}
 
Example #5
Source File: ComponentValidator.java    From component-runtime with Apache License 2.0 6 votes vote down vote up
private void validateDocumentation(final AnnotationFinder finder, final List<Class<?>> components,
        final Set<String> errors) {
    errors
            .addAll(components
                    .stream()
                    .filter(c -> !c.isAnnotationPresent(Documentation.class))
                    .map(c -> "No @Documentation on '" + c.getName() + "'")
                    .sorted()
                    .collect(toSet()));
    errors
            .addAll(findOptions(finder)
                    .filter(field -> !field.isAnnotationPresent(Documentation.class)
                            && !field.getType().isAnnotationPresent(Documentation.class))
                    .map(field -> "No @Documentation on '" + field + "'")
                    .sorted()
                    .collect(toSet()));
}
 
Example #6
Source File: ScanTask.java    From component-runtime with Apache License 2.0 6 votes vote down vote up
private Stream<String> scanList() {
    final AnnotationFinder finder = newFinder();
    final Filter filter = newFilter();
    return Stream
            .concat(Stream
                    .of(PartitionMapper.class, Processor.class, Emitter.class, Service.class,
                            Internationalized.class)
                    .flatMap(it -> finder.findAnnotatedClasses(it).stream()),
                    Stream
                            .of(Request.class)
                            .flatMap(it -> finder.findAnnotatedMethods(it).stream())
                            .map(Method::getDeclaringClass))
            .distinct()
            .map(Class::getName)
            .sorted()
            .filter(filter::accept);
}
 
Example #7
Source File: DocBaseGenerator.java    From component-runtime with Apache License 2.0 6 votes vote down vote up
protected Stream<ComponentDescription> components() {
    final AnnotationFinder finder = newFinder();
    return findComponents(finder).map(component -> {
        final Collection<ParameterMeta> parameterMetas = parameterModelService
                .buildParameterMetas(Constructors.findConstructor(component),
                        ofNullable(component.getPackage()).map(Package::getName).orElse(""),
                        new BaseParameterEnricher.Context(new LocalConfigurationService(emptyList(), "tools")));
        final Component componentMeta = componentMarkers()
                .filter(component::isAnnotationPresent)
                .map(component::getAnnotation)
                .map(this::asComponent)
                .findFirst()
                .orElseThrow(NoSuchElementException::new);
        String family = "";
        try {
            family = findFamily(componentMeta, component);
        } catch (final IllegalArgumentException iae) {
            // skip for doc
        }
        return new ComponentDescription(component, family, componentMeta.name(), getDoc(component),
                sort(parameterMetas), resolver, defaultValueInspector, locale, emptyDefaultValue());
    });
}
 
Example #8
Source File: Generator.java    From component-runtime with Apache License 2.0 6 votes vote down vote up
private static void generatedUi(final File generatedDir) throws Exception {
    final File file = new File(generatedDir, "generated_ui.adoc");
    try (final PrintStream stream = new PrintStream(new WriteIfDifferentStream(file))) {
        stream.println();
        final File api = jarLocation(Ui.class);
        final ClassLoader loader = Thread.currentThread().getContextClassLoader();
        final AnnotationFinder finder = new AnnotationFinder(
                api.isDirectory() ? new FileArchive(loader, api) : new JarArchive(loader, api.toURI().toURL()));
        final ParameterExtensionEnricher enricher = new UiParameterEnricher();
        try (final Jsonb jsonb = newJsonb()) {
            finder
                    .findAnnotatedClasses(Ui.class)
                    .stream()
                    .sorted(Comparator.comparing(Class::getName))
                    .forEach(type -> renderUiDoc(stream, enricher, jsonb, type));
        }
        stream.println();

    }
}
 
Example #9
Source File: AnnotationDeployerTest.java    From tomee with Apache License 2.0 6 votes vote down vote up
@Test
public void findRestClasses() throws Exception {
    final WebApp webApp = new WebApp();
    webApp.setContextRoot("/");
    webApp.setId("web");
    webApp.setVersion("2.5");
    WebModule webModule = new WebModule(webApp, webApp.getContextRoot(), Thread.currentThread().getContextClassLoader(), "myapp", webApp.getId());
    webModule.setFinder(new AnnotationFinder(new ClassesArchive(RESTClass.class, RESTMethod.class, RESTApp.class)).link());

    final AnnotationDeployer annotationDeployer = new AnnotationDeployer();
    webModule = annotationDeployer.deploy(webModule);

    final Set<String> classes = webModule.getRestClasses();
    final Set<String> applications = webModule.getRestApplications();

    assertEquals(1, classes.size());
    assertTrue(classes.contains(RESTClass.class.getName()));
    // assertTrue(classes.contains(RESTMethod.class.getName()));

    assertEquals(1, applications.size());
    assertEquals(RESTApp.class.getName(), applications.iterator().next());
}
 
Example #10
Source File: CheckAnnotationTest.java    From tomee with Apache License 2.0 5 votes vote down vote up
@Keys({@Key(value = "ann.local.forLocalBean", type = KeyType.WARNING)})
public EjbModule shouldWarnForLocalAnnotationOnBeanWithNoInterface() {
    final EjbJar ejbJar = new EjbJar();
    ejbJar.addEnterpriseBean(new StatelessBean(EjbWithoutInterface.class));
    final EjbModule ejbModule = new EjbModule(ejbJar);
    ejbModule.setFinder(new AnnotationFinder(new ClassesArchive(EjbWithoutInterface.class)).link());
    return ejbModule;
}
 
Example #11
Source File: CheckAnnotationTest.java    From tomee with Apache License 2.0 5 votes vote down vote up
@Keys({@Key(value = "annotation.invalid.managedbean.webservice", type = KeyType.WARNING)})
public AppModule testWebServiceWithManagedBean() {
    final EjbJar ejbJar = new EjbJar();
    ejbJar.addEnterpriseBean(new ManagedBean(Red.class));
    final EjbModule ejbModule = new EjbModule(ejbJar);
    ejbModule.setFinder(new AnnotationFinder(new ClassesArchive(Red.class)).link());

    final AppModule appModule = new AppModule(ejbModule);
    return appModule;
}
 
Example #12
Source File: AnnotationDeployerTest.java    From tomee with Apache License 2.0 5 votes vote down vote up
@Test
public void testSortClasses() throws Exception {
    final AnnotationFinder finder = new AnnotationFinder(new ClassesArchive(Emerald.class)).link();

    final List<Annotated<Class<?>>> classes = finder.findMetaAnnotatedClasses(Resource.class);
    assertTrue(classes.size() >= 3);

    final List<Annotated<Class<?>>> sorted = AnnotationDeployer.sortClasses(classes);

    assertTrue(sorted.size() >= 3);

    assertEquals(Emerald.class, sorted.get(0).get());
    assertEquals(Green.class, sorted.get(1).get());
    assertEquals(Color.class, sorted.get(2).get());
}
 
Example #13
Source File: CheckAnnotationTest.java    From tomee with Apache License 2.0 5 votes vote down vote up
@Keys({@Key(value = "annotation.invalid.messagedriven.webservice", type = KeyType.WARNING)})
public AppModule testWebServiceWithMessageDriven() {
    final EjbJar ejbJar = new EjbJar();
    ejbJar.addEnterpriseBean(new MessageDrivenBean(Yellow.class));
    final EjbModule ejbModule = new EjbModule(ejbJar);
    ejbModule.setFinder(new AnnotationFinder(new ClassesArchive(Yellow.class)).link());

    final AppModule appModule = new AppModule(ejbModule);
    return appModule;
}
 
Example #14
Source File: CheckAnnotationTest.java    From tomee with Apache License 2.0 5 votes vote down vote up
@Keys({@Key(value = "annotation.invalid.stateful.webservice", type = KeyType.WARNING)})
public AppModule testWebServiceWithStateful() {
    final EjbJar ejbJar = new EjbJar();
    ejbJar.addEnterpriseBean(new StatefulBean(Green.class));
    final EjbModule ejbModule = new EjbModule(ejbJar);
    ejbModule.setFinder(new AnnotationFinder(new ClassesArchive(Green.class)).link());

    final AppModule appModule = new AppModule(ejbModule);
    return appModule;
}
 
Example #15
Source File: LocalBeanAnnotatedLocalTest.java    From tomee with Apache License 2.0 5 votes vote down vote up
@Keys({@Key(value = "ann.local.forLocalBean", type = KeyType.WARNING)})
public AppModule testWebServiceWithStateful() {
    final EjbJar ejbJar = new EjbJar();
    ejbJar.addEnterpriseBean(new StatelessBean(LocalBeanLocal.class));

    final EjbModule ejbModule = new EjbModule(ejbJar);
    ejbModule.setFinder(new AnnotationFinder(new ClassesArchive(LocalBeanLocal.class)));

    return new AppModule(ejbModule);
}
 
Example #16
Source File: AbstractXmlAnnotationFinderTest.java    From tomee with Apache License 2.0 5 votes vote down vote up
@Before
public void initFinder() throws Exception {
    final ClassLoader loader = Thread.currentThread().getContextClassLoader();
    System.setProperty(SCAN_XML_PROPERTY, scanXml());
    finder = new AnnotationFinder(new ConfigurableClasspathArchive(loader,
        Arrays.asList(
            new URL(loader.getResource(scanXml()).toExternalForm().replace(scanXml(), ""))
        )
    ));
    System.clearProperty("openejb.scan.xml.name");
}
 
Example #17
Source File: AnnotationDeployerTest.java    From tomee with Apache License 2.0 5 votes vote down vote up
@Test
public void testSortMethods() throws Exception {
    final AnnotationFinder finder = new AnnotationFinder(new ClassesArchive(Emerald.class)).link();

    final List<Annotated<Method>> classes = finder.findMetaAnnotatedMethods(Resource.class);
    assertTrue(classes.size() >= 3);

    final List<Annotated<Method>> sorted = AnnotationDeployer.sortMethods(classes);

    assertTrue(sorted.size() >= 3);

    assertEquals(Emerald.class, sorted.get(0).get().getDeclaringClass());
    assertEquals(Green.class, sorted.get(1).get().getDeclaringClass());
    assertEquals(Color.class, sorted.get(2).get().getDeclaringClass());
}
 
Example #18
Source File: Generator.java    From component-runtime with Apache License 2.0 5 votes vote down vote up
private static void generatedJUnitEnvironment(final File generatedDir) throws MalformedURLException {
    final File file = new File(generatedDir, "generated_junit-environments.adoc");
    try (final PrintStream stream = new PrintStream(new WriteIfDifferentStream(file))) {
        stream.println();
        stream.println("NOTE: the configuration is read from system properties, environment variables, ....");
        stream.println();
        final File api = jarLocation(BaseEnvironmentProvider.class);
        final ClassLoader loader = Thread.currentThread().getContextClassLoader();
        final AnnotationFinder finder = new AnnotationFinder(
                api.isDirectory() ? new FileArchive(loader, api) : new JarArchive(loader, api.toURI().toURL()));
        finder
                .link()
                .findSubclasses(BaseEnvironmentProvider.class)
                .stream()
                .filter(c -> !Modifier.isAbstract(c.getModifiers()))
                .sorted(Comparator.comparing(Class::getName))
                .forEach(type -> {
                    final BaseEnvironmentProvider environment;
                    try {
                        environment = BaseEnvironmentProvider.class.cast(type.getConstructor().newInstance());
                    } catch (final InstantiationException | IllegalAccessException | NoSuchMethodException
                            | InvocationTargetException e) {
                        throw new IllegalStateException(e);
                    }
                    stream.println(environment.getName() + ":: " + "__class: " + type.getSimpleName() + "_. ");
                });
        stream.println();
    }
}
 
Example #19
Source File: DitaMojo.java    From component-runtime with Apache License 2.0 5 votes vote down vote up
@Override
public void doExecute() {
    if (locales == null) {
        return;
    }
    locales.stream().map(Locale::new).map(locale -> {
        final String localeStr = locale.toString();
        final File output = new File(String.format(this.output, localeStr.isEmpty() ? "" : ("_" + localeStr)));

        final Collection<String> exclusions = getExcludes(excludes, sharedExcludes);
        new DitaDocumentationGenerator(getClasses(), locale, getLog(), output, ignoreTypeColumn, ignorePathColumn) {

            @Override
            protected Stream<Class<?>> findComponents(final AnnotationFinder finder) {
                return super.findComponents(finder).filter(it -> !exclusions.contains(it.getName()));
            }
        }.run();
        return output;
    }).filter(it -> attach).forEach(artifact -> {
        final String artifactName = artifact.getName();
        int dot = artifactName.lastIndexOf('_');
        if (dot < 0) {
            dot = artifactName.lastIndexOf('.');
        }
        getLog().info("Attaching " + artifact.getAbsolutePath());
        if (dot > 0) {
            helper
                    .attachArtifact(project, "zip",
                            artifactName.substring(dot + 1).replace('.', '-') + "-documentation", artifact);
        } else {
            helper.attachArtifact(project, "zip", artifactName + "-documentation", artifact);
        }
    });
}
 
Example #20
Source File: Generator.java    From component-runtime with Apache License 2.0 5 votes vote down vote up
private static void generatedConditions(final File generatedDir) throws Exception {
    final File file = new File(generatedDir, "generated_conditions.adoc");
    try (final PrintStream stream = new PrintStream(new WriteIfDifferentStream(file))) {
        stream.println();
        final File api = jarLocation(Condition.class);
        final ClassLoader loader = Thread.currentThread().getContextClassLoader();
        final ConditionParameterEnricher enricher = new ConditionParameterEnricher();
        try (final Jsonb jsonb = newJsonb()) {
            final AnnotationFinder finder = new AnnotationFinder(
                    api.isDirectory() ? new FileArchive(loader, api) : new JarArchive(loader, api.toURI().toURL()));
            finder
                    .findAnnotatedClasses(Condition.class)
                    .stream()
                    .sorted(comparing(Class::getName))
                    .forEach(type -> {
                        stream.println();
                        stream.println("= " + capitalizeWords(type.getSimpleName()));
                        stream.println();
                        stream.println(extractDoc(type));
                        stream.println();
                        stream.println("- API: `@" + type.getName() + "`");
                        stream.println("- Type: `" + type.getAnnotation(Condition.class).value() + "`");
                        stream.println("- Sample:");
                        stream.println();
                        stream.println("[source,js]");
                        stream.println("----");
                        stream
                                .println(jsonb
                                        .toJson(new TreeMap<>(enricher
                                                .onParameterAnnotation("test", String.class,
                                                        generateAnnotation(type))))
                                        .replace("tcomp::", ""));
                        stream.println("----");
                        stream.println();
                    });
            stream.println();
        }

    }
}
 
Example #21
Source File: Generator.java    From component-runtime with Apache License 2.0 5 votes vote down vote up
private static void generatedTypes(final File generatedDir) throws Exception {
    final File file = new File(generatedDir, "generated_configuration-types.adoc");
    try (final PrintStream stream = new PrintStream(new WriteIfDifferentStream(file))) {
        final File api = jarLocation(ConfigurationType.class);
        final ClassLoader loader = Thread.currentThread().getContextClassLoader();
        final ConfigurationTypeParameterEnricher enricher = new ConfigurationTypeParameterEnricher();
        final AnnotationFinder finder = new AnnotationFinder(
                api.isDirectory() ? new FileArchive(loader, api) : new JarArchive(loader, api.toURI().toURL()));
        try (final Jsonb jsonb = newJsonb()) {
            finder
                    .findAnnotatedClasses(ConfigurationType.class)
                    .stream()
                    .sorted(comparing(Class::getName))
                    .forEach(type -> {
                        stream.println();
                        stream.println("= " + capitalizeWords(type.getAnnotation(ConfigurationType.class).value()));
                        stream.println();
                        stream.println(extractDoc(type));
                        stream.println();
                        stream.println("- API: @" + type.getName());
                        stream.println("- Sample:");
                        stream.println();
                        stream.println("[source,js]");
                        stream.println("----");
                        stream
                                .println(jsonb
                                        .toJson(new TreeMap<>(enricher
                                                .onParameterAnnotation("value", String.class,
                                                        generateAnnotation(type)))));
                        stream.println("----");
                        stream.println();
                    });
        }
        stream.println();

    }
}
 
Example #22
Source File: ComponentValidator.java    From component-runtime with Apache License 2.0 5 votes vote down vote up
private void validateHttpClient(final AnnotationFinder finder, final Set<String> errors) {
    errors
            .addAll(finder
                    .findAnnotatedClasses(Request.class)
                    .stream()
                    .map(Class::getDeclaringClass)
                    .distinct()
                    .flatMap(c -> HttpClientFactoryImpl.createErrors(c).stream())
                    .sorted()
                    .collect(toSet()));
}
 
Example #23
Source File: ScanTask.java    From component-runtime with Apache License 2.0 5 votes vote down vote up
private AnnotationFinder newFinder() {
    return new AnnotationFinder(new CompositeArchive(scannedFiles.stream().map(c -> {
        try {
            return ClasspathArchive.archive(Thread.currentThread().getContextClassLoader(), c.toURI().toURL());
        } catch (final MalformedURLException e) {
            throw new IllegalArgumentException(e);
        }
    }).toArray(Archive[]::new)));
}
 
Example #24
Source File: ComponentValidator.java    From component-runtime with Apache License 2.0 5 votes vote down vote up
private void validateNoFinalOption(final AnnotationFinder finder, final Set<String> errors) {
    errors
            .addAll(findOptions(finder)
                    .filter(field -> Modifier.isFinal(field.getModifiers()))
                    .distinct()
                    .map(field -> "@Option fields must not be final, found one field violating this rule: " + field)
                    .sorted()
                    .collect(toSet()));
}
 
Example #25
Source File: Generator.java    From component-runtime with Apache License 2.0 4 votes vote down vote up
private static void generatedActions(final File generatedDir) throws Exception {
    final File file = new File(generatedDir, "generated_actions.adoc");
    try (final PrintStream stream = new PrintStream(new WriteIfDifferentStream(file))) {
        stream.println();
        final File api = jarLocation(ActionType.class);
        final ClassLoader loader = Thread.currentThread().getContextClassLoader();
        final AnnotationFinder finder = new AnnotationFinder(
                api.isDirectory() ? new FileArchive(loader, api) : new JarArchive(loader, api.toURI().toURL()));
        try (final Jsonb jsonb = newJsonb()) {
            finder
                    .findAnnotatedClasses(ActionType.class)
                    .stream()
                    .sorted(Comparator
                            .comparing(t -> t.getAnnotation(ActionType.class).value() + "#" + t.getSimpleName()))
                    .forEach(type -> {
                        final ActionType actionType = type.getAnnotation(ActionType.class);
                        final Class<?> returnedType = actionType.expectedReturnedType();
                        final String actionTypeValue = actionType.value();
                        stream.println();
                        stream.println("= " + capitalizeWords(actionTypeValue));
                        stream.println();
                        stream.println(extractDoc(type));
                        stream.println();
                        stream.println("- Type: `" + actionTypeValue + "`");
                        stream.println("- API: `@" + type.getName() + "`");
                        if (returnedType != Object.class) {
                            stream.println("- Returned type: `" + returnedType.getName() + "`");
                            stream.println("- Sample:");
                            stream.println();
                            stream.println("[source,js]");
                            stream.println("----");
                            stream.println(sample(jsonb, returnedType));
                            stream.println("----");
                        }
                        stream.println();
                    });
        }
        stream.println();

        stream.println("== Built In Actions");
        stream.println();
        stream.println("These actions are provided - or not - by the application the UI runs within.");
        stream.println();
        stream.println("TIP: always ensure you don't require this action in your component.");
        stream.println();
        Stream.of(BuiltInSuggestable.class).forEach(it -> {
            stream.println("= built_in_suggestable");
            stream.println();
            stream.println(extractDoc(BuiltInSuggestable.class));
            stream.println();
            stream.println("- API: `@" + BuiltInSuggestable.class.getName() + "`");
            stream.println();
        });
    }
}
 
Example #26
Source File: ComponentValidator.java    From component-runtime with Apache License 2.0 4 votes vote down vote up
private Stream<Field> findOptions(final AnnotationFinder finder) {
    return finder.findAnnotatedFields(Option.class).stream();
}
 
Example #27
Source File: Generator.java    From component-runtime with Apache License 2.0 4 votes vote down vote up
private static void generatedConstraints(final File generatedDir) throws Exception {
    final File file = new File(generatedDir, "generated_constraints.adoc");
    try (final PrintStream stream = new PrintStream(new WriteIfDifferentStream(file))) {
        stream.println();
        final File api = jarLocation(Validation.class);
        final ClassLoader loader = Thread.currentThread().getContextClassLoader();
        final AnnotationFinder finder = new AnnotationFinder(
                api.isDirectory() ? new FileArchive(loader, api) : new JarArchive(loader, api.toURI().toURL()));
        final ValidationParameterEnricher enricher = new ValidationParameterEnricher();
        try (final Jsonb jsonb = newJsonb()) {
            Stream.concat(finder.findAnnotatedClasses(Validation.class).stream().map(validation -> {
                final Validation val = validation.getAnnotation(Validation.class);
                return createConstraint(validation, val);

            }), finder
                    .findAnnotatedClasses(Validations.class)
                    .stream()
                    .flatMap(validations -> Stream
                            .of(validations.getAnnotation(Validations.class).value())
                            .map(validation -> createConstraint(validations, validation))))
                    .sorted((o1, o2) -> {
                        final int types = Stream
                                .of(o1.types)
                                .map(Class::getName)
                                .collect(joining("/"))
                                .compareTo(Stream.of(o2.types).map(Class::getName).collect(joining("/")));
                        if (types == 0) {
                            return o1.name.compareTo(o2.name);
                        }
                        return types;
                    })
                    .forEach(constraint -> {
                        stream.println();
                        stream.println("= " + capitalizeWords(constraint.name));
                        stream.println();
                        stream.println(constraint.description);
                        stream.println();
                        stream.println("- API: `@" + constraint.marker.getName() + "`");
                        stream.println("- Name: `" + constraint.name + "`");
                        stream.println("- Parameter Type: `" + constraint.paramType + "`");
                        stream.println("- Supported Types:");
                        Stream
                                .of(constraint.types)
                                .map(Class::getName)
                                .map(it -> "-- `" + it + "`")
                                .forEach(stream::println);
                        stream.println("- Sample:");
                        stream.println();
                        stream.println("[source,js]");
                        stream.println("----");
                        stream
                                .println(jsonb
                                        .toJson(new TreeMap<>(enricher
                                                .onParameterAnnotation("test", constraint.types[0],
                                                        generateAnnotation(constraint.marker))))
                                        .replace("tcomp::", ""));
                        stream.println("----");
                        stream.println();
                    });
        }
        stream.println();

    }
}
 
Example #28
Source File: DocBaseGenerator.java    From component-runtime with Apache License 2.0 4 votes vote down vote up
protected Stream<Class<?>> findComponents(final AnnotationFinder finder) {
    return componentMarkers().flatMap(a -> finder.findAnnotatedClasses(a).stream());
}
 
Example #29
Source File: ComponentValidator.java    From component-runtime with Apache License 2.0 4 votes vote down vote up
private void validateLocalConfiguration(final AnnotationFinder finder, final String pluginId,
        final Set<String> errors) {

    // first check TALEND-INF/local-configuration.properties
    errors
            .addAll(Stream
                    .of(classes)
                    .map(root -> new File(root, "TALEND-INF/local-configuration.properties"))
                    .filter(File::exists)
                    .flatMap(props -> {
                        final Properties properties = new Properties();
                        try (final InputStream stream = new BufferedInputStream(new FileInputStream(props))) {
                            properties.load(stream);
                        } catch (final IOException e) {
                            throw new IllegalStateException(e);
                        }
                        return properties
                                .stringPropertyNames()
                                .stream()
                                .filter(it -> !it.toLowerCase(Locale.ROOT).startsWith(pluginId + "."))
                                .map(it -> "'" + it + "' does not start with '" + pluginId + "', "
                                        + "it is recommended to prefix all keys by the family");
                    })
                    .collect(toSet()));

    // then check the @DefaultValue annotation
    errors
            .addAll(Stream
                    .concat(finder.findAnnotatedFields(DefaultValue.class).stream(),
                            finder.findAnnotatedConstructorParameters(DefaultValue.class).stream())
                    .map(d -> {
                        final DefaultValue annotation = d.getAnnotation(DefaultValue.class);
                        if (annotation.value().startsWith("local_configuration:") && !annotation
                                .value()
                                .toLowerCase(Locale.ROOT)
                                .startsWith("local_configuration:" + pluginId + ".")) {
                            return d + " does not start with family name (followed by a dot): '" + pluginId + "'";
                        }
                        return null;
                    })
                    .filter(Objects::nonNull)
                    .collect(toSet()));
}
 
Example #30
Source File: CheckCdiEnabledTest.java    From tomee with Apache License 2.0 4 votes vote down vote up
@Keys(@Key(value = "cdi.notEnabled", type = KeyType.WARNING))
public EjbModule cdiShouldBeOn() throws OpenEJBException {
    return new EjbModule(new EjbJar())
        .finder(new AnnotationFinder(new ClassesArchive(Bean1.class, Bean2.class)));
}