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:co.cask.cdap.metrics.query.MetricQueryParser.java

static MetricDataQuery parse(URI requestURI) throws MetricsPathException {
    MetricDataQueryBuilder builder = new MetricDataQueryBuilder();
    // metric will be at the end.
    String uriPath = requestURI.getRawPath();
    int index = uriPath.lastIndexOf("/");
    builder.setMetricName(urlDecode(uriPath.substring(index + 1)));
    // strip the metric from the end of the path
    if (index != -1) {
        String strippedPath = uriPath.substring(0, index);
        if (strippedPath.startsWith("/system/cluster")) {
            builder.setSliceByTagValues(
                    ImmutableMap.of(Constants.Metrics.Tag.NAMESPACE, Constants.SYSTEM_NAMESPACE));
            builder.setScope("system");
        } else if (strippedPath.startsWith("/system/transactions")) {
            builder.setSliceByTagValues(ImmutableMap.of(Constants.Metrics.Tag.NAMESPACE,
                    Constants.SYSTEM_NAMESPACE, Constants.Metrics.Tag.COMPONENT, TRANSACTION_METRICS_CONTEXT));
            builder.setScope("system");
        } else {/* w  w w. j a va2  s.  co  m*/
            parseContext(strippedPath, builder);
        }
    } else {
        builder.setSliceByTagValues(Maps.<String, String>newHashMap());
    }
    parseQueryString(requestURI, builder);

    return builder.build();
}

From source file:net.oauth.signature.OAuthSignatureMethod.java

protected static String normalizeUrl(String url) throws URISyntaxException {
    URI uri = new URI(url);
    String scheme = uri.getScheme().toLowerCase();
    String authority = uri.getAuthority().toLowerCase();
    boolean dropPort = (scheme.equals("http") && uri.getPort() == 80)
            || (scheme.equals("https") && uri.getPort() == 443);
    if (dropPort) {
        // find the last : in the authority
        int index = authority.lastIndexOf(":");
        if (index >= 0) {
            authority = authority.substring(0, index);
        }/*from   w  w w .j  a v  a2s  . com*/
    }
    String path = uri.getRawPath();
    if (path == null || path.length() <= 0) {
        path = "/"; // conforms to RFC 2616 section 3.2.2
    }
    // we know that there is no query and no fragment here.
    return scheme + "://" + authority + path;
}

From source file:org.orbeon.oxf.util.URLRewriterUtils.java

/**
 * Rewrite a URL based on a base URL, a URL, and a rewriting mode.
 *
 * @param scheme            base URL scheme
 * @param host              base URL host
 * @param port              base URL port
 * @param contextPath       base URL context path
 * @param requestPath       base URL request path
 * @param urlString         URL to rewrite (accept human-readable URI)
 * @param rewriteMode       rewrite mode (see ExternalContext.Response)
 * @return                  rewritten URL
 *//*from   ww  w .  j  a v a 2  s.c  o  m*/
private static String rewriteURL(String scheme, String host, int port, String contextPath, String requestPath,
        String urlString, int rewriteMode) {
    // Accept human-readable URI
    urlString = NetUtils.encodeHRRI(urlString, true);

    // Case where a protocol is specified: the URL is left untouched (except for human-readable processing)
    if (NetUtils.urlHasProtocol(urlString))
        return urlString;

    try {
        final String baseURLString;
        {
            String _baseURLString;
            // Prepend absolute base if needed
            if ((rewriteMode & ExternalContext.Response.REWRITE_MODE_ABSOLUTE) != 0) {
                _baseURLString = scheme + "://" + host + ((port == 80 || port == -1) ? "" : ":" + port);
            } else {
                _baseURLString = "";
            }
            // Append context path if needed
            if ((rewriteMode & ExternalContext.Response.REWRITE_MODE_ABSOLUTE_PATH_NO_CONTEXT) == 0)
                _baseURLString = _baseURLString + contextPath;

            baseURLString = _baseURLString;
        }

        // Return absolute path URI with query string and fragment identifier if needed
        if (urlString.startsWith("?")) {
            // This is a special case that appears to be implemented
            // in Web browsers as a convenience. Users may use it.
            return baseURLString + requestPath + urlString;
        } else if ((rewriteMode & ExternalContext.Response.REWRITE_MODE_ABSOLUTE_PATH_OR_RELATIVE) != 0
                && !urlString.startsWith("/") && !"".equals(urlString)) {
            // Don't change the URL if it is a relative path and we don't force absolute
            return urlString;
        } else {
            // Regular case, parse the URL

            final URI baseURIWithPath = new URI("http", "example.org", requestPath, null);
            final URI resolvedURI = baseURIWithPath.resolve(urlString).normalize();// normalize to remove "..", etc.

            // Append path, query and fragment
            final String query = resolvedURI.getRawQuery();
            final String fragment = resolvedURI.getRawFragment();
            final String tempResult = resolvedURI.getRawPath() + ((query != null) ? "?" + query : "")
                    + ((fragment != null) ? "#" + fragment : "");

            // Prepend base
            return baseURLString + tempResult;
        }
    } catch (Exception e) {
        throw new OXFException(e);
    }
}

From source file:com.sworddance.util.UriFactoryImpl.java

public static URI createUriWithOptions(Object uriStr, boolean schemaRequired, boolean pathRequired) {
    URI uri = createUri(uriStr);
    if (uri != null && uriStr != null) {
        String newUriStr = uriStr.toString();
        String path = uri.getRawPath();
        if (pathRequired && isEmpty(path)) {
            String rawQuery = uri.getRawQuery();
            newUriStr += PATH_SEPARATOR + (rawQuery == null ? "" : rawQuery);
        }//w ww. j  a v  a  2  s  .  co  m
        if (schemaRequired && !uri.isAbsolute() && !newUriStr.startsWith(PATH_SEPARATOR)) {
            // TODO: check for a relative uri! will produce something like http:/httpdocs/demo if newUriStr does not have host information.
            newUriStr = "//" + newUriStr;
        }
        //noinspection StringEquality
        if (uriStr != newUriStr) {
            uri = createUri(newUriStr);
        }
    }
    return uri;
}

From source file:org.jets3t.service.utils.SignatureUtils.java

/**
 * Replace the hostname of the given URI endpoint to match the given region.
 *
 * @param uri/*from ww w . j  a v a 2 s.c  o m*/
 * @param region
 *
 * @return
 * URI with hostname that may or may not have been changed to be appropriate
 * for the given region. For example, the hostname "s3.amazonaws.com" is
 * unchanged for the "us-east-1" region but for the "eu-central-1" region
 * becomes "s3-eu-central-1.amazonaws.com".
 */
public static URI awsV4CorrectHostnameForRegion(URI uri, String region) {
    String[] hostSplit = uri.getHost().split("\\.");
    if (region.equals("us-east-1")) {
        hostSplit[hostSplit.length - 3] = "s3";
    } else {
        hostSplit[hostSplit.length - 3] = "s3-" + region;
    }
    String newHost = ServiceUtils.join(hostSplit, ".");
    try {
        String rawPathAndQuery = uri.getRawPath();
        if (uri.getRawQuery() != null) {
            rawPathAndQuery += "?" + uri.getRawQuery();
        }
        return new URL(uri.getScheme(), newHost, uri.getPort(), rawPathAndQuery).toURI();
    } catch (URISyntaxException e) {
        throw new RuntimeException(e);
    } catch (MalformedURLException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.cruxframework.crux.core.server.rest.spi.HttpUtil.java

public static UriInfo extractUriInfo(HttpServletRequest request) {
    String servletPrefix = request.getServletPath();
    String contextPath = request.getContextPath();
    if (servletPrefix != null && servletPrefix.length() > 0 && !servletPrefix.equals("/")) {
        if (!contextPath.endsWith("/") && !servletPrefix.startsWith("/")) {
            contextPath += "/";
        }//w  w  w . j a v  a 2 s .  com
        contextPath += servletPrefix;
    }
    URI absolutePath = null;
    try {
        URL absolute = new URL(request.getRequestURL().toString());

        UriBuilder builder = new UriBuilder();
        builder.scheme(absolute.getProtocol());
        builder.host(absolute.getHost());
        builder.port(absolute.getPort());
        builder.path(absolute.getPath());
        builder.replaceQuery(null);
        absolutePath = builder.build();
    } catch (MalformedURLException e) {
        throw new RuntimeException(e);
    }

    String path = PathHelper.getEncodedPathInfo(absolutePath.getRawPath(), contextPath);
    URI relativeURI = UriBuilder.fromUri(path).replaceQuery(request.getQueryString()).build();

    URI baseURI = absolutePath;
    if (!path.trim().equals("")) {
        String tmpContextPath = contextPath;
        if (!tmpContextPath.endsWith("/")) {
            tmpContextPath += "/";
        }
        baseURI = UriBuilder.fromUri(absolutePath).replacePath(tmpContextPath).build();
    }
    UriInfo uriInfo = new UriInfo(baseURI, relativeURI);
    return uriInfo;
}

From source file:org.mycore.common.xml.MCRXMLFunctions.java

/**
 * Encodes the path so that it can be safely used in an URI.
 * @param asciiOnly/*from ww  w. j a va2s.c  o  m*/
 *          if true, return only ASCII characters (e.g. encode umlauts)
 * @return encoded path as described in RFC 2396
 */
public static String encodeURIPath(String path, boolean asciiOnly) throws URISyntaxException {
    URI relativeURI = new URI(null, null, path, null, null);
    return asciiOnly ? relativeURI.toASCIIString() : relativeURI.getRawPath();
}

From source file:com.wavemaker.runtime.ws.HTTPBindingSupport.java

@SuppressWarnings("unchecked")
private static <T extends Object> T getResponse(QName serviceQName, QName portQName, String endpointAddress,
        HTTPRequestMethod method, T postSource, BindingProperties bindingProperties, Class<T> type,
        Map<String, Object> headerParams) throws WebServiceException {

    Service service = Service.create(serviceQName);
    URI endpointURI;
    try {/*from   ww  w .  ja  v  a 2s  .c o m*/
        if (bindingProperties != null) {
            // if BindingProperties had endpointAddress defined, then use
            // it instead of the endpointAddress passed in from arguments.
            String endAddress = bindingProperties.getEndpointAddress();
            if (endAddress != null) {
                endpointAddress = endAddress;
            }
        }
        endpointURI = new URI(endpointAddress);
    } catch (URISyntaxException e) {
        throw new WebServiceException(e);
    }

    String endpointPath = null;
    String endpointQueryString = null;
    if (endpointURI != null) {
        endpointPath = endpointURI.getRawPath();
        endpointQueryString = endpointURI.getRawQuery();
    }

    service.addPort(portQName, HTTPBinding.HTTP_BINDING, endpointAddress);

    Dispatch<T> d = service.createDispatch(portQName, type, Service.Mode.MESSAGE);

    Map<String, Object> requestContext = d.getRequestContext();
    requestContext.put(MessageContext.HTTP_REQUEST_METHOD, method.toString());
    requestContext.put(MessageContext.QUERY_STRING, endpointQueryString);
    requestContext.put(MessageContext.PATH_INFO, endpointPath);

    Map<String, List<String>> reqHeaders = null;
    if (bindingProperties != null) {
        String httpBasicAuthUsername = bindingProperties.getHttpBasicAuthUsername();
        if (httpBasicAuthUsername != null) {
            requestContext.put(BindingProvider.USERNAME_PROPERTY, httpBasicAuthUsername);
            String httpBasicAuthPassword = bindingProperties.getHttpBasicAuthPassword();
            requestContext.put(BindingProvider.PASSWORD_PROPERTY, httpBasicAuthPassword);
        }

        int connectionTimeout = bindingProperties.getConnectionTimeout();
        requestContext.put(JAXWSProperties.CONNECT_TIMEOUT, Integer.valueOf(connectionTimeout));

        int requestTimeout = bindingProperties.getRequestTimeout();
        requestContext.put(JAXWSProperties.REQUEST_TIMEOUT, Integer.valueOf(requestTimeout));

        Map<String, List<String>> httpHeaders = bindingProperties.getHttpHeaders();
        if (httpHeaders != null && !httpHeaders.isEmpty()) {
            reqHeaders = (Map<String, List<String>>) requestContext.get(MessageContext.HTTP_REQUEST_HEADERS);
            if (reqHeaders == null) {
                reqHeaders = new HashMap<String, List<String>>();
                requestContext.put(MessageContext.HTTP_REQUEST_HEADERS, reqHeaders);
            }
            for (Entry<String, List<String>> entry : httpHeaders.entrySet()) {
                reqHeaders.put(entry.getKey(), entry.getValue());
            }
        }
    }

    // Parameters to pass in http header
    if (headerParams != null && headerParams.size() > 0) {
        if (null == reqHeaders) {
            reqHeaders = new HashMap<String, List<String>>();
        }
        Set<Entry<String, Object>> entries = headerParams.entrySet();
        for (Map.Entry<String, Object> entry : entries) {
            List<String> valList = new ArrayList<String>();
            valList.add((String) entry.getValue());
            reqHeaders.put(entry.getKey(), valList);
            requestContext.put(MessageContext.HTTP_REQUEST_HEADERS, reqHeaders);
        }
    }

    logger.info("Invoking HTTP '" + method + "' request with URL: " + endpointAddress);

    T result = d.invoke(postSource);
    return result;
}

From source file:edu.ku.brc.specify.conversion.ConvertMiscData.java

/**
 * @param oldDBConn//from   w  ww  .  j  a  v a2 s  .  co m
 * @param newDBConn
 * @return
 */
public static void convertImagesToWebLinks(final Connection oldDBConn, final Connection newDBConn) {
    IdMapperIFace ceMapper = IdMapperMgr.getInstance().addTableMapper("collectingevent", "CollectingEventID",
            false);

    PreparedStatement pStmt1 = null;
    try {
        Timestamp now = new Timestamp(System.currentTimeMillis());
        pStmt1 = newDBConn
                .prepareStatement("UPDATE collectingevent SET VerbatimDate=? WHERE CollectingEventID=?");

        int errCnt = 0;
        int cnt = 0;

        String sql = "SELECT VerbatimDate, CollectingEventID FROM collectingevent WHERE VerbatimDate IS NOT NULL";
        Vector<Object[]> rows = BasicSQLUtils.query(oldDBConn, sql);
        for (Object[] row : rows) {
            Integer newId = ceMapper.get((Integer) row[1]);
            if (newId != null) {
                String fileName = (String) row[0];
                String shortenName = fileName.substring(fileName.lastIndexOf('/') + 1, fileName.length());
                shortenName = URLDecoder.decode(shortenName, "UTF-8");

                URI uri = new URI("file", "/" + shortenName, null);
                String uriStr = uri.getRawPath();
                System.out.println("[" + shortenName + "][" + uriStr + "]");
                shortenName = uriStr.substring(uriStr.lastIndexOf('/') + 1, uriStr.length());

                System.out.println("[" + shortenName + "][" + fileName + "]");
                if (shortenName.length() < 51) {
                    pStmt1.setString(1, shortenName);
                    pStmt1.setInt(2, newId);
                    pStmt1.execute();
                    cnt++;
                } else {
                    System.err.println(
                            String.format("Name Length Error %d [%s]", shortenName.length(), shortenName));
                    errCnt++;
                }
            } else {
                System.err.println(String.format("Couldn't map OldID %d", (Integer) row[1]));
                errCnt++;
            }
        }
        System.out.println(
                String.format("Done - convertImagesToWebLinks Transfered : %d,  Errors: %d", cnt, errCnt));

    } catch (Exception ex) {
        ex.printStackTrace();

    } finally {
        try {
            if (pStmt1 != null)
                pStmt1.close();

        } catch (Exception ex) {
        }
    }
}

From source file:net.ripe.rpki.validator.util.HierarchicalUriCache.java

public boolean contains(URI uriToCheck) {
    URI uri = uriToCheck;
    while (StringUtils.isNotEmpty(uri.getRawPath())) {
        if (cache.contains(uri)) {
            return true;
        }/*from ww  w  .  ja v a 2  s.c  om*/
        String path = uri.getRawPath();
        if ("/".equals(path)) {
            return false;
        }

        if (path.endsWith("/")) {
            path = path.substring(0, path.length() - 1);
        }

        int i = path.lastIndexOf('/');
        if (i != -1) {
            uri = uri.resolve(path.substring(0, i + 1));
        } else {
            return false;
        }
    }
    return false;
}