List of usage examples for java.lang ClassLoader ClassLoader
protected ClassLoader(ClassLoader parent)
From source file:org.sourcepit.m2p2.osgi.embedder.maven.P2Test.java
@Override protected ClassLoader getClassLoader() { return new ClassLoader(super.getClassLoader()) { @Override/*from w w w. j a va 2s . c o m*/ public Enumeration<URL> getResources(String name) throws IOException { if ("META-INF/plexus/components.xml".equals(name)) { List<URL> res = new ArrayList<URL>(); Enumeration<URL> resources = super.getResources(name); int i = 0; while (resources.hasMoreElements()) { URL url = (URL) resources.nextElement(); if (i > 0) { res.add(url); } i++; } return Collections.enumeration(res); } return super.getResources(name); } }; }
From source file:org.alfresco.web.forms.xforms.Schema2XFormsProperties.java
public ResourceBundle getResourceBundle(final Form form, final Locale locale) { final LinkedList<ResourceBundle> bundles = new LinkedList<ResourceBundle>(); for (String location : this.locations) { ClassLoader loader = Thread.currentThread().getContextClassLoader(); location = location.replace("${form.name}", (NamespaceService.CONTENT_MODEL_PREFIX + ':' + form.getName())); if (location.startsWith("alfresco:")) { location = location.substring("alfresco:".length()); loader = new ClassLoader(loader) { public InputStream getResourceAsStream(String name) { LOGGER.debug("loading resource " + name); final ResultSet results = searchService.query(Repository.getStoreRef(), SearchService.LANGUAGE_LUCENE, "PATH:\"" + name + "\""); try { LOGGER.debug("search returned " + results.length() + " results"); if (results.length() == 1) { final NodeRef nr = results.getNodeRef(0); final ContentReader reader = contentService.getReader(nr, ContentModel.PROP_CONTENT); return reader.getContentInputStream(); } else { return super.getResourceAsStream(name); }//from www. j a v a 2s . com } finally { results.close(); } } }; } else if (location.startsWith("classpath:")) { location = location.substring("classpath:".length()); } LOGGER.debug("using loader " + loader + " for location " + location); try { final ResourceBundle rb = ResourceBundle.getBundle(location, locale, loader); LOGGER.debug("found bundle " + rb + " for location " + location); bundles.addFirst(rb); } catch (MissingResourceException mse) { LOGGER.debug("unable to located bundle at " + location + ": " + mse.getMessage()); } } ResourceBundle result = null; for (ResourceBundle rb : bundles) { result = (result == null ? rb : new ResourceBundleWrapper(rb, result)); } return result; }
From source file:org.elasticsearch.hadoop.script.GroovyScriptEngineService.java
public GroovyScriptEngineService(Settings settings) { super(settings); deprecationLogger.deprecated("[groovy] scripts are deprecated, use [painless] scripts instead"); // Creates the classloader here in order to isolate Groovy-land code final SecurityManager sm = System.getSecurityManager(); if (sm != null) { sm.checkPermission(new SpecialPermission()); }/* w w w .ja v a2 s. c om*/ this.loader = AccessController.doPrivileged((PrivilegedAction<ClassLoader>) () -> { // snapshot our context (which has permissions for classes), since the script has none AccessControlContext context = AccessController.getContext(); return new ClassLoader(getClass().getClassLoader()) { @Override protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException { if (sm != null) { try { context.checkPermission(new ClassPermission(name)); } catch (SecurityException e) { throw new ClassNotFoundException(name, e); } } return super.loadClass(name, resolve); } }; }); }
From source file:io.neba.spring.web.NebaRequestContextFilterTest.java
@Test public void testFilterToleratesAbsenceOfOptionalDependencyToBgHttpServletRequest() throws Exception { ClassLoader classLoaderWithoutBgServlets = new ClassLoader(getClass().getClassLoader()) { @Override/*from w w w.ja v a 2s . c om*/ public Class<?> loadClass(String name) throws ClassNotFoundException { if (BackgroundHttpServletRequest.class.getName().equals(name)) { // This optional dependency is not present on the class path in this test scenario. throw new ClassNotFoundException( "THIS IS AN EXPECTED TEST EXCEPTION. The dependency to bgservlets is optional."); } if (NebaRequestContextFilter.class.getName().equals(name)) { // Define the test subject's class class in this class loader, thus its dependencies - // such as the background servlet request - are also loaded via this class loader. try { byte[] classFileData = toByteArray( getResourceAsStream(name.replace('.', '/').concat(".class"))); return defineClass(name, classFileData, 0, classFileData.length); } catch (IOException e) { throw new ClassNotFoundException("Unable to load " + name + ".", e); } } return super.loadClass(name); } }; Class<?> filterClass = classLoaderWithoutBgServlets.loadClass(NebaRequestContextFilter.class.getName()); assertThat(valueOfField(filterClass, "IS_BGSERVLETS_PRESENT")).isFalse(); Object filter = filterClass.newInstance(); invoke(filter, "doFilter", request, response, chain); }
From source file:Main.java
/** * Writes a DOM document to a stream. The precise output format is not * guaranteed but this method will attempt to indent it sensibly. * * <p class="nonnormative"><b>Important</b>: There might be some problems * with <code><![CDATA[ ]]></code> sections in the DOM tree you pass * into this method. Specifically, some CDATA sections my not be written as * CDATA section or may be merged with other CDATA section at the same * level. Also if plain text nodes are mixed with CDATA sections at the same * level all text is likely to end up in one big CDATA section. * <br>//from w w w . j av a 2s .co m * For nodes that only have one CDATA section this method should work fine. * </p> * * @param doc DOM document to be written * @param out data sink * @param enc XML-defined encoding name (for example, "UTF-8") * @throws IOException if JAXP fails or the stream cannot be written to */ public static void write(Document doc, OutputStream out, String enc) throws IOException { if (enc == null) { throw new NullPointerException( "You must set an encoding; use \"UTF-8\" unless you have a good reason not to!"); // NOI18N } Document doc2 = normalize(doc); ClassLoader orig = Thread.currentThread().getContextClassLoader(); Thread.currentThread() .setContextClassLoader(AccessController.doPrivileged(new PrivilegedAction<ClassLoader>() { // #195921 @Override public ClassLoader run() { return new ClassLoader(ClassLoader.getSystemClassLoader().getParent()) { @Override public InputStream getResourceAsStream(String name) { if (name.startsWith("META-INF/services/")) { return new ByteArrayInputStream(new byte[0]); // JAXP #6723276 } return super.getResourceAsStream(name); } }; } })); try { TransformerFactory tf = TransformerFactory.newInstance(); Transformer t = tf.newTransformer(new StreamSource(new StringReader(IDENTITY_XSLT_WITH_INDENT))); DocumentType dt = doc2.getDoctype(); if (dt != null) { String pub = dt.getPublicId(); if (pub != null) { t.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, pub); } String sys = dt.getSystemId(); if (sys != null) { t.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, sys); } } t.setOutputProperty(OutputKeys.ENCODING, enc); try { t.setOutputProperty(ORACLE_IS_STANDALONE, "yes"); } catch (IllegalArgumentException x) { // fine, introduced in JDK 7u4 } // See #123816 Set<String> cdataQNames = new HashSet<String>(); collectCDATASections(doc2, cdataQNames); if (cdataQNames.size() > 0) { StringBuilder cdataSections = new StringBuilder(); for (String s : cdataQNames) { cdataSections.append(s).append(' '); //NOI18N } t.setOutputProperty(OutputKeys.CDATA_SECTION_ELEMENTS, cdataSections.toString()); } Source source = new DOMSource(doc2); Result result = new StreamResult(out); t.transform(source, result); } catch (javax.xml.transform.TransformerException | RuntimeException e) { // catch anything that happens throw new IOException(e); } finally { Thread.currentThread().setContextClassLoader(orig); } }
From source file:io.neba.core.spring.web.filter.NebaRequestContextFilterTest.java
@Test public void testFilterToleratesAbsenceOfOptionalDependencyToBgHttpServletRequest() throws Exception { ClassLoader classLoaderWithoutBgServlets = new ClassLoader(getClass().getClassLoader()) { @Override//from w ww .ja v a 2 s .com public Class<?> loadClass(String name) throws ClassNotFoundException { if (BackgroundHttpServletRequest.class.getName().equals(name)) { // This optional dependency is not present on the class path in this test scenario. throw new ClassNotFoundException( "THIS IS AN EXPECTED TEST EXCEPTION. The dependency to bgservlets is optional."); } if (NebaRequestContextFilter.class.getName().equals(name)) { // Define the test subject's class class in this class loader, thus its dependencies - // such as the background servlet request - are also loaded via this class loader. try { byte[] classFileData = toByteArray( getResourceAsStream(name.replace('.', '/').concat(".class"))); return defineClass(name, classFileData, 0, classFileData.length); } catch (IOException e) { throw new ClassNotFoundException("Unable to load " + name + ".", e); } } return super.loadClass(name); } }; Class<?> filterClass = classLoaderWithoutBgServlets.loadClass(NebaRequestContextFilter.class.getName()); assertThat(field("IS_BGSERVLETS_PRESENT").ofType(boolean.class).in(filterClass).get()).isFalse(); Object filter = filterClass.newInstance(); method("doFilter").withParameterTypes(ServletRequest.class, ServletResponse.class, FilterChain.class) .in(filter).invoke(request, response, chain); }
From source file:io.neba.core.logviewer.LogfileViewerConsolePluginTest.java
@Test @SuppressWarnings("unchecked") public void testLogViewerToleratesMissingDecoratedObjectFactoryFactory() throws Exception { ClassLoader classLoaderWithoutDecoratedObjectFactory = new ClassLoader(getClass().getClassLoader()) { @Override// ww w .j a v a 2s .c o m public Class<?> loadClass(String name) throws ClassNotFoundException { if (DecoratedObjectFactory.class.getName().equals(name)) { // This optional dependency is not present on the class path in this test scenario. throw new ClassNotFoundException("THIS IS AN EXPECTED TEST EXCEPTION. The presence of " + DecoratedObjectFactory.class.getName() + " is optional."); } if (LogfileViewerConsolePlugin.class.getName().equals(name)) { // Define the test subject's class class in this class loader, thus its dependencies - // such as the DecoratedObjectFactory - are also loaded via this class loader. try { byte[] classFileData = toByteArray( getResourceAsStream(name.replace('.', '/').concat(".class"))); return defineClass(name, classFileData, 0, classFileData.length); } catch (IOException e) { throw new ClassNotFoundException("Unable to load " + name + ".", e); } } return super.loadClass(name); } }; Class<? extends Servlet> type = (Class<? extends Servlet>) classLoaderWithoutDecoratedObjectFactory .loadClass(LogfileViewerConsolePlugin.class.getName()); Servlet logViewerInstance = type.newInstance(); ServletConfig config = mock(ServletConfig.class); ServletContext context = mock(ServletContext.class); doReturn(context).when(config).getServletContext(); injectTailServlet(logViewerInstance); invokeInit(logViewerInstance, config); invokeDestroy(logViewerInstance); verify(context, never()).setAttribute(any(), any()); verify(context, never()).removeAttribute(any()); }
From source file:org.apache.flink.client.CliFrontendPackageProgramTest.java
/** * Ensure that we will never have the following error. * //from ww w . j a v a 2 s. co m * The test works as follows: * - Use the CliFrontend to invoke a jar file that loads a class which is only available * in the jarfile itself (via a custom classloader) * - Change the Usercode classloader of the PackagedProgram to a special classloader for this test * - the classloader will accept the special class (and return a String.class) * * org.apache.flink.client.program.ProgramInvocationException: The main method caused an error. at org.apache.flink.client.program.PackagedProgram.callMainMethod(PackagedProgram.java:398) at org.apache.flink.client.program.PackagedProgram.invokeInteractiveModeForExecution(PackagedProgram.java:301) at org.apache.flink.client.program.Client.getOptimizedPlan(Client.java:140) at org.apache.flink.client.program.Client.getOptimizedPlanAsJson(Client.java:125) at org.apache.flink.client.CliFrontend.info(CliFrontend.java:439) at org.apache.flink.client.CliFrontend.parseParameters(CliFrontend.java:931) at org.apache.flink.client.CliFrontend.main(CliFrontend.java:951) Caused by: java.io.IOException: java.lang.RuntimeException: java.lang.ClassNotFoundException: org.apache.hadoop.hive.ql.io.RCFileInputFormat at org.apache.hcatalog.mapreduce.HCatInputFormat.setInput(HCatInputFormat.java:102) at org.apache.hcatalog.mapreduce.HCatInputFormat.setInput(HCatInputFormat.java:54) at tlabs.CDR_In_Report.createHCatInputFormat(CDR_In_Report.java:322) at tlabs.CDR_Out_Report.main(CDR_Out_Report.java:380) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:622) at org.apache.flink.client.program.PackagedProgram.callMainMethod(PackagedProgram.java:383) */ @Test public void testPlanWithExternalClass() throws CompilerException, ProgramInvocationException { final boolean[] callme = { false }; // create a final object reference, to be able to change its val later try { String[] parameters = { getTestJarPath(), "-c", TEST_JAR_CLASSLOADERTEST_CLASS, "some", "program" }; CommandLine line = new PosixParser().parse(CliFrontend.getProgramSpecificOptions(new Options()), parameters, false); CliFrontend frontend = new CliFrontend(); Object result = frontend.buildProgram(line); assertTrue(result instanceof PackagedProgram); PackagedProgram prog = spy((PackagedProgram) result); ClassLoader testClassLoader = new ClassLoader(prog.getUserCodeClassLoader()) { @Override public Class<?> loadClass(String name) throws ClassNotFoundException { if ("org.apache.hadoop.hive.ql.io.RCFileInputFormat".equals(name)) { callme[0] = true; return String.class; // Intentionally return the wrong class. } else { return super.loadClass(name); } } }; when(prog.getUserCodeClassLoader()).thenReturn(testClassLoader); Assert.assertArrayEquals(new String[] { "some", "program" }, prog.getArguments()); Assert.assertEquals(TEST_JAR_CLASSLOADERTEST_CLASS, prog.getMainClassName()); Configuration c = new Configuration(); c.setString(ConfigConstants.JOB_MANAGER_IPC_ADDRESS_KEY, "devil"); Client cli = new Client(c, getClass().getClassLoader()); cli.getOptimizedPlanAsJson(prog, 666); } catch (ProgramInvocationException pie) { assertTrue("Classloader was not called", callme[0]); // class not found exception is expected as some point if (!(pie.getCause() instanceof ClassNotFoundException)) { System.err.println(pie.getMessage()); pie.printStackTrace(); fail("Program caused an exception: " + pie.getMessage()); } } catch (Exception e) { assertTrue("Classloader was not called", callme[0]); System.err.println(e.getMessage()); e.printStackTrace(); fail("Program caused an exception: " + e.getMessage()); } }
From source file:eu.stratosphere.client.CliFrontendPackageProgramTest.java
/** * Ensure that we will never have the following error. * // w w w . j av a2 s . c o m * The test works as follows: * - Use the CliFrontend to invoke a jar file that loads a class which is only available * in the jarfile itself (via a custom classloader) * - Change the Usercode classloader of the PackagedProgram to a special classloader for this test * - the classloader will accept the special class (and return a String.class) * * eu.stratosphere.client.program.ProgramInvocationException: The main method caused an error. at eu.stratosphere.client.program.PackagedProgram.callMainMethod(PackagedProgram.java:398) at eu.stratosphere.client.program.PackagedProgram.invokeInteractiveModeForExecution(PackagedProgram.java:301) at eu.stratosphere.client.program.Client.getOptimizedPlan(Client.java:140) at eu.stratosphere.client.program.Client.getOptimizedPlanAsJson(Client.java:125) at eu.stratosphere.client.CliFrontend.info(CliFrontend.java:439) at eu.stratosphere.client.CliFrontend.parseParameters(CliFrontend.java:931) at eu.stratosphere.client.CliFrontend.main(CliFrontend.java:951) Caused by: java.io.IOException: java.lang.RuntimeException: java.lang.ClassNotFoundException: org.apache.hadoop.hive.ql.io.RCFileInputFormat at org.apache.hcatalog.mapreduce.HCatInputFormat.setInput(HCatInputFormat.java:102) at org.apache.hcatalog.mapreduce.HCatInputFormat.setInput(HCatInputFormat.java:54) at tlabs.CDR_In_Report.createHCatInputFormat(CDR_In_Report.java:322) at tlabs.CDR_Out_Report.main(CDR_Out_Report.java:380) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:622) at eu.stratosphere.client.program.PackagedProgram.callMainMethod(PackagedProgram.java:383) */ @Test public void testPlanWithExternalClass() throws CompilerException, ProgramInvocationException { final Boolean callme[] = { false }; // create a final object reference, to be able to change its val later try { String[] parameters = { getTestJarPath(), "-c", TEST_JAR_CLASSLOADERTEST_CLASS, "some", "program" }; CommandLine line = new PosixParser().parse(CliFrontend.getProgramSpecificOptions(new Options()), parameters, false); CliFrontend frontend = new CliFrontend(); Object result = frontend.buildProgram(line); assertTrue(result instanceof PackagedProgram); PackagedProgram prog = spy((PackagedProgram) result); ClassLoader testClassLoader = new ClassLoader(prog.getUserCodeClassLoader()) { @Override public Class<?> loadClass(String name) throws ClassNotFoundException { assertTrue(name.equals("org.apache.hadoop.hive.ql.io.RCFileInputFormat")); callme[0] = true; return String.class; // Intentionally return the wrong class. } }; when(prog.getUserCodeClassLoader()).thenReturn(testClassLoader); Assert.assertArrayEquals(new String[] { "some", "program" }, prog.getArguments()); Assert.assertEquals(TEST_JAR_CLASSLOADERTEST_CLASS, prog.getMainClassName()); Configuration c = new Configuration(); c.setString(ConfigConstants.JOB_MANAGER_IPC_ADDRESS_KEY, "devil"); Client cli = new Client(c); cli.getOptimizedPlanAsJson(prog, 666); } catch (ProgramInvocationException pie) { assertTrue("Classloader was not called", callme[0]); // class not found exception is expected as some point if (!(pie.getCause() instanceof ClassNotFoundException)) { System.err.println(pie.getMessage()); pie.printStackTrace(); fail("Program caused an exception: " + pie.getMessage()); } } catch (Exception e) { assertTrue("Classloader was not called", callme[0]); System.err.println(e.getMessage()); e.printStackTrace(); fail("Program caused an exception: " + e.getMessage()); } }
From source file:org.wisdom.framework.jpa.PersistenceUnitComponent.java
/** * In this method we just create a simple temporary class loader. This class * loader uses the bundle's class loader as parent but defines the classes * in this class loader. This has the implicit assumption that the temp * class loader is used BEFORE any bundle's classes are loaded since a class * loader does parent delegation first. Sigh, guess it works most of the * time. There is however, no good alternative though in OSGi we could * actually refresh the bundle./*ww w . j a v a2 s . co m*/ * * @see javax.persistence.spi.PersistenceUnitInfo#getNewTempClassLoader() */ @Override public ClassLoader getNewTempClassLoader() { return new ClassLoader(getClassLoader()) { //NOSONAR /** * Searches for the .class file and define it using the current class loader. * @param className the class name * @return the class object * @throws ClassNotFoundException if the class cannot be found */ @Override protected Class findClass(String className) throws ClassNotFoundException { // Use path of class, then get the resource String path = className.replace('.', '/').concat(".class"); URL resource = getParent().getResource(path); if (resource == null) { throw new ClassNotFoundException(className + " as resource " + path + " in " + getParent()); } try { ByteArrayOutputStream bout = new ByteArrayOutputStream(); IOUtils.copy(resource.openStream(), bout); byte[] buffer = bout.toByteArray(); return defineClass(className, buffer, 0, buffer.length); } catch (Exception e) { throw new ClassNotFoundException(className + " as resource" + path + " in " + getParent(), e); } } /** * Finds a resource in the bundle. * @param resource the resource * @return the url of the resource from the bundle, {@code null} if not found. */ @Override protected URL findResource(String resource) { return getParent().getResource(resource); } /** * Finds resources in the bundle. * @param resource the resource * @return the url of the resources from the bundle, empty if not found. */ @Override protected Enumeration<URL> findResources(String resource) throws IOException { return getParent().getResources(resource); } }; }