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.turn.splicer.SplicerServlet.java

/**
 * Parses a TsQuery out of request, divides into subqueries, and writes result
 * from openTsdb//from   w  ww.  j  av  a  2 s .c o m
 *
 * Format for GET request:
 * start - required start time of query
 * end - optional end time of query, if not provided will use current time as end
 * x - expression (functions + metrics)
 * m - metrics only - no functions, [aggregator]:[optional_downsampling]:metric{optional tags}
 * either x or m must be provided, otherwise nothing to query!
 * ms - optional for millisecond resolution
 * padding - optional pad front of value's with 0's
 *
 *example:
 * /api/query?start=1436910725795&x=abs(sum:1m-avg:tcollector.collector.lines_received)"
 * @param request
 * @param response
 * @throws IOException
 */
private void doGetWork(HttpServletRequest request, HttpServletResponse response) throws IOException {
    LOG.info(request.getQueryString());

    final TsQuery dataQuery = new TsQuery();

    dataQuery.setStart(request.getParameter("start"));
    dataQuery.setEnd(request.getParameter("end"));

    dataQuery.setPadding(Boolean.valueOf(request.getParameter("padding")));

    if (request.getParameter("ms") != null) {
        dataQuery.setMsResolution(true);
    }

    List<ExpressionTree> expressionTrees = null;

    final String[] expressions = request.getParameterValues("x");

    if (expressions != null) {
        expressionTrees = new ArrayList<ExpressionTree>();
        List<String> metricQueries = new ArrayList<String>();

        SplicerUtils.syntaxCheck(expressions, dataQuery, metricQueries, expressionTrees);
    }

    //not supporting metric queries from GET yet...
    //TODO: fix this or decide if we need to support "m" type queries
    if (request.getParameter("m") != null) {
        final List<String> legacy_queries = Arrays.asList(request.getParameterValues("m"));
        for (String q : legacy_queries) {
            SplicerUtils.parseMTypeSubQuery(q, dataQuery);
        }
    }

    LOG.info("Serving query={}", dataQuery);

    LOG.info("Original TsQuery Start time={}, End time={}", Const.tsFormat(dataQuery.startTime()),
            Const.tsFormat(dataQuery.endTime()));

    response.setCharacterEncoding("UTF-8");
    response.setContentType("application/json");

    try (RegionChecker checker = REGION_UTIL.getRegionChecker()) {
        List<TsdbResult[]> exprResults = Lists.newArrayList();
        if (expressionTrees == null || expressionTrees.size() == 0) {
            System.out.println("expression trees == null...figure this out later");
            response.getWriter().write("No expression or error parsing expression");
        } else {
            try {
                List<Future<TsdbResult[]>> futureList = new ArrayList<Future<TsdbResult[]>>(
                        expressionTrees.size());

                TsQuery prev = null;

                for (ExpressionTree expressionTree : expressionTrees) {
                    futureList.add(pool.submit(new ExpressionTreeWorker(expressionTree)));
                }

                for (Future<TsdbResult[]> future : futureList) {
                    exprResults.add(future.get());
                }
                response.getWriter().write(TsdbResult.toJson(SplicerUtils.flatten(exprResults)));
            } catch (Exception e) {
                LOG.error("Could not evaluate expression tree", e);
                e.printStackTrace();
            }
        }
    }
}

From source file:fr.aliasource.webmail.server.LoginFilter.java

private String computeMyUrl(HttpServletRequest hreq, HttpServletResponse resp) {
    StringBuilder ret = new StringBuilder(hreq.getRequestURL().toString());
    if (hreq.getQueryString() != null) {
        ret.append("?");
        ret.append(hreq.getQueryString());
    }/*from w  w  w  .  jav  a  2  s . co m*/
    try {
        return URLEncoder.encode(resp.encodeRedirectURL(ret.toString()), "UTF-8");
    } catch (UnsupportedEncodingException e) {
        return hreq.getRequestURL().toString();
    }
}

From source file:net.community.chest.gitcloud.facade.backend.git.BackendReceivePackFactory.java

@Override
public ReceivePack create(C request, Repository db)
        throws ServiceNotEnabledException, ServiceNotAuthorizedException {
    final String logPrefix;
    if (request instanceof HttpServletRequest) {
        HttpServletRequest req = (HttpServletRequest) request;
        logPrefix = "create(" + req.getMethod() + ")[" + req.getRequestURI() + "][" + req.getQueryString()
                + "]";
    } else {/*from   w w  w . j av  a2s.c  o  m*/
        logPrefix = "create(" + db.getDirectory() + ")";
    }
    if (logger.isDebugEnabled()) {
        logger.debug(logPrefix + ": " + db.getDirectory());
    }

    ReceivePack receive = new ReceivePack(db) {
        @Override
        @SuppressWarnings("synthetic-access")
        public void receive(InputStream input, OutputStream output, OutputStream messages) throws IOException {
            InputStream effIn = input;
            OutputStream effOut = output, effMessages = messages;
            if (logger.isTraceEnabled()) {
                LineLevelAppender inputAppender = new LineLevelAppender() {
                    @Override
                    public void writeLineData(CharSequence lineData) throws IOException {
                        logger.trace(logPrefix + " upload(C): " + lineData);
                    }

                    @Override
                    public boolean isWriteEnabled() {
                        return true;
                    }
                };
                effIn = new TeeInputStream(effIn, new HexDumpOutputStream(inputAppender), true);

                LineLevelAppender outputAppender = new LineLevelAppender() {
                    @Override
                    public void writeLineData(CharSequence lineData) throws IOException {
                        logger.trace(logPrefix + " upload(S): " + lineData);
                    }

                    @Override
                    public boolean isWriteEnabled() {
                        return true;
                    }
                };
                effOut = new TeeOutputStream(effOut, new HexDumpOutputStream(outputAppender));

                if (effMessages != null) {
                    LineLevelAppender messagesAppender = new LineLevelAppender() {
                        @Override
                        public void writeLineData(CharSequence lineData) throws IOException {
                            logger.trace(logPrefix + " upload(M): " + lineData);
                        }

                        @Override
                        public boolean isWriteEnabled() {
                            return true;
                        }
                    };
                    // TODO review the decision to use an AsciiLineOutputStream here
                    effMessages = new TeeOutputStream(effMessages, new AsciiLineOutputStream(messagesAppender));
                }
            }

            super.receive(effIn, effOut, effMessages);
        }
    };
    receive.setTimeout(receiveTimeoutValue);

    // TODO set pushing user identity for reflog
    // receive.setRefLogIdent(new PersonIdent(user.username, user.username + "@" + origin))

    // TODO set advanced options
    // receive.setAllowCreates(user.canCreateRef(repository));
    // receive.setAllowDeletes(user.canDeleteRef(repository));
    // receive.setAllowNonFastForwards(user.canRewindRef(repository));

    // TODO setup the receive hooks
    // receive.setPreReceiveHook(preRcvHook);
    // receive.setPostReceiveHook(postRcvHook);

    return receive;
}

From source file:io.soabase.web.filters.LanguageFilter.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    if (request instanceof HttpServletRequest) {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        AtomicReference<String> fixedQueryString = new AtomicReference<>();
        String queryStringCode = getFromQueryString(httpRequest.getQueryString(), fixedQueryString);
        String expectedLanguageCode = MoreObjects.firstNonNull(queryStringCode,
                getLanguageCode(null, getCookie(httpRequest)));
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        Optional<String> foundCookie = getCookie(httpRequest);
        if (!foundCookie.isPresent() || !foundCookie.get().equals(expectedLanguageCode)) {
            Cookie cookie = new Cookie(cookieName, expectedLanguageCode);
            httpResponse.addCookie(cookie);
        }//from   w  w w .ja v  a2  s  .  co m

        if (queryStringCode != null) {
            StringBuffer redirectUrl = httpRequest.getRequestURL();
            if (!fixedQueryString.get().isEmpty()) {
                redirectUrl.append("?").append(fixedQueryString.get());
            }
            ((HttpServletResponse) response).sendRedirect(redirectUrl.toString());
            return;
        }
    }
    chain.doFilter(request, response);
}

From source file:org.iwethey.forums.web.admin.AdminInterceptor.java

/**
 * <p>Check the session for an authenticated admin user. If none, redirect to
 * the login page.</p>//from   w w  w  .  ja v a2s.co m
 *
 * @param request The servlet request object.
 * @param response The servlet response object.
 * @param handler The request handler processing this request.
 */
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
        throws Exception {
    Integer id = (Integer) WebUtils.getSessionAttribute(request, USER_ID_ATTRIBUTE);

    if (id == null) {
        String uri = request.getServletPath();
        String query = request.getQueryString();

        ModelAndView mv = new ModelAndView(new RedirectView("../user/login.iwt"));

        throw new ModelAndViewDefiningException(mv);
    } else {
        User u = mUserManager.getUserById(id);

        return u.isAdmin();
    }
}

From source file:com.googlecode.psiprobe.controllers.apps.RemoveApplicationAttributeController.java

protected ModelAndView handleContext(String contextName, Context context, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    String attrName = ServletRequestUtils.getStringParameter(request, "attr");
    context.getServletContext().removeAttribute(attrName);

    return new ModelAndView(
            new RedirectView(request.getContextPath() + getViewName() + "?" + request.getQueryString()));
}

From source file:com.sielpe.controller.GestionarCandidatos.java

/**
 * peticion listar Elecciones/*  w  w w  .  j  a v  a 2 s.c o  m*/
 *
 * @param request
 * @param response
 * @throws IOException
 * @throws ServletException
 */
public void ListarCandidatos(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    if (request.getQueryString() == null || request.getParameter("msg") != null) {
        ArrayList<Candidato> listaCandidatos = (ArrayList) facadeDAO.listarCandidatos();
        request.setAttribute("listCandidatos", listaCandidatos);
        request.getRequestDispatcher("GestionCandidatos.jsp").forward(request, response);
    } else {
        redireccionNuevoCandidato(request, response);
    }
}

From source file:io.kamax.mxisd.controller.identity.v1.SessionRestController.java

@RequestMapping(value = "/3pid/getValidated3pid")
String check(HttpServletRequest request, HttpServletResponse response, @RequestParam String sid,
        @RequestParam("client_secret") String secret) {
    log.info("Requested: {}", request.getRequestURL(), request.getQueryString());

    try {//ww w . ja v a  2s .c o m
        ThreePidValidation pid = mgr.getValidated(sid, secret);

        JsonObject obj = new JsonObject();
        obj.addProperty("medium", pid.getMedium());
        obj.addProperty("address", pid.getAddress());
        obj.addProperty("validated_at", pid.getValidation().toEpochMilli());

        return gson.toJson(obj);
    } catch (SessionNotValidatedException e) {
        log.info("Session {} was requested but has not yet been validated", sid);
        throw e;
    }
}

From source file:net.eusashead.hateoas.hal.response.impl.AbstractHalResponseBuilder.java

/**
 * Construct a {@link ResponseBuilder} with
 * the supplied {@link RepresentationFactory}
 * and {@link HttpServletRequest}/*  w  w  w . ja v a  2s  .  c o m*/
 * @param representationFactory {@link RepresentationFactory} for constructing the HAL {@link Representation}
 * @param request incoming {@link HttpServletRequest} for which the response is built for
 */
public AbstractHalResponseBuilder(RepresentationFactory representationFactory, HttpServletRequest request) {

    super(request);

    // Set the RepresentationFactory
    this.representationFactory = representationFactory;

    // Create the URI for the resource
    StringBuilder uriBuilder = new StringBuilder(request.getRequestURI());
    if (request.getQueryString() != null) {
        uriBuilder.append("?");
        uriBuilder.append(request.getQueryString());
    }
    this.uri = uriBuilder.toString();

    // Create representation
    this.entity = representationFactory.newRepresentation(uri);
}

From source file:ch.unifr.pai.twice.widgets.mpproxy.server.SimpleHttpUrlConnectionServletFilter.java

/**
 * @param request/*from w  w  w  .java2 s .  c om*/
 * @return the full request string including GET-parameters
 */
private String getFullRequestString(HttpServletRequest request) {
    StringBuilder sb = new StringBuilder();
    sb.append(request.getRequestURL());
    if (request.getQueryString() != null) {
        sb.append("?");
        sb.append(request.getQueryString());
    }
    return sb.toString();
}