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:fr.openwide.talendalfresco.rest.server.ContentImportCommandServlet.java

/**
 * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
 *//*from w w w.  j a v  a 2s .  c o  m*/
protected void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    String uri = req.getRequestURI();

    if (logger.isDebugEnabled())
        logger.debug(
                "Processing URL: " + uri + (req.getQueryString() != null ? ("?" + req.getQueryString()) : ""));

    AuthenticationStatus status = servletAuthenticate(req, res);
    if (status == AuthenticationStatus.Failure) {
        return;
    }

    setNoCacheHeaders(res);

    uri = uri.substring(req.getContextPath().length());
    StringTokenizer t = new StringTokenizer(uri, "/");
    int tokenCount = t.countTokens();
    if (tokenCount < 3) {
        throw new IllegalArgumentException("Command Servlet URL did not contain all required args: " + uri);
    }

    t.nextToken(); // skip servlet name

    // get the command processor to execute the command e.g. "workflow"
    String procName = t.nextToken();

    // get the command to perform
    String command = t.nextToken();

    // get any remaining uri elements to pass to the processor
    String[] urlElements = new String[tokenCount - 3];
    for (int i = 0; i < tokenCount - 3; i++) {
        urlElements[i] = t.nextToken();
    }

    // retrieve the URL arguments to pass to the processor
    Map<String, String> args = new HashMap<String, String>(8, 1.0f);
    Enumeration names = req.getParameterNames();
    while (names.hasMoreElements()) {
        String name = (String) names.nextElement();
        args.put(name, req.getParameter(name));
    }

    try {
        // get configured command processor by name from Config Service
        CommandProcessor processor = createCommandProcessor(procName);

        // validate that the processor has everything it needs to run the command
        if (processor.validateArguments(getServletContext(), command, args, urlElements) == false) {
            redirectToLoginPage(req, res, getServletContext());
            return;
        }

        ServiceRegistry serviceRegistry = getServiceRegistry(getServletContext());
        UserTransaction txn = null;
        try {
            if (!(processor instanceof RestCommandProcessor)
                    || ((RestCommandProcessor) processor).isTransactional()) {
                // [talendalfresco] disable tx for ImportCommand
                txn = serviceRegistry.getTransactionService().getUserTransaction();
                txn.begin();
            }

            // inform the processor to execute the specified command
            if (processor instanceof ExtCommandProcessor) {
                ((ExtCommandProcessor) processor).process(serviceRegistry, req, res, command);
            } else {
                processor.process(serviceRegistry, req, command);
            }

            if (!(processor instanceof RestCommandProcessor)
                    || ((RestCommandProcessor) processor).isTransactional()) {
                // [talendalfresco] disable tx for ImportCommand
                // commit the transaction
                txn.commit();
            }
        } catch (Throwable txnErr) {
            if (!(processor instanceof RestCommandProcessor)
                    || ((RestCommandProcessor) processor).isTransactional()) {
                // [talendalfresco] disable tx for ImportCommand
                try {
                    if (txn != null) {
                        txn.rollback();
                    }
                } catch (Exception tex) {
                }
            }
            throw txnErr;
        }

        String returnPage = req.getParameter(ARG_RETURNPAGE);
        if (returnPage != null && returnPage.length() != 0) {
            if (logger.isDebugEnabled())
                logger.debug("Redirecting to specified return page: " + returnPage);

            res.sendRedirect(returnPage);
        } else {
            if (logger.isDebugEnabled())
                logger.debug("No return page specified, displaying status output.");

            if (res.getContentType() == null) {
                res.setContentType("text/html");
            }

            // request that the processor output a useful status message
            PrintWriter out = res.getWriter();
            processor.outputStatus(out);
            out.close();
        }
    } catch (Throwable err) {
        throw new AlfrescoRuntimeException("Error during command servlet processing: " + err.getMessage(), err);
    }
}

From source file:de.mpg.mpdl.inge.syndication.presentation.RestServlet.java

/**
 * {@inheritDoc}/*from w  w w .  java2  s .  c  om*/
 */
@Override
protected final void doPost(final HttpServletRequest req, final HttpServletResponse resp)
        throws ServletException, IOException {
    String url = null;
    try {
        url = PropertyReader.getProperty("escidoc.syndication.service.url") + req.getServletPath()
                + req.getPathInfo();
    } catch (Exception e) {
        handleException(e, resp);
    }
    String q = req.getQueryString();

    if (Utils.checkVal(q)) {
        url += "?" + q;
    }

    Feed feed = synd.getFeeds().matchFeedByUri(url);

    // set correct mime-type
    resp.setContentType("application/" + (url.contains("rss_") ? "rss" : "atom") + "+xml; charset=utf-8");

    // cache handling
    String ttl = feed.getCachingTtl();

    if (Utils.checkVal(ttl)) {
        long ttlLong = Long.parseLong(ttl) * 1000L;
        resp.setHeader("control-cache", "max-age=" + ttl + ", must-revalidate");

        DateFormat df = new SimpleDateFormat("E, dd MMM yyyy HH:mm:ss z");
        df.setTimeZone(TimeZone.getTimeZone("GMT"));
        resp.setHeader("Expires", df.format(new Date(System.currentTimeMillis() + ttlLong)));
    }

    try {
        synd.getFeed(url, resp.getWriter());
    } catch (SyndicationException e) {
        handleException(e, resp);
    } catch (URISyntaxException e) {
        resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Wrong URI syntax: " + url);
        return;
    } catch (FeedException e) {
        handleException(e, resp);
    }

}

From source file:com.github.restdriver.clientdriver.unit.HttpRealRequestTest.java

@Test
public void instantiationWithHttpRequestPopulatesCorrectly() throws IOException {

    HttpServletRequest mockRequest = mock(HttpServletRequest.class);
    String expectedPathInfo = "someUrlPath";
    String expectedMethod = "GET";
    Enumeration<String> expectedHeaderNames = Collections.enumeration(Arrays.asList("header1"));

    String bodyContent = "bodyContent";
    String expectedContentType = "contentType";

    when(mockRequest.getPathInfo()).thenReturn(expectedPathInfo);
    when(mockRequest.getMethod()).thenReturn(expectedMethod);
    when(mockRequest.getQueryString()).thenReturn("hello=world");
    when(mockRequest.getHeaderNames()).thenReturn(expectedHeaderNames);
    when(mockRequest.getHeader("header1")).thenReturn("thisIsHeader1");
    when(mockRequest.getInputStream())/*from   w  ww  .ja v  a  2s  .com*/
            .thenReturn(new DummyServletInputStream(IOUtils.toInputStream(bodyContent)));
    when(mockRequest.getContentType()).thenReturn(expectedContentType);

    RealRequest realRequest = new HttpRealRequest(mockRequest);

    assertThat((String) realRequest.getPath(), is(expectedPathInfo));
    assertThat(realRequest.getMethod(), is(Method.GET));
    assertThat(realRequest.getParams().size(), is(1));
    assertThat((String) realRequest.getParams().get("hello").iterator().next(), is("world"));
    assertThat((String) realRequest.getHeaders().get("header1"), is("thisIsHeader1"));
    assertThat((String) realRequest.getBodyContentType(), is(expectedContentType));

}

From source file:com.sdl.odata.controller.AbstractODataController.java

/**
 * Converts an {@code HttpServletRequest} to an {@code ODataRequest}.
 *
 * @param servletRequest The {@code HttpServletRequest}.
 * @return An {@code ODataRequest} containing the request information.
 * @throws java.io.IOException If an I/O error occurs.
 *//*from   w  ww .  j  av  a 2  s .com*/
private ODataRequest buildODataRequest(HttpServletRequest servletRequest) throws IOException {
    ODataRequest.Builder builder = new ODataRequest.Builder();

    builder.setMethod(ODataRequest.Method.valueOf(servletRequest.getMethod()));

    // Unfortunately, HttpServletRequest makes it difficult to get the full URI
    StringBuilder sb = getRequestURL(servletRequest);
    String queryString = servletRequest.getQueryString();
    if (!isNullOrEmpty(queryString)) {
        sb.append('?').append(queryString);
    }
    builder.setUri(sb.toString());

    // Unfortunately, HttpServletRequest has a very old-style API to iterate the headers
    Enumeration e = servletRequest.getHeaderNames();
    while (e.hasMoreElements()) {
        String name = (String) e.nextElement();
        String value = servletRequest.getHeader(name);
        builder.setHeader(name, value);
    }

    // Read the request body
    InputStream in = servletRequest.getInputStream();
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    int count;
    byte[] buffer = new byte[BUFFER_SIZE];
    while ((count = in.read(buffer)) != -1) {
        out.write(buffer, 0, count);
    }
    builder.setBody(out.toByteArray());

    return builder.build();
}

From source file:me.smoe.lzy.filter.AccessLogFilter.java

private void logAccessAPI(HttpServletRequest request) {
    try {//from   www  . j a  v a 2  s  . c  o m
        User user = (User) request.getSession().getAttribute(Constants.SESSION_USER);
        String userId = user != null ? user.getId() : "NOT_LOGIN";
        String remoteAddr = request.getRemoteAddr();
        String method = request.getMethod();
        String requestURI = request.getRequestURI();
        String userAgent = StringUtils.defaultString(request.getHeader("User-Agent"));

        String queryString = request.getQueryString();
        if (queryString != null) {
            queryString = URLDecoder.decode(request.getQueryString(), Constants.CHARSET);
        }
        requestURI = requestURI
                + (StringUtils.isNotEmpty(queryString) ? ("?" + queryString) : StringUtils.EMPTY);

        Logger.getRestAccessLogger().info(
                String.format("[%s] [%s] [%s] %s [%s]", userId, remoteAddr, method, requestURI, userAgent));
    } catch (Exception e) {
        Logger.getRestAccessLogger().warn("AccessAPI logger error: " + e.getMessage(), e);
    }
}

From source file:com.jfinal.core.ActionHandler.java

/**
 * handle//  www  .j  a v  a2s  .  co m
 * 1: Action action = actionMapping.getAction(target)
 * 2: new Invocation(...).invoke()
 * 3: render(...)
 */
public final void handle(String target, HttpServletRequest request, HttpServletResponse response,
        boolean[] isHandled) {
    if (target.indexOf('.') != -1) {
        return;
    }

    isHandled[0] = true;
    String[] urlPara = { null };
    Action action = actionMapping.getAction(target, urlPara);

    if (action == null) {
        if (log.isWarnEnabled()) {
            String qs = request.getQueryString();
            log.warn("404 Action Not Found: " + (qs == null ? target : target + "?" + qs));
        }
        renderFactory.getErrorRender(404).setContext(request, response).render();
        return;
    }

    try {
        Controller controller = action.getControllerClass().newInstance();
        controller.init(request, response, urlPara[0]);

        if (devMode) {
            if (ActionReporter.isReportAfterInvocation(request)) {
                new Invocation(action, controller).invoke();
                ActionReporter.report(controller, action);
            } else {
                ActionReporter.report(controller, action);
                new Invocation(action, controller).invoke();
            }
        } else {
            new Invocation(action, controller).invoke();
        }

        Render render = controller.getRender();
        if (render instanceof ActionRender) {
            String actionUrl = ((ActionRender) render).getActionUrl();
            if (target.equals(actionUrl))
                throw new RuntimeException("The forward action url is the same as before.");
            else
                handle(actionUrl, request, response, isHandled);
            return;
        }

        if (render == null)
            render = renderFactory.getDefaultRender(action.getViewPath() + action.getMethodName());
        render.setContext(request, response, action.getViewPath()).render();
    } catch (RenderException e) {
        if (log.isErrorEnabled()) {
            String qs = request.getQueryString();
            log.error(qs == null ? target : target + "?" + qs, e);
        }
    } catch (ActionException e) {
        int errorCode = e.getErrorCode();
        if (errorCode == 404 && log.isWarnEnabled()) {
            String qs = request.getQueryString();
            log.warn("404 Not Found: " + (qs == null ? target : target + "?" + qs));
        } else if (errorCode == 401 && log.isWarnEnabled()) {
            String qs = request.getQueryString();
            log.warn("401 Unauthorized: " + (qs == null ? target : target + "?" + qs));
        } else if (errorCode == 403 && log.isWarnEnabled()) {
            String qs = request.getQueryString();
            log.warn("403 Forbidden: " + (qs == null ? target : target + "?" + qs));
        } else if (log.isErrorEnabled()) {
            String qs = request.getQueryString();
            log.error(qs == null ? target : target + "?" + qs, e);
        }
        e.getErrorRender().setContext(request, response, action.getViewPath()).render();
    } catch (Throwable t) {
        if (log.isErrorEnabled()) {
            String qs = request.getQueryString();
            log.error(qs == null ? target : target + "?" + qs, t);
        }
        request.setAttribute("exception", ExceptionUtils.getStackTrace(t));
        renderFactory.getErrorRender(500).setContext(request, response, action.getViewPath()).render();
    }
}

From source file:de.mpg.escidoc.services.syndication.presentation.RestServlet.java

/**
 * {@inheritDoc}/*ww w. j  a va2 s  . co m*/
 */
@Override
protected final void doPost(final HttpServletRequest req, final HttpServletResponse resp)
        throws ServletException, IOException {
    String url = null;
    try {
        url = PropertyReader.getProperty("escidoc.syndication.service.url") + req.getServletPath()
                + req.getPathInfo();
    } catch (Exception e) {
        handleException(e, resp);
    }
    String q = req.getQueryString();

    if (Utils.checkVal(q)) {
        url += "?" + q;
    }

    Feed feed = synd.getFeeds().matchFeedByUri(url);

    //set correct mime-type
    resp.setContentType("application/" + (url.contains("rss_") ? "rss" : "atom") + "+xml; charset=utf-8");

    //cache handling
    String ttl = feed.getCachingTtl();

    if (Utils.checkVal(ttl)) {
        long ttlLong = Long.parseLong(ttl) * 1000L;
        resp.setHeader("control-cache", "max-age=" + ttl + ", must-revalidate");

        DateFormat df = new SimpleDateFormat("E, dd MMM yyyy HH:mm:ss z");
        df.setTimeZone(TimeZone.getTimeZone("GMT"));
        resp.setHeader("Expires", df.format(new Date(System.currentTimeMillis() + ttlLong)));
    }

    try {
        synd.getFeed(url, resp.getWriter());
    } catch (SyndicationException e) {
        handleException(e, resp);
    } catch (URISyntaxException e) {
        resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Wrong URI syntax: " + url);
        return;
    } catch (FeedException e) {
        handleException(e, resp);
    }

}

From source file:org.iwethey.forums.web.HeaderInterceptor.java

/**
 * Load the model with the information needed for the header JSP,
 * including user statistics, the quote-of-the-page, and the
 * navigation bar links. Sets the last URI attribute in the session.
 * <p>//w w  w  .j  a v  a 2s.co  m
 * @param request The servlet request object.
 * @param response The servlet response object.
 * @param handler The request handler processing this request.
 * @param mv The ModelAndView created by the controller wrapped by this interceptor.
 */
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
        ModelAndView mv) throws Exception {
    String currentUri = request.getRequestURI();
    if (!(currentUri.indexOf("toggle") >= 0 || currentUri.indexOf("logout") >= 0
            || currentUri.indexOf("mark") >= 0)) {
        String query = request.getQueryString();
        if (query != null) {
            currentUri = currentUri + "?" + query;
        }
        WebUtils.setSessionAttribute(request, LAST_URI_ATTRIBUTE, currentUri);
    }

    View view = mv.getView();
    if (view != null && view instanceof RedirectView) {
        return;
    }

    // Copy the stuff set above on the request into the model.
    // Some view engines (Velocity as an example) use the model differently.
    mv.addObject("now", request.getAttribute("now"));
    mv.addObject("start", request.getAttribute("start"));
    mv.addObject(USER_ATTRIBUTE, request.getAttribute(USER_ATTRIBUTE));
    mv.addObject("username", request.getAttribute("username"));

    mv.addObject("userCount", new Integer(mUserManager.getUserCount()));
    int actives = mUserManager.getActiveUserCount();
    mv.addObject("activeUserCount", new Integer(actives));
    mv.addObject("activeSingle", Boolean.valueOf(actives == 1));

    mv.addObject("lph", new Integer(3));
    mv.addObject("mpl", new Integer(60 / 3));

    mv.addObject("notice", mAdminManager.getNotice());

    mv.addObject("lrpd", mAdminManager.getLRPD());

    List nav = null;
    Map model = mv.getModel();
    if (model != null) {
        nav = (List) model.get("navigation");
    }
    if (nav == null) {
        nav = new ArrayList();
    }

    nav.add(0, new NavigationEntry("home", "/main.iwt"));

    mv.addObject("navigation", nav);

    //mv.addObject("ctx", new ContextTool(request, response, RequestContextUtils.getLocale(request), mMessageSource));
}

From source file:io.stallion.requests.StRequest.java

public StRequest(String path, Request baseRequest, HttpServletRequest request) {
    this.setPath(path);
    this.request = request;
    this.baseRequest = baseRequest;
    this.query = request.getQueryString();
}

From source file:org.esgf.web.MetadataExtractorController.java

/**
 * Sends a relay to fetch the appropriate metadata file.
 *
 * @param  request  HttpServletRequest object containing the query string
 * @param  response  HttpServletResponse object containing the metadata in json format
 *
 *///from  w  ww . j  av a  2 s.c o  m
private String relay(HttpServletRequest request, HttpServletResponse response)
        throws IOException, JSONException, ParserConfigurationException {
    String queryString = request.getQueryString();
    LOG.debug("queryString=" + queryString);

    String requestUri = request.getRequestURI();
    LOG.debug("requestUri=" + requestUri);

    String jsonContent = "";

    String id = request.getParameter("id");
    LOG.debug("id: " + id);
    String title = request.getParameter("title");
    LOG.debug("title: " + title);

    //String format = request.getParameter("metadataformat");
    //String filename = request.getParameter("metadatafile");
    /*
    if(METADATA_FILE_LOCATION.startsWith("/var/folders/"))
    {
    METADATA_FILE_LOCATION = "/tmp/";
    }
            
            
            
            
    URL f = new URL(filename);
            
            
    if(format.equalsIgnoreCase("oai"))
    {
    jsonContent = processOAI(f,id);
    }
    else if(format.equalsIgnoreCase("fgdc"))
    {
    jsonContent = processFGDC(f,id);
    }
    else if(format.equalsIgnoreCase("cas"))
    {
    jsonContent = processCAS(f,id);
    }
    else //thredds
    {
    jsonContent = processTHREDDS(f,id);
    }
     */

    return jsonContent;
}