List of usage examples for java.lang ClassLoader loadClass
public Class<?> loadClass(String name) throws ClassNotFoundException
From source file:com.scaleunlimited.cascading.DatumCompilerTest.java
@Test public void testUUID() throws Exception { CompiledDatum result = DatumCompiler.generate(MyUUIDDatumTemplate.class); File baseDir = new File("build/test/DatumCompilerTest/testUUID/"); FileUtils.deleteDirectory(baseDir);//from w w w .ja va 2 s. c om File srcDir = new File(baseDir, result.getPackageName().replaceAll("\\.", "/")); assertTrue(srcDir.mkdirs()); File codeFile = new File(srcDir, result.getClassName() + ".java"); OutputStream os = new FileOutputStream(codeFile); IOUtils.write(result.getClassCode(), os, "UTF-8"); os.close(); // Compile with Janino, give it a try. We have Janino since // it's a cascading dependency, but probably want to add a test // dependency on it. ClassLoader cl = new JavaSourceClassLoader(this.getClass().getClassLoader(), // parentClassLoader new File[] { baseDir }, // optionalSourcePath (String) null // optionalCharacterEncoding ); // WARNING - we have to use xxxDatumTemplate as the base name, so that the code returned // by the compiler is for type xxxDatum. Otherwise when we try to load the class here, // we'll likely get the base (template) class, which will mask our generated class. Class clazz = cl.loadClass(result.getPackageName() + "." + result.getClassName()); assertEquals("MyUUIDDatum", clazz.getSimpleName()); Constructor c = clazz.getConstructor(UUID.class); BaseDatum datum = (BaseDatum) c.newInstance(UUID.randomUUID()); // Verify that it can be serialized with Hadoop. // TODO figure out why Hadoop serializations aren't available??? /* BasePlatform testPlatform = new HadoopPlatform(DatumCompilerTest.class); Tap tap = testPlatform.makeTap( testPlatform.makeBinaryScheme(datum.getFields()), testPlatform.makePath("build/test/DatumCompilerTest/testSimpleSchema/")); TupleEntryCollector writer = tap.openForWrite(testPlatform.makeFlowProcess()); writer.add(datum.getTuple()); writer.close(); TupleEntryIterator iter = tap.openForRead(testPlatform.makeFlowProcess()); TupleEntry te = iter.next(); // TODO how to test round-trip? */ }
From source file:com.microsoft.tfs.core.internal.db.ConnectionConfiguration.java
public ConnectionConfiguration(final PersistenceStore cacheStore, final String pathId, final boolean verboseInput) { Check.notNull(cacheStore, "cacheStore"); //$NON-NLS-1$ pathIdentifer = Metadata.SCHEMA_VERSION + "-" + pathId; //$NON-NLS-1$ verbose = verboseInput;//w w w .j a va2 s . co m configuration = new Configuration(ConnectionConfiguration.class, "/" + DB_PROPS_FILE_NAME); //$NON-NLS-1$ driverClass = configuration.getConfiguration(DRIVER_CONFIG_KEY, DRIVER_DEFAULT); url = configuration.getConfiguration(URL_CONFIG_KEY, URL_DEFAULT); username = configuration.getConfiguration(USERNAME_CONFIG_KEY, USERNAME_DEFAULT); password = configuration.getConfiguration(PASSWORD_CONFIG_KEY, PASSWORD_DEFAULT); final String extraClasspath = configuration.getConfiguration(CLASSPATH_CONFIG_KEY, null); if (url.equals(URL_DEFAULT)) { if (cacheStore instanceof VersionedVendorFilesystemPersistenceStore) { /* * This may still return null if no candidate areas were * lockable. */ databaseDiskDirectory = getDirectoryForDiskDatabase( (VersionedVendorFilesystemPersistenceStore) cacheStore, pathIdentifer); } else { log.warn(MessageFormat.format( "The {0} used to create {1} is not a {2}, which is required to retarget HSQLDB storage (it can only use files). The fallback URL of {3} will be used.", //$NON-NLS-1$ PersistenceStore.class.getName(), ConnectionConfiguration.class.getName(), VersionedVendorFilesystemPersistenceStore.class.getName(), URL_FALLBACK)); } if (databaseDiskDirectory == null) { url = URL_FALLBACK; } else { final File db = new File(databaseDiskDirectory, "teamexplorer"); //$NON-NLS-1$ url = "jdbc:hsqldb:file:" + db.getAbsolutePath(); //$NON-NLS-1$ } } ClassLoader jdbcLoader = getClass().getClassLoader(); if (extraClasspath != null) { final File extraJar = new File(extraClasspath); try { jdbcLoader = new URLClassLoader(new URL[] { extraJar.toURL() }, jdbcLoader); } catch (final MalformedURLException ex) { throw new RuntimeException(ex); } } try { driver = (Driver) jdbcLoader.loadClass(driverClass).newInstance(); } catch (final Throwable t) { throw new RuntimeException(MessageFormat.format("unable to load specified jdbc driver class [{0}]", //$NON-NLS-1$ driverClass), t); } if (verbose) { System.out.println(MessageFormat.format("DB connection URL: [{0}]", url)); //$NON-NLS-1$ System.out.println(MessageFormat.format("DB driver class: [{0}] (version {1}.{2})", //$NON-NLS-1$ driver.getClass().getName(), Integer.toString(driver.getMajorVersion()), Integer.toString(driver.getMinorVersion()))); System.out.println(MessageFormat.format("DB driver loaded from: [{0}]", //$NON-NLS-1$ getDriverClassURL().toExternalForm())); } }
From source file:com.github.helenusdriver.commons.lang3.reflect.ReflectionUtils.java
/** * Find all classes from a given jar file and add them to the provided * list./*from www . ja va 2 s . c o m*/ * * @author paouelle * * @param classes the non-<code>null</code> collection of classes where to add new * found classes * @param url the non-<code>null</code> url for the jar where to find classes * @param resource the non-<code>null</code> resource being scanned that * corresponds to given package * @param cl the classloader to find the classes with */ private static void findClassesFromJar(Collection<Class<?>> classes, URL url, String resource, ClassLoader cl) { try { final JarURLConnection conn = (JarURLConnection) url.openConnection(); final URL jurl = conn.getJarFileURL(); try (final JarInputStream jar = new JarInputStream(jurl.openStream());) { while (true) { final JarEntry entry = jar.getNextJarEntry(); if (entry == null) { break; } final String name = entry.getName(); if (name.endsWith(".class") && name.startsWith(resource)) { final String cname = name.substring(0, name.length() - 6 // 6 for .class ).replace(File.separatorChar, '.'); try { classes.add(cl.loadClass(cname)); } catch (ClassNotFoundException e) { // ignore it } } } } } catch (IOException e) { throw new IllegalArgumentException("unable to find classes in package", e); } }
From source file:com.scaleunlimited.cascading.DatumCompilerTest.java
@Test public void testSimpleSchema() throws Exception { CompiledDatum result = DatumCompiler.generate(MyDatumTemplate.class); File baseDir = new File("build/test/DatumCompilerTest/testSimpleSchema/"); FileUtils.deleteDirectory(baseDir);//from w w w . j a va 2s . c om File srcDir = new File(baseDir, result.getPackageName().replaceAll("\\.", "/")); assertTrue(srcDir.mkdirs()); File codeFile = new File(srcDir, result.getClassName() + ".java"); OutputStream os = new FileOutputStream(codeFile); IOUtils.write(result.getClassCode(), os, "UTF-8"); os.close(); // Compile with Janino, give it a try. We have Janino since // it's a cascading dependency, but probably want to add a test // dependency on it. ClassLoader cl = new JavaSourceClassLoader(this.getClass().getClassLoader(), // parentClassLoader new File[] { baseDir }, // optionalSourcePath (String) null // optionalCharacterEncoding ); // WARNING - we have to use xxxDatumTemplate as the base name, so that the code returned // by the compiler is for type xxxDatum. Otherwise when we try to load the class here, // we'll likely get the base (template) class, which will mask our generated class. Class clazz = cl.loadClass(result.getPackageName() + "." + result.getClassName()); assertEquals("MyDatum", clazz.getSimpleName()); // Verify that we have a constructor which takes all of the fields. // private String _name; // private int ageAndRisk; // private Date _date; // private Tuple _aliases; // private String[] _phoneNumbers // private MyDatumEnum _enum Constructor c = clazz.getConstructor(String.class, int.class, Date.class, Tuple.class, String[].class, MyDatumEnum.class); BaseDatum datum = (BaseDatum) c.newInstance("robert", 25, new Date(), new Tuple("bob", "rob"), new String[] { "555-1212", "555-4848" }, MyDatumEnum.DATUM_COMPILER_ENUM_2); // Verify that it can be serialized with Hadoop. // TODO figure out why Hadoop serializations aren't available??? /* BasePlatform testPlatform = new HadoopPlatform(DatumCompilerTest.class); Tap tap = testPlatform.makeTap( testPlatform.makeBinaryScheme(datum.getFields()), testPlatform.makePath("build/test/DatumCompilerTest/testSimpleSchema/")); TupleEntryCollector writer = tap.openForWrite(testPlatform.makeFlowProcess()); writer.add(datum.getTuple()); writer.close(); TupleEntryIterator iter = tap.openForRead(testPlatform.makeFlowProcess()); TupleEntry te = iter.next(); // TODO how to test round-trip? */ }
From source file:com.netflix.simianarmy.basic.BasicSimianArmyContext.java
/** * Load a class specified by the config; for drop-in replacements. * (Duplicates a method in MonkeyServer; refactor to util?). * * @param key/*w w w . j a v a 2 s .co m*/ * @return */ @SuppressWarnings("rawtypes") private Class loadClientClass(String key) { ClassLoader classLoader = getClass().getClassLoader(); try { String clientClassName = config.getStrOrElse(key, null); if (clientClassName == null || clientClassName.isEmpty()) { LOGGER.info("using standard class for " + key); return null; } Class newClass = classLoader.loadClass(clientClassName); LOGGER.info("using " + key + " loaded " + newClass.getCanonicalName()); return newClass; } catch (ClassNotFoundException e) { throw new RuntimeException("Could not load " + key, e); } }
From source file:org.bytesoft.bytejta.supports.spring.TransactionEndpointPostProcessor.java
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { ClassLoader cl = Thread.currentThread().getContextClassLoader(); BeanDefinition protocolDef = null;//w ww .ja v a 2 s. com List<BeanDefinition> beanDefList = new ArrayList<BeanDefinition>(); String[] beanNameArray = beanFactory.getBeanDefinitionNames(); for (int i = 0; i < beanNameArray.length; i++) { String beanName = beanNameArray[i]; BeanDefinition beanDef = beanFactory.getBeanDefinition(beanName); String beanClassName = beanDef.getBeanClassName(); Class<?> beanClass = null; try { beanClass = cl.loadClass(beanClassName); } catch (Exception ex) { continue; } if (TransactionEndpointAware.class.isAssignableFrom(beanClass)) { beanDefList.add(beanDef); } else if (ProtocolConfig.class.isAssignableFrom(beanClass)) { if (protocolDef == null) { protocolDef = beanDef; } else { throw new FatalBeanException( "There are more than one com.alibaba.dubbo.config.ProtocolConfig was found!"); } } } if (protocolDef == null) { throw new FatalBeanException( "No configuration of class com.alibaba.dubbo.config.ProtocolConfig was found."); } MutablePropertyValues protocolValues = protocolDef.getPropertyValues(); PropertyValue protocolValue = protocolValues.getPropertyValue("port"); if (protocolValue == null || protocolValue.getValue() == null) { throw new FatalBeanException("Attribute 'port' of <dubbo:protocol ... /> is null."); } String host = CommonUtils.getInetAddress(); String port = String.valueOf(protocolValue.getValue()); String identifier = String.format("%s:%s", host, port); for (int i = 0; i < beanDefList.size(); i++) { BeanDefinition beanDef = beanDefList.get(i); MutablePropertyValues mpv = beanDef.getPropertyValues(); mpv.addPropertyValue(TransactionEndpointAware.ENDPOINT_FIELD_NAME, identifier); } }
From source file:com.edgenius.wiki.render.impl.MacroManagerImpl.java
public void load() { ClassLoader classLoader = Macro.class.getClassLoader(); BufferedReader is = null;/*from w w w .ja v a 2s .c o m*/ try { is = new BufferedReader(new InputStreamReader(classLoader.getResourceAsStream(macroResource))); String macroClz; while ((macroClz = is.readLine()) != null) { //get macro class if (StringUtils.isBlank(macroClz) || macroClz.trim().startsWith("#")) { //skip comment continue; } try { Object obj = classLoader.loadClass(macroClz.trim()).newInstance(); if (obj instanceof Macro) { Macro macro = (Macro) obj; macro.init(applicationContext); String[] names = macro.getName(); container.put(names, macro); log.info("Macro class loading success:" + names[0]); //put to containerIndex, so that macro can quick locate when try to get by name for (String name : names) { containerIndex.put(name.toLowerCase(), names); } if (obj instanceof ImmutableContentMacro) { if (!macro.isPaired()) { AuditLogger.error( "Unexpected case: ImmutableMacro is not paired macro, is that correct?" + Arrays.toString(macro.getName())); throw new Exception( "Unexpected case: ImmutableMacro is not paired macro, is that correct?" + Arrays.toString(macro.getName())); } immutableContentMacroMap.add(macro); } } } catch (Exception e) { log.error("Initial macro class " + macroClz + " failed. This macro is ignored!!!", e); } } } catch (IOException e) { log.error("Macro resource file " + macroResource + " not found.", e); } finally { IOUtils.closeQuietly(is); } }
From source file:org.bytesoft.bytetcc.supports.spring.CompensableEndpointPostProcessor.java
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { ClassLoader cl = Thread.currentThread().getContextClassLoader(); BeanDefinition protocolDef = null;//from ww w. java 2 s .c o m List<BeanDefinition> beanDefList = new ArrayList<BeanDefinition>(); String[] beanNameArray = beanFactory.getBeanDefinitionNames(); for (int i = 0; i < beanNameArray.length; i++) { String beanName = beanNameArray[i]; BeanDefinition beanDef = beanFactory.getBeanDefinition(beanName); String beanClassName = beanDef.getBeanClassName(); Class<?> beanClass = null; try { beanClass = cl.loadClass(beanClassName); } catch (Exception ex) { logger.debug("Cannot load class {}, beanId= {}!", beanClassName, beanName, ex); continue; } if (CompensableEndpointAware.class.isAssignableFrom(beanClass)) { beanDefList.add(beanDef); } else if (ProtocolConfig.class.isAssignableFrom(beanClass)) { if (protocolDef == null) { protocolDef = beanDef; } else { throw new FatalBeanException( "There are more than one com.alibaba.dubbo.config.ProtocolConfig was found!"); } } } if (protocolDef == null) { throw new FatalBeanException( "No configuration of class com.alibaba.dubbo.config.ProtocolConfig was found."); } MutablePropertyValues protocolValues = protocolDef.getPropertyValues(); PropertyValue protocolValue = protocolValues.getPropertyValue("port"); if (protocolValue == null || protocolValue.getValue() == null) { throw new FatalBeanException("Attribute 'port' of <dubbo:protocol ... /> is null."); } String host = CommonUtils.getInetAddress(); String port = String.valueOf(protocolValue.getValue()); String identifier = String.format("%s:%s", host, port); for (int i = 0; i < beanDefList.size(); i++) { BeanDefinition beanDef = beanDefList.get(i); MutablePropertyValues mpv = beanDef.getPropertyValues(); mpv.addPropertyValue(CompensableEndpointAware.ENDPOINT_FIELD_NAME, identifier); } }
From source file:jfs.sync.JFSFileProducerManager.java
/** * Registers all factories and sets the default factory. *//* w ww . j a va 2 s . c o m*/ @SuppressWarnings("unchecked") private JFSFileProducerManager() { factories = new HashMap<String, JFSFileProducerFactory>(); Properties p = new Properties(); ClassLoader classLoader = this.getClass().getClassLoader(); try { p.load(classLoader.getResourceAsStream("producers.properties")); } catch (Exception e) { log.error("JFSFileProducerManager()", e); } // try/catch for (Object property : p.keySet()) { String className = "" + property; if (className.startsWith("jfs.sync.")) { if ("on".equals(p.getProperty(className))) { try { Class<JFSFileProducerFactory> c = (Class<JFSFileProducerFactory>) classLoader .loadClass(className); Constructor<JFSFileProducerFactory> constructor = c.getConstructor(new Class<?>[0]); JFSFileProducerFactory factory = constructor.newInstance(new Object[0]); String name = factory.getName(); factories.put(name, factory); } catch (Exception e) { log.error("JFSFileProducerManager()", e); } // try/catch } // if } // if } // for defaultFactory = factories.get(JFSLocalFileProducerFactory.SCHEME_NAME); }
From source file:de.klemp.middleware.controller.Controller.java
/** * !!!! Important Method for creating new classes !!!! This method returns * the different classes of the first and second component. If a new class * is created, then it has to be added into this method. This method is * needed for the GUI. Method which use this method: getClassNames(...), * searchMethods(), getMethod()/*from w w w . jav a 2s. com*/ * * @param component * 1 or 2 * @return ArrayList: list with objects of the classes */ private static ArrayList<Object> getClasses(String component) { // http://tutorials.jenkov.com/java-reflection/dynamic-class-loading-reloading.html // http://stackoverflow.com/questions/1456930/how-do-i-read-all-classes-from-a-java-package-in-the-classpath // http://www.dzone.com/snippets/get-all-classes-within-package ArrayList<Object> classes = new ArrayList<Object>(); Enumeration<URL> urls; try { ClassLoader loader = Thread.currentThread().getContextClassLoader(); urls = loader.getResources(component); while (urls.hasMoreElements()) { URL url = urls.nextElement(); File file = new File(url.getFile()); File[] files = file.listFiles(); for (int i = 0; i < files.length; i++) { String[] f = files[i].getName().split("\\."); Class c; try { c = loader.loadClass(component + "." + f[0]); classes.add(c.newInstance()); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) { logger.error("Classes could not be refreshed", e); } } } } catch (IOException e) { logger.error("SQL Exception", e); } return classes; }