Example usage for javax.servlet.http HttpServletRequest toString

List of usage examples for javax.servlet.http HttpServletRequest toString

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletRequest toString.

Prototype

public String toString() 

Source Link

Document

Returns a string representation of the object.

Usage

From source file:se.vgregion.pubsub.loadtesting.LoadtestingServlet.java

private String getFragment(HttpServletRequest request) {
    // !!! Jetty dependent
    String s = request.toString();
    int hash = s.indexOf("#");
    int end = s.indexOf("]", hash);
    if (hash > -1) {
        return s.substring(hash + 1, end);
    } else {//from  w  w w.  j a  v a 2s.c  o  m
        throw new RuntimeException("Can not parse fragment, this code is Jetty specific for now");
    }
}

From source file:com.cognifide.aet.rest.LockServlet.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("GET: " + req.toString());
    }/*from  w w w . j a v  a2 s  .  c o  m*/
    resp.setContentType(APPLICATION_JSON_CONTENT_TYPE);

    String key = getKey(req);
    if (StringUtils.isBlank(key)) {
        resp.getWriter().write(GSON.toJson(getLocks()));
    } else {
        resp.getWriter().write(GSON.toJson(lockService.isLockPresent(key)));
    }
    resp.flushBuffer();
}

From source file:com.cognifide.aet.rest.LockServlet.java

@Override
protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("PUT: " + req.toString());
    }/*from w w w  .  ja v a2 s  .  c  o m*/
    resp.setContentType(APPLICATION_JSON_CONTENT_TYPE);
    String value = req.getParameter(VALUE_PARAM);
    String key = getKey(req);
    if (StringUtils.isBlank(key) || StringUtils.isBlank(value)) {
        resp.setStatus(404);
    } else {
        lockService.setLock(key, value);
    }
    resp.flushBuffer();
}

From source file:com.cognifide.aet.rest.LockServlet.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("POST: " + req.toString());
    }/* w  w  w .  ja v a 2 s .  co m*/
    resp.setContentType(APPLICATION_JSON_CONTENT_TYPE);
    String value = req.getParameter(VALUE_PARAM);
    String key = getKey(req);
    if (StringUtils.isBlank(key) || StringUtils.isBlank(value)) {
        resp.setStatus(404);
    } else if (lockService.trySetLock(key, value)) {
        resp.setStatus(200);
    } else {
        resp.setStatus(409);
    }
    resp.flushBuffer();
}

From source file:com.intel.cosbench.driver.handler.AbstractCommandHandler.java

@Override
public ModelAndView handleRequest(HttpServletRequest req, HttpServletResponse res) {
    Response response = null;//from ww w  .j  a v a  2 s.  com
    try {
        response = process(req, res);
    } catch (BadRequestException bre) {
        response = new Response(400, "unrecognized request: " + req.toString());
    } catch (NotFoundException nfe) {
        response = new Response(404, "mission not found");
    } catch (IllegalStateException ise) {
        response = new Response(409, ise.getMessage());
    } catch (ConfigException ce) {
        response = new Response(400, ce.getMessage());
    } catch (Exception e) {
        response = new Response(500, e.getMessage());
        LOGGER.error("unexpected error", e);
    }
    return new ModelAndView(JSON, "response", response);
}

From source file:com.logiclander.jaasmine.authentication.http.JaasLoginFilter.java

/**
 * This implementation will filter requests for credentials and determine if
 * processing of the FilterChain can proceed.  Filtering occurs as follows:
 * <OL>/*from w ww  . jav  a 2 s . c o  m*/
 *  <LI>If the request is not an HttpServletRequest and the response is not
 * an HttpServletResponse, continue processing the filter chain (this almost
 * never happens)</LI>
 *  <LI>The HttpSession is checked for an attribute named
 * {@link AuthenticationService#SUBJECT_KEY
 * AuthenticationService.SUBJECT_KEY}</LI>
 *  <LI>If found, then processing the filter chain continues.</LI>
 *  <LI>If not found, then the request is checked for the {@code username}
 * and {@code password} parameters.  If these parameters are present, then
 * the SimpleAuthenticationService's login method is invoked with those
 * credentials.</LI>
 *  <LI>If a Subject is returned, it is saved to the HttpSession with the
 * key from above.</LI>
 * </OL>
 * When the login is successful, the ServletRequest is wrapped in a
 * {@link JaasmineHttpServletRequest}.  If it is unsuccessful, this filter
 * will send the request to a login processor as follows:
 * <OL>
 *  <LI>If {@code loginPath} is set, dispatch the request to that resource.
 * </LI>
 *  <LI>If (@code loginRedirect} is set, redirect the request to that URL.
 * </LI>
 *  <LI>Dispatch to {@code loginServletName} if neither of the above are
 * set./LI>
 * </OL>
 *
 * @param request the ServletRequest
 * @param response the ServletResponse
 * @param chain the FilterChain
 * @throws IOException if an I/O error occurs in the FilterChain
 * @throws ServletException if a processing error occurs in the FilterChain
 */
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {

    if (logger.isDebugEnabled()) {
        logger.debug(String.format("%s: entering doFilter", filterName));
    }

    if (!(request instanceof HttpServletRequest) && !(response instanceof HttpServletResponse)) {

        logger.debug("This is not an HTTP request");
        chain.doFilter(request, response);

    } else {

        HttpServletRequest httpReq = (HttpServletRequest) request;
        HttpServletResponse httpResp = (HttpServletResponse) response;

        Exception exception = null;

        if (logger.isDebugEnabled()) {
            logger.debug(String.format("Filtering request: %s%s", httpReq.getContextPath(),
                    httpReq.getServletPath()));
        }

        try {

            if (!hasRequestUri(httpReq)) {
                cacheRequestUri(httpReq);
            }

            boolean canExecute = hasCredentials(httpReq);

            // Attempt to login the user and obtain a Subject.

            if (!canExecute) {
                canExecute = login(httpReq);
            }

            if (canExecute) {

                // The Subject was found which means the user has a valid
                // credential (Subject).  Processing can continue.

                // TODO: always wrap request, set to cached requestURI
                HttpServletRequest sendOn = httpReq;

                if (setRemoteUserOnLogin) {
                    sendOn = new JaasmineHttpServletRequest(httpReq, getSubject(httpReq));
                    logger.debug(String.format("Wrapping request in %s", sendOn.toString()));

                }

                chain.doFilter(sendOn, httpResp);

            } else {

                // No Subject found, need to dispatch to someplace to gather
                // the user's credentials and attempt a login on the
                // next request.

                RequestDispatcher loginDispatcher = null;
                if (!loginPath.equals(EMPTY_STRING)) {

                    loginDispatcher = httpReq.getSession().getServletContext().getRequestDispatcher(loginPath);

                    if (logger.isDebugEnabled()) {
                        logger.debug(String.format("Dispatching login " + "request to path %s", loginPath));
                    }

                } else if (!loginRedirect.equals(EMPTY_STRING)) {

                    if (logger.isDebugEnabled()) {
                        logger.debug(String.format("Redirectiong login " + "request to %s", loginRedirect));
                    }
                    httpResp.sendRedirect(loginRedirect);

                    // TODO: cache incoming requestURI

                    return;

                } else if (isUsingBasicAuthentication) {

                    String s = "Basic realm=\"Jaasmine\"";
                    httpResp.setHeader("WWW-Authenticate", s);
                    httpResp.setStatus(401);

                    return;
                } else {

                    loginDispatcher = httpReq.getSession().getServletContext()
                            .getNamedDispatcher(loginServletName);

                    if (logger.isDebugEnabled()) {
                        logger.debug(String.format("Dispatching login " + "request to named dispatcher %s",
                                loginServletName));
                    }
                }

                if (loginDispatcher != null) {

                    loginDispatcher.forward(httpReq, httpResp);
                    return;

                } else {

                    // Try to figure out what went wrong and send back
                    // a HELPFUL exception message.

                    String msg = "";

                    if (!loginPath.equals(EMPTY_STRING)) {

                        // First, is there a loginPath set, but nowhere to
                        // send it to?

                        msg = String.format(
                                "loginPath set to %s, but no " + "resource is available to dispatch to",
                                loginPath);
                    } else {

                        // Is JaasLoginServlet (or the servlet-name
                        // specified by loginServletName) not configured in
                        // the web.xml?

                        msg = String.format("Servlet named %s specified by "
                                + "the loginServletName is not configured in " + "the web.xml",
                                loginServletName);
                    }

                    throw new ServletException(msg);

                }
            }

        } catch (IOException ex) {

            exception = ex;
            throw (ex);

        } catch (ServletException ex) {

            exception = ex;
            throw (ex);

        } finally {

            if (exception != null) {

                if (logger.isErrorEnabled()) {
                    String msg = String.format("Caught exception in filter chain: %s", exception.getMessage());
                    logger.error(msg, exception);
                }
            }

        }
    }
}

From source file:org.dataone.proto.trove.mn.rest.base.AbstractWebController.java

protected void debugRequest(HttpServletRequest request) {
    /*     see values with just a plain old request object being sent through */
    logger.debug("request RequestURL: " + request.getRequestURL());
    logger.debug("request RequestURI: " + request.getRequestURI());
    logger.debug("request PathInfo: " + request.getPathInfo());
    logger.debug("request PathTranslated: " + request.getPathTranslated());
    logger.debug("request QueryString: " + request.getQueryString());
    logger.debug("request ContextPath: " + request.getContextPath());
    logger.debug("request ServletPath: " + request.getServletPath());
    logger.debug("request toString:" + request.toString());
    Enumeration<String> attributeNames = request.getAttributeNames();
    while (attributeNames.hasMoreElements()) {
        String attributeName = attributeNames.nextElement();
        logger.debug("request " + attributeName + ": " + request.getAttribute(attributeName));
    }/*from  w  w  w  .  j  av  a 2  s . co  m*/
    /*      values of proxyServletWrapper request object to be sent through */
    logger.info("");

    /*      uncomment to see what the parameters of servlet passed in are  */
    Map<String, String[]> parameterMap = request.getParameterMap();

    for (Object key : parameterMap.keySet()) {
        String[] values = parameterMap.get((String) key);
        for (int i = 0; i < values.length; ++i) {
            logger.info("request ParameterMap: " + (String) key + " = " + values[i]);
        }

    }
    logger.debug("");

}

From source file:com.vmware.identity.samlservice.LogoutState.java

/**
 * Construct logout state object//from w w  w.j a  v a2  s  .c  o  m
 *
 * @param request
 * @param response2
 * @param sessionManager
 * @param locale
 */
public LogoutState(HttpServletRequest request, HttpServletResponse response, SessionManager sessionManager,
        Locale locale, MessageSource messageSource) {
    log.debug("Constructing from request " + request.toString());

    Validate.notNull(request);
    Validate.notNull(sessionManager);
    this.processingState = ProcessingState.UNKNOWN;
    this.setRequest(request);
    this.setResponse(response);
    this.setLocale(locale);
    this.setMessageSource(messageSource);
    this.sessionManager = sessionManager;
    //TODO - check for correlation id in the headers PR1561606
    this.correlationId = UUID.randomUUID().toString();
    this.factory = new DefaultIdmAccessorFactory(this.correlationId);
    Validate.notNull(factory);
    this.idmAccessor = factory.getIdmAccessor();
    this.validator = new LogoutStateValidator();
    RequestCacheFactory requestFactory = new DefaultRequestCacheFactory();
    this.requestCache = requestFactory.getRequestCache();

    this.relayState = request.getParameter(Shared.RELAY_STATE_PARAMETER);
    this.signature = request.getParameter(Shared.SIGNATURE_PARAMETER);
    this.sigAlg = request.getParameter(Shared.SIGNATURE_ALGORITHM_PARAMETER);
    this.samlRequest = request.getParameter(Shared.SAML_REQUEST_PARAMETER);
    this.samlResponse = request.getParameter(Shared.SAML_RESPONSE_PARAMETER);
    this.validationResult = new ValidationResult(HttpServletResponse.SC_FORBIDDEN, "Forbidden", null);
    Validate.isTrue(this.samlRequest != null || this.samlResponse != null);

    // construct message that was supposed to be signed
    if (this.signature != null && this.sigAlg != null) {
        try {
            if (this.samlRequest != null) {
                this.signedMessage = Shared.SAML_REQUEST_PARAMETER + "="
                        + URLEncoder.encode(this.samlRequest, "UTF-8");
            } else if (this.samlResponse != null) {
                this.signedMessage = Shared.SAML_RESPONSE_PARAMETER + "="
                        + URLEncoder.encode(this.samlResponse, "UTF-8");
            }
            if (this.relayState != null) {
                this.signedMessage = this.signedMessage + "&" + Shared.RELAY_STATE_PARAMETER + "="
                        + URLEncoder.encode(this.relayState, "UTF-8");
                // print out decoded relay state. Note that we do not need
                // to
                // store decoded value.
                byte[] relayStateBytes = Base64.decode(this.relayState);
                log.debug("Relay state specified was " + new String(relayStateBytes));
            }
            this.signedMessage = this.signedMessage + "&" + Shared.SIGNATURE_ALGORITHM_PARAMETER + "="
                    + URLEncoder.encode(this.sigAlg, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            log.debug("Could not reconstruct signed message");
            this.signedMessage = null;
        }
    }

    this.processingState = ProcessingState.INITIALIZED;
}

From source file:net.lightbody.bmp.proxy.jetty.jetty.servlet.ServletHandler.java

protected void handleTrace(HttpServletRequest request, HttpServletResponse response) throws IOException {
    response.setHeader(HttpFields.__ContentType, HttpFields.__MessageHttp);
    OutputStream out = response.getOutputStream();
    ByteArrayISO8859Writer writer = new ByteArrayISO8859Writer();
    writer.write(request.toString());
    writer.flush();//www  .  ja va  2  s  .co m
    response.setIntHeader(HttpFields.__ContentLength, writer.size());
    writer.writeTo(out);
    out.flush();
}

From source file:org.commoncrawl.service.listcrawler.MultiPartFilter.java

/**
 * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest,
 *      javax.servlet.ServletResponse, javax.servlet.FilterChain)
 *//*from  w  ww .jav  a2s  .  c  o m*/
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    LOG.info("Hit doFilter");
    HttpServletRequest srequest = (HttpServletRequest) request;
    if (srequest.getContentType() == null || !srequest.getContentType().startsWith("multipart/form-data")) {
        LOG.info(srequest.toString());
        LOG.info("Rejecting. Invalid mime type:" + srequest.getContentType());
        chain.doFilter(request, response);
        return;
    }

    LOG.info("OK Looks Good So Far");

    BufferedInputStream in = new BufferedInputStream(request.getInputStream());
    String content_type = srequest.getContentType();

    // TODO - handle encodings

    String boundary = "--" + value(content_type.substring(content_type.indexOf("boundary=")));
    byte[] byteBoundary = (boundary + "--").getBytes(StringUtil.__ISO_8859_1);
    MultiMap params = new MultiMap();

    try {
        // Get first boundary
        byte[] bytes = TypeUtil.readLine(in);
        String line = bytes == null ? null : new String(bytes, "UTF-8");
        if (line == null || !line.equals(boundary)) {
            throw new IOException("Missing initial multi part boundary");
        }

        // Read each part
        boolean lastPart = false;
        String content_disposition = null;
        String file_content_type = null;
        while (!lastPart) {
            while (true) {
                bytes = TypeUtil.readLine(in);
                // If blank line, end of part headers
                if (bytes == null || bytes.length == 0)
                    break;
                line = new String(bytes, "UTF-8");

                // place part header key and value in map
                int c = line.indexOf(':', 0);
                if (c > 0) {
                    String key = line.substring(0, c).trim().toLowerCase();
                    String value = line.substring(c + 1, line.length()).trim();
                    if (key.equals("content-disposition"))
                        content_disposition = value;
                    else if (key.equals("content-type"))
                        file_content_type = value;
                }
            }
            // Extract content-disposition
            boolean form_data = false;
            if (content_disposition == null) {
                throw new IOException("Missing content-disposition");
            }

            StringTokenizer tok = new StringTokenizer(content_disposition, ";");
            String name = null;
            String filename = null;
            while (tok.hasMoreTokens()) {
                String t = tok.nextToken().trim();
                String tl = t.toLowerCase();
                if (t.startsWith("form-data"))
                    form_data = true;
                else if (tl.startsWith("name="))
                    name = value(t);
                else if (tl.startsWith("filename="))
                    filename = value(t);
            }

            // Check disposition
            if (!form_data) {
                continue;
            }
            if (name == null || name.length() == 0) {
                continue;
            }

            OutputStream out = null;
            File file = null;
            try {
                if (filename != null && filename.length() > 0) {
                    file = File.createTempFile("MultiPart", "", tempdir);
                    LOG.info("Got FileName:" + filename + " Creating Temp File:" + file);
                    out = new FileOutputStream(file);

                    UploadFileData uploadData = new UploadFileData();

                    uploadData.fieldName = name;
                    uploadData.incomingFile = file;
                    uploadData.incomingFilename = filename;
                    uploadData.incomingContentType = file_content_type;

                    request.setAttribute(name, uploadData);

                    params.put(name, filename);

                    if (_deleteFiles) {
                        //file.deleteOnExit();
                        ArrayList<UploadFileData> files = (ArrayList<UploadFileData>) request
                                .getAttribute(FILES);
                        if (files == null) {
                            files = new ArrayList<UploadFileData>();
                            request.setAttribute(FILES, files);
                        }
                        files.add(uploadData);
                    }

                } else
                    out = new ByteArrayOutputStream();

                int state = -2;
                int c;
                boolean cr = false;
                boolean lf = false;

                // loop for all lines`
                while (true) {
                    int b = 0;
                    while ((c = (state != -2) ? state : in.read()) != -1) {
                        state = -2;
                        // look for CR and/or LF
                        if (c == 13 || c == 10) {
                            if (c == 13)
                                state = in.read();
                            break;
                        }
                        // look for boundary
                        if (b >= 0 && b < byteBoundary.length && c == byteBoundary[b])
                            b++;
                        else {
                            // this is not a boundary
                            if (cr)
                                out.write(13);
                            if (lf)
                                out.write(10);
                            cr = lf = false;
                            if (b > 0)
                                out.write(byteBoundary, 0, b);
                            b = -1;
                            out.write(c);
                        }
                    }
                    // check partial boundary
                    if ((b > 0 && b < byteBoundary.length - 2) || (b == byteBoundary.length - 1)) {
                        if (cr)
                            out.write(13);
                        if (lf)
                            out.write(10);
                        cr = lf = false;
                        out.write(byteBoundary, 0, b);
                        b = -1;
                    }
                    // boundary match
                    if (b > 0 || c == -1) {
                        if (b == byteBoundary.length)
                            lastPart = true;
                        if (state == 10)
                            state = -2;
                        break;
                    }
                    // handle CR LF
                    if (cr)
                        out.write(13);
                    if (lf)
                        out.write(10);
                    cr = (c == 13);
                    lf = (c == 10 || state == 10);
                    if (state == 10)
                        state = -2;
                }
            } finally {
                if (out != null) {
                    out.close();
                }
            }

            if (file == null) {
                bytes = ((ByteArrayOutputStream) out).toByteArray();
                params.add(name, bytes);
            }
        }

        // handle request
        chain.doFilter(new Wrapper(srequest, params), response);
    } catch (IOException e) {
        LOG.error("###Exception In Multipart:" + CCStringUtils.stringifyException(e));
        throw e;
    } finally {
        LOG.info("Deleting Files Here");
        deleteFiles(request);
    }
}