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:fr.dutra.confluence2wordpress.util.UrlUtils.java

/**
 * Sanitizes the given URL by escaping the path and query parameters, if necessary.
 * @see "http://stackoverflow.com/questions/724043/http-url-address-encoding-in-java"
 * @param url/*from w w w.  j  a v  a 2s.  c  om*/
 * @return
 * @throws URISyntaxException
 * @throws MalformedURLException
 */
public static String sanitize(String url) throws URISyntaxException, MalformedURLException {
    URL temp = new URL(url);
    URI uri = new URI(temp.getProtocol(), temp.getUserInfo(), temp.getHost(), temp.getPort(), temp.getPath(),
            temp.getQuery(), temp.getRef());
    return uri.toASCIIString();
}

From source file:SageCollegeProject.guideBox.java

public static String GetEncWebCall(String webcall) {
    try {//from   w ww.j  a v  a  2s . co  m
        URL url = new URL(webcall);
        URI test = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(),
                url.getQuery(), url.getRef());
        return test.toASCIIString();
    } catch (URISyntaxException | MalformedURLException ex) {
        Logger.getLogger(guideBox.class.getName()).log(Level.SEVERE, null, ex);
    }
    return "";
}

From source file:com.adguard.filter.rules.ContentType.java

/**
 * Detects content type using request url
 *
 * @param url Url// www.  jav  a 2 s  .  c  o m
 * @return Content type detected
 */
public static ContentType detectContentType(URL url) {
    String path = url.getPath();

    for (Map.Entry<String, ContentType> entry : FILE_EXTENSION_CONTENT_TYPE.entrySet()) {
        if (StringUtils.endsWith(path, entry.getKey())) {
            return entry.getValue();
        }
    }

    return ContentType.OTHER;
}

From source file:com.google.gdt.eclipse.designer.webkit.WebKitSupportWin32.java

public static void deployIfNeededAndLoad() {
    if (!m_initialized) {
        try {/*from   w ww.j a va2  s. c o m*/
            // extract
            Bundle bundle = Platform.getBundle("com.google.gdt.eclipse.designer.hosted.2_0.webkit");
            URL resource = FileLocator.resolve(bundle.getResource("WebKit.zip"));
            ZipFile zipFile = new ZipFile(resource.getPath());
            try {
                if (deployNeeded(zipFile)) {
                    extract(zipFile);
                }
            } finally {
                zipFile.close();
            }
            load();
            m_available = true;
        } catch (Throwable e) {
            // ignore
        }
        m_initialized = true;
    }
}

From source file:io.seldon.importer.articles.AttributesImporterUtils.java

public static String getBaseUrl(String url) throws Exception {
    URL aURL = new URL(url);

    String protocol = aURL.getProtocol();
    String host = aURL.getHost();
    String path = aURL.getPath();

    String baseUrl = String.format("%s://%s%s", protocol, host, path);
    return baseUrl;
}

From source file:com.ibm.jaggr.core.util.PathUtil.java

/**
 * Convenience method to convert a URL to a URI that doesn't throw a
 * URISyntaxException if the path component for the URL contains
 * spaces (like {@link URL#toURI()} does).
 *
 * @param url The input URL//from  ww w .  j  a  v  a  2 s .  co  m
 * @return The URI
 * @throws URISyntaxException
 */
public static URI url2uri(URL url) throws URISyntaxException {
    return new URI(url.getProtocol(), url.getAuthority(), url.getPath(), url.getQuery(), url.getRef());
}

From source file:info.dolezel.fatrat.plugins.helpers.NativeHelpers.java

public static Map<String, String> getPackageVersions() throws IOException {
    Map<String, String> rv = new HashMap<String, String>();
    String[] jars = System.getProperty("java.class.path").split(":");

    for (String jar : jars) {
        File fo = new File(jar);
        String name;//from ww  w .  java2  s .  com

        if (!fo.exists())
            continue;

        name = fo.getName();

        if (name.startsWith("fatrat-") && !name.equals("fatrat-jplugins-core.jar")
                && !name.equals("fatrat-jplugins-json.jar"))
            getPackageVersion(fo, rv);
    }
    for (URL url : loader.getURLs()) {
        String jarPath = url.getPath().replaceFirst("[.]jar[!].*", ".jar").replaceFirst("file:", "");
        getPackageVersion(new File(jarPath), rv);
    }

    return rv;
}

From source file:com.autentia.common.util.FileSystemUtils.java

/**
 * Devuelve la ruta absoluta hasta el directorio a partir del cual se puede obtener la clase. Si la clase est en un
 * .class se obtiene la ruta hasta el directorio donde empezar el paquete de la clase (es decir los directorios
 * com/foo/barr/... no estaran incluidos en el resultado). Si la clase est en un .jar se obtiene la ruta donde
 * est el jar.//from   w ww. ja v  a  2s . c  o m
 * <p>
 * Para encontrar la clase se busacara haciendo un <code>getResource()</code> a la propia clase que se quiere
 * localizar.
 * <p>
 * El directorio que se devuelve termina con el caracter separador de directorios (segn la plataforma).
 * 
 * @param clazz clase que se pretende localizar.
 * @return ruta absoluta hasta el directorio donde se puede localizar la clase.
 */
public static String getPathToClassOrJar(Class<?> clazz) {
    // 
    // No utilizamos el separador del sistema porque en Windows y, al menos, bajo Tomcat,
    // el mtodo class.getResource() espera como parmetro el separador de unix.
    // 
    final String PATH_SEPARATOR = "/";
    String cn = PATH_SEPARATOR + clazz.getName().replace('.', PATH_SEPARATOR.charAt(0)) + ".class";
    final URL url = clazz.getResource(cn);
    String path = url.getPath();
    final int indexOfClass = path.indexOf(cn);
    final int indexOfClassMinusOne = indexOfClass - 1;

    // La URL que define donde est una clase es del estilo:
    // * file:/...class
    // * jar:file:/...jar!/...class
    // Con URL.getPath() se obtiene una cadena que ya tiene quitado el primer protocolo (file: o jar:).
    final int begin;
    final int end;
    if (path.charAt(indexOfClassMinusOne) == '!') {
        // La clase est en un jar, as que quitamos el protocolo 'file:' del principio,
        // y el nombre del jar del final
        begin = path.indexOf(':') + 1;
        end = path.lastIndexOf(PATH_SEPARATOR, indexOfClassMinusOne) + 1;
    } else {
        begin = 0;
        end = indexOfClass + 1;
    }
    path = path.substring(begin, end);
    return getCannonicalPath(path);
}

From source file:com.adrguides.utils.HTTPUtils.java

public static InputStream openAddress(Context context, URL url) throws IOException {
    if ("file".equals(url.getProtocol()) && url.getPath().startsWith("/android_asset/")) {
        return context.getAssets().open(url.getPath().substring(15)); // "/android_asset/".length() == 15
    } else {/*from  ww  w .  j av a2s  .  com*/
        URLConnection urlconn = url.openConnection();
        urlconn.setReadTimeout(10000 /* milliseconds */);
        urlconn.setConnectTimeout(15000 /* milliseconds */);
        urlconn.setAllowUserInteraction(false);
        urlconn.setDoInput(true);
        urlconn.setDoOutput(false);
        if (urlconn instanceof HttpURLConnection) {
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            int responsecode = connection.getResponseCode();
            if (responsecode != HttpURLConnection.HTTP_OK) {
                throw new IOException("Http response code returned:" + responsecode);
            }
        }
        return urlconn.getInputStream();
    }
}

From source file:com.asual.summer.core.util.ResourceUtils.java

public static List<URL> getClasspathResources(String name, boolean jarURL) {

    List<URL> list = new ArrayList<URL>();
    try {/*from  w  ww  .  j  ava  2s  .  c o m*/
        Enumeration<URL> resources = RequestUtils.class.getClassLoader().getResources(name);
        while (resources.hasMoreElements()) {
            URL resource = resources.nextElement();
            if (jarURL || jarURL == org.springframework.util.ResourceUtils.isJarURL(resource)) {
                list.add(resource);
            }
        }
    } catch (Exception e) {
    }

    Collections.sort(list, new Comparator<URL>() {

        private static final String PREFIX = "/summer-";

        public int compare(URL o1, URL o2) {
            return o1.getPath().indexOf(PREFIX) - o2.getPath().indexOf(PREFIX);
        }

    });

    return list;
}