Java Code Examples for java.io.File.toURL()

The following are Jave code examples for showing how to use toURL() of the java.io.File class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: incubator-netbeans   File: ProxyURLStreamHandlerFactoryTest.java   View Source Code Vote up 6 votes
public void testHandleSpaceInPathAsProducedByEclipse() throws Exception {
    File d = new File(getWorkDir(), "space in path");
    d.mkdirs();
    File f = new File(d, "x.jar");
    JarOutputStream os = new JarOutputStream(new FileOutputStream(f));
    os.putNextEntry(new JarEntry("test.txt"));
    os.write(10);
    os.close();
    
    URL u = new URL("jar:" + f.toURL() + "!/test.txt");
    DataInputStream is = new DataInputStream(u.openStream());
    byte[] arr = new byte[100];
    is.readFully(arr, 0, 1);
    assertEquals("One byte", 10, arr[0]);
    is.close();
}
 
Example 2
Project: incubator-netbeans   File: TransformUtil.java   View Source Code Vote up 6 votes
public static String getURLName (FileObject fileObject) throws MalformedURLException, FileStateInvalidException {
        URL fileURL = null;
        File file = FileUtil.toFile (fileObject);

        if ( file != null ) {
//            if ( Util.THIS.isLoggable() ) /* then */ {
//                try {
//                    Util.THIS.debug ("[TransformUtil.getURLName]");
//                    Util.THIS.debug ("    file = " + file);
//                    Util.THIS.debug ("    file.getCanonicalPath = " + file.getCanonicalPath());
//                    Util.THIS.debug ("    file.getAbsolutePath  = " + file.getAbsolutePath());
//                    Util.THIS.debug ("    file.toString  = " + file.toString());
//                    Util.THIS.debug ("    file.toURL  = " + file.toURL());
//                } catch (Exception exc) {
//                    Util.THIS.debug ("DEBUG Exception", exc);
//                }
//            }

            fileURL = file.toURL();
        } else {
            fileURL = fileObject.getURL();
        }

        return fileURL.toExternalForm();
    }
 
Example 3
Project: lams   File: ClasspathUtilsTest.java   View Source Code Vote up 6 votes
public void testGetClasspathComponentsFromClassLoader() throws MalformedURLException
{
    ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
    try
    {
        File file = new File("/some/package/dir");
        URL[] urls = new URL[] { file.toURL() };            
        // assert my package can't be found yet
        List components = ClasspathUtils.getClasspathComponents();
        Collections.sort(components);
        assertTrue(Collections.binarySearch(components, file.getPath()) < 0);
        // test my package is found
        URLClassLoader ucl = new URLClassLoader(urls, classLoader);
        Thread.currentThread().setContextClassLoader(ucl);
        components = ClasspathUtils.getClasspathComponents();
        Collections.sort(components);
        assertTrue( Collections.binarySearch(components, file.getAbsolutePath()) >= 0);
    }
    finally
    {
        Thread.currentThread().setContextClassLoader(classLoader);
    }
}
 
Example 4
Project: openjdk-jdk10   File: Security.java   View Source Code Vote up 6 votes
/**
 * The ProxyServer class is compiled by jtreg, but we want to
 * move it so it is not on the application claspath. We want to
 * load it through a separate classloader so that it has a separate
 * protection domain and security permissions.
 *
 * Its permissions are in the second grant block in each policy file
 */
static void setupProxy() throws IOException, ClassNotFoundException, NoSuchMethodException {
    testclasses = System.getProperty("test.classes");
    subdir = new File (testclasses, "proxydir");
    subdir.mkdir();

    movefile("ProxyServer.class");
    movefile("ProxyServer$Connection.class");
    movefile("ProxyServer$1.class");

    URL url = subdir.toURL();
    System.out.println("URL for class loader = " + url);
    URLClassLoader urlc = new URLClassLoader(new URL[] {url});
    proxyClass = Class.forName("ProxyServer", true, urlc);
    proxyConstructor = proxyClass.getConstructor(Integer.class, Boolean.class);
}
 
Example 5
Project: jdk8u-jdk   File: JdiLoadedByCustomLoader.java   View Source Code Vote up 6 votes
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);
}
 
Example 6
Project: openjdk-jdk10   File: OctaneTest.java   View Source Code Vote up 6 votes
public Double genericNashornTest(final String benchmark, final String testPath, final String[] args) throws Throwable {
    try {
        final PerformanceWrapper wrapper = new PerformanceWrapper();

        final ByteArrayOutputStream baos = new ByteArrayOutputStream();
        final PrintStream ps = new PrintStream(baos);

        final java.io.File test=new java.io.File(testPath);
        final File absoluteFile=test.getAbsoluteFile();
        @SuppressWarnings("deprecation")
        final
        URL testURL=absoluteFile.toURL();

        wrapper.runExecuteOnlyTest(testPath, 0, 0, testURL.toString(), ps, System.err, args);

        final byte[] output = baos.toByteArray();
        final List<String> result = outputToStrings(output);

        final Double _result = filterBenchmark(result, benchmark);

        return _result;
    } catch (final Throwable e) {
        e.printStackTrace();
        throw e;
    }
}
 
Example 7
Project: monarch   File: StatUtils.java   View Source Code Vote up 6 votes
private static byte[] readBytes(File file) throws IOException {
  int byteCount = (int) file.length();

  byte[] input = new byte[byteCount];

  URL url = file.toURL();
  assertThat(url).isNotNull();

  InputStream is = url.openStream();
  assertThat(is).isNotNull();

  BufferedInputStream bis = new BufferedInputStream(is);
  int bytesRead = bis.read(input);
  bis.close();

  assertThat(bytesRead).isEqualTo(byteCount);
  return input;
}
 
Example 8
Project: Recaf   File: Plugins.java   View Source Code Vote up 6 votes
/**
 * Initialize any plugins in the given jar.
 * 
 * @param jar
 *            Jar containing plugin classes.
 * @param classes
 *            Set of all classes within the jar.
 * @throws Exception
 *             Thrown if URLClassLoader couldn't be made or an instance of a
 *             class could not be loaded.
 */
@SuppressWarnings("deprecation")
private void load(File jar, Set<String> classes) throws IOException {
	// Create loader, and load classes.
	URLClassLoader child = new URLClassLoader(new URL[] { jar.toURL() }, ClassLoader.getSystemClassLoader());
	for (String name : classes) {
		try {
			Class<?> loaded = Class.forName(name, true, child);
			// Load and register plugins.
			if (Plugin.class.isAssignableFrom(loaded)) {
				Plugin instance = (Plugin) loaded.newInstance();
				loadPlugin(instance);
			}
		} catch (Throwable e) {
			Recaf.INSTANCE.logging.info("From '" + jar.getName() + "' failed to load '" + name + "' because: " + e.toString(), 2);
		}
	}
}
 
Example 9
Project: monarch   File: StatArchiveWriterReaderIntegrationTest.java   View Source Code Vote up 6 votes
private byte[] readBytes(File file) throws MalformedURLException, IOException {
  int byteCount = (int) file.length();

  byte[] input = new byte[byteCount];

  URL url = file.toURL();
  assertNotNull(url);

  InputStream is = url.openStream();
  assertNotNull(is);

  BufferedInputStream bis = new BufferedInputStream(is);
  int bytesRead = bis.read(input);
  bis.close();

  assertEquals(byteCount, bytesRead);
  return input;
}
 
Example 10
Project: incubator-netbeans   File: InstanceDataObjectGetNameTest.java   View Source Code Vote up 5 votes
protected void setUp () throws Exception {
    
    cnt = 0;
    
    File f = new File(getWorkDir(), "layer.xml");
    FileWriter w = new FileWriter(f);
    w.write("<filesystem><file name='x.instance'> ");
    w.write("  <attr name='name' methodvalue='" + InstanceDataObjectGetNameTest.class.getName() + ".computeName'/> ");
    w.write("</file></filesystem> ");
    w.close();

    fs = new MultiFileSystem(new FileSystem[] { 
        FileUtil.createMemoryFileSystem(), 
        new XMLFileSystem(f.toURL())
    });
    FileObject fo = fs.findResource("x.instance");
    assertNotNull(fo);
    
    assertNull(fo.getAttribute("name"));
    assertEquals("One call", 1, cnt);
    // clean
    cnt = 0;

    obj = DataObject.find(fo);
    
    assertEquals("No calls now", 0, cnt);
}
 
Example 11
Project: incubator-netbeans   File: TransformPerformer.java   View Source Code Vote up 5 votes
/**
 * If possible it finds "file:" URL if <code>fileObject</code> is on LocalFileSystem.
 * @return URL of <code>fileObject</code>.
 */
protected URL preferFileURL(FileObject fileObject) throws MalformedURLException, FileStateInvalidException {
    URL fileURL = null;
    File file = FileUtil.toFile(fileObject);
    
    if ( file != null ) {
        fileURL = file.toURL();
    } else {
        fileURL = fileObject.getURL();
    }
    return fileURL;
}
 
Example 12
Project: openjdk-jdk10   File: ToURL.java   View Source Code Vote up 5 votes
static void go(String fn) throws Exception {
    File f = new File(fn);
    URL u = f.toURL();
    String ufn = u.getFile();
    if (!ufn.endsWith("/"))
        throw new Exception(u + " does not end with slash");
    if (ufn.endsWith("//"))
        throw new Exception(u + " ends with two slashes");
}
 
Example 13
Project: sagiri   File: PluginBubble.java   View Source Code Vote up 5 votes
public PluginBubble(File pluginFile) throws Exception {
    URLClassLoader loader = new URLClassLoader(new URL[]{pluginFile.toURL()}, ClassLoader.getSystemClassLoader());
    InputStream stream = loader.getResourceAsStream("plugin.json");
    JSONObject json = new JSONObject(IOUtils.toString(stream, "utf-8"));
    stream.close();

    pluginName = json.getString("name");
    pluginInstance = (SagiriPlugin) loader.loadClass(json.getString("main")).newInstance();
}
 
Example 14
Project: javaide   File: DexClassLoader.java   View Source Code Vote up 5 votes
/**
 * Finds a resource. This method is called by {@code getResource()} after
 * the parent ClassLoader has failed to find a loaded resource of the same
 * name.
 *
 * @param name The name of the resource to find
 * @return the location of the resource as a URL, or {@code null} if the
 * resource is not found.
 */
@Override
protected URL findResource(String name) {
    ensureInit();

    int length = mFiles.length;

    for (int i = 0; i < length; i++) {
        File pathFile = mFiles[i];
        ZipFile zip = mZips[i];

        if (zip.getEntry(name) != null) {
            if (VERBOSE_DEBUG)
                System.out.println("  found " + name + " in " + pathFile);
            try {
                // File.toURL() is compliant with RFC 1738 in always
                // creating absolute path names. If we construct the
                // URL by concatenating strings, we might end up with
                // illegal URLs for relative names.
                return new URL("jar:" + pathFile.toURL() + "!/" + name);
            } catch (MalformedURLException e) {
                throw new RuntimeException(e);
            }
        }
    }

    if (VERBOSE_DEBUG)
        System.out.println("  resource " + name + " not found");

    return null;
}
 
Example 15
Project: openjdk-jdk10   File: JdiLoadedByCustomLoader.java   View Source Code Vote up 5 votes
public static void main(String args[]) throws Exception {
    // create files from given arguments and tools.jar
    File f1 = new File(args[0]);

    // create class loader
    URL[] urls = { f1.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);
}
 
Example 16
Project: incubator-netbeans   File: DbDriverManagerTest.java   View Source Code Vote up 4 votes
private static JDBCDriver createDummyJDBCDriver(File dataDir) throws MalformedURLException {
    URL url = dataDir.toURL();
    return JDBCDriver.create("test_driver", "DbDriverManagerTest DummyDriver", "DummyDriver", new URL[] { url });
}
 
Example 17
Project: joai-project   File: RepositoryManager.java   View Source Code Vote up 4 votes
/**
 *  Loads a new index at the current location and closes the previous one, if one was open.
 *
 * @exception  Exception  Description of the Exception
 */
private void loadNewIndex() throws Exception {

	// Set up indexing fields for XML formats, if a config exists:
	try {
		File xmlIndexerConf = new File(getConfigDir(), "xmlIndexerFieldsConfigIndex.xml");
		if (xmlIndexerConf.exists()) {
			xmlIndexerFieldsConfig = new XMLIndexerFieldsConfig(xmlIndexerConf.toURL());
			prtln("Search fields initialized successfully (XMLIndexerFieldsConfig)");
		}
	} catch (Throwable t) {
		prtlnErr("Error initializing the XMLIndexerFieldsConfig (skipping...): " + t);
	}

	// Set up an Analyzer for indexing and searching that handles each field appropriately (based on the config provided)
	PerFieldAnalyzer perFieldAnalyzer = new PerFieldAnalyzer();

	// Add the fields/analyzers from the fields config to the perFieldAnalyzer:
	if (xmlIndexerFieldsConfig != null) {
		Iterator it = xmlIndexerFieldsConfig.getFieldAnalyzers().entrySet().iterator();
		while (it.hasNext()) {
			Map.Entry pairs = (Map.Entry) it.next();
			prtln("Adding field/analyzer from XMLIndexerFieldsConfig: " + pairs.getKey() + "=" + pairs.getValue());
			perFieldAnalyzer.setAnalyzer((String) pairs.getKey(), (String) pairs.getValue());
		}
	}

	// Configure the core Analyzers to use on a per-field basis, overriding any definitions provided above:
	perFieldAnalyzer.addAnalyzersInBundle(Utils.getPropertiesResourceBundle("RepositoryManagerLuceneAnalyzers.properties"));
	perFieldAnalyzer.addAnalyzersInBundle(Utils.getPropertiesResourceBundle("FileIndexingPluginLuceneAnalyzers.properties"));

	prtln("perFieldAnalyzer configured as: " + perFieldAnalyzer);

	if (indexLocation == null)
		indexLocation = repositoryDataDir + "/repository_index";

	SimpleLuceneIndex oldIndex = index;

	SimpleLuceneIndex newIndex = new SimpleLuceneIndex(indexLocation, perFieldAnalyzer);
	newIndex.setOperator(SimpleLuceneIndex.DEFAULT_AND);
	index = newIndex;
	index.setAttribute("repositoryManager", this);

	if (oldIndex != null)
		oldIndex.close();
}
 
Example 18
Project: parabuild-ci   File: DetectorFactoryCollection.java   View Source Code Vote up 4 votes
/**
 * Load all plugins.
 * If a setPluginList() has been called, then those plugins
 * are loaded.  Otherwise, the "findbugs.home" property is checked
 * to determine where FindBugs is installed, and the plugin files
 * are dynamically loaded from the plugin directory.
 */
private void loadPlugins() {
	// Load all detector plugins.

	if (pluginList == null) {
		String homeDir = FindBugs.getHome();
		if (homeDir == null)
			return;

		File pluginDir = new File(homeDir + File.separator + "plugin");
		File[] contentList = pluginDir.listFiles();
		if (contentList == null) {
			System.err.println("Error: The path " + pluginDir.getPath() + " does not seem to be a directory!");
			System.err.println("No FindBugs plugins could be loaded");
			pluginList = new File[0];
			return;
		}

		ArrayList<File> arr = new ArrayList<File>();
		for (int i = 0; i < contentList.length; ++i) {
			if (contentList[i].getName().endsWith(".jar")) {
				if (FindBugs.DEBUG) System.out.println("Found plugin: " + contentList[i].toString());
				arr.add(contentList[i]);
			}
		}
		pluginList = (File[]) arr.toArray(new File[arr.size()]);
	}

	int numLoaded = 0;
	for (int i = 0; i < pluginList.length; ++i) {
		File file = pluginList[i];
		try {
			if (FindBugs.DEBUG) System.out.println("Loading plugin: " + file.toString());
			URL url = file.toURL();
			PluginLoader pluginLoader = new PluginLoader(url, this.getClass().getClassLoader());

			Plugin plugin = pluginLoader.getPlugin();
			pluginByIdMap.put(plugin.getPluginId(), plugin);
			
			// Register all of the detectors that this plugin contains
			for (Iterator<DetectorFactory> j = plugin.detectorFactoryIterator();
					j.hasNext(); ) {
				DetectorFactory factory = j.next();
				registerDetector(factory);
			}

			I18N i18n = I18N.instance();

			// Register the BugPatterns
			for (Iterator<BugPattern> j = plugin.bugPatternIterator(); j.hasNext();){ 
				BugPattern bugPattern = j.next();
				i18n.registerBugPattern(bugPattern);
			}
			
			// Register the BugCodes
			for (Iterator<BugCode> j = plugin.bugCodeIterator(); j.hasNext(); ) {
				BugCode bugCode = j.next();
				i18n.registerBugCode(bugCode);
			}

			++numLoaded;
		} catch (Exception e) {
			System.err.println("Warning: could not load plugin " + file.getPath() + ": " + e.toString());
			if (FindBugs.DEBUG)
				e.printStackTrace();
		}
	}

	//System.out.println("Loaded " + numLoaded + " plugins");
}
 
Example 19
Project: monarch   File: GemFireCacheImpl.java   View Source Code Vote up 4 votes
public URL getCacheXmlURL() {
  if (this.getMyId().getVmKind() == DistributionManager.LOCATOR_DM_TYPE) {
    return null;
  }
  File xmlFile = testCacheXml;
  if (xmlFile == null) {
    xmlFile = this.system.getConfig().getCacheXmlFile();
  }
  if ("".equals(xmlFile.getName())) {
    return null;
  }

  URL url = null;
  if (!xmlFile.exists() || !xmlFile.isFile()) {
    // do a resource search
    String resource = xmlFile.getPath();
    resource = resource.replaceAll("\\\\", "/");
    if (resource.length() > 1 && resource.startsWith("/")) {
      resource = resource.substring(1);
    }
    url = ClassPathLoader.getLatest().getResource(getClass(), resource);
  } else {
    try {
      url = xmlFile.toURL();
    } catch (IOException ex) {
      throw new CacheXmlException(
          LocalizedStrings.GemFireCache_COULD_NOT_CONVERT_XML_FILE_0_TO_AN_URL
              .toLocalizedString(xmlFile),
          ex);
    }
  }
  if (url == null) {
    File defaultFile = DistributionConfig.DEFAULT_CACHE_XML_FILE;
    if (!xmlFile.equals(defaultFile)) {
      if (!xmlFile.exists()) {
        throw new CacheXmlException(
            LocalizedStrings.GemFireCache_DECLARATIVE_CACHE_XML_FILERESOURCE_0_DOES_NOT_EXIST
                .toLocalizedString(xmlFile));
      } else /* if (!xmlFile.isFile()) */ {
        throw new CacheXmlException(
            LocalizedStrings.GemFireCache_DECLARATIVE_XML_FILE_0_IS_NOT_A_FILE
                .toLocalizedString(xmlFile));
      }
    }
  }

  return url;
}
 
Example 20
Project: lams   File: DigestingPlugIn.java   View Source Code Vote up 2 votes
/**
 * Given a string, return a URL to a Filesystem resource of that name.
 * @param path a path to a file.
 * @return a URL identifying the resource in the in the file system.
 * @throws MalformedURLException
 * @throws FileNotFoundException
 */
protected URL getFileURL(String path) throws IOException {
    File file = new File(path);
    return file.toURL();
}