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:edu.mayo.informatics.lexgrid.convert.directConversions.UMLSHistoryFileToSQL.java

public static void validateFile(URI fileLocation, String token, boolean validateLevel) throws Exception {

    BufferedReader reader = null;
    int lineNo = 1;
    if (token == null) {
        token = token_;// ww w. ja v a 2 s .  c om
    }

    // test MRCUI.RRF
    URI mrCUIFile = fileLocation.resolve("MRCUI.RRF");
    if (mrCUIFile == null) {

        throw new ConnectionFailure("Did not find the expected MRCUI.RRF file in the location provided.");
    }
    if (mrCUIFile.getScheme().equals("file")) {

        new FileReader(new File(mrCUIFile)).close();
    } else {
        new InputStreamReader(mrCUIFile.toURL().openConnection().getInputStream()).close();
    }

    try {
        reader = getReader(mrCUIFile);
        String line = reader.readLine();
        lineNo = 1;
        boolean notAMonth = false;
        while (line != null) {

            if (line.startsWith("#") || line.length() == 0) {
                line = reader.readLine();
                continue;
            }

            if (validateLevel && lineNo > 10) {
                break;
            }

            List<String> elements = deTokenizeString(line, token_);

            if (elements.size() != 7) {
                throw new Exception(
                        "MRCUI.RRF " + "(" + "Line:" + lineNo + ")" + " is not in the required format.");
            }
            if (!elements.get(0).toLowerCase().startsWith("c")) {
                throw new Exception("MRCUI.RRF " + "(" + "Line:" + lineNo + "): " + "The concept("
                        + elements.get(0) + ") is not in the required format.");
            }

            try {
                String month = elements.get(1).substring(4);
                int i = Integer.parseInt(month);
                if (i < 0 || i > 12) {
                    throw new Exception();
                } else {
                    notAMonth = false;
                }
            } catch (Exception e) {
                notAMonth = true;
            }

            if (!elements.get(1).endsWith("AA") && !elements.get(1).endsWith("AB")
                    && !elements.get(1).endsWith("AC") && !elements.get(1).endsWith("AD") && notAMonth) {
                throw new Exception("MRCUI.RRF " + "(" + "Line:" + lineNo + "): " + "The Release id ("
                        + elements.get(1) + ") is not in the required format.");
            }
            lineNo++;
            line = reader.readLine();
        }

    } catch (MalformedURLException e1) {
        e1.printStackTrace();
    } catch (IOException e1) {
        e1.printStackTrace();
    } finally {
        reader.close();
    }

    // test MRCONSO.RRF
    URI mrCONSOFile = fileLocation.resolve("MRCONSO.RRF");
    if (mrCONSOFile == null) {

        throw new ConnectionFailure("Did not find the expected MRCONSO.RRF file in the location provided.");
    }
    if (mrCONSOFile.getScheme().equals("file")) {

        new FileReader(new File(mrCONSOFile)).close();
    } else {
        new InputStreamReader(mrCONSOFile.toURL().openConnection().getInputStream()).close();
    }

    try {
        reader = getReader(mrCONSOFile);
        String line = reader.readLine();
        lineNo = 1;
        while (line != null) {

            if (line.startsWith("#") || line.length() == 0) {
                line = reader.readLine();
                continue;
            }

            if (validateLevel && lineNo > 10) {
                break;
            }

            List<String> elements = deTokenizeString(line, token_);

            if (elements.size() != 18) {
                throw new Exception(
                        "MRCONSO.RRF " + "(" + "Line:" + lineNo + ")" + " is not in the required format.");
            }

            lineNo++;
            line = reader.readLine();
        }

    } catch (MalformedURLException e1) {
        e1.printStackTrace();
    } catch (IOException e1) {
        e1.printStackTrace();
    } finally {
        reader.close();
    }
}

From source file:org.apache.taverna.databundle.DataBundles.java

/**
 * Deeply resolve a {@link Path} to JVM objects.
 * <p>/* w ww.j a v a 2 s .c  o m*/
 * This method is intended mainly for presentational uses 
 * with a particular input/output port from
 * {@link #getPorts(Path)} or {@link #getPort(Path, String)}.
 * <p>
 * Note that as all lists are resolved deeply (including lists of lists)
 * and when using options {@link ResolveOptions#STRING} or {@link ResolveOptions#BYTES}
 * the full content of the values are read into memory, this 
 * method can be time-consuming.
 * <p>
 * If the path is <code>null</code> or {@link #isMissing(Path)},
 * <code>null</code> is returned, unless the option
 * {@link ResolveOptions#REPLACE_NULL} is specified, which would return the
 * empty String "".
 * <p>
 * If the path {@link #isValue(Path)} and the option
 * {@link ResolveOptions#STRING} is specified, its
 * {@link #getStringValue(Path)} is returned (assuming an UTF-8 encoding).
 * NOTE: Binary formats (e.g. PNG) will NOT be represented correctly read as
 * UTF-8 String and should instead be read directly with
 * {@link Files#newInputStream(Path, java.nio.file.OpenOption...)}. Note
 * that this could consume a large amount of memory as no size checks are
 * performed.
 * <p>
 * If the option {@link ResolveOptions#URI} is specified, all non-missing 
 * non-error leaf values are resolved as a {@link URI}. If the path is a 
 * {@link #isReference(Path)} the URI will be the reference from 
 * {@link #getReference(Path)}, otherwise the URI will  
 * identify a {@link Path} within the current {@link Bundle}.
 * <p>
 * If the path {@link #isValue(Path)} and the option
 * {@link ResolveOptions#BYTES} is specified, the complete content is returned as
 * a <code>byte[]</code>. Note that this could consume a large amount of memory
 * as no size checks are performed.
 * <p>
 * If the path {@link #isError(Path)}, the corresponding
 * {@link ErrorDocument} is returned, except when the option
 * {@link ResolveOptions#REPLACE_ERRORS} is specified, which means errors are
 * returned as <code>null</code> (or <code>""</code> if {@link ResolveOptions#REPLACE_NULL} is also specified).
 * <p>
 * If the path {@link #isReference(Path)} and the option 
 * {@link ResolveOptions#URI} is <strong>not</strong> set, 
 * either a {@link File} or a {@link URL} is returned, 
 * depending on its protocol. If the reference protocol has no
 * corresponding {@link URLStreamHandler}, a {@link URI} is returned
 * instead. 
 * <p>
 * If the path {@link #isList(Path)}, a {@link List} is returned
 * corresponding to resolving the paths from {@link #getList(Path)}. using
 * this method with the same options.
 * <p>
 * If none of the above, the {@link Path} itself is returned. This is 
 * thus the default for non-reference non-error leaf values if neither 
 * {@link ResolveOptions#STRING}, {@link ResolveOptions#BYTES} or
 * {@link ResolveOptions#URI} are specified.
 * To force returning of {@link Path}s for all non-missing leaf values, specify
 * {@link ResolveOptions#PATH};
 * 
 * @param path
 *            Data bundle path to resolve
 * @param options
 *            Resolve options
 * @return <code>null</code>, a {@link String}, {@link ErrorDocument},
 *         {@link URL}, {@link File}, {@link Path} or {@link List}
 *         (containing any of these) depending on the path type and the options.
 * @throws IOException
 *             If the path (or any of the path in a contained list) can't be
 *             accessed
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
public static Object resolve(Path path, ResolveOptions... options) throws IOException {
    EnumSet<ResolveOptions> opt;
    if (options.length == 0) {
        opt = EnumSet.of(ResolveOptions.DEFAULT); // no-op
    } else {
        opt = EnumSet.of(ResolveOptions.DEFAULT, options);
    }

    if (opt.contains(ResolveOptions.BYTES) && opt.contains(ResolveOptions.STRING)) {
        throw new IllegalArgumentException("Incompatible options: BYTES and STRING");
    }
    if (opt.contains(ResolveOptions.BYTES) && opt.contains(ResolveOptions.PATH)) {
        throw new IllegalArgumentException("Incompatible options: BYTES and PATH");
    }
    if (opt.contains(ResolveOptions.BYTES) && opt.contains(ResolveOptions.URI)) {
        throw new IllegalArgumentException("Incompatible options: BYTES and URI");
    }
    if (opt.contains(ResolveOptions.STRING) && opt.contains(ResolveOptions.PATH)) {
        throw new IllegalArgumentException("Incompatible options: STRING and PATH");
    }
    if (opt.contains(ResolveOptions.STRING) && opt.contains(ResolveOptions.URI)) {
        throw new IllegalArgumentException("Incompatible options: STRING and URI");
    }
    if (opt.contains(ResolveOptions.PATH) && opt.contains(ResolveOptions.URI)) {
        throw new IllegalArgumentException("Incompatible options: PATH and URI");
    }

    if (path == null || isMissing(path)) {
        if (!opt.contains(ResolveOptions.REPLACE_NULL)) {
            return null;
        }
        if (opt.contains(ResolveOptions.BYTES)) {
            return new byte[0];
        }
        if (opt.contains(ResolveOptions.PATH)) {
            return path;
        }
        if (opt.contains(ResolveOptions.URI)) {
            return path.toUri();
        }
        // STRING and DEFAULT
        return "";

    }

    if (isList(path)) {
        List<Path> list = getList(path);
        List<Object> objectList = new ArrayList<Object>(list.size());
        for (Path pathElement : list) {
            objectList.add(resolve(pathElement, options));
        }
        return objectList;
    }
    if (opt.contains(ResolveOptions.PATH)) {
        return path;
    }
    if (isError(path)) {
        if (opt.contains(ResolveOptions.REPLACE_ERRORS)) {
            return opt.contains(ResolveOptions.REPLACE_NULL) ? "" : null;
        }
        return getError(path);
    }
    if (opt.contains(ResolveOptions.URI)) {
        if (isReference(path)) {
            return getReference(path);
        } else {
            return path.toUri();
        }
    }
    if (isReference(path)) {
        URI reference = getReference(path);
        String scheme = reference.getScheme();
        if ("file".equals(scheme)) {
            return new File(reference);
        } else {
            try {
                return reference.toURL();
            } catch (IllegalArgumentException | MalformedURLException e) {
                return reference;
            }
        }
    }
    if (isValue(path)) {
        if (opt.contains(ResolveOptions.BYTES)) {
            return Files.readAllBytes(path);
        }
        if (opt.contains(ResolveOptions.STRING)) {
            return getStringValue(path);
        }
    }
    // Fall-back - return Path as-is
    return path;
}

From source file:org.ambraproject.util.TextUtils.java

/**
 * @param url A URL// www  .j  a  va  2 s . com
 * @return whether the url is a valid address
 */
public static boolean verifyUrl(final String url) {
    try {
        URI u = new URI(url);

        // To see if we can get a valid url or if we get an exception
        u.toURL();
        return true;
    } catch (Exception e) {
        return false;
    }
}

From source file:com.bosch.iot.things.example.historian.Collector.java

private static IntegrationClient setupClient() throws RuntimeException, NumberFormatException {
    Properties props = new Properties(System.getProperties());
    try {// w  w w.ja  va 2s  .  c om
        if (new File("config.properties").exists()) {
            props.load(new FileReader("config.properties"));
        } else {
            InputStream i = Thread.currentThread().getContextClassLoader()
                    .getResourceAsStream("config.properties");
            props.load(i);
            i.close();
        }
        LOGGER.info("Used integration client config: {}", props);
    } catch (IOException ex) {
        throw new RuntimeException(ex);
    }

    String clientId = props.getProperty("clientId");
    String apiToken = props.getProperty("apiToken");
    String defaultNamespace = props.getProperty("defaultNamespace");
    URI keystoreUri;
    try {
        keystoreUri = Collector.class.getResource("/CRClient.jks").toURI();
    } catch (URISyntaxException ex) {
        throw new RuntimeException(ex);
    }

    String keystorePassword = props.getProperty("keyStorePassword");
    String keyAlias = props.getProperty("keyAlias");
    String keyAliasPassword = props.getProperty("keyAliasPassword");
    String proxyHost = props.getProperty("http.proxyHost");
    String proxyPort = props.getProperty("http.proxyPort");

    AuthenticationConfiguration authenticationConfiguration;
    try {
        authenticationConfiguration = PublicKeyAuthenticationConfiguration.newBuilder().clientId(clientId)
                .keyStoreLocation(keystoreUri.toURL()).keyStorePassword(keystorePassword).alias(keyAlias)
                .aliasPassword(keyAliasPassword).build();
    } catch (MalformedURLException ex) {
        throw new RuntimeException(ex);
    }

    IntegrationClientConfiguration.OptionalConfigSettable configSettable = IntegrationClientConfiguration
            .newBuilder().apiToken(apiToken).defaultNamespace(defaultNamespace)
            .authenticationConfiguration(authenticationConfiguration)
            .providerConfiguration(MessagingProviders.thingsWebsocketProviderBuilder().build());

    if (proxyHost != null && proxyPort != null) {
        configSettable = configSettable.proxyConfiguration(ProxyConfiguration.newBuilder().proxyHost(proxyHost)
                .proxyPort(Integer.parseInt(proxyPort)).build());
    }

    IntegrationClient client = IntegrationClientImpl.newInstance(configSettable.build());

    return client;
}

From source file:org.apache.synapse.config.SynapseConfigUtils.java

public static InputSource getInputSourceFormURI(URI uri) {

    if (uri == null) {
        if (log.isDebugEnabled()) {
            log.debug("Can not create a URL from 'null' ");
        }//  w ww  . ja va 2 s.  c o m
        return null;
    }
    try {
        URL url = uri.toURL();
        String protocol = url.getProtocol();
        String path = url.getPath();
        if (protocol == null || "".equals(protocol)) {
            url = new URL("file:" + path);
        }
        URLConnection connection = getURLConnection(url);
        if (connection == null) {
            if (log.isDebugEnabled()) {
                log.debug("Cannot create a URLConnection for given URL : " + uri);
            }
            return null;
        }
        BufferedInputStream urlInStream = new BufferedInputStream(connection.getInputStream());
        return new InputSource(urlInStream);
    } catch (MalformedURLException e) {
        handleException("Invalid URL ' " + uri + " '", e);
    } catch (IOException e) {
        handleException("IOError when getting a stream from given url : " + uri, e);
    }
    return null;
}

From source file:org.apache.ode.axis2.util.Axis2UriResolver.java

public InputSource resolveEntity(String targetNamespace, String schemaLocation, String baseUri) {
    if (LOG.isDebugEnabled()) {
        LOG.debug("resolveEntity: targetNamespace=" + targetNamespace + " schemaLocation=" + schemaLocation
                + " baseUri=" + baseUri);
    }/*from   ww w  .  ja  v a2  s .  c  o  m*/
    InputStream is;
    try {
        URI base = new URI(baseUri);
        URI uri = base.resolve(schemaLocation);
        is = uri.toURL().openStream();
        if (is == null) {
            LOG.error("Exception resolving entity: schemaLocation=" + schemaLocation + " baseUri=" + baseUri);
            return null;
        }
        InputSource source = new InputSource(is);
        source.setSystemId(uri.toString());
        source.setPublicId(schemaLocation);
        return new InputSource(is);
    } catch (Exception e) {
        LOG.error("Exception resolving entity: schemaLocation=" + schemaLocation + " baseUri=" + baseUri, e);
        return null;
    }
}

From source file:crawlercommons.fetcher.file.SimpleFileFetcherTest.java

@Test
public void testEmptyFile() throws Exception {
    URI uri = new File("src/test/resources/empty-file").toURI();
    String url = uri.toURL().toExternalForm();

    SimpleFileFetcher fetcher = new SimpleFileFetcher();
    FetchedResult result = fetcher.get(url);
    Assert.assertEquals(HttpStatus.SC_OK, result.getStatusCode());
    Assert.assertEquals(0, result.getContentLength());
    Assert.assertEquals(0, result.getResponseRate());
}

From source file:com.legstar.jaxb.plugin.EnumCases.java

/**
 * Check Get Set methods on enumerations.
 * @throws Exception if test fails// ww w.j a  v a2 s. co m
 */
public void testGetSetEnum() throws Exception {
    /* Load the generated class */
    URI loc = GEN_SRC_DIR.toURI();
    URL[] ua = { loc.toURL() };
    URLClassLoader cl = new URLClassLoader(ua);
    Class<?> clazzSearchRequestType = cl.loadClass("com.legstar.test.coxb.enumvar.SearchRequestType");
    Object searchRequest = clazzSearchRequestType.newInstance();

    /* Create an Enum type with a value */
    Class<?> clazzSafeSearchOptionsType = cl.loadClass("com.legstar.test.coxb.enumvar.SafeSearchOptionsType");
    Field[] fields = clazzSafeSearchOptionsType.getDeclaredFields();
    for (Field field : fields) {
        _log.debug(field.getName());
    }

    /* Create a new enum type with a value */
    Method getValueMethod = clazzSafeSearchOptionsType.getMethod("value", (Class[]) null);
    Method fromValueMethod = clazzSafeSearchOptionsType.getMethod("fromValue",
            new Class[] { getValueMethod.getReturnType() });
    Object safeSearchOption = fromValueMethod.invoke(null, new Object[] { "Strict" });

    /* Get the value of an Enum */
    getValueMethod.invoke(safeSearchOption, (Object[]) null);

    /* Set the Enum value*/
    Class<?>[] param = { clazzSafeSearchOptionsType };
    String setterName = "setSafeSearch";
    Method setter = searchRequest.getClass().getMethod(setterName, param);
    setter.invoke(searchRequest, safeSearchOption);

    String getterName = "getSafeSearch";
    Method getter = searchRequest.getClass().getMethod(getterName);
    Object result = getter.invoke(searchRequest);
    assertEquals("Strict", getValueMethod.invoke(result, (Object[]) null));
}

From source file:org.forgerock.json.ref.jackson.JacksonReferenceTransformer.java

@Override
protected JsonValue resolve(URI uri) throws JsonException {
    JsonValue result;/*  ww  w .  j  a  va 2 s  .  c o m*/
    try (InputStream in = uri.toURL().openStream()) {
        result = new JsonValue(mapper.readValue(in, Object.class));
    } catch (IOException ioe) {
        throw new JsonException(ioe);
    }
    result.getTransformers().add(0, new JacksonReferenceTransformer(uri, result)); // support $refs
    return result;
}

From source file:crawlercommons.fetcher.file.SimpleFileFetcherTest.java

@Test
public void testSimpleFetching() throws Exception {
    URI uri = new File("src/test/resources/text-file.txt").toURI();
    String url = uri.toURL().toExternalForm();

    SimpleFileFetcher fetcher = new SimpleFileFetcher();
    FetchedResult result = fetcher.get(url);
    Assert.assertEquals(0, result.getNumRedirects());
    Assert.assertEquals(HttpStatus.SC_OK, result.getStatusCode());

    String fetchedContent = new String(result.getContent(), "us-ascii");
    Assert.assertEquals("Now is the time for all good men to come to the aid of their country.",
            fetchedContent);//w w  w.j  a  v a  2 s.c  om
}