Example usage for javax.servlet.http HttpServletRequest getQueryString

List of usage examples for javax.servlet.http HttpServletRequest getQueryString

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletRequest getQueryString.

Prototype

public String getQueryString();

Source Link

Document

Returns the query string that is contained in the request URL after the path.

Usage

From source file:com.esri.gpt.control.arcims.ServletConnectorProxy.java

/**
 * Communicates with redirect url and works as a transparent proxy
 * //from   ww w  .  j a va2  s  . co  m
 * @param request
 *          the servlet request
 * @param response
 *          the servlet response
 * @throws IOException
 *           if an exception occurs
 */
private void executeProxy(HttpServletRequest request, HttpServletResponse response) throws IOException {

    HttpURLConnection httpCon = null;
    URL redirectURL = null;
    InputStream input = null;
    OutputStream output = null;
    InputStream proxyInput = null;
    OutputStream proxyOutput = null;

    try {

        input = request.getInputStream();
        output = response.getOutputStream();

        String sQueryStr = request.getQueryString();
        String sAuthorization = request.getHeader("Authorization");
        String requestBody = readInputCharacters(input);
        String requestMethod = request.getMethod();
        String contentType = request.getContentType();
        String encoding = request.getCharacterEncoding();

        LOGGER.finer(" Request method = " + requestMethod);
        LOGGER.finer(" Query string = " + sQueryStr);
        LOGGER.finer(" Authorization header =" + sAuthorization);
        LOGGER.finer(" Character Encoding = " + encoding);
        LOGGER.finer(" The redirect URL is " + this._redirectURL + "?" + sQueryStr);

        redirectURL = new URL(this._redirectURL + "?" + sQueryStr);

        httpCon = (HttpURLConnection) redirectURL.openConnection();

        httpCon.setDoInput(true);
        httpCon.setDoOutput(true);
        httpCon.setUseCaches(false);
        httpCon.setRequestMethod(requestMethod);
        httpCon.setRequestProperty("Content-type", contentType);

        if (sAuthorization != null) {
            httpCon.addRequestProperty("Authorization", sAuthorization);
        }

        proxyOutput = httpCon.getOutputStream();
        send(requestBody, proxyOutput);

        String authenticateHdr = httpCon.getHeaderField("WWW-Authenticate");
        if (authenticateHdr != null) {
            LOGGER.finer(" WWW-Authenticate : " + authenticateHdr);
            response.setHeader("WWW-Authenticate",
                    StringEscapeUtils.escapeHtml4(Val.stripControls(authenticateHdr)));
        }
        LOGGER.finer(" Response Code : " + httpCon.getResponseCode());

        if ((httpCon.getResponseCode() == HttpURLConnection.HTTP_FORBIDDEN)) {

            response.sendError(HttpServletResponse.SC_FORBIDDEN);
        } else if ((httpCon.getResponseCode() == HttpURLConnection.HTTP_UNAUTHORIZED)) {
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
        } else if ((httpCon.getResponseCode() == HttpURLConnection.HTTP_INTERNAL_ERROR)) {
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        } else {
            proxyInput = httpCon.getInputStream();
            send(proxyInput, output);
        }

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (input != null) {
            input.close();
        }
        if (output != null) {
            output.close();
        }
        if (proxyInput != null) {
            proxyInput.close();
        }
        if (proxyOutput != null) {
            proxyOutput.close();
        }
        if (httpCon != null) {
            httpCon.disconnect();
        }
    }
}

From source file:net.duckling.ddl.web.controller.AttachmentController.java

@RequestMapping
public ModelAndView display(HttpServletRequest request, HttpServletResponse response,
        @PathVariable("rid") Integer rid) throws IOException, ServletException {
    String redirect = request.getParameter("redirect");
    if (StringUtils.isEmpty(redirect)) {
        String url = request.getRequestURL().toString() + "?" + request.getQueryString() + "&redirect=redirect";
        request.setAttribute("url", url);
        request.setAttribute("noHref", "no");
        request.getRequestDispatcher("/jsp/aone/hash/dealHashRequest.jsp").forward(request, response);
        return null;
    }//from   w w  w .  ja  va 2s.  c  o  m

    if (checkUserConflict(request, response)) {
        return null;
    }

    Resource resource = resourceService.getResource(rid);
    if (resource == null || resource.getTid() != VWBContext.getCurrentTid() || resource.isDelete()) {
        ModelAndView m = dealResourceRemove(request, resource);
        if (m != null) {
            return m;
        }
        notFound(request, response, true);
        return null;
    }
    ModelAndView mv = null;
    if (resource.isFile()) {
        mv = dealFile(request, response, resource);
    } else {
        notFound(request, response, true);
        return null;
    }
    mv.addObject("pageType", "list");
    if (resource.isAvailable()) {
        mv.addObject("resourePath", getParentPath(resource));
    }
    mv.addObject("teamUrl", urlGenerator.getURL(resource.getTid(), UrlPatterns.T_LIST, null, null));
    mv.addObject("teamHome", urlGenerator.getURL(resource.getTid(), UrlPatterns.T_TEAM_HOME, null, null));
    addMyTeam(request, mv);
    return mv;
}

From source file:cn.vlabs.duckling.vwb.VWBDriverServlet.java

private String buildURL(URLParser info, HttpServletRequest request) {
    boolean isHttp;
    StringBuffer buff = new StringBuffer();
    buff.append(request.getScheme() + "://");
    isHttp = "http".equalsIgnoreCase(request.getScheme());

    buff.append(request.getServerName());
    if (isHttp) {
        if (request.getServerPort() != 80)
            buff.append(":" + request.getServerPort());
    } else if (request.getServerPort() != 443) {
        buff.append(":" + request.getServerPort());
    }/*from w  w  w . j a  v  a2s  .com*/

    buff.append(info.getURI());
    if (request.getQueryString() != null) {
        buff.append("?" + request.getQueryString());
    }
    return buff.toString();
}

From source file:eionet.util.Util.java

/**
 *
 *
 *///from w ww . j  a  va  2  s. co m
public static String getServletPathWithQueryString(HttpServletRequest request) {

    StringBuffer result = new StringBuffer();
    String servletPath = request.getServletPath();
    if (servletPath != null && servletPath.length() > 0) {
        if (servletPath.startsWith("/") && servletPath.length() > 1) {
            result.append(servletPath.substring(1));
        }
        String queryString = request.getQueryString();
        if (queryString != null && queryString.length() > 0) {
            result.append("?").append(queryString);
        }
    }

    return result.toString();
}

From source file:com.boylesoftware.web.Router.java

/**
 * Send request for user authentication, which can be a redirect to the
 * login page, or the 401 HTTP code.// w  w  w  .ja  v  a 2  s  . c  om
 *
 * @param webapp The web-application.
 * @param request The HTTP request.
 * @param response The HTTP response.
 *
 * @throws ServletException If an error happens.
 */
private void sendRequestForAuthentication(final AbstractWebApplication webapp, final HttpServletRequest request,
        final HttpServletResponse response) throws ServletException {

    LooseCannon.heel();

    final String loginPageURI = webapp.getRouterConfiguration().getLoginPageURI();
    if (loginPageURI != null) {

        try (final PooledStringBuffer buf = StringBufferPool.get()) {
            final StringBuilder sb = buf.getStringBuilder();

            sb.append(request.getRequestURI());
            final String queryString = request.getQueryString();
            if (queryString != null)
                sb.append('?').append(queryString);
            final String targetURI = sb.toString();
            sb.setLength(0);

            sb.append("https://").append(request.getServerName());

            final int httpsPort = webapp.getHTTPSPort();
            if (httpsPort != 443)
                sb.append(':').append(httpsPort);

            sb.append(StringUtils.emptyIfNull(request.getContextPath())).append(loginPageURI).append('?')
                    .append(Authenticator.TARGET_URI).append('=');

            try {
                sb.append(URLEncoder.encode(targetURI, "UTF-8"));
            } catch (final UnsupportedEncodingException e) {
                throw new ServletException("UTF-8 is unsupported.", e);
            }

            response.setStatus(HttpServletResponse.SC_SEE_OTHER);
            response.setHeader("Location", sb.toString());
        }

    } else {
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        // TODO: configure realm in the application configuration
        response.setHeader("WWW-Authenticate", "Basic realm=\"Application\"");
    }
}

From source file:org.realityforge.proxy_servlet.AbstractProxyServlet.java

/**
 * Reads the request URI from {@code servletRequest} and rewrites it, considering {@link
 * #_targetUri}. It's used to make the new request.
 *///from w w  w.j  a v  a 2  s.c o m
protected String rewriteUrlFromRequest(final HttpServletRequest servletRequest) {
    final StringBuilder sb = new StringBuilder(500);
    sb.append(_target);
    // Handle the path given to the servlet
    if (null != servletRequest.getPathInfo()) {
        //ex: /my/path.html
        sb.append(encodeUriQuery(servletRequest.getPathInfo()));
    }
    // Handle the query string
    //ex:(following '?'): name=value&foo=bar#fragment
    final String queryString = servletRequest.getQueryString();
    if (null != queryString && queryString.length() > 0) {
        sb.append('?');
        final int fragIdx = queryString.indexOf('#');
        final String queryNoFrag = (fragIdx < 0 ? queryString : queryString.substring(0, fragIdx));
        sb.append(encodeUriQuery(queryNoFrag));
        //Fragments should never be sent so we don't....
    }
    return sb.toString();
}

From source file:com.adaptris.core.http.jetty.BasicJettyConsumer.java

protected void logHeaders(HttpServletRequest req) {
    if (additionalDebug()) {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        PrintWriter p = new PrintWriter(out);
        p.println("Received HTTP Headers");
        p.println("URL " + req.getRequestURL());
        p.println("URI " + req.getRequestURI());
        p.println("Query " + req.getQueryString());
        for (Enumeration e = req.getHeaderNames(); e.hasMoreElements();) {
            String key = (String) e.nextElement();
            Enumeration values = req.getHeaders(key);
            StringBuffer sb = new StringBuffer();
            while (values.hasMoreElements()) {
                sb.append(values.nextElement()).append(",");
            }//  w ww .  ja v  a  2 s . c o  m
            String s = sb.toString();
            p.println(key + ": " + s.substring(0, s.lastIndexOf(",")));
        }
        p.close();
        log.trace(out.toString());
    }
}

From source file:com.codeabovelab.dm.gateway.proxy.common.HttpProxy.java

/**
 * Reads the request URI from {@code servletRequest} and rewrites it, considering targetUri.
 * It's used to make the new request./*from  www. ja  v a2s .c  o m*/
 */
private String rewriteUrlFromRequest(HttpProxyContext proxyContext) {
    HttpServletRequest servletRequest = proxyContext.getRequest();
    StringBuilder uri = new StringBuilder(500);
    uri.append(proxyContext.getTargetPath());
    // Handle the path given to the servlet
    if (servletRequest.getPathInfo() != null) {//ex: /my/path.html
        uri.append(HttpProxyUtil.encodeUriQuery(servletRequest.getPathInfo()));
    }
    // Handle the query string & fragment
    String queryString = servletRequest.getQueryString();//ex:(following '?'): name=value&foo=bar#fragment
    String fragment = null;
    //split off fragment from queryString, updating queryString if found
    if (queryString != null) {
        int fragIdx = queryString.indexOf('#');
        if (fragIdx >= 0) {
            fragment = queryString.substring(fragIdx + 1);
            queryString = queryString.substring(0, fragIdx);
        }
    }

    queryString = rewriteQueryStringFromRequest(servletRequest, queryString);
    if (queryString != null && queryString.length() > 0) {
        uri.append('?');
        uri.append(HttpProxyUtil.encodeUriQuery(queryString));
    }

    if (DO_SEND_URL_FRAGMENT && fragment != null) {
        uri.append('#');
        uri.append(HttpProxyUtil.encodeUriQuery(fragment));
    }
    return uri.toString();
}

From source file:io.hops.hopsworks.api.jupyter.URITemplateProxyServlet.java

@Override
protected void service(HttpServletRequest servletRequest, HttpServletResponse servletResponse)
        throws ServletException, IOException {

    //First collect params
    /*//from www.  j  a  v a 2s.  c  o m
     * Do not use servletRequest.getParameter(arg) because that will
     * typically read and consume the servlet InputStream (where our
     * form data is stored for POST). We need the InputStream later on.
     * So we'll parse the query string ourselves. A side benefit is
     * we can keep the proxy parameters in the query string and not
     * have to add them to a URL encoded form attachment.
     */
    String queryString = "?" + servletRequest.getQueryString();//no "?" but might have "#"
    int hash = queryString.indexOf('#');
    if (hash >= 0) {
        queryString = queryString.substring(0, hash);
    }
    List<NameValuePair> pairs;
    try {
        //note: HttpClient 4.2 lets you parse the string without building the URI
        pairs = URLEncodedUtils.parse(new URI(queryString), "UTF-8");
    } catch (URISyntaxException e) {
        throw new ServletException("Unexpected URI parsing error on " + queryString, e);
    }
    LinkedHashMap<String, String> params = new LinkedHashMap<>();
    for (NameValuePair pair : pairs) {
        params.put(pair.getName(), pair.getValue());
    }

    //Now rewrite the URL
    StringBuffer urlBuf = new StringBuffer();//note: StringBuilder isn't supported by Matcher
    Matcher matcher = TEMPLATE_PATTERN.matcher(targetUriTemplate);
    while (matcher.find()) {
        String arg = matcher.group(1);
        String replacement = params.remove(arg);//note we remove
        if (replacement != null) {
            matcher.appendReplacement(urlBuf, replacement);
            port = replacement;
        } else if (port != null) {
            matcher.appendReplacement(urlBuf, port);
        } else {
            throw new ServletException("Missing HTTP parameter " + arg + " to fill the template");
        }
    }
    matcher.appendTail(urlBuf);
    String newTargetUri = urlBuf.toString();
    servletRequest.setAttribute(ATTR_TARGET_URI, newTargetUri);
    try {
        targetUriObj = new URI(newTargetUri);
    } catch (Exception e) {
        throw new ServletException("Rewritten targetUri is invalid: " + newTargetUri, e);
    }
    servletRequest.setAttribute(ATTR_TARGET_HOST, URIUtils.extractHost(targetUriObj));

    //Determine the new query string based on removing the used names
    StringBuilder newQueryBuf = new StringBuilder(queryString.length());
    for (Map.Entry<String, String> nameVal : params.entrySet()) {
        if (newQueryBuf.length() > 0) {
            newQueryBuf.append('&');
        }
        newQueryBuf.append(nameVal.getKey()).append('=');
        if (nameVal.getValue() != null) {
            newQueryBuf.append(nameVal.getValue());
        }
    }
    servletRequest.setAttribute(ATTR_QUERY_STRING, newQueryBuf.toString());

    // Create Exchange object with targetUriObj
    // create transport object
    //    ServiceProxy sp = new ServiceProxy();
    //    sp.setTargetUrl(ATTR_TARGET_URI);
    //    super.service(servletRequest, servletResponse);

    //              RouterUtil.initializeRoutersFromSpringWebContext(appCtx, config.
    //              getServletContext(), getProxiesXmlLocation(config));
}