Example usage for java.net URL getPath

List of usage examples for java.net URL getPath

Introduction

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

Prototype

public String getPath() 

Source Link

Document

Gets the path part of this URL .

Usage

From source file:de.tudarmstadt.ukp.dkpro.lexsemresource.core.util.FileUtils.java

/**
 * Make the given URL available as a file. A temporary file is created and
 * deleted upon a regular shutdown of the JVM. If the parameter {@code
 * aCache} is {@code true}, the temporary file is remembered in a cache and
 * if a file is requested for the same URL at a later time, the same file is
 * returned again. If the previously created file has been deleted
 * meanwhile, it is recreated from the URL.
 *
 * @param aUrl//from w  w w .j av  a  2 s .  c  o m
 *            the URL.
 * @param aCache
 *            use the cache or not.
 * @return a file created from the given URL.
 * @throws IOException
 *             if the URL cannot be accessed to (re)create the file.
 */
public static synchronized File getUrlAsFile(URL aUrl, boolean aCache) throws IOException {
    // If the URL already points to a file, there is not really much to do.
    if ("file".equals(aUrl.getProtocol())) {
        return new File(aUrl.getPath());
    }

    // Lets see if we already have a file for this URL in our cache. Maybe
    // the file has been deleted meanwhile, so we also check if the file
    // actually still exists on disk.
    File file = urlFileCache.get(aUrl);
    if (!aCache || (file == null) || !file.exists()) {
        // Create a temporary file and try to preserve the file extension
        String suffix = ".temp";
        String name = new File(aUrl.getPath()).getName();
        int suffixSep = name.indexOf(".");
        if (suffixSep != -1) {
            suffix = name.substring(suffixSep + 1);
            name = name.substring(0, suffixSep);
        }

        // Get a temporary file which will be deleted when the JVM shuts
        // down.
        file = File.createTempFile(name, suffix);
        file.deleteOnExit();

        // Now copy the file from the URL to the file.
        InputStream is = null;
        OutputStream os = null;
        try {
            is = aUrl.openStream();
            os = new FileOutputStream(file);
            IOUtils.copy(is, os);
        } finally {
            IOUtils.closeQuietly(is);
            IOUtils.closeQuietly(os);
        }

        // Remember the file
        if (aCache) {
            urlFileCache.put(aUrl, file);
        }
    }

    return file;
}

From source file:Urls.java

/** Whether the URL refers to a resource in the local file system. */
public static boolean isLocal(java.net.URL url) {
    if (isLocalFile(url)) {
        return true;
    }//from   w  ww . j a  va2 s  . co m
    String protocol = url.getProtocol();
    if ("jar".equalsIgnoreCase(protocol)) {
        String path = url.getPath();
        int emIdx = path.lastIndexOf('!');
        String subUrlString = emIdx == -1 ? path : path.substring(0, emIdx);
        try {
            URL subUrl = new URL(subUrlString);
            return isLocal(subUrl);
        } catch (java.net.MalformedURLException mfu) {
            return false;
        }
    } else {
        return false;
    }
}

From source file:eu.eubrazilcc.lvl.core.util.UrlUtils.java

/**
 * Gets the path part of an URI.//  ww w .j  a va  2  s  . com
 * @param uri - input URI
 * @return the path part of the specified URI or an empty string if one does not exist.
 * @throws IllegalArgumentException If a malformed URI occurs.
 */
public static String getPath(final URI uri) {
    checkArgument(uri != null, "Uninitialized URI");
    try {
        final URI nUri = uri.normalize();
        final URL url = nUri.isAbsolute() ? nUri.toURL()
                : new URL(new URL("http://example.org/"), nUri.getPath());
        return url.getPath();
    } catch (MalformedURLException e) {
        throw new IllegalArgumentException("Malformed URI", e);
    }
}

From source file:adalid.util.info.JavaInfo.java

public static void printManifestInfo(String extension, boolean details, URL url) throws IOException {
    InputStream stream = url.openStream();
    if (stream == null) {
        return;/*from ww  w  . ja va 2s.c  om*/
    }
    //      String file = url.getFile();
    String path = StringUtils.removeEndIgnoreCase(url.getPath(), "!/" + JarFile.MANIFEST_NAME);
    String name = StringUtils.substringAfterLast(path, "/");
    Manifest manifest = new Manifest(stream);
    if (!extensionNameMatches(manifest, extension)) {
        return;
    }
    //      out.println(file);
    printManifestInfo(path, name, details, manifest);
}

From source file:com.yunrang.hadoop.app.utils.CustomizedUtil.java

/**
 * Find a jar that contains a class of the same name, if any. It will return
 * a jar file, even if that is not the first thing on the class path that
 * has a class with the same name. Looks first on the classpath and then in
 * the <code>packagedClasses</code> map.
 * /*  ww w. j a  va2  s.  co  m*/
 * @param my_class the class to find.
 * @return a jar file that contains the class, or null.
 * @throws IOException
 */
public static String findContainingJar(Class<?> my_class, Map<String, String> packagedClasses)
        throws IOException {
    ClassLoader loader = my_class.getClassLoader();
    String class_file = my_class.getName().replaceAll("\\.", "/") + ".class";
    // first search the classpath
    for (Enumeration<URL> itr = loader.getResources(class_file); itr.hasMoreElements();) {
        URL url = itr.nextElement();
        if ("jar".equals(url.getProtocol())) {
            String toReturn = url.getPath();
            if (toReturn.startsWith("file:")) {
                toReturn = toReturn.substring("file:".length());
            }
            // URLDecoder is a misnamed class, since it actually decodes
            // x-www-form-urlencoded MIME type rather than actual
            // URL encoding (which the file path has). Therefore it would
            // decode +s to ' 's which is incorrect (spaces are actually
            // either unencoded or encoded as "%20"). Replace +s first, so
            // that they are kept sacred during the decoding process.
            toReturn = toReturn.replaceAll("\\+", "%2B");
            toReturn = URLDecoder.decode(toReturn, "UTF-8");
            return toReturn.replaceAll("!.*$", "");
        }
    }
    // now look in any jars we've packaged using JarFinder. Returns null
    // when
    // no jar is found.
    return packagedClasses.get(class_file);
}

From source file:wuit.crawler.searcher.Crawler.java

public static void getUrlInfo(DSCrawlerUrl info) {
    try {/*from www.  j  av a  2 s. c  o m*/
        URL _url = new URL(info.url);
        info.dns = _url.getHost() + "";
        info.path = _url.getPath();
        info.file = _url.getProtocol();
        if (!info.url.equals("") && info.url != null) {
            InetAddress a = InetAddress.getByName(_url.getHost());
            if (a != null)
                info.IP = a.getHostAddress();
        }
    } catch (Exception e) {
        System.out.println(" crawler   " + e.getMessage());
    }
}

From source file:org.infinispan.server.test.rest.security.RESTCertSecurityTest.java

public static CloseableHttpClient securedClient(String alias) {
    try {/*from   w w  w  .ja  v a  2  s . c o m*/
        SSLContext ctx = SSLContext.getInstance("TLS");
        JBossJSSESecurityDomain jsseSecurityDomain = new JBossJSSESecurityDomain("client_cert_auth");
        jsseSecurityDomain.setKeyStorePassword("changeit");
        ClassLoader tccl = Thread.currentThread().getContextClassLoader();
        URL keystore = tccl.getResource("client.keystore");
        jsseSecurityDomain.setKeyStoreURL(keystore.getPath());
        jsseSecurityDomain.setClientAlias(alias);
        jsseSecurityDomain.reloadKeyAndTrustStore();
        KeyManager[] keyManagers = jsseSecurityDomain.getKeyManagers();
        TrustManager[] trustManagers = jsseSecurityDomain.getTrustManagers();
        ctx.init(keyManagers, trustManagers, null);
        X509HostnameVerifier verifier = new X509HostnameVerifier() {

            @Override
            public void verify(String s, SSLSocket sslSocket) throws IOException {
            }

            @Override
            public void verify(String s, X509Certificate x509Certificate) throws SSLException {
            }

            @Override
            public void verify(String s, String[] strings, String[] strings1) throws SSLException {
            }

            @Override
            public boolean verify(String string, SSLSession ssls) {
                return true;
            }
        };
        ConnectionSocketFactory sslssf = new SSLConnectionSocketFactory(ctx, verifier);//SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        ConnectionSocketFactory plainsf = new PlainConnectionSocketFactory();
        Registry<ConnectionSocketFactory> sr = RegistryBuilder.<ConnectionSocketFactory>create()
                .register("http", plainsf).register("https", sslssf).build();
        HttpClientConnectionManager pcm = new PoolingHttpClientConnectionManager(sr);
        CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(pcm).build();

        return httpClient;
    } catch (Exception ex) {
        ex.printStackTrace();
        return null;
    }
}

From source file:org.silvertunnel.netlib.adapter.httpclient.HttpClientUtil.java

private static InputStream action_NOT_NEEDED(URL url) throws IOException {

    HttpHost target = new HttpHost(url.getHost(), url.getPort(), url.getProtocol());

    DefaultHttpClient httpclient = new DefaultHttpClient(connMgr, params);

    HttpGet req = new HttpGet(url.getPath());

    log.info("executing request to " + target);

    HttpResponse rsp = httpclient.execute(target, req);
    HttpEntity entity = rsp.getEntity();
    /*//from   ww w.j a  v a 2s . c om
    if (entity != null) {
    log.info(EntityUtils.toString(entity));
    }
    */
    return entity.getContent();

    // When HttpClient instance is no longer needed, 
    // shut down the connection manager to ensure
    // immediate deallocation of all system resources

    //TODO: httpclient.getConnectionManager().shutdown();        

}

From source file:org.eclipse.wst.json.core.internal.download.HttpClientProvider.java

private static File getCachedFile(URL url) {
    IPath stateLocation = JSONCorePlugin.getDefault().getStateLocation();
    IPath downloadFolder = stateLocation.append(JSON_DOWNLOAD_FOLDER);
    String urlPath = url.getPath();
    IPath filePath = downloadFolder.append(urlPath);
    File file = filePath.toFile();
    return file;//from   w w w .  ja va2s .c om
}

From source file:org.openimaj.web.scraping.images.ImgurClient.java

/**
 * @param url//ww w.j  a va2  s .c  o  m
 * @return the imgur type and hash, or null if the URL was too tricky
 */
public static ImgurTypeHash imgurURLtoHash(URL url) {
    if (!url.getHost().contains("imgur"))
        return null;
    final String path = url.getPath();
    final String[] split = path.split("[/]+");
    if (split.length == 0)
        return null;
    else if (split.length == 2) {
        if (split[1].equals("gallery"))
            return new ImgurTypeHash(ImgurType.GALLERY, null);
        else {
            final Matcher matcher = hashPattern.matcher(split[1]);
            if (matcher.find()) {
                final String hash = split[1].substring(0, matcher.end());
                return new ImgurTypeHash(ImgurType.IMAGE, hash);
            }
            return null;
        }
    } else {
        final String hashPart = split[split.length - 1];
        final String typePart = split[split.length - 2];
        ImgurType type = ImgurType.IMAGE;
        if (typePart.equals("a"))
            type = ImgurType.ALBUM;

        final Matcher matcher = hashPattern.matcher(hashPart);
        matcher.find();
        final String hash = hashPart.substring(0, matcher.end());
        return new ImgurTypeHash(type, hash);
    }

}