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:eu.sisob.uma.footils.File.FileFootils.java

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

From source file:de.betterform.agent.web.WebUtil.java

/**
 * this method is responsible for passing all context information needed by the Adapter and Processor from
 * ServletRequest to Context. Will be called only once when the form-session is inited (GET).
 * <p/>//  ww  w . j  a  va  2  s .c om
 * <p/>
 * todo: better logging of context params
 *
 * @param request     the Servlet request to fetch params from
 * @param httpSession the Http Session context
 * @param processor   the XFormsProcessor which receives the context params
 * @param sessionkey  the key to identify the XFormsSession
 */
public static void setContextParams(HttpServletRequest request, HttpSession httpSession,
        XFormsProcessor processor, String sessionkey) throws XFormsConfigException {
    Map servletMap = new HashMap();
    servletMap.put(WebProcessor.SESSION_ID, sessionkey);
    processor.setContextParam(XFormsProcessor.SUBMISSION_RESPONSE, servletMap);

    //adding requestURI to context
    processor.setContextParam(WebProcessor.REQUEST_URI, WebUtil.getRequestURI(request));

    //adding request URL to context
    String requestURL = request.getRequestURL().toString();
    processor.setContextParam(WebProcessor.REQUEST_URL, requestURL);

    // the web app name with an '/' prepended e.g. '/betterform' by default
    String contextRoot = WebUtil.getContextRoot(request);
    processor.setContextParam(WebProcessor.CONTEXTROOT, contextRoot);
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("context root of webapp: " + processor.getContextParam(WebProcessor.CONTEXTROOT));
    }

    String requestPath = "";
    URL url = null;
    String plainPath = "";
    try {
        url = new URL(requestURL);
        requestPath = url.getPath();
    } catch (MalformedURLException e) {
        e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
    }
    if (requestPath.length() != 0) {
        //adding request path e.g. '/betterform/forms/demo/registration.xhtml'
        processor.setContextParam(WebProcessor.REQUEST_PATH, requestPath);

        //adding filename of requested doc to context
        String fileName = requestPath.substring(requestPath.lastIndexOf('/') + 1, requestPath.length());//FILENAME xforms
        processor.setContextParam(FILENAME, fileName);

        if (requestURL.contains(contextRoot)) { //case1: contextRoot is a part of the URL
            //adding plainPath which is the part between contextroot and filename e.g. '/forms' for a requestPath of '/betterform/forms/Status.xhtml'
            plainPath = requestPath.substring(contextRoot.length() + 1,
                    requestPath.length() - fileName.length());
            processor.setContextParam(PLAIN_PATH, plainPath);
        } else {//case2: contextRoot is not a part of the URL take the part previous the filename.
            String[] urlParts = requestURL.split("/");
            plainPath = urlParts[urlParts.length - 2];
        }

        //adding contextPath - requestPath without the filename
        processor.setContextParam(CONTEXT_PATH, contextRoot + "/" + plainPath);
    }

    //adding session id to context
    processor.setContextParam(HTTP_SESSION_ID, httpSession.getId());
    //adding context absolute path to context

    //EXIST-WORKAROUND: TODO triple check ...
    //TODO: triple check where this is used.
    if (request.isRequestedSessionIdValid()) {
        processor.setContextParam(EXISTDB_USER, httpSession.getAttribute(EXISTDB_USER));
    }

    //adding pathInfo to context - attention: this is only available when a servlet is requested
    String s1 = request.getPathInfo();
    if (s1 != null) {
        processor.setContextParam(WebProcessor.PATH_INFO, s1);
    }
    processor.setContextParam(WebProcessor.QUERY_STRING,
            (request.getQueryString() != null ? request.getQueryString() : ""));

    //storing the realpath for webapp

    String realPath = WebFactory.getRealPath(".", httpSession.getServletContext());
    File f = new File(realPath);
    URI fileURI = f.toURI();

    processor.setContextParam(WebProcessor.REALPATH, fileURI.toString());
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("real path of webapp: " + realPath);
    }

    //storing the TransformerService
    processor.setContextParam(TransformerService.TRANSFORMER_SERVICE,
            httpSession.getServletContext().getAttribute(TransformerService.TRANSFORMER_SERVICE));
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("TransformerService: "
                + httpSession.getServletContext().getAttribute(TransformerService.TRANSFORMER_SERVICE));
    }

    //[2] read any request params that are *not* betterForm params and pass them into the context map
    Enumeration params = request.getParameterNames();
    String s;
    while (params.hasMoreElements()) {
        s = (String) params.nextElement();
        //store all request-params we don't use in the context map of XFormsProcessorImpl
        String value = request.getParameter(s);
        processor.setContextParam(s, value);
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("added request param '" + s + "' added to context");
            LOGGER.debug("param value'" + value);
        }
    }

}

From source file:com.gargoylesoftware.htmlunit.html.HtmlAnchor.java

/**
 * <span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span><br>
 *
 * @param href the href// ww  w . j a va 2  s .co  m
 * @param page the HtmlPage
 * @return the calculated target url.
 * @throws MalformedURLException if an IO error occurs
 */
public static URL getTargetUrl(final String href, final HtmlPage page) throws MalformedURLException {
    URL url = page.getFullyQualifiedUrl(href);
    // fix for empty url
    if (StringUtils.isEmpty(href)) {
        final boolean dropFilename = page.getWebClient().getBrowserVersion()
                .hasFeature(ANCHOR_EMPTY_HREF_NO_FILENAME);
        if (dropFilename) {
            String path = url.getPath();
            path = path.substring(0, path.lastIndexOf('/') + 1);
            url = UrlUtils.getUrlWithNewPath(url, path);
            url = UrlUtils.getUrlWithNewRef(url, null);
        } else {
            url = UrlUtils.getUrlWithNewRef(url, null);
        }
    }
    return url;
}

From source file:gov.nasa.ensemble.common.io.FileUtilities.java

/**
 * Copy the entries specified from the bundle provided to the metadata area for the bundle provided, and return the URL for the metadata area for this bundle.
 * /* w  ww.j a  v a 2s.  c om*/
 * @param bundle
 * @param path
 * @param filePattern
 * @param recurse
 * @return URL
 * @throws IOException
 */
public static URL copyToMetadata(Bundle bundle, String path, String filePattern, boolean recurse)
        throws IOException {
    Location instanceLocation = Platform.getInstanceLocation();
    URL dataArea = getDataArea(instanceLocation, bundle.getSymbolicName());
    Enumeration entries = bundle.findEntries(path, filePattern, recurse);
    while (entries.hasMoreElements()) {
        URL entry = (URL) entries.nextElement();
        String entryPath = entry.getPath();
        try {
            InputStream inputStream = FileLocator.openStream(bundle, new Path(entryPath), false);
            URI dataURI = dataArea.toURI();
            URI fullPath = URI.create(dataURI.toString() + entryPath);
            File file = new File(fullPath);
            if (!file.exists()) {
                file.getParentFile().mkdirs();
                file.createNewFile();
            }
            FileOutputStream outputStream = new FileOutputStream(file);
            IOUtils.copy(inputStream, outputStream);
            outputStream.close();
        } catch (Exception e) {
            // skip this one
        }
    }
    return dataArea;
}

From source file:crow.weibo.util.WeiboUtil.java

/**
 * ?URL,URL Path URL ???//w w w.j a va2  s  .  c om
 * 
 * @param url
 * @return
 */
public static String getNormalizedUrl(String url) {
    try {
        URL ul = new URL(url);
        StringBuilder buf = new StringBuilder();
        buf.append(ul.getProtocol());
        buf.append("://");
        buf.append(ul.getHost());
        if ((ul.getProtocol().equals("http") || ul.getProtocol().equals("https")) && ul.getPort() != -1) {
            buf.append(":");
            buf.append(ul.getPort());
        }
        buf.append(ul.getPath());
        return buf.toString();
    } catch (Exception e) {
    }
    return null;
}

From source file:org.unitedinternet.cosmo.dav.caldav.report.MultigetReport.java

private static URL normalizeHref(URL context, String href) throws CosmoDavException {
    URL url = null;/* www  .  j  a  va 2s.c  o  m*/
    try {
        url = new URL(context, href);
        // check that the URL is escaped. it's questionable whether or
        // not we should all unescaped URLs, but at least as of
        // 10/02/2007, iCal 3.0 generates them
        url.toURI();
        return url;
    } catch (URISyntaxException e) {
        try {
            URI escaped = new URI(url.getProtocol(), url.getAuthority(), url.getPath(), url.getQuery(),
                    url.getRef());
            return new URL(escaped.toString());
        } catch (URISyntaxException | MalformedURLException e2) {
            throw new BadRequestException("Malformed unescaped href " + href + ": " + e.getMessage());
        }
    } catch (MalformedURLException e) {
        throw new BadRequestException("Malformed href " + href + ": " + e.getMessage());
    }
}

From source file:org.mrgeo.utils.HadoopUtils.java

public static String findContainingJar(Class clazz) {
    ClassLoader loader = clazz.getClassLoader();
    String classFile = clazz.getName().replaceAll("\\.", "/") + ".class";
    try {/*  w ww. j  a  va 2s.  c om*/
        for (Enumeration 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());
                }
                //toReturn = URLDecoder.decode(toReturn, "UTF-8");
                return toReturn.replaceAll("!.*$", "");
            }
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    return null;
}

From source file:de.betterform.agent.web.WebFactory.java

/**
 * get the absolute file path for a given relative path in the webapp. Handles some differences in server behavior
 * with the execution of context.getRealPath on various servers/operating systems
 *
 * @param path    a path relative to the context root of the webapp
 * @param context the servletcontext/*  w ww  .  j  av  a 2 s  . co  m*/
 * @return the absolute file path for given relative webapp path
 */
public static String getRealPath(String path, ServletContext context) throws XFormsConfigException {
    if (path == null) {
        path = "/";
    }
    if (!path.startsWith("/")) {
        path = "/" + path;
    }
    try {
        URI resourceURI = null;
        String computedRealPath = null;
        URL rootURL = Thread.currentThread().getContextClassLoader().getResource("/");
        URL resourceURL = context.getResource(path);

        if (rootURL != null) {
            resourceURI = rootURL.toURI();
        }

        if (resourceURI != null && resourceURI.getScheme().equalsIgnoreCase("file")) {
            String resourcePath = rootURL.getPath();
            String rootPath = new File(resourcePath).getParentFile().getParent();
            computedRealPath = new File(rootPath, path).getAbsolutePath();
        } else if (resourceURL != null) {
            computedRealPath = new File(resourceURL.toExternalForm(), path).getAbsolutePath();
        } else {
            String resourcePath = context.getRealPath("/");
            computedRealPath = new File(resourcePath, path).getAbsolutePath();
        }
        return java.net.URLDecoder.decode(computedRealPath, StandardCharsets.UTF_8.name());
    } catch (UnsupportedEncodingException e) {
        throw new XFormsConfigException("path could not be resolved: " + path, e);
    } catch (URISyntaxException e) {
        throw new XFormsConfigException("path could not be resolved: " + path, e);
    } catch (MalformedURLException e) {
        throw new XFormsConfigException("path could not be resolved: " + path, e);
    }
}

From source file:it.geosolutions.geostore.core.security.password.URLMasterPasswordProvider.java

static InputStream input(URL url, File configDir) throws IOException {
    //check for a file url
    if (url == null) {
        //default master password
        url = URLMasterPasswordProvider.class.getClassLoader().getResource("passwd");
    }//from www . j a  v  a2  s .  c o m
    if ("file".equalsIgnoreCase(url.getProtocol())) {
        File f;
        try {
            f = new File(url.toURI());
        } catch (URISyntaxException e) {
            f = new File(url.getPath());
        }

        //check if the file is relative
        if (!f.isAbsolute()) {
            //make it relative to the config directory for this password provider
            f = new File(configDir, f.getPath());
        }
        return new FileInputStream(f);
    } else {
        return url.openStream();
    }
}

From source file:URLUtil.java

/**
 * Method that tries to get a stream (ideally, optimal one) to read from the
 * specified URL. Currently it just means creating a simple file input stream
 * if the URL points to a (local) file, and otherwise relying on URL classes
 * input stream creation method./*from w w w .  j  a  va2  s  .c o m*/
 */
public static InputStream inputStreamFromURL(URL url) throws IOException {
    if ("file".equals(url.getProtocol())) {
        /*
         * As per [WSTX-82], can not do this if the path refers to a network drive
         * on windows. This fixes the problem; might not be needed on all
         * platforms (NFS?), but should not matter a lot: performance penalty of
         * extra wrapping is more relevant when accessing local file system.
         */
        String host = url.getHost();
        if (host == null || host.length() == 0) {
            return new FileInputStream(url.getPath());
        }
    }
    return url.openStream();
}