Example usage for java.net URL getProtocol

List of usage examples for java.net URL getProtocol

Introduction

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

Prototype

public String getProtocol() 

Source Link

Document

Gets the protocol name of this URL .

Usage

From source file:org.lightcouch.CouchDbUtil.java

/**
 * List directory contents for a resource folder. Not recursive. This is
 * basically a brute-force implementation. Works for regular files and also
 * JARs.//  w  w w .j  av  a  2 s  .  c  o  m
 * 
 * @author Greg Briggs
 * @param clazz
 *            Any java class that lives in the same place as the resources
 *            you want.
 * @param path
 *            Should end with "/", but not start with one.
 * @return Just the name of each member item, not the full paths.
 */
public static List<String> listResources(String path) {
    String fileURL = null;
    try {
        URL entry = Platform.getBundle("org.lightcouch").getEntry(path);
        File file = null;
        if (entry != null) {
            fileURL = FileLocator.toFileURL(entry).getPath();
            // remove leading slash from absolute path when on windows
            if (OSValidator.isWindows())
                fileURL = fileURL.substring(1, fileURL.length());
            file = new File(fileURL);
        }
        URL dirURL = file.toPath().toUri().toURL();

        if (dirURL != null && dirURL.getProtocol().equals("file")) {
            return Arrays.asList(new File(dirURL.toURI()).list());
        }
        if (dirURL != null && dirURL.getProtocol().equals("jar")) {
            String jarPath = dirURL.getPath().substring(5, dirURL.getPath().indexOf("!"));
            JarFile jar = new JarFile(URLDecoder.decode(jarPath, "UTF-8"));
            Enumeration<JarEntry> entries = jar.entries();
            Set<String> result = new HashSet<String>();
            while (entries.hasMoreElements()) {
                String name = entries.nextElement().getName();
                if (name.startsWith(path)) {
                    String entry1 = name.substring(path.length());
                    int checkSubdir = entry1.indexOf("/");
                    if (checkSubdir >= 0) {
                        entry1 = entry1.substring(0, checkSubdir);
                    }
                    if (entry1.length() > 0) {
                        result.add(entry1);
                    }
                }
            }
            return new ArrayList<String>(result);
        }
        return null;
    } catch (Exception e) {
        throw new CouchDbException("fileURL: " + fileURL, e);
    }
}

From source file:org.apache.jmeter.protocol.http.control.AuthManager.java

static boolean isSupportedProtocol(URL url) {
    String protocol = url.getProtocol().toLowerCase(java.util.Locale.ENGLISH);
    return protocol.equals(HTTPConstants.PROTOCOL_HTTP) || protocol.equals(HTTPConstants.PROTOCOL_HTTPS);
}

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

/**
 * Extracts the protocol from an URL./*from   w  w w .  jav  a 2s .  c o  m*/
 * @param url - the source URL
 * @return the protocol of the URL. In case that no protocol is found, {@link #FILE}
 *         is assumed.
 */
public static String extractProtocol(final URL url) {
    checkArgument(url != null, "Uninitialized URL");
    String protocol = url.getProtocol();
    if (isBlank(protocol)) {
        protocol = FILE;
    }
    return protocol;
}

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  va2s.  c  o  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:com.netflix.genie.web.controllers.ControllerUtils.java

/**
 * Given a HTTP {@code request} and a {@code path} this method will return the root of the request minus the path.
 * Generally the path will be derived from {@link #getRemainingPath(HttpServletRequest)} and this method will be
 * called subsequently./*from   w  w  w .  j  a va2 s.  c  om*/
 * <p>
 * If the request URL is {@code https://myhost/api/v3/jobs/12345/output/genie/run?myparam=4#BLAH} and the path is
 * {@code genie/run} this method should return {@code https://myhost/api/v3/jobs/12345/output/}.
 * <p>
 * All query parameters and references will be stripped off.
 *
 * @param request The HTTP request to get information from
 * @param path    The path that should be removed from the end of the request URL
 * @return The base of the request
 * @throws MalformedURLException If we're unable to create a new valid URL after removing the path
 * @since 4.0.0
 */
static URL getRequestRoot(final URL request, @Nullable final String path) throws MalformedURLException {
    final String currentPath = request.getPath();
    final String newPath = StringUtils.removeEnd(currentPath, path);
    return new URL(request.getProtocol(), request.getHost(), request.getPort(), newPath);
}

From source file:org.paxml.core.ResourceLocator.java

/**
 * Make an Spring resource string from relative path which contains
 * wildcards./*from  w  ww  .  ja  va2s  .  com*/
 * 
 * @param base
 *            the base Spring resource
 * @param relative
 *            the relative path
 * @return the absolute spring resource path
 */
public static String getRelativeResource(final Resource base, final String relative) {
    String result;
    // find from both class path and file system
    final boolean root = relative.startsWith("/") || relative.startsWith("\\");

    try {
        URL url = base.getURL();

        if (root) {
            result = url.getProtocol() + ":" + relative;
        } else {
            String path = FilenameUtils.getFullPathNoEndSeparator(url.getFile());
            result = url.getProtocol() + ":" + path + "/" + relative;
        }

    } catch (IOException e) {
        throw new PaxmlRuntimeException("Cannot get the relative path for plan file: " + base, e);
    }
    return result;
}

From source file:eu.planets_project.tb.impl.services.ServiceRegistryManager.java

/**
 * As the wsdlcontent is not well-formed we're not able to use DOM here.
 * Parse through the xml manually to return a list of given ServiceEndpointAddresses
 * @param xhtml// w  ww.j a  v  a2 s  .c o  m
 * @return
 * @throws Exception
 */
@Deprecated
private static Set<URI> extractEndpointsFromWebPage(String xhtml) {
    Set<URI> ret = new HashSet<URI>();

    // Pull out all matching URLs:
    Matcher matcher = urlpattern.matcher(xhtml);
    while (matcher.find()) {
        //log.info("Found match: "+matcher.group());
        try {
            URL wsdlUrl = new URL(matcher.group());
            // Switch the authority for the 'proper' one:
            wsdlUrl = new URL(wsdlUrl.getProtocol(), PlanetsServerConfig.getHostname(),
                    PlanetsServerConfig.getPort(), wsdlUrl.getFile());
            //log.info("Got matching URL: "+wsdlUrl);
            try {
                ret.add(wsdlUrl.toURI());
            } catch (URISyntaxException e) {
            }
        } catch (MalformedURLException e) {
            log.warn("Could not parse URL from " + matcher.group());
        }
    }

    return ret;
}

From source file:com.google.gerrit.server.documentation.MarkdownFormatter.java

private static String readPegdownCss(AtomicBoolean file) throws IOException {
    String name = "pegdown.css";
    URL url = MarkdownFormatter.class.getResource(name);
    if (url == null) {
        throw new FileNotFoundException("Resource " + name);
    }/*  w  w  w. j  a  v  a 2  s.  co m*/
    file.set("file".equals(url.getProtocol()));
    try (InputStream in = url.openStream(); TemporaryBuffer.Heap tmp = new TemporaryBuffer.Heap(128 * 1024)) {
        tmp.copy(in);
        return new String(tmp.toByteArray(), UTF_8);
    }
}

From source file:net.dataforte.commons.resources.ClassUtils.java

/**
 * Returns all classes within the specified package. Supports filesystem, JARs and JBoss VFS
 * //from w  w  w  .jav  a 2 s  . com
 * @param folder
 * @return
 * @throws IOException
 */
public static Class<?>[] getClassesForPackage(String pckgname) 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 {
        ClassLoader cld = Thread.currentThread().getContextClassLoader();
        if (cld == null) {
            throw new ClassNotFoundException("Can't get class loader.");
        }
        // Ask for all resources for the path
        Enumeration<URL> resources = cld.getResources(pckgname.replace('.', '/'));
        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(pckgname.replace('.', '/')) && e.getName().endsWith(".class")
                            && !e.getName().contains("$")) {
                        String className = e.getName().replace("/", ".").substring(0, e.getName().length() - 6);
                        classes.add(Class.forName(className, true, cld));
                    }
                }
            } else if (res.getProtocol().equalsIgnoreCase("vfszip")) { // JBoss 5+
                try {
                    Object content = res.getContent();
                    Method getChildren = content.getClass().getMethod("getChildren");
                    List<?> files = (List<?>) getChildren.invoke(res.getContent());
                    Method getPathName = null;
                    for (Object o : files) {
                        if (getPathName == null) {
                            getPathName = o.getClass().getMethod("getPathName");
                        }
                        String pathName = (String) getPathName.invoke(o);
                        if (pathName.endsWith(".class")) {
                            String className = pathName.replace("/", ".").substring(0, pathName.length() - 6);
                            classes.add(Class.forName(className, true, cld));
                        }
                    }
                } catch (Exception e) {
                    throw new IOException("Error while scanning " + res.toString(), e);
                }
            } else {
                directories.add(new File(URLDecoder.decode(res.getPath(), "UTF-8")));
            }
        }
    } catch (NullPointerException x) {
        throw new ClassNotFoundException(
                pckgname + " does not appear to be a valid package (Null pointer exception)", x);
    } catch (UnsupportedEncodingException encex) {
        throw new ClassNotFoundException(
                pckgname + " does not appear to be a valid package (Unsupported encoding)", encex);
    } catch (IOException ioex) {
        throw new ClassNotFoundException(
                "IOException was thrown when trying to get all resources for " + pckgname, ioex);
    }

    // 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
            String[] files = directory.list();
            for (String file : files) {
                // we are only interested in .class files
                if (file.endsWith(".class")) {
                    // removes the .class extension
                    classes.add(Class.forName(pckgname + '.' + file.substring(0, file.length() - 6)));
                }
            }
        } else {
            throw new ClassNotFoundException(
                    pckgname + " (" + directory.getPath() + ") does not appear to be a valid package");
        }
    }
    Class<?>[] classesA = new Class[classes.size()];
    classes.toArray(classesA);
    return classesA;
}

From source file:com.fengduo.bee.commons.core.lang.ClassLoaderUtils.java

public static List<?> load(String classpath, ClassFilter filter) throws Exception {
    List<Object> objs = new ArrayList<Object>();
    URL resource = ClassLoaderUtils.class.getClassLoader().getResource(classpath);
    logger.debug("Search from {} ...", resource.getPath());
    List<String> classnameArray;
    if ("jar".equalsIgnoreCase(resource.getProtocol())) {
        String file = resource.getFile();
        String jarName = file.substring(file.indexOf("/"), (file.lastIndexOf("jar") + 3));
        classnameArray = getClassNamesInPackage(jarName, classpath);
    } else {/*from  w w  w .ja  v  a2 s  . c o  m*/
        Collection<File> listFiles = FileUtils.listFiles(new File(resource.getPath()), null, false);
        String classNamePrefix = classpath.replaceAll("/", ".");
        classnameArray = new ArrayList<String>();
        for (File file : listFiles) {
            String name = file.getName();
            if (name.endsWith(".class") == false) {
                continue;
            }
            if (StringUtils.contains(name, '$')) {
                logger.warn("NOT SUPPORT INNERT CLASS" + file.getAbsolutePath());
                continue;
            }
            String classname = classNamePrefix + "." + StringUtils.remove(name, ".class");
            classnameArray.add(classname);
        }
    }

    for (String classname : classnameArray) {
        try {
            Class<?> loadClass = ClassLoaderUtils.class.getClassLoader().loadClass(classname);
            if (filter != null && !filter.filter(loadClass)) {
                logger.error("{}  {} ", classname, filter);
                continue;
            }
            // if (ClassLoaderUtil.class.isAssignableFrom(loadClass) == false) {
            // logger.error("{} ?????", classname);
            // continue;
            // }
            Object newInstance = loadClass.newInstance();
            objs.add(newInstance);
            logger.debug("load {}/{}.class success", resource.getPath(), classname);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("load " + resource.getPath() + "/" + classname + ".class failed", e);
        }
    }
    return objs;
}