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:net.sourceforge.subsonic.backend.controller.RedirectionController.java

private String getFullRequestURL(HttpServletRequest request) throws UnsupportedEncodingException {
    StringBuilder builder = new StringBuilder(request.getRequestURL());

    // For backwards compatibility; return query parameters in exact same sequence.
    if ("GET".equalsIgnoreCase(request.getMethod())) {
        if (request.getQueryString() != null) {
            builder.append("?").append(request.getQueryString());
        }/*from   ww  w  .  j  av a  2  s .co  m*/
        return builder.toString();
    }

    builder.append("?");

    Enumeration<?> paramNames = request.getParameterNames();
    while (paramNames.hasMoreElements()) {
        String paramName = (String) paramNames.nextElement();
        String[] paramValues = request.getParameterValues(paramName);
        for (String paramValue : paramValues) {
            String p = URLEncoder.encode(paramValue, "UTF-8");
            builder.append(paramName).append("=").append(p).append("&");
        }
    }

    return builder.toString();
}

From source file:com.epam.cme.storefront.controllers.pages.AbstractPageController.java

protected void storeContinueUrl(final HttpServletRequest request) {
    final StringBuilder url = new StringBuilder();
    url.append(request.getServletPath());
    final String queryString = request.getQueryString();
    if (queryString != null && !queryString.isEmpty()) {
        url.append('?').append(queryString);
    }//from ww  w.jav  a 2  s  .c om
    getSessionService().setAttribute(WebConstants.CONTINUE_URL, url.toString());
}

From source file:org.openmrs.module.openhmis.cashier.web.controller.BillAddEditController.java

private String buildRedirectUrl(HttpServletRequest request) {
    String redirectUrl = "redirect:" + UrlUtil.formUrl(CashierWebConstants.CASHIER_PAGE);
    String returnUrlParam = "?returnUrl=" + UrlUtil.formUrl(CashierWebConstants.BILL_PAGE);
    String requestQueryParam = "";

    if (request.getQueryString() != null) {
        requestQueryParam = encodeRequestQuery(request);
    }/*w w w . ja v a2 s .c o  m*/

    return redirectUrl + returnUrlParam + requestQueryParam;
}

From source file:com.microsoft.applicationinsights.web.extensibility.modules.WebRequestTrackingTelemetryModule.java

/**
 * Begin request processing.//from w  w  w.j a  v a  2s  .  co  m
 * @param req The request to process
 * @param res The response to modify
 */
@Override
public void onBeginRequest(ServletRequest req, ServletResponse res) {
    if (!isInitialized) {
        // Avoid logging to not spam the log. It is sufficient that the module initialization failure
        // has been logged.
        return;
    }

    try {
        RequestTelemetryContext context = ThreadContext.getRequestTelemetryContext();
        RequestTelemetry telemetry = context.getHttpRequestTelemetry();

        HttpServletRequest request = (HttpServletRequest) req;
        String method = request.getMethod();
        String rURI = request.getRequestURI();
        String scheme = request.getScheme();
        String host = request.getHeader("Host");
        String query = request.getQueryString();
        String userAgent = request.getHeader("User-Agent");

        telemetry.setHttpMethod(method);
        if (!Strings.isNullOrEmpty(query)) {
            telemetry.setUrl(String.format("%s://%s%s?%s", scheme, host, rURI, query));
        } else {
            telemetry.setUrl(String.format("%s://%s%s", scheme, host, rURI));
        }

        // TODO: this is a very naive implementation, which doesn't take into account various MVC f/ws implementation.
        // Next step is to implement the smart request name calculation which will support the leading MVC f/ws.
        String rUriWithoutSessionId = removeSessionIdFromUri(rURI);
        telemetry.setName(String.format("%s %s", method, rUriWithoutSessionId));
        telemetry.getContext().getUser().setUserAgent(userAgent);
        telemetry.setTimestamp(new Date(context.getRequestStartTimeTicks()));
    } catch (Exception e) {
        String moduleClassName = this.getClass().getSimpleName();
        InternalLogger.INSTANCE.error(
                "Telemetry module " + moduleClassName + " onBeginRequest failed with exception: %s",
                e.getMessage());
    }
}

From source file:com.yahoo.dba.perf.myperf.springmvc.VarhistoryController.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 w w  w.  jav  a  2  s.  c  om
    DBInstanceInfo dbinfo = null;

    //first session check
    boolean isSessionValid = WebAppUtil.hasValidSession(req);
    if (!isSessionValid)
        return this.respondFailure("session timeout. Please logout and re-login.", req);

    qps = WebAppUtil.parseRequestParameter(req);
    qps.setSql("mysql_global_variables");

    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);

    //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 = new ResultList();
    ColumnDescriptor desc = new ColumnDescriptor();
    desc.addColumn("VARIABLE_NAME", false, 1);
    desc.addColumn("VARIABLE_VALUE", false, 2);
    desc.addColumn("COMMENTS", false, 3);
    rList.setColumnDescriptor(desc);
    try {
        ConfigHistory ch = ConfigHistory
                .load(new File(new File(this.frameworkContext.getFileReposirtoryPath()), "autoscan"), dbinfo);
        if (ch != null && ch.getChanges().size() > 0) {
            {
                ResultRow row = new ResultRow();
                List<String> cols = new ArrayList<String>();
                cols.add("CHANGES");
                cols.add("");
                cols.add(ch.getStartingConfig().getTime() + " - " + ch.getLastCheckedConfig().getTime());
                row.setColumns(cols);
                row.setColumnDescriptor(desc);
                rList.addRow(row);

            }
            //list changed in reverse order
            for (int i = ch.getChanges().size() - 1; i >= 0; i--) {
                ConfigBlock cb = ch.getChanges().get(i);

                ResultRow row = new ResultRow();
                List<String> cols = new ArrayList<String>();
                cols.add("CHANGE TIME");
                cols.add(cb.getTime());
                cols.add("Timestamp (UTC) when checked");
                row.setColumns(cols);
                row.setColumnDescriptor(desc);
                rList.addRow(row);

                HashMap<String, String> changes = new HashMap<String, String>();
                //scan changes with old value
                for (Map.Entry<String, String> e : cb.getVariables().entrySet()) {
                    String key = e.getKey();
                    String val = e.getValue();
                    if (key.startsWith("+-")) {
                        changes.put(key.substring(2), val);
                    }
                }

                for (Map.Entry<String, String> e : cb.getVariables().entrySet()) {
                    String key = e.getKey();
                    String v = e.getValue();
                    row = new ResultRow();
                    cols = new ArrayList<String>();
                    if (key.startsWith("+-"))
                        continue;//skip
                    else if (key.startsWith("+-"))
                        cols.add(key.substring(1));//removed
                    else
                        cols.add(key);
                    cols.add(v);
                    if (changes.containsKey(key))
                        cols.add("Prev Value: " + changes.get(key));
                    else if (key.startsWith("-"))
                        cols.add("Removed");
                    else
                        cols.add("");
                    row.setColumns(cols);
                    row.setColumnDescriptor(desc);
                    rList.addRow(row);
                }
                //add an empty line
                row = new ResultRow();
                cols = new ArrayList<String>();
                cols.add("");
                cols.add("");
                cols.add("");
                row.setColumns(cols);
                row.setColumnDescriptor(desc);
                rList.addRow(row);

            }
        }
        {
            ConfigBlock cb = ch.getStartingConfig();

            ResultRow row = new ResultRow();
            List<String> cols = new ArrayList<String>();
            cols.add("FIRST RECORD TIME");
            cols.add(cb.getTime());
            if (ch != null && ch.getChanges().size() > 0)
                cols.add("First Recorded Timestamp (UTC)");
            else
                cols.add("No Changes Since First Check (Timestamp UTC)");
            row.setColumns(cols);
            row.setColumnDescriptor(desc);
            rList.addRow(row);

            for (Map.Entry<String, String> e : cb.getVariables().entrySet()) {
                String key = e.getKey();
                String v = e.getValue();
                row = new ResultRow();
                cols = new ArrayList<String>();
                cols.add(key);
                cols.add(v);
                cols.add("");
                row.setColumns(cols);
                row.setColumnDescriptor(desc);
                rList.addRow(row);
            }

        }

    } catch (Throwable ex) {
        logger.log(Level.SEVERE, "Exception", ex);
        status = Constants.STATUS_BAD;
        message = "Exception: " + ex.getMessage();
    }

    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(rList, qps, status, message));
    return mv;
}

From source file:org.activiti.app.service.editor.ActivitiModelQueryService.java

public ResultListDataRepresentation getModels(String filter, String sort, Integer modelType,
        HttpServletRequest request) {

    // need to parse the filterText parameter ourselves, due to encoding issues with the default parsing.
    String filterText = null;/*  w  w  w. j  a va 2 s.c om*/
    List<NameValuePair> params = URLEncodedUtils.parse(request.getQueryString(), Charset.forName("UTF-8"));
    if (params != null) {
        for (NameValuePair nameValuePair : params) {
            if ("filterText".equalsIgnoreCase(nameValuePair.getName())) {
                filterText = nameValuePair.getValue();
            }
        }
    }

    List<ModelRepresentation> resultList = new ArrayList<ModelRepresentation>();
    List<Model> models = null;

    String validFilter = makeValidFilterText(filterText);

    User user = SecurityUtils.getCurrentUserObject();

    if (validFilter != null) {
        models = modelRepository.findByModelTypeAndCreatedBy(user.getId(), modelType, validFilter, sort);

    } else {
        models = modelRepository.findByModelTypeAndCreatedBy(user.getId(), modelType, sort);
    }

    if (CollectionUtils.isNotEmpty(models)) {
        List<String> addedModelIds = new ArrayList<String>();
        for (Model model : models) {
            if (addedModelIds.contains(model.getId()) == false) {
                addedModelIds.add(model.getId());
                ModelRepresentation representation = createModelRepresentation(model);
                resultList.add(representation);
            }
        }
    }

    ResultListDataRepresentation result = new ResultListDataRepresentation(resultList);
    return result;
}

From source file:kziomek.filter.logging.MvcLoggingFilter.java

private String buildRequestMessage(final HttpServletRequest request, String prefix) {
    StringBuilder msg = new StringBuilder();
    msg.append(prefix);//from   w w w  . j a va  2 s  .  c  o  m

    /* Query params */
    if (isIncludeQueryString()) {
        msg.append(request.getMethod()).append(" ").append(request.getRequestURI());
        if (request.getQueryString() != null) {
            msg.append('?').append(request.getQueryString());
        }
    }

    /* Headers */
    if (isIncludeHeaders()) {
        Map<String, String> headers = getHeadersInfo(request);
        msg.append(" headers=").append(headers);
    }

    /* Payload */
    if (isIncludePayload()) {
        if (request instanceof BufferedRequestWrapper && !isMultipart(request)) {
            BufferedRequestWrapper requestWrapper = (BufferedRequestWrapper) request;
            try {
                int length = Math.min(requestWrapper.toByteArray().length, getMaxPayloadLength());
                String charEncoding = requestWrapper.getCharacterEncoding() != null
                        ? requestWrapper.getCharacterEncoding()
                        : "UTF-8";
                String payload = new String(requestWrapper.toByteArray(), 0, length, charEncoding).trim()
                        .replace("\n", "");
                if (!StringUtils.isEmpty(payload)) {
                    msg.append(" payload=").append(payload);
                }

            } catch (UnsupportedEncodingException e) {
                logger.warn("Failed to parse request payload", e);
            }
        }
    }
    return msg.toString();
}

From source file:org.jfree.eastwood.ChartServlet.java

/**
 * Process a GET request./*from www  . jav  a 2  s  .  c  o m*/
 *
 * @param request  the request.
 * @param response  the response.
 *
 * @throws ServletException if there is a servlet related problem.
 * @throws IOException if there is an I/O problem.
 */
public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    OutputStream out = response.getOutputStream();

    try {
        Map params = Parameters.parseQueryString(request.getQueryString());
        JFreeChart chart = ChartEngine.buildChart(params, this.font);

        if (chart != null) {
            response.setContentType("image/png");

            // *** CHART SIZE ***
            String[] size = (String[]) params.get("chs");
            int[] dims = new int[2];
            if (size != null) {
                dims = parseChartDimensions(size[0]);
            } else {
                dims = new int[] { 200, 125 };
            }

            ChartUtilities.writeChartAsPNG(out, chart, dims[0], dims[1]);
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        out.close();
    }

}

From source file:org.jetbrains.webdemo.handlers.ServerHandler.java

public void handle(final HttpServletRequest request, final HttpServletResponse response) throws IOException {

    if (request.getQueryString() != null && request.getQueryString().equals("test")) {
        try (PrintWriter out = response.getWriter()) {
            out.write("ok");
        } catch (Throwable e) {
            ErrorWriter.ERROR_WRITER.writeExceptionToExceptionAnalyzer(e, "TEST", request.getHeader("Origin"),
                    "null");
        }/* www .ja v  a  2 s  .  c  o  m*/
    } else {
        SessionInfo sessionInfo;
        if (CommonSettings.IS_TEST_VERSION) {
            response.setHeader("Access-Control-Allow-Origin", "*");
        } else {
            response.setHeader("Access-Control-Allow-Origin",
                    "http://staging.kotlinlang.org.s3-website-eu-west-1.amazonaws.com");
        }
        try {
            switch (request.getParameter("type")) {
            case ("getUserName"):
                sessionInfo = setSessionInfo(request.getSession(), request.getHeader("Origin"));
                sendUserName(request, response, sessionInfo);
                break;
            case ("sendMail"):
                sessionInfo = setSessionInfo(request.getSession(), request.getHeader("Origin"));
                sessionInfo.setType(SessionInfo.TypeOfRequest.SEND_MAIL);
                sendMail(request, response, sessionInfo);
                break;
            case ("loadHelpForWords"):
                sendHelpContentForWords(request, response);
                break;
            case ("getKotlinVersions"):
                sendKotlinVersions(request, response);
                break;
            case ("run"):
                forwardRunRequest(request, response);
                break;
            case ("highlight"):
                forwardHighlightRequest(request, response);
                break;
            case ("complete"):
                forwardCompleteRequest(request, response);
                break;
            case ("convertToKotlin"):
                forwardConvertResult(request, response);
                break;
            default: {
                sessionInfo = setSessionInfo(request.getSession(), request.getHeader("Origin"));
                MyHttpSession session = new MyHttpSession(sessionInfo);
                session.handle(request, response);
            }
            }
        } catch (Throwable e) {
            //Do not stop server
            ErrorWriter.ERROR_WRITER.writeExceptionToExceptionAnalyzer(e, "UNKNOWN", "unknown",
                    request.getRequestURI() + "?" + request.getQueryString());
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    }
}

From source file:com.alibaba.sample.petstore.web.common.PetstoreUserAuth.java

public void onDeny(Status status) throws Exception {
    HttpServletRequest request = status.rundata.getRequest();
    HttpServletResponse response = status.rundata.getResponse();
    URIBroker redirectURI = uriBrokerService.getURIBroker(brokerId);

    assertNotNull(redirectURI, "no URI broker found: %s", brokerId);

    StringBuffer buf = request.getRequestURL();
    String queryString = trimToNull(request.getQueryString());

    if (queryString != null) {
        buf.append('?').append(queryString);
    }//from  w w  w .j a  va 2  s. c o  m

    String returnURL = buf.toString();

    response.sendRedirect(redirectURI.addQueryData(returnKey, returnURL).render());
}