Java Code Examples for java.net.URI#toURL()

The following examples show how to use java.net.URI#toURL() . 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: ColParser.java    From jaamsim with Apache License 2.0 6 votes vote down vote up
public static MeshData parse(URI asset) throws RenderException {

		try {
			ColParser colParser = new ColParser(asset.toURL());

			MeshData finalData = colParser.getData();
			finalData.setSource(asset.toString());

			colParser.processContent();

			return finalData;

		} catch (Exception e) {
			LogBox.renderLogException(e);
			throw new RenderException(e.getMessage());
		}
	}
 
Example 2
Source File: JarResource.java    From quarkus with Apache License 2.0 6 votes vote down vote up
@Override
public ProtectionDomain getProtectionDomain(ClassLoader classLoader) {
    URL url = null;
    try {
        String path = jarPath.toAbsolutePath().toString();
        if (!path.startsWith("/")) {
            path = "/" + path;
        }
        URI uri = new URI("jar:file", null, path + "!/", null);
        url = uri.toURL();
    } catch (URISyntaxException | MalformedURLException e) {
        throw new RuntimeException("Unable to create protection domain for " + jarPath, e);
    }
    CodeSource codesource = new CodeSource(url, (Certificate[]) null);
    ProtectionDomain protectionDomain = new ProtectionDomain(codesource, null, classLoader, null);
    return protectionDomain;
}
 
Example 3
Source File: TGUpdateWrittenFileController.java    From tuxguitar with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Override
public void update(TGContext context, TGActionContext actionContext) {
	try {
		String fileName = actionContext.getAttribute(TGWriteFileAction.ATTRIBUTE_FILE_NAME);
		if( fileName != null ) {
			URI uri = new File(fileName).toURI();
			URL url = uri.toURL();
			
			TGDocumentListManager.getInstance(context).findCurrentDocument().setUri(uri);
			
			TGFileHistory tgFileHistory = TGFileHistory.getInstance(context);
			tgFileHistory.reset(url);
			tgFileHistory.setChooserPath( url );
		}
		
		super.update(context, actionContext);
	} catch (MalformedURLException e) {
		throw new TGException(e);
	}
}
 
Example 4
Source File: FetchDocListTask.java    From marathonv5 with Apache License 2.0 6 votes vote down vote up
@Override protected String call() throws Exception {
    System.out.println("---- FetchDocListTask  docsUrl = "+docsDirUrl);
    StringBuilder builder = new StringBuilder();
    try {
        URI uri = new URI(docsDirUrl + "allclasses-frame.html");
        URL url = uri.toURL();
        URLConnection urlConnection = url.openConnection();
        urlConnection.setConnectTimeout(5000); //set timeout to 5 secs
        InputStream in = urlConnection.getInputStream();

        BufferedReader reader = new BufferedReader(new InputStreamReader(in));
        String line;
        while ((line = reader.readLine()) != null) {
            builder.append(line);
            builder.append('\n');
        }
        reader.close();
    } catch (URISyntaxException e) {
        e.printStackTrace();
    }
    return builder.toString();
}
 
Example 5
Source File: URLUtils.java    From maestro-java with Apache License 2.0 6 votes vote down vote up
/**
 * Gets the file name of a given URI
 * 
 * @param uri
 *            the input URI object
 * @return the file name part of the URI
 * @throws MalformedURLException
 *             if the URI is invalid or null
 */
public static String getFilename(final URI uri)
		throws MalformedURLException {
	URL url;

	if (uri == null) {
		throw new MalformedURLException("The input URL 'null' is not valid");
	}

	url = uri.toURL();

	String filePath = url.getFile();
	int lastIndex = filePath.lastIndexOf(URL_SEPARATOR);

	String filenameWithParameters = filePath.substring(lastIndex + 1);
	
	return removeParametersFromName(filenameWithParameters);
}
 
Example 6
Source File: ConfigFile.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Creates a new {@code ConfigurationSpi} object from the specified
 * {@code URI}.
 *
 * @param uri the {@code URI}
 * @throws SecurityException if the {@code ConfigurationSpi} can not be
 *                           initialized
 * @throws NullPointerException if {@code uri} is null
 */
public Spi(URI uri) {
    // only load config from the specified URI
    try {
        url = uri.toURL();
        init();
    } catch (IOException ioe) {
        throw new SecurityException(ioe);
    }
}
 
Example 7
Source File: Transformers.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * Converts a URL to a URI
 */
public static Transformer<URL, URI> toURL() {
    return new Transformer<URL, URI>() {
        public URL transform(URI original) {
            try {
                return original.toURL();
            } catch (MalformedURLException e) {
                throw UncheckedException.throwAsUncheckedException(e);
            }
        }
    };
}
 
Example 8
Source File: JarEntryInfo.java    From kumuluzee with MIT License 5 votes vote down vote up
public URL getURL() { // used in findResource() and findResources()
    try {
        String jarFileName = new File(jarFileInfo.getJarFile().getName()).toURI().toString();
        URI uri = new URI("jar:" + jarFileName + "!/" + jarEntry);
        return uri.toURL();
    } catch (URISyntaxException | MalformedURLException e) {
        return null;
    }
}
 
Example 9
Source File: JnlpResponseCache.java    From libreveris with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public CacheRequest put (URI           uri,
                         URLConnection conn)
    throws IOException
{
    URL url = uri.toURL();
    service.loadResource(url, null, service.getDefaultProgressWindow());

    return null;
}
 
Example 10
Source File: EndToEndTest.java    From selenium with Apache License 2.0 5 votes vote down vote up
private static Object[] createInMemory() throws MalformedURLException, URISyntaxException  {
  Tracer tracer = DefaultTestTracer.createTracer();
  EventBus bus = ZeroMqEventBus.create(
      new ZContext(),
      "inproc://end-to-end-pub",
      "inproc://end-to-end-sub",
      true);

  URI nodeUri = new URI("http://localhost:4444");
  CombinedHandler handler = new CombinedHandler();
  HttpClient.Factory clientFactory = new RoutableHttpClientFactory(
      nodeUri.toURL(),
      handler,
      HttpClient.Factory.createDefault());

  SessionMap sessions = new LocalSessionMap(tracer, bus);
  handler.addHandler(sessions);

  Distributor distributor = new LocalDistributor(tracer, bus, clientFactory, sessions, null);
  handler.addHandler(distributor);

  LocalNode node = LocalNode.builder(tracer, bus, nodeUri, nodeUri, null)
      .add(CAPS, createFactory(nodeUri))
      .build();
  handler.addHandler(node);
  distributor.add(node);

  Router router = new Router(tracer, clientFactory, sessions, distributor);

  Server<?> server = createServer(router);
  server.start();

  return new Object[] { server, clientFactory };
}
 
Example 11
Source File: BuiltinClassLoader.java    From Bytecoder with Apache License 2.0 5 votes vote down vote up
private URL createURL(URI uri) {
    URL url = null;
    try {
        url = uri.toURL();
    } catch (MalformedURLException | IllegalArgumentException e) {
    }
    return url;
}
 
Example 12
Source File: ConfigFile.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Creates a new {@code ConfigurationSpi} object from the specified
 * {@code URI}.
 *
 * @param uri the {@code URI}
 * @throws SecurityException if the {@code ConfigurationSpi} can not be
 *                           initialized
 * @throws NullPointerException if {@code uri} is null
 */
public Spi(URI uri) {
    // only load config from the specified URI
    try {
        url = uri.toURL();
        init();
    } catch (IOException ioe) {
        throw new SecurityException(ioe);
    }
}
 
Example 13
Source File: UrlResource.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * Create a new {@code UrlResource} based on the given URI object.
 * @param uri a URI
 * @throws MalformedURLException if the given URL path is not valid
 * @since 2.5
 */
public UrlResource(URI uri) throws MalformedURLException {
	Assert.notNull(uri, "URI must not be null");
	this.uri = uri;
	this.url = uri.toURL();
	this.cleanedUrl = getCleanedUrl(this.url, uri.toString());
}
 
Example 14
Source File: BotsImpl.java    From geoportal-server-harvester with Apache License 2.0 5 votes vote down vote up
private String assureRelative(String path) {
  try {
    URI uri = new URI(path);
    if (uri.isAbsolute()) {
      URL url = uri.toURL();
      path = String.format("/%s%s%s", url.getPath(), url.getQuery() != null ? "#" + url.getQuery() : "", url.getRef() != null ? "#" + url.getRef() : "").replaceAll("/+", "/");
    }
    return path;
  } catch (Exception ex) {
    return path;
  }
}
 
Example 15
Source File: ConfigFile.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Creates a new {@code ConfigurationSpi} object from the specified
 * {@code URI}.
 *
 * @param uri the {@code URI}
 * @throws SecurityException if the {@code ConfigurationSpi} can not be
 *                           initialized
 * @throws NullPointerException if {@code uri} is null
 */
public Spi(URI uri) {
    // only load config from the specified URI
    try {
        url = uri.toURL();
        init();
    } catch (IOException ioe) {
        throw new SecurityException(ioe);
    }
}
 
Example 16
Source File: TestUrlStreamHandler.java    From big-c with Apache License 2.0 4 votes vote down vote up
/**
 * Test opening and reading from an InputStream through a file:// URL.
 * 
 * @throws IOException
 * @throws URISyntaxException
 */
@Test
public void testFileUrls() throws IOException, URISyntaxException {
  // URLStreamHandler is already set in JVM by testDfsUrls() 
  Configuration conf = new HdfsConfiguration();

  // Locate the test temporary directory.
  if (!TEST_ROOT_DIR.exists()) {
    if (!TEST_ROOT_DIR.mkdirs())
      throw new IOException("Cannot create temporary directory: " + TEST_ROOT_DIR);
  }

  File tmpFile = new File(TEST_ROOT_DIR, "thefile");
  URI uri = tmpFile.toURI();

  FileSystem fs = FileSystem.get(uri, conf);

  try {
    byte[] fileContent = new byte[1024];
    for (int i = 0; i < fileContent.length; ++i)
      fileContent[i] = (byte) i;

    // First create the file through the FileSystem API
    OutputStream os = fs.create(new Path(uri.getPath()));
    os.write(fileContent);
    os.close();

    // Second, open and read the file content through the URL API.
    URL fileURL = uri.toURL();

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

    byte[] bytes = new byte[4096];
    assertEquals(1024, is.read(bytes));
    is.close();

    for (int i = 0; i < fileContent.length; ++i)
      assertEquals(fileContent[i], bytes[i]);

    // Cleanup: delete the file
    fs.delete(new Path(uri.getPath()), false);

  } finally {
    fs.close();
  }

}
 
Example 17
Source File: Jsapi10SpokenInput.java    From JVoiceXML with GNU Lesser General Public License v2.1 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public GrammarImplementation<?> loadGrammar(final URI uri,
        final GrammarType type) throws NoresourceError, IOException,
        UnsupportedFormatError {
    if (recognizer == null) {
        throw new NoresourceError("No recognizer available!");
    }

    if (type != GrammarType.JSGF) {
        throw new UnsupportedFormatError(
                "JSAPI 1.0 implementation supports only type "
                        + GrammarType.JSGF.getType());
    }

    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("loading grammar from URI '" + uri + "'");
    }
    final RuleGrammar grammar;
    try {
        final URL url = uri.toURL();
        InputStream input = url.openStream();
        final BufferedInputStream bufferedInput = new BufferedInputStream(
                input);
        bufferedInput.mark(Integer.MAX_VALUE);
        final ByteArrayOutputStream out = new ByteArrayOutputStream();
        final byte[] buffer = new byte[256];
        int read = 0;
        do {
            read = bufferedInput.read(buffer);
            if (read > 0) {
                out.write(buffer, 0, read);
            }
        } while (read >= 0);
        bufferedInput.reset();
        final InputStreamReader reader = new InputStreamReader(bufferedInput);
        grammar = recognizer.loadJSGF(reader);
    } catch (javax.speech.recognition.GrammarException ge) {
        throw new UnsupportedFormatError(ge.getMessage(), ge);
    }

    return new RuleGrammarImplementation(grammar, uri);
}
 
Example 18
Source File: TestUrlStreamHandler.java    From RDFS with Apache License 2.0 4 votes vote down vote up
/**
 * Test opening and reading from an InputStream through a file:// URL.
 * 
 * @throws IOException
 * @throws URISyntaxException
 */
public void testFileUrls() throws IOException, URISyntaxException {
  // URLStreamHandler is already set in JVM by testDfsUrls() 
  Configuration conf = new Configuration();

  // Locate the test temporary directory.
  File tmpDir = new File(conf.get("hadoop.tmp.dir"));
  if (!tmpDir.exists()) {
    if (!tmpDir.mkdirs())
      throw new IOException("Cannot create temporary directory: " + tmpDir);
  }

  File tmpFile = new File(tmpDir, "thefile");
  URI uri = tmpFile.toURI();

  FileSystem fs = FileSystem.get(uri, conf);

  try {
    byte[] fileContent = new byte[1024];
    for (int i = 0; i < fileContent.length; ++i)
      fileContent[i] = (byte) i;

    // First create the file through the FileSystem API
    OutputStream os = fs.create(new Path(uri.getPath()));
    os.write(fileContent);
    os.close();

    // Second, open and read the file content through the URL API.
    URL fileURL = uri.toURL();

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

    byte[] bytes = new byte[4096];
    assertEquals(1024, is.read(bytes));
    is.close();

    for (int i = 0; i < fileContent.length; ++i)
      assertEquals(fileContent[i], bytes[i]);

    // Cleanup: delete the file
    fs.delete(new Path(uri.getPath()), false);

  } finally {
    fs.close();
  }

}
 
Example 19
Source File: classloader.java    From gemfirexd-oss with Apache License 2.0 4 votes vote down vote up
private void class_jar(String command)
{
	ArrayList list = new ArrayList();
	gfsh.parseCommand(command, list);
	if (list.size() < 3) {
		gfsh.println("Error: must specify the jar paths");
		return;
	}
	
	String jarPaths = (String)list.get(2);
	if (jarPaths == null) {
		return;
	}
	jarPaths = jarPaths.trim();
	if (jarPaths.length() == 0) {
		return;
	}
	
	String pathSeparator = System.getProperty("path.separator");
	try {
		jarPaths = jarPaths.replace(pathSeparator.charAt(0), ',');
		String split[] = jarPaths.split(",");
		URL url[] = new URL[split.length];
		ArrayList<String> classNameList = new ArrayList();
		for (int i = 0; i < split.length; i++) {
			String path = split[i];
			File file = new File(path);
			URI uri = file.toURI();
			url[i] = uri.toURL();
			String[] classNames = ClassFinder.getAllClassNames(path);
			for (int j = 0; j < classNames.length; j++) {
				classNameList.add(classNames[j]);
			}
		}
		URLClassLoader cl = new URLClassLoader(url);
		for (String className : classNameList) {
			Class<?> cls = Class.forName(className, true, cl);
			
			// KeyType registration
			if (KeyType.class.isAssignableFrom(cls) && 
				cls.getSimpleName().matches(".*_v\\d++$") == false) 
			{
				Method method = cls.getMethod("getKeyType", (Class[])null);
				KeyType keyType = (KeyType)method.invoke(cls, (Object[])null);
				KeyTypeManager.registerKeyType(keyType);
			}
		}
     gfsh.println();
     gfsh.println("application classes successfully loaded from: " + jarPaths);
	} catch (Exception ex) {
		gfsh.println("Error: " + ex.getClass().getSimpleName() + " - " + ex.getMessage());
		if (gfsh.isDebug()) {
			ex.printStackTrace();
		}
	}
}
 
Example 20
Source File: UrlStreamResource.java    From super-cloudops with Apache License 2.0 3 votes vote down vote up
/**
 * Create a new {@code UrlResource} based on the given URI object.
 * 
 * @param uri
 *            a URI
 * @throws MalformedURLException
 *             if the given URL path is not valid
 * @since 2.5
 */
public UrlStreamResource(URI uri) throws MalformedURLException {
	Assert2.notNull(uri, "URI must not be null");
	this.uri = uri;
	this.url = uri.toURL();
	this.cleanedUrl = getCleanedUrl(this.url, uri.toString());
}