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

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

Introduction

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

Prototype

public Set<BeanDefinition> findCandidateComponents(String basePackage) 

Source Link

Document

Scan the class path for candidate components.

Usage

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

@SuppressWarnings("unchecked")
public void scanEntities() {
    for (String path : entitiesScanPath) {
        ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(
                true);/*from  www.j a  v a  2 s  .  c  o  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/*from   w  w  w .j ava  2  s  .  co  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) {

    /*// w w w .j  a v a2s.  c o  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);
            }
        }
    }
}