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:org.apache.hadoop.yarn.server.resourcemanager.webapp.RMWebAppFilter.java

@Override
public void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    response.setCharacterEncoding("UTF-8");
    String htmlEscapedUri = HtmlQuoting.quoteHtmlChars(request.getRequestURI());

    if (htmlEscapedUri == null) {
        htmlEscapedUri = "/";
    }/*from   w  w w.j  a v  a 2  s  .co  m*/

    String uriWithQueryString = htmlEscapedUri;
    String htmlEscapedUriWithQueryString = htmlEscapedUri;

    String queryString = request.getQueryString();
    if (queryString != null && !queryString.isEmpty()) {
        String reqEncoding = request.getCharacterEncoding();
        if (reqEncoding == null || reqEncoding.isEmpty()) {
            reqEncoding = "ISO-8859-1";
        }
        Charset encoding = Charset.forName(reqEncoding);
        List<NameValuePair> params = URLEncodedUtils.parse(queryString, encoding);
        String urlEncodedQueryString = URLEncodedUtils.format(params, encoding);
        uriWithQueryString += "?" + urlEncodedQueryString;
        htmlEscapedUriWithQueryString = HtmlQuoting
                .quoteHtmlChars(request.getRequestURI() + "?" + urlEncodedQueryString);
    }

    RMWebApp rmWebApp = injector.getInstance(RMWebApp.class);
    rmWebApp.checkIfStandbyRM();
    if (rmWebApp.isStandby() && shouldRedirect(rmWebApp, htmlEscapedUri)) {

        String redirectPath = rmWebApp.getRedirectPath();

        if (redirectPath != null && !redirectPath.isEmpty()) {
            redirectPath += uriWithQueryString;
            String redirectMsg = "This is standby RM. The redirect url is: " + htmlEscapedUriWithQueryString;
            PrintWriter out = response.getWriter();
            out.println(redirectMsg);
            response.setHeader("Location", redirectPath);
            response.setStatus(HttpServletResponse.SC_TEMPORARY_REDIRECT);
            return;
        } else {
            boolean doRetry = true;
            String retryIntervalStr = request.getParameter(YarnWebParams.NEXT_REFRESH_INTERVAL);
            int retryInterval = 0;
            if (retryIntervalStr != null) {
                try {
                    retryInterval = Integer.parseInt(retryIntervalStr.trim());
                } catch (NumberFormatException ex) {
                    doRetry = false;
                }
            }
            int next = calculateExponentialTime(retryInterval);

            String redirectUrl = appendOrReplaceParamter(path + uriWithQueryString,
                    YarnWebParams.NEXT_REFRESH_INTERVAL + "=" + (retryInterval + 1));
            if (redirectUrl == null || next > MAX_SLEEP_TIME) {
                doRetry = false;
            }
            String redirectMsg = doRetry
                    ? "Can not find any active RM. Will retry in next " + next + " seconds."
                    : "There is no active RM right now.";
            redirectMsg += "\nHA Zookeeper Connection State: " + rmWebApp.getHAZookeeperConnectionState();
            PrintWriter out = response.getWriter();
            out.println(redirectMsg);
            if (doRetry) {
                response.setHeader("Refresh", next + ";url=" + redirectUrl);
                response.setStatus(HttpServletResponse.SC_TEMPORARY_REDIRECT);
            }
        }
        return;
    } else if (ahsEnabled) {
        String ahsRedirectUrl = ahsRedirectPath(uriWithQueryString, rmWebApp);
        if (ahsRedirectUrl != null) {
            response.setHeader("Location", ahsRedirectUrl);
            response.setStatus(HttpServletResponse.SC_TEMPORARY_REDIRECT);
            return;
        }
    }

    super.doFilter(request, response, chain);
}

From source file:com.haulmont.cuba.restapi.DataServiceController.java

private void sendError(HttpServletRequest request, HttpServletResponse response, Throwable e)
        throws IOException {
    log.error("Error processing request: " + request.getRequestURI() + "?" + request.getQueryString(), e);

    Configuration configuration = AppBeans.get(Configuration.class);
    boolean isProductionMode = configuration.getConfig(RestConfig.class).getProductionMode();

    String msg;//from   w  ww.  ja  v a  2 s  .  c  o  m
    if (isProductionMode) {
        msg = "Internal server error";
    } else {
        Throwable t = ExceptionUtils.getRootCause(e);
        msg = t != null ? ExceptionUtils.getStackTrace(t) : ExceptionUtils.getStackTrace(e);
    }
    response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg);
}

From source file:com.versatus.jwebshield.filter.SecurityFilter.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {

    // Assume its HTTP
    HttpServletRequest httpReq = (HttpServletRequest) request;

    String reqInfo = "J-WebShield Alert: CSRF attack detected! request URL="
            + httpReq.getRequestURL().toString() + "| from IP address=" + httpReq.getRemoteAddr();

    logger.debug("doFilter: IP address=" + httpReq.getRemoteAddr());
    logger.debug("doFilter: pathInfo=" + httpReq.getPathInfo());
    logger.debug("doFilter: queryString=" + httpReq.getQueryString());
    logger.debug("doFilter: requestURL=" + httpReq.getRequestURL().toString());
    logger.debug("doFilter: method=" + httpReq.getMethod());
    logger.debug("doFilter: Origin=" + httpReq.getHeader("Origin"));
    logger.info("doFilter: Referer=" + httpReq.getHeader("Referer"));
    logger.info("doFilter: " + csrfHeaderName + "=" + httpReq.getHeader(csrfHeaderName));

    UrlExclusionList exclList = (UrlExclusionList) request.getServletContext()
            .getAttribute(SecurityConstant.CSRF_CHECK_URL_EXCL_LIST_ATTR_NAME);
    HttpSession session = httpReq.getSession(false);
    if (session == null) {
        chain.doFilter(request, response);
        return;/*from w  ww  . ja  va2 s.  co  m*/
    }

    logger.debug("doFilter: matching " + httpReq.getRequestURI() + " to exclusions list "
            + exclList.getExclusionMap());

    try {
        if (!exclList.isEmpty() && exclList.isMatch(httpReq.getRequestURI())) {
            chain.doFilter(request, response);
            return;
        }
    } catch (Exception e) {
        logger.error("doFilter", e);
    }
    // check CSRF cookie/header
    boolean csrfHeaderPassed = false;
    String rawCsrfHeaderVal = httpReq.getHeader(csrfHeaderName);
    if (useCsrfToken && StringUtils.isNotBlank(rawCsrfHeaderVal)) {
        String csrfHeader = StringUtils.strip(httpReq.getHeader(csrfHeaderName), "\"");
        logger.debug("doFilter: csrfHeader after decoding" + csrfHeader);
        Cookie[] cookies = httpReq.getCookies();
        for (Cookie c : cookies) {
            String name = c.getName();

            if (StringUtils.isNotBlank(csrfCookieName) && csrfCookieName.equals(name)) {

                logger.debug("doFilter: cookie domain=" + c.getDomain() + "|name=" + name + "|value="
                        + c.getValue() + "|path=" + c.getPath() + "|maxage=" + c.getMaxAge() + "|httpOnly="
                        + c.isHttpOnly());

                logger.debug("doFilter: string comp:" + StringUtils.difference(csrfHeader, c.getValue()));

                if (StringUtils.isNotBlank(csrfHeader) && csrfHeader.equals(c.getValue())) {

                    csrfHeaderPassed = true;
                    logger.info("Header " + csrfHeaderName + " value matches the cookie " + csrfCookieName);
                    break;
                } else {
                    logger.info(
                            "Header " + csrfHeaderName + " value does not match the cookie " + csrfCookieName);
                }
            }

        }
        // String csrfCookieVal = (String) session
        // .getAttribute(SecurityConstant.CSRFCOOKIE_VALUE_PARAM);
        // if (csrfCookieVal != null && csrfCookieVal.equals(csrfHeader)) {
        // // chain.doFilter(request, response);
        // // return;
        // csrfHeaderPassed = true;
        // } else {
        // // logger.info(reqInfo);
        // // sendSecurityReject(response);
        // }
    }

    if (useCsrfToken && csrfHeaderPassed) {
        chain.doFilter(request, response);
        return;
    }

    // Validate that the salt is in the cache
    Cache<SecurityInfo, SecurityInfo> csrfPreventionSaltCache = (Cache<SecurityInfo, SecurityInfo>) httpReq
            .getSession().getAttribute(SecurityConstant.SALT_CACHE_ATTR_NAME);

    if (csrfPreventionSaltCache != null) {
        // Get the salt sent with the request
        String saltName = (String) httpReq.getSession().getAttribute(SecurityConstant.SALT_PARAM_NAME);

        logger.debug("doFilter: csrf saltName=" + saltName);

        if (saltName != null) {

            String salt = httpReq.getParameter(saltName);

            logger.debug("doFilter: csrf salt=" + salt);

            if (salt != null) {

                SecurityInfo si = new SecurityInfo(saltName, salt);

                logger.debug("doFilter: csrf token=" + csrfPreventionSaltCache.getIfPresent(si));

                SecurityInfo cachedSi = csrfPreventionSaltCache.getIfPresent(si);
                if (cachedSi != null) {
                    // csrfPreventionSaltCache.invalidate(si);
                    if (SecurityTokenFilter.checkReferer) {
                        String refHeader = StringUtils.defaultString(httpReq.getHeader("Referer"));
                        logger.debug("doFilter: refHeader=" + refHeader);
                        if (StringUtils.isNotBlank(refHeader)) {
                            try {
                                URL refUrl = new URL(refHeader);
                                refHeader = refUrl.getHost();
                            } catch (MalformedURLException mex) {
                                logger.debug("doFilter: parsing referer header failed", mex);
                            }
                        }
                        if (!cachedSi.getRefererHost().isEmpty()
                                && !refHeader.equalsIgnoreCase(cachedSi.getRefererHost())) {
                            logger.info("Potential CSRF detected - Referer host does not match orignal! "
                                    + refHeader + " != " + cachedSi.getRefererHost());
                            sendSecurityReject(response);
                        }
                    }

                    chain.doFilter(request, response);
                } else {
                    logger.info(reqInfo);
                    sendSecurityReject(response);
                }
            } else if (httpMethodMatch(httpReq.getMethod())) {
                // let flow through
                chain.doFilter(request, response);
            } else {
                logger.info(reqInfo);
                sendSecurityReject(response);
            }
        }
    } else {
        chain.doFilter(request, response);
    }

}

From source file:com.microsoft.azure.oidc.filter.helper.impl.SimpleAuthenticationHelper.java

private String getAuthenticationEndPoint(final HttpServletRequest httpRequest, final Token token,
        final Boolean isError) {
    if (httpRequest == null) {
        throw new PreconditionException("Required parameter is null");
    }//from  w w  w.j a  v  a2  s. c o  m
    try {
        final String requestURI = httpRequest.getRequestURI();
        final String queryString = httpRequest.getQueryString();
        final ApplicationSettings applicationSettings = applicationSettingsLoader.load();
        final Configuration configuration = configurationCache.load();
        if (configuration == null) {
            throw new GeneralException("Error loading configuration");
        }
        final HttpSession session = httpRequest.getSession(false);
        final String sessionName = session == null ? "" : session.getId();
        final StringBuilder uriStringBuilder = new StringBuilder();
        Base64 encoder = new Base64();

        if (isError) {
            final State previousState = getState(httpRequest);
            uriStringBuilder.append(previousState.getRequestURI());
        } else {
            uriStringBuilder.append(requestURI);
            if (queryString != null && !"".equals(queryString.trim())) {
                uriStringBuilder.append("?");
                uriStringBuilder.append(queryString);
            }
        }

        final String userID = token == null ? "" : token.getUserID().getValue();
        final State state = stateFactory.createState(userID, sessionName, uriStringBuilder.toString());
        final ObjectMapper mapper = new ObjectMapper();
        final String stateString = mapper.writeValueAsString(state);
        final String urlString = String.format(
                "%s%sclient_Id=%s&state=%s&nonce=defaultNonce&redirect_uri=%s&scope=openid%%20offline_access&response_type=code+id_token&prompt=%s&response_mode=form_post",
                configuration.getAuthenticationEndPoint(),
                configuration.getAuthenticationEndPoint().getName().contains("?") ? "&" : "?",
                applicationSettings.getApplicationId(),
                new String(encoder.encode(stateString.getBytes()), "UTF-8"),
                URLEncoder.encode(applicationSettings.getRedirectURL().getValue(), "UTF-8"),
                token == null ? "login" : "none");
        return urlString;
    } catch (IOException e) {
        throw new GeneralException("IO Exception", e);
    }
}

From source file:com.sinosoft.one.mvc.web.impl.thread.ActionEngine.java

public int isAccepted(HttpServletRequest request) {
    if (paramExistenceChecker.length == 0) { //??1
        return 1;
    }//www .  j av  a2s  . co m
    int total = 0;
    Map<String, String[]> params = resolveQueryString(request.getQueryString());
    for (ParamExistenceChecker checker : paramExistenceChecker) {
        int c = checker.check(params);
        if (c == -1) { //-1??
            if (logger.isDebugEnabled()) {
                logger.debug("Accepted check not passed by " + checker.toString());
            }
            return -1;
        }
        //FIXME ??????
        //?????
        total += c;
    }
    return total;
}

From source file:org.iqvis.nvolv3.request.filter.LoggingFilter.java

@SuppressWarnings("unused")
private void logRequest(final HttpServletRequest request) {
    StringBuilder msg = new StringBuilder();
    msg.append(REQUEST_PREFIX);/*  w  w w .  j  av  a2  s  .  c o  m*/
    if (request instanceof RequestWrapper) {
        msg.append("request id=").append(((RequestWrapper) request).getId()).append("; ");
    }
    HttpSession session = request.getSession(false);
    if (session != null) {
        msg.append("session id=").append(session.getId()).append("; ");
    }
    if (request.getContentType() != null) {
        msg.append("content type=").append(request.getContentType()).append("; ");
    }
    msg.append("uri=").append(request.getRequestURI());
    if (request.getQueryString() != null) {
        msg.append('?').append(request.getQueryString());
    }

    if (request instanceof RequestWrapper && !isMultipart(request)) {
        RequestWrapper requestWrapper = (RequestWrapper) request;
        try {
            String charEncoding = requestWrapper.getCharacterEncoding() != null
                    ? requestWrapper.getCharacterEncoding()
                    : "UTF-8";
            msg.append("; payload=").append(new String(requestWrapper.toByteArray(), charEncoding));
        } catch (UnsupportedEncodingException e) {
            logger.warn("Failed to parse request payload", e);
        }

    }
    logger.debug(msg.toString());
}

From source file:com.ms.app.web.commons.valve.AccessControlValue.java

/***
 * ?/*w w w  . ja  v a2 s .  co m*/
 */
public PipelineResult invoke(HttpServletRequest request, HttpServletResponse response, PipelineMap map)
        throws Exception {
    BaseWebUser webUser = BaseWebUser.getCurrentUser();
    CookieManager cookieManager = CookieManagerLocator.get(request, response);
    // ?
    if (webUser != null && webUser.isHasLogin()) {
        cookieManager.set(CookieKeyEnum.last_access_time, String.valueOf(System.currentTimeMillis()));
        return null;
    }
    String uri = request.getRequestURI();
    boolean canAnonymousAccess = canAnonymousAccess(uri);
    if (canAnonymousAccess) {
        return null;
    }
    String qs = request.getQueryString();
    if (qs != null) {
        uri = uri + "?" + qs;
    }
    boolean isAjax = InvokeTypeTools.isAjax(request);
    if (isAjax) {
        String callback = request.getParameter("callback");
        if (StringUtils.isEmpty(callback)) {
            String needLogin = JsonResultUtils.getNeedLoginJson();
            response.getOutputStream().write(needLogin.getBytes("utf-8"));
        } else {
            String needLogin = JSONPResultUtils.getNeedLoginJson(callback);
            response.getOutputStream().write(needLogin.getBytes("utf-8"));
        }
        return PipelineResult.gotoFinally("gotoLogin", null);
    } else {
        String returnUrl = request.getParameter("returnurl");
        String gotoUrl = normalUrl;
        gotoUrl = gotoUrl + "?returnurl=" + (returnUrl == null ? uri : returnUrl);
        logger.info("gotouri=" + gotoUrl);
        return PipelineResult.gotoFinally("gotoLogin", gotoUrl);
    }

}

From source file:org.mitre.dsmiley.httpproxy.URITemplateProxyServlet.java

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

    //First collect params
    /*/*  w  ww  . jav a  2s .  co 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<String, String>();
    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) {
            throw new ServletException("Missing HTTP parameter " + arg + " to fill the template");
        }
        matcher.appendReplacement(urlBuf, replacement);
    }
    matcher.appendTail(urlBuf);
    String newTargetUri = urlBuf.toString();
    servletRequest.setAttribute(ATTR_TARGET_URI, newTargetUri);
    URI targetUriObj;
    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());

    super.service(servletRequest, servletResponse);
}

From source file:au.org.ala.biocache.web.MapController.java

private String getQueryHash(HttpServletRequest request)
        throws NoSuchAlgorithmException, UnsupportedEncodingException {
    MessageDigest md = MessageDigest.getInstance("MD5");
    md.update(request.getQueryString().getBytes("UTF-8"));
    byte[] digest = md.digest();
    StringBuffer sb = new StringBuffer();
    for (byte b : digest) {
        sb.append(Integer.toHexString((int) (b & 0xff)));
    }/*w w  w . j  a va2s  . co m*/
    return sb.toString();
}

From source file:com.twinsoft.convertigo.engine.util.HttpServletRequestTwsWrapper.java

public HttpServletRequestTwsWrapper(HttpServletRequest request) {
    super(request);
    try {/*from   w  ww . j av  a2 s . co  m*/
        if (request.getCharacterEncoding() == null) {
            request.setCharacterEncoding("UTF-8");
        }

        if (request.getMethod().equalsIgnoreCase("PUT")
                && MimeType.WwwForm.is(HeaderName.ContentType.getHeader(request))) {
            try {
                String content = IOUtils.toString(request.getInputStream(), request.getCharacterEncoding());
                addQuery(content);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        // parse GET parameters
        addQuery(request.getQueryString());

        // retrieve POST parameters ( == not defined in GET )
        for (Entry<String, String[]> entry : GenericUtils.<Map<String, String[]>>cast(request.getParameterMap())
                .entrySet()) {
            if (!parameters.containsKey(entry.getKey())) {
                parameters.put(entry.getKey(), entry.getValue());
            }
        }
    } catch (UnsupportedEncodingException e) {
        parameters.clear();
        parameters.putAll(GenericUtils.<Map<String, String[]>>cast(request.getParameterMap()));
    }
}