List of usage examples for java.lang Class asSubclass
@SuppressWarnings("unchecked") public <U> Class<? extends U> asSubclass(Class<U> clazz)
From source file:edu.umich.flowfence.client.QuarentineModule.java
private static <T> Class<? extends T> checkClass(String className, Class<T> clazz, ClassLoader loader) throws ClassNotFoundException { Class<?> resultClazz; if ("void".equals(className)) { if ("void".equals(clazz.getName())) { return clazz; } else if ("java.lang.Void".equals(clazz.getName())) { return clazz; } else {//from w ww . j a v a 2s. c o m throw new ClassCastException("Void type in non-void context"); } } resultClazz = ClassUtils.getClass(loader, className, true); // Special handling for primitives. // If we can be handled by one of the primitive conversions, allow it. if (resultClazz.isPrimitive()) { if (ClassUtils.isAssignable(resultClazz, clazz, true)) { return clazz; } else { throw new ClassCastException("Cannot convert " + className + " to " + clazz.getName()); } } return resultClazz.asSubclass(clazz); }
From source file:org.apache.bval.jsr.DefaultValidationProviderResolver.java
/** * {@inheritDoc}//from w ww .j a va2s. c o m */ public List<ValidationProvider<?>> getValidationProviders() { List<ValidationProvider<?>> providers = new ArrayList<ValidationProvider<?>>(); try { // get our classloader ClassLoader cl = Thread.currentThread().getContextClassLoader(); if (cl == null) cl = DefaultValidationProviderResolver.class.getClassLoader(); // find all service provider cfgs Enumeration<URL> cfgs = cl.getResources(SPI_CFG); while (cfgs.hasMoreElements()) { final URL url = cfgs.nextElement(); BufferedReader br = null; try { br = new BufferedReader(new InputStreamReader(url.openStream()), 256); String line = br.readLine(); // cfgs may contain multiple providers and/or comments while (line != null) { line = line.trim(); if (!line.startsWith("#")) { try { // try loading the specified class @SuppressWarnings("rawtypes") final Class<? extends ValidationProvider> providerType = cl.loadClass(line) .asSubclass(ValidationProvider.class); // create an instance to return providers.add( Reflection.newInstance(providerType.asSubclass(ValidationProvider.class))); } catch (ClassNotFoundException e) { throw new ValidationException( "Failed to load provider " + line + " configured in file " + url, e); } } line = br.readLine(); } } catch (IOException e) { throw new ValidationException("Error trying to read " + url, e); } finally { if (br != null) { br.close(); } } } } catch (IOException e) { throw new ValidationException("Error trying to read a " + SPI_CFG, e); } // caller must handle the case of no providers found return providers; }
From source file:com.chiorichan.plugin.loader.PluginClassLoader.java
PluginClassLoader(final JavaPluginLoader loader, final ClassLoader parent, final PluginDescriptionFile description, final File dataFolder, final File file) throws InvalidPluginException, MalformedURLException { super(new URL[] { file.toURI().toURL() }, parent); Validate.notNull(loader, "Loader cannot be null"); this.loader = loader; this.description = description; this.dataFolder = dataFolder; this.file = file; try {// w w w. ja va 2s .c o m Class<?> jarClass; try { jarClass = Class.forName(description.getMain(), true, this); } catch (ClassNotFoundException ex) { throw new InvalidPluginException("Cannot find mane class `" + description.getMain() + "'", ex); } Class<? extends Plugin> pluginClass; try { pluginClass = jarClass.asSubclass(Plugin.class); } catch (ClassCastException ex) { throw new InvalidPluginException( "main class `" + description.getMain() + "' does not extend Plugin", ex); } plugin = pluginClass.newInstance(); } catch (IllegalAccessException ex) { throw new InvalidPluginException("No public constructor", ex); } catch (InstantiationException ex) { throw new InvalidPluginException("Abnormal plugin type", ex); } }
From source file:org.godhuli.rhipe.RHMR.java
public void setJob() throws ClassNotFoundException, IOException, URISyntaxException { Calendar cal = Calendar.getInstance(); SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_NOW); String jname = rhoptions_.get("rhipe_jobname"); boolean uscomb = false; if (jname.equals("")) job_.setJobName(sdf.format(cal.getTime())); else/*from w w w . j ava 2 s .c o m*/ job_.setJobName(jname); job_.setJarByClass(RHMR.class); // System.err.println(rhoptions_.get("rhipe_outputformat_class")); Class<?> clz = config_.getClassByName(rhoptions_.get("rhipe_outputformat_class")); Class<? extends OutputFormat> ofc = clz.asSubclass(OutputFormat.class); job_.setOutputFormatClass(ofc); Class<?> clz2 = config_.getClassByName(rhoptions_.get("rhipe_inputformat_class")); Class<? extends InputFormat> ifc = clz2.asSubclass(InputFormat.class); job_.setInputFormatClass(ifc); if (!rhoptions_.get("rhipe_input_folder").equals("")) FileInputFormat.setInputPaths(job_, rhoptions_.get("rhipe_input_folder")); // System.out.println("FOO"); // System.out.println(rhoptions_.get("rhipe.use.hadoop.combiner")); if (rhoptions_.get("rhipe.use.hadoop.combiner").equals("TRUE")) uscomb = true; String[] output_folder = rhoptions_.get("rhipe_output_folder").split(","); for (int i = 0; i < output_folder.length; i++) System.out.println(output_folder[i]); // System.exit(0); if (!rhoptions_.get("rhipe_partitioner_class").equals("none")) { RHMRHelper.PARTITION_START = Integer.parseInt(rhoptions_.get("rhipe_partitioner_start")) - 1; RHMRHelper.PARTITION_END = Integer.parseInt(rhoptions_.get("rhipe_partitioner_end")) - 1; Class<?> clz3 = config_.getClassByName(rhoptions_.get("rhipe_partitioner_class")); Class<? extends org.apache.hadoop.mapreduce.Partitioner> pc = clz3 .asSubclass(org.apache.hadoop.mapreduce.Partitioner.class); job_.setPartitionerClass(pc); // String pt = rhoptions_.get("rhipe_partitioner_type"); // if(pt.equals("numeric")){ // RHMRHelper.PARTITION_TYPE = REXP.RClass.REAL; // }else if(pt.equals("string")){ // RHMRHelper.PARTITION_TYPE = REXP.RClass.STRING; // }else if(pt.equals("integer")){ // RHMRHelper.PARTITION_TYPE = REXP.RClass.INTEGER; // }else throw new IOException("Invalid class for the partitioner, must be one of numeric, string, integer"); } if (!output_folder[0].equals("")) { Path ofp = new Path(output_folder[0]); FileSystem srcFs = FileSystem.get(job_.getConfiguration()); srcFs.delete(ofp, true); if (rhoptions_.get("rhipe_outputformat_class") .equals("org.apache.hadoop.mapreduce.lib.output.NullOutputFormat")) { srcFs.mkdirs(ofp); } FileOutputFormat.setOutputPath(job_, ofp); job_.setMapOutputKeyClass(Class.forName(rhoptions_.get("rhipe_map_output_keyclass"))); job_.setMapOutputValueClass(Class.forName(rhoptions_.get("rhipe_map_output_valueclass"))); job_.setOutputKeyClass(Class.forName(rhoptions_.get("rhipe_outputformat_keyclass"))); job_.setOutputValueClass(Class.forName(rhoptions_.get("rhipe_outputformat_valueclass"))); } else { job_.setOutputFormatClass(org.apache.hadoop.mapreduce.lib.output.NullOutputFormat.class); job_.setOutputKeyClass(org.apache.hadoop.io.NullWritable.class); job_.setOutputValueClass(org.apache.hadoop.io.NullWritable.class); job_.setMapOutputKeyClass(org.apache.hadoop.io.NullWritable.class); job_.setMapOutputValueClass(org.apache.hadoop.io.NullWritable.class); } job_.setMapperClass(RHMRMapper.class); if (uscomb) job_.setCombinerClass(RHMRReducer.class); job_.setReducerClass(RHMRReducer.class); // System.out.println("Conf done"); }
From source file:net.dmulloy2.ultimatearena.api.ArenaLoader.java
protected final ArenaType loadArenaType(File file) throws InvalidArenaException { Validate.notNull(file, "file cannot be null!"); if (!file.exists()) throw new InvalidArenaException(new FileNotFoundException(file.getPath() + " does not exist")); ArenaDescription description = getArenaDescription(file); ArenaClassLoader loader;/*from ww w . j av a 2 s .c o m*/ try { loader = loadClasses(description.getName(), file); } catch (MalformedURLException ex) { throw new InvalidArenaException("Failed to load classes from file " + file.getName(), ex); } Class<?> jarClass; try { jarClass = Class.forName(description.getMain(), true, loader); } catch (ClassNotFoundException ex) { throw new InvalidArenaException("Cannot find main class '" + description.getMain() + "'", ex); } Class<? extends ArenaType> clazz; try { clazz = jarClass.asSubclass(ArenaType.class); } catch (ClassCastException ex) { throw new InvalidArenaException("Main class '" + jarClass.getName() + "' does not extend ArenaType", ex); } try { ArenaType type = clazz.newInstance(); type.initialize(plugin, description, loader, file, new File(plugin.getDataFolder(), type.getName())); return type; } catch (Throwable ex) { throw new InvalidArenaException("Failed to create and initialize instance", ex); } }
From source file:org.apache.bval.jsr.xml.ValidationParser.java
private void applyParameterNameProvider(final ValidationConfigType xmlConfig, final ConfigurationImpl targetConfig) { final String parameterNameProvider = xmlConfig.getParameterNameProvider(); if (targetConfig.getParameterNameProvider() == targetConfig.getDefaultParameterNameProvider()) { // ref == if (parameterNameProvider != null) { final Class<?> loaded = loadClass(parameterNameProvider); if (loaded != null) { final Class<? extends ParameterNameProvider> clazz = loaded .asSubclass(ParameterNameProvider.class); targetConfig.parameterNameProviderClass(clazz); log.log(Level.INFO, String.format("Using %s as validation provider.", parameterNameProvider)); } else { log.log(Level.SEVERE, "Can't load " + parameterNameProvider); }/*from w ww.j a va 2 s . c om*/ } } }
From source file:org.opt4j.config.ModuleAutoFinder.java
/** * Returns all not abstract classes that implement {@link PropertyModule}. * //from w ww .ja v a 2 s .c o m * @return all property modules */ protected Collection<Class<? extends Module>> getAll() { Starter starter = new Starter(); Collection<File> files = starter.addPlugins(); classLoader = ClassLoader.getSystemClassLoader(); String paths = System.getProperty("java.class.path"); StringTokenizer st = new StringTokenizer(paths, ";\n:"); while (st.hasMoreTokens()) { String path = st.nextToken(); File f = new File(path); if (f.exists()) { try { f = f.getCanonicalFile(); files.add(f); } catch (IOException e) { e.printStackTrace(); } } } List<Class<?>> classes = new ArrayList<Class<?>>(); for (File file : files) { if (isJar(file)) { try { classes.addAll(getAllClasses(new ZipFile(file))); } catch (ZipException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (UnsupportedClassVersionError e) { System.err.println(file + " not supported: bad version number"); } } else { classes.addAll(getAllClasses(file)); } } List<Class<? extends Module>> modules = new ArrayList<Class<? extends Module>>(); for (Class<?> clazz : classes) { if (Opt4JModule.class.isAssignableFrom(clazz) && !Modifier.isAbstract(clazz.getModifiers())) { Class<? extends Module> module = clazz.asSubclass(Module.class); Ignore i = module.getAnnotation(Ignore.class); if (i == null && !module.isAnonymousClass() && accept.transform(module) && !ignore.transform(module)) { modules.add(module); invokeOut("Add module: " + module.toString()); } } } return modules; }
From source file:com.chiorichan.plugin.loader.JavaPluginLoader.java
private void removeClass(String name) { Class<?> clazz = classes.remove(name); try {/* w w w.j a v a 2s. c om*/ if ((clazz != null) && (ConfigurationSerializable.class.isAssignableFrom(clazz))) { Class<? extends ConfigurationSerializable> serializable = clazz .asSubclass(ConfigurationSerializable.class); ConfigurationSerialization.unregisterClass(serializable); } } catch (NullPointerException ex) { // Boggle! // (Native methods throwing NPEs is not fun when you can't stop it before-hoof) } }
From source file:org.apache.nifi.web.security.spring.LoginIdentityProviderFactoryBean.java
private LoginIdentityProvider createLoginIdentityProvider(final String identifier, final String loginIdentityProviderClassName) throws Exception { // get the classloader for the specified login identity provider final ClassLoader loginIdentityProviderClassLoader = ExtensionManager .getClassLoader(loginIdentityProviderClassName); if (loginIdentityProviderClassLoader == null) { throw new Exception( String.format("The specified login identity provider class '%s' is not known to this nifi.", loginIdentityProviderClassName)); }/*from w w w. j a v a 2s. co m*/ // get the current context classloader final ClassLoader currentClassLoader = Thread.currentThread().getContextClassLoader(); final LoginIdentityProvider instance; try { // set the appropriate class loader Thread.currentThread().setContextClassLoader(loginIdentityProviderClassLoader); // attempt to load the class Class<?> rawLoginIdentityProviderClass = Class.forName(loginIdentityProviderClassName, true, loginIdentityProviderClassLoader); Class<? extends LoginIdentityProvider> loginIdentityProviderClass = rawLoginIdentityProviderClass .asSubclass(LoginIdentityProvider.class); // otherwise create a new instance Constructor constructor = loginIdentityProviderClass.getConstructor(); instance = (LoginIdentityProvider) constructor.newInstance(); // method injection performMethodInjection(instance, loginIdentityProviderClass); // field injection performFieldInjection(instance, loginIdentityProviderClass); // call post construction lifecycle event instance.initialize(new StandardLoginIdentityProviderInitializationContext(identifier, this)); } finally { if (currentClassLoader != null) { Thread.currentThread().setContextClassLoader(currentClassLoader); } } return withNarLoader(instance); }