java.net.URLClassLoader源码实例Demo

类java.net.URLClassLoader源码实例Demo

下面列出了java.net.URLClassLoader 类实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: triplea   文件: AvailableGames.java
private static Map<String, URI> getGamesFromZip(final File map) {
  final Map<String, URI> availableGames = new HashMap<>();

  try (InputStream fis = new FileInputStream(map);
      ZipInputStream zis = new ZipInputStream(fis);
      URLClassLoader loader = new URLClassLoader(new URL[] {map.toURI().toURL()})) {
    ZipEntry entry = zis.getNextEntry();
    while (entry != null) {
      if (entry.getName().contains("games/") && entry.getName().toLowerCase().endsWith(".xml")) {
        final URL url = loader.getResource(entry.getName());
        if (url != null) {
          availableGames.putAll(
              getAvailableGames(URI.create(url.toString().replace(" ", "%20"))));
        }
      }
      // we have to close the loader to allow files to be deleted on windows
      zis.closeEntry();
      entry = zis.getNextEntry();
    }
  } catch (final IOException e) {
    log.log(Level.SEVERE, "Error reading zip file in: " + map.getAbsolutePath(), e);
  }
  return availableGames;
}
 
源代码2 项目: jdk8u-dev-jdk   文件: JdiLoadedByCustomLoader.java
public static void main(String args[]) throws Exception {
    // create files from given arguments and tools.jar
    File f1 = new File(args[0]);
    String home = System.getProperty("java.home");
    String tools = ".." + File.separatorChar + "lib" +
        File.separatorChar + "tools.jar";
    File f2 = (new File(home, tools)).getCanonicalFile();

    // create class loader
    URL[] urls = { f1.toURL(), f2.toURL() };
    URLClassLoader cl = new URLClassLoader(urls);

    // load ListConnectors using the class loader
    // and then invoke the list method.
    Class c = Class.forName("ListConnectors", true, cl);
    Method m = c.getDeclaredMethod("list");
    Object o = c.newInstance();
    m.invoke(o);
}
 
源代码3 项目: jdk8u-jdk   文件: Main.java
private ContentSigner loadSigningMechanism(String signerClassName,
    String signerClassPath) throws Exception {

    // construct class loader
    String cpString = null;   // make sure env.class.path defaults to dot

    // do prepends to get correct ordering
    cpString = PathList.appendPath(System.getProperty("env.class.path"), cpString);
    cpString = PathList.appendPath(System.getProperty("java.class.path"), cpString);
    cpString = PathList.appendPath(signerClassPath, cpString);
    URL[] urls = PathList.pathToURLs(cpString);
    ClassLoader appClassLoader = new URLClassLoader(urls);

    // attempt to find signer
    Class<?> signerClass = appClassLoader.loadClass(signerClassName);

    // Check that it implements ContentSigner
    Object signer = signerClass.newInstance();
    if (!(signer instanceof ContentSigner)) {
        MessageFormat form = new MessageFormat(
            rb.getString("signerClass.is.not.a.signing.mechanism"));
        Object[] source = {signerClass.getName()};
        throw new IllegalArgumentException(form.format(source));
    }
    return (ContentSigner)signer;
}
 
源代码4 项目: hottub   文件: SchemaGenerator.java
private static String setClasspath(String givenClasspath) {
    StringBuilder cp = new StringBuilder();
    appendPath(cp, givenClasspath);
    ClassLoader cl = Thread.currentThread().getContextClassLoader();
    while (cl != null) {
        if (cl instanceof URLClassLoader) {
            for (URL url : ((URLClassLoader) cl).getURLs()) {
                appendPath(cp, url.getPath());
            }
        }
        cl = cl.getParent();
    }

    appendPath(cp, findJaxbApiJar());
    return cp.toString();
}
 
源代码5 项目: jdk8u-dev-jdk   文件: ClassLoaderTest.java
public static void main(String[] args) throws Exception {

        File file = new File(BASE);
        URL[] urls = new URL[1];
        urls[0] = file.toURI().toURL();
        URLClassLoader ucl = new URLClassLoader(urls);
        Class<?> c = ucl.loadClass("MyTransform");
        Constructor<?> cons = c.getConstructor(new Class[] {});
        Object o = cons.newInstance();
        // Apache code swallows the ClassNotFoundExc, so we need to
        // check if the Transform has already been registered by registering
        // it again and catching an AlgorithmAlreadyRegisteredExc
        try {
            Transform.register(MyTransform.URI, "MyTransform");
            throw new Exception("ClassLoaderTest failed");
        } catch (AlgorithmAlreadyRegisteredException e) {
            // test passed
        }
    }
 
源代码6 项目: gridgo   文件: AbstractTest.java
public void init() throws Exception {
    System.out.println("init...");
    // Provide the URL corresponding to the folder that contains the class
    // `javassist.MyClass`
    this.cl = new URLClassLoader(new URL[] { new File("target/classes").toURI().toURL(),
            new File("target/test-classes").toURI().toURL() }) {

        protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
            try {
                // Try to find the class for this CL
                return findClass(name);
            } catch (ClassNotFoundException e) {
                // Could not find the class so load it from the parent
                return super.loadClass(name, resolve);
            }
        }
    };
    // Get the current context CL and store it into old
    this.old = Thread.currentThread().getContextClassLoader();
    // Set the custom CL as new context CL
    Thread.currentThread().setContextClassLoader(cl);
}
 
源代码7 项目: cxf   文件: JAXRSContainerTest.java
@Test
public void testOnewayMethod() throws Exception {
    JAXRSContainer container = new JAXRSContainer(null);

    final String onewayMethod = "deleteRepository";
    ToolContext context = new ToolContext();
    context.put(WadlToolConstants.CFG_OUTPUTDIR, output.getCanonicalPath());
    context.put(WadlToolConstants.CFG_WADLURL, getLocation("/wadl/test.xml"));
    context.put(WadlToolConstants.CFG_COMPILE, "true");
    context.put(WadlToolConstants.CFG_ONEWAY, onewayMethod);
    container.setContext(context);
    container.execute();

    assertNotNull(output.list());

    ClassCollector cc = context.get(ClassCollector.class);
    assertEquals(1, cc.getServiceClassNames().size());
    try (URLClassLoader loader = new URLClassLoader(new URL[]{output.toURI().toURL()})) {
        final Class<?> generatedClass = loader.loadClass(cc.getServiceClassNames().values().iterator().next());
        Method m = generatedClass.getMethod(onewayMethod, String.class);
        assertNotNull(m.getAnnotation(Oneway.class));
    }
}
 
源代码8 项目: AVM   文件: ReflectionBenchmarkUniqueAccessTest.java
private long uniqueInstanceMethodHandleInstanceFieldReadAccessInvokeExactOnly(int spins) throws Throwable {
    ReflectionTarget[] targets = new ReflectionTarget[spins];
    MethodHandle[] fields = new MethodHandle[spins];

    for (int i = 0; i < spins; i++) {
        ClassLoader loader = new URLClassLoader(new URL[]{ classpathDirectory.toURI().toURL() });
        Class<?> clazz = loader.loadClass(targetClassName);
        targets[i] = (ReflectionTarget) MethodHandles.lookup().findConstructor(clazz, MethodType.methodType(void.class)).invoke();
        fields[i] = MethodHandles.lookup().findGetter(clazz, instanceField, Object.class);
    }

    long start = System.nanoTime();
    for (int i = 0; i < spins; i++) {
        Object o = fields[i].invokeExact(targets[i]);
    }
    long end = System.nanoTime();
    return end - start;
}
 
源代码9 项目: j2cl   文件: PackageInfoCache.java
public static void init(List<String> classPathEntries, Problems problems) {
  checkState(
      packageInfoCacheStorage.get() == null,
      "PackageInfoCache should only be initialized once per thread.");

  // Constructs a URLClassLoader to do the dirty work of finding package-info.class files in the
  // classpath of the compile.
  List<URL> classPathUrls = new ArrayList<>();
  for (String classPathEntry : classPathEntries) {
    try {
      classPathUrls.add(new URL("file:" + classPathEntry));
    } catch (MalformedURLException e) {
      problems.fatal(FatalError.CANNOT_OPEN_FILE, e.toString());
    }
  }
  URLClassLoader resourcesClassLoader =
      new URLClassLoader(
          Iterables.toArray(classPathUrls, URL.class), PackageInfoCache.class.getClassLoader());

  packageInfoCacheStorage.set(new PackageInfoCache(resourcesClassLoader, problems));
}
 
源代码10 项目: incubator-tez   文件: TestTezClientUtils.java
/**
 * 
 * @throws Exception
 */
@Test (timeout=5000)
public void validateSetTezJarLocalResourcesDefinedExistingDirectoryIgnored() throws Exception {
  URL[] cp = ((URLClassLoader)ClassLoader.getSystemClassLoader()).getURLs();
  StringBuffer buffer = new StringBuffer();
  for (URL url : cp) {
    buffer.append(url.toExternalForm());
    buffer.append(",");
  }
  TezConfiguration conf = new TezConfiguration();
  conf.set(TezConfiguration.TEZ_LIB_URIS, buffer.toString());
  conf.setBoolean(TezConfiguration.TEZ_IGNORE_LIB_URIS, true);
  Credentials credentials = new Credentials();
  Map<String, LocalResource> localizedMap = TezClientUtils.setupTezJarsLocalResources(conf, credentials);
  assertTrue(localizedMap.isEmpty());
}
 
源代码11 项目: TencentKona-8   文件: AllocationStackTrace.java
/**
 * Imitates class loading. Each invocation of this method causes a new class
 * loader object is created and a new class is loaded by this class loader.
 * Method throws OOM when run out of memory.
 */
static protected void loadNewClass() {
    try {
        String jarUrl = "file:" + (counter++) + ".jar";
        URL[] urls = new URL[]{new URL(jarUrl)};
        URLClassLoader cl = new URLClassLoader(urls);
        Proxy.newProxyInstance(
                cl,
                new Class[]{Foo.class},
                new FooInvocationHandler(new FooBar()));
    } catch (java.net.MalformedURLException badThing) {
        // should never occur
        System.err.println("Unexpected error: " + badThing);
        throw new RuntimeException(badThing);
    }
}
 
源代码12 项目: kogito-runtimes   文件: ChangeSetTest.java
@Test
public void testCustomClassLoader() throws Exception {
    // JBRULES-3630
    String absolutePath = new File("file").getAbsolutePath();

    URL url = ChangeSetTest.class.getResource(ChangeSetTest.class.getSimpleName() + ".class");
    AtomicReference<File> jar = new AtomicReference<>();
    assertTimeoutPreemptively(Duration.ofSeconds(10), () -> {
        File file = new File( url.toURI() );
        while ( true ) {
            file = file.getParentFile();
            File j = new File( file, "/src/test/resources/org/drools/compiler/compiler/xml/changeset/changeset.jar" );
            if ( j.exists() ) {
                jar.set(j);
                break;
            }
        }
    }, "JAR not found in time.");

    ClassLoader classLoader = URLClassLoader.newInstance(new URL[]{jar.get().toURI().toURL()}, getClass().getClassLoader());
    Resource changeSet = ResourceFactory.newClassPathResource("changeset1.xml", classLoader);
    KnowledgeBuilderConfiguration conf = KnowledgeBuilderFactory.newKnowledgeBuilderConfiguration(null, classLoader);
    KnowledgeBuilder builder = KnowledgeBuilderFactory.newKnowledgeBuilder(conf);
    builder.add(changeSet, ResourceType.CHANGE_SET);
}
 
源代码13 项目: openjdk-jdk8u   文件: B7050028.java
public static void main(String[] args) throws Exception {
    URLConnection conn = B7050028.class.getResource("B7050028.class").openConnection();
    int len = conn.getContentLength();
    byte[] data = new byte[len];
    InputStream is = conn.getInputStream();
    is.read(data);
    is.close();
    conn.setDefaultUseCaches(false);
    File jar = File.createTempFile("B7050028", ".jar");
    jar.deleteOnExit();
    OutputStream os = new FileOutputStream(jar);
    ZipOutputStream zos = new ZipOutputStream(os);
    ZipEntry ze = new ZipEntry("B7050028.class");
    ze.setMethod(ZipEntry.STORED);
    ze.setSize(len);
    CRC32 crc = new CRC32();
    crc.update(data);
    ze.setCrc(crc.getValue());
    zos.putNextEntry(ze);
    zos.write(data, 0, len);
    zos.closeEntry();
    zos.finish();
    zos.close();
    os.close();
    System.out.println(new URLClassLoader(new URL[] {new URL("jar:" + jar.toURI() + "!/")}, ClassLoader.getSystemClassLoader().getParent()).loadClass(B7050028.class.getName()));
}
 
源代码14 项目: IoTgo_Android_App   文件: Loader.java
/**
 * Generate the classpath (as a string) of all classloaders
 * above the given classloader.
 * 
 * This is primarily used for jasper.
 * @return the system class path
 */
public static String getClassPath(ClassLoader loader) throws Exception
{
    StringBuilder classpath=new StringBuilder();
    while (loader != null && (loader instanceof URLClassLoader))
    {
        URL[] urls = ((URLClassLoader)loader).getURLs();
        if (urls != null)
        {     
            for (int i=0;i<urls.length;i++)
            {
                Resource resource = Resource.newResource(urls[i]);
                File file=resource.getFile();
                if (file!=null && file.exists())
                {
                    if (classpath.length()>0)
                        classpath.append(File.pathSeparatorChar);
                    classpath.append(file.getAbsolutePath());
                }
            }
        }
        loader = loader.getParent();
    }
    return classpath.toString();
}
 
private void setupSwagger() {
  BeanConfig beanConfig = new BeanConfig();
  beanConfig.setTitle("Pinot Starter API");
  beanConfig.setDescription("APIs for accessing Pinot Starter information");
  beanConfig.setContact("https://github.com/apache/incubator-pinot");
  beanConfig.setVersion("1.0");
  beanConfig.setSchemes(new String[]{"http"});
  beanConfig.setBasePath(_baseUri.getPath());
  beanConfig.setResourcePackage(RESOURCE_PACKAGE);
  beanConfig.setScan(true);

  HttpHandler httpHandler =
      new CLStaticHttpHandler(PinotServiceManagerAdminApiApplication.class.getClassLoader(), "/api/");
  // map both /api and /help to swagger docs. /api because it looks nice. /help for backward compatibility
  _httpServer.getServerConfiguration().addHttpHandler(httpHandler, "/api/", "/help/");

  URL swaggerDistLocation = PinotServiceManagerAdminApiApplication.class.getClassLoader()
      .getResource("META-INF/resources/webjars/swagger-ui/2.2.2/");
  CLStaticHttpHandler swaggerDist = new CLStaticHttpHandler(new URLClassLoader(new URL[]{swaggerDistLocation}));
  _httpServer.getServerConfiguration().addHttpHandler(swaggerDist, "/swaggerui-dist/");
}
 
源代码16 项目: SearchServices   文件: SOLRAPIClientTest.java
public ClassLoader getResourceClassLoader()
{

    File f = new File("woof", "alfrescoResources");
    if (f.canRead() && f.isDirectory())
    {

        URL[] urls = new URL[1];

        try
        {
            URL url = f.toURI().normalize().toURL();
            urls[0] = url;
        }
        catch (MalformedURLException e)
        {
            throw new AlfrescoRuntimeException("Failed to add resources to classpath ", e);
        }

        return URLClassLoader.newInstance(urls, this.getClass().getClassLoader());
    }
    else
    {
        return this.getClass().getClassLoader();
    }
}
 
源代码17 项目: GriefDefender   文件: BootstrapUtil.java
public static void addUrlToClassLoader(String name, File input) {
    try {
        final ClassLoader classLoader = GDBootstrap.class.getClassLoader();
        if (classLoader instanceof URLClassLoader) {
            try {
                METHOD_ADD_URL.invoke(classLoader, new URL("jar:file:" + input.getPath() + "!/"));
            } catch (Throwable t) {
                t.printStackTrace();
            }
        } else {
            throw new RuntimeException("Unknown classloader: " + classLoader.getClass());
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}
 
源代码18 项目: jdk8u-jdk   文件: LeakTest.java
private static WeakReference<ClassLoader>
        testShadow(Class<?> originalTestClass) throws Exception {
    URLClassLoader originalLoader =
            (URLClassLoader) originalTestClass.getClassLoader();
    URL[] urls = originalLoader.getURLs();
    URLClassLoader shadowLoader =
            new ShadowClassLoader(urls, originalLoader.getParent());
    System.out.println("Shadow loader is " + shadowLoader);
    String className = originalTestClass.getName();
    Class<?> testClass = Class.forName(className, false, shadowLoader);
    if (testClass.getClassLoader() != shadowLoader) {
        throw new IllegalArgumentException("Loader didn't work: " +
                testClass.getClassLoader() + " != " + shadowLoader);
    }
    Method main = testClass.getMethod("main", String[].class);
    main.invoke(null, (Object) new String[0]);
    return new WeakReference<ClassLoader>(shadowLoader);
}
 
源代码19 项目: tomee   文件: TomEEJarScanner.java
@Override
public void scan(final JarScanType scanType, final ServletContext context, final JarScannerCallback callback) {
    super.scan(scanType, context, callback);
    if (!embeddedSurefireScanning(scanType, context, callback) && isScanClassPath() && !URLClassLoader.class.isInstance(getSystemClassLoader())
            && !Boolean.getBoolean("tomee.classpath.scanning.disabled")) {
        // TODO: check on tomcat upgrade if it is fixed
        final String cp = System.getProperty("java.class.path");
        final Collection<URL> urls = new HashSet<>();
        for (final String jar : cp.split(File.pathSeparator)) {
            if(!jar.isEmpty()){
                try {
                    urls.add(new File(jar).toURI().toURL());
                } catch (MalformedURLException e) {
                    // no-op
                }
            }
        }
        doScan(scanType, callback, new LinkedList<>(urls));
    }
}
 
源代码20 项目: AVM   文件: ReflectionBenchmarkUniqueAccessTest.java
private long uniqueInstanceMethodHandleInstanceFieldWriteAccessInvokeExactOnly(int spins) throws Throwable {
    ReflectionTarget[] targets = new ReflectionTarget[spins];
    MethodHandle[] fields = new MethodHandle[spins];

    for (int i = 0; i < spins; i++) {
        ClassLoader loader = new URLClassLoader(new URL[]{ classpathDirectory.toURI().toURL() });
        Class<?> clazz = loader.loadClass(targetClassName);
        targets[i] = (ReflectionTarget) MethodHandles.lookup().findConstructor(clazz, MethodType.methodType(void.class)).invoke();
        fields[i] = MethodHandles.lookup().findSetter(clazz, instanceField, Object.class);
    }

    Object object = new Object();

    long start = System.nanoTime();
    for (int i = 0; i < spins; i++) {
        fields[i].invokeExact(targets[i], object);
    }
    long end = System.nanoTime();
    return end - start;
}
 
源代码21 项目: netbeans   文件: StandaloneTest.java
@Override
protected void setUp() throws Exception {
    URL api = CommandLine.class.getProtectionDomain().getCodeSource().getLocation();
    URL options = Options.class.getProtectionDomain().getCodeSource().getLocation();
    
    loader = new URLClassLoader(
        new URL[] { api, options },
        CommandLine.class.getClassLoader().getParent()
    );
    Thread.currentThread().setContextClassLoader(loader);
    
    classCommandLine = loader.loadClass(CommandLine.class.getName());
    classOptions = loader.loadClass(Options.class.getName());
    methodProcess = classCommandLine.getMethod("process", String[].class);
    methodUsage = classCommandLine.getMethod("usage", PrintWriter.class);
}
 
源代码22 项目: osp   文件: LaunchClassChooser.java
LaunchableClassMap(String[] names) {
  jarOrDirectoryNames = names;
  // create a URL for each jar or directory
  Collection<URL> urls = new ArrayList<URL>();
  // changed by D Brown 2007-11-06 for Linux
  // changed by F Esquembre and D Brown 2010-03-02 to allow arbitrary base path
  String basePath = LaunchClassChooser.baseDirectoryPath;
  if (basePath==null) basePath = OSPRuntime.getLaunchJarDirectory();
  for(int i = 0; i<names.length; i++) {
    String path = XML.getResolvedPath(names[i], basePath);
    if (!path.endsWith(".jar") && !path.endsWith("/")) { //$NON-NLS-1$ //$NON-NLS-2$
    	path += "/";  // directories passed to URLClassLoader must end with slash //$NON-NLS-1$
    }
    try {
      urls.add(new URL("file:"+path)); //$NON-NLS-1$
    } catch(MalformedURLException ex) {
      OSPLog.info(ex+" "+path);        //$NON-NLS-1$
    }
  }
  // create the class loader
  classLoader = URLClassLoader.newInstance(urls.toArray(new URL[0]));
}
 
源代码23 项目: quarkus   文件: ArcTestContainer.java
@Override
public void afterEach(ExtensionContext extensionContext) throws Exception {
    ClassLoader oldTccl = getRootExtensionStore(extensionContext).get(KEY_OLD_TCCL, ClassLoader.class);
    Thread.currentThread().setContextClassLoader(oldTccl);

    URLClassLoader testClassLoader = getRootExtensionStore(extensionContext).get(KEY_TEST_CLASSLOADER,
            URLClassLoader.class);
    if (testClassLoader != null) {
        try {
            testClassLoader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    shutdown();
}
 
源代码24 项目: hottub   文件: IndirectlyLoadABundle.java
public boolean testGetAnonymousLogger() throws Throwable {
    // Test getAnonymousLogger()
    URLClassLoader loadItUpCL = new URLClassLoader(getURLs(), null);
    Class<?> loadItUpClazz = Class.forName("LoadItUp1", true, loadItUpCL);
    ClassLoader actual = loadItUpClazz.getClassLoader();
    if (actual != loadItUpCL) {
        throw new Exception("LoadItUp1 was loaded by an unexpected CL: "
                             + actual);
    }
    Object loadItUpAnon = loadItUpClazz.newInstance();
    Method testAnonMethod = loadItUpClazz.getMethod("getAnonymousLogger",
                                                    String.class);
    try {
        return (Logger)testAnonMethod.invoke(loadItUpAnon, rbName) != null;
    } catch (InvocationTargetException ex) {
        throw ex.getTargetException();
    }
}
 
源代码25 项目: The-5zig-Mod   文件: PluginManagerImpl.java
Class<?> getClassByName(String name, URLClassLoader ignore) {
	Class<?> clazz = cachedClasses.get(name);
	if (clazz != null) {
		return clazz;
	}
	for (LoadedPlugin plugin : plugins) {
		PluginClassLoader classLoader = plugin.getClassLoader();
		if (classLoader == ignore) {
			continue;
		}
		try {
			clazz = classLoader.findClass(name, false);
		} catch (ClassNotFoundException ignored) {
		}
		if (clazz != null) {
			cachedClasses.put(name, clazz);
			return clazz;
		}
	}
	return null;
}
 
源代码26 项目: openjdk-8   文件: ClassLoad.java
public static void main(String[] args) throws Exception {
     boolean error = true;

     // Start a dummy server to return 404
     HttpServer server = HttpServer.create(new InetSocketAddress(0), 0);
     HttpHandler handler = new HttpHandler() {
         public void handle(HttpExchange t) throws IOException {
             InputStream is = t.getRequestBody();
             while (is.read() != -1);
             t.sendResponseHeaders (404, -1);
             t.close();
         }
     };
     server.createContext("/", handler);
     server.start();

     // Client request
     try {
         URL url = new URL("http://localhost:" + server.getAddress().getPort());
         String name = args.length >= 2 ? args[1] : "foo.bar.Baz";
         ClassLoader loader = new URLClassLoader(new URL[] { url });
         System.out.println(url);
         Class c = loader.loadClass(name);
         System.out.println("Loaded class \"" + c.getName() + "\".");
     } catch (ClassNotFoundException ex) {
         System.out.println(ex);
         error = false;
     } finally {
         server.stop(0);
     }
     if (error)
         throw new RuntimeException("No ClassNotFoundException generated");
}
 
源代码27 项目: claw-compiler   文件: Configuration.java
/**
 * Read all the transformation sets.
 *
 * @param sets Parent element "sets" for the transformation set.
 * @throws Exception If transformation set file does not exist or not well
 *                   formatted.
 */
private void readSets(Element sets) throws Exception {
  File xsdSchema = Paths.get(_configuration_path, SET_XSD).toFile();

  NodeList transformationSets = sets.getElementsByTagName(SET_ELEMENT);
  for(int i = 0; i < transformationSets.getLength(); ++i) {
    Element e = (Element) transformationSets.item(i);
    String setName = e.getAttribute(NAME_ATTR);
    File setFile = Paths.get(_configuration_path, setName + XML_EXT).toFile();
    if(!setFile.exists()) {
      throw new Exception("Transformation set " + setName
          + " cannot be found!");
    }

    Document setDocument = parseAndValidate(setFile, xsdSchema);
    Element root = setDocument.getDocumentElement();
    boolean isExternal = root.hasAttribute(JAR_ATTR);

    // Try to locate the external jar
    if(isExternal) {
      String externalJar = root.getAttribute(JAR_ATTR);
      URLClassLoader loader = loadExternalJar(externalJar);
      readTransformations(setName, root, loader);
    } else {
      readTransformations(setName, root, null);
    }
  }
}
 
源代码28 项目: openjdk-jdk8u-backup   文件: JaxbMarshallTest.java
@Test
public void marshallClassCastExceptionTest() throws Exception {
    JAXBContext jaxbContext;
    Marshaller marshaller;
    URLClassLoader jaxbContextClassLoader;
    // Generate java classes by xjc
    runXjc(XSD_FILENAME);
    // Compile xjc generated java files
    compileXjcGeneratedClasses();

    // Create JAXB context based on xjc generated package.
    // Need to create URL class loader ot make compiled classes discoverable
    // by JAXB context
    jaxbContextClassLoader = URLClassLoader.newInstance(new URL[] {testWorkDirUrl});
    jaxbContext = JAXBContext.newInstance( TEST_PACKAGE, jaxbContextClassLoader);

    // Create instance of Xjc generated data type.
    // Java classes were compiled during the test execution hence reflection
    // is needed here
    Class classLongListClass = jaxbContextClassLoader.loadClass(TEST_CLASS);
    Object objectLongListClass = classLongListClass.newInstance();
    // Get 'getIn' method object
    Method getInMethod = classLongListClass.getMethod( GET_LIST_METHOD, (Class [])null );
    // Invoke 'getIn' method
    List<Long> inList = (List<Long>)getInMethod.invoke(objectLongListClass);
    // Add values into the jaxb object list
    inList.add(Long.valueOf(0));
    inList.add(Long.valueOf(43));
    inList.add(Long.valueOf(1000000123));

    // Marshall constructed complex type variable to standard output.
    // In case of failure the ClassCastException will be thrown
    marshaller = jaxbContext.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    marshaller.marshal(objectLongListClass, System.out);
}
 
源代码29 项目: coroutines   文件: GenericGeneratorsTest.java
@Test
public void mustCreateAndRunIfObjectStatements() throws Exception {
    // Augment signature
    methodNode.desc = Type.getMethodDescriptor(
            Type.getType(String.class),
            new Type[] { Type.getType(Object.class), Type.getType(Object.class) });
    
    // Initialize variable table
    VariableTable varTable = new VariableTable(classNode, methodNode);
    Variable intVar1 = varTable.getArgument(1);
    Variable intVar2 = varTable.getArgument(2);
    
    // Update method logic
    /**
     * if (arg1 == arg2) {
     *     return "match";
     * }
     * return "nomatch";
     */
    methodNode.instructions
            = merge(
                    ifObjectsEqual(
                            loadVar(intVar1),
                            loadVar(intVar2),
                            returnValue(Type.getType(String.class), loadStringConst("match"))),
                    returnValue(Type.getType(String.class), loadStringConst("nomatch"))
            );
    
    Object testObj1 = "test1";
    Object testObj2 = "test2";
    // Write to JAR file + load up in classloader -- then execute tests
    try (URLClassLoader cl = createJarAndLoad(classNode)) {
        Object obj = cl.loadClass(STUB_CLASSNAME).newInstance();
        
        assertEquals("match", MethodUtils.invokeMethod(obj, STUB_METHOD_NAME, testObj1, testObj1));
        assertEquals("nomatch", MethodUtils.invokeMethod(obj, STUB_METHOD_NAME, testObj1, testObj2));
        assertEquals("match", MethodUtils.invokeMethod(obj, STUB_METHOD_NAME, testObj2, testObj2));
    }
}
 
源代码30 项目: dependency-mediator   文件: DependencyMediator.java
private static Collection<URLClassLoader> getClassLoaders(ClassLoader baseClassLoader) {
    Collection<URLClassLoader> loaders = new ArrayList<URLClassLoader>();
    ClassLoader loader = baseClassLoader;
    while (loader != null) {
        //Ignore 
        if ("sun.misc.Launcher$ExtClassLoader".equals(loader.getClass().getName())) {
            break;
        }
        if (loader instanceof URLClassLoader) {
            loaders.add((URLClassLoader) loader);
        }
        loader = loader.getParent();
    }
    return loaders;
}
 
源代码评论
动弹
沙发等你来抢
 类所在包
 同包方法