Example usage for java.net URI getRawPath

List of usage examples for java.net URI getRawPath

Introduction

In this page you can find the example usage for java.net URI getRawPath.

Prototype

public String getRawPath() 

Source Link

Document

Returns the raw path component of this URI.

Usage

From source file:org.gss_project.gss.server.rest.FilesHandler.java

/**
 * A helper method that extracts the relative resource path,
 * after removing the 'files' namespace.
 * The path returned is <i>not</i> URL-decoded.
 *
 * @param req the HTTP request/*from  w w w  .  j  a va 2 s .  co m*/
 * @param path the specified path
 * @return the path relative to the root folder
 * @throws URISyntaxException
 * @throws RpcException in case an error occurs while communicating
 *                   with the backend
 * @throws UnsupportedEncodingException
 */
private String getDestinationPath(HttpServletRequest req, String path)
        throws URISyntaxException, RpcException, UnsupportedEncodingException {
    URI uri = new URI(path);
    String dest = uri.getRawPath();
    // Remove the context path from the destination URI.
    String contextPath = req.getContextPath();
    if (!dest.startsWith(contextPath))
        throw new URISyntaxException(dest, "Destination path does not start with " + contextPath);
    dest = dest.substring(contextPath.length());
    // Remove the servlet path from the destination URI.
    String servletPath = req.getServletPath();
    if (!dest.startsWith(servletPath))
        throw new URISyntaxException(dest, "Destination path does not start with " + servletPath);
    dest = dest.substring(servletPath.length());
    // Strip the username part
    if (dest.length() < 2)
        throw new URISyntaxException(dest, "No username in the destination URI");
    int slash = dest.substring(1).indexOf('/');
    if (slash == -1)
        throw new URISyntaxException(dest, "No username in the destination URI");
    // Decode the user to get the proper characters (mainly the @)
    String owner = URLDecoder.decode(dest.substring(1, slash + 1), "UTF-8");
    User o;
    o = getService().findUser(owner);
    if (o == null)
        throw new URISyntaxException(dest, "User " + owner + " not found");

    req.setAttribute(DESTINATION_OWNER_ATTRIBUTE, o);
    dest = dest.substring(slash + 1);

    // Chop the resource namespace part
    dest = dest.substring(RequestHandler.PATH_FILES.length());

    dest = dest.endsWith("/") ? dest : dest + '/';
    return dest;
}

From source file:com.groupon.odo.bmp.http.BrowserMobHttpClient.java

private URI makeUri(String url) throws URISyntaxException {
    // MOB-120: check for | character and change to correctly escaped %7C
    url = url.replace(" ", "%20");
    url = url.replace(">", "%3C");
    url = url.replace("<", "%3E");
    url = url.replace("#", "%23");
    url = url.replace("{", "%7B");
    url = url.replace("}", "%7D");
    url = url.replace("|", "%7C");
    url = url.replace("\\", "%5C");
    url = url.replace("^", "%5E");
    url = url.replace("~", "%7E");
    url = url.replace("[", "%5B");
    url = url.replace("]", "%5D");
    url = url.replace("`", "%60");
    url = url.replace("\"", "%22");

    URI uri = new URI(url);

    // are we using the default ports for http/https? if so, let's rewrite the URI to make sure the :80 or :443
    // is NOT included in the string form the URI. The reason we do this is that in HttpClient 4.0 the Host header
    // would include a value such as "yahoo.com:80" rather than "yahoo.com". Not sure why this happens but we don't
    // want it to, and rewriting the URI solves it
    if ((uri.getPort() == 80 && "http".equals(uri.getScheme()))
            || (uri.getPort() == 443 && "https".equals(uri.getScheme()))) {
        // we rewrite the URL with a StringBuilder (vs passing in the components of the URI) because if we were
        // to pass in these components using the URI's 7-arg constructor query parameters get double escaped (bad!)
        StringBuilder sb = new StringBuilder(uri.getScheme()).append("://");
        if (uri.getRawUserInfo() != null) {
            sb.append(uri.getRawUserInfo()).append("@");
        }/*from  w  w w .java  2s. co m*/
        sb.append(uri.getHost());
        if (uri.getRawPath() != null) {
            sb.append(uri.getRawPath());
        }
        if (uri.getRawQuery() != null) {
            sb.append("?").append(uri.getRawQuery());
        }
        if (uri.getRawFragment() != null) {
            sb.append("#").append(uri.getRawFragment());
        }

        uri = new URI(sb.toString());
    }
    return uri;
}

From source file:org.kitodo.production.services.data.ProcessService.java

/**
 * Get directory for TIFF images.// w  w  w  . j  a  va2  s.  c  o m
 *
 * @param useFallBack
 *            add description
 * @param processId
 *            id of process object
 * @param processTitle
 *            title of process object
 * @param processBaseURI
 *            base URI of process object
 * @return tif directory
 */
public URI getImagesTifDirectory(boolean useFallBack, Integer processId, String processTitle,
        URI processBaseURI) {
    URI dir = fileService.getProcessSubTypeURI(processId, processTitle, processBaseURI, ProcessSubType.IMAGE,
            null);

    /* nur die _tif-Ordner anzeigen, die nicht mir orig_ anfangen */
    FilenameFilter filterDirectory = new FileNameEndsAndDoesNotBeginWithFilter(DIRECTORY_PREFIX + "_",
            "_" + DIRECTORY_SUFFIX);
    URI tifDirectory = null;
    List<URI> directories = fileService.getSubUris(filterDirectory, dir);
    for (URI directory : directories) {
        tifDirectory = directory;
    }

    if (Objects.isNull(tifDirectory) && useFallBack && !SUFFIX.isEmpty()) {
        List<URI> folderList = fileService.getSubUrisForProcess(null, processId, processTitle, processBaseURI,
                ProcessSubType.IMAGE, "");
        for (URI folder : folderList) {
            if (folder.toString().endsWith(SUFFIX)) {
                tifDirectory = folder;
                break;
            }
        }
    }

    tifDirectory = getImageDirectory(useFallBack, dir, tifDirectory);

    URI result = fileService.getProcessSubTypeURI(processId, processTitle, processBaseURI, ProcessSubType.IMAGE,
            null);

    if (Objects.isNull(tifDirectory)) {
        tifDirectory = URI
                .create(result.getRawPath() + Helper.getNormalizedTitle(processTitle) + "_" + DIRECTORY_SUFFIX);
    }

    return tifDirectory;
}

From source file:org.dasein.cloud.atmos.AtmosMethod.java

private @Nonnull String toSignatureString(@Nonnull HttpRequestBase method, @Nonnull String contentType,
        @Nonnull String range, @Nonnull String date, @Nonnull URI resource, @Nonnull List<Header> emcHeaders) {
    StringBuilder emcHeaderString = new StringBuilder();

    TreeSet<String> sorted = new TreeSet<String>();

    for (Header header : emcHeaders) {
        sorted.add(header.getName().toLowerCase());
    }//  ww  w .j a  va2  s.  c  o  m
    boolean first = true;
    for (String headerName : sorted) {
        for (Header header : emcHeaders) {
            if (header.getName().toLowerCase().equals(headerName)) {
                if (!first) {
                    emcHeaderString.append("\n");
                } else {
                    first = false;
                }
                String val = header.getValue();

                if (val == null) {
                    val = "";
                }
                emcHeaderString.append(headerName);
                emcHeaderString.append(":");
                StringBuilder tmp = new StringBuilder();
                for (char c : val.toCharArray()) {
                    if (Character.isWhitespace(c)) {
                        tmp.append(" ");
                    } else {
                        tmp.append(c);
                    }
                }
                val = tmp.toString();
                while (val.contains("  ")) {
                    val = val.replaceAll("  ", " ");
                }
                emcHeaderString.append(val);
            }
        }
    }
    String path = resource.getRawPath().toLowerCase();

    if (resource.getRawQuery() != null) {
        path = path + "?" + resource.getRawQuery().toLowerCase();
    }

    return (method.getMethod() + "\n" + contentType + "\n" + range + "\n" + date + "\n" + path + "\n"
            + emcHeaderString.toString());
}

From source file:org.jets3t.service.impl.rest.httpclient.RestStorageService.java

/**
 * Authorizes an HTTP/S request by signing it with an HMAC signature compatible with
 * the S3 service and Google Storage (legacy) authorization techniques.
 *
 * The signature is added to the request as an Authorization header.
 *
 * @param httpMethod/*from w w w .jav  a 2  s.c  o  m*/
 * the request object
 * @throws ServiceException
 */
public void authorizeHttpRequest(HttpUriRequest httpMethod, HttpContext context) throws ServiceException {
    if (getProviderCredentials() != null) {
        if (log.isDebugEnabled()) {
            log.debug("Adding authorization for Access Key '" + getProviderCredentials().getAccessKey() + "'.");
        }
    } else {
        if (log.isDebugEnabled()) {
            log.debug("Service has no Credential and is un-authenticated, skipping authorization");
        }
        return;
    }

    URI uri = httpMethod.getURI();
    String hostname = uri.getHost();

    /*
     * Determine the complete URL for the S3 resource, including any S3-specific parameters.
     */
    // Use raw-path, otherwise escaped characters are unescaped and a wrong
    // signature is produced
    String xfullUrl = uri.getPath();
    String fullUrl = uri.getRawPath();

    // If we are using an alternative hostname, include the hostname/bucketname in the resource path.
    String s3Endpoint = this.getEndpoint();
    if (hostname != null && !s3Endpoint.equals(hostname)) {
        int subdomainOffset = hostname.lastIndexOf("." + s3Endpoint);
        if (subdomainOffset > 0) {
            // Hostname represents an S3 sub-domain, so the bucket's name is the CNAME portion
            fullUrl = "/" + hostname.substring(0, subdomainOffset) + fullUrl;
        } else {
            // Hostname represents a virtual host, so the bucket's name is identical to hostname
            fullUrl = "/" + hostname + fullUrl;
        }
    }

    String queryString = uri.getRawQuery();
    if (queryString != null && queryString.length() > 0) {
        fullUrl += "?" + queryString;
    }

    // Set/update the date timestamp to the current time
    // Note that this will be over-ridden if an "x-amz-date" or
    // "x-goog-date" header is present.
    httpMethod.setHeader("Date", ServiceUtils.formatRfc822Date(getCurrentTimeWithOffset()));

    if (log.isDebugEnabled()) {
        log.debug("For creating canonical string, using uri: " + fullUrl);
    }

    // Generate a canonical string representing the operation.
    String canonicalString = null;
    try {
        canonicalString = RestUtils.makeServiceCanonicalString(httpMethod.getMethod(), fullUrl,
                convertHeadersToMap(httpMethod.getAllHeaders()), null, getRestHeaderPrefix(),
                getResourceParameterNames());
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e.getMessage(), e);
    }
    if (log.isDebugEnabled()) {
        log.debug("Canonical string ('|' is a newline): " + canonicalString.replace('\n', '|'));
    }

    // Sign the canonical string.
    String signedCanonical = ServiceUtils.signWithHmacSha1(getProviderCredentials().getSecretKey(),
            canonicalString);

    // Add encoded authorization to connection as HTTP Authorization header.
    String authorizationString = getSignatureIdentifier() + " " + getProviderCredentials().getAccessKey() + ":"
            + signedCanonical;
    httpMethod.setHeader("Authorization", authorizationString);
}

From source file:net.sf.taverna.t2.security.credentialmanager.impl.CredentialManagerImpl.java

protected LinkedHashSet<URI> getPossibleServiceURIsToLookup(URI serviceURI, boolean usePathRecursion) {
    try {//from   w w  w  . j av a 2 s  .c om
        serviceURI = serviceURI.normalize();
        serviceURI = dnParser.setUserInfoForURI(serviceURI, null);
    } catch (URISyntaxException ex) {
        logger.warn("Could not strip userinfo from " + serviceURI, ex);
    }

    /*
     * We'll use a LinkedHashSet to avoid checking for duplicates, like if
     * serviceURI.equals(withoutQuery) Only the first hit should be added to
     * the set.
     */
    LinkedHashSet<URI> possibles = new LinkedHashSet<URI>();

    possibles.add(serviceURI);
    if (!usePathRecursion || !serviceURI.isAbsolute())
        return possibles;

    /*
     * We'll preserve the fragment, as it is used to indicate the realm
     */
    String rawFragment = serviceURI.getRawFragment();
    if (rawFragment == null)
        rawFragment = "";

    URI withoutQuery = serviceURI.resolve(serviceURI.getRawPath());
    addFragmentedURI(possibles, withoutQuery, rawFragment);

    // Immediate parent
    URI parent = withoutQuery.resolve(".");
    addFragmentedURI(possibles, parent, rawFragment);
    URI oldParent = null;
    // Top parent (to be added later)
    URI root = parent.resolve("/");
    while (!parent.equals(oldParent) && !parent.equals(root) && parent.getPath().length() > 0) {
        // Intermediate parents, but not for "http://bla.org" as we would
        // find "http://bla.org.."
        oldParent = parent;
        parent = parent.resolve("..");
        addFragmentedURI(possibles, parent, rawFragment);
    }
    // In case while-loop did not do so, also include root
    addFragmentedURI(possibles, root, rawFragment);
    if (rawFragment.length() > 0)
        // Add the non-fragment versions in the bottom of the list
        for (URI withFragment : new ArrayList<>(possibles))
            try {
                possibles.add(dnParser.setFragmentForURI(withFragment, null));
            } catch (URISyntaxException e) {
                logger.warn("Could not non-fragment URI " + withFragment);
            }
    return possibles;
}

From source file:org.apache.manifoldcf.crawler.connectors.webcrawler.WebcrawlerConnector.java

/** Convert a document identifier to filename.
 * @param documentIdentifier/*from w  w  w .ja v a  2  s. co  m*/
 * @return
 * @throws URISyntaxException
 */
protected String documentIdentifiertoFileName(String documentIdentifier) throws URISyntaxException {
    StringBuffer path = new StringBuffer();
    URI uri = null;

    uri = new URI(documentIdentifier);

    if (uri.getRawPath() != null) {
        if (uri.getRawPath().equals("")) {
            path.append("");
        } else if (uri.getRawPath().equals("/")) {
            path.append("index.html");
        } else if (uri.getRawPath().length() != 0) {
            if (uri.getRawPath().endsWith("/")) {
                path.append("index.html");
            } else {
                String[] names = uri.getRawPath().split("/");
                path.append(names[names.length - 1]);
            }
        }
    }

    if (path.length() > 0) {
        if (uri.getRawQuery() != null) {
            path.append("?");
            path.append(uri.getRawQuery());
        }
    }

    return path.toString();
}