public SlytherClient() { try { configuration = ConfigHandler.INSTANCE.readConfig(CONFIGURATION_FILE, ClientConfig.class); saveConfig(); } catch (IOException e) { UIUtils.displayException("Unable to read config", e); Log.catching(e); } temporaryServerSelection = configuration.server; Reflections reflections = new Reflections(""); Set<Class<?>> annotated = reflections.getTypesAnnotatedWith(Controller.class); for (Class<?> controller : annotated) { if (IController.class.isAssignableFrom(controller)) { try { Controller annotation = controller.getAnnotation(Controller.class); setController((IController) controller.getDeclaredConstructor().newInstance()); Log.info("Using controller \"{}\" ({})", annotation.name(), controller.getSimpleName()); break; } catch (Exception e) { } } } renderHandler = new RenderHandler(this); renderHandler.setup(); setup(); }
/** * This method assumes that the DDL updates are located in the classpath under the folder defined * by {@link #packagePrefix} The updates files must respect the pattern returned by {@link * #buildUpdateFilePattern(String)}. * * @param tableName The name of the table to load updates for. * @return The table updates. * @throws java.io.IOException If an I/O error occurs * @throws TableUpdatesNotFoundException If updates for the given tables are not found. */ @Override public SortedSet<Update> loadUpdates(String tableName) throws IOException, TableUpdatesNotFoundException { Reflections reflections = new Reflections(packagePrefix + tableName, new ResourcesScanner()); Set<String> resources = reflections.getResources(Pattern.compile(buildUpdateFilePattern(tableName))); if (resources.isEmpty()) { throw new TableUpdatesNotFoundException(tableName); } SortedSet<Update> updates = new TreeSet<Update>(Update.UPDATE_COMPARATOR); for (String resource : resources) { int id = extractIdFromFileName(new File(resource).getName()); BufferedReader reader = new BufferedReader( new InputStreamReader(ClassLoader.getSystemResourceAsStream(resource))); String line; StringBuilder ddl = new StringBuilder(); while ((line = reader.readLine()) != null) { ddl.append(line).append("\n"); } updates.add(new Update(id, ddl.toString())); } return updates; }
public List<VisTextButton> getButtons(Class<? extends Annotation> cls) { List<VisTextButton> btnList = new ArrayList<>(); Reflections r = new Reflections("net.ncguy.impossible.graph.nodes"); Set<Class<?>> clsSet = r.getTypesAnnotatedWith(cls); r.save("nodeBtns.bin"); System.out.println("gfdsgfd"); for (Class<?> c : clsSet) { VisTextButton btn = new VisTextButton("Add " + TextUtils.formatString(c.getSimpleName())); btn.addListener( new ClickListener() { @Override public void clicked(InputEvent event, float x, float y) { super.clicked(event, x, y); try { BaseNode node = (BaseNode) c.getConstructor(GraphBase.class).newInstance(graphBase); addNode(node); } catch (Exception e) { e.printStackTrace(); } graphBase.rebuildDnD(); } }); btnList.add(btn); } return btnList; }
@SuppressWarnings("unchecked") // apache commons collection api does not support generics public static Set<Class<? extends Page>> getAnnotatedWicketPage( String packageScanPath, Class<? extends Annotation> annotationClazz) { Reflections reflections = new Reflections(packageScanPath); return SetUtils.predicatedSet( reflections.getTypesAnnotatedWith(annotationClazz), PAGE_PREDICATE); }
/** * This processes the deployment dependencies, which are made available by the {@link * KieContainer} {@link ClassLoader}. * * @param kieContainer The {@link KieContainer}, used to get the {@link ClassLoader} * @param deployedUnit The {@link DeployedUnitImpl}, used to store the classes loaded */ protected void processClassloader(KieContainer kieContainer, DeployedUnitImpl deployedUnit) { if (kieContainer.getClassLoader() instanceof ProjectClassLoader) { ClassLoader parentCl = kieContainer.getClassLoader().getParent(); if (parentCl instanceof URLClassLoader) { URL[] urls = ((URLClassLoader) parentCl).getURLs(); if (urls == null || urls.length == 0) { return; } ConfigurationBuilder builder = new ConfigurationBuilder(); builder.addUrls(urls); builder.addClassLoader(kieContainer.getClassLoader()); Reflections reflections = new Reflections(builder); Set<Class<?>> xmlRootElemClasses = reflections.getTypesAnnotatedWith(XmlRootElement.class); Set<Class<?>> xmlTypeClasses = reflections.getTypesAnnotatedWith(XmlType.class); Set<Class<?>> remoteableClasses = reflections.getTypesAnnotatedWith(Remotable.class); Set<Class<?>> allClasses = new HashSet<Class<?>>(); for (Set<Class<?>> classesToAdd : new Set[] {xmlRootElemClasses, xmlTypeClasses, remoteableClasses}) { if (classesToAdd != null) { allClasses.addAll(classesToAdd); } } for (Class<?> clazz : allClasses) { filterClassesAddedToDeployedUnit(deployedUnit, clazz); } } } }
public static Set<Class<?>> getTypesAnnotatedWith( Class<? extends Annotation> annotation, ClassLoader... classLoaders) throws Exception { Set<Class<?>> implementations; implementations = (Set<Class<?>>) classesCache.get(annotation); ConfigurationBuilder cb = new ConfigurationBuilder() .setUrls(ClasspathHelper.forPackage("es.caib")) .setScanners(new SubTypesScanner(), new TypeAnnotationsScanner()); if (classLoaders != null && classLoaders.length != 0) { cb.addClassLoaders(classLoaders); } if (implementations == null) { implementations = new HashSet<Class<?>>(); Reflections ref = new Reflections(cb); Set<Class<?>> tmp = ref.getTypesAnnotatedWith(annotation); implementations.addAll(tmp); classesCache.put(annotation, implementations); } return implementations; }
/** * Finds all test resources and returns the information that JUnit needs to dynamically create the * corresponding test cases. * * @return the test data needed to dynamically create the test cases */ @Parameters(name = "test {index}: {5}: {6}") public static List<Object[]> data() { String filter = System.getProperty("okapi.symbol.test"); String backend = "uk.org.okapibarcode.backend"; Reflections reflections = new Reflections(backend); Set<Class<? extends Symbol>> symbols = reflections.getSubTypesOf(Symbol.class); List<Object[]> data = new ArrayList<>(); for (Class<? extends Symbol> symbol : symbols) { String symbolName = symbol.getSimpleName().toLowerCase(); if (filter == null || filter.equals(symbolName)) { String dir = "src/test/resources/" + backend.replace('.', '/') + "/" + symbolName; for (File file : getPropertiesFiles(dir)) { String fileBaseName = file.getName().replaceAll(".properties", ""); File codewordsFile = new File(file.getParentFile(), fileBaseName + ".codewords"); File pngFile = new File(file.getParentFile(), fileBaseName + ".png"); File errorFile = new File(file.getParentFile(), fileBaseName + ".error"); data.add( new Object[] { symbol, file, codewordsFile, pngFile, errorFile, symbolName, fileBaseName }); } } } return data; }
/** @return A list of the settings callbacks. */ public static Set<Method> getSettingsCallbacks() { // Init the search in the root package. Reflections reflections = new Reflections("org.saucistophe", new MethodAnnotationsScanner()); Set<Method> annotatedMethods = reflections.getMethodsAnnotatedWith(SettingsCallback.class); return annotatedMethods; }
/** @return A list of the settable fields. */ public static List<Field> getSettableFields() { // Init the search in the root package. Reflections reflections = new Reflections("org.saucistophe", new FieldAnnotationsScanner()); Set<Field> annotatedFields = reflections.getFieldsAnnotatedWith(SettingsField.class); // Turn the set to a list to sort it. List<Field> fieldsList = new ArrayList<>(annotatedFields); fieldsList.sort( (Field field1, Field field2) -> { // Retrieve the fields info. SettingsField fieldInfo1 = field1.getAnnotation(SettingsField.class); SettingsField fieldInfo2 = field2.getAnnotation(SettingsField.class); // If the name wasn't set, get the field's declared name. String actualName1 = fieldInfo1.name().isEmpty() ? field1.getName() : fieldInfo1.name(); String actualName2 = fieldInfo2.name().isEmpty() ? field2.getName() : fieldInfo2.name(); // Elaborate a sortable string representation. String sortableString1 = fieldInfo1.category() + "." + actualName1; String sortableString2 = fieldInfo2.category() + "." + actualName2; return sortableString1.compareTo(sortableString2); }); return fieldsList; }
private Iterator<Resource> getFilesFromParams() throws IOException { System.err.printf( "%s system property not specified, using 'dir'" + " parameter from configuration file\n", DIR_PROPERTY); String resource = (String) getConfigParameterValue("dir"); String suffix = (String) getConfigParameterValue("suffix"); if (resource != null) { System.err.printf("Reading files from classpath directory: %s\n", resource); Reflections reflections = new Reflections( new ConfigurationBuilder() .setUrls(ClasspathHelper.forPackage("")) .setScanners(new ResourcesScanner())); Set<String> files = reflections.getResources(Pattern.compile(".*\\." + suffix)); Collection<Resource> resources = Collections2.transform(files, new StringToResourceFunction("/")); final Pattern p = Pattern.compile("^" + resource); Collection<Resource> filtered = Collections2.filter( resources, new Predicate<Resource>() { @Override public boolean apply(Resource input) { Matcher m = p.matcher(input.name); return m.find(); } }); return filtered.iterator(); } else { throw new IOException(String.format("Parameter 'dir' must be specified")); } }
private void loadExtensionsFromClassloaders( Map<String, DefaultCoreExtension> extensions, DefaultCoreExtensionRepository repository) { Set<URL> mavenURLs = ClasspathHelper.forPackage(MAVENPACKAGE); ConfigurationBuilder configurationBuilder = new ConfigurationBuilder(); configurationBuilder.setScanners(new ResourcesScanner()); configurationBuilder.setUrls(mavenURLs); configurationBuilder.filterInputsBy( new FilterBuilder.Include(FilterBuilder.prefix(MAVENPACKAGE))); Reflections reflections = new Reflections(configurationBuilder); Set<String> descriptors = reflections.getResources(Predicates.equalTo("pom.xml")); for (String descriptor : descriptors) { URL descriptorUrl = getClass().getClassLoader().getResource(descriptor); try { DefaultCoreExtension coreExtension = parseMavenPom(descriptorUrl, repository); extensions.put(coreExtension.getId().getId(), coreExtension); } catch (Exception e) { this.logger.warn("Failed to pase extension descriptor [{}]", descriptorUrl, e); } } // Try to find more guess(extensions, repository); }
@Test public void testCommands() { Reflections reflections = new Reflections("com.greatmancode.craftconomy3.commands"); for (Class<? extends CommandExecutor> clazz : reflections.getSubTypesOf(CommandExecutor.class)) { try { CommandExecutor instance = clazz.newInstance(); if (instance.help() == null) { fail("Help is null for: " + clazz.getName()); } if (instance.maxArgs() < 0) { fail("Fail maxArgs for class: " + clazz.getName()); } if (instance.minArgs() < 0) { fail("Fail minArgs for class: " + clazz.getName()); } if (instance.maxArgs() < instance.minArgs()) { fail("Fail maxArgs less than minArgs for class:" + clazz.getName()); } if (instance.getPermissionNode() != null) { if (!instance.getPermissionNode().contains("craftconomy")) { fail("Fail permissionNode for class: " + clazz.getName()); } } if (!instance.playerOnly() && instance.playerOnly()) { fail("Fail playerOnly. Should never get this.."); } } catch (InstantiationException e) { fail(e.getMessage()); } catch (IllegalAccessException e) { fail(e.getMessage()); } } }
@Test public void testReflections() throws Exception { Reflections reflections = new Reflections( new ConfigurationBuilder() .setScanners(new ResourcesScanner()) .addClassLoader(Thread.currentThread().getContextClassLoader())); for (String s : reflections.getResources(Pattern.compile(".*\\.conf"))) { System.out.println(s); } reflections = new Reflections( "com", new Scanner() { public void setConfiguration(Configuration configuration) { int i1234 = 1234; i1234++; } public Multimap<String, String> getStore() { int i1234 = 1234; i1234++; return null; } public void setStore(Multimap<String, String> store) { int i1234 = 1234; i1234++; } public Scanner filterResultsBy(Predicate<String> filter) { int i1234 = 1234; i1234++; return null; } public boolean acceptsInput(String file) { int i1234 = 1234; i1234++; return false; } public void scan(File file) { // TODO Auto-generated method stub int i1234 = 1234; i1234++; } public boolean acceptResult(String fqn) { int i1234 = 1234; i1234++; return false; } }); }
private List<Class<? extends Job>> getJobClasses(Class annotation) { Set<Class<? extends Job>> jobs = (Set<Class<? extends Job>>) reflections.getSubTypesOf(Job.class); Set<Class<?>> annotatedClasses = reflections.getTypesAnnotatedWith(annotation); return Sets.intersection(new HashSet<Class<? extends Job>>(jobs), annotatedClasses) .immutableCopy() .asList(); }
public Set<String> findServiceImplementations( Class<?> serviceClass, ClassLoader classpathResourceLoader) { return ImmutableSet.copyOf( transform( intersection( reflections.getTypesAnnotatedWith(markerAnnotation), reflections.getSubTypesOf(serviceClass)), new ClassToName())); }
static { final Reflections reflections = new Reflections("uk.ac.ebi.interpro.scan.model"); final Set<Class<? extends Match>> allClasses = reflections.getSubTypesOf(Match.class); for (Class clazz : allClasses) { if (!Modifier.isAbstract(clazz.getModifiers())) { // Concrete only. CONCRETE_MATCH_CLASSES.add(clazz.getSimpleName()); } } }
@Override public DioritePlugin loadPlugin(final File file) throws PluginException { try { final PluginClassLoader classLoader = new PluginClassLoader(file); final ConfigurationBuilder config = new ConfigurationBuilder(); config.setClassLoaders(new PluginClassLoader[] {classLoader}); config.setUrls(ClasspathHelper.forClassLoader(classLoader)); final Reflections ref = new Reflections(config); final Set<Class<?>> annotated = ref.getTypesAnnotatedWith(Plugin.class); if (annotated.isEmpty()) { throw new PluginException("Plugin annotation doesn't found!"); } if (annotated.size() > 1) { throw new PluginException("Plugin has more than one main class!"); } final Class<?> mainClass = annotated.iterator().next(); if (!DioritePlugin.class.isAssignableFrom(mainClass)) { throw new PluginException("Main class must extend PluginMainClass!"); } final DioritePlugin dioritePlugin = (DioritePlugin) mainClass.newInstance(); final Plugin pluginDescription = mainClass.getAnnotation(Plugin.class); if (ServerImpl.getInstance().getPluginManager().getPlugin(pluginDescription.name()) != null) { throw new PluginException("Plugin " + pluginDescription.name() + " is arleady loaded!"); } dioritePlugin.init( classLoader, this, dioritePlugin, pluginDescription.name(), pluginDescription.version(), pluginDescription.author(), pluginDescription.description(), pluginDescription.website()); System.out.println( "Loading " + pluginDescription.name() + " v" + pluginDescription.version() + " by " + pluginDescription.author() + " from file " + file.getName()); dioritePlugin.onLoad(); return dioritePlugin; } catch (final InstantiationException | IllegalAccessException | MalformedURLException e) { throw new PluginException("Exception while loading plugin from file " + file.getName(), e); } }
/** * Find all the Java classes that have proper @ClientDtoFactoryVisitor annotation. * * @throws java.io.IOException */ @SuppressWarnings("unchecked") private static void findDtoFactoryVisitors() throws IOException { Reflections reflection = new Reflections(getConfigurationBuilder()); Set<Class<?>> classes = reflection.getTypesAnnotatedWith(ClientDtoFactoryVisitor.class); int i = 0; for (Class clazz : classes) { dtoFactoryVisitors.put(clazz.getCanonicalName(), "provider_" + i++); System.out.println( String.format("New DtoFactoryVisitor found: %s", clazz.getCanonicalName())); } System.out.println(String.format("Found: %d DtoFactoryVisitor(s)", dtoFactoryVisitors.size())); }
@Programmatic @Override public <T> Set<Class<? extends T>> findSubTypesOfClasses(Class<T> type) { Vfs.setDefaultURLTypes(getUrlTypes()); final Reflections reflections = new Reflections( ClasspathHelper.forClassLoader(Thread.currentThread().getContextClassLoader()), ClasspathHelper.forClass(Object.class), new SubTypesScanner(false)); return reflections.getSubTypesOf(type); }
@Parameterized.Parameters public static Collection<Class<? extends CompoundPredicate>> getCompoundPredicateImplementations() { // locate all classes which implement CompoundPredicate and exercise them Reflections reflections = new Reflections( new ConfigurationBuilder() .forPackages("com.hazelcast.query.impl.predicates") .addScanners(new SubTypesScanner()) .build()); return reflections.getSubTypesOf(CompoundPredicate.class); }
public static void loadMaps(String packageName) { Reflections reflections = new Reflections(packageName); Set<Class<?>> classes = reflections.getTypesAnnotatedWith(MapConfig.class); for (Class<?> clazz : classes) { try { Object map = clazz.newInstance(); maps.add((Map) map); } catch (Exception e) { logger.severe("Unable to load map: " + clazz.getName()); e.printStackTrace(); } } }
@Test public void findAllClasses() { Reflections reflections = new Reflections("example.module.workflow"); Set<Class<? extends Object>> classes = reflections.getTypesAnnotatedWith( example.module.workflow.annotation.WorkflowDefinition.class); Iterator<Class<? extends Object>> iterator = classes.iterator(); while (iterator.hasNext()) { Class<? extends Object> cls = iterator.next(); System.out.println(cls.getName()); } System.out.println("end"); }
public DisambiguationExtractorFactory() throws InstantiationException, IllegalAccessException { nameToId = new HashMap<String, String>(); idToName = new IdentityHashMap<String, String>(); Reflections reflections = new Reflections(THIS_PACKAGE); Set<Class<? extends DisambiguationExtractor>> classes = reflections.getSubTypesOf(DisambiguationExtractor.class); @SuppressWarnings("unchecked") Class<? extends DisambiguationExtractor>[] ar = classes.toArray(new Class[classes.size()]); String name, eid; for (Class<? extends DisambiguationExtractor> c : ar) { name = c.getSimpleName(); // if this is not extractor if (!name.startsWith("EX_")) { continue; } DisambiguationExtractor e = c.newInstance(); eid = e.getId(); // all extractors must have id if (eid == null || eid.isEmpty()) { String m = "Creating extractor: " + name + " with no id value given (null)."; logger.error(m); throw new IllegalStateException(m); } nameToId.put(name, eid); // checking, if every extractors has unique id if (idToName.containsKey(eid)) { String m = "Some extractors have the same id: " + eid + ": " + name + ", " + idToName.get(eid) + "."; logger.error(m); throw new IllegalStateException(m); } idToName.put(eid, name); } }
private Set<Class<?>> getAnnotatedClasses() { Reflections reflections; String classes = System.getProperty("operation_classes"); if (classes != null) { String[] split = classes.split(","); Set<Class<?>> classSet = new HashSet<>(split.length); for (String className : split) { reflections = new Reflections(className); classSet.addAll(reflections.getTypesAnnotatedWith(OperationsClass.class)); } return classSet; } reflections = new Reflections(); return reflections.getTypesAnnotatedWith(OperationsClass.class); }
public Loader() { Set<Class<?>> classes = getAnnotatedClasses(); Reflections reflections; instances = new HashMap<>(classes.size()); methods = new HashMap<>(); for (Class<?> clazz : classes) { putInstance(clazz); reflections = new Reflections(clazz.getPackage().getName(), new MethodAnnotationsScanner()); Set<Method> allMethods = reflections.getMethodsAnnotatedWith(Operation.class); for (Method method : allMethods) { methods.put(getOperationMask(method), method); } } LOGGER.debug("All operations successfully loaded"); }
public static Test suite() throws Exception { TestSuite mainSuite = new TestSuite("LexBIG validation tests"); Reflections reflections = new Reflections( "org.LexGrid.LexBIG", new TypeAnnotationsScanner(), new SubTypesScanner(false)); Set<Class<? extends Object>> allClasses = reflections.getTypesAnnotatedWith(RemoteApiSafeTest.class); for (Class test : allClasses) { mainSuite.addTestSuite(test); } return mainSuite; }
/** * Return all classes which extend our Command interface. * * @return */ private Set<Class<? extends Command>> getCommandClasses() { if (commandClasses != null) return commandClasses; commandClasses = reflections.getSubTypesOf(Command.class); Set<Class<? extends BaseCommand>> baseCommandClasses = reflections.getSubTypesOf(BaseCommand.class); for (Class<? extends BaseCommand> bc : baseCommandClasses) { commandClasses.add((Class<? extends Command>) bc); } if (commandClasses == null || commandClasses.size() == 0) { log.severe("No command classes found, HSP will not be able to register commands!"); } return commandClasses; }
@Override public List<MdTable> getTables() { List<MdTable> tables = new ArrayList<>(); for (String xmlFile : reflections.getStore().getResources(XML_FILE)) { try (InputStream is = getClass().getClassLoader().getResourceAsStream(xmlFile)) { List<MdTable> ts = getTables(is); int numTables = 0; if (ts != null) { tables.addAll(ts); numTables = ts.size(); for (MdTable t : ts) { t.getMetadata().put(TABLE_SOURCE_KEY, xmlFile); } } log.info(String.format("%d tables loaded from XML file: %s", numTables, xmlFile)); } catch (Exception ex) { if (log.isDebugEnabled()) { log.debug(String.format("Error while loading tables from XML file %s: %s", xmlFile, ex)); } } } return tables; }
@Test public void jaxbClassesTest() throws Exception { Assume.assumeTrue(TestType.JAXB.equals(getType())); Set<Class<?>> jaxbClasses = reflections.getTypesAnnotatedWith(XmlRootElement.class); assertTrue("Not enough classes found! [" + jaxbClasses.size() + "]", jaxbClasses.size() > 20); String className = null; try { for (Class<?> jaxbClass : jaxbClasses) { if (jaxbClass.getDeclaringClass() != null && jaxbClass.getDeclaringClass().getSimpleName().endsWith("Test")) { continue; } className = jaxbClass.getName(); Constructor<?> construct = jaxbClass.getConstructor(new Class[] {}); Object jaxbInst = construct.newInstance(new Object[] {}); testRoundTrip(jaxbInst); } } catch (Exception e) { e.printStackTrace(); fail(className + ": " + e.getClass().getSimpleName() + " [" + e.getMessage() + "]"); } }
public static <T extends Object> Set<Class<? extends T>> getSubTypesOfInterface( Class<T> interficie) throws Exception { Set<Class<? extends T>> implementations; implementations = (Set<Class<? extends T>>) classesCache.get(interficie); if (implementations == null) { implementations = new HashSet<Class<? extends T>>(); Reflections ref = getReflections(); Set<Class<? extends T>> tmp = ref.getSubTypesOf(interficie); implementations.addAll(tmp); classesCache.put(interficie, implementations); } return implementations; }