java.net.URLClassLoader Java Examples

The following examples show how to use java.net.URLClassLoader. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ReflectionBenchmarkUniqueAccessTest.java    From AVM with MIT License 7 votes vote down vote up
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;
}
 
Example #2
Source File: BootstrapUtil.java    From GriefDefender with MIT License 6 votes vote down vote up
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();
    }
}
 
Example #3
Source File: AllocationStackTrace.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * 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);
    }
}
 
Example #4
Source File: ChangeSetTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #5
Source File: TomEEJarScanner.java    From tomee with Apache License 2.0 6 votes vote down vote up
@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));
    }
}
 
Example #6
Source File: TestTezClientUtils.java    From incubator-tez with Apache License 2.0 6 votes vote down vote up
/**
 * 
 * @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());
}
 
Example #7
Source File: PackageInfoCache.java    From j2cl with Apache License 2.0 6 votes vote down vote up
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));
}
 
Example #8
Source File: B7050028.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
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()));
}
 
Example #9
Source File: ReflectionBenchmarkUniqueAccessTest.java    From AVM with MIT License 6 votes vote down vote up
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;
}
 
Example #10
Source File: Loader.java    From IoTgo_Android_App with MIT License 6 votes vote down vote up
/**
 * 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();
}
 
Example #11
Source File: StandaloneTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #12
Source File: LeakTest.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
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);
}
 
Example #13
Source File: LaunchClassChooser.java    From osp with GNU General Public License v3.0 6 votes vote down vote up
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]));
}
 
Example #14
Source File: PinotServiceManagerAdminApiApplication.java    From incubator-pinot with Apache License 2.0 6 votes vote down vote up
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/");
}
 
Example #15
Source File: AvailableGames.java    From triplea with GNU General Public License v3.0 6 votes vote down vote up
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;
}
 
Example #16
Source File: JAXRSContainerTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@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));
    }
}
 
Example #17
Source File: SOLRAPIClientTest.java    From SearchServices with GNU Lesser General Public License v3.0 6 votes vote down vote up
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();
    }
}
 
Example #18
Source File: ArcTestContainer.java    From quarkus with Apache License 2.0 6 votes vote down vote up
@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();
}
 
Example #19
Source File: AbstractTest.java    From gridgo with MIT License 6 votes vote down vote up
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);
}
 
Example #20
Source File: IndirectlyLoadABundle.java    From hottub with GNU General Public License v2.0 6 votes vote down vote up
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();
    }
}
 
Example #21
Source File: Main.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
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;
}
 
Example #22
Source File: PluginManagerImpl.java    From The-5zig-Mod with MIT License 6 votes vote down vote up
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;
}
 
Example #23
Source File: SchemaGenerator.java    From hottub with GNU General Public License v2.0 6 votes vote down vote up
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();
}
 
Example #24
Source File: PluginClassLoader.java    From cherry with Apache License 2.0 5 votes vote down vote up
private URLClassLoader replaceClassLoader(final URLClassLoader oldLoader,
		final File base, final FileFilter filter) {

	if (null != base && base.canRead() && base.isDirectory()) {
		File[] files = base.listFiles(filter);

		if (null == files || 0 == files.length){
			logger.error("replaceClassLoader base dir:{} is empty", base.getAbsolutePath());
			return oldLoader;
		}

		logger.error("replaceClassLoader base dir: {} ,size: {}", base.getAbsolutePath(), files.length);
		
		URL[] oldElements = oldLoader.getURLs();
		URL[] elements = new URL[oldElements.length + files.length];
		System.arraycopy(oldElements, 0, elements, 0, oldElements.length);

		for (int j = 0; j < files.length; j++) {
			try {
				URL element = files[j].toURI().normalize().toURL();
				elements[oldElements.length + j] = element;
				
				logger.info("Adding '{}' to classloader", element.toString());
				
			} catch (MalformedURLException e) {
				logger.error("load jar file error", e);
			}
		}
		ClassLoader oldParent = oldLoader.getParent();
		IoUtils.closeQuietly(oldLoader); // best effort
		return URLClassLoader.newInstance(elements, oldParent);
	}
	
	return oldLoader;
}
 
Example #25
Source File: GraphicalReceiver.java    From yfiton with Apache License 2.0 5 votes vote down vote up
private String getClasspath() {
    StringBuilder result = new StringBuilder();

    for (URL url : ((URLClassLoader) Thread.currentThread().getContextClassLoader()).getURLs()) {
        result.append(new File(url.getPath()));
        result.append(File.pathSeparatorChar);
    }

    return result.toString();
}
 
Example #26
Source File: AbstractDynamicTypeBuilderForInliningTest.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
@Test
public void testDefaultValue() throws Exception {
    Class<?> dynamicType = create(Baz.class)
            .method(named(FOO)).defaultValue(FOO, String.class)
            .make()
            .load(new URLClassLoader(new URL[0], null), ClassLoadingStrategy.Default.WRAPPER)
            .getLoaded();
    assertThat(dynamicType.getDeclaredMethods().length, is(1));
    assertThat(dynamicType.getDeclaredMethod(FOO).getDefaultValue(), is((Object) FOO));
}
 
Example #27
Source File: GetOpenApiDocAction.java    From endpoints-java with Apache License 2.0 5 votes vote down vote up
/**
 * Generates an OpenAPI document for an array of service classes.
 *
 * @param classPath Class path to load service classes and their dependencies
 * @param outputFilePath File to store the OpenAPI document in
 * @param hostname The hostname to use for the OpenAPI document
 * @param basePath The base path to use for the OpenAPI document, e.g. /_ah/api
 * @param serviceClassNames Array of service class names of the API
 * @param outputToDisk Iff {@code true}, outputs a openapi.json to disk.
 * @return a single OpenAPI document representing all service classes.
 */
public String genOpenApiDoc(
    URL[] classPath, String outputFilePath, String hostname, String basePath,
    List<String> serviceClassNames, boolean outputToDisk)
    throws ClassNotFoundException, IOException, ApiConfigException {
  File outputFile = new File(outputFilePath);
  File outputDir = outputFile.getParentFile();
  if (!outputDir.isDirectory() || outputFile.isDirectory()) {
    throw new IllegalArgumentException(outputFilePath + " is not a file");
  }

  ClassLoader classLoader = new URLClassLoader(classPath, getClass().getClassLoader());
  ApiConfig.Factory configFactory = new ApiConfig.Factory();
  Class<?>[] serviceClasses = loadClasses(classLoader, serviceClassNames);
  List<ApiConfig> apiConfigs = Lists.newArrayListWithCapacity(serviceClasses.length);
  TypeLoader typeLoader = new TypeLoader(classLoader);
  ApiConfigLoader configLoader = new ApiConfigLoader(configFactory, typeLoader,
      new ApiConfigAnnotationReader(typeLoader.getAnnotationTypes()));
  ServiceContext serviceContext = ServiceContext.create();
  for (Class<?> serviceClass : serviceClasses) {
    apiConfigs.add(configLoader.loadConfiguration(serviceContext, serviceClass));
  }
  SwaggerGenerator generator = new SwaggerGenerator();
  SwaggerContext swaggerContext = new SwaggerContext()
      .setHostname(hostname)
      .setBasePath(basePath);
  Swagger swagger = generator.writeSwagger(apiConfigs, true, swaggerContext);
  String swaggerStr = Json.mapper().writer(new EndpointsPrettyPrinter())
      .writeValueAsString(swagger);
  if (outputToDisk) {
    Files.write(swaggerStr, outputFile, UTF_8);
    System.out.println("OpenAPI document written to " + outputFilePath);
  }

  return swaggerStr;
}
 
Example #28
Source File: Main.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
private static FileSystem createFsWithURLClassloader(String javaHome) throws IOException{
    URL url = Paths.get(javaHome, "lib", "jrt-fs.jar").toUri().toURL();
    URLClassLoader loader = new URLClassLoader(new URL[] { url });
    return FileSystems.newFileSystem(URI.create("jrt:/"),
                                                Collections.emptyMap(),
                                                loader);
}
 
Example #29
Source File: DynamicCompiler.java    From oxygen with Apache License 2.0 5 votes vote down vote up
public DynamicCompiler() {
  ClassLoader parent = Thread.currentThread().getContextClassLoader();
  this.loader = new DynamicClassLoader(parent, byteCodes);
  this.compiler = ToolProvider.getSystemJavaCompiler();
  if (this.compiler == null) {
    throw Exceptions.fail("no compiler found");
  }
  StandardJavaFileManager fileManager = compiler.getStandardFileManager(collector, null, null);
  if (parent instanceof URLClassLoader) {
    try {
      List<File> files = new ArrayList<>();
      for (URL url : ((URLClassLoader) parent).getURLs()) {
        files.add(new File(url.getFile()));
      }
      fileManager.setLocation(StandardLocation.CLASS_PATH, files);
    } catch (IOException e) {
      throw new IllegalStateException(e.getMessage(), e);
    }
  }
  this.manager = new DynamicJavaFileManager(fileManager, loader, sources, byteCodes);
  this.options = new ArrayList<>();
  String value = CoreConfigKeys.COMPILER_OPTIONS.getValue();
  if (Strings.hasText(value)) {
    for (String option : value.split(Strings.COMMA)) {
      options.add(option.trim());
    }
  }
}
 
Example #30
Source File: DefaultMethodRegressionTestsRun.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
static void runClass(
        File classPath,
        String classname) throws Exception {
    URL[] urls = {classPath.toURI().toURL()};
    ClassLoader loader = new URLClassLoader(urls);
    Class<?> c = loader.loadClass(classname);

    Class<?>[] argTypes = new Class<?>[]{String[].class};
    Object[] methodArgs = new Object[]{null};

    Method method = c.getMethod("main", argTypes);
    method.invoke(c, methodArgs);
}