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:com.splicemachine.mrio.api.SpliceTableMapReduceUtil.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.
 *
 * This is shamelessly copied from JobConf
 *
 * @param my_class the class to find./*from   www  . j  a v  a  2  s  .  c  o m*/
 * @return a jar file that contains the class, or null.
 * @throws IOException
 */
private static String findContainingJar(Class my_class) {
    ClassLoader loader = my_class.getClassLoader();
    String class_file = my_class.getName().replaceAll("\\.", "/") + ".class";
    try {
        for (Enumeration itr = loader.getResources(class_file); 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.aurel.track.dbase.InitReportTemplateBL.java

public static void addReportTemplates() {
    URL urlSrc;
    File srcDir = null;/*from   w  w w .  j a v a  2 s  .  c o m*/
    //first try to get the template dir through class.getResource(path)
    urlSrc = PluginUtils.class.getResource("/resources/reportTemplates");
    urlSrc = PluginUtils.createValidFileURL(urlSrc);
    if (urlSrc != null) {
        LOGGER.info("Retrieving report templates from " + urlSrc.toString());
        srcDir = new File(urlSrc.getPath());
        Long uuid = new Date().getTime();
        File tmpDir = new File(
                System.getProperty("java.io.tmpdir") + File.separator + "TrackTmp" + uuid.toString());
        if (!tmpDir.isDirectory()) {
            tmpDir.mkdir();
        }
        tmpDir.deleteOnExit();

        File[] files = srcDir.listFiles(new InitReportTemplateBL.Filter());
        if (files == null || files.length == 0) {
            LOGGER.error("Problem unzipping report template: No files.");
            return;
        }
        for (int index = 0; index < files.length; index++) {
            ZipFile zipFile = null;
            try {
                String sname = files[index].getName();
                String oid = sname.substring(sname.length() - 6, sname.length() - 4);
                zipFile = new ZipFile(files[index], ZipFile.OPEN_READ);
                LOGGER.debug("Extracting template from " + files[index].getName());
                unzipFileIntoDirectory(zipFile, tmpDir);

                File descriptor = new File(tmpDir, "description.xml");
                InputStream in = new FileInputStream(descriptor);
                //parse using builder to get DOM representation of the XML file
                Map<String, Object> desc = ReportBL.getTemplateDescription(in);

                String rname = "The name";
                String description = "The description";
                String expfmt = (String) desc.get("format");

                Map<String, String> localizedStuff = (Map<String, String>) desc
                        .get("locale_" + Locale.getDefault().getLanguage());
                if (localizedStuff != null) {
                    rname = localizedStuff.get("listing");
                    description = localizedStuff.get("description");
                } else {
                    localizedStuff = (Map<String, String>) desc.get("locale_en");
                    rname = localizedStuff.get("listing");
                    description = localizedStuff.get("description");
                }

                addReportTemplateToDatabase(new Integer(oid), rname, expfmt, description);

            } catch (IOException e) {
                LOGGER.error("Problem unzipping report template " + files[index].getName());
                LOGGER.debug(ExceptionUtils.getStackTrace(e));
            }
        }
    }
}

From source file:com.github.sakserv.minicluster.impl.KnoxLocalCluster.java

public static boolean copyResourcesRecursively( //
        final URL originUrl, final File destination) {
    try {//from ww  w .ja va  2 s .c  o m
        final URLConnection urlConnection = originUrl.openConnection();
        if (urlConnection instanceof JarURLConnection) {
            return copyJarResourcesRecursively(destination, (JarURLConnection) urlConnection);
        } else {
            return copyFilesRecusively(new File(originUrl.getPath()), destination);
        }
    } catch (final IOException e) {
        e.printStackTrace();
    }
    return false;
}

From source file:com.k42b3.aletheia.protocol.http.Util.java

/**
 * This method takes an base url and resolves the href to an url
 * /*w  w w .j a v a  2 s .  co m*/
 * @param baseUrl
 * @param href
 * @return string
 * @throws MalformedURLException
 */
public static String resolveHref(String baseUrl, String href) throws MalformedURLException {
    URL currentUrl = new URL(baseUrl);

    if (href.startsWith("http://") || href.startsWith("https://")) {
        // we have an absolute url
        return href;
    } else if (href.startsWith("//")) {
        return currentUrl.getProtocol() + ":" + href;
    } else if (href.startsWith("?")) {
        return currentUrl.getProtocol() + "://" + currentUrl.getHost() + currentUrl.getPath() + href;
    } else {
        // we have an path wich must be resolved to the base url
        String completePath;

        if (href.startsWith("/")) {
            completePath = href;
        } else {
            int pos = currentUrl.getPath().lastIndexOf('/');
            String path;

            if (pos != -1) {
                path = currentUrl.getPath().substring(0, pos);
            } else {
                path = currentUrl.getPath();
            }

            completePath = path + "/" + href;
        }

        // remove dot segments from path
        String path = removeDotSegments(completePath);

        // build url
        String url = currentUrl.getProtocol() + "://" + currentUrl.getHost() + path;

        // add query params
        int sPos, ePos;
        sPos = href.indexOf('?');

        if (sPos != -1) {
            String query;
            ePos = href.indexOf('#');

            if (ePos == -1) {
                query = href.substring(sPos + 1);
            } else {
                query = href.substring(sPos + 1, ePos);
            }

            if (!query.isEmpty()) {
                url += "?" + query;
            }
        }

        // add fragment
        sPos = href.indexOf('#');

        if (sPos != -1) {
            String fragment = href.substring(sPos + 1);

            if (!fragment.isEmpty()) {
                url += "#" + fragment;
            }
        }

        return url;
    }
}

From source file:net.pms.external.ExternalFactory.java

private static File url2file(URL url) {
    File f;//from   w w  w.  j a  va 2s.  c o m

    try {
        f = new File(url.toURI());
    } catch (URISyntaxException e) {
        f = new File(url.getPath());
    }

    return f;
}

From source file:sce.RESTAppMetricJob.java

public static URL convertToURLEscapingIllegalCharacters(String string) {
    try {//w w w  .jav a 2s .c om
        String decodedURL = URLDecoder.decode(string, "UTF-8");
        URL url = new URL(decodedURL);
        URI uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(),
                url.getQuery(), url.getRef());
        return uri.toURL();
    } catch (MalformedURLException | URISyntaxException | UnsupportedEncodingException e) {
        e.printStackTrace();
        return null;
    }
}

From source file:io.andyc.papercut.api.PrintApi.java

/**
 * Parses the final form submission HTMl and extracts the submit job url
 * which can be used to check the file upload status
 *
 * @param prevElement {Element} - the final file upload form HTML result
 *
 * @return {String} - the full URL used to check the status of the file
 * upload//from  w  ww  .j  a va2s . c  o  m
 */
static String getStatusCheckURL(Document prevElement, String baseDomain) throws MalformedURLException {

    Matcher match = PrintApi.statusPathPattern.matcher(prevElement.body().data());
    match.find();
    String printPathVariable = match.group();
    match = PrintApi.urlPattern.matcher(printPathVariable);
    match.find();
    String uploadId = match.group().replaceAll("\'", "");
    URL u = new URL(baseDomain);
    String url = baseDomain.replaceAll(u.getPath(), "");
    return url + "/rpc/web-print/job-status/" + uploadId + ".json";
}

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

/**
 * Devuelve un <tt>InputStream</tt> apuntando al <tt>resource</tt> que se ha localizado en el CLASSPATH.
 * <p>//from   w  w  w .  j av  a  2 s  . c  o  m
 * Primero se busca en el CLASSPATH asociado al Thread, luego en el ClassLoader, y por ltimo en el ClassLoader de
 * esta clase.
 * 
 * @param resource recurso que se quiere localizar en el CLASSPATH.
 * @return un <tt>InputStream</tt> apuntando al <tt>resource</tt> que se ha localizado en el CLASSPATH.
 *         <tt>null</tt> si no se ha encontrado.
 */
public static String searchInClasspath(String resource) {
    URL url = Thread.currentThread().getContextClassLoader().getResource(resource);
    if (url == null) {
        url = ClassLoader.getSystemResource(resource);
        if (url == null) {
            url = FileSystemUtils.class.getClassLoader().getResource(resource);
            if (url == null) {
                throw new MissingResourceException("Cannot find resource '" + resource + "' in none classpath",
                        FileSystemUtils.class.getName(), resource);
            }
        }
    }

    return url.getPath();
}

From source file:de.jlo.talendcomp.jasperrepo.RepositoryClient.java

public static String checkRepositoryUrl(String urlStr) {
    if (urlStr == null || urlStr.isEmpty()) {
        throw new IllegalArgumentException("url cannot be null or empty");
    }//from w w w.j a  v  a  2  s. c o m
    if (urlStr.endsWith(repositoryUrlPath)) {
        // everything is fine
        return urlStr;
    } else {
        // extract url parts
        try {
            URL url = new URL(urlStr);
            String host = url.getHost();
            String prot = url.getProtocol();
            int port = url.getPort();
            String path = url.getPath();
            if (path.length() > 1) {
                int pos = path.indexOf('/', 1);
                if (pos > 0) {
                    path = path.substring(0, pos);
                }
                path = path + repositoryUrlPath;
            } else {
                path = repositoryUrlPath;
            }
            StringBuilder newUrl = new StringBuilder();
            newUrl.append(prot);
            newUrl.append("://");
            newUrl.append(host);
            if (port > 0) {
                newUrl.append(":");
                newUrl.append(port);
            }
            newUrl.append(path);
            System.out.println("Given URL:" + urlStr + " changed to a repository URL:" + newUrl.toString());
            return newUrl.toString();
        } catch (MalformedURLException e) {
            throw new IllegalArgumentException("URL: " + urlStr + " is not valied:" + e.getMessage(), e);
        }
    }
}

From source file:com.vmware.aurora.global.Configuration.java

/**
 * /* ww w .  j a  va 2  s  .com*/
 * @return a memory view of all properties inside serengeti.properties and vc.properties
 */
private static PropertiesConfiguration init() {
    PropertiesConfiguration config = null;

    String homeDir = System.getProperties().getProperty("serengeti.home.dir");
    String ngcConfigFile = NGC_PROP_FILE;
    if (homeDir != null && homeDir.length() > 0) {
        StringBuilder builder = new StringBuilder();
        builder.append(homeDir).append(File.separator).append("conf").append(File.separator);
        configFileName = builder.toString() + "serengeti.properties";
        ngcConfigFile = builder.toString() + NGC_PROP_FILE;
    } else {
        configFileName = "serengeti.properties";
    }

    try {
        URL url = ConfigurationUtils.locate(null, configFileName);
        logger.info("Reading properties file serengeti.properties from " + url.getPath());
        serengetiCfg = new PropertiesConfiguration();
        serengetiCfg.setEncoding("UTF-8");
        serengetiCfg.setFileName(configFileName);
        serengetiCfg.load();
        config = (PropertiesConfiguration) serengetiCfg.clone();
    } catch (ConfigurationException ex) {
        String message = "Failed to load serengeti.properties file.";
        logger.fatal(message, ex);
        throw AuroraException.APP_INIT_ERROR(ex, message);
    }

    String propertyFilePrefix = System.getProperty("PROPERTY_FILE_PREFIX", "vc");
    String propertyFileName = propertyFilePrefix + ".properties";

    try {
        logger.info("Reading properties file " + propertyFileName);
        vcCfg = new PropertiesConfiguration(propertyFileName);
        Iterator<?> keys = vcCfg.getKeys();
        while (keys.hasNext()) {
            String key = (String) keys.next();
            config.setProperty(key, vcCfg.getProperty(key));
        }
    } catch (ConfigurationException ex) {
        // error out if the configuration file is not there
        String message = "Failed to load vc.properties file.";
        logger.fatal(message, ex);
        throw AuroraException.APP_INIT_ERROR(ex, message);
    }
    // load ngc_registrar.properties
    try {
        logger.info("Reading properties file " + ngcConfigFile);
        ngcCfg = new PropertiesConfiguration(ngcConfigFile);
        ngcCfg.setEncoding("UTF-8");
        Iterator<?> keys = ngcCfg.getKeys();
        while (keys.hasNext()) {
            String key = (String) keys.next();
            config.setProperty(key, ngcCfg.getProperty(key));
        }
    } catch (ConfigurationException ex) {
        // error out if the configuration file is not there
        String message = "Failed to load file " + NGC_PROP_FILE;
        logger.fatal(message, ex);
        throw AuroraException.APP_INIT_ERROR(ex, message);
    }

    logConfig(config);
    return config;
}