Example usage for java.net URI getRawQuery

List of usage examples for java.net URI getRawQuery

Introduction

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

Prototype

public String getRawQuery() 

Source Link

Document

Returns the raw query component of this URI.

Usage

From source file:com.mcxiaoke.next.http.util.URLUtils.java

/**
 * Returns a list of {@link org.apache.http.NameValuePair NameValuePairs} as built from the URI's query portion. For example, a URI
 * of http://example.org/path/to/file?a=1&b=2&c=3 would return a list of three NameValuePairs, one for a=1, one for
 * b=2, and one for c=3. By convention, {@code '&'} and {@code ';'} are accepted as parameter separators.
 * <p/>//from  ww w .j a  v a  2  s .  c  o  m
 * This is typically useful while parsing an HTTP PUT.
 * <p/>
 * This API is currently only used for testing.
 *
 * @param uri     URI to parse
 * @param charset Charset name to use while parsing the query
 * @return a list of {@link org.apache.http.NameValuePair} as built from the URI's query portion.
 */
public static List<NameValuePair> parse(final URI uri, final String charset) {
    final String query = uri.getRawQuery();
    if (query != null && query.length() > 0) {
        final List<NameValuePair> result = new ArrayList<NameValuePair>();
        final Scanner scanner = new Scanner(query);
        parse(result, scanner, QP_SEP_PATTERN, charset);
        return result;
    }
    return Collections.emptyList();
}

From source file:com.gamesalutes.utils.WebUtils.java

public static Map<String, String> getQueryParameters(URI uri) {
    if (uri == null)
        throw new NullPointerException("uri");
    return urlDecode(uri.getRawQuery(), false);
}

From source file:com.ctriposs.r2.message.rest.QueryTunnelUtil.java

/**
 * @param request   a RestRequest object to be encoded as a tunneled POST
 * @param threshold the size of the query params above which the request will be encoded
 *
 * @return an encoded RestRequest/* w  ww  . ja v  a 2s  .  com*/
 */
public static RestRequest encode(final RestRequest request, int threshold)
        throws URISyntaxException, MessagingException, IOException {
    URI uri = request.getURI();

    // Check to see if we should tunnel this request by testing the length of the query
    // if the query is NULL, we won't bother to encode.
    // 0 length is a special case that could occur with a url like http://www.foo.com?
    // which we don't want to encode, because we'll lose the "?" in the process
    // Otherwise only encode queries whose length is greater than or equal to the
    // threshold value.

    String query = uri.getRawQuery();

    if (query == null || query.length() == 0 || query.length() < threshold) {
        return request;
    }

    RestRequestBuilder requestBuilder = new RestRequestBuilder(request);

    // reconstruct URI without query
    uri = new URI(uri.getScheme(), uri.getUserInfo(), uri.getHost(), uri.getPort(), uri.getPath(), null,
            uri.getFragment());

    // If there's no existing body, just pass the request as x-www-form-urlencoded
    ByteString entity = request.getEntity();
    if (entity == null || entity.length() == 0) {
        requestBuilder.setHeader(HEADER_CONTENT_TYPE, FORM_URL_ENCODED);
        requestBuilder.setEntity(ByteString.copyString(query, Data.UTF_8_CHARSET));
    } else {
        // If we have a body, we must preserve it, so use multipart/mixed encoding

        MimeMultipart multi = createMultiPartEntity(entity, request.getHeader(HEADER_CONTENT_TYPE), query);
        requestBuilder.setHeader(HEADER_CONTENT_TYPE, multi.getContentType());
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        multi.writeTo(os);
        requestBuilder.setEntity(ByteString.copy(os.toByteArray()));
    }

    // Set the base uri, supply the original method in the override header, and change method to POST
    requestBuilder.setURI(uri);
    requestBuilder.setHeader(HEADER_METHOD_OVERRIDE, requestBuilder.getMethod());
    requestBuilder.setMethod(RestMethod.POST);

    return requestBuilder.build();
}

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  w w w .  jav a2s  .c  om
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.linkedin.r2.message.rest.QueryTunnelUtil.java

/**
 * @param request   a RestRequest object to be encoded as a tunneled POST
 * @param requestContext a RequestContext object associated with the request
 * @param threshold the size of the query params above which the request will be encoded
 *
 * @return an encoded RestRequest/*w ww  .j a v a  2s .com*/
 */
public static RestRequest encode(final RestRequest request, RequestContext requestContext, int threshold)
        throws URISyntaxException, MessagingException, IOException {
    URI uri = request.getURI();

    // Check to see if we should tunnel this request by testing the length of the query
    // if the query is NULL, we won't bother to encode.
    // 0 length is a special case that could occur with a url like http://www.foo.com?
    // which we don't want to encode, because we'll lose the "?" in the process
    // Otherwise only encode queries whose length is greater than or equal to the
    // threshold value.

    String query = uri.getRawQuery();

    boolean forceQueryTunnel = requestContext.getLocalAttr(R2Constants.FORCE_QUERY_TUNNEL) != null
            && (Boolean) requestContext.getLocalAttr(R2Constants.FORCE_QUERY_TUNNEL);

    if (query == null || query.length() == 0 || (query.length() < threshold && !forceQueryTunnel)) {
        return request;
    }

    RestRequestBuilder requestBuilder = new RestRequestBuilder(request);

    // reconstruct URI without query
    uri = new URI(uri.getScheme(), uri.getUserInfo(), uri.getHost(), uri.getPort(), uri.getPath(), null,
            uri.getFragment());

    // If there's no existing body, just pass the request as x-www-form-urlencoded
    ByteString entity = request.getEntity();
    if (entity == null || entity.length() == 0) {
        requestBuilder.setHeader(HEADER_CONTENT_TYPE, FORM_URL_ENCODED);
        requestBuilder.setEntity(ByteString.copyString(query, Data.UTF_8_CHARSET));
    } else {
        // If we have a body, we must preserve it, so use multipart/mixed encoding

        MimeMultipart multi = createMultiPartEntity(entity, request.getHeader(HEADER_CONTENT_TYPE), query);
        requestBuilder.setHeader(HEADER_CONTENT_TYPE, multi.getContentType());
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        multi.writeTo(os);
        requestBuilder.setEntity(ByteString.copy(os.toByteArray()));
    }

    // Set the base uri, supply the original method in the override header, and change method to POST
    requestBuilder.setURI(uri);
    requestBuilder.setHeader(HEADER_METHOD_OVERRIDE, requestBuilder.getMethod());
    requestBuilder.setMethod(RestMethod.POST);

    return requestBuilder.build();
}

From source file:org.mulgara.scon.Connection.java

/**
 * Encodes a URI if it looks like it needs it.
 * @param u The URI to encode, if needed.
 * @return a minimally encoded URI.//from   w  w w .  j  av  a2  s  . c om
 */
private static final String enc(URI u) {
    try {
        // if there is no query, then just return the unencoded URI
        String query = u.getRawQuery();
        if (query == null)
            return u.toString();
        // encode the query, and add it to the end of the URI
        String encQuery = encode(query);
        String encU = new URI(u.getScheme(), u.getUserInfo(), u.getHost(), u.getPort(), u.getPath(), encQuery,
                u.getFragment()).toString();
        // if the partial encoding works, then return it
        if (decode(encU).equals(u.toString()))
            return encU;
        // nothing else worked, so encode it fully
        return encode(u.toString());
    } catch (URISyntaxException e) {
        throw new IllegalArgumentException("Unable to encode a URI", e);
    }
}

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

/**
 * Replace the hostname of the given URI endpoint to match the given region.
 *
 * @param uri//w ww.  j a va  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: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);
        }/*from   w w  w  .  j  a  v a2  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:com.discovery.darchrow.net.ParamUtil.java

/**
 * ?.//w  ww .ja  v  a2  s  .  c o  m
 * 
 * <p>
 * uri????,?,?{@code a=1&a=2},a,[3,4],{@code a=3&a=4}.
 * </p>
 * 
 * @param uri
 *            ? ?,?,??,<br>
 *            ??, ?
 * @param arrayValueMap
 *            singleValueMap  request.getParameterMap
 * @param charsetType
 *            ??, {@link CharsetType}<br>
 *            <span style="color:green">null empty,?,?</span><br>
 *            ??,??,ie?chrome? url ,?
 * @return  <code>uri</code> null, {@link StringUtils#EMPTY}<br>
 */
public static String addParameterArrayValueMap(URI uri, Map<String, String[]> arrayValueMap,
        String charsetType) {
    return null == uri ? StringUtils.EMPTY
            : addParameterArrayValueMap(uri.toString(), uri.getRawQuery(), arrayValueMap, charsetType);
}

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   w  ww  . ja  va2s.  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;
}