io.github.lukehutch.fastclasspathscanner.FastClasspathScanner Java Examples

The following examples show how to use io.github.lukehutch.fastclasspathscanner.FastClasspathScanner. 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: FCSPlugin.java    From redpipe with Apache License 2.0 6 votes vote down vote up
@Override
public Completable deployToResteasy(VertxResteasyDeployment deployment) {
	return Completable.defer(() -> {
		JsonArray packages = AppGlobals.get().getConfig().getJsonArray("scan");
		if(packages == null) {
			System.err.println("Not scanning any packages, please specify the 'scan' array of packages in configuration");
		}else {
			String[] packagesToScan = (String[]) packages.getList().toArray(new String[packages.size()]);
			new FastClasspathScanner(packagesToScan)
			.matchClassesWithAnnotation(Path.class, klass -> {
				if(!Modifier.isAbstract(klass.getModifiers()))
					deployment.getActualResourceClasses().add(klass);
			})
			.matchClassesWithAnnotation(Provider.class, klass -> {
				if(!Modifier.isAbstract(klass.getModifiers()))
					deployment.getActualProviderClasses().add(klass);
			})
			.scan();
		}
		return super.deployToResteasy(deployment);
	});
}
 
Example #2
Source File: BinLogDistributorClient.java    From kkbinlog with Apache License 2.0 6 votes vote down vote up
/**
 * 自动扫描注册handler
 *
 * @return
 */
public BinLogDistributorClient autoScanHandler() {
    //初始化handler
    System.getProperties().put("sun.misc.ProxyGenerator.saveGeneratedFiles", "true");
    List<Class<? extends DatabaseEventHandler>> tempHandlers = new ArrayList<>();
    new FastClasspathScanner().matchClassesImplementing(DatabaseEventHandler.class, tempHandlers::add).scan();
    tempHandlers.forEach(h -> {
        List<String> keys = addHandler(h);
        if (keys.size() > 0) {
            try {
                DatabaseEventHandler handler = h.newInstance();
                keys.forEach(k -> HANDLER_MAP.put(k, handler));
            } catch (InstantiationException | IllegalAccessException e) {
                log.severe(e.toString());
                e.printStackTrace();
            }
        }
    });
    return this;
}
 
Example #3
Source File: ProtocolSerializer.java    From reef with Apache License 2.0 6 votes vote down vote up
/**
 * Finds all of the messages in the specified packaged and calls register.
 * @param messagePackage A string which contains the full name of the
 *                       package containing the protocol messages.
 */
@Inject
private ProtocolSerializer(
    @Parameter(ProtocolSerializerNamespace.class) final String messagePackage) {

  // Build a list of the message reflection classes.
  final ScanResult scanResult = new FastClasspathScanner(messagePackage).scan();
  final List<String> scanNames = scanResult.getNamesOfSubclassesOf(SpecificRecordBase.class);
  final List<Class<?>> messageClasses = scanResult.classNamesToClassRefs(scanNames);

  // Add the header message from the org.apache.reef.wake.avro.message package.
  messageClasses.add(Header.class);

  // Register all of the messages in the specified package.
  for (final Class<?> cls : messageClasses) {
    this.register(cls);
  }
}
 
Example #4
Source File: JsonldContextFactory.java    From jackson-jsonld with MIT License 6 votes vote down vote up
public static ObjectNode fromPackage(String packageName) {
    ObjectNode generatedContext = JsonNodeFactory.withExactBigDecimals(true).objectNode();
    FastClasspathScanner scanner = new FastClasspathScanner(packageName);
    scanner.matchAllStandardClasses((clazz) -> {
        if(!Modifier.isAbstract(clazz.getModifiers()) && AnnotationsUtils.isAnnotationPresent(clazz, JsonldTypeFromJavaClass.class)) {
            Optional<String> type = JsonldResourceUtils.dynamicTypeLookup(clazz);
            type.ifPresent(t ->generatedContext.set(clazz.getSimpleName(), TextNode.valueOf(t)));
        }
        if(AnnotationsUtils.isAnnotationPresent(clazz, ioinformarics.oss.jackson.module.jsonld.annotation.JsonldResource.class)) {
            Optional<ObjectNode> resourceContext = fromAnnotations(clazz);
            resourceContext.ifPresent((context) -> JsonUtils.merge(generatedContext, context));
        }
    });
    scanner.scan();
    return (ObjectNode) JsonNodeFactory.withExactBigDecimals(true).objectNode().set("@context", generatedContext);
}
 
Example #5
Source File: ClassScanner.java    From bender with Apache License 2.0 6 votes vote down vote up
public static Set<Class> getSubtypes(List<Class> clazzes)
    throws InterruptedException, ExecutionException {
  Set<Class> classSet = new HashSet<Class>();
  int threads = Runtime.getRuntime().availableProcessors();
  ExecutorService pool = Executors.newFixedThreadPool(threads);
  Future<ScanResult> futureScan =
      new FastClasspathScanner("com.nextdoor.bender").scanAsync(pool, threads);
  ScanResult s = futureScan.get();

  for (Class<? extends AbstractConfig<?>> clazz : clazzes) {
    s.getNamesOfSubclassesOf(clazz).forEach(c -> {
      try {
        classSet.add((Class<? extends AbstractConfig<?>>) Class.forName(c));
      } catch (ClassNotFoundException e) {
      }
    });
  }
  pool.shutdown();

  /*
   * Remove abstract classes as they are not allowed in the mapper
   */
  classSet.removeIf(p -> Modifier.isAbstract(p.getModifiers()) == true);

  return classSet;
}
 
Example #6
Source File: ReflectionTypeDictionaryFactory.java    From ja-micro with Apache License 2.0 6 votes vote down vote up
public Map<MessageType, Parser<com.google.protobuf.Message>> populateParsersFromClasspath() {
    Map<MessageType, Parser<com.google.protobuf.Message>> parsers = new HashMap<>();
    List<Class<? extends com.google.protobuf.GeneratedMessageV3>> foundProtoMessages = new ArrayList<>();

    new FastClasspathScanner()
            .matchSubclassesOf(com.google.protobuf.GeneratedMessageV3.class, matchingClass ->
                    foundProtoMessages.add(matchingClass)).scan();

    // This algorithm adds parsers for all protobuf messages in the classpath including base types such as com.google.protobuf.DoubleValue.
    for (Class<? extends com.google.protobuf.GeneratedMessageV3> clazz : foundProtoMessages) {
        try {
            java.lang.reflect.Method method = clazz.getMethod("parser"); // static method, no arguments
            @SuppressWarnings("unchecked")
            Parser<com.google.protobuf.Message> parser = (Parser<com.google.protobuf.Message>) method.invoke(null, (Object[]) null); // static method, no arguments
            parsers.put(MessageType.of(clazz), parser);

            // too noisy: logger.debug("Added parser for protobuf type {}", clazz.getTypeName());

        } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException ignored) {
            // too noisy: logger.debug("Ignoring protobuf type {} as we cannot invoke static method parse().", clazz.getTypeName());
        }
    }

    return parsers;
}
 
Example #7
Source File: AbstractServiceAutomaticHandlerRegistrationTest.java    From ja-micro with Apache License 2.0 6 votes vote down vote up
@Test
public void it_should_find_handlers() throws Exception {
    TestService service = new TestService();
    service.initializeGuice();

    FastClasspathScanner scanner = new FastClasspathScanner();
    ScanResult scanResult = scanner.scan();
    List<String> rpcHandlers = scanResult.getNamesOfClassesWithAnnotation(RpcHandler.class);

    service.registerMethodHandlers(rpcHandlers);

    Map<String, ServiceMethodHandler<? extends Message, ? extends Message>> s = service.getMethodHandlers();
    assertThat(s.size() == 2);
    assertThat(s.containsKey("Test.handler1"));
    assertThat(s.containsKey("Test.handler2"));
    assertThat(s.get("Test.handler1").getClass().equals(TestHandler.class));
    assertThat(s.get("Test.handler2").getClass().equals(TestHandler2.class));
}
 
Example #8
Source File: HashClassfileContents.java    From uavstack with Apache License 2.0 6 votes vote down vote up
public HashClassfileContents(String... packagePrefixesToScan) {
    this.classNameToClassfileHash = new HashMap<String, String>();
    this.scanner = new FastClasspathScanner(packagePrefixesToScan)
    // MD5-hash all files ending in ".class"
            .matchFilenameExtension("class", new FileMatchProcessor() {
                @Override
                public void processMatch(String relativePath, InputStream inputStream, int length)
                        throws IOException {
                    final MessageDigest digest;
                    try {
                        digest = MessageDigest.getInstance("MD5");
                    } catch (NoSuchAlgorithmException e) {
                        throw new RuntimeException(e);
                    }
                    final byte[] buffer = new byte[8192];
                    for (int read; (read = inputStream.read(buffer)) > 0;) {
                        digest.update(buffer, 0, read);
                    }
                    String hash = "0000000000000000000000000000000"
                            + new BigInteger(1, digest.digest()).toString(16);
                    String className = relativePath.substring(0, relativePath.length() - 6).replace('/', '.');
                    classNameToClassfileHash.put(className, hash.substring(hash.length() - 32));
                }
            });
}
 
Example #9
Source File: TestScanner.java    From scheduler with GNU Lesser General Public License v3.0 5 votes vote down vote up
public List<TestCampaign> testGroups(String... groups) throws IllegalAccessException, InvocationTargetException, InstantiationException {
    List<Executable> ms = new ArrayList<>();
    Set<String> ok = Stream.of(groups).collect(Collectors.toSet());

    FastClasspathScanner scanner = new FastClasspathScanner();
    scanner.matchClassesWithMethodAnnotation(CstrTest.class, (cl, m) -> {
        CstrTest a = m.getAnnotation(CstrTest.class);
        for (String g : a.groups()) {
            if (ok.contains(g)) {
                ms.add(m);
            }
        }
    }).scan(Runtime.getRuntime().availableProcessors() - 1);
    return test(ms.toArray(new Method[ms.size()]));
}
 
Example #10
Source File: FastclassPathScannerProvider.java    From nubes with Apache License 2.0 5 votes vote down vote up
public FastclassPathScannerProvider(String ppackage){
    packageName = ppackage;

    if (cachedScans.containsKey(ppackage)){
    }else{
        FastClasspathScanner fastClasspathScanner = new FastClasspathScanner(ppackage);
        ScanResult scanResult = fastClasspathScanner.scan();
        cachedScans.put(ppackage, scanResult);
    }
}
 
Example #11
Source File: FCSClassFinderImpl.java    From qaf with MIT License 5 votes vote down vote up
@Override
public List<Class<?>> getClasses(String pkg) throws IOException {
	List<Class<?>> classes = new ArrayList<Class<?>>();
	List<String> classNames =
			new FastClasspathScanner(pkg).scan().getNamesOfAllClasses();
	for (String className : classNames) {
		try {
			classes.add(Class.forName(className));
		} catch (Throwable e) {
			System.err.println(e.getMessage());
		}
	}
	return classes;
}
 
Example #12
Source File: MSCPProfileHandler.java    From uavstack with Apache License 2.0 5 votes vote down vote up
public void handle(String compnentClass, String featureName, ProfileElementInstance inst,
        FastClasspathScanner fcs) {

    List<String> MSCPComponents = fcs.getNamesOfSubclassesOf(compnentClass);

    for (String MSCPComponent : MSCPComponents) {
        this.process(MSCPComponent, featureName, inst);
    }
}
 
Example #13
Source File: ComponentProfileHandler.java    From uavstack with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
private void getDynInfoForWebService(String componentClassName, ProfileElementInstance inst, ProfileContext context,
        Map<String, Class<?>> annoAvailableClasses, FastClasspathScanner fcs) {

    if (!componentClassName.equals("javax.jws.WebService")) {
        return;
    }

    Class<?> annoClass = annoAvailableClasses.get(componentClassName);
    if (null == annoClass) {
        return;
    }

    List<String> coms = fcs.getNamesOfClassesWithAnnotation(annoClass);

    if (null == coms || coms.isEmpty()) {
        return;
    }
    // construct data "dyn" for webservice
    InterceptContext ic = context.get(InterceptContext.class);
    List<WebServiceProfileInfo> wsli = (ArrayList<WebServiceProfileInfo>) ic.get("webservice.profile.info");
    if (wsli == null || wsli.isEmpty()) {
        return;
    }
    for (WebServiceProfileInfo wslinfo : wsli) {
        String url = wslinfo.getUrl();
        String clazz = (wslinfo.getImpl() instanceof String) ? (String) wslinfo.getImpl()
                : wslinfo.getImpl().getClass().getName();
        if (coms.contains(clazz)) {
            Map<String, Object> dynInfos = new LinkedHashMap<String, Object>();
            Map<String, Object> info = (Map<String, Object>) inst.getValues().get(clazz);
            dynInfos.put("url", url);
            dynInfos.put("className", clazz);
            info.put("dyn", dynInfos);
            inst.getValues().put(clazz, info);
        }
    }

}
 
Example #14
Source File: ComponentProfileHandler.java    From uavstack with Apache License 2.0 5 votes vote down vote up
/**
 * loadComponentsByDynamic
 * 
 * @param context
 * 
 * @param context
 * @param componentClassName
 * @param inst
 * @param context
 */
protected void loadComponentsByDynamic(InterceptContext itContext, String componentClassName,
        ProfileElementInstance inst, ProfileContext context, Map<String, Class<?>> annoAvailableClasses,
        FastClasspathScanner fcs) {

    /**
     * NOTE: in order to compatible with Servlet 2.5, using Reflection to call the Dynamic Servlet Profiling
     */
    getDynInfoForServlet(itContext, componentClassName, inst, context);
    // in order to compatible with jax-ws
    getDynInfoForWebService(componentClassName, inst, context, annoAvailableClasses, fcs);

}
 
Example #15
Source File: ComponentProfileHandler.java    From uavstack with Apache License 2.0 5 votes vote down vote up
/**
 * TODO:need scan out all classes extends from "javax.ws.rs.core.Application"
 */
@SuppressWarnings("unused")
private List<Class<?>> figureOutResourcesFromApplicationClasses(ProfileContext context) {

    FastClasspathScanner fcs = context.get(FastClasspathScanner.class);

    List<String> applicationClasses = fcs.getNamesOfSubclassesOf("javax.ws.rs.core.Application");

    if (null == applicationClasses || applicationClasses.size() == 0) {
        return null;
    }
    // TODO: no finish
    return null;
}
 
Example #16
Source File: WebServiceListener.java    From uavstack with Apache License 2.0 5 votes vote down vote up
public void doInstallDProxy(ClassLoader webapploader, final String appid, String contextPath) {

        // like SMS, which uses the sun jax-ws RI/Metro-jax-ws RI bind webservices when the servlet starts should
        // profile in ComponentProfileHandler

        FastClasspathScanner fcs = new FastClasspathScanner(new ClassLoader[] { webapploader });
        fcs.scan();
        List<String> endPoints = fcs.getNamesOfDirectSubclassesOf("javax.xml.ws.Endpoint");

        if (!endPoints.isEmpty()) {
            dpInstall.setTargetClassLoader(webapploader);

            for (int i = 0; i < endPoints.size(); i++) {

                dpInstall.installProxy(endPoints.get(i),
                        new String[] { "com.creditease.uav.monitorframework.webservice.interceptors" },
                        new DynamicProxyProcessor() {

                            @Override
                            public void process(DPMethod m) throws Exception {

                                if ("publish".equals(m.getName()) && m.getParameterTypes().length > 0
                                        && m.getParameterTypes()[0].getSimpleName().equals("String")) {

                                    dpInstall.defineLocalVal(m, "mObj", WebServiceListenerIT.class);
                                    m.insertBefore("{mObj=new WebServiceListenerIT(\"" + appid
                                            + "\");mObj.obtainWsInfo($1,getImplementor());}");

                                }

                            }
                        }, false);
            }

            // release loader
            dpInstall.releaseTargetClassLoader();
        }

    }
 
Example #17
Source File: RpcMethodScanner.java    From ja-micro with Apache License 2.0 5 votes vote down vote up
public List<String> getGeneratedProtoClasses(String serviceName) {
    FastClasspathScanner cpScanner = new FastClasspathScanner();
    ScanResult scanResult = cpScanner.scan();
    List<String> oldProtobuf = scanResult.getNamesOfSubclassesOf(GeneratedMessage.class);
    List<String> newProtobuf = scanResult.getNamesOfSubclassesOf(GeneratedMessageV3.class);
    List<String> retval = Stream.concat(oldProtobuf.stream(),
            newProtobuf.stream()).collect(Collectors.toList());
    String[] packageTokens = serviceName.split("\\.");
    return retval.stream().filter(s -> protoFilePackageMatches(s, packageTokens)).collect(Collectors.toList());
}
 
Example #18
Source File: TracingModule.java    From ja-micro with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
private Object findTracingPlugin(Injector injector) {
    Object retval = null;
    String pluginName = serviceProperties.getProperty("tracing");
    if (StringUtils.isBlank(pluginName)) {
        logger.debug("no tracing plugin set, defaulting to 'noop'");
        pluginName = "noop";
    }
    if (plugins == null) {
        plugins = new FastClasspathScanner().scan().getNamesOfClassesWithAnnotation(TracingPlugin.class);
    }
    boolean found = false;
    for (String plugin : plugins) {
        try {
            @SuppressWarnings("unchecked")
            Class<? extends TracingPlugin> pluginClass = (Class<? extends TracingPlugin>) Class.forName(plugin);
            TracingPlugin anno = pluginClass.getAnnotation(TracingPlugin.class);
            if (anno != null && pluginName.equals(anno.name())) {
                retval = injector.getInstance(pluginClass);
                found = true;
                break;
            }
        } catch (ClassNotFoundException e) {
            logger.error("Tracing plugin not found", e);
        }
    }
    if (! found) {
        logger.warn("Tracing plugin '{}' was not found in the class path", pluginName);
    }
    return retval;
}
 
Example #19
Source File: MetricsReporterModule.java    From ja-micro with Apache License 2.0 5 votes vote down vote up
private Object findPlugin(Injector injector) {
    Object retval = null;
    ServiceProperties serviceProperties = injector.getInstance(ServiceProperties.class);
    String pluginName = serviceProperties.getProperty("metricsReporter");
    if (StringUtils.isBlank(pluginName)) {
        return null;
    }
    if (plugins == null) { // only scan if not already set
        plugins = new FastClasspathScanner().scan().getNamesOfClassesWithAnnotation(MetricsReporterPlugin.class);
    }
    boolean found = false;
    for (String plugin : plugins) {
        try {
            @SuppressWarnings("unchecked") Class<? extends MetricsReporterPlugin> pluginClass =
                    (Class<? extends MetricsReporterPlugin>) Class.forName(plugin);
            MetricsReporterPlugin anno = pluginClass.getAnnotation(MetricsReporterPlugin.class);
            if (anno != null && pluginName.equals(anno.name())) {
                retval = injector.getInstance(pluginClass);
                found = true;
                break;
            }
        } catch (ClassNotFoundException e) {
            logger.error("MetricsReporterPlugin not found", e);
        }
    }
    if (! found) {
        logger.warn("Metrics reporting plugin '{}' was not found in the class path", pluginName);
    }
    return retval;
}
 
Example #20
Source File: ServiceRegistryModule.java    From ja-micro with Apache License 2.0 5 votes vote down vote up
private Object findServiceRegistryPlugin(Injector injector) {
    Object retval = null;
    String pluginName = serviceProperties.getProperty("registry");
    if (StringUtils.isBlank(pluginName)) {
        return null;
    }
    if (serviceRegistryPlugins == null) { // only scan if not already set
        serviceRegistryPlugins = new FastClasspathScanner().scan().getNamesOfClassesWithAnnotation(ServiceRegistryPlugin.class);
    }
    boolean found = false;
    for (String plugin : serviceRegistryPlugins) {
        try {
            @SuppressWarnings("unchecked")
            Class<? extends ServiceRegistryPlugin> pluginClass =
                    (Class<? extends ServiceRegistryPlugin>) Class.forName(plugin);
            ServiceRegistryPlugin anno = pluginClass.getAnnotation(ServiceRegistryPlugin.class);
            if (anno != null && pluginName.equals(anno.name())) {
                retval = injector.getInstance(pluginClass);
                found = true;
                break;
            }
        } catch (ClassNotFoundException e) {
            logger.error("ServiceRegistryPlugin not found", e);
        }
    }
    if (! found) {
        logger.warn("Registry plugin '{}' was not found in the class path", pluginName);
    }
    return retval;
}
 
Example #21
Source File: ConfigurationModule.java    From ja-micro with Apache License 2.0 5 votes vote down vote up
private Object findConfigurationPlugin(Injector injector) {
    Object retval = null;
    String pluginName = serviceProperties.getProperty("configuration");
    if (StringUtils.isBlank(pluginName)) {
        return null;
    }
    if (configurationPlugins == null) { // only scan if not already set
        configurationPlugins = new FastClasspathScanner().scan().getNamesOfClassesWithAnnotation(ConfigurationPlugin.class);
    }
    boolean found = false;
    for (String plugin : configurationPlugins) {
        try {
            @SuppressWarnings("unchecked")
            Class<? extends ConfigurationPlugin> pluginClass =
                    (Class<? extends ConfigurationPlugin>) Class.forName(plugin);
            ConfigurationPlugin anno = pluginClass.getAnnotation(ConfigurationPlugin.class);
            if (anno != null && pluginName.equals(anno.name())) {
                retval = injector.getInstance(pluginClass);
                found = true;
                break;
            }
        } catch (ClassNotFoundException e) {
            logger.error("ConfigurationPlugin not found", e);
        }
    }
    if (! found) {
        logger.warn("Configuration plugin '{}' was not found in the class path", pluginName);
    }
    return retval;
}
 
Example #22
Source File: MSCPProfileHandler.java    From uavstack with Apache License 2.0 4 votes vote down vote up
@Override
public void doProfiling(ProfileElement elem, ProfileContext context) {

    UAVServer.ServerVendor sv = (UAVServer.ServerVendor) UAVServer.instance()
            .getServerInfo(CaptureConstants.INFO_APPSERVER_VENDOR);

    // only support MSCP Application
    if (sv != UAVServer.ServerVendor.MSCP) {
        return;
    }

    if (!ProfileConstants.PROELEM_COMPONENT.equals(elem.getElemId())) {
        return;
    }

    InterceptContext ic = context.get(InterceptContext.class);

    if (ic == null) {
        this.logger.warn("Profile:Annotation FAILs as No InterceptContext available", null);
        return;
    }

    /**
     * 1. get webappclassloader
     */
    ClassLoader webappclsLoader = (ClassLoader) ic.get(InterceptConstants.WEBAPPLOADER);

    if (null == webappclsLoader) {
        this.logger.warn("Profile:JARS FAILs as No webappclsLoader available", null);
        return;
    }

    Collection<ClassLoader> clList = ConfigurationManager.getInstance().getFeatureClassLoader();
    clList.add(webappclsLoader);

    ClassLoader[] allcl = new ClassLoader[clList.size()];
    allcl = clList.toArray(allcl);

    /**
     * 2. see what kind of components we could get via annotations or interface or parentClass
     */
    FastClasspathScanner fcs = new FastClasspathScanner(allcl, "com.creditease.uav", "com.creditease.agent",
            "org.uavstack");
    fcs.scan();

    /**
     * 3. get MSCPServlets profile info
     */

    InterceptContext itContext = context.get(InterceptContext.class);
    String appRootPath = (String) itContext.get(InterceptConstants.BASEPATH);
    String appName = (String) itContext.get(InterceptConstants.APPNAME);

    for (String componentClassName : componentClassMap.keySet()) {

        // set the instance id = simple name of the annotation class
        ProfileElementInstance inst = elem.getInstance(componentClassName);

        ComponentProcessor cp = componentClassMap.get(componentClassName);

        cp.handle(componentClassName, appName, inst, fcs);

    }

    /**
     * 4. load application info
     */
    loadAppInfo(elem, appRootPath, appName);
}
 
Example #23
Source File: ReflectionTypeDictionaryFactory.java    From ja-micro with Apache License 2.0 4 votes vote down vote up
public Map<MessageType, MessageHandler<? extends com.google.protobuf.Message>> populateHandlersFromClasspath() {
    Map<MessageType, MessageHandler<? extends com.google.protobuf.Message>> handlers = new HashMap<>();

    List<Class<? extends MessageHandler>> foundHandlers = new ArrayList<>();

    new FastClasspathScanner()
            .matchClassesImplementing(MessageHandler.class, matchingClass ->
                    foundHandlers.add(matchingClass)).scan();

    foundHandlers.forEach((handlerClass) -> {
        Type[] interfaces = handlerClass.getGenericInterfaces();

        for (Type it : interfaces) {
            if (it instanceof ParameterizedType) {

                ParameterizedType pt = ((ParameterizedType) it);

                if (pt.getRawType().getTypeName().equals((MessageHandler.class.getTypeName()))) {
                    // We expect exactly one type argument
                    Type t = pt.getActualTypeArguments()[0];

                    MessageType type = MessageType.of(t);
                    MessageHandler<? extends com.google.protobuf.Message> handler = null;

                    try {
                        // Ask Guice for an instance of the handler.
                        // We cannot simply use e.g. the default constructor as any meaningful handler would need to
                        // be wired to dependencies such as databases, metrics, etc.
                        handler = (MessageHandler<? extends com.google.protobuf.Message>) injector.getInstance(handlerClass);
                    } catch (ConfigurationException | ProvisionException e) {
                        logger.warn("Cannot instantiate MessageHandler {} using Guice.", handlerClass, e);
                    }

                    if (handler != null) {
                        MessageHandler previous = handlers.put(type, handler);
                        if (previous == null) {
                            logger.info("Added message handler {} for type {}", handlerClass, type);
                        } else {
                            logger.warn("Duplicate message handler {} for type {} was replaced by {}", previous.getClass().getTypeName(), type, handlerClass);
                        }
                    }
                }
            } else {
                logger.warn("Cannot add untyped instance of MessageHander {} to TypeDictionary", handlerClass.getTypeName());
            }
        }
    });

    return handlers;
}
 
Example #24
Source File: JettyServiceBase.java    From ja-micro with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) {
    try {
        verifyDefaultCharset();

        // find main class, rpc handlers, healthcheck providers, serviceRegistryPlugins,
        // configuration plugins, and metrics reporting plugins
        List<String> serviceEntries = new ArrayList<>();
        List<String> rpcHandlers = new ArrayList<>();
        List<String> hcProviders = new ArrayList<>();
        List<String> serviceRegistryPlugins = new ArrayList<>();
        List<String> configPlugins = new ArrayList<>();
        List<String> metricsReportingPlugins = new ArrayList<>();
        List<String> tracingPlugins = new ArrayList<>();

        new FastClasspathScanner()
                .matchClassesWithAnnotation(OrangeMicroservice.class, matchingClass ->
                        serviceEntries.add(matchingClass.getName()))
                .matchClassesWithAnnotation(RpcHandler.class, matchingClass ->
                        rpcHandlers.add(matchingClass.getName()))
                .matchClassesWithAnnotation(HealthCheckProvider.class, matchingClass ->
                        hcProviders.add(matchingClass.getName()))
                .matchClassesWithAnnotation(ServiceRegistryPlugin.class, matchingClass ->
                        serviceRegistryPlugins.add(matchingClass.getName()))
                .matchClassesWithAnnotation(ConfigurationPlugin.class, matchingClass ->
                        configPlugins.add(matchingClass.getName()))
                .matchClassesWithAnnotation(MetricsReporterPlugin.class, matchingClass ->
                        metricsReportingPlugins.add(matchingClass.getName()))
                .matchClassesWithAnnotation(TracingPlugin.class, matchingClass ->
                        tracingPlugins.add(matchingClass.getName()))
                .scan();

        if (serviceEntries.isEmpty()) {
            logger.error("No OrangeMicroservice classes found");
            System.exit(-1);
        } else if (serviceEntries.size() > 1) {
            logger.error("More than one OrangeMicroservice class found: {}", serviceEntries);
            System.exit(-1);
        }
        //create main class
        Class<?> serviceClass = Class.forName(serviceEntries.get(0));
        AbstractService service = (AbstractService) serviceClass.newInstance();

        displayHelpAndExitIfNeeded(args, service);

        service.enableJmx();

        service.initProperties(args);

        service.setConfigurationPlugins(configPlugins);
        service.setServiceRegistryPlugins(serviceRegistryPlugins);
        service.setMetricsReporterPlugins(metricsReportingPlugins);
        service.setTracingPlugins(tracingPlugins);

        service.initializeConfigurationManager();

        service.initializeGuice();

        service.initializeMetricsReporting();

        service.initializeServiceDiscovery();

        service.registerMethodHandlers(rpcHandlers);
        service.registerMethodHandlers();

        //we have to start the container before service registration happens to know the port
        service.startJettyContainer();

        Annotation[] serviceAnnos = serviceClass.getAnnotations();

        service.initializeServiceRegistration();

        service.verifyEnvironment();

        //we start health checks first so we can see services with bad state
        if (!hcProviders.isEmpty()) {
            service.initializeHealthCheckManager(hcProviders);
        }

        if (hasAnnotation(serviceAnnos, EnableDatabaseMigration.class)) {
            //this will block until the database is available.
            //it will then attempt a migration.  if the migration fails,
            //   the process emits an error and pauses.  it's senseless to continue.
            service.performDatabaseMigration();
        }

        service.bootstrapComplete();
    } catch (Exception ex) {
        logger.error("Uncaught exception running service", ex);
    }
}
 
Example #25
Source File: FastClasspathScanningReflector.java    From typesafeconfig-guice with Apache License 2.0 4 votes vote down vote up
public FastClasspathScanningReflector(String ...scannerSpec) {
    this.scanner = new FastClasspathScanner(scannerSpec).enableMethodInfo().enableFieldInfo().ignoreFieldVisibility().ignoreMethodVisibility();
    this.scanResult = scanner.scan();
}
 
Example #26
Source File: SpecScanner.java    From scheduler with GNU Lesser General Public License v3.0 3 votes vote down vote up
public SpecScanner() {

        functions = Collections.synchronizedList(new ArrayList<>());
        sides = Collections.synchronizedList(new ArrayList<>());

        scanner = new FastClasspathScanner();
    }