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:com.liferay.sync.engine.SyncSystemTest.java

protected static Path getResourceFilePath(String name) throws Exception {
    Class<?> clazz = SyncSystemTest.class;

    URL url = clazz.getResource(name);

    return Paths.get(url.toURI());
}

From source file:com.cpjit.swagger4j.util.ReflectUtils.java

/**
 * ????/*from  ww  w .  jav a2s . c  om*/
 * 
 * @param basePackage
 * @param recursion
 *            ????
 * @return    ???null
 *          0
 *          <li>?</li>
 *          <li>package-info.java?</li>
 *          <li>?basePackage</li>
 * @since 1.0.0
 */
public static List<Package> scanPackage(final String basePackage, boolean recursion) {
    if (StringUtils.isBlank(basePackage)) {
        return Collections.emptyList();
    }

    Set<Package> packages = new HashSet<Package>();
    String pack2path = basePackage.replaceAll("\\.", "/");
    URL url = ResourceUtil.getResource(pack2path);
    if (url == null) { // ?
        return Collections.emptyList();
    }

    Path pkFile = null;
    try {
        pkFile = Paths.get(url.toURI());
    } catch (URISyntaxException e) {
        throw new IllegalArgumentException(basePackage + "????", e);
    }
    if (!Files.isDirectory(pkFile)) {
        throw new IllegalArgumentException(basePackage + "????");
    }

    Package pk = null;
    try {
        pk = getPackage(basePackage);
    } catch (Exception e) {
    }
    if (pk != null) {
        packages.add(pk);
    }

    if (recursion && StringUtils.isNotBlank(basePackage)) { // ???
        try (DirectoryStream<Path> childs = Files.newDirectoryStream(pkFile)) {
            childs.forEach(child -> {
                if (Files.isDirectory(child)) {
                    String childPackage = basePackage + "." + child.getFileName().toString();
                    if (StringUtils.isBlank(basePackage)) { // 
                        childPackage = child.getFileName().toString();
                    }
                    packages.addAll(scanPackage(childPackage, true));
                }
            });
        } catch (Exception e) {
            throw new IllegalStateException(e);
        }
    }
    if (packages.size() < 1) { // ??
        return Collections.emptyList();
    }

    return new ArrayList<Package>(packages);
}

From source file:com.google.gwt.dev.resource.impl.ResourceOracleImpl.java

private static void addAllClassPathEntries(TreeLogger logger, ClassLoader classLoader,
        List<ClassPathEntry> classPath) {
    // URL is expensive in collections, so we use URI instead
    // See://from   w w  w.  ja  v  a 2  s. c o  m
    // http://michaelscharf.blogspot.com/2006/11/javaneturlequals-and-hashcode-make.html
    Set<URI> seenEntries = new HashSet<URI>();
    for (; classLoader != null; classLoader = classLoader.getParent()) {
        if (classLoader instanceof URLClassLoader) {
            URLClassLoader urlClassLoader = (URLClassLoader) classLoader;
            URL[] urls = urlClassLoader.getURLs();
            for (URL url : urls) {
                URI uri;
                try {
                    uri = url.toURI();
                } catch (URISyntaxException e) {
                    logger.log(TreeLogger.WARN, "Error processing classpath URL '" + url + "'", e);
                    continue;
                }
                if (seenEntries.contains(uri)) {
                    continue;
                }
                seenEntries.add(uri);
                Throwable caught;
                try {
                    ClassPathEntry entry = createEntryForUrl(logger, url);
                    if (entry != null) {
                        classPath.add(entry);
                    }
                    continue;
                } catch (AccessControlException e) {
                    if (logger.isLoggable(TreeLogger.DEBUG)) {
                        logger.log(TreeLogger.DEBUG, "Skipping URL due to access restrictions: " + url);
                    }
                    continue;
                } catch (URISyntaxException e) {
                    caught = e;
                } catch (IOException e) {
                    caught = e;
                }
                logger.log(TreeLogger.WARN, "Error processing classpath URL '" + url + "'", caught);
            }
        }
    }
}

From source file:fr.free.movierenamer.scrapper.impl.movie.RottenTomatoesScrapper.java

public static IdInfo rottenTomatoesIdLookUp(IdInfo imdbId) {
    if (imdbId.getIdType() != AvailableApiIds.IMDB) {
        return null;
    }//from   w  w w  .j  av a2s. c o m

    try {
        URL searchUrl = new URL("http", apiHost,
                "/api/public/v" + version + "/movie_alias.json?apikey=" + apikey + "&type=imdb&id=" + imdbId);
        JSONObject json = URIRequest.getJsonDocument(searchUrl.toURI());
        String id = JSONUtils.selectString("id", json);
        if (id != null && !id.isEmpty()) {
            return new IdInfo(Integer.parseInt(id), ScrapperUtils.AvailableApiIds.ROTTENTOMATOES);
        }
    } catch (Exception ex) {
        // No id found
    }

    return null;
}

From source file:com.cpjit.swagger4j.util.ReflectUtils.java

/**
 * ????//from ww w  .j  a v  a2 s  . c o m
 * 
 * @param packageName
 * @return ????null
 *       0
 *       <li>?packNames0</li>
 *       <li>??</li>
 * @throws FileNotFoundException ?
 * @throws IllegalArgumentException ???
 * @since 1.0.0
 */
public static List<String> scanClazzName(String packageName)
        throws FileNotFoundException, IllegalArgumentException {
    String pack2path = packageName.replaceAll("\\.", "/");
    if (StringUtils.isBlank(packageName)) {
        pack2path = "";
    }

    URL fullPath = ResourceUtil.getResource(pack2path);
    if (fullPath == null) {
        throw new FileNotFoundException("[" + packageName + "]?");
    }
    Path pack;
    try {
        pack = Paths.get(fullPath.toURI());
    } catch (URISyntaxException e) {
        throw new IllegalArgumentException(e);
    }
    if (!Files.isDirectory(pack)) {
        throw new IllegalArgumentException("[" + packageName + "]????");
    }

    Set<String> clazzNames = new HashSet<String>();
    String prefix = StringUtils.isBlank(packageName) ? "" : packageName + ".";
    // ?Java?
    try (DirectoryStream<Path> clazzs = Files.newDirectoryStream(pack, "*.class");) {
        clazzs.forEach(clazz -> { // ???
            String clazzName = prefix + clazz.getFileName().toString().replace(".class", "");
            clazzNames.add(clazzName);
        });
    } catch (IOException e) {
        throw new IllegalArgumentException(e);
    }

    if (clazzNames.size() < 1) { // ?
        return Collections.emptyList();
    }
    return new ArrayList<String>(clazzNames);
}

From source file:com.qmetry.qaf.automation.core.ConfigurationManager.java

private static Map<String, String> getBuildInfo() {
    Manifest manifest = null;/*ww  w  . ja  v a 2  s .  c o  m*/
    Map<String, String> buildInfo = new HashMap<String, String>();
    JarFile jar = null;
    try {
        URL url = ConfigurationManager.class.getProtectionDomain().getCodeSource().getLocation();
        File file = new File(url.toURI());
        jar = new JarFile(file);
        manifest = jar.getManifest();
    } catch (NullPointerException ignored) {
    } catch (URISyntaxException ignored) {
    } catch (IOException ignored) {
    } catch (IllegalArgumentException ignored) {
    } finally {
        if (null != jar)
            try {
                jar.close();
            } catch (IOException e) {
                log.warn(e.getMessage());
            }
    }

    if (manifest == null) {
        return buildInfo;
    }

    try {
        Attributes attributes = manifest.getAttributes("Build-Info");
        Set<Entry<Object, Object>> entries = attributes.entrySet();
        for (Entry<Object, Object> e : entries) {
            buildInfo.put(String.valueOf(e.getKey()), String.valueOf(e.getValue()));
        }
    } catch (NullPointerException e) {
        // Fall through
    }

    return buildInfo;
}

From source file:jp.go.aist.six.util.core.web.spring.Http.java

/**
 * Generic HTTP method execution./* www  .  ja  v a  2s . com*/
 *
 * @throws  HttpException
 *  when an exceptional condition occurred during the HTTP method execution.
 */
protected static <T> T _execute(final URL from_url, final HttpMethod method, final RequestCallback callback,
        final ResponseExtractor<T> extractor) {
    _LOG_.debug("HTTP: method = " + method + ", URL=" + from_url);

    URI from_uri = null;
    try {
        from_uri = from_url.toURI();
        //throws URISyntaxException
    } catch (URISyntaxException ex) {
        throw new HttpException(ex);
    }

    T response = null;
    try {
        RestTemplate rest = new RestTemplate();
        response = rest.execute(from_uri, method, callback, extractor);
    } catch (RestClientException ex) {
        _LOG_.error("HTTP error: " + ex);
        throw new HttpException(ex);
    }

    return response;
}

From source file:fr.free.movierenamer.scrapper.impl.movie.RottenTomatoesScrapper.java

public static IdInfo imdbIdLookup(IdInfo rottenTomatoesId) {
    if (rottenTomatoesId.getIdType() != ScrapperUtils.AvailableApiIds.ROTTENTOMATOES) {
        return null;
    }//w  w w  .  j a va2  s . c o m

    try {
        URL searchUrl = new URL("http", apiHost, "/api/public/v" + version + "/movies/"
                + rottenTomatoesId.toString() + ".json?apikey=" + apikey);
        JSONObject json = URIRequest.getJsonDocument(searchUrl.toURI());
        JSONObject jobject = JSONUtils.selectObject("alternate_ids", json);
        if (jobject != null) {
            Integer imdbId = JSONUtils.selectInteger("imdb", jobject);
            if (imdbId != null) {
                return new IdInfo(imdbId, ScrapperUtils.AvailableApiIds.IMDB);
            }
        }
    } catch (MalformedURLException ex) {
        Logger.getLogger(RottenTomatoesScrapper.class.getName()).log(Level.SEVERE, null, ex);
    } catch (URISyntaxException ex) {
        Logger.getLogger(RottenTomatoesScrapper.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(RottenTomatoesScrapper.class.getName()).log(Level.SEVERE, null, ex);
    }

    return null;
}

From source file:com.igormaznitsa.sciareto.ui.UiUtils.java

private static void showURLExternal(@Nonnull final URL url) {
    if (Desktop.isDesktopSupported()) {
        final Desktop desktop = Desktop.getDesktop();
        if (desktop.isSupported(Desktop.Action.BROWSE)) {
            try {
                desktop.browse(url.toURI());
            } catch (Exception x) {
                LOGGER.error("Can't browse URL in Desktop", x);
            }//from   w  ww.java  2 s  .  com
        } else if (SystemUtils.IS_OS_LINUX) {
            final Runtime runtime = Runtime.getRuntime();
            try {
                runtime.exec("xdg-open " + url);
            } catch (IOException e) {
                LOGGER.error("Can't browse URL under Linux", e);
            }
        } else if (SystemUtils.IS_OS_MAC) {
            final Runtime runtime = Runtime.getRuntime();
            try {
                runtime.exec("open " + url);
            } catch (IOException e) {
                LOGGER.error("Can't browse URL on MAC", e);
            }
        }
    }

}

From source file:com.google.gwt.dev.resource.impl.ResourceOracleImpl.java

public static ClassPathEntry createEntryForUrl(TreeLogger logger, URL url)
        throws URISyntaxException, IOException {
    if (url.getProtocol().equals("file")) {
        File f = new File(url.toURI());
        String lowerCaseFileName = f.getName().toLowerCase(Locale.ENGLISH);
        if (f.isDirectory()) {
            return new DirectoryClassPathEntry(f);
        } else if (f.isFile() && lowerCaseFileName.endsWith(".jar")) {
            return ZipFileClassPathEntry.get(f);
        } else if (f.isFile() && lowerCaseFileName.endsWith(".zip")) {
            return ZipFileClassPathEntry.get(f);
        } else {/*from www.ja  v  a  2s.co m*/
            // It's a file ending in neither jar nor zip, speculatively try to
            // open as jar/zip anyway.
            try {
                return ZipFileClassPathEntry.get(f);
            } catch (Exception ignored) {
            }
            if (logger.isLoggable(TreeLogger.TRACE)) {
                logger.log(TreeLogger.TRACE, "Unexpected entry in classpath; " + f
                        + " is neither a directory nor an archive (.jar or .zip)");
            }
            return null;
        }
    } else {
        logger.log(TreeLogger.WARN, "Unknown URL type for " + url, null);
        return null;
    }
}