Example usage for org.springframework.context.annotation ClassPathScanningCandidateComponentProvider addIncludeFilter

List of usage examples for org.springframework.context.annotation ClassPathScanningCandidateComponentProvider addIncludeFilter

Introduction

In this page you can find the example usage for org.springframework.context.annotation ClassPathScanningCandidateComponentProvider addIncludeFilter.

Prototype

public void addIncludeFilter(TypeFilter includeFilter) 

Source Link

Document

Add an include type filter to the end of the inclusion list.

Usage

From source file:org.springframework.retry.backoff.BackOffPolicySerializationTests.java

@Parameters(name = "{index}: {0}")
public static List<Object[]> policies() {
    List<Object[]> result = new ArrayList<Object[]>();
    ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(true);
    scanner.addIncludeFilter(new AssignableTypeFilter(BackOffPolicy.class));
    scanner.addExcludeFilter(new RegexPatternTypeFilter(Pattern.compile(".*Test.*")));
    scanner.addExcludeFilter(new RegexPatternTypeFilter(Pattern.compile(".*Mock.*")));
    scanner.addExcludeFilter(new RegexPatternTypeFilter(Pattern.compile(".*Configuration.*")));
    Set<BeanDefinition> candidates = scanner.findCandidateComponents("org.springframework.retry");
    for (BeanDefinition beanDefinition : candidates) {
        try {//from w  w  w .  j  a v a  2  s  .  c o m
            result.add(new Object[] { BeanUtils
                    .instantiate(ClassUtils.resolveClassName(beanDefinition.getBeanClassName(), null)) });
        } catch (Exception e) {
            logger.warn("Cannot create instance of " + beanDefinition.getBeanClassName());
        }
    }
    return result;
}

From source file:org.springframework.retry.policy.RetryContextSerializationTests.java

@Parameters(name = "{index}: {0}")
public static List<Object[]> policies() {
    List<Object[]> result = new ArrayList<Object[]>();
    ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(true);
    scanner.addIncludeFilter(new AssignableTypeFilter(RetryPolicy.class));
    scanner.addExcludeFilter(new RegexPatternTypeFilter(Pattern.compile(".*Test.*")));
    scanner.addExcludeFilter(new RegexPatternTypeFilter(Pattern.compile(".*Mock.*")));
    Set<BeanDefinition> candidates = scanner.findCandidateComponents("org.springframework.retry.policy");
    for (BeanDefinition beanDefinition : candidates) {
        try {//from ww w  .  java  2 s.c om
            result.add(new Object[] { BeanUtils
                    .instantiate(ClassUtils.resolveClassName(beanDefinition.getBeanClassName(), null)) });
        } catch (Exception e) {
            logger.warn("Cannot create instance of " + beanDefinition.getBeanClassName(), e);
        }
    }
    ExceptionClassifierRetryPolicy extra = new ExceptionClassifierRetryPolicy();
    extra.setExceptionClassifier(new SubclassClassifier<Throwable, RetryPolicy>(new AlwaysRetryPolicy()));
    result.add(new Object[] { extra });
    return result;
}

From source file:org.tdar.core.service.ReflectionService.java

/**
 * Find all classes that implement the identified Class
 * // w  w w. j  a v a  2  s.  c  om
 * @param cls
 * @return
 */
public static Set<BeanDefinition> findClassesThatImplement(Class<?> cls) {
    ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(
            false);
    scanner.addIncludeFilter(new AssignableTypeFilter(cls));
    String basePackage = ORG_TDAR2;
    Set<BeanDefinition> findCandidateComponents = scanner.findCandidateComponents(basePackage);
    return findCandidateComponents;
}

From source file:org.tdar.core.service.ReflectionService.java

/**
 * find all Classes that support the identified Annotation
 * //from  www .  j  av  a  2s  .  co m
 * @param annots
 * @return
 * @throws NoSuchBeanDefinitionException
 * @throws ClassNotFoundException
 */
@SafeVarargs
public static Class<?>[] scanForAnnotation(Class<? extends Annotation>... annots)
        throws ClassNotFoundException {
    List<Class<?>> toReturn = new ArrayList<>();
    ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(
            false);
    for (Class<? extends Annotation> annot : annots) {
        scanner.addIncludeFilter(new AnnotationTypeFilter(annot));
    }
    String basePackage = ORG_TDAR2;
    for (BeanDefinition bd : scanner.findCandidateComponents(basePackage)) {
        String beanClassName = bd.getBeanClassName();
        Class<?> cls = Class.forName(beanClassName);
        toReturn.add(cls);
    }
    return toReturn.toArray(new Class<?>[0]);
}

From source file:org.teiid.spring.autoconfigure.TeiidServer.java

boolean findAndConfigureViews(VDBMetaData vdb, ApplicationContext context,
        PhysicalNamingStrategy namingStrategy) {
    ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(
            false);/*from   w w w . j ava2s  .c o  m*/
    provider.addIncludeFilter(new AnnotationTypeFilter(javax.persistence.Entity.class));
    provider.addIncludeFilter(new AnnotationTypeFilter(javax.persistence.Embeddable.class));
    provider.addIncludeFilter(new AnnotationTypeFilter(SelectQuery.class));
    provider.addIncludeFilter(new AnnotationTypeFilter(UserDefinedFunctions.class));

    String basePackage = context.getEnvironment().getProperty(TeiidConstants.ENTITY_SCAN_DIR);
    if (basePackage == null) {
        logger.warn("***************************************************************");
        logger.warn("\"" + TeiidConstants.ENTITY_SCAN_DIR
                + "\" is NOT set, scanning entire classpath for @Entity classes.");
        logger.warn("consider setting this property to avoid time consuming scanning");
        logger.warn("***************************************************************");
        basePackage = "*";
    }

    // check to add any source models first based on the annotations
    boolean load = false;
    Set<BeanDefinition> components = provider.findCandidateComponents(basePackage);
    for (BeanDefinition c : components) {
        try {
            Class<?> clazz = Class.forName(c.getBeanClassName());
            ExcelTable excelAnnotation = clazz.getAnnotation(ExcelTable.class);

            if (excelAnnotation != null) {
                addExcelModel(vdb, clazz, excelAnnotation);
                load = true;
            }
        } catch (ClassNotFoundException e) {
            logger.warn("Error loading entity classes");
        }
    }

    ModelMetaData model = new ModelMetaData();
    model.setName(EXPOSED_VIEW);
    model.setModelType(Model.Type.VIRTUAL);
    MetadataFactory mf = new MetadataFactory(VDBNAME, VDBVERSION,
            SystemMetadata.getInstance().getRuntimeTypeMap(), model);

    if (components.isEmpty()) {
        if (isRedirectUpdatesEnabled(context)) {
            // when no @entity classes are defined then this is service based, sniff the
            // metadata
            // from Teiid models that are defined and build Hibernate metadata from it.
            buildVirtualBaseLayer(vdb, context, mf);
        } else {
            return false;
        }
    }

    Metadata metadata = getMetadata(components, namingStrategy, mf);
    UDFProcessor udfProcessor = new UDFProcessor(metadata, vdb);
    for (BeanDefinition c : components) {
        try {
            Class<?> clazz = Class.forName(c.getBeanClassName());
            Entity entityAnnotation = clazz.getAnnotation(Entity.class);
            SelectQuery selectAnnotation = clazz.getAnnotation(SelectQuery.class);
            TextTable textAnnotation = clazz.getAnnotation(TextTable.class);
            JsonTable jsonAnnotation = clazz.getAnnotation(JsonTable.class);
            ExcelTable excelAnnotation = clazz.getAnnotation(ExcelTable.class);
            UserDefinedFunctions udfAnnotation = clazz.getAnnotation(UserDefinedFunctions.class);

            if (textAnnotation != null && entityAnnotation != null) {
                new TextTableView(metadata).buildView(clazz, mf, textAnnotation);
            } else if (jsonAnnotation != null && entityAnnotation != null) {
                new JsonTableView(metadata).buildView(clazz, mf, jsonAnnotation);
            } else if (selectAnnotation != null && entityAnnotation != null) {
                new SimpleView(metadata).buildView(clazz, mf, selectAnnotation);
            } else if (excelAnnotation != null && entityAnnotation != null) {
                new ExcelTableView(metadata).buildView(clazz, mf, excelAnnotation);
            } else if (udfAnnotation != null) {
                udfProcessor.buildFunctions(clazz, mf, udfAnnotation);
            } else if (selectAnnotation == null && entityAnnotation != null) {
                new EntityBaseView(metadata, vdb, this).buildView(clazz, mf, entityAnnotation);
            }

            // check for sequence
            if (entityAnnotation != null) {
                udfProcessor.buildSequence(clazz, mf, entityAnnotation);
            }
        } catch (ClassNotFoundException e) {
            logger.warn("Error loading entity classes");
        }
    }
    udfProcessor.finishProcessing();

    // check if the redirection is in play
    if (isRedirectUpdatesEnabled(context)) {
        String redirectedDSName = getRedirectedDataSource(context);
        try {
            // rename current view model to something else
            model.setName("internal");
            model.setVisible(false);

            DataSource redirectedDS = (DataSource) ((SBConnectionFactoryProvider) getConnectionFactoryProviders()
                    .get(redirectedDSName)).getBean();
            String driverName = getDriverName(redirectedDS);
            if (driverName == null) {
                throw new IllegalStateException("Redirection of updates enabled, however datasource"
                        + " configured for redirection is not recognized.");
            }

            RedirectionSchemaBuilder mg = new RedirectionSchemaBuilder(context, redirectedDSName);
            // if none of the annotations defined, create layer with tables from all data
            // sources
            if (mf.getSchema().getTables().isEmpty()) {
                throw new IllegalStateException("Redirection of updates enabled, however there are no "
                        + "@Entity found. There must be atleast one @Entity for this feature to work.");
            }

            // now add the modified model that does the redirection
            ModelMetaData exposedModel = mg.buildRedirectionLayer(mf, EXPOSED_VIEW);
            vdb.addModel(exposedModel);

            // we need to create the schema in the redirected data source to store the
            // ephemeral data, will use
            // hibernate metadata for schema generation techniques.
            ModelMetaData redirectedModel = vdb.getModel(redirectedDSName);
            assert (redirectedModel != null);
            String dialect = redirectedModel.getPropertyValue(DIALECT);
            if (dialect == null) {
                throw new IllegalStateException(
                        "Redirection is enabled, however data source named \"" + redirectedDSName
                                + "\" cannot be used with schema initialization, choose a different data source"
                                + "as there are no schema generation facilities for this data source.");
            }
            new RedirectionSchemaInitializer(redirectedDS, redirectedDSName, getDialect(dialect), metadata,
                    this.metadataSources.getServiceRegistry(), mf.getSchema(), context).init();

            // reload the redirection model as it has new entries now after schema
            // generation.
            try {
                vdb.addModel(buildModelFromDataSource(redirectedDSName, driverName, context, false));
            } catch (AdminException e) {
                throw new IllegalStateException("Error adding the source, cause: " + e.getMessage());
            }
            load = true;
        } catch (BeansException e) {
            throw new IllegalStateException("Redirection is enabled, however data source named \""
                    + redirectedDSName + "\" is not configured. Please configure a data source.");
        }
    }
    if (!mf.getSchema().getTables().isEmpty()) {
        load = true;
        String ddl = DDLStringVisitor.getDDLString(mf.getSchema(), null, null);
        model.addSourceMetadata("DDL", ddl);
        vdb.addModel(model);
    }
    return load;
}

From source file:org.usergrid.persistence.Schema.java

@SuppressWarnings("unchecked")
public void scanEntities() {
    for (String path : entitiesScanPath) {
        ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(
                true);/*from  w  w  w  . ja  va2s  .co m*/
        provider.addIncludeFilter(new AssignableTypeFilter(TypedEntity.class));

        Set<BeanDefinition> components = provider.findCandidateComponents(path);
        for (BeanDefinition component : components) {
            try {
                Class<?> cls = Class.forName(component.getBeanClassName());
                if (Entity.class.isAssignableFrom(cls)) {
                    registerEntity((Class<? extends Entity>) cls);
                }
            } catch (ClassNotFoundException e) {
                logger.error("Unable to get entity class ", e);
            }
        }
        registerEntity(DynamicEntity.class);
    }
}

From source file:ru.cwt.console.EasyShellServer.java

@PostConstruct
private void init() {
    registerCommand("exit", new Command() {
        @Override/*w  w w  . j a  v  a 2s  .  c  o  m*/
        public void execute(String name, String argument, EasyTerminal terminal) throws IOException {
            terminal.close();
        }
    });

    registerCommand("help", new Command() {
        @Override
        public void execute(String name, String argument, EasyTerminal terminal) throws IOException {
            terminal.write(TelnetUtils.join(" ", commands.keySet()) + "\r\n");
            terminal.flush();
        }
    });

    registerCommand("status", new Command() {
        @Override
        public void execute(String name, String argument, EasyTerminal terminal) throws IOException {
            Map<String, Integer> status = probeService.getPoolersStatus();

            int c = 0;
            for (String p : status.keySet()) {
                terminal.write("Pooler " + p + " task count " + status.get(p) + "\r\n");
                c += status.get(p);
            }

            terminal.write("Total tasks in queue " + c + "\r\n");

            terminal.flush();
        }
    });

    registerCommand("list", new Command() {
        @Override
        public void execute(String name, String argument, EasyTerminal terminal) throws IOException {
            switch (argument) {
            case "hosts":
                if (probeService.getHosts().size() > 0) {
                    terminal.write("available hosts: \r\n");

                    for (String hostId : probeService.getHosts().keySet()) {
                        Host h = probeService.getHosts().get(hostId);
                        terminal.write(
                                " " + h.getName() + " (" + h.getAddressType() + ":" + h.getAddress() + ")\r\n");
                    }
                } else {
                    terminal.write("no hosts \r\n");
                }

                break;

            case "checks":
                if (probeService.getHosts().size() > 0) {
                    terminal.write("available probe checks: \r\n");

                    for (String hostId : probeService.getHosts().keySet()) {
                        Host h = probeService.getHosts().get(hostId);

                        if (CollectionUtils.isEmpty(h.getChecks())) {
                            terminal.write(" Host: " + h.getName() + " has no probe check\r\n");

                        } else {
                            terminal.write(" Host: " + h.getName() + " (" + h.getAddressType() + ":"
                                    + h.getAddress() + ")\r\n");

                            for (ServiceCheck sc : h.getChecks()) {
                                terminal.write(
                                        "  * " + sc.getName() + " (" + sc.getServiceBeanName() + ")\r\n");
                            }
                        }
                    }
                } else {
                    terminal.write("no checks \r\n");
                }

                break;

            case "services":
                terminal.write("available probe beans: \r\n");
                final ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(
                        false);
                provider.addIncludeFilter(new RegexPatternTypeFilter(Pattern.compile(".*")));

                final Set<BeanDefinition> classes = provider
                        .findCandidateComponents("ru.cwt.devscheck.probe.impl");

                for (BeanDefinition bean : classes) {
                    terminal.write(" " + bean.getBeanClassName() + "\r\n");
                }

                break;

            default:
                terminal.write("unknown argument '" + argument + "'. allowed values: host, check\r\n");
            }

            terminal.flush();
        }
    });

    registerCommand("add", new Command() {
        @Override
        public void execute(String name, String argument, EasyTerminal terminal) throws IOException {

            String[] params = StringUtils.split(argument, " ");
            if (params.length == 0) {
                terminal.write("unknown argument '" + argument + "'. allowed values: host, check\r\n");
            } else {

                switch (params[0]) {
                case "host":
                    if (params.length < 4) {
                        terminal.write("wrong parameters count. usage: add host name ip type\r\n");
                        terminal.write(" type can be one of: WMWARE,WINDOWS,LINUX,MACOSX,CISCO,IBM_BLADE\r\n");
                    } else {
                        Host h = new Host();
                        h.setName(params[1]);
                        if (StringUtils.contains(params[2], "."))
                            h.setAddressType(AddressType.IPV4);
                        else
                            h.setAddressType(AddressType.IPV6);
                        h.setAddress(params[2]);
                        h.setHostType(HostType.valueOf(params[3]));
                        h.setCreateDate(new Date());

                        if (!probeService.addHost(h)) {
                            terminal.write("Error adding Host\r\n");
                        }
                    }

                    break;

                case "check":
                    if (params.length < 3) {
                        terminal.write("wrong parameters count. usage: add check host check-name clazz\r\n");
                    } else {
                        ServiceCheck sc = new ServiceCheck();
                        sc.setName(params[2]);
                        sc.setServiceBeanName(params[3]);
                        sc.setCreateDate(new Date());
                        if (!probeService.addServiceCheck(params[1], sc)) {
                            terminal.write("Error adding ServiceCheck\r\n");
                        }
                    }

                    break;

                case "treshold":
                    if (params.length < 4) {
                        terminal.write("wrong parameters count. usage: add treshold name warning alert\r\n");
                    } else {
                        Treshold t = new Treshold();
                        t.setName(params[2]);
                        t.setWarning(NumberUtils.createDouble(params[3]));
                        t.setAlert(NumberUtils.createDouble(params[4]));
                        if (!probeService.addTreshold(t)) {
                            terminal.write("Error adding Treshold\r\n");
                        }
                    }
                    break;

                default:
                    terminal.write("unknown argument '" + argument + "'. allowed values: host, check\r\n");
                }
            }

            terminal.flush();
        }
    });

    registerCommand("discovery", new Command() {
        @Override
        public void execute(String name, String argument, EasyTerminal terminal) throws IOException {
            String[] params = StringUtils.split(argument, " ");
            if (params.length < 3) {
                terminal.write("wrong parameters count. usage: discovery from-ip to-ip ServiceCherk\r\n");
            } else {
                ServiceCheck check = new ServiceCheck("ping", null, new HashMap<>(),
                        "ru.cwt.devscheck.probe.impl.PingServiceBean");

                discoveryService.scan(params[0], params[1], check);
            }

            terminal.flush();
        }
    });

    try {
        start(InetAddress.getByName(addr), Integer.parseInt(port));

        log.info("Start shell server at {}:{} ", addr, port);
    } catch (Exception e) {
        log.error("Cant init shell server", e);
    }
}

From source file:ubic.gemma.core.apps.GemmaCLI.java

public static void main(String[] args) {

    /*//from   w  ww .j a  v a2 s.  co m
     * Build a map from command names to classes.
     */
    Map<CommandGroup, Map<String, String>> commands = new HashMap<>();
    Map<String, Class<? extends AbstractCLI>> commandClasses = new HashMap<>();
    try {

        final ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(
                false);
        provider.addIncludeFilter(new RegexPatternTypeFilter(Pattern.compile(".*")));

        // searching entire hierarchy is 1) slow and 2) generates annoying logging from static initialization code.
        final Set<BeanDefinition> classes = provider.findCandidateComponents("ubic.gemma.core.apps");
        classes.addAll(provider.findCandidateComponents("ubic.gemma.core.loader.association.phenotype"));

        for (BeanDefinition bean : classes) {
            try {
                @SuppressWarnings("unchecked")
                Class<? extends AbstractCLI> aClazz = (Class<? extends AbstractCLI>) Class
                        .forName(bean.getBeanClassName());

                Object cliInstance = aClazz.newInstance();

                Method method = aClazz.getMethod("getCommandName");
                String commandName = (String) method.invoke(cliInstance, new Object[] {});
                if (commandName == null || StringUtils.isBlank(commandName)) {
                    // keep null to avoid printing some commands...
                    continue;
                }

                Method method2 = aClazz.getMethod("getShortDesc");
                String desc = (String) method2.invoke(cliInstance, new Object[] {});

                Method method3 = aClazz.getMethod("getCommandGroup");
                CommandGroup g = (CommandGroup) method3.invoke(cliInstance, new Object[] {});

                if (!commands.containsKey(g)) {
                    commands.put(g, new TreeMap<String, String>());
                }

                commands.get(g).put(commandName, desc + " (" + bean.getBeanClassName() + ")");

                commandClasses.put(commandName, aClazz);
            } catch (Exception e) {
                // OK, this can happen if we hit a non useful class.
            }
        }
    } catch (Exception e1) {
        System.err.println("ERROR! Report to developers: " + e1.getMessage());
        System.exit(1);
    }

    if (args.length == 0 || args[0].equalsIgnoreCase("--help") || args[0].equalsIgnoreCase("-help")
            || args[0].equalsIgnoreCase("help")) {
        GemmaCLI.printHelp(commands);
    } else {
        LinkedList<String> f = new LinkedList<>(Arrays.asList(args));
        String commandRequested = f.remove(0);
        Object[] argsToPass = f.toArray(new String[] {});

        if (!commandClasses.containsKey(commandRequested)) {
            System.err.println("Unrecognized command: " + commandRequested);
            GemmaCLI.printHelp(commands);
            System.err.println("Unrecognized command: " + commandRequested);
            System.exit(1);
        } else {
            try {
                Class<?> c = commandClasses.get(commandRequested);
                Method method = c.getMethod("main", String[].class);
                System.err.println("========= Gemma CLI invocation of " + commandRequested + " ============");
                System.err.println("Options: " + GemmaCLI.getOptStringForLogging(argsToPass));
                //noinspection JavaReflectionInvocation // It works
                method.invoke(null, (Object) argsToPass);
            } catch (Exception e) {
                System.err.println("Gemma CLI error: " + e.getClass().getName() + " - " + e.getMessage());
                System.err.println(ExceptionUtils.getStackTrace(e));
                throw new RuntimeException(e);
            } finally {
                System.err.println("========= Gemma CLI run of " + commandRequested + " complete ============");
                System.exit(0);
            }
        }
    }
}