Java Code Examples for org.reflections.util.ClasspathHelper

The following examples show how to use org.reflections.util.ClasspathHelper. These examples are extracted from open source projects. 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 Project: smart-admin   Source File: DataScopeSqlConfigService.java    License: MIT License 7 votes vote down vote up
/**
 * 刷新 所有添加数据范围注解的接口方法配置<class.method,DataScopeSqlConfigDTO></>
 *
 * @return
 */
private Map<String, DataScopeSqlConfigDTO> refreshDataScopeMethodMap() {
    Reflections reflections = new Reflections(new ConfigurationBuilder().setUrls(ClasspathHelper.forPackage(scanPackage)).setScanners(new MethodAnnotationsScanner()));
    Set<Method> methods = reflections.getMethodsAnnotatedWith(DataScope.class);
    for (Method method : methods) {
        DataScope dataScopeAnnotation = method.getAnnotation(DataScope.class);
        if (dataScopeAnnotation != null) {
            DataScopeSqlConfigDTO configDTO = new DataScopeSqlConfigDTO();
            configDTO.setDataScopeType(dataScopeAnnotation.dataScopeType().getType());
            configDTO.setJoinSql(dataScopeAnnotation.joinSql());
            configDTO.setWhereIndex(dataScopeAnnotation.whereIndex());
            dataScopeMethodMap.put(method.getDeclaringClass().getSimpleName() + "." + method.getName(), configDTO);
        }
    }
    return dataScopeMethodMap;
}
 
Example 2
/**
 * Prepares the logger context. Locates the context and
 * sets the configuration file.
 * @return the logger context
 */
private ServletContextListener prepareAndgetContextListener() {
    try {
        if (StringUtils.isNotBlank(this.loggerContextPackageName)) {
            final Collection<URL> set = ClasspathHelper.forPackage(this.loggerContextPackageName);
            final Reflections reflections = new Reflections(new ConfigurationBuilder().addUrls(set).setScanners(new SubTypesScanner()));
            final Set<Class<? extends ServletContextListener>> subTypesOf = reflections.getSubTypesOf(ServletContextListener.class);
            final ServletContextListener loggingContext = subTypesOf.iterator().next().newInstance();
            this.context.setInitParameter(this.logConfigurationField, this.logConfigurationFile.getURI().toString());
            return loggingContext;
        }
        return null;
    } catch (final Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example 3
Source Project: kafka-connect-twitter   Source File: SchemaGeneratorTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void tweetEntities() {
  Reflections reflections = new Reflections(new ConfigurationBuilder()
      .setUrls(ClasspathHelper.forJavaClassPath())
      .forPackages(TweetEntity.class.getPackage().getName())
  );

  List<Class<?>> allClasses = new ArrayList<>();
  List<Class<? extends TweetEntity>> classes = list(reflections, TweetEntity.class);
  allClasses.add(MediaEntity.Variant.class);
  allClasses.add(MediaEntity.Size.class);
  allClasses.addAll(classes);


  for (Class<?> cls : allClasses) {
    StringBuilder builder = new StringBuilder();
    processClass(cls, builder);

    System.out.println(builder);
  }


}
 
Example 4
public ReflectionsServiceDiscovery(String resourceSearchPackages, JsonServiceLocator locator) {
	this.locator = locator;

	ConfigurationBuilder builder = new ConfigurationBuilder();

	PreconditionUtil.assertNotNull("no resourceSearchPackage configured", resourceSearchPackages);

	FilterBuilder filter = new FilterBuilder();
	for (String resourceSearchPackage : resourceSearchPackages.split(",")) {
		builder = builder.addUrls(ClasspathHelper.forPackage(resourceSearchPackage));
		filter.includePackage(resourceSearchPackage);
	}
	filter.includePackage(Repository.class.getPackage().getName());
	filter.includePackage(ResourceRepository.class.getPackage().getName());
	builder = builder.filterInputsBy(filter);

	builder = builder.addUrls(ClasspathHelper.forClass(Repository.class));
	builder = builder.addUrls(ClasspathHelper.forClass(ResourceRepository.class));
	builder = builder.addUrls(ClasspathHelper.forClass(ResourceRepositoryV2.class));

	builder = builder.setScanners(new SubTypesScanner(false), new TypeAnnotationsScanner());
	reflections = new Reflections(builder);
}
 
Example 5
public void addLoader(ClassLoader loader) {
    if (builder == null) {
        this.builder = new ConfigurationBuilder();
        builder.setScanners(new SubTypesScanner(), new TypeAnnotationsScanner());
    }
    builder.addClassLoader(loader);
    builder.addUrls(ClasspathHelper.forClassLoader(loader));

    if(loader instanceof JoinClassLoader) {
        // When the object "reflections" is created in the method scanClassPath(), are scanned the URLs so
        // it is necessary to add the URLs from the enclosing class loader in the JoinClassLoader that it
        // contains the fixture classpath (see org.reflections.Reflections.scan()).
        builder.addUrls(ClasspathHelper.forClassLoader(((JoinClassLoader) loader).getEnclosingClassLoader()));
    }

    scanClassPath(builder);
}
 
Example 6
Source Project: anno4j   Source File: RoleClassLoader.java    License: Apache License 2.0 6 votes vote down vote up
private void scanConceptsWithReflections() throws ObjectStoreConfigException {
    logger.debug("Search for concepts with reflections");
    Set<URL> classpath = new HashSet<>();
    classpath.addAll(ClasspathHelper.forClassLoader());
    classpath.addAll(ClasspathHelper.forJavaClassPath());
    classpath.addAll(ClasspathHelper.forManifest());
    classpath.addAll(ClasspathHelper.forPackage(""));
    Reflections reflections = new Reflections(new ConfigurationBuilder()
            .setUrls(classpath)
.useParallelExecutor()
.filterInputsBy(FilterBuilder.parsePackages("-java, -javax, -sun, -com.sun"))
            .setScanners(new SubTypesScanner(), new TypeAnnotationsScanner()));

    Set<Class<?>> annotated = reflections.getTypesAnnotatedWith(Iri.class, true);
    logger.debug("Search for concepts with reflections resulted in " + annotated.size() + " classes");
    for (Class clazz : annotated) {
        logger.debug("Found concept class: " + clazz.getCanonicalName());
        roleMapper.addConcept(clazz);
    }
}
 
Example 7
Source Project: anno4j   Source File: ProxyCompileTool.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Creates an Anno4j instance that can use the concepts contained in the given JAR file.
 * @param ontologyJar A JAR file containing concepts.
 * @param classLoader The class loader to use.
 * @param persistSchemaAnnotations Whether schema annotations should be scanned.
 * @return Returns an Anno4j instance.
 * @throws Exception Thrown on error.
 */
private static Anno4j getAnno4jWithClassLoader(File ontologyJar, ClassLoader classLoader, boolean persistSchemaAnnotations) throws Exception {
    Set<URL> clazzes = new HashSet<>();
    clazzes.addAll(ClasspathHelper.forManifest(ontologyJar.toURI().toURL()));
    Anno4j anno4j = new Anno4j(new SailRepository(new MemoryStore()), new IDGeneratorAnno4jURN(), null, persistSchemaAnnotations, clazzes);

    // Register concepts found in JAR:
    RoleMapper mapper = anno4j.getObjectRepository().getConnection().getObjectFactory().getResolver().getRoleMapper();
    for (final String className : getClassNamesInJar(ontologyJar)) {
        Class<?> clazz = classLoader.loadClass(className);
        if(clazz.getAnnotation(Iri.class) != null) {
            mapper.addConcept(clazz);
        }
    }

    return anno4j;
}
 
Example 8
Source Project: robe   Source File: GuiceBundle.java    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Creates a {@link org.reflections.Reflections} with the given packages (configuration)
 *
 * @param scanPackages
 */
private void createReflections(String[] scanPackages) {
    if (scanPackages.length < 1) {
        LOGGER.warn("No package defined in configuration (scanPackages)!");
        return;
    }
    ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
    FilterBuilder filterBuilder = new FilterBuilder();
    for (String packageName : scanPackages) {
        configurationBuilder.addUrls(ClasspathHelper.forPackage(packageName));
        filterBuilder.include(FilterBuilder.prefix(packageName));
    }

    configurationBuilder.filterInputsBy(filterBuilder).setScanners(new SubTypesScanner(), new TypeAnnotationsScanner());
    this.reflections = new Reflections(configurationBuilder);

}
 
Example 9
Source Project: yawp   Source File: ClassloaderScanner.java    License: MIT License 6 votes vote down vote up
private Reflections buildReflections(String packages) {
    String[] packagesArray = packages.replaceAll(" ", "").split(",");

    FilterBuilder filter = new FilterBuilder();

    Set<URL> urls = new HashSet();

    for (String packageStr : packagesArray) {
        urls.addAll(ClasspathHelper.forPackage(packageStr));
        filter.include(FilterBuilder.prefix(packageStr));
    }

    return new Reflections(new ConfigurationBuilder()
            .addUrls(urls)
            .filterInputsBy(filter)
            .setScanners(new TypeAnnotationsScanner(), new SubTypesScanner()));
}
 
Example 10
Source Project: streams   Source File: ElasticsearchParentChildUpdaterIT.java    License: Apache License 2.0 6 votes vote down vote up
@BeforeClass
public void prepareTestParentChildPersistUpdater() throws Exception {

  testConfiguration = new ComponentConfigurator<>(ElasticsearchWriterConfiguration.class).detectConfiguration( "ElasticsearchParentChildUpdaterIT");
  testClient = ElasticsearchClientManager.getInstance(testConfiguration).client();

  ClusterHealthRequest clusterHealthRequest = Requests.clusterHealthRequest();
  ClusterHealthResponse clusterHealthResponse = testClient.admin().cluster().health(clusterHealthRequest).actionGet();
  assertNotEquals(clusterHealthResponse.getStatus(), ClusterHealthStatus.RED);

  IndicesExistsRequest indicesExistsRequest = Requests.indicesExistsRequest(testConfiguration.getIndex());
  IndicesExistsResponse indicesExistsResponse = testClient.admin().indices().exists(indicesExistsRequest).actionGet();
  assertTrue(indicesExistsResponse.isExists());

  Reflections reflections = new Reflections(new ConfigurationBuilder()
      .setUrls(ClasspathHelper.forPackage("org.apache.streams.pojo.json"))
      .setScanners(new SubTypesScanner()));
  objectTypes = reflections.getSubTypesOf(ActivityObject.class);

  Path testdataDir = Paths.get("target/dependency/activitystreams-testdata");
  files = Files.list(testdataDir).collect(Collectors.toList());

}
 
Example 11
Source Project: streams   Source File: StreamsJacksonModule.java    License: Apache License 2.0 6 votes vote down vote up
public StreamsJacksonModule() {
  super();

  Reflections reflections = new Reflections(new ConfigurationBuilder()
      .setUrls(ClasspathHelper.forPackage("org.apache.streams.jackson"))
      .setScanners(new SubTypesScanner()));

  Set<Class<? extends StreamsDateTimeFormat>> dateTimeFormatClasses = reflections.getSubTypesOf(StreamsDateTimeFormat.class);

  List<String> dateTimeFormats = new ArrayList<>();
  for (Class dateTimeFormatClass : dateTimeFormatClasses) {
    try {
      dateTimeFormats.add(((StreamsDateTimeFormat) (dateTimeFormatClass.newInstance())).getFormat());
    } catch (Exception ex) {
      LOGGER.warn("Exception getting format from " + dateTimeFormatClass);
    }
  }

  addSerializer(DateTime.class, new StreamsDateTimeSerializer(DateTime.class));
  addDeserializer(DateTime.class, new StreamsDateTimeDeserializer(DateTime.class, dateTimeFormats));

  addSerializer(Period.class, new StreamsPeriodSerializer(Period.class));
  addDeserializer(Period.class, new StreamsPeriodDeserializer(Period.class));
}
 
Example 12
Source Project: streams   Source File: ActivitySerDeTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Tests that defined activity verbs have an example which can be loaded into
 * Activity beans and into verb-specific beans.
 * @throws Exception Exception
 */
@Test
public void testVerbSerDe() throws Exception {

  Reflections reflections = new Reflections(new ConfigurationBuilder()
      .setUrls(ClasspathHelper.forPackage("org.apache.streams.pojo.json"))
      .setScanners(new SubTypesScanner()));
  Set<Class<? extends Activity>> verbs = reflections.getSubTypesOf(Activity.class);

  for ( Class verbClass : verbs) {
    LOGGER.info("Verb: " + verbClass.getSimpleName() );
    Activity activity = (Activity) verbClass.newInstance();
    String verbName = activity.getVerb();
    String testfile = verbName.toLowerCase() + ".json";
    LOGGER.info("Serializing: activities/" + testfile );
    Path testActivityPath = Paths.get("target/dependency/activitystreams-testdata/" + testfile);
    assert (testActivityPath.toFile().exists());
    FileInputStream testActivityFileStream = new FileInputStream(testActivityPath.toFile());
    assert (testActivityFileStream != null);
    activity = MAPPER.convertValue(MAPPER.readValue(testActivityFileStream, verbClass), Activity.class);
    String activityString = MAPPER.writeValueAsString(activity);
    LOGGER.info("Deserialized: " + activityString );
    assert ( !activityString.contains("null") );
    assert ( !activityString.contains("[]") );
  }
}
 
Example 13
Source Project: elasticactors   Source File: MessagesScanner.java    License: Apache License 2.0 6 votes vote down vote up
@PostConstruct
public void init() {
    String[] basePackages = ScannerHelper.findBasePackagesOnClasspath(applicationContext.getClassLoader());
    ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();

    for (String basePackage : basePackages) {
        configurationBuilder.addUrls(ClasspathHelper.forPackage(basePackage));
    }

    Reflections reflections = new Reflections(configurationBuilder);

    Set<Class<?>> messageClasses = reflections.getTypesAnnotatedWith(Message.class);

    for (Class<?> messageClass : messageClasses) {
        Message messageAnnotation = messageClass.getAnnotation(Message.class);
        // get the serialization framework
        SerializationFramework framework = applicationContext.getBean(messageAnnotation.serializationFramework());
        framework.register(messageClass);
    }
}
 
Example 14
Source Project: spring-boot-starter-micro-job   Source File: ClassTools.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 获取指定package下的接口实现类
 *
 * @param scannerPackage 扫描的package
 * @return 实现类集合
 */
public static Set<Class<? extends JobTrigger>> getJobs(String scannerPackage) {
    ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
    configurationBuilder.setScanners(new TypeAnnotationsScanner(), new SubTypesScanner());
    configurationBuilder.filterInputsBy(new FilterBuilder().includePackage(scannerPackage));
    configurationBuilder.addUrls(ClasspathHelper.forPackage(scannerPackage));
    Reflections reflections = new Reflections(scannerPackage);
    return reflections.getSubTypesOf(JobTrigger.class);
}
 
Example 15
Source Project: Flink-CEPplus   Source File: CheckForbiddenMethodsUsage.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testNoDefaultEncoding() throws Exception {
	final Reflections reflections = new Reflections(new ConfigurationBuilder()
		.useParallelExecutor(Runtime.getRuntime().availableProcessors())
		.addUrls(ClasspathHelper.forPackage("org.apache.flink"))
		.addScanners(new MemberUsageScanner()));

	for (ForbiddenCall forbiddenCall : forbiddenCalls) {
		final Set<Member> methodUsages = forbiddenCall.getUsages(reflections);
		methodUsages.removeAll(forbiddenCall.getExclusions());
		assertEquals("Unexpected calls: " + methodUsages, 0, methodUsages.size());
	}
}
 
Example 16
Source Project: flink   Source File: CheckForbiddenMethodsUsage.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testNoDefaultEncoding() throws Exception {
	final Reflections reflections = new Reflections(new ConfigurationBuilder()
		.useParallelExecutor(Runtime.getRuntime().availableProcessors())
		.addUrls(ClasspathHelper.forPackage("org.apache.flink"))
		.addScanners(new MemberUsageScanner()));

	for (ForbiddenCall forbiddenCall : forbiddenCalls) {
		final Set<Member> methodUsages = forbiddenCall.getUsages(reflections);
		methodUsages.removeAll(forbiddenCall.getExclusions());
		assertEquals("Unexpected calls: " + methodUsages, 0, methodUsages.size());
	}
}
 
Example 17
Source Project: api-boot   Source File: ClassTools.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 初始化反射对象
 *
 * @param scannerPackage 扫描的package
 * @return 反射对象
 */
static Reflections initReflections(String scannerPackage) {
    ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
    configurationBuilder.setScanners(new TypeAnnotationsScanner(), new SubTypesScanner());
    configurationBuilder.filterInputsBy(new FilterBuilder().includePackage(scannerPackage));
    configurationBuilder.addUrls(ClasspathHelper.forPackage(scannerPackage));
    return new Reflections(scannerPackage);
}
 
Example 18
Source Project: jdmn   Source File: DecisionDiscovery.java    License: Apache License 2.0 5 votes vote down vote up
public Set<Class<?>> discover(String packagePrefix) {
    Reflections reflections = new Reflections(new ConfigurationBuilder()
            .setUrls(ClasspathHelper.forPackage(packagePrefix))
            .filterInputsBy(new FilterBuilder().includePackage(packagePrefix))
    );
    return reflections.getTypesAnnotatedWith(DRGElement.class);
}
 
Example 19
public Set<String> getConfigs() {
    Set<String> configs = new HashSet<>();
    Reflections reflections = new Reflections(new ConfigurationBuilder().setUrls(ClasspathHelper.forPackage(pacakgePath)).setScanners(new MethodParameterScanner()));
    Set<Method> methodsAnnotatedWith = reflections.getMethodsWithAnyParamAnnotated(ParamsValidate.class);
    Iterator<Method> it = methodsAnnotatedWith.iterator();
    while (it.hasNext()) {
        Method method = it.next();
        String classAndMethod = method.getDeclaringClass().getCanonicalName() + "." + method.getName();
        //生成expression配置
        String expression = "execution (* " + classAndMethod + "(..))";
        configs.add(expression);
    }
    return configs;
}
 
Example 20
Source Project: springboot-shiro-cas-mybatis   Source File: CasLoggerFactory.java    License: MIT License 5 votes vote down vote up
/**
 * Instantiates a new Cas logger factory.
 * Configures the reflection scanning engine to be prepared to scan <code>org.slf4j.impl</code>
 * in order to find other available factories.
 */
public CasLoggerFactory() {
    this.loggerMap = new ConcurrentHashMap<>();
    final Collection<URL> set = ClasspathHelper.forPackage(PACKAGE_TO_SCAN);
    final Reflections reflections = new Reflections(new ConfigurationBuilder().addUrls(set).setScanners(new SubTypesScanner()));

    final Set<Class<? extends ILoggerFactory>> subTypesOf = reflections.getSubTypesOf(ILoggerFactory.class);
    subTypesOf.remove(this.getClass());

    if (subTypesOf.size() > 1) {
        Util.report("Multiple ILoggerFactory bindings are found on the classpath:");
        for (final Class<? extends ILoggerFactory> c : subTypesOf) {
            Util.report("* " + c.getCanonicalName());
        }
    }

    if (subTypesOf.isEmpty()) {
        final RuntimeException e = new RuntimeException("No ILoggerFactory could be found on the classpath."
                + " CAS cannot determine the logging framework."
                + " Examine the project dependencies and ensure that there is one and only one logging framework available.");

        Util.report(e.getMessage(), e);
        throw e;
    }
    this.realLoggerFactoryClass = subTypesOf.iterator().next();
    Util.report("ILoggerFactory to be used for logging is: " + this.realLoggerFactoryClass.getName());
}
 
Example 21
Source Project: Civs   Source File: Civs.java    License: GNU General Public License v3.0 5 votes vote down vote up
private void instantiateSingletons() {
    ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
    FilterBuilder filterBuilder = new FilterBuilder();
    configurationBuilder.addUrls(ClasspathHelper.forPackage("org.redcastlemedia.multitallented.civs"));
    filterBuilder.includePackage("org.redcastlemedia.multitallented.civs")
            .excludePackage("org.redcastlemedia.multitallented.civs.dynmaphook")
            .excludePackage("org.redcastlemedia.multitallented.civs.placeholderexpansion");
    configurationBuilder.filterInputsBy(filterBuilder);
    Reflections reflections = new Reflections(configurationBuilder);
    Set<Class<?>> classes = reflections.getTypesAnnotatedWith(CivsSingleton.class);
    List<Class<?>> classList = new ArrayList<>(classes);
    classList.sort(new Comparator<Class<?>>() {
        @Override
        public int compare(Class<?> o1, Class<?> o2) {
            return o1.getAnnotation(CivsSingleton.class).priority().compareTo(o2.getAnnotation(CivsSingleton.class).priority());
        }
    });
    for (Class<?> currentSingleton : classList) {
        try {
            Method method = currentSingleton.getMethod("getInstance");
            if (method != null) {
                method.invoke(currentSingleton);
            }
        } catch (Exception e) {

        }
    }
}
 
Example 22
Source Project: jkes   Source File: ClassUtils.java    License: Apache License 2.0 5 votes vote down vote up
static Set<Class<?>> getClasses(String packageName) {
    List<ClassLoader> classLoadersList = new LinkedList<>();
    classLoadersList.add(ClasspathHelper.contextClassLoader());
    classLoadersList.add(ClasspathHelper.staticClassLoader());

    Reflections reflections = new Reflections(new ConfigurationBuilder()
            .setScanners(new SubTypesScanner(false /* don't exclude Object.class */), new ResourcesScanner())
            .setUrls(ClasspathHelper.forClassLoader(classLoadersList.toArray(new ClassLoader[0])))
            .filterInputsBy(new FilterBuilder().include(FilterBuilder.prefix(packageName))));

    Set<Class<?>> classes = reflections.getSubTypesOf(Object.class);
    return classes;
}
 
Example 23
private static void printUsage() {

		System.out.println("Usage: ./gradlew run -Pdemo=<demo>\n\nAvailable options for <demo>");

		List<ClassLoader> classLoadersList = new LinkedList<ClassLoader>();
		classLoadersList.add(ClasspathHelper.contextClassLoader());
		classLoadersList.add(ClasspathHelper.staticClassLoader());

		Reflections reflections = new Reflections(new ConfigurationBuilder()
		    .setScanners(new SubTypesScanner(false /* don't exclude Object.class */), new ResourcesScanner())
		    .setUrls(ClasspathHelper.forClassLoader(classLoadersList.toArray(new ClassLoader[0])))
		    .filterInputsBy(new FilterBuilder().include(FilterBuilder.prefix(testsPackage))));
		
		Set<Class<?>> classes = reflections.getSubTypesOf(Object.class);
		TreeSet<String> sortedClasses = new TreeSet<String>();
		HashMap<String,String> classDescriptions = new HashMap<String, String>();
		for (Class<? extends Object> cl : classes) {
			if (!cl.getSimpleName().equals("")) {
				sortedClasses.add(cl.getName().replace(testsPackage+".",""));
				String descString = "";
				if (cl.getAnnotation(DemoDescription.class) != null) descString = cl.getAnnotation(DemoDescription.class).desc();
				classDescriptions.put(cl.getName().replace(testsPackage+".",""),descString);
			}
		}
		for (String className : sortedClasses) {
			System.out.println();				
			List<String> descStrings = StringUtils.description("   \u001B[1m\u001b[32m"+className+"\u001b[0m: ", classDescriptions.get(className), 72, 6);
			for (String ds : descStrings) System.out.println(ds);
		}
		
		System.out.println();
		String note = "Most examples require the ReedsSheppCarPlanner motion planner, which is provided via a"
				+ "linked library that has to be built and depends on ompl (http://ompl.kavrakilab.org/)"
				+ "and mrpt (http://www.mrpt.org/). See REAME.md for building instructions.";
		List<String> formattedNote = StringUtils.description("NOTE: ", note, 72);
		for (String line : formattedNote) System.out.println(line);
		
	}
 
Example 24
Source Project: connect-utils   Source File: PluginLoader.java    License: Apache License 2.0 5 votes vote down vote up
public PluginLoader(Package pkg) {
  this.pkg = pkg;
  this.reflections = new Reflections(new ConfigurationBuilder()
      .setUrls(ClasspathHelper.forJavaClassPath())
      .forPackages(pkg.getName())
      .addScanners(new ResourcesScanner())
  );
}
 
Example 25
Source Project: funktion-connectors   Source File: ConnectorGenerator.java    License: Apache License 2.0 5 votes vote down vote up
private CamelCatalog createCamelCatalog() throws IOException{
    CamelCatalog result = new DefaultCamelCatalog(true);
    //add funktion camel components

    Predicate<String> filter = new FilterBuilder().includePackage("io.fabric8.funktion.camel");
    Reflections resources = new Reflections(new ConfigurationBuilder()
                                                .filterInputsBy(filter)
                                                .setScanners(new ResourcesScanner())
                                                .setUrls(ClasspathHelper.forJavaClassPath()));


    Set<String> jsonFiles = resources.getResources(Pattern.compile(".*\\.json"));


    LOG.info("Processing Funktion Camel components ...");
    for (String jsonFile: jsonFiles){
        InputStream inputStream = getClass().getClassLoader().getResourceAsStream(jsonFile);
        ObjectMapper mapper = new ObjectMapper();
        JsonNode root = mapper.readTree(inputStream);
        JsonNode component = root.path("component");
        if (!component.isMissingNode()) {
            String scheme = component.path("scheme").asText();
            String componentName = component.path("javaType").asText();
            result.addComponent(scheme,componentName);
            LOG.info("Processed component " + scheme);
        }else{
            LOG.error("Failed to find Component for " + jsonFile);
        }
    }
    return result;
}
 
Example 26
Source Project: drftpd   Source File: GlobalContext.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * If you're creating a GlobalContext object and it's not part of a TestCase
 * you're not doing it correctly, GlobalContext is a Singleton
 */
protected GlobalContext() {
    Reflections reflections = new Reflections(new ConfigurationBuilder()
            .setUrls(ClasspathHelper.forPackage("org.drftpd"))
            .setScanners(new MethodAnnotationsScanner()));

    hooksMethods = reflections.getMethodsAnnotatedWith(CommandHook.class);
    logger.debug("We have annotated (found) [{}] hook methods", hooksMethods.size());
}
 
Example 27
Source Project: sldeditor   Source File: RegisterClasses.java    License: GNU General Public License v3.0 5 votes vote down vote up
/**
 * Initialise.
 *
 * @param data the data
 */
public static void initialise(ConversionData data)
{
    List<ClassLoader> classLoadersList = new LinkedList<ClassLoader>();
    classLoadersList.add(ClasspathHelper.contextClassLoader());
    classLoadersList.add(ClasspathHelper.staticClassLoader());

    registerRenderers(classLoadersList, data);
    registerSymbols(classLoadersList, data);
    registerLabelRenderers(classLoadersList, data);
    registerTextBackground(classLoadersList, data);
    registerNumberFormat(classLoadersList, data);
}
 
Example 28
Source Project: java-flagz   Source File: ReflectionsCache.java    License: MIT License 5 votes vote down vote up
/**
 * Get the appropriate set of URLs.
 *
 * This returns a set of URLs for a given set of package prefixes. You can use an empty string
 * to get everything but it can be slow for big apps.
 */
private static Set<URL> urlsToReflect(List<String> packagePrefixes) {
  List<String> prefixesWithFlags = ImmutableList.<String>builder().addAll(packagePrefixes)
      .add("org.flagz").build();
  return prefixesWithFlags
      .stream()
      .flatMap(prefix -> ClasspathHelper.forPackage(prefix).stream())
      .collect(Collectors.toSet());
}
 
Example 29
Source Project: Java2PlantUML   Source File: Parser.java    License: Apache License 2.0 5 votes vote down vote up
private static Collection<URL> getUrls(List<ClassLoader> classLoadersList) {
    classLoadersList.add(ClasspathHelper.contextClassLoader());
    classLoadersList.add(ClasspathHelper.staticClassLoader());
    Collection<URL> urls = ClasspathHelper.forClassLoader(classLoadersList.toArray(new ClassLoader[0]));
    CLASS_LOADER = new URLClassLoader(urls.toArray(new URL[0]));
    return urls;
}
 
Example 30
Source Project: anno4j   Source File: OWLSchemaPersistingManagerTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testMatchingExistingSchema() throws Exception {
    Anno4j anno4j = new Anno4j();

    OWLClazz myPerson = anno4j.createObject(OWLClazz.class, (Resource) new URIImpl("http://example.de/#validly_annotated_person"));
    RDFSProperty bossProperty = anno4j.createObject(RDFSProperty.class, (Resource) new URIImpl("http://example.de/#has_boss"));

    Restriction bossAllValuesFromRestr = anno4j.createObject(Restriction.class);
    bossAllValuesFromRestr.setOnClazz(Sets.newHashSet(myPerson));
    bossAllValuesFromRestr.setOnProperty(Sets.newHashSet(bossProperty));
    bossAllValuesFromRestr.setAllValuesFrom(Sets.<OWLClazz>newHashSet(myPerson));

    Reflections types = new Reflections(
            new ConfigurationBuilder()
                    .setUrls(
                            ClasspathHelper.forClass(Person.class, ClasspathHelper.staticClassLoader()),
                            ClasspathHelper.forClass(PersonSupport.class, ClasspathHelper.staticClassLoader())
                    )
                    .setScanners(new MethodAnnotationsScanner(), new FieldAnnotationsScanner(), new TypeAnnotationsScanner(), new SubTypesScanner())
    );

    Transaction transaction = anno4j.createTransaction();
    transaction.begin();
    SchemaPersistingManager persistingManager = new OWLSchemaPersistingManager(transaction.getConnection());

    boolean exceptionThrown = false;
    try {
        persistingManager.persistSchema(types);
    } catch (SchemaPersistingManager.ContradictorySchemaException e) {
        exceptionThrown = true;
    }
    assertFalse(exceptionThrown);
}