Example usage for java.net URI toURL

List of usage examples for java.net URI toURL

Introduction

In this page you can find the example usage for java.net URI toURL.

Prototype

public URL toURL() throws MalformedURLException 

Source Link

Document

Constructs a URL from this URI.

Usage

From source file:org.geoserver.web.wicket.FileExistsValidator.java

@Override
protected void onValidate(IValidatable validatable) {
    String uriSpec = Converters.convert(validatable.getValue(), String.class);

    // Make sure we are dealing with a local path
    try {//from   w  ww .j a  v a 2s. c o m
        URI uri = new URI(uriSpec);
        if (uri.getScheme() != null && !"file".equals(uri.getScheme())) {
            if (delegate != null) {
                delegate.validate(validatable);
                InputStream is = null;
                try {
                    URLConnection connection = uri.toURL().openConnection();
                    connection.setConnectTimeout(10000);
                    is = connection.getInputStream();
                } catch (Exception e) {
                    error(validatable, "FileExistsValidator.unreachable",
                            Collections.singletonMap("file", uriSpec));
                } finally {
                    IOUtils.closeQuietly(is);
                }
            }
            return;
        } else {
            // ok, strip away the scheme and just get to the path
            String path = uri.getPath();
            if (path != null && new File(path).exists()) {
                return;
            }
        }
    } catch (URISyntaxException e) {
        // may be a windows path, move on               
    }

    // local to data dir?
    File relFile = GeoserverDataDirectory.findDataFile(uriSpec);
    if (relFile == null || !relFile.exists()) {
        error(validatable, "FileExistsValidator.fileNotFoundError", Collections.singletonMap("file", uriSpec));
    }
}

From source file:org.codice.alliance.imaging.chip.actionprovider.ImagingChipActionProvider.java

private static Optional<URL> getChippingUrl(Metacard metacard) {
    // canHandle has already been checked at this point, so no need to verify isPresent
    final URI derivedResourceUri = getOriginalDerivedResourceUri(metacard).get();
    if (canBeChippedLocally(derivedResourceUri)) {
        final String defaultChippingUrlString = String.format("%s%s?id=%s&source=%s",
                SystemBaseUrl.EXTERNAL.getBaseUrl(), PATH, metacard.getId(), metacard.getSourceId());
        try {//from   w  ww  . j a v  a  2  s. c  o  m
            return Optional.of(new URL(defaultChippingUrlString));
        } catch (MalformedURLException e) {
            // This should never happen.
        }
    } else {
        // If the resource.derived-uri attribute value matches the usual Alliance download URL format
        // ("[protocol]://[host]:[port]/[services name]/catalog/sources/[source id]/[metacard
        // id]?transform=resource&qualifier=[original or overview]"), assume that there is a
        // chipping URL that can be constructed from the scheme, host, port, source, and id of
        // the value. This allows the {@value TITLE} Action to link directly to the remote
        // system if the derived resource is from another Alliance instance.
        try {
            final URL derivedResourceUrl = derivedResourceUri.toURL();

            final String host = derivedResourceUrl.getHost(); // {@code null} if the host is undefined
            final int port = derivedResourceUrl.getPort(); // -1 if the port is not set
            final String path = derivedResourceUrl.getPath(); // an empty string if one does not exist
            final String query = derivedResourceUrl.getQuery(); // <CODE>null</CODE> if one does not exist
            final String expectedQuery = String.format("transform=resource&qualifier=%s", ORIGINAL_QUALIFIER);
            if (!StringUtils.isEmpty(host) && port != -1
                    && ALLIANCE_DOWNLOAD_RESOURCE_PATH_PATTERN.matcher(path).matches()
                    && StringUtils.equals(query, expectedQuery)) {
                final String[] paths = path.split("/");
                final String source = paths[4];
                final String id = paths[5];

                final String chippingPathString = String.format("%s?id=%s&source=%s", PATH, id, source);
                try {
                    return Optional
                            .of(new URL(derivedResourceUrl.getProtocol(), host, port, chippingPathString));
                } catch (MalformedURLException e) {
                    // This should probably never happen because the parts used to construct the URL have
                    // been validated.
                }
            } else {
                // Unable to construct a remote chipping URL because the original resource.derived-uri
                // does not match the known Alliance format.
            }
        } catch (MalformedURLException e) {
            // Unable to cast derivedResourceUri to a URL, which means that the resource still may be
            // able to be chipped locally but is not yet supported by the canBeChippedLocally method.
        }
    }

    LOGGER.debug(
            "Unable to construct a chipping URL for NITF image metacard id={}, source id={}, resource-uri={}. Not displaying the Chip Image Action.",
            metacard.getId(), metacard.getResourceURI(), metacard.getSourceId());
    return Optional.empty();
}

From source file:org.apache.juddi.v3.client.mapping.wsdl.WSDLLocatorImpl.java

/**
 * Internal method to normalize the importUrl. The importLocation can be
 * relative to the parentLocation./*from  ww w.  j a  va  2s . c o m*/
 *
 * @param parentLocation
 * @param importLocation
 * @return a url
 */
protected URL constructImportUrl(String parentLocation, String importLocation) {
    URL importUrl = null;
    try {
        URI importLocationURI = new URI(importLocation);
        if (importLocationURI.getScheme() != null || parentLocation == null) {
            importUrl = importLocationURI.toURL();
        } else {
            String parentDir = parentLocation.substring(0, parentLocation.lastIndexOf("/"));
            URI uri = new URI(parentDir + "/" + importLocation);
            importUrl = uri.normalize().toURL();
        }
    } catch (Exception e) {
        log.error(e.getMessage(), e);
    }
    if (importUrl != null) {
        log.debug("importUrl: " + importUrl.toExternalForm());
    } else {
        log.error("importUrl is null!");
    }
    return importUrl;
}

From source file:ca.simplegames.micro.utils.UrlResource.java

/**
 * Create a new UrlResource./*from  w  ww  . ja  va  2  s  .  c  om*/
 *
 * @param uri a URI
 * @throws MalformedURLException if the given URL path is not valid
 */
public UrlResource(URI uri) throws MalformedURLException {
    Assert.notNull(uri, "URI must not be null");
    this.url = uri.toURL();
    this.cleanedUrl = getCleanedUrl(this.url, uri.toString());
    this.uri = uri;
}

From source file:org.datavec.api.records.reader.impl.jackson.JacksonRecordReader.java

@Override
public List<Record> loadFromMetaData(List<RecordMetaData> recordMetaDatas) throws IOException {

    List<Record> out = new ArrayList<>();
    for (RecordMetaData metaData : recordMetaDatas) {
        URI uri = metaData.getURI();

        String fileAsString;/*from   w ww  . j  av a 2s .c o  m*/
        try {
            fileAsString = FileUtils.readFileToString(new File(uri.toURL().getFile()));
        } catch (IOException e) {
            throw new RuntimeException("Error reading URI file", e);
        }

        List<Writable> writables = readValues(uri, fileAsString);
        out.add(new org.datavec.api.records.impl.Record(writables, metaData));
    }

    return out;
}

From source file:org.geoserver.catalog.ResourcePoolTest.java

@Test
public void testSEStyleWithRelativePath() throws IOException {
    StyleInfo si = getCatalog().getStyleByName("relative");

    assertNotNull(si);// ww w  .j  a v  a2s .  com
    Style style = si.getStyle();
    PolygonSymbolizer ps = (PolygonSymbolizer) style.featureTypeStyles().get(0).rules().get(0).symbolizers()
            .get(0);
    ExternalGraphic eg = (ExternalGraphic) ps.getFill().getGraphicFill().graphicalSymbols().get(0);
    URI uri = eg.getOnlineResource().getLinkage();
    assertNotNull(uri);
    File actual = DataUtilities.urlToFile(uri.toURL()).getCanonicalFile();
    assertEquals(rockFillSymbolFile, actual);
}

From source file:org.bndtools.rt.repository.client.RemoteRestRepository.java

@Override
public SortedSet<Version> versions(String bsn) throws Exception {
    SortedSet<Version> result = new TreeSet<Version>();

    URI requestUri = new URI(baseUri.getScheme(), baseUri.getUserInfo(), baseUri.getHost(), baseUri.getPort(),
            baseUri.getPath() + "/bundles/" + bsn, null, null);
    InputStream stream = requestUri.toURL().openStream();

    try {/*from www. jav  a 2 s .c  o  m*/
        Iterable<JSONObject> iterable = parseJSONObjectList(new InputStreamReader(stream));
        for (JSONObject node : iterable) {
            Object versionNode = node.get("version");
            if (versionNode == null || !(versionNode instanceof String))
                throw new Exception("Missing or invalid 'version' field.");
            Version version = new Version((String) versionNode);
            result.add(version);
        }
    } finally {
        IO.close(stream);
    }

    return result;
}

From source file:at.diamonddogs.data.dataobjects.WebRequest.java

@SuppressWarnings("javadoc")
public void setUrl(URI uri) {
    try {/* ww w .  jav a2  s  .  com*/
        this.url = uri.toURL();
    } catch (Throwable t) {
        LOGGER.warn("Invalid url:" + url, t);
        this.url = null;
    }
}

From source file:org.bndtools.rt.repository.client.RemoteRestRepository.java

@Override
public List<String> list(String pattern) throws Exception {
    LinkedList<String> result = new LinkedList<String>();

    URI requestUri = new URI(baseUri.getScheme(), baseUri.getUserInfo(), baseUri.getHost(), baseUri.getPort(),
            baseUri.getPath() + "/bundles", "pattern=" + pattern, null);
    InputStream stream = requestUri.toURL().openStream();
    try {/*from  w w  w.  java 2  s  .c  om*/
        Iterable<JSONObject> iterable = parseJSONObjectList(new InputStreamReader(stream));
        for (JSONObject node : iterable) {
            Object bsnNode = node.get("bsn");
            if (bsnNode == null || !(bsnNode instanceof String))
                throw new Exception("Missing or invalid 'bsn' field.");
            result.add((String) bsnNode);
        }
    } finally {
        IO.close(stream);
    }

    return result;
}

From source file:org.dita.dost.ant.PluginInstallTask.java

public void setPluginFile(final String pluginFile) {
    try {// w ww .  j  a  va  2  s  .  c o m
        this.pluginFile = Paths.get(pluginFile);
    } catch (InvalidPathException e) {
        // Ignore
    }
    try {
        final URI uri = new URI(pluginFile);
        if (uri.isAbsolute()) {
            this.pluginUrl = uri.toURL();
        }
    } catch (MalformedURLException | URISyntaxException e) {
        // Ignore
    }
    if (pluginFile.contains("@")) {
        final String[] tokens = pluginFile.split("@");
        pluginName = tokens[0];
        pluginVersion = new SemVerMatch(tokens[1]);
    } else {
        pluginName = pluginFile;
        pluginVersion = null;
    }
}