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.eolya.utils.http.HttpUtils.java

public static boolean isChildOf(URL urlChild, URL urlFather) {
    String urlChildPath = fixUpUrl(urlChild.getPath().toLowerCase());
    String urlFatherPath = fixUpUrl(urlFather.getPath().toLowerCase());

    return urlChildPath.startsWith(urlFatherPath);
}

From source file:eionet.cr.util.URLUtil.java

/**
 *
 * @param urlString/*from ww w  .j ava2  s. co m*/
 * @return
 */
public static String normalizeUrl(String urlString) {

    // if given URL string is null, return it as it is
    if (urlString == null) {
        return urlString;
    }

    // we're going to need both the URL and URI wrappers
    URL url = null;
    URI uri = null;
    try {
        url = new URL(urlString.trim());
        uri = url.toURI();
    } catch (MalformedURLException e) {
        return urlString;
    } catch (URISyntaxException e) {
        return urlString;
    }

    // get all the various parts of this URL
    String protocol = url.getProtocol();
    String userInfo = url.getUserInfo();
    String host = url.getHost();
    int port = url.getPort();
    String path = url.getPath();
    String query = url.getQuery();
    String reference = url.getRef();

    // start building the result, processing each of the above-found URL parts

    StringBuilder result = new StringBuilder();

    try {
        if (!StringUtils.isEmpty(protocol)) {
            result.append(decodeEncode(protocol.toLowerCase())).append("://");
        }

        if (!StringUtils.isEmpty(userInfo)) {
            result.append(decodeEncode(userInfo, ":")).append("@");
        }

        if (!StringUtils.isEmpty(host)) {
            result.append(decodeEncode(host.toLowerCase()));
        }

        if (port != -1 && port != 80) {
            result.append(":").append(port);
        }

        if (!StringUtils.isEmpty(path)) {
            result.append(normalizePath(path));
        }

        if (!StringUtils.isEmpty(query)) {
            String normalizedQuery = normalizeQueryString(uri);
            if (!StringUtils.isBlank(normalizedQuery)) {
                result.append("?").append(normalizedQuery);
            }
        }

        if (!StringUtils.isEmpty(reference)) {
            result.append("#").append(decodeEncode(reference));
        }
    } catch (UnsupportedEncodingException e) {
        throw new CRRuntimeException("Unsupported encoding: " + e.getMessage(), e);
    }

    return result.toString();
}

From source file:com.centeractive.ws.SchemaUtils.java

private static void loadDefaultSchema(URL url) throws Exception {
    XmlObject xmlObject = XmlUtils.createXmlObject(url);
    if (!((Document) xmlObject.getDomNode()).getDocumentElement().getNamespaceURI().equals(Constants.XSD_NS))
        return;//  ww w.j  a  va 2  s .  co m

    String targetNamespace = getTargetNamespace(xmlObject);

    if (defaultSchemas.containsKey(targetNamespace))
        log.warn("Overriding schema for targetNamespace " + targetNamespace);

    defaultSchemas.put(targetNamespace, xmlObject);

    log.debug("Added default schema from " + url.getPath() + " with targetNamespace " + targetNamespace);
}

From source file:com.gargoylesoftware.htmlunit.util.UrlUtils.java

/**
 * Creates and returns a new URL identical to the specified URL, except using the specified reference.
 * @param u the URL on which to base the returned URL
 * @param newRef the new reference to use in the returned URL
 * @return a new URL identical to the specified URL, except using the specified reference
 * @throws MalformedURLException if there is a problem creating the new URL
 *///from   w ww . ja v a 2s  .  co m
public static URL getUrlWithNewRef(final URL u, final String newRef) throws MalformedURLException {
    return createNewUrl(u.getProtocol(), u.getAuthority(), u.getPath(), newRef, u.getQuery());
}

From source file:com.gargoylesoftware.htmlunit.util.UrlUtils.java

/**
 * Creates and returns a new URL identical to the specified URL, except using the specified protocol.
 * @param u the URL on which to base the returned URL
 * @param newProtocol the new protocol to use in the returned URL
 * @return a new URL identical to the specified URL, except using the specified protocol
 * @throws MalformedURLException if there is a problem creating the new URL
 *///w ww .j a v  a 2 s  . c om
public static URL getUrlWithNewProtocol(final URL u, final String newProtocol) throws MalformedURLException {
    return createNewUrl(newProtocol, u.getAuthority(), u.getPath(), u.getRef(), u.getQuery());
}

From source file:com.gargoylesoftware.htmlunit.util.UrlUtils.java

/**
 * Creates and returns a new URL identical to the specified URL, except using the specified query string.
 * @param u the URL on which to base the returned URL
 * @param newQuery the new query string to use in the returned URL
 * @return a new URL identical to the specified URL, except using the specified query string
 * @throws MalformedURLException if there is a problem creating the new URL
 *//*from w w w . ja  v a  2s .co m*/
public static URL getUrlWithNewQuery(final URL u, final String newQuery) throws MalformedURLException {
    return createNewUrl(u.getProtocol(), u.getAuthority(), u.getPath(), u.getRef(), newQuery);
}

From source file:net.aepik.alasca.core.ldap.Schema.java

/**
 * Retourne l'ensemble des syntaxes connues, qui sont
 * contenues dans le package 'ldap.syntax'.
 * @return String[] L'ensemble des noms de classes de syntaxes.
 *///from  w  ww. j av a  2 s  .c o  m
public static String[] getSyntaxes() {
    String[] result = null;
    try {
        String packageName = getSyntaxPackageName();
        URL url = Schema.class.getResource("/" + packageName.replace('.', '/'));
        if (url == null) {
            return null;
        }
        if (url.getProtocol().equals("jar")) {
            Vector<String> vectTmp = new Vector<String>();
            int index = url.getPath().indexOf('!');
            String path = URLDecoder.decode(url.getPath().substring(index + 1), "UTF-8");
            JarFile jarFile = new JarFile(URLDecoder.decode(url.getPath().substring(5, index), "UTF-8"));
            if (path.charAt(0) == '/') {
                path = path.substring(1);
            }
            Enumeration<JarEntry> jarFiles = jarFile.entries();
            while (jarFiles.hasMoreElements()) {
                JarEntry tmp = jarFiles.nextElement();
                //
                // Pour chaque fichier dans le jar, on regarde si c'est un
                // fichier de classe Java.
                //
                if (!tmp.isDirectory() && tmp.getName().substring(tmp.getName().length() - 6).equals(".class")
                        && tmp.getName().startsWith(path)) {
                    int i = tmp.getName().lastIndexOf('/');
                    String classname = tmp.getName().substring(i + 1, tmp.getName().length() - 6);
                    vectTmp.add(classname);
                }
            }
            jarFile.close();
            result = new String[vectTmp.size()];
            for (int i = 0; i < vectTmp.size(); i++) {
                result[i] = vectTmp.elementAt(i);
            }
        } else if (url.getProtocol().equals("file")) {
            //
            // On cr le fichier associ pour parcourir son contenu.
            // En l'occurence, c'est un dossier.
            //
            File[] files = (new File(url.toURI())).listFiles();
            //
            // On liste tous les fichiers qui sont dedans.
            // On les stocke dans un vecteur ...
            //
            Vector<File> vectTmp = new Vector<File>();
            for (File f : files) {
                if (!f.isDirectory()) {
                    vectTmp.add(f);
                }
            }
            //
            // ... pour ensuite les mettres dans le tableau de resultat.
            //
            result = new String[vectTmp.size()];
            for (int i = 0; i < vectTmp.size(); i++) {
                String name = vectTmp.elementAt(i).getName();
                int a = name.indexOf('.');
                name = name.substring(0, a);
                result[i] = name;
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    if (result != null) {
        Arrays.sort(result);
    }
    return result;
}

From source file:at.beris.virtualfile.util.UrlUtils.java

/**
 * Masks sensitive information in an url (e.g. for logging)
 *
 * @param url//from   www. j  a va 2  s.  c om
 * @return
 */
public static String maskedUrlString(URL url) {
    StringBuilder stringBuilder = new StringBuilder("");

    stringBuilder.append(url.getProtocol());
    stringBuilder.append(':');
    if (!url.getProtocol().toLowerCase().equals("file"))
        stringBuilder.append("//");

    String authority = url.getAuthority();
    if (!StringUtils.isEmpty(authority)) {
        String[] authorityParts = authority.split("@");

        if (authorityParts.length > 1) {
            String[] userInfoParts = authorityParts[0].split(":");
            stringBuilder.append(userInfoParts[0]);

            if (userInfoParts.length > 1) {
                stringBuilder.append(":***");
            }
            stringBuilder.append('@');
            stringBuilder.append(authorityParts[1]);
        } else {
            stringBuilder.append(authorityParts[0]);
        }
    }

    stringBuilder.append(url.getPath());

    return stringBuilder.toString();
}

From source file:com.gargoylesoftware.htmlunit.util.UrlUtils.java

/**
 * Creates and returns a new URL identical to the specified URL, except using the specified port.
 * @param u the URL on which to base the returned URL
 * @param newPort the new port to use in the returned URL
 * @return a new URL identical to the specified URL, except using the specified port
 * @throws MalformedURLException if there is a problem creating the new URL
 *///w w w.ja va2  s .c o m
public static URL getUrlWithNewPort(final URL u, final int newPort) throws MalformedURLException {
    return createNewUrl(u.getProtocol(), u.getUserInfo(), u.getHost(), newPort, u.getPath(), u.getRef(),
            u.getQuery());
}

From source file:Main.java

public static List<Class<?>> getClassesForPackage(final String iPackageName, final ClassLoader iClassLoader)
        throws ClassNotFoundException {
    // This will hold a list of directories matching the pckgname.
    // There may be more than one if a package is split over multiple jars/paths
    List<Class<?>> classes = new ArrayList<Class<?>>();
    ArrayList<File> directories = new ArrayList<File>();
    try {//from w  ww  . java2  s . c o  m
        // Ask for all resources for the path
        final String packageUrl = iPackageName.replace('.', '/');
        Enumeration<URL> resources = iClassLoader.getResources(packageUrl);
        if (!resources.hasMoreElements()) {
            resources = iClassLoader.getResources(packageUrl + CLASS_EXTENSION);
            if (resources.hasMoreElements()) {
                throw new IllegalArgumentException(
                        iPackageName + " does not appear to be a valid package but a class");
            }
        } else {
            while (resources.hasMoreElements()) {
                URL res = resources.nextElement();
                if (res.getProtocol().equalsIgnoreCase("jar")) {
                    JarURLConnection conn = (JarURLConnection) res.openConnection();
                    JarFile jar = conn.getJarFile();
                    for (JarEntry e : Collections.list(jar.entries())) {

                        if (e.getName().startsWith(iPackageName.replace('.', '/'))
                                && e.getName().endsWith(CLASS_EXTENSION) && !e.getName().contains("$")) {
                            String className = e.getName().replace("/", ".").substring(0,
                                    e.getName().length() - 6);
                            classes.add(Class.forName(className));
                        }
                    }
                } else
                    directories.add(new File(URLDecoder.decode(res.getPath(), "UTF-8")));
            }
        }
    } catch (NullPointerException x) {
        throw new ClassNotFoundException(
                iPackageName + " does not appear to be " + "a valid package (Null pointer exception)");
    } catch (UnsupportedEncodingException encex) {
        throw new ClassNotFoundException(
                iPackageName + " does not appear to be " + "a valid package (Unsupported encoding)");
    } catch (IOException ioex) {
        throw new ClassNotFoundException(
                "IOException was thrown when trying " + "to get all resources for " + iPackageName);
    }

    // For every directory identified capture all the .class files
    for (File directory : directories) {
        if (directory.exists()) {
            // Get the list of the files contained in the package
            File[] files = directory.listFiles();
            for (File file : files) {
                if (file.isDirectory()) {
                    classes.addAll(findClasses(file, iPackageName));
                } else {
                    String className;
                    if (file.getName().endsWith(CLASS_EXTENSION)) {
                        className = file.getName().substring(0,
                                file.getName().length() - CLASS_EXTENSION.length());
                        classes.add(Class.forName(iPackageName + '.' + className));
                    }
                }
            }
        } else {
            throw new ClassNotFoundException(
                    iPackageName + " (" + directory.getPath() + ") does not appear to be a valid package");
        }
    }
    return classes;
}