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:it.jugpadova.controllers.EventController.java

private String buildChannelLink(HttpServletRequest req) {
    StringBuffer channelLink = req.getRequestURL();
    if (req.getQueryString() != null) {
        channelLink.append('?').append(req.getQueryString());
    }/*w  w  w  . j a  v a 2 s.  c om*/
    return channelLink.toString();
}

From source file:grails.plugin.cache.web.filter.AbstractFilter.java

/**
 * This method should throw IOExceptions, not wrap them.
 *///from w w w  .ja  v  a  2 s .c  om
protected void logThrowable(final Throwable throwable, final HttpServletRequest httpRequest)
        throws ServletException, IOException {

    StringBuilder messageBuffer = new StringBuilder("Throwable thrown during doFilter on request with URI: ")
            .append(httpRequest.getRequestURI()).append(" and Query: ").append(httpRequest.getQueryString())
            .append(" : ").append(throwable.getMessage());

    if (suppressStackTraces) {
        log.warn(messageBuffer.append("\nTop StackTraceElement: ").append(throwable.getStackTrace()[0])
                .toString());
    } else {
        log.warn(messageBuffer.toString(), throwable);
    }

    if (throwable instanceof IOException) {
        throw (IOException) throwable;
    }

    throw new ServletException(throwable);
}

From source file:AIR.Common.Web.Session.HttpRequestLoggerInitializerFilter.java

@SuppressWarnings("unchecked")
private void addRequestDetailsToLoggers(HttpServletRequest request) {
    final String method = request.getMethod();
    logger.debug("========================== Request Logging Start ===================================");
    logger.debug("Method:       " + method);
    logger.debug("Request URI:  " + request.getRequestURI());
    logger.debug("Received at:  " + MDC.get("requestTime"));
    logger.debug("Query String: " + request.getQueryString());
    logger.debug("<<<<<<<<< Headers start >>>>>>>>>>");

    Enumeration<String> headerNames = request.getHeaderNames();
    while (headerNames.hasMoreElements()) {
        String headerName = headerNames.nextElement();
        String headerValue = request.getHeader(headerName);
        logger.debug(headerName + " : " + headerValue);
    }// ww w. j  a  v  a  2 s .co  m
    logger.debug("<<<<<<<<< Headers end >>>>>>>>>>");
}

From source file:de.adorsys.oauth.server.FixedServletUtils.java

/**
 * Creates a new HTTP request from the specified HTTP servlet request.
 *
 * @param servletRequest              The servlet request. Must not be
 *                        {@code null}./*  w w  w  .j  av a 2  s. c  om*/
 * @param maxEntityLength The maximum entity length to accept, -1 for
 *                        no limit.
 *
 * @return The HTTP request.
 *
 * @throws IllegalArgumentException The the servlet request method is
 *                                  not GET, POST, PUT or DELETE or the
 *                                  content type header value couldn't
 *                                  be parsed.
 * @throws IOException              For a POST or PUT body that
 *                                  couldn't be read due to an I/O
 *                                  exception.
 */
public static HTTPRequest createHTTPRequest(final HttpServletRequest servletRequest, final long maxEntityLength)
        throws IOException {

    HTTPRequest.Method method = HTTPRequest.Method.valueOf(servletRequest.getMethod().toUpperCase());

    String urlString = reconstructRequestURLString(servletRequest);

    URL url;

    try {
        url = new URL(urlString);

    } catch (MalformedURLException e) {

        throw new IllegalArgumentException("Invalid request URL: " + e.getMessage() + ": " + urlString, e);
    }

    HTTPRequest request = new HTTPRequest(method, url);

    try {
        request.setContentType(servletRequest.getContentType());

    } catch (ParseException e) {

        throw new IllegalArgumentException("Invalid Content-Type header value: " + e.getMessage(), e);
    }

    Enumeration<String> headerNames = servletRequest.getHeaderNames();

    while (headerNames.hasMoreElements()) {
        final String headerName = headerNames.nextElement();
        request.setHeader(headerName, servletRequest.getHeader(headerName));
    }

    if (method.equals(HTTPRequest.Method.GET) || method.equals(HTTPRequest.Method.DELETE)) {

        request.setQuery(servletRequest.getQueryString());

    } else if (method.equals(HTTPRequest.Method.POST) || method.equals(HTTPRequest.Method.PUT)) {

        if (maxEntityLength > 0 && servletRequest.getContentLength() > maxEntityLength) {
            throw new IOException("Request entity body is too large, limit is " + maxEntityLength + " chars");
        }

        Map<String, String[]> parameterMap = servletRequest.getParameterMap();
        StringBuilder builder = new StringBuilder();

        if (!parameterMap.isEmpty()) {
            for (Entry<String, String[]> entry : parameterMap.entrySet()) {
                String key = entry.getKey();
                String[] value = entry.getValue();
                if (value.length > 0 && value[0] != null) {
                    String encoded = URLEncoder.encode(value[0], "UTF-8");
                    builder = builder.append(key).append('=').append(encoded).append('&');
                }
            }
            String queryString = StringUtils.substringBeforeLast(builder.toString(), "&");
            request.setQuery(queryString);

        } else {
            // read body
            StringBuilder body = new StringBuilder(256);

            BufferedReader reader = servletRequest.getReader();
            reader.reset();
            char[] cbuf = new char[256];

            int readChars;

            while ((readChars = reader.read(cbuf)) != -1) {

                body.append(cbuf, 0, readChars);

                if (maxEntityLength > 0 && body.length() > maxEntityLength) {
                    throw new IOException(
                            "Request entity body is too large, limit is " + maxEntityLength + " chars");
                }
            }

            reader.reset();
            // reader.close();

            request.setQuery(body.toString());
        }
    }

    return request;
}

From source file:com.mawujun.util.web.UrlPathHelper.java

/**
 * Return the request URI for root of the given request. If this is a forwarded request,
 * correctly resolves to the request URI of the original request.
 * <p>Relies on the Servlet 2.4 'forward' attributes. These attributes may be set by
 * other components when running in a Servlet 2.3 environment.
 * @param request current HTTP request/*  ww  w  . ja  va 2s.c  o  m*/
 * @return the query string
 */
public String getOriginatingQueryString(HttpServletRequest request) {
    String queryString = (String) request.getAttribute(WebUtils.FORWARD_QUERY_STRING_ATTRIBUTE);
    if (queryString == null) {
        queryString = request.getQueryString();
    }
    return queryString;
}

From source file:edu.cornell.mannlib.vitro.webapp.filters.VitroRequestPrep.java

private void logRequestUriForDebugging(HttpServletRequest req) {
    if (log.isDebugEnabled()) {
        try {/*from  w ww  .ja  va  2  s.  co m*/
            String uriString = req.getRequestURI();
            String queryString = req.getQueryString();
            if ((queryString != null) && (queryString.length() > 0)) {
                uriString += "?" + queryString;
            }
            log.debug("RequestURI: " + uriString);
        } catch (Exception e) {
            // Don't want to kill the request if the logging fails.
        }
    }
}

From source file:org.ncbo.stanford.util.security.filter.AuthorizationFilter.java

@Override
protected int beforeHandle(Request request, Response response) {
    int retVal = CONTINUE;

    if (isException(request, response)) {
        return retVal;
    }//from   w w w. ja v  a 2  s . co  m

    HttpServletRequest httpRequest = RequestUtils.getHttpServletRequest(request);
    extractAttributes(request, response);
    Map<String, Object> params = request.getAttributes();
    RequestUtils.parseQueryString(httpRequest.getQueryString(), params);
    RESTfulSession session = (RESTfulSession) params.get(ApplicationConstants.USER_SESSION_NAME);
    SecurityContextHolder ctx = null;
    UserBean user = null;
    ErrorTypeEnum error = null;

    if (session == null
            || (ctx = (SecurityContextHolder) session
                    .getAttribute(ApplicationConstants.SECURITY_CONTEXT_KEY)) == null
            || (user = ctx.getUserBean()) == null) {
        // This should never happen. NULL session means user failed to
        // authenticate but somehow made it to this filter. The security
        // context or user should not be null either.
        error = ErrorTypeEnum.INVALID_SESSION;
    } else {
        // Admin has access to all ontologies
        if (user.isAdmin()) {
            return retVal;
        }

        StringBuffer sb = new StringBuffer(0);
        Map<Integer, Integer> mapTranslated = new HashMap<Integer, Integer>(0);
        List<Integer> ontologyIds = findOntologyIdsInRequest(params, mapTranslated);

        int deniedOntologyId = 0;

        for (Integer ontologyId : ontologyIds) {
            // only the owner of ontology is allowed to
            // executed non-GET requests
            if (!request.getMethod().equals(Method.GET) && !user.isOwner(ontologyId)) {
                deniedOntologyId = ontologyId;
                break;
            }

            // check if ontology is restricted and if so,
            // check that the user is in this ontology's ACL
            if (ontologyService.isInAcl(ontologyId) && !user.isInAcl(ontologyId)) {
                sb.append(mapTranslated.get(ontologyId) + ", ");

                if (deniedOntologyId == 0) {
                    deniedOntologyId = ontologyId;
                }
            }
        }

        if (deniedOntologyId > 0) {
            String ontologyLink = "http://bioportal.bioontology.org/ontologies/" + deniedOntologyId
                    + "?p=terms";
            error = ErrorTypeEnum.ACCESS_DENIED;
            error.setErrorMessage("This ontology is either private or licensed. Please go to " + ontologyLink
                    + " to get access to the ontology.");
        }
    }

    if (error != null) {
        retVal = STOP;
        response.setStatus(Status.CLIENT_ERROR_FORBIDDEN, error.getErrorMessage());
        xmlSerializationService.generateXMLResponse(request, response, null);
    }

    return retVal;
}

From source file:com.yahoo.dba.perf.myperf.springmvc.VardiffController.java

@Override
protected ModelAndView handleRequestImpl(HttpServletRequest req, HttpServletResponse resp) throws Exception {
    int status = Constants.STATUS_OK;
    String message = "OK";

    logger.info("receive url " + req.getQueryString());
    QueryParameters qps = null;/*from  ww  w .  j a  v  a 2  s.  co  m*/
    DBInstanceInfo dbinfo = null;
    DBInstanceInfo dbinfo2 = null;
    DBConnectionWrapper connWrapper = null;
    DBConnectionWrapper connWrapper2 = null;

    qps = WebAppUtil.parseRequestParameter(req);
    qps.setSql("mysql_global_variables");
    qps.getSqlParams().put("p_1", "");
    String group2 = req.getParameter("p_1");
    String host2 = req.getParameter("p_2");
    //validation input
    String validation = qps.validate();
    if (validation == null || validation.isEmpty()) {
        //do we have such query?
        try {
            QueryInputValidator.validateSql(this.frameworkContext.getSqlManager(), qps);
        } catch (Exception ex) {
            validation = ex.getMessage();
        }
    }
    if (validation != null && !validation.isEmpty())
        return this.respondFailure(validation, req);

    dbinfo = this.frameworkContext.getDbInfoManager().findDB(qps.getGroup(), qps.getHost());
    if (dbinfo == null)
        return this.respondFailure("Cannot find record for DB (" + qps.getGroup() + ", " + qps.getHost() + ")",
                req);
    dbinfo2 = this.frameworkContext.getDbInfoManager().findDB(group2, host2);
    if (dbinfo2 == null)
        return this.respondFailure("Cannot find record for DB (" + group2 + ", " + host2 + ")", req);

    try {
        connWrapper = WebAppUtil.getDBConnection(req, this.frameworkContext, dbinfo);
        if (connWrapper == null) {
            status = Constants.STATUS_BAD;
            message = "failed to connect to target db (" + dbinfo + ")";
        } else {
            connWrapper2 = WebAppUtil.getDBConnection(req, this.frameworkContext, dbinfo2);
            if (connWrapper2 == null) {
                status = Constants.STATUS_BAD;
                message = "failed to connect to target db (" + dbinfo2 + ")";
            }
        }
    } catch (Throwable th) {
        logger.log(Level.SEVERE, "Exception", th);
        status = Constants.STATUS_BAD;
        message = "Failed to get connection to target db (" + dbinfo + "): " + th.getMessage();
    }

    if (status == -1)
        return this.respondFailure(message, req);

    //when we reach here, at least we have valid query and can connect to db   
    WebAppUtil.storeLastDbInfoRequest(qps.getGroup(), qps.getHost(), req);
    ModelAndView mv = null;
    ResultList rList = null;
    ResultList rList2 = null;

    try {
        rList = this.frameworkContext.getQueryEngine().executeQueryGeneric(qps, connWrapper, qps.getMaxRows());
        rList2 = this.frameworkContext.getQueryEngine().executeQueryGeneric(qps, connWrapper2,
                qps.getMaxRows());
        logger.info("Done query " + qps.getSql() + " with " + (rList != null ? rList.getRows().size() : 0)
                + " records, " + (rList2 != null ? rList2.getRows().size() : 0) + " records");
        WebAppUtil.closeDBConnection(req, connWrapper, false);
        WebAppUtil.closeDBConnection(req, connWrapper2, false);
    } catch (Throwable ex) {
        logger.log(Level.SEVERE, "Exception", ex);
        if (ex instanceof SQLException) {
            SQLException sqlEx = SQLException.class.cast(ex);
            String msg = ex.getMessage();
            logger.info(sqlEx.getSQLState() + ", " + sqlEx.getErrorCode() + ", " + msg);
            //check if the connection is still good
            if (!DBUtils.checkConnection(connWrapper.getConnection())) {
                WebAppUtil.closeDBConnection(req, connWrapper, true);
            } else
                WebAppUtil.closeDBConnection(req, connWrapper, true);
            if (!DBUtils.checkConnection(connWrapper2.getConnection())) {
                WebAppUtil.closeDBConnection(req, connWrapper2, true);
            } else
                WebAppUtil.closeDBConnection(req, connWrapper2, true);
        } else {
            WebAppUtil.closeDBConnection(req, connWrapper, false);
            WebAppUtil.closeDBConnection(req, connWrapper2, false);
        }
        status = Constants.STATUS_BAD;
        message = "Exception: " + ex.getMessage();
    }

    if (status == Constants.STATUS_BAD)
        return this.respondFailure(message, req);

    HashMap<String, String> param1 = new HashMap<String, String>(rList.getRows().size());
    HashMap<String, String> param2 = new HashMap<String, String>(rList2.getRows().size());
    for (ResultRow r : rList.getRows()) {
        param1.put(r.getColumns().get(0), r.getColumns().get(1));
    }
    for (ResultRow r : rList2.getRows()) {
        param2.put(r.getColumns().get(0), r.getColumns().get(1));
    }
    ColumnDescriptor desc = new ColumnDescriptor();
    desc.addColumn("VARIABLE_NAME", false, 1);
    desc.addColumn("DB1", false, 2);
    desc.addColumn("DB2", false, 3);

    ResultList fList = new ResultList();
    fList.setColumnDescriptor(desc);

    HashSet<String> diffSet = new HashSet<String>();
    for (Map.Entry<String, String> e : param1.entrySet()) {
        String k = e.getKey();
        String v = e.getValue();
        if (v != null)
            v = v.trim();
        else
            v = "";
        String v2 = null;
        if (param2.containsKey(k))
            v2 = param2.get(k);
        if (v2 != null)
            v2 = v2.trim();
        else
            v2 = "";
        if (!v.equals(v2)) {
            ResultRow row = new ResultRow();
            List<String> cols = new ArrayList<String>();
            cols.add(k);
            cols.add(v);
            cols.add(v2);
            row.setColumns(cols);
            row.setColumnDescriptor(desc);
            fList.addRow(row);
            diffSet.add(k);
        }
    }

    for (Map.Entry<String, String> e : param2.entrySet()) {
        String k = e.getKey();
        String v = e.getValue();
        if (v == null || v.isEmpty())
            continue;
        if (diffSet.contains(k) || param1.containsKey(k))
            continue;
        ResultRow row = new ResultRow();
        List<String> cols = new ArrayList<String>();
        cols.add(k);
        cols.add("");
        cols.add(v);
        row.setColumns(cols);
        row.setColumnDescriptor(desc);
        fList.addRow(row);
    }

    mv = new ModelAndView(this.jsonView);
    if (req.getParameter("callback") != null && req.getParameter("callback").trim().length() > 0)
        mv.addObject("callback", req.getParameter("callback"));//YUI datasource binding

    mv.addObject("json_result", ResultListUtil.toJSONString(fList, qps, status, message));
    return mv;
}

From source file:com.example.HoneycombFilter.java

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

    if (!(request instanceof HttpServletRequest)) {
        chain.doFilter(request, response);
        return;/*from  ww w .  j a v  a 2  s  .  co  m*/
    }
    HttpServletRequest req = (HttpServletRequest) request;
    long start = System.nanoTime();
    try {
        chain.doFilter(request, response);
    } finally {
        long responseTimeNanos = System.nanoTime() - start;
        Event event = libhoney.newEvent();
        event.addField("method", req.getMethod());
        event.addField("path", req.getRequestURI());
        event.addField("query", req.getQueryString());
        Principal principal = req.getUserPrincipal();
        if (principal != null) {
            event.addField("user", principal.getName());
        }
        event.addField("host", req.getRemoteHost());
        event.addField("responseTimeNanos", responseTimeNanos);
        try {
            event.send();
        } catch (HoneyException e) {
            log.error(e.getMessage(), e);
        }
    }
}

From source file:com.sun.socialsite.web.filters.CustomizedPageFragmentCachingFilter.java

@Override
protected String calculateKey(final HttpServletRequest req) {
    String uri = null;/*from  w w  w. java2s  . co m*/
    String query = null;

    if (req.getAttribute("javax.servlet.include.request_uri") != null) {
        uri = (String) (req.getAttribute("javax.servlet.include.request_uri"));
        query = (String) (req.getAttribute("javax.servlet.include.query_string"));
    } else {
        uri = req.getRequestURI();
        query = req.getQueryString();
    }

    // TODO: something better than this anonymous/loggedin workaround
    StringBuilder sb = new StringBuilder();
    sb.append((req.getRemoteUser() != null) ? "LOGGED_IN" : "ANONYMOUS");
    sb.append("|");
    sb.append(req.getMethod());
    sb.append("|");
    sb.append(uri);
    if (query != null) {
        sb.append("?").append(query);
    }

    String key = sb.toString();
    log.trace("key=" + key);

    return key;
}