Example usage for java.net URL toURI

List of usage examples for java.net URL toURI

Introduction

In this page you can find the example usage for java.net URL toURI.

Prototype

public URI toURI() throws URISyntaxException 

Source Link

Document

Returns a java.net.URI equivalent to this URL.

Usage

From source file:at.tfr.securefs.util.Main.java

public void parseOpts(String[] args) throws Exception {

    List<String> argList = Arrays.asList(args);
    Iterator<String> iter = argList.iterator();

    if (args.length == 0) {
        System.out.println("Usage: [options] <file>");
        System.out.println("<file>: file to use for de/encryption");
        System.out.println("Options:");
        System.out.println("\t-t\tTest using test key with file");
        System.out.println("\t-d\tdecrypt file with test key - default");
        System.out.println("\t-e\tencrypt file with test key");
        System.out.println("\t-s <salt> \tsalt - default: use file name");
        System.out.println("\t-b <path> \base path for file access, default use ClassLoader roots");
        System.out.println("\t-o <outFile> \tfile to write to, relative to basePath");
        System.exit(0);//from  w w w. j a v  a 2s .  c o  m
    }

    while (iter.hasNext()) {
        String a = iter.next();

        switch (a) {
        case "-t":
            test = true;
            break;
        case "-d":
            mode = Cipher.DECRYPT_MODE;
            break;
        case "-e":
            mode = Cipher.ENCRYPT_MODE;
            break;
        case "-s":
            configuration.setSalt(iter.next());
            break;
        case "-b":
            basePath = new File(iter.next()).toPath();
            break;
        case "-o":
            outFile = iter.next();
            break;
        default:
            file = a;
        }
    }

    if (file == null)
        throw new FileNotFoundException("no file defined");

    if (basePath == null) {
        URL resource = this.getClass().getResource("/" + file);
        if (resource == null)
            throw new FileNotFoundException("cannot find basePath for file: " + file);
        URI uri = resource.toURI();
        String absolutePath = new File(uri).getAbsolutePath();
        basePath = new File(absolutePath).getParentFile().toPath();
    }

}

From source file:fr.gael.dhus.service.ProductService.java

private static boolean checkUrl(URL url) {
    Objects.requireNonNull(url, "`url` parameter must not be null");

    // OData Synchronized product, DELME
    if (url.getPath().endsWith("$value")) {
        // Ignoring ...
        return true;
    }//w  ww . ja  v a2s .c om

    // Case of simple file
    try {
        File f = new File(url.toString());
        if (f.exists())
            return true;
    } catch (Exception e) {
        logger.debug("url \"" + url + "\" not formatted as a file");
    }

    // Case of local URL
    try {
        URI local = new File(".").toURI();
        URI uri = local.resolve(url.toURI());
        File f = new File(uri);
        if (f.exists())
            return true;
    } catch (Exception e) {
        logger.debug("url \"" + url + "\" not a local URL");
    }

    // Case of remote URL
    try {
        URLConnection con = url.openConnection();
        con.connect();
        InputStream is = con.getInputStream();
        is.close();
        return true;
    } catch (Exception e) {
        logger.debug("url \"" + url + "\" not a remote URL");
    }
    // Unrecovrable case
    return false;
}

From source file:io.cloudslang.lang.compiler.CompileDecisionTest.java

@Test
public void testDecisionSystemPropertyDependencies() throws Exception {
    URL decision = getClass().getResource("/decision/decision_3_sp.sl");

    CompilationArtifact compilationArtifact = compiler.compile(fromFile(decision.toURI()), emptySetSlangSource);

    validateCompilationArtifact(compilationArtifact, inputs3, outputs2, results2, spSet1);
}

From source file:org.openxrd.discovery.impl.HtmlLinkDiscoveryMethod.java

/** {@inheritDoc} */
public URI getXRDLocation(URI uri) throws DiscoveryException {

    try {/*ww w.j  a  v  a2 s .  c o  m*/
        HttpResponse response = fetch(uri);
        HttpEntity entity = response.getEntity();

        if (entity == null) {
            entity.consumeContent();
            return null;
        }

        String content = EntityUtils.toString(entity);
        Parser htmlParser = Parser.createParser(content, null);

        LinkVisitor linkVisitor = new LinkVisitor();
        htmlParser.visitAllNodesWith(linkVisitor);

        for (Tag tag : linkVisitor.getLinks()) {
            if (!XRDConstants.XRD_MIME_TYPE.equals(tag.getAttribute("type"))) {
                continue;
            }

            if (!XRDConstants.XRD_REL_DESCRIBEDBY.equalsIgnoreCase(tag.getAttribute("rel"))) {
                continue;
            }

            try {
                URL xrdLocation = new URL(uri.toURL(), tag.getAttribute("href"));
                LOG.debug("Found XRD location: {}", xrdLocation.toString());

                return xrdLocation.toURI();
            } catch (URISyntaxException e) {
                continue;
            }
        }

        return null;
    } catch (IOException e) {
        throw new DiscoveryException(e);
    } catch (ParserException e) {
        throw new DiscoveryException(e);
    }
}

From source file:com.arangodb.ArangoConfigureTest.java

@Test
public void sslWithSelfSignedCertificateTest() throws ArangoException, KeyManagementException,
        NoSuchAlgorithmException, KeyStoreException, CertificateException, IOException, URISyntaxException {

    // create a sslContext for the self signed certificate
    URL resource = this.getClass().getResource(SSL_TRUSTSTORE);
    SSLContext sslContext = SSLContexts.custom()
            .loadTrustMaterial(Paths.get(resource.toURI()).toFile(), SSL_TRUSTSTORE_PASSWORD.toCharArray())
            .build();//  ww w  . ja  v  a 2  s  .  c o m

    ArangoConfigure configuration = new ArangoConfigure("/ssl-arangodb.properties");
    configuration.setSslContext(sslContext);
    configuration.init();

    ArangoDriver arangoDriver = new ArangoDriver(configuration);

    ArangoVersion version = arangoDriver.getVersion();

    Assert.assertNotNull(version);
}

From source file:com.asakusafw.testdriver.DirectIoUtilTest.java

private File asFile(String name) {
    URL url = getClass().getResource(name);
    assertThat(url, is(notNullValue()));
    try {/*from  www .j av a2  s .c  om*/
        return new File(url.toURI());
    } catch (URISyntaxException e) {
        Assume.assumeNoException(e);
        throw new AssertionError(e);
    }
}

From source file:fr.free.movierenamer.scrapper.impl.trailer.VideoDetectiveScrapper.java

@Override
protected TrailerInfo fetchTrailerInfo(Trailer searchResult) throws Exception {

    URL url = searchResult.getTrailerUrl();
    Matcher matcher = idPattern.matcher(url.toExternalForm());
    if (!matcher.find()) {
        throw new Exception("No id found for " + searchResult);
    }/*  ww w .  j  a va  2 s  .c om*/

    Map<TrailerProperty, String> info = new EnumMap<TrailerProperty, String>(TrailerProperty.class);
    Map<Quality, URL> streams = new EnumMap<Quality, URL>(Quality.class);

    String id = matcher.group(1);

    String urlStr = String.format(infoUrl, cusomerId, id);
    URL uri = new URL(urlStr);

    JSONObject json = URIRequest.getJsonDocument(uri.toURI());
    List<JSONObject> pnodes = JSONUtils.selectList("playlist", json);

    info.put(TrailerProperty.title, searchResult.getName());
    info.put(TrailerProperty.provider, searchResult.getProviderName());
    info.put(TrailerProperty.runtime, searchResult.getRuntime());
    info.put(TrailerProperty.overview, JSONUtils.selectString("description", pnodes.get(0)));

    List<JSONObject> nodes = JSONUtils.selectList("sources", pnodes.get(0));
    for (JSONObject node : nodes) {
        String label = JSONUtils.selectString("label", node);
        if (label != null) {
            Bitrate bt;
            try {
                bt = Bitrate.valueOf("B_" + (label.replace(" ", "_")));
            } catch (Exception ex) {
                continue;
            }

            if (streams.containsKey(bt.getQuality())) {
                continue;
            }

            streams.put(bt.getQuality(), new URL(JSONUtils.selectString("file", node)));
        }
    }

    return new TrailerInfo(info, streams, searchResult.getLang());
}

From source file:org.opendaylight.sfc.sbrest.json.ExporterUtilTest.java

private String gatherUtilJsonStringFromFile(String testFileName) {
    String jsonString = null;/*from   w  w  w .ja v a 2 s  .c  om*/

    try {
        URL fileURL = getClass().getResource(testFileName);
        jsonString = TestUtil.readFile(fileURL.toURI(), StandardCharsets.UTF_8);
    } catch (IOException | URISyntaxException e) {
        e.printStackTrace();
    }

    for (UtilTestValues utilTestValue : UtilTestValues.values()) {
        // noinspection ConstantConditions
        jsonString = jsonString.replaceAll("\\b" + utilTestValue.name() + "\\b", utilTestValue.getValue());
    }

    return jsonString;
}

From source file:com.mmnaseri.dragonfly.entity.impl.DefaultEntityContext.java

/**
 * This method will determine the classpath argument passed to the JavaC compiler used by this
 * implementation/*from   www .  ja  v a2s .c  om*/
 *
 * @return the classpath
 */
protected String getClassPath(ClassLoader classLoader) {
    final Set<File> classPathElements = new HashSet<File>();
    //Adding runtime dependencies available to the project
    final URL[] urls;
    if (classLoader instanceof URLClassLoader) {
        urls = ((URLClassLoader) classLoader).getURLs();
    } else if (classLoader instanceof ConfigurableClassLoader) {
        urls = ((ConfigurableClassLoader) classLoader).getUrls();
    } else {
        urls = new URL[0];
    }
    for (URL url : urls) {
        try {
            final File file = new File(url.toURI());
            if (file.exists()) {
                classPathElements.add(file);
            }
        } catch (Throwable ignored) {
        }
    }
    return with(classPathElements).transform(new Transformer<File, String>() {
        @Override
        public String map(File input) {
            return input.getAbsolutePath();
        }
    }).join(File.pathSeparator);
}

From source file:org.wikimedia.analytics.kraken.pageview.PageviewCanonical.java

/**
 * Enter one or more keys to search for, this list of keys is
 * interpreted as key1 or key2; this function is not intended
 * to retrieve the values of multiple keys. In that case,
 * call this function multiple times.//from   w ww .j  av  a 2 s  . com
 * @param keys
 * @return
 */
private String searchQueryAction(final String[] keys) {
    try {
        URL pURL = fixApacheHttpComponentBug(url);

        List<NameValuePair> qparams = URLEncodedUtils.parse(pURL.toURI(), "utf-8");
        ListIterator<NameValuePair> it = qparams.listIterator();
        while (it.hasNext()) {
            NameValuePair nvp = it.next();
            for (String key : keys) {
                if (nvp.getName().equals(key)) {
                    return nvp.getValue();
                }
            }
        }
    } catch (URISyntaxException e) {
        return "key.not.found";
    } catch (MalformedURLException e) {
        return "malformed.url";
    }
    return "key.not.found";
}