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

The following are Jave code examples for showing how to use toURL() of the java.net.URI 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: openjdk-jdk10   File: BuiltinClassLoader.java   View Source Code Vote up 6 votes
/**
 * Returns the URL to a resource in a module or {@code null} if not found.
 */
private URL findResource(ModuleReference mref, String name) throws IOException {
    URI u;
    if (System.getSecurityManager() == null) {
        u = moduleReaderFor(mref).find(name).orElse(null);
    } else {
        try {
            u = AccessController.doPrivileged(new PrivilegedExceptionAction<> () {
                @Override
                public URI run() throws IOException {
                    return moduleReaderFor(mref).find(name).orElse(null);
                }
            });
        } catch (PrivilegedActionException pae) {
            throw (IOException) pae.getCause();
        }
    }
    if (u != null) {
        try {
            return u.toURL();
        } catch (MalformedURLException | IllegalArgumentException e) { }
    }
    return null;
}
 
Example 2
Project: intellij-deps-ini4j   File: IniPreferencesFactory.java   View Source Code Vote up 6 votes
URL getResource(String location) throws IllegalArgumentException
{
    try
    {
        URI uri = new URI(location);
        URL url;

        if (uri.getScheme() == null)
        {
            url = Thread.currentThread().getContextClassLoader().getResource(location);
        }
        else
        {
            url = uri.toURL();
        }

        return url;
    }
    catch (Exception x)
    {
        throw new IllegalArgumentException(x);
    }
}
 
Example 3
Project: marathonv5   File: FetchDocListTask.java   View Source Code Vote up 6 votes
@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 4
Project: incubator-netbeans   File: JavaTypeProvider.java   View Source Code Vote up 5 votes
@CheckForNull
private static URL toURL(@NullAllowed final URI uri) {
    try {
        return uri == null ?
            null :
            uri.toURL();
    } catch (MalformedURLException ex) {
        LOGGER.log(
            Level.FINE,
            "Cannot convert URI to URL",    //NOI18N
            ex);
        return null;
    }
}
 
Example 5
Project: openjdk-jdk10   File: TestCache.java   View Source Code Vote up 5 votes
public synchronized CacheRequest put(URI uri, URLConnection conn)
throws IOException {
    System.out.println("put: " + uri);
    Thread.currentThread().dumpStack();
    URL url = uri.toURL();
    return new DeployCacheRequest(url, conn);

}
 
Example 6
Project: oneops   File: URLUtil.java   View Source Code Vote up 5 votes
/**
 * Checks the given string is valid url conforming to rfc3986.
 *
 * @param url url string
 * @return <code>true</code> if it conforming to the standard,
 * else return <code>false</code>
 */
public static boolean isValidURL(String url) {
    try {
        URI uri = new URI(url);
        uri.toURL();
        return true;
    } catch (Exception e) {
        logger.warn(url + " is not a valid url, error: " + e.getMessage());
        return false;
    }
}
 
Example 7
Project: incubator-netbeans   File: FileOwnerQuery.java   View Source Code Vote up 5 votes
/**
 * Find the project, if any, which "owns" the given URI.
 * @param uri the URI to the file (generally on disk); must be absolute and not opaque (though {@code jar}-protocol URIs are unwrapped as a convenience)
 * @return a project which contains it, or null if there is no known project containing it
 * @throws IllegalArgumentException if the URI is relative or opaque
 */
public static Project getOwner(URI uri) {
    try {
        URL url = uri.toURL();
        if (FileUtil.isArchiveArtifact(url)) {
            url = FileUtil.getArchiveFile(url);
            if (url != null) {
                uri = url.toURI();
            }
        }
    } catch (MalformedURLException | URISyntaxException e) {
        LOG.log(Level.INFO, null, e);
    }
    if (!uri.isAbsolute() || uri.isOpaque()) {
        throw new IllegalArgumentException("Bad URI: " + uri); // NOI18N
    }
    for (FileOwnerQueryImplementation q : getInstances()) {
        Project p = q.getOwner(uri);
        if (p != null) {
            if (LOG.isLoggable(Level.FINE)) {
                LOG.log(Level.FINE, "getOwner({0}) -> {1} from {2}", new Object[] {uri, p, q});
            }
            return p == UNOWNED ? null : p;
        }
    }
    LOG.log(Level.FINE, "getOwner({0}) -> nil", uri);
    return null;
}
 
Example 8
Project: incubator-netbeans   File: ProjectClassPathModifier.java   View Source Code Vote up 5 votes
private static Collection<URL> toURLs(Collection<URI> libs)  {
    URL[] urls = new URL[libs.size()];
    int index = 0;
    for (URI u : libs) {
        try {
            urls[index++] = u.toURL();
        } catch (MalformedURLException ex) {
            return Collections.emptyList();
        }
    }
    return Arrays.asList(urls);
}
 
Example 9
Project: microbean-helm   File: TestURLChartLoader.java   View Source Code Vote up 5 votes
@Before
public void setUp() throws IOException {
  // Chart is arbitrary, but it does have subcharts in it, which exercise some tricky logic
  final URI uri = URI.create("https://kubernetes-charts.storage.googleapis.com/wordpress-0.6.6.tgz");
  assertNotNull(uri);
  final URL url = uri.toURL();
  assertNotNull(url);
  final URLConnection connection = url.openConnection();
  assertNotNull(connection);
  connection.addRequestProperty("Accept-Encoding", "gzip");
  connection.connect();
  assertEquals("application/x-tar", connection.getContentType());
  this.remoteUrl = url;
}
 
Example 10
Project: jaffa-framework   File: PatternGenerator.java   View Source Code Vote up 5 votes
/**
 * Creates a mapping of data needed during code generation.  All domain
 * models passed in will be mapped
 * to their table names.  All fields for each domain model will be mapped
 * to their column names.
 *
 * @param dataSet the set of xml files to create the data mapping from
 */
public void setData(List<File> dataSet)
        throws IOException, PatternGeneratorException, SAXException,
               ParserConfigurationException {
    for (File file : dataSet) {

        // get the root object
        URI uri = file.toURI();
        URL url = uri.toURL();
        DatabaseTableInformation tableData = extractModelData(url);

        // get all values in upper case
        String domainObject = tableData.getDomainModelName().toUpperCase();
        String tableName = tableData.getTableName().toUpperCase();
        tableNames.put(domainObject, tableName);

        // add each field column in this domain object
        if (!columnNames.containsKey(domainObject)) {
            columnNames.put(domainObject, new HashMap<String, String>());
        }
        for (Map.Entry<String, String> entry : tableData.getFieldToColumnName().entrySet()) {
            String fieldName = entry.getKey().toUpperCase();
            String columnName = entry.getValue().toUpperCase();
            columnNames.get(domainObject).put(fieldName, columnName);
        }
    }
}
 
Example 11
Project: ZXingAndroidExt   File: HttpHelper.java   View Source Code Vote up 5 votes
public static URI unredirect(URI uri) throws IOException {
    if (!REDIRECTOR_DOMAINS.contains(uri.getHost())) {
        return uri;
    }
    URL url = uri.toURL();
    HttpURLConnection connection = safelyOpenConnection(url);
    connection.setInstanceFollowRedirects(false);
    connection.setDoInput(false);
    connection.setRequestMethod("HEAD");
    connection.setRequestProperty("User-Agent", "ZXing (Android)");
    try {
        int responseCode = safelyConnect(connection);
        switch (responseCode) {
            case HttpURLConnection.HTTP_MULT_CHOICE:
            case HttpURLConnection.HTTP_MOVED_PERM:
            case HttpURLConnection.HTTP_MOVED_TEMP:
            case HttpURLConnection.HTTP_SEE_OTHER:
            case 307: // No constant for 307 Temporary Redirect ?
                String location = connection.getHeaderField("Location");
                if (location != null) {
                    try {
                        return new URI(location);
                    } catch (URISyntaxException e) {
                        // nevermind
                    }
                }
        }
        return uri;
    } finally {
        connection.disconnect();
    }
}
 
Example 12
Project: OCast-Java   File: DialServiceParser.java   View Source Code Vote up 5 votes
private DialService readService(XmlPullParser parser) throws DialException, IOException, XmlPullParserException {
    DialService service;
    String name = null;
    DialService.State state = null;
    URL absoluteLink = null;
    AdditionalData additionalData = null;

    parser.require(XmlPullParser.START_TAG, "urn:dial-multiscreen-org:schemas:dial", TAG_SERVICE);
    while (parser.next() != XmlPullParser.END_TAG) {
        if (parser.getEventType() != XmlPullParser.START_TAG) {
            continue;
        }
        String tag = parser.getName();
        if (tag.equals(TAG_ADDITIONAL_DATA)) {
            additionalData = readAdditionalData(parser);
        } else if (tag.equals(TAG_NAME)) {
            name = DialParserUtils.readTextValue(parser, TAG_NAME, null);
        } else if (tag.equals(TAG_STATE)) {
            state = readState(parser);
        } else if (tag.equals(TAG_LINK)) {
            URI link = readLink(parser);
            if(link != null && link.isAbsolute()) {
                absoluteLink = link.toURL();
            } else {
                try {
                    // not confident about this being the right way to do it
                    absoluteLink = new URI(baseUrl.toString() + "/").resolve(link).toURL();
                } catch (URISyntaxException e) {
                    throw new DialException(e);
                }
            }
        } else {
            DialParserUtils.skip(parser);
        }
    }

    service = new DialService(baseUrl, name, state, absoluteLink, additionalData);
    checkService(service);
    return service;
}
 
Example 13
Project: microbean-helm   File: TestCharts.java   View Source Code Vote up 5 votes
@Before
public void setUp() throws IOException {
  final URI uri = URI.create("https://kubernetes-charts.storage.googleapis.com/redis-0.10.1.tgz");
  assertNotNull(uri);
  final URL url = uri.toURL();
  assertNotNull(url);
  final URLConnection connection = url.openConnection();
  assertNotNull(connection);
  connection.addRequestProperty("Accept-Encoding", "gzip");
  connection.connect();
  assertEquals("application/x-tar", connection.getContentType());
  this.redisUrl = url;
}
 
Example 14
Project: hadoop   File: StandbyCheckpointer.java   View Source Code Vote up 4 votes
private URL getHttpAddress(Configuration conf) throws IOException {
  final String scheme = DFSUtil.getHttpClientScheme(conf);
  String defaultHost = NameNode.getServiceAddress(conf, true).getHostName();
  URI addr = DFSUtil.getInfoServerWithDefaultHost(defaultHost, conf, scheme);
  return addr.toURL();
}
 
Example 15
Project: hadoop   File: TestUrlStreamHandler.java   View Source Code Vote up 4 votes
/**
 * 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 16
Project: SimpleAudio   File: AbstractAudio.java   View Source Code Vote up 4 votes
/**
 * @param uri the resource as {@linkplain URI}
 * @throws AudioException if something is wrong with the resource
 * @since 1.0.0
 */
public AbstractAudio(URI uri) throws AudioException {
	
	try {
		
		this.resource = uri.toURL();
		this.fileFormat = FileFormat.getFormatByName(this.resource.toExternalForm());
		
		if(this.fileFormat == null) {
			
			throw new AudioException("Unsupported file format!");
		}
		
	} catch(Exception exception) {
		
		throw new AudioException(exception);
	}
}
 
Example 17
Project: gemoc-studio   File: ResourceHelpers.java   View Source Code Vote up 4 votes
static public URL IResourceToURL(IResource resource) throws MalformedURLException {
	URI locationURI = resource.getLocationURI();
	return locationURI.toURL();		
}
 
Example 18
Project: boutique-de-jus   File: BoutiqueDeJusWebServer.java   View Source Code Vote up 3 votes
/**
 * Initializes the jetty server from XML configuratoin
 *
 * @param configFile
 *         jetty configuration file. The file must configure a server, otherwise the method will fail
 * @param props
 *
 * @return the configured server instace
 *
 * @throws Exception
 */
public static Server loadServerFromConfigFile(URI configFile, Map<String, String> props) throws Exception {

    XmlConfiguration configuration = new XmlConfiguration(configFile.toURL());
    configuration.getProperties().putAll(props);

    return (Server) configuration.configure();
}
 
Example 19
Project: freecol   File: FAFileResource.java   View Source Code Vote up 2 votes
/**
 * Do not use directly.
 *
 * @param resourceLocator The {@code URI} used when loading this
 *     resource.
 * @exception IOException if FAFile can not be opened.
 */
public FAFileResource(URI resourceLocator) throws IOException {
    super(resourceLocator);
    URL url = resourceLocator.toURL();
    FAFile = new FAFile(url.openStream());
}
 
Example 20
Project: FreeCol   File: VideoResource.java   View Source Code Vote up 2 votes
/**
 * Do not use directly.
 *
 * @param resourceLocator The {@code URI} used when loading this
 *     resource.
 * @exception IOException if the URI is malformed.
 */
public VideoResource(URI resourceLocator) throws IOException {
    super(resourceLocator);
    
    this.video = new Video(resourceLocator.toURL());
}