List of usage examples for java.lang ClassLoader ClassLoader
protected ClassLoader()
From source file:com.almende.eve.deploy.Boot.java
/** * The default agent booter. It takes an EVE yaml file and creates all * agents mentioned in the "agents" section. * /* w ww .j a va2 s . c o m*/ * @param args * Single argument: args[0] -> Eve yaml */ public static void main(final String[] args) { if (args.length == 0) { LOG.warning("Missing argument pointing to yaml file:"); LOG.warning("Usage: java -jar <jarfile> eve.yaml"); return; } final ClassLoader cl = new ClassLoader() { @Override protected Class<?> findClass(final String name) throws ClassNotFoundException { Class<?> result = null; try { result = super.findClass(name); } catch (ClassNotFoundException cne) { } if (result == null) { FileInputStream fi = null; try { String path = name.replace('.', '/'); fi = new FileInputStream(System.getProperty("user.dir") + "/" + path + ".class"); byte[] classBytes = new byte[fi.available()]; fi.read(classBytes); fi.close(); return defineClass(name, classBytes, 0, classBytes.length); } catch (Exception e) { LOG.log(Level.WARNING, "Failed to load class:", e); } } if (result == null) { throw new ClassNotFoundException(name); } return result; } }; String configFileName = args[0]; try { InputStream is = new FileInputStream(new File(configFileName)); boot(is, cl); } catch (FileNotFoundException e) { LOG.log(Level.WARNING, "Couldn't find configfile:" + configFileName, e); return; } }
From source file:org.wisdom.template.thymeleaf.OgnlOpsByReflectionTest.java
@BeforeClass public static void prepare() throws ClassNotFoundException { ClassLoader classLoader = new ClassLoader() { @Override//www.ja v a 2 s .c o m public Class<?> loadClass(String name) throws ClassNotFoundException { if (name.equals(OgnlOps.class.getName())) { byte[] clazz; try { clazz = FileUtils.readFileToByteArray(new File("target/classes/ognl/OgnlOps.class")); } catch (IOException e) { throw new ClassNotFoundException("Cannot define the class"); } return defineClass(OgnlOps.class.getName(), clazz, 0, clazz.length); } else { return OgnlOpsByReflectionTest.class.getClassLoader().loadClass(name); } } }; clazz = classLoader.loadClass(OgnlOps.class.getName()); }
From source file:io.servicecomb.swagger.generator.core.unittest.UnitTestSwaggerUtils.java
public static SwaggerGenerator testSwagger(String resPath, SwaggerGeneratorContext context, Class<?> cls, String... methods) {//from ww w . j a v a 2 s .co m SwaggerGeneratorForTest generator = new SwaggerGeneratorForTest(context, cls); generator.setClassLoader(new ClassLoader() { }); generator.replaceMethods(methods); Swagger swagger = generator.generate(); String expectSchema = loadExpect(resPath); Swagger expectSwagger = parse(expectSchema); String schema = pretty(swagger); swagger = parse(schema); if (swagger != null && !swagger.equals(expectSwagger)) { Assert.assertEquals(expectSchema, schema); } return generator; }
From source file:org.kalypso.commons.i18n.ResourceBundleUtils.java
/** * @param baseURL/* w ww . j a v a2s.c o m*/ * Base name for which to try to load the resource bundle.<br> * If <code>baseUrl</code> is something like <code>http://somehost/myfile.txt</code>, we try to load * properties like <code>http://somehost/myfile.properties</code>.<br> * Urls with query part or anchor are not supported. * @return <code>null</code>, if no such resource bundle is found. Any exceptions are reported to the {@link org.eclipse.core.runtime.ILog}-facilities. */ public static ResourceBundle loadResourceBundle(final URL baseURL) { try { // Unfinished: this does probably does not cover all cases... final URL _baseURL = extractBaseUrl(baseURL); final String path = baseURL.getPath(); final String baseName = FilenameUtils.getBaseName(path); // REMARK: the trick here is to use the special class loader, that just links back to the given url. // This allows us to use the full functionality of the ResourceBundle#getBundle implementation. final ClassLoader loader = new ClassLoader() { @Override protected URL findResource(final String name) { try { // The ResourceBundle replaces all '.' by '/' (assuming it is a classname) // but we know better. The name can never contain a real '/', because we // truncated it (see above). final String resourceName = name.replace('/', '.'); return new URL(_baseURL, resourceName); } catch (final MalformedURLException e) { e.printStackTrace(); return null; } } }; return ResourceBundle.getBundle(baseName, Locale.getDefault(), loader); } catch (final MissingResourceException e) { KalypsoCommonsDebug.DEBUG_I18N.printf(IStatus.INFO, "No resource bundle found for: %s%n", baseURL); //$NON-NLS-1$ return null; } catch (final MalformedURLException e) { KalypsoCommonsDebug.DEBUG_I18N.printf(IStatus.WARNING, "Could not load resource bundle found for: %s (%s)%n", baseURL, e.toString()); //$NON-NLS-1$ return null; } }
From source file:info.archinnov.achilles.internal.context.ConfigurationContextTest.java
@Test public void should_select_classloader_from_osgi() throws Exception { //Given//from w w w . j av a 2s .c o m ConfigurationContext context = new ConfigurationContext(); final ClassLoader osgiClassLoader = new ClassLoader() { @Override public Class<?> loadClass(String name) throws ClassNotFoundException { return super.loadClass(name); } }; context.setOSGIClassLoader(osgiClassLoader); //When final ClassLoader classLoader = context.selectClassLoader(CompleteBean.class); //Then assertThat(classLoader).isSameAs(osgiClassLoader); }
From source file:org.enerj.apache.commons.beanutils.BeanificationTestCase.java
/** Test of the methodology we'll use for some of the later tests */ public void testMemoryTestMethodology() throws Exception { // test methodology // many thanks to Juozas Baliuka for suggesting this method ClassLoader loader = new ClassLoader() { };/*from w ww .j a va 2 s.c om*/ WeakReference reference = new WeakReference(loader); Class myClass = loader.loadClass("org.enerj.apache.commons.beanutils.BetaBean"); assertNotNull("Weak reference released early", reference.get()); // dereference class loader and class: loader = null; myClass = null; int iterations = 0; int bytz = 2; while (true) { System.gc(); if (iterations++ > MAX_GC_ITERATIONS) { fail("Max iterations reached before resource released."); } if (reference.get() == null) { break; } else { // create garbage: byte[] b = new byte[bytz]; bytz = bytz * 2; } } }
From source file:com.varaneckas.hawkscope.cfg.ConfigurationFactory.java
/** * Loads {@link Configuration}/*from ww w.j av a2 s. com*/ * * @see #configuration */ private void loadConfiguration() { final Map<String, String> cfg = getDefaults(); try { final ResourceBundle data = UTF8ResourceBundle.getBundle(CONFIG_FILE_NAME, new ClassLoader() { @Override protected URL findResource(final String name) { try { final String file = loadConfigFilePath() + "/." + name; log.debug("Resolving config file: " + file); return new File(file).toURI().toURL(); } catch (final MalformedURLException e) { log.error("Failed loading file", e); return null; } } }); final Enumeration<String> keys = data.getKeys(); while (keys.hasMoreElements()) { final String key = keys.nextElement(); cfg.put(key, data.getString(key)); } } catch (final MissingResourceException e) { log.debug("Configuration not found, using defaults. (" + e.getMessage() + ")"); write(new Configuration(cfg)); } configuration = new Configuration(cfg); }
From source file:com.igormaznitsa.jcp.it.maven.ITPreprocessorMojo.java
@Test @SuppressWarnings("unchecked") public void testPreprocessorUsage() throws Exception { final File testDir = ResourceExtractor.simpleExtractResources(this.getClass(), "./dummy_maven_project"); final Verifier verifier = new Verifier(testDir.getAbsolutePath()); verifier.deleteArtifact("com.igormaznitsa", "DummyMavenProjectToTestJCP", "1.0-SNAPSHOT", "jar"); verifier.executeGoal("package"); assertFalse("Folder must be removed", new File("./dummy_maven_project/target").exists()); final File resultJar = ResourceExtractor.simpleExtractResources(this.getClass(), "./dummy_maven_project/DummyMavenProjectToTestJCP-1.0-SNAPSHOT.jar"); verifier.verifyErrorFreeLog();/* w w w. ja v a 2s .c om*/ verifier.verifyTextInLog("PREPROCESSED_TESTING_COMPLETED"); verifier.verifyTextInLog("Cleaning has been started"); verifier.verifyTextInLog("Removing preprocessed source folder"); verifier.verifyTextInLog("Removing preprocessed test source folder"); verifier.verifyTextInLog("Scanning for deletable directories"); verifier.verifyTextInLog("Deleting directory:"); verifier.verifyTextInLog("Cleaning has been completed"); verifier.verifyTextInLog(" mvn.project.property.some.datapass.base=***** "); verifier.verifyTextInLog(" mvn.project.property.some.private.key=***** "); final JarAnalyzer jarAnalyzer = new JarAnalyzer(resultJar); List<JarEntry> classEntries; try { classEntries = (List<JarEntry>) jarAnalyzer.getClassEntries(); for (final JarEntry ce : classEntries) { assertFalse(ce.getName().contains("excludedfolder")); } assertEquals("Must have only class", 1, classEntries.size()); final JarEntry classEntry = classEntries.get(0); assertNotNull(findClassEntry(jarAnalyzer, "com/igormaznitsa/dummyproject/testmain2.class")); DataInputStream inStream = null; final byte[] buffer = new byte[(int) classEntry.getSize()]; Class<?> instanceClass = null; try { inStream = new DataInputStream(jarAnalyzer.getEntryInputStream(classEntry)); inStream.readFully(buffer); instanceClass = new ClassLoader() { public Class<?> loadClass(final byte[] data) throws ClassNotFoundException { return defineClass(null, data, 0, data.length); } }.loadClass(buffer); } finally { IOUtils.closeQuietly(inStream); } if (instanceClass != null) { final Object instance = instanceClass.newInstance(); assertEquals("Must return the project name", "Dummy Maven Project To Test JCP", instanceClass.getMethod("test").invoke(instance)); } else { fail("Unexpected state"); } } finally { jarAnalyzer.closeQuietly(); } }
From source file:org.xwiki.store.legacy.internal.datanucleus.LoadStoreTest.java
@Test public void testXWikiDocumentClass() throws Exception { final XWikiDocument xdoc = new XWikiDocument(new DocumentReference("xwiki", "Test", "TestClass")); this.store.saveXWikiDoc(xdoc, null); Assert.assertFalse(this.store.getClassList(null).contains("xwiki:Test.TestClass")); final BaseClass xclass = xdoc.getXClass(); xclass.addField("string", new StringClass()); this.store.saveXWikiDoc(xdoc, null); Assert.assertTrue(this.store.getClassList(null).contains("xwiki:Test.TestClass")); xclass.addField("number", new NumberClass()); this.store.saveXWikiDoc(xdoc, null); Collection c;/*from w ww. ja va2 s. c o m*/ c = (Collection) this.store.getQueryManager() .createQuery("SELECT cls.bytes FROM " + "org.xwiki.store.objects.PersistableClass AS cls " + "WHERE cls.name = 'xwiki.Test.TestClass'", "jpql") .execute(); Assert.assertEquals(1, c.size()); final byte[] byteCode = (byte[]) c.toArray()[0]; Class cls = (new ClassLoader() { { this.defineClass("xwiki.Test.TestClass", byteCode, 0, byteCode.length); } }).loadClass("xwiki.Test.TestClass"); cls.getDeclaredField("string"); cls.getDeclaredField("number"); final BaseObject obj = xdoc.newXObject(new DocumentReference("xwiki", "Test", "TestClass"), this.xcontext); obj.set("string", "Hello World", this.xcontext); obj.set("number", 123, this.xcontext); this.store.saveXWikiDoc(xdoc, null); c = (Collection) this.store.getQueryManager().createQuery("SELECT obj FROM " + "xwiki.Test.TestClass AS obj " + "WHERE obj.id = 'xwiki:Test.TestClass.objects[0]'", "jpql") .execute(); Assert.assertEquals(1, c.size()); cls = c.toArray()[0].getClass(); cls.getDeclaredField("string"); cls.getDeclaredField("number"); }
From source file:org.marketcetera.util.log.I18NMessageProviderTest.java
@Test public void customClassLoader() throws Exception { // Verify that the resource is not available. I18NMessageProvider provider = new I18NMessageProvider(TEST_MEM_PROVIDER); Iterator<LoggingEvent> events = getAppender().getEvents().iterator(); assertEvent(/* w w w . j a va 2s . c o m*/ events.next(), Level.ERROR, TEST_CATEGORY, "Message file missing: provider '" + TEST_MEM_PROVIDER + "'; base name '" + TEST_MEM_PROVIDER + I18NMessageProvider.MESSAGE_FILE_EXTENSION + "'", TEST_LOCATION); assertEvent(events.next(), Level.ERROR, TEST_CATEGORY, "Abnormal exception: stack trace", TEST_LOCATION); assertFalse(events.hasNext()); getAppender().clear(); // Create a provider with a custom classloader. Properties messages = new Properties(); messages.put("hello.msg", "Hello"); messages.put("hello.title", "Hello {0}!"); ByteArrayOutputStream output = new ByteArrayOutputStream(); try { messages.store(output, StringUtils.EMPTY); } finally { output.close(); } final byte[] inputStream = output.toByteArray(); final String propertiesName = TEST_MEM_PROVIDER + I18NMessageProvider.MESSAGE_FILE_EXTENSION + ".properties"; provider = new I18NMessageProvider(TEST_MEM_PROVIDER, new ClassLoader() { @Override public InputStream getResourceAsStream(String name) { if (propertiesName.equals(name)) { return new ByteArrayInputStream(inputStream); } return super.getResourceAsStream(name); } }); assertNoEvents(); // Messages can now be translated. I18NLoggerProxy logger = new I18NLoggerProxy(provider); I18NMessage0P helloMsg = new I18NMessage0P(logger, "hello"); I18NMessage1P helloTitle = new I18NMessage1P(logger, "hello", "title"); Locale saved = Locale.getDefault(); try { Locale.setDefault(Locale.ROOT); assertEquals("Hello", provider.getText(helloMsg)); assertEquals("Hello World!", provider.getText(helloTitle, "World")); } finally { Locale.setDefault(saved); } }