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:Main.java

public static void unzip(URL _url, URL _dest, boolean _remove_top) {
    int BUFFER_SZ = 2048;
    File file = new File(_url.getPath());

    String dest = _dest.getPath();
    new File(dest).mkdir();

    try {/*from  ww w.  j  a  va2  s  . c om*/
        ZipFile zip = new ZipFile(file);
        Enumeration<? extends ZipEntry> zipFileEntries = zip.entries();

        // Process each entry
        while (zipFileEntries.hasMoreElements()) {
            // grab a zip file entry
            ZipEntry entry = (ZipEntry) zipFileEntries.nextElement();
            String currentEntry = entry.getName();

            if (_remove_top)
                currentEntry = currentEntry.substring(currentEntry.indexOf('/'), currentEntry.length());

            File destFile = new File(dest, currentEntry);
            //destFile = new File(newPath, destFile.getName());
            File destinationParent = destFile.getParentFile();

            // create the parent directory structure if needed
            destinationParent.mkdirs();

            if (!entry.isDirectory()) {
                BufferedInputStream is;
                is = new BufferedInputStream(zip.getInputStream(entry));
                int currentByte;
                // establish buffer for writing file
                byte data[] = new byte[BUFFER_SZ];

                // write the current file to disk
                FileOutputStream fos = new FileOutputStream(destFile);
                BufferedOutputStream dst = new BufferedOutputStream(fos, BUFFER_SZ);

                // read and write until last byte is encountered
                while ((currentByte = is.read(data, 0, BUFFER_SZ)) != -1) {
                    dst.write(data, 0, currentByte);
                }
                dst.flush();
                dst.close();
                is.close();
            }
            /*
            if (currentEntry.endsWith(".zip"))
            {
            // found a zip file, try to open
            extractFolder(destFile.getAbsolutePath());
            }*/
        }
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

From source file:com.vaadin.testbench.testutils.ImageLoader.java

public static File getImageFile(String folder, String filename) {
    URL imgUrl = ImageLoader.class.getClassLoader().getResource(folder + "/" + filename);
    assertNotNull("Missing reference " + filename, imgUrl);
    File imgFile = new File(imgUrl.getPath());
    return imgFile;
}

From source file:com.jaeksoft.searchlib.util.LinkUtils.java

public final static URI newEncodedURI(String u) throws MalformedURLException, URISyntaxException {
    URL tmpUrl = new URL(u);
    return new URI(tmpUrl.getProtocol(), tmpUrl.getUserInfo(), tmpUrl.getHost(), tmpUrl.getPort(),
            tmpUrl.getPath(), tmpUrl.getQuery(), tmpUrl.getRef());
}

From source file:com.ericsson.eiffel.remrem.generate.EiffelRemremControllerIntegrationTest.java

public static String getMessagingVersion() {
    Enumeration resEnum;//  ww  w .j ava  2 s  . c o m
    try {
        resEnum = Thread.currentThread().getContextClassLoader().getResources(JarFile.MANIFEST_NAME);
        while (resEnum.hasMoreElements()) {
            try {
                URL url = (URL) resEnum.nextElement();
                if (url.getPath().contains("eiffel-remrem-semantics")) {
                    InputStream is = url.openStream();
                    if (is != null) {
                        Manifest manifest = new Manifest(is);
                        Attributes mainAttribs = manifest.getMainAttributes();
                        String version = mainAttribs.getValue("semanticsVersion");
                        if (version != null) {
                            return version;
                        }
                    }
                }
            } catch (Exception e) {
                // Silently ignore wrong manifests on classpath?
            }
        }
    } catch (IOException e1) {
        // Silently ignore wrong manifests on classpath?
    }
    return null;
}

From source file:Main.java

public static String getFileName(String extUrl) {
    URL url = null;
    String path = extUrl;//from  w w  w.j a  v  a 2s .  c  om
    try {
        url = new URL(extUrl);
        path = url.getPath();
    } catch (MalformedURLException e) {
        path = extUrl;
    }
    String filename = "";
    String[] pathContents = path.split("[\\\\/]");
    if (pathContents != null) {
        int pathContentsLength = pathContents.length;
        System.out.println("Path Contents Length: " + pathContentsLength);
        String lastPart = pathContents[pathContentsLength - 1];
        String[] lastPartContents = lastPart.split("\\.");
        if (lastPartContents != null && lastPartContents.length > 1) {
            int lastPartContentLength = lastPartContents.length;
            String name = "";
            for (int i = 0; i < lastPartContentLength; i++) {
                if (i < (lastPartContents.length - 1)) {
                    name += lastPartContents[i];
                    if (i < (lastPartContentLength - 2)) {
                        name += ".";
                    }
                }
            }
            String extension = lastPartContents[lastPartContentLength - 1];
            filename = name + "." + extension;
        }
    }
    return filename;
}

From source file:com.cloudera.sqoop.util.Jars.java

/**
 * Return the jar file path that contains a particular class.
 * Method mostly cloned from o.a.h.mapred.JobConf.findContainingJar().
 *///  w ww. j a v a 2  s  . c  o  m
public static String getJarPathForClass(Class<? extends Object> classObj) {
    ClassLoader loader = classObj.getClassLoader();
    String classFile = classObj.getName().replaceAll("\\.", "/") + ".class";
    try {
        for (Enumeration<URL> itr = loader.getResources(classFile); itr.hasMoreElements();) {
            URL 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("!.*$", "");
            }
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    return null;
}

From source file:com.moki.touch.util.UrlUtil.java

/**
 * This method determines if we are able to download a vimeo video from the current url
 * @param url a url that redirects to a vimeo video
 * @return true if it is a downloadable vimeo link
 *//*from w ww.j ava  2 s. co  m*/
public static boolean isCachebleVimeoLink(String url) {
    boolean isDownloadableVimeoLink = false;
    try {
        URL vimeoUrl = new URL(url);
        isDownloadableVimeoLink = vimeoUrl.getHost().contains("vimeo")
                && vimeoUrl.getPath().contains("download");
    } catch (MalformedURLException e) {
        Log.i(UrlUtil.class.getSimpleName(), "url passed to isCacheblevimeoLink was malformed");
    }
    return isDownloadableVimeoLink;
}

From source file:in.flipbrain.Utils.java

public static String getVideoId(String url) throws MalformedURLException {
    URL u = new URL(url);
    String host = u.getHost();//w  w  w  .j  a  v  a2  s  .c  om
    if (host.equals("youtu.be")) {
        return u.getPath();
    } else if (host.equals("www.youtube.com")) {
        String path = u.getPath();
        if (path.contains("embed")) {
            return path.substring(path.indexOf("/"));
        } else {
            String query = u.getQuery();
            String[] parts = query.split("&");
            for (String p : parts) {
                if (p.startsWith("v=")) {
                    return p.substring(2);
                }
            }
        }
    }
    return null;
}

From source file:fll.web.WebTestUtils.java

public static WebClient getConversation() throws IOException, SAXException {
    final WebClient conversation = new WebClient();

    // always login first
    final Page loginPage = conversation.getPage(TestUtils.URL_ROOT + "login.jsp");
    Assert.assertTrue("Received non-HTML response from web server", loginPage.isHtmlPage());

    final HtmlPage loginHtml = (HtmlPage) loginPage;
    HtmlForm form = loginHtml.getFormByName("login");
    Assert.assertNotNull("Cannot find login form", form);

    final HtmlTextInput userTextField = form.getInputByName("user");
    userTextField.setValueAttribute(IntegrationTestUtils.TEST_USERNAME);

    final HtmlPasswordInput passTextField = form.getInputByName("pass");
    passTextField.setValueAttribute(IntegrationTestUtils.TEST_PASSWORD);

    final HtmlSubmitInput button = form.getInputByName("submit_login");
    final Page response = button.click();

    final URL responseURL = response.getUrl();
    final String address = responseURL.getPath();
    final boolean correctAddress;
    if (address.contains("login.jsp")) {
        correctAddress = false;// www.j  ava2s. com
    } else {
        correctAddress = true;
    }
    Assert.assertTrue("Unexpected URL after login: " + address, correctAddress);

    return conversation;
}

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 ww  w.j a v a 2s .c om
        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;
}