Java Code Examples for java.net.URLClassLoader#newInstance()

The following examples show how to use java.net.URLClassLoader#newInstance() . 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: MemoryLeakTestCase.java    From commons-beanutils with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a new class loader instance.
 */
private static URLClassLoader newClassLoader() throws MalformedURLException {

    final String dataFilePath = MemoryLeakTestCase.class.getResource("pojotests").getFile();
    //System.out.println("dataFilePath: " + dataFilePath);
    final String location = "file://" + dataFilePath.substring(0,dataFilePath.length()-"org.apache.commons.beanutils2.memoryleaktests.pojotests".length());
    //System.out.println("location: " + location);

    final StringBuilder newString = new StringBuilder();
    for (int i=0;i<location.length();i++) {
        if (location.charAt(i)=='\\') {
            newString.append("/");
        } else {
            newString.append(location.charAt(i));
        }
    }
    final String classLocation = newString.toString();
    //System.out.println("classlocation: " + classLocation);

    final URLClassLoader theLoader = URLClassLoader.newInstance(new URL[]{new URL(classLocation)},null);
    return theLoader;
}
 
Example 2
Source File: BuildVsRuntimeJarAccessTest.java    From styx with Apache License 2.0 6 votes vote down vote up
@Test
public void pluginAndDependencyClassesAreAvailableWhenReferencingDirectory() throws IOException, ClassNotFoundException {
    Path jarLocation = createTemporarySharedDirectoryForJars();

    URL[] urls = list(jarLocation)
            .map(BuildVsRuntimeJarAccessTest::url)
            .toArray(URL[]::new);

    try (URLClassLoader classLoader = URLClassLoader.newInstance(urls)) {
        Class<?> pluginClass = classLoader.loadClass("testgrp.TestPlugin");
        assertThat(pluginClass.getName(), is("testgrp.TestPlugin"));

        Class<?> dependencyClass = classLoader.loadClass("depend.ExampleDependency");
        assertThat(dependencyClass.getName(), is("depend.ExampleDependency"));
    }
}
 
Example 3
Source File: Java2WSDL.java    From carbon-commons with Apache License 2.0 6 votes vote down vote up
/**
 * This is the fall though method for wsdlview. This will check for required resources.
 *
 * @param options options array
 * @param uuids   uuid array
 * @return String id
 * @throws AxisFault will be thrown.
 */
public String java2wsdlWithResources(String[] options, String[] uuids) throws AxisFault {

    ClassLoader prevCl = Thread.currentThread().getContextClassLoader();
    try {
        URL[] urls = new URL[uuids.length];
        for (int i = 0; i < uuids.length; i++) {
            urls[i] = new File(uuids[i]).toURL();
        }
        ClassLoader newCl = URLClassLoader.newInstance(urls, prevCl);
        Thread.currentThread().setContextClassLoader(newCl);
        return java2wsdl(options);
    } catch (MalformedURLException e) {
        throw AxisFault.makeFault(e);
    } finally {
        Thread.currentThread().setContextClassLoader(prevCl);
    }

}
 
Example 4
Source File: FeatureListHandler.java    From jAudioGIT with GNU Lesser General Public License v2.1 5 votes vote down vote up
public void characters(char[] ch, int start, int length)
			throws SAXException {
		switch (tagType) {
		case FEATURE_LIST:
			break;
		case FEATURE:
			break;
		case CLASS:
			className = new String(ch, start, length);
			break;
		case ON:
			break;
		case PLUGIN_LOCATION:
			try {
					URL[] pluginURL = new URL[]{new URL(new String(ch,start,length))};
					classLoader =URLClassLoader.newInstance(pluginURL, Thread.currentThread().getContextClassLoader());
//					java.lang.Thread.currentThread().setContextClassLoader(classLoader);
				} catch (MalformedURLException e) {
					throw new SAXException("Plugin location not a valid URL:"+new String(ch,start,length));
				}
				break;
		case AGGREGATOR:
			className = new String(ch,start,length);
			break;
		default:
			if(!firstTag){
				throw new SAXException("Unknown tagType found (" + tagType + ") - content='"+new String(ch,start,length)+"'");
			}
		}
	}
 
Example 5
Source File: VersionHelper12.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
ClassLoader getURLClassLoader(String[] url)
    throws MalformedURLException {
        ClassLoader parent = getContextClassLoader();
        /*
         * Classes may only be loaded from an arbitrary URL code base when
         * the system property com.sun.jndi.ldap.object.trustURLCodebase
         * has been set to "true".
         */
        if (url != null && "true".equalsIgnoreCase(trustURLCodebase)) {
            return URLClassLoader.newInstance(getUrlArray(url), parent);
        } else {
            return parent;
        }
}
 
Example 6
Source File: JaxbMarshallTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
@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);
}
 
Example 7
Source File: FastGenericSerializerGeneratorTest.java    From avro-util with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@BeforeTest(groups = {"serializationTest"})
public void prepare() throws Exception {
  tempDir = getCodeGenDirectory();

  classLoader = URLClassLoader.newInstance(new URL[]{tempDir.toURI().toURL()},
      FastGenericSerializerGeneratorTest.class.getClassLoader());
}
 
Example 8
Source File: FastDeserializerDefaultsTest.java    From avro-util with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@BeforeTest(groups = {"deserializationTest"})
public void prepare() throws Exception {
  Path tempPath = Files.createTempDirectory("generated");
  tempDir = tempPath.toFile();

  classLoader = URLClassLoader.newInstance(new URL[]{tempDir.toURI().toURL()},
      FastDeserializerDefaultsTest.class.getClassLoader());
}
 
Example 9
Source File: VersionHelper12.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
ClassLoader getURLClassLoader(String[] url)
    throws MalformedURLException {
        ClassLoader parent = getContextClassLoader();
        /*
         * Classes may only be loaded from an arbitrary URL code base when
         * the system property com.sun.jndi.ldap.object.trustURLCodebase
         * has been set to "true".
         */
        if (url != null && "true".equalsIgnoreCase(trustURLCodebase)) {
            return URLClassLoader.newInstance(getUrlArray(url), parent);
        } else {
            return parent;
        }
}
 
Example 10
Source File: VersionHelper12.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * @param className A non-null fully qualified class name.
 * @param codebase A non-null, space-separated list of URL strings.
 */
public Class<?> loadClass(String className, String codebase)
        throws ClassNotFoundException, MalformedURLException {

    ClassLoader parent = getContextClassLoader();
    ClassLoader cl =
             URLClassLoader.newInstance(getUrlArray(codebase), parent);

    return loadClass(className, cl);
}
 
Example 11
Source File: ResourceBundleWrapper.java    From buffer_bci with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Instantiate a {@link URLClassLoader} for resource lookups where the
 * codeBase URL is removed.  This method is typically called from an
 * applet's init() method.  If this method is never called, the
 * <code>getBundle()</code> methods map to the standard
 * {@link ResourceBundle} lookup methods.
 *
 * @param codeBase  the codeBase URL.
 * @param urlClassLoader  the class loader.
 */
public static void removeCodeBase(URL codeBase,
        URLClassLoader urlClassLoader) {
    List urlsNoBase = new ArrayList();

    URL[] urls = urlClassLoader.getURLs();
    for (int i = 0; i < urls.length; i++) {
        if (!urls[i].sameFile(codeBase)) {
            urlsNoBase.add(urls[i]);
        }
    }
    // substitute the filtered URL list
    URL[] urlsNoBaseArray = (URL[]) urlsNoBase.toArray(new URL[0]);
    noCodeBaseClassLoader = URLClassLoader.newInstance(urlsNoBaseArray);
}
 
Example 12
Source File: FridaAndroidTracer.java    From FridaAndroidTracer with MIT License 5 votes vote down vote up
private ClassLoader loadJars(String[] jarFiles) {
    URL[] urls = Stream.of(jarFiles)
            .map(name -> {
                try {
                    return new File(name).toURI().toURL();
                } catch (MalformedURLException e) {
                    System.out.println("Fail to load jar file: " + name);
                    e.printStackTrace();
                    return null;
                }
            })
            .toArray(URL[]::new);
    return URLClassLoader.newInstance(urls, ClassLoader.getSystemClassLoader());
}
 
Example 13
Source File: SamsungBleStack.java    From awesomesauce-rfduino with GNU Lesser General Public License v2.1 5 votes vote down vote up
/** Function to use our version of BluetoothAdapter and BluetoothDevice if the native Android OS doesn't have 4.3 yet. 
 * @throws IOException 
 * @throws ClassNotFoundException **/
public static void loadSamsungLibraries(Context hostActivityContext) throws IOException, ClassNotFoundException{
	File internalStoragePath = hostActivityContext.getFileStreamPath("com.samsung.ble.sdk-1.0.jar");
	if (!internalStoragePath.exists()){
		
	
	  //We'll copy the SDK to disk so we can open the JAR file:
	  // it has to be first copied from asset resource to a storage location.
	  InputStream jar = hostActivityContext.getAssets().open("com.samsung.ble.sdk-1.0.jar", Context.MODE_PRIVATE);
	  FileOutputStream outputStream = hostActivityContext.openFileOutput("com.samsung.ble.sdk-1.0.jar", Context.MODE_PRIVATE);
	     
	  int size = 0;
	    // Read the entire resource into a local byte buffer.
	    byte[] buffer = new byte[1024];
	    while((size=jar.read(buffer,0,1024))>=0){
	      outputStream.write(buffer,0,size);
	    }
	    jar.close();
	   
	}
	    
	  Log.i(logTag, internalStoragePath.getAbsolutePath()+" exists? "+ internalStoragePath.exists());
	  
         URL[] urls = { new URL("jar:file:" + internalStoragePath.getAbsolutePath()+"!/") };
         URLClassLoader cl  = URLClassLoader.newInstance(urls);
         
         samsungBluetoothAdapterClass = cl.loadClass("android.bluetooth.BluetoothAdapter");
         samsungBluetoothDeviceClass = cl.loadClass("android.bluetooth.BluetoothDevice");
 	
}
 
Example 14
Source File: FastSpecificDeserializerGeneratorTest.java    From avro-util with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@BeforeTest(groups = {"deserializationTest"})
public void prepare() throws Exception {
  Path tempPath = Files.createTempDirectory("generated");
  tempDir = tempPath.toFile();

  classLoader = URLClassLoader.newInstance(new URL[]{tempDir.toURI().toURL()},
      FastSpecificDeserializerGeneratorTest.class.getClassLoader());
}
 
Example 15
Source File: VersionHelper12.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * @param className A non-null fully qualified class name.
 * @param codebase A non-null, space-separated list of URL strings.
 */
public Class<?> loadClass(String className, String codebase)
        throws ClassNotFoundException, MalformedURLException {

    ClassLoader parent = getContextClassLoader();
    ClassLoader cl =
             URLClassLoader.newInstance(getUrlArray(codebase), parent);

    return loadClass(className, cl);
}
 
Example 16
Source File: RuntimeTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
private static void testURLClassLoaderURL(URL jarURL,
        int mainVersionExpected, int helperVersionExpected,
        int resourceVersionExpected) throws ClassNotFoundException,
        NoSuchMethodException, IllegalAccessException,
        IllegalArgumentException, InvocationTargetException, IOException {
    System.out.println(
            "Testing URLClassLoader MV JAR support for URL: " + jarURL);
    URL[] urls = { jarURL };
    int mainVersionActual;
    int helperVersionActual;
    int resourceVersionActual;
    try (URLClassLoader cl = URLClassLoader.newInstance(urls)) {
        Class c = cl.loadClass("testpackage.Main");
        Method getMainVersion = c.getMethod("getMainVersion");
        mainVersionActual = (int) getMainVersion.invoke(null);
        Method getHelperVersion = c.getMethod("getHelperVersion");
        helperVersionActual = (int) getHelperVersion.invoke(null);
        try (InputStream ris = cl.getResourceAsStream("versionResource");
                BufferedReader br = new BufferedReader(
                        new InputStreamReader(ris))) {
            resourceVersionActual = Integer.parseInt(br.readLine());
        }
    }

    assertEquals(mainVersionActual, mainVersionExpected,
                     "Test failed: Expected Main class version: "
                     + mainVersionExpected + " Actual version: "
                     + mainVersionActual);
    assertEquals(helperVersionActual, helperVersionExpected,
                     "Test failed: Expected Helper class version: "
                     + helperVersionExpected + " Actual version: "
                     + helperVersionActual);
    assertEquals(resourceVersionActual, resourceVersionExpected,
                     "Test failed: Expected resource version: "
                     + resourceVersionExpected + " Actual version: "
                     + resourceVersionActual);
}
 
Example 17
Source File: PojoSerializerUpgradeTest.java    From flink with Apache License 2.0 4 votes vote down vote up
private void testPojoSerializerUpgrade(String classSourceA, String classSourceB, boolean hasBField, boolean isKeyedState) throws Exception {
	final Configuration taskConfiguration = new Configuration();
	final ExecutionConfig executionConfig = new ExecutionConfig();
	final KeySelector<Long, Long> keySelector = new IdentityKeySelector<>();
	final Collection<Long> inputs = Arrays.asList(1L, 2L, 45L, 67L, 1337L);

	// run the program with classSourceA
	File rootPath = temporaryFolder.newFolder();
	File sourceFile = writeSourceFile(rootPath, POJO_NAME + ".java", classSourceA);
	compileClass(sourceFile);

	final ClassLoader classLoader = URLClassLoader.newInstance(
		new URL[]{rootPath.toURI().toURL()},
		Thread.currentThread().getContextClassLoader());

	OperatorSubtaskState stateHandles = runOperator(
		taskConfiguration,
		executionConfig,
		new StreamMap<>(new StatefulMapper(isKeyedState, false, hasBField)),
		keySelector,
		isKeyedState,
		stateBackend,
		classLoader,
		null,
		inputs);

	// run the program with classSourceB
	rootPath = temporaryFolder.newFolder();

	sourceFile = writeSourceFile(rootPath, POJO_NAME + ".java", classSourceB);
	compileClass(sourceFile);

	final ClassLoader classLoaderB = URLClassLoader.newInstance(
		new URL[]{rootPath.toURI().toURL()},
		Thread.currentThread().getContextClassLoader());

	runOperator(
		taskConfiguration,
		executionConfig,
		new StreamMap<>(new StatefulMapper(isKeyedState, true, hasBField)),
		keySelector,
		isKeyedState,
		stateBackend,
		classLoaderB,
		stateHandles,
		inputs);
}
 
Example 18
Source File: DefaultMethodTest.java    From yGuard with MIT License 4 votes vote down vote up
@Test
public void SimpleChainTest() {
  final String testTypeName = "com.yworks.yshrink.java13.SimpleChainTest";

  final String fileName = "SimpleChainTest.txt";
  final URL source = getClass().getResource(fileName);
  assertNotNull("Could not resolve " + fileName + '.', source);


  // compile the java source code
  final com.yworks.util.Compiler compiler = com.yworks.util.Compiler.newCompiler();

  final ByteArrayOutputStream baos = new ByteArrayOutputStream();
  compiler.compile(List.of(compiler.newUrlSource(testTypeName, source)), baos);

  try {
    // store resulting bytecode in temporary files and ...
    File inTmp = File.createTempFile(name.getMethodName() + "_in_", ".jar");
    File outTmp = File.createTempFile(name.getMethodName() + "_out_", ".jar");
    Files.write(inTmp.toPath(), baos.toByteArray());

    // Run shrinker
    YShrink yShrink = new YShrink(false, "SHA-1,MD5");
    InOutPair inOutPair = new InOutPair();
    inOutPair.setIn(inTmp);
    inOutPair.setOut(outTmp);
    yShrink.doShrinkPairs(List.of(inOutPair), new AllMainMethodsFilter(), null);

    //   load shrinked class and run test method
    final ByteArrayOutputStream output = new ByteArrayOutputStream();
    final ClassLoader cl = URLClassLoader.newInstance(new URL[]{outTmp.toURI().toURL()});
    final Class shrinkedType = Class.forName(testTypeName, true, cl);
    final Method run =  shrinkedType.getMethod("run", PrintStream.class);
    run.invoke(null, new PrintStream(output));

    //   check test method output
    assertEquals(
            "Wrong test output",
            String.format("Hello from second interface%n", System.lineSeparator()),
            output.toString());

    // clean up and remove temporary files
    inTmp.delete();
    outTmp.delete();
  } catch (Exception e) {
    e.printStackTrace();
  }
}
 
Example 19
Source File: MyBatisGeneratorTool.java    From mybatis-generator-plugin with Apache License 2.0 4 votes vote down vote up
/**
 * 获取目标目录的ClassLoader
 * @return
 */
public ClassLoader getTargetClassLoader() throws MalformedURLException {
    return URLClassLoader.newInstance(new URL[]{
            new File(targetProject).toURI().toURL()
    });
}
 
Example 20
Source File: TestUtils.java    From coroutines with GNU Lesser General Public License v3.0 3 votes vote down vote up
/**
 * Writes entries to a JAR and loads it up.
 * @param entries class nodes to put in to jar
 * @return class loader with files in newly created JAR available
 * @throws IOException if any IO error occurs
 * @throws NullPointerException if any argument is {@code null} or contains {@code null}
 * @throws IllegalArgumentException if {@code classNodes} is empty
 */
public static URLClassLoader createJarAndLoad(JarEntry ... entries) throws IOException {
    Validate.notNull(entries);
    Validate.noNullElements(entries);
    
    File jarFile = createJar(entries);
    return URLClassLoader.newInstance(new URL[] { jarFile.toURI().toURL() }, TestUtils.class.getClassLoader());
}