Example usage for javax.servlet.http HttpServletRequest getRequestedSessionId

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

Introduction

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

Prototype

public String getRequestedSessionId();

Source Link

Document

Returns the session ID specified by the client.

Usage

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

public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    request.setAttribute("Dump", this);
    request.setCharacterEncoding("ISO_8859_1");
    getServletContext().setAttribute("Dump", this);

    String info = request.getPathInfo();
    if (info != null && info.endsWith("Exception")) {
        try {//  ww  w  .j av a 2s  .  c  om
            throw (Throwable) (Loader.loadClass(this.getClass(), info.substring(1)).newInstance());
        } catch (Throwable th) {
            throw new ServletException(th);
        }
    }

    String redirect = request.getParameter("redirect");
    if (redirect != null && redirect.length() > 0) {
        response.getOutputStream().println("THIS SHOULD NOT BE SEEN!");
        response.sendRedirect(redirect);
        response.getOutputStream().println("THIS SHOULD NOT BE SEEN!");
        return;
    }

    String error = request.getParameter("error");
    if (error != null && error.length() > 0) {
        response.getOutputStream().println("THIS SHOULD NOT BE SEEN!");
        response.sendError(Integer.parseInt(error));
        response.getOutputStream().println("THIS SHOULD NOT BE SEEN!");
        return;
    }

    String length = request.getParameter("length");
    if (length != null && length.length() > 0) {
        response.setContentLength(Integer.parseInt(length));
    }

    String buffer = request.getParameter("buffer");
    if (buffer != null && buffer.length() > 0)
        response.setBufferSize(Integer.parseInt(buffer));

    request.setCharacterEncoding("UTF-8");
    response.setContentType("text/html");

    if (info != null && info.indexOf("Locale/") >= 0) {
        try {
            String locale_name = info.substring(info.indexOf("Locale/") + 7);
            Field f = java.util.Locale.class.getField(locale_name);
            response.setLocale((Locale) f.get(null));
        } catch (Exception e) {
            LogSupport.ignore(log, e);
            response.setLocale(Locale.getDefault());
        }
    }

    String cn = request.getParameter("cookie");
    String cv = request.getParameter("value");
    String v = request.getParameter("version");
    if (cn != null && cv != null) {
        Cookie cookie = new Cookie(cn, cv);
        cookie.setComment("Cookie from dump servlet");
        if (v != null) {
            cookie.setMaxAge(300);
            cookie.setPath("/");
            cookie.setVersion(Integer.parseInt(v));
        }
        response.addCookie(cookie);
    }

    String pi = request.getPathInfo();
    if (pi != null && pi.startsWith("/ex")) {
        OutputStream out = response.getOutputStream();
        out.write("</H1>This text should be reset</H1>".getBytes());
        if ("/ex0".equals(pi))
            throw new ServletException("test ex0", new Throwable());
        if ("/ex1".equals(pi))
            throw new IOException("test ex1");
        if ("/ex2".equals(pi))
            throw new UnavailableException("test ex2");
        if ("/ex3".equals(pi))
            throw new HttpException(501);
    }

    PrintWriter pout = response.getWriter();
    Page page = null;

    try {
        page = new Page();
        page.title("Dump Servlet");

        page.add(new Heading(1, "Dump Servlet"));
        Table table = new Table(0).cellPadding(0).cellSpacing(0);
        page.add(table);
        table.newRow();
        table.addHeading("getMethod:&nbsp;").cell().right();
        table.addCell("" + request.getMethod());
        table.newRow();
        table.addHeading("getContentLength:&nbsp;").cell().right();
        table.addCell(Integer.toString(request.getContentLength()));
        table.newRow();
        table.addHeading("getContentType:&nbsp;").cell().right();
        table.addCell("" + request.getContentType());
        table.newRow();
        table.addHeading("getCharacterEncoding:&nbsp;").cell().right();
        table.addCell("" + request.getCharacterEncoding());
        table.newRow();
        table.addHeading("getRequestURI:&nbsp;").cell().right();
        table.addCell("" + request.getRequestURI());
        table.newRow();
        table.addHeading("getRequestURL:&nbsp;").cell().right();
        table.addCell("" + request.getRequestURL());
        table.newRow();
        table.addHeading("getContextPath:&nbsp;").cell().right();
        table.addCell("" + request.getContextPath());
        table.newRow();
        table.addHeading("getServletPath:&nbsp;").cell().right();
        table.addCell("" + request.getServletPath());
        table.newRow();
        table.addHeading("getPathInfo:&nbsp;").cell().right();
        table.addCell("" + request.getPathInfo());
        table.newRow();
        table.addHeading("getPathTranslated:&nbsp;").cell().right();
        table.addCell("" + request.getPathTranslated());
        table.newRow();
        table.addHeading("getQueryString:&nbsp;").cell().right();
        table.addCell("" + request.getQueryString());

        table.newRow();
        table.addHeading("getProtocol:&nbsp;").cell().right();
        table.addCell("" + request.getProtocol());
        table.newRow();
        table.addHeading("getScheme:&nbsp;").cell().right();
        table.addCell("" + request.getScheme());
        table.newRow();
        table.addHeading("getServerName:&nbsp;").cell().right();
        table.addCell("" + request.getServerName());
        table.newRow();
        table.addHeading("getServerPort:&nbsp;").cell().right();
        table.addCell("" + Integer.toString(request.getServerPort()));
        table.newRow();
        table.addHeading("getLocalName:&nbsp;").cell().right();
        table.addCell("" + request.getLocalName());
        table.newRow();
        table.addHeading("getLocalAddr:&nbsp;").cell().right();
        table.addCell("" + request.getLocalAddr());
        table.newRow();
        table.addHeading("getLocalPort:&nbsp;").cell().right();
        table.addCell("" + Integer.toString(request.getLocalPort()));
        table.newRow();
        table.addHeading("getRemoteUser:&nbsp;").cell().right();
        table.addCell("" + request.getRemoteUser());
        table.newRow();
        table.addHeading("getRemoteAddr:&nbsp;").cell().right();
        table.addCell("" + request.getRemoteAddr());
        table.newRow();
        table.addHeading("getRemoteHost:&nbsp;").cell().right();
        table.addCell("" + request.getRemoteHost());
        table.newRow();
        table.addHeading("getRemotePort:&nbsp;").cell().right();
        table.addCell("" + request.getRemotePort());
        table.newRow();
        table.addHeading("getRequestedSessionId:&nbsp;").cell().right();
        table.addCell("" + request.getRequestedSessionId());
        table.newRow();
        table.addHeading("isSecure():&nbsp;").cell().right();
        table.addCell("" + request.isSecure());

        table.newRow();
        table.addHeading("isUserInRole(admin):&nbsp;").cell().right();
        table.addCell("" + request.isUserInRole("admin"));

        table.newRow();
        table.addHeading("getLocale:&nbsp;").cell().right();
        table.addCell("" + request.getLocale());

        Enumeration locales = request.getLocales();
        while (locales.hasMoreElements()) {
            table.newRow();
            table.addHeading("getLocales:&nbsp;").cell().right();
            table.addCell(locales.nextElement());
        }

        table.newRow();
        table.newHeading().cell().nest(new Font(2, true)).add("<BR>Other HTTP Headers")
                .attribute("COLSPAN", "2").left();
        Enumeration h = request.getHeaderNames();
        String name;
        while (h.hasMoreElements()) {
            name = (String) h.nextElement();

            Enumeration h2 = request.getHeaders(name);
            while (h2.hasMoreElements()) {
                String hv = (String) h2.nextElement();
                table.newRow();
                table.addHeading(name + ":&nbsp;").cell().right();
                table.addCell(hv);
            }
        }

        table.newRow();
        table.newHeading().cell().nest(new Font(2, true)).add("<BR>Request Parameters")
                .attribute("COLSPAN", "2").left();
        h = request.getParameterNames();
        while (h.hasMoreElements()) {
            name = (String) h.nextElement();
            table.newRow();
            table.addHeading(name + ":&nbsp;").cell().right();
            table.addCell(request.getParameter(name));
            String[] values = request.getParameterValues(name);
            if (values == null) {
                table.newRow();
                table.addHeading(name + " Values:&nbsp;").cell().right();
                table.addCell("NULL!!!!!!!!!");
            } else if (values.length > 1) {
                for (int i = 0; i < values.length; i++) {
                    table.newRow();
                    table.addHeading(name + "[" + i + "]:&nbsp;").cell().right();
                    table.addCell(values[i]);
                }
            }
        }

        table.newRow();
        table.newHeading().cell().nest(new Font(2, true)).add("<BR>Cookies").attribute("COLSPAN", "2").left();
        Cookie[] cookies = request.getCookies();
        for (int i = 0; cookies != null && i < cookies.length; i++) {
            Cookie cookie = cookies[i];

            table.newRow();
            table.addHeading(cookie.getName() + ":&nbsp;").cell().attribute("VALIGN", "TOP").right();
            table.addCell(cookie.getValue());
        }

        /* ------------------------------------------------------------ */
        table.newRow();
        table.newHeading().cell().nest(new Font(2, true)).add("<BR>Request Attributes")
                .attribute("COLSPAN", "2").left();
        Enumeration a = request.getAttributeNames();
        while (a.hasMoreElements()) {
            name = (String) a.nextElement();
            table.newRow();
            table.addHeading(name + ":&nbsp;").cell().attribute("VALIGN", "TOP").right();
            table.addCell("<pre>" + toString(request.getAttribute(name)) + "</pre>");
        }

        /* ------------------------------------------------------------ */
        table.newRow();
        table.newHeading().cell().nest(new Font(2, true)).add("<BR>Servlet InitParameters")
                .attribute("COLSPAN", "2").left();
        a = getInitParameterNames();
        while (a.hasMoreElements()) {
            name = (String) a.nextElement();
            table.newRow();
            table.addHeading(name + ":&nbsp;").cell().attribute("VALIGN", "TOP").right();
            table.addCell("<pre>" + toString(getInitParameter(name)) + "</pre>");
        }

        table.newRow();
        table.newHeading().cell().nest(new Font(2, true)).add("<BR>Context InitParameters")
                .attribute("COLSPAN", "2").left();
        a = getServletContext().getInitParameterNames();
        while (a.hasMoreElements()) {
            name = (String) a.nextElement();
            table.newRow();
            table.addHeading(name + ":&nbsp;").cell().attribute("VALIGN", "TOP").right();
            table.addCell("<pre>" + toString(getServletContext().getInitParameter(name)) + "</pre>");
        }

        table.newRow();
        table.newHeading().cell().nest(new Font(2, true)).add("<BR>Context Attributes")
                .attribute("COLSPAN", "2").left();
        a = getServletContext().getAttributeNames();
        while (a.hasMoreElements()) {
            name = (String) a.nextElement();
            table.newRow();
            table.addHeading(name + ":&nbsp;").cell().attribute("VALIGN", "TOP").right();
            table.addCell("<pre>" + toString(getServletContext().getAttribute(name)) + "</pre>");
        }

        if (request.getContentType() != null && request.getContentType().startsWith("multipart/form-data")
                && request.getContentLength() < 1000000) {
            MultiPartRequest multi = new MultiPartRequest(request);
            String[] parts = multi.getPartNames();

            table.newRow();
            table.newHeading().cell().nest(new Font(2, true)).add("<BR>Multi-part content")
                    .attribute("COLSPAN", "2").left();
            for (int p = 0; p < parts.length; p++) {
                name = parts[p];
                table.newRow();
                table.addHeading(name + ":&nbsp;").cell().attribute("VALIGN", "TOP").right();
                table.addCell("<pre>" + multi.getString(parts[p]) + "</pre>");
            }
        }

        String res = request.getParameter("resource");
        if (res != null && res.length() > 0) {
            table.newRow();
            table.newHeading().cell().nest(new Font(2, true)).add("<BR>Get Resource: " + res)
                    .attribute("COLSPAN", "2").left();

            table.newRow();
            table.addHeading("this.getClass():&nbsp;").cell().right();
            table.addCell("" + this.getClass().getResource(res));

            table.newRow();
            table.addHeading("this.getClass().getClassLoader():&nbsp;").cell().right();
            table.addCell("" + this.getClass().getClassLoader().getResource(res));

            table.newRow();
            table.addHeading("Thread.currentThread().getContextClassLoader():&nbsp;").cell().right();
            table.addCell("" + Thread.currentThread().getContextClassLoader().getResource(res));

            table.newRow();
            table.addHeading("getServletContext():&nbsp;").cell().right();
            try {
                table.addCell("" + getServletContext().getResource(res));
            } catch (Exception e) {
                table.addCell("" + e);
            }
        }

        /* ------------------------------------------------------------ */
        page.add(Break.para);
        page.add(new Heading(1, "Request Wrappers"));
        ServletRequest rw = request;
        int w = 0;
        while (rw != null) {
            page.add((w++) + ": " + rw.getClass().getName() + "<br/>");
            if (rw instanceof HttpServletRequestWrapper)
                rw = ((HttpServletRequestWrapper) rw).getRequest();
            else if (rw instanceof ServletRequestWrapper)
                rw = ((ServletRequestWrapper) rw).getRequest();
            else
                rw = null;
        }

        page.add(Break.para);
        page.add(new Heading(1, "International Characters"));
        page.add("Directly encoced:  Drst<br/>");
        page.add("HTML reference: D&uuml;rst<br/>");
        page.add("Decimal (252) 8859-1: D&#252;rst<br/>");
        page.add("Hex (xFC) 8859-1: D&#xFC;rst<br/>");
        page.add(
                "Javascript unicode (00FC) : <script language='javascript'>document.write(\"D\u00FCrst\");</script><br/>");
        page.add(Break.para);
        page.add(new Heading(1, "Form to generate GET content"));
        TableForm tf = new TableForm(response.encodeURL(getURI(request)));
        tf.method("GET");
        tf.addTextField("TextField", "TextField", 20, "value");
        tf.addButton("Action", "Submit");
        page.add(tf);

        page.add(Break.para);
        page.add(new Heading(1, "Form to generate POST content"));
        tf = new TableForm(response.encodeURL(getURI(request)));
        tf.method("POST");
        tf.addTextField("TextField", "TextField", 20, "value");
        Select select = tf.addSelect("Select", "Select", true, 3);
        select.add("ValueA");
        select.add("ValueB1,ValueB2");
        select.add("ValueC");
        tf.addButton("Action", "Submit");
        page.add(tf);

        page.add(new Heading(1, "Form to upload content"));
        tf = new TableForm(response.encodeURL(getURI(request)));
        tf.method("POST");
        tf.attribute("enctype", "multipart/form-data");
        tf.addFileField("file", "file");
        tf.addButton("Upload", "Upload");
        page.add(tf);

        page.add(new Heading(1, "Form to get Resource"));
        tf = new TableForm(response.encodeURL(getURI(request)));
        tf.method("POST");
        tf.addTextField("resource", "resource", 20, "");
        tf.addButton("Action", "getResource");
        page.add(tf);

    } catch (Exception e) {
        log.warn(LogSupport.EXCEPTION, e);
    }

    page.write(pout);

    String data = request.getParameter("data");
    if (data != null && data.length() > 0) {
        int d = Integer.parseInt(data);
        while (d > 0) {
            pout.println("1234567890123456789012345678901234567890123456789\n");
            d = d - 50;

        }
    }

    pout.close();

    if (pi != null) {
        if ("/ex4".equals(pi))
            throw new ServletException("test ex4", new Throwable());
        if ("/ex5".equals(pi))
            throw new IOException("test ex5");
        if ("/ex6".equals(pi))
            throw new UnavailableException("test ex6");
        if ("/ex7".equals(pi))
            throw new HttpException(501);
    }

    request.getInputStream().close();

}

From source file:nl.ordina.jtech.http2.java8.server.tomcat.SimpleImagePush.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    System.out.println("request path: " + req.getContextPath() + " >> " + req.getServletPath() + " >> "
            + req.getPathTranslated());/* w  w  w .ja  va2  s .co m*/

    if (req.getPathTranslated() != null && req.getPathTranslated().contains("dynamic-image")) {
        handleDynamicImage(req, resp);
    }

    final HttpSession session = req.getSession(true);
    System.out.println(" (possibly new) sessionid: " + session.getId() + ", requested sessionid: "
            + req.getRequestedSessionId() + ", from cookie: " + req.isRequestedSessionIdFromCookie()
            + ", valid: " + req.isRequestedSessionIdValid());

    /*
     * Result:
     * GET https://localhost:8443/http2-java8-example-1.0/return.gif?answer=42
     *  header: x-my-header=[bar]
     *  header: x-my-header-1=[foo]
     *  header: x-my-header-1=[zaphod]
     */
    // Tomcat impl: http://svn.apache.org/viewvc/tomcat/tc9.0.x/branches/gsoc-jaspic/java/org/apache/catalina/core/ApplicationPushBuilder.java?view=markup
    PushBuilder pb = req.getPushBuilder().path("return.gif") // path is the only required value

            // note: the browser does not show these headers - only the ones delivered in the pushed resource itself
            .setHeader("x-my-header", "overwritten by subsequent setHeader").setHeader("x-my-header", "bar")
            .addHeader("x-my-header-1", "foo").addHeader("x-my-header-1", "zaphod") // note: had expected this to be reported as x-my-header-1=[foo,zaphod] ?

            // GET is default
            // ?! "IllegalArgumentException - if the method set expects a request body (eg POST)"; does not happen; Tomcat does not enforce it!
            .method("POST")

            .queryString("answer=42")

            //.sessionId("some-session-id") // dropped?! "pushed request will include the session ID either as a Cookie or as a URI parameter"
            .sessionId(session.getId())

    ;
    final boolean pushResult;
    try {
        //pb.push(); // results in 'java.lang.NoSuchMethodError: javax.servlet.http.PushBuilder.push()V'
        // - Tomcat's Servlet 4.0 API version return type is boolean, not void!
        final Method push = pb.getClass().getMethod("push");
        pushResult = (boolean) push.invoke(pb);
    } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
        if (e.getCause() instanceof UnsupportedOperationException) {
            respondWith(resp,
                    "<p>The following image was NOT provided via a push request! "
                            + "Cannot push over plain HTTP/1.x.</p>" + "<img src=\"" + req.getContextPath()
                            + "/return.gif\"/>");
            return;
        }
        respondWith(resp, e.getClass().getName() + ": " + e.getMessage() + ", cause: " + e.getCause());
        return;
    }

    simplePush(req, "Chrome Pony.png");
    simplePush(req, "second.html");

    respondWith(resp,
            "<p>The following static image was provided via a push request with result " + pushResult + "</p>"
                    + "<img src=\"" + req.getContextPath() + "/return.gif\"/><br/>"
                    + "<p>Dynamic push request: </p><img src=\"push/dynamic-image\"/><br/>"
                    + "<p><a href=\"second.html\">Link naar gepushte pagina</a></p>");
}

From source file:org.apache.camel.component.websocket.SignalkWebSocketServlet.java

public void init() throws ServletException {
    try {/*from ww  w .  jav  a2  s  .c  om*/
        String bs = getInitParameter("bufferSize");
        if (logger.isDebugEnabled())
            logger.debug("Upgrade ws, create factory:");
        this._webSocketFactory = new WebSocketFactory(this, (bs == null) ? 8192 : Integer.parseInt(bs)) {
            private WebSocketBuffers _buffers = new WebSocketBuffers(8192);
            private Map<WebSocketServletConnection, String> sessionMap = new HashMap<WebSocketServletConnection, String>();

            public void upgrade(HttpServletRequest request, HttpServletResponse response, WebSocket websocket,
                    String protocol) throws IOException {
                String sessionId = request.getRequestedSessionId();
                if (logger.isDebugEnabled())
                    logger.debug("Upgrade ws, requested sessionId:" + sessionId);
                if (StringUtils.isBlank(sessionId)) {
                    sessionId = request.getSession().getId();
                    if (logger.isDebugEnabled())
                        logger.debug("Request.sessionId:" + sessionId);

                }
                if (StringUtils.isBlank(sessionId)) {
                    sessionId = ((DefaultWebsocket) websocket).getConnectionKey();
                    if (logger.isDebugEnabled())
                        logger.debug("Request.wsSessionId:" + sessionId);

                }

                if (!("websocket".equalsIgnoreCase(request.getHeader("Upgrade"))))
                    throw new IllegalStateException("!Upgrade:websocket");
                if (!("HTTP/1.1".equals(request.getProtocol()))) {
                    throw new IllegalStateException("!HTTP/1.1");
                }
                int draft = request.getIntHeader("Sec-WebSocket-Version");
                if (draft < 0) {
                    draft = request.getIntHeader("Sec-WebSocket-Draft");
                }

                int requestedVersion = draft;
                AbstractHttpConnection http = AbstractHttpConnection.getCurrentConnection();
                if (http instanceof BlockingHttpConnection)
                    throw new IllegalStateException("Websockets not supported on blocking connectors");
                ConnectedEndPoint endp = (ConnectedEndPoint) http.getEndPoint();

                List<String> extensions_requested = new ArrayList<>();

                Enumeration<String> e = request.getHeaders("Sec-WebSocket-Extensions");
                while (e.hasMoreElements()) {
                    QuotedStringTokenizer tok = new QuotedStringTokenizer((String) e.nextElement(), ",");
                    while (tok.hasMoreTokens()) {
                        extensions_requested.add(tok.nextToken());
                    }

                }

                if (draft < getMinVersion())
                    draft = 2147483647;

                WebSocketServletConnection connection;
                switch (draft) {
                case -1:
                case 0:
                    connection = new WebSocketServletConnectionD00(this, websocket, endp, this._buffers,
                            http.getTimeStamp(), (int) getMaxIdleTime(), protocol);
                    break;
                case 1:
                case 2:
                case 3:
                case 4:
                case 5:
                case 6:
                    connection = new WebSocketServletConnectionD06(this, websocket, endp, this._buffers,
                            http.getTimeStamp(), (int) getMaxIdleTime(), protocol);
                    break;
                case 7:
                case 8:
                    List<Extension> extensions = initExtensions(extensions_requested, 5, 5, 3);
                    connection = new WebSocketServletConnectionD08(this, websocket, endp, this._buffers,
                            http.getTimeStamp(), (int) getMaxIdleTime(), protocol, extensions, draft);
                    break;
                case 13:
                    List<Extension> extensions1 = initExtensions(extensions_requested, 5, 5, 3);
                    connection = new WebSocketServletConnectionRFC6455(this, websocket, endp, this._buffers,
                            http.getTimeStamp(), (int) getMaxIdleTime(), protocol, extensions1, draft);
                    break;
                case 9:
                case 10:
                case 11:
                case 12:
                default:
                    String versions = "13";
                    if (getMinVersion() <= 8)
                        versions = new StringBuilder().append(versions).append(", 8").toString();
                    if (getMinVersion() <= 6)
                        versions = new StringBuilder().append(versions).append(", 6").toString();
                    if (getMinVersion() <= 0) {
                        versions = new StringBuilder().append(versions).append(", 0").toString();
                    }
                    response.setHeader("Sec-WebSocket-Version", versions);

                    StringBuilder err = new StringBuilder();
                    err.append("Unsupported websocket client version specification ");
                    if (requestedVersion >= 0)
                        err.append("[").append(requestedVersion).append("]");
                    else {
                        err.append("<Unspecified, likely a pre-draft version of websocket>");
                    }
                    err.append(", configured minVersion [").append(getMinVersion()).append("]");
                    err.append(", reported supported versions [").append(versions).append("]");
                    // LOG.warn(err.toString(), new Object[0]);

                    throw new HttpException(400, "Unsupported websocket version specification");
                }

                addConnection(connection);

                connection.getConnection().setMaxBinaryMessageSize(getMaxBinaryMessageSize());
                connection.getConnection().setMaxTextMessageSize(getMaxTextMessageSize());

                connection.handshake(request, response, protocol);
                response.flushBuffer();

                connection.fillBuffersFrom(((HttpParser) http.getParser()).getHeaderBuffer());
                connection.fillBuffersFrom(((HttpParser) http.getParser()).getBodyBuffer());
                String wsSession = ((DefaultWebsocket) websocket).getConnectionKey();
                //if(logger.isDebugEnabled())logger.debug("Upgraded session " + request.getSession().getId() + " to ws " + ((DefaultWebsocket) websocket).getConnectionKey());
                if (logger.isDebugEnabled())
                    logger.debug("Upgraded session " + sessionId + " to ws " + wsSession + " from remote ip:"
                            + request.getRemoteAddr());
                try {
                    sessionMap.put(connection, wsSession);
                    SubscriptionManagerFactory.getInstance().add(sessionId, wsSession,
                            ConfigConstants.OUTPUT_WS, request.getLocalAddr(), request.getRemoteAddr());
                    //add default sub, or specific sub here, all instant policy
                    String subscribe = request.getParameter("subscribe");
                    if (StringUtils.isBlank(subscribe) || "self".equals(subscribe)) {
                        //subscribe to self
                        String sub = "{\"context\":\"vessels.self\",\"subscribe\":[{\"path\":\"*\", \"policy\":\"instant\"}]}";
                        sendSub(request, sub, wsSession);
                    } else if ("all".equals(subscribe)) {
                        //subscribe to all
                        String sub = "{\"context\":\"vessels.*\",\"subscribe\":[{\"path\":\"*\", \"policy\":\"instant\"}]}";
                        sendSub(request, sub, wsSession);
                    } else if ("none".equals(subscribe)) {
                        //subscribe to none - do nothing
                    }

                } catch (Exception e1) {
                    logger.error(e1.getMessage(), e1);
                    throw new IOException(e1);
                }
                // LOG.debug("Websocket upgrade {} {} {} {}", new Object[] { request.getRequestURI(), Integer.valueOf(draft), protocol, connection });
                request.setAttribute("org.eclipse.jetty.io.Connection", connection);
                connection.getConnection().sendMessage(Util.getWelcomeMsg().toString());
            }

            private void sendSub(HttpServletRequest request, String sub, String wsSession) throws Exception {
                Map<String, Object> headers = new HashMap<>();
                headers.put(MSG_SRC_IP, request.getRemoteAddr());
                headers.put(MSG_SRC_IP_PORT, request.getRemotePort());

                if (Util.sameNetwork(request.getLocalAddr(), request.getRemoteAddr())) {
                    headers.put(MSG_TYPE, INTERNAL_IP);
                } else {
                    headers.put(MSG_TYPE, EXTERNAL_IP);
                }
                headers.put(WebsocketConstants.CONNECTION_KEY, wsSession);
                if (logger.isDebugEnabled())
                    logger.debug("Sending connection sub:" + sub);
                producer.sendBodyAndHeaders(RouteManager.SEDA_INPUT, sub, headers);

            }

            @Override
            protected boolean removeConnection(WebSocketServletConnection connection) {
                //unsubscribe and remove websocket session
                String wsSession = sessionMap.get(connection);
                if (logger.isDebugEnabled())
                    logger.debug("Ended wsSession " + wsSession);
                try {
                    SubscriptionManagerFactory.getInstance().removeWsSession(wsSession);
                } catch (Exception e1) {
                    logger.error(e1.getMessage(), e1);
                }
                return super.removeConnection(connection);
            }

        };
        this._webSocketFactory.setMaxTextMessageSize(256 * 1024);
        this._webSocketFactory.start();

        String max = getInitParameter("maxIdleTime");
        if (max != null) {
            this._webSocketFactory.setMaxIdleTime(Integer.parseInt(max));
        }
        max = getInitParameter("maxTextMessageSize");
        if (max != null) {
            this._webSocketFactory.setMaxTextMessageSize(Integer.parseInt(max));
        }
        max = getInitParameter("maxBinaryMessageSize");
        if (max != null) {
            this._webSocketFactory.setMaxBinaryMessageSize(Integer.parseInt(max));
        }
        String min = getInitParameter("minVersion");
        if (min != null)
            this._webSocketFactory.setMinVersion(Integer.parseInt(min));
    } catch (ServletException x) {
        throw x;
    } catch (Exception x) {
        throw new ServletException(x);
    }
}

From source file:org.apache.catalina.core.StandardHostValve.java

/**
 * Select the appropriate child Context to process this request,
 * based on the specified request URI.  If no matching Context can
 * be found, return an appropriate HTTP error.
 *
 * @param request Request to be processed
 * @param response Response to be produced
 * @param valveContext Valve context used to forward to the next Valve
 *
 * @exception IOException if an input/output error occurred
 * @exception ServletException if a servlet error occurred
 *//*from  w  w w . j av a2 s .  c o m*/
public final void invoke(Request request, Response response, ValveContext valveContext)
        throws IOException, ServletException {

    // Select the Context to be used for this Request
    Context context = request.getContext();
    if (context == null) {
        ((HttpServletResponse) response.getResponse()).sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                sm.getString("standardHost.noContext"));
        return;
    }

    // Bind the context CL to the current thread
    if (context.getLoader() != null) {
        // Not started - it should check for availability first
        // This should eventually move to Engine, it's generic.
        Thread.currentThread().setContextClassLoader(context.getLoader().getClassLoader());
    }

    // Update the session last access time for our session (if any)
    HttpServletRequest hreq = (HttpServletRequest) request.getRequest();
    String sessionId = hreq.getRequestedSessionId();
    if (sessionId != null) {
        Manager manager = context.getManager();
        if (manager != null) {
            Session session = manager.findSession(sessionId);
            if (session != null)
                session.access();
        }
    }

    // Ask this Context to process this request
    context.getPipeline().invoke(request, response);

    // Error page processing
    response.setSuspended(false);

    Throwable t = (Throwable) hreq.getAttribute(Globals.EXCEPTION_ATTR);

    if (t != null) {
        throwable(request, response, t);
    } else {
        status(request, response);
    }

    Thread.currentThread().setContextClassLoader(StandardHostValve.class.getClassLoader());

}

From source file:org.apache.catalina.realm.RealmBase.java

/**
 * Enforce any user data constraint required by the security constraint
 * guarding this request URI.  Return <code>true</code> if this constraint
 * was not violated and processing should continue, or <code>false</code>
 * if we have created a response already.
 *
 * @param request Request we are processing
 * @param response Response we are creating
 * @param constraint Security constraint being checked
 *
 * @exception IOException if an input/output error occurs
 *//*from  w ww.  j  a va 2 s .c om*/
public boolean hasUserDataPermission(HttpRequest request, HttpResponse response,
        SecurityConstraint[] constraints) throws IOException {

    // Is there a relevant user data constraint?
    if (constraints == null || constraints.length == 0) {
        if (log.isDebugEnabled())
            log.debug("  No applicable security constraint defined");
        return (true);
    }
    for (int i = 0; i < constraints.length; i++) {
        SecurityConstraint constraint = constraints[i];
        String userConstraint = constraint.getUserConstraint();
        if (userConstraint == null) {
            if (log.isDebugEnabled())
                log.debug("  No applicable user data constraint defined");
            return (true);
        }
        if (userConstraint.equals(Constants.NONE_TRANSPORT)) {
            if (log.isDebugEnabled())
                log.debug("  User data constraint has no restrictions");
            return (true);
        }

    }
    // Validate the request against the user data constraint
    if (request.getRequest().isSecure()) {
        if (log.isDebugEnabled())
            log.debug("  User data constraint already satisfied");
        return (true);
    }
    // Initialize variables we need to determine the appropriate action
    HttpServletRequest hrequest = (HttpServletRequest) request.getRequest();
    HttpServletResponse hresponse = (HttpServletResponse) response.getResponse();
    int redirectPort = request.getConnector().getRedirectPort();

    // Is redirecting disabled?
    if (redirectPort <= 0) {
        if (log.isDebugEnabled())
            log.debug("  SSL redirect is disabled");
        hresponse.sendError(HttpServletResponse.SC_FORBIDDEN, hrequest.getRequestURI());
        return (false);
    }

    // Redirect to the corresponding SSL port
    StringBuffer file = new StringBuffer();
    String protocol = "https";
    String host = hrequest.getServerName();
    // Protocol
    file.append(protocol).append("://");
    // Host with port
    file.append(host).append(":").append(redirectPort);
    // URI
    file.append(hrequest.getRequestURI());
    String requestedSessionId = hrequest.getRequestedSessionId();
    if ((requestedSessionId != null) && hrequest.isRequestedSessionIdFromURL()) {
        file.append(";jsessionid=");
        file.append(requestedSessionId);
    }
    String queryString = hrequest.getQueryString();
    if (queryString != null) {
        file.append('?');
        file.append(queryString);
    }
    if (log.isDebugEnabled())
        log.debug("  Redirecting to " + file.toString());
    hresponse.sendRedirect(file.toString());
    return (false);

}

From source file:org.apache.catalina.servlets.DefaultServlet.java

/**
 * Show HTTP header information.// www.ja  va  2 s . c om
 *
 * @param req Description of the Parameter
 */
protected void showRequestInfo(HttpServletRequest req) {

    System.out.println();
    System.out.println("SlideDAV Request Info");
    System.out.println();

    // Show generic info
    System.out.println("Encoding : " + req.getCharacterEncoding());
    System.out.println("Length : " + req.getContentLength());
    System.out.println("Type : " + req.getContentType());

    System.out.println();
    System.out.println("Parameters");

    Enumeration parameters = req.getParameterNames();

    while (parameters.hasMoreElements()) {
        String paramName = (String) parameters.nextElement();
        String[] values = req.getParameterValues(paramName);
        System.out.print(paramName + " : ");
        for (int i = 0; i < values.length; i++) {
            System.out.print(values[i] + ", ");
        }
        System.out.println();
    }

    System.out.println();

    System.out.println("Protocol : " + req.getProtocol());
    System.out.println("Address : " + req.getRemoteAddr());
    System.out.println("Host : " + req.getRemoteHost());
    System.out.println("Scheme : " + req.getScheme());
    System.out.println("Server Name : " + req.getServerName());
    System.out.println("Server Port : " + req.getServerPort());

    System.out.println();
    System.out.println("Attributes");

    Enumeration attributes = req.getAttributeNames();

    while (attributes.hasMoreElements()) {
        String attributeName = (String) attributes.nextElement();
        System.out.print(attributeName + " : ");
        System.out.println(req.getAttribute(attributeName).toString());
    }

    System.out.println();

    // Show HTTP info
    System.out.println();
    System.out.println("HTTP Header Info");
    System.out.println();

    System.out.println("Authentication Type : " + req.getAuthType());
    System.out.println("HTTP Method : " + req.getMethod());
    System.out.println("Path Info : " + req.getPathInfo());
    System.out.println("Path translated : " + req.getPathTranslated());
    System.out.println("Query string : " + req.getQueryString());
    System.out.println("Remote user : " + req.getRemoteUser());
    System.out.println("Requested session id : " + req.getRequestedSessionId());
    System.out.println("Request URI : " + req.getRequestURI());
    System.out.println("Context path : " + req.getContextPath());
    System.out.println("Servlet path : " + req.getServletPath());
    System.out.println("User principal : " + req.getUserPrincipal());

    System.out.println();
    System.out.println("Headers : ");

    Enumeration headers = req.getHeaderNames();

    while (headers.hasMoreElements()) {
        String headerName = (String) headers.nextElement();
        System.out.print(headerName + " : ");
        System.out.println(req.getHeader(headerName));
    }

    System.out.println();
    System.out.println();

}

From source file:org.apache.catalina.valves.ExtendedAccessLogValve.java

/**
 * Get app specific data./*from  w  w w.  jav a  2s .c  o  m*/
 * @param fieldInfo The field to decode
 * @param request Where we will pull the data from.
 * @return The appropriate value
 */
private String getAppSpecific(FieldInfo fieldInfo, Request request) {

    ServletRequest sr = request.getRequest();
    HttpServletRequest hsr = null;
    if (sr instanceof HttpServletRequest)
        hsr = (HttpServletRequest) sr;

    switch (fieldInfo.xType) {
    case FieldInfo.X_PARAMETER:
        return wrap(urlEncode(sr.getParameter(fieldInfo.value)));
    case FieldInfo.X_REQUEST:
        return wrap(sr.getAttribute(fieldInfo.value));
    case FieldInfo.X_SESSION:
        HttpSession session = null;
        if (hsr != null) {
            session = hsr.getSession(false);
            if (session != null)
                return wrap(session.getAttribute(fieldInfo.value));
        }
        break;
    case FieldInfo.X_COOKIE:
        Cookie[] c = hsr.getCookies();
        for (int i = 0; c != null && i < c.length; i++) {
            if (fieldInfo.value.equals(c[i].getName())) {
                return wrap(c[i].getValue());
            }
        }
    case FieldInfo.X_APP:
        return wrap(request.getContext().getServletContext().getAttribute(fieldInfo.value));
    case FieldInfo.X_SERVLET_REQUEST:
        if (fieldInfo.location == FieldInfo.X_LOC_AUTHTYPE) {
            return wrap(hsr.getAuthType());
        } else if (fieldInfo.location == FieldInfo.X_LOC_REMOTEUSER) {
            return wrap(hsr.getRemoteUser());
        } else if (fieldInfo.location == FieldInfo.X_LOC_REQUESTEDSESSIONID) {
            return wrap(hsr.getRequestedSessionId());
        } else if (fieldInfo.location == FieldInfo.X_LOC_REQUESTEDSESSIONIDFROMCOOKIE) {
            return wrap("" + hsr.isRequestedSessionIdFromCookie());
        } else if (fieldInfo.location == FieldInfo.X_LOC_REQUESTEDSESSIONIDVALID) {
            return wrap("" + hsr.isRequestedSessionIdValid());
        } else if (fieldInfo.location == FieldInfo.X_LOC_CONTENTLENGTH) {
            return wrap("" + hsr.getContentLength());
        } else if (fieldInfo.location == FieldInfo.X_LOC_CHARACTERENCODING) {
            return wrap(hsr.getCharacterEncoding());
        } else if (fieldInfo.location == FieldInfo.X_LOC_LOCALE) {
            return wrap(hsr.getLocale());
        } else if (fieldInfo.location == FieldInfo.X_LOC_PROTOCOL) {
            return wrap(hsr.getProtocol());
        } else if (fieldInfo.location == FieldInfo.X_LOC_SCHEME) {
            return wrap(hsr.getScheme());
        } else if (fieldInfo.location == FieldInfo.X_LOC_SECURE) {
            return wrap("" + hsr.isSecure());
        }
        break;
    default:
        ;
    }

    return "-";

}

From source file:org.apache.cocoon.servlet.DebugFilter.java

/**
 * Log debug information about the current environment.
 * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain)
 *//*from  w ww.  j av a  2  s.  c o  m*/
public void doFilter(ServletRequest req, ServletResponse res, FilterChain filterChain)
        throws IOException, ServletException {
    // we don't do debug msgs if this is not a http servlet request
    if (!(req instanceof HttpServletRequest)) {
        filterChain.doFilter(req, res);
        return;
    }
    try {
        ++activeRequestCount;
        final HttpServletRequest request = (HttpServletRequest) req;

        if (getLogger().isDebugEnabled()) {
            final StringBuffer msg = new StringBuffer();

            msg.append("DEBUGGING INFORMATION:").append(lineSeparator);
            msg.append("REQUEST: ").append(request.getRequestURI()).append(lineSeparator).append(lineSeparator);
            msg.append("CONTEXT PATH: ").append(request.getContextPath()).append(lineSeparator);
            msg.append("SERVLET PATH: ").append(request.getServletPath()).append(lineSeparator);
            msg.append("PATH INFO: ").append(request.getPathInfo()).append(lineSeparator).append(lineSeparator);

            msg.append("REMOTE HOST: ").append(request.getRemoteHost()).append(lineSeparator);
            msg.append("REMOTE ADDRESS: ").append(request.getRemoteAddr()).append(lineSeparator);
            msg.append("REMOTE USER: ").append(request.getRemoteUser()).append(lineSeparator);
            msg.append("REQUEST SESSION ID: ").append(request.getRequestedSessionId()).append(lineSeparator);
            msg.append("REQUEST PREFERRED LOCALE: ").append(request.getLocale().toString())
                    .append(lineSeparator);
            msg.append("SERVER HOST: ").append(request.getServerName()).append(lineSeparator);
            msg.append("SERVER PORT: ").append(request.getServerPort()).append(lineSeparator)
                    .append(lineSeparator);

            msg.append("METHOD: ").append(request.getMethod()).append(lineSeparator);
            msg.append("CONTENT LENGTH: ").append(request.getContentLength()).append(lineSeparator);
            msg.append("PROTOCOL: ").append(request.getProtocol()).append(lineSeparator);
            msg.append("SCHEME: ").append(request.getScheme()).append(lineSeparator);
            msg.append("AUTH TYPE: ").append(request.getAuthType()).append(lineSeparator).append(lineSeparator);
            msg.append("CURRENT ACTIVE REQUESTS: ").append(activeRequestCount).append(lineSeparator);

            // log all of the request parameters
            final Enumeration e = request.getParameterNames();

            msg.append("REQUEST PARAMETERS:").append(lineSeparator).append(lineSeparator);

            while (e.hasMoreElements()) {
                String p = (String) e.nextElement();

                msg.append("PARAM: '").append(p).append("' ").append("VALUES: '");
                String[] params = request.getParameterValues(p);
                for (int i = 0; i < params.length; i++) {
                    msg.append("[" + params[i] + "]");
                    if (i != (params.length - 1)) {
                        msg.append(", ");
                    }
                }

                msg.append("'").append(lineSeparator);
            }

            // log all of the header parameters
            final Enumeration e2 = request.getHeaderNames();

            msg.append("HEADER PARAMETERS:").append(lineSeparator).append(lineSeparator);

            while (e2.hasMoreElements()) {
                String p = (String) e2.nextElement();

                msg.append("PARAM: '").append(p).append("' ").append("VALUES: '");
                Enumeration e3 = request.getHeaders(p);
                while (e3.hasMoreElements()) {
                    msg.append("[" + e3.nextElement() + "]");
                    if (e3.hasMoreElements()) {
                        msg.append(", ");
                    }
                }

                msg.append("'").append(lineSeparator);
            }

            msg.append(lineSeparator).append("SESSION ATTRIBUTES:").append(lineSeparator).append(lineSeparator);

            // log all of the session attributes
            final HttpSession session = ((HttpServletRequest) req).getSession(false);
            if (session != null) {
                // Fix bug #12139: Session can be modified while still
                // being enumerated here
                synchronized (session) {
                    final Enumeration se = session.getAttributeNames();
                    while (se.hasMoreElements()) {
                        String p = (String) se.nextElement();
                        msg.append("PARAM: '").append(p).append("' ").append("VALUE: '")
                                .append(session.getAttribute(p)).append("'").append(lineSeparator);
                    }
                }
            }
            getLogger().debug(msg.toString());
        }

        // Delegate
        filterChain.doFilter(request, res);
    } finally {
        --activeRequestCount;
    }
}

From source file:org.apache.nifi.processors.standard.HandleHttpRequest.java

@Override
public void onTrigger(final ProcessContext context, final ProcessSession session) throws ProcessException {
    try {//from  w w  w .j a  v a2s .  c  om
        if (!initialized.get()) {
            initializeServer(context);
        }
    } catch (Exception e) {
        context.yield();
        throw new ProcessException("Failed to initialize the server", e);
    }

    final HttpRequestContainer container = containerQueue.poll();
    if (container == null) {
        return;
    }

    final long start = System.nanoTime();
    final HttpServletRequest request = container.getRequest();
    FlowFile flowFile = session.create();
    try {
        flowFile = session.importFrom(request.getInputStream(), flowFile);
    } catch (final IOException e) {
        getLogger().error("Failed to receive content from HTTP Request from {} due to {}",
                new Object[] { request.getRemoteAddr(), e });
        session.remove(flowFile);
        return;
    }

    final String charset = request.getCharacterEncoding() == null
            ? context.getProperty(URL_CHARACTER_SET).getValue()
            : request.getCharacterEncoding();

    final String contextIdentifier = UUID.randomUUID().toString();
    final Map<String, String> attributes = new HashMap<>();
    try {
        putAttribute(attributes, HTTPUtils.HTTP_CONTEXT_ID, contextIdentifier);
        putAttribute(attributes, "mime.type", request.getContentType());
        putAttribute(attributes, "http.servlet.path", request.getServletPath());
        putAttribute(attributes, "http.context.path", request.getContextPath());
        putAttribute(attributes, "http.method", request.getMethod());
        putAttribute(attributes, "http.local.addr", request.getLocalAddr());
        putAttribute(attributes, HTTPUtils.HTTP_LOCAL_NAME, request.getLocalName());
        final String queryString = request.getQueryString();
        if (queryString != null) {
            putAttribute(attributes, "http.query.string", URLDecoder.decode(queryString, charset));
        }
        putAttribute(attributes, HTTPUtils.HTTP_REMOTE_HOST, request.getRemoteHost());
        putAttribute(attributes, "http.remote.addr", request.getRemoteAddr());
        putAttribute(attributes, "http.remote.user", request.getRemoteUser());
        putAttribute(attributes, HTTPUtils.HTTP_REQUEST_URI, request.getRequestURI());
        putAttribute(attributes, "http.request.url", request.getRequestURL().toString());
        putAttribute(attributes, "http.auth.type", request.getAuthType());

        putAttribute(attributes, "http.requested.session.id", request.getRequestedSessionId());
        final DispatcherType dispatcherType = request.getDispatcherType();
        if (dispatcherType != null) {
            putAttribute(attributes, "http.dispatcher.type", dispatcherType.name());
        }
        putAttribute(attributes, "http.character.encoding", request.getCharacterEncoding());
        putAttribute(attributes, "http.locale", request.getLocale());
        putAttribute(attributes, "http.server.name", request.getServerName());
        putAttribute(attributes, HTTPUtils.HTTP_PORT, request.getServerPort());

        final Enumeration<String> paramEnumeration = request.getParameterNames();
        while (paramEnumeration.hasMoreElements()) {
            final String paramName = paramEnumeration.nextElement();
            final String value = request.getParameter(paramName);
            attributes.put("http.param." + paramName, value);
        }

        final Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (final Cookie cookie : cookies) {
                final String name = cookie.getName();
                final String cookiePrefix = "http.cookie." + name + ".";
                attributes.put(cookiePrefix + "value", cookie.getValue());
                attributes.put(cookiePrefix + "domain", cookie.getDomain());
                attributes.put(cookiePrefix + "path", cookie.getPath());
                attributes.put(cookiePrefix + "max.age", String.valueOf(cookie.getMaxAge()));
                attributes.put(cookiePrefix + "version", String.valueOf(cookie.getVersion()));
                attributes.put(cookiePrefix + "secure", String.valueOf(cookie.getSecure()));
            }
        }

        if (queryString != null) {
            final String[] params = URL_QUERY_PARAM_DELIMITER.split(queryString);
            for (final String keyValueString : params) {
                final int indexOf = keyValueString.indexOf("=");
                if (indexOf < 0) {
                    // no =, then it's just a key with no value
                    attributes.put("http.query.param." + URLDecoder.decode(keyValueString, charset), "");
                } else {
                    final String key = keyValueString.substring(0, indexOf);
                    final String value;

                    if (indexOf == keyValueString.length() - 1) {
                        value = "";
                    } else {
                        value = keyValueString.substring(indexOf + 1);
                    }

                    attributes.put("http.query.param." + URLDecoder.decode(key, charset),
                            URLDecoder.decode(value, charset));
                }
            }
        }
    } catch (final UnsupportedEncodingException uee) {
        throw new ProcessException("Invalid character encoding", uee); // won't happen because charset has been validated
    }

    final Enumeration<String> headerNames = request.getHeaderNames();
    while (headerNames.hasMoreElements()) {
        final String headerName = headerNames.nextElement();
        final String headerValue = request.getHeader(headerName);
        putAttribute(attributes, "http.headers." + headerName, headerValue);
    }

    final Principal principal = request.getUserPrincipal();
    if (principal != null) {
        putAttribute(attributes, "http.principal.name", principal.getName());
    }

    final X509Certificate certs[] = (X509Certificate[]) request
            .getAttribute("javax.servlet.request.X509Certificate");
    final String subjectDn;
    if (certs != null && certs.length > 0) {
        final X509Certificate cert = certs[0];
        subjectDn = cert.getSubjectDN().getName();
        final String issuerDn = cert.getIssuerDN().getName();

        putAttribute(attributes, HTTPUtils.HTTP_SSL_CERT, subjectDn);
        putAttribute(attributes, "http.issuer.dn", issuerDn);
    } else {
        subjectDn = null;
    }

    flowFile = session.putAllAttributes(flowFile, attributes);

    final HttpContextMap contextMap = context.getProperty(HTTP_CONTEXT_MAP)
            .asControllerService(HttpContextMap.class);
    final boolean registered = contextMap.register(contextIdentifier, request, container.getResponse(),
            container.getContext());

    if (!registered) {
        getLogger().warn(
                "Received request from {} but could not process it because too many requests are already outstanding; responding with SERVICE_UNAVAILABLE",
                new Object[] { request.getRemoteAddr() });

        try {
            container.getResponse().setStatus(Status.SERVICE_UNAVAILABLE.getStatusCode());
            container.getResponse().flushBuffer();
            container.getContext().complete();
        } catch (final Exception e) {
            getLogger().warn("Failed to respond with SERVICE_UNAVAILABLE message to {} due to {}",
                    new Object[] { request.getRemoteAddr(), e });
        }

        session.remove(flowFile);
        return;
    }

    final long receiveMillis = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - start);
    session.getProvenanceReporter().receive(flowFile, HTTPUtils.getURI(attributes),
            "Received from " + request.getRemoteAddr() + (subjectDn == null ? "" : " with DN=" + subjectDn),
            receiveMillis);
    session.transfer(flowFile, REL_SUCCESS);
    getLogger().info("Transferring {} to 'success'; received from {}",
            new Object[] { flowFile, request.getRemoteAddr() });
}

From source file:org.apache.ranger.security.web.filter.RangerSSOAuthenticationFilter.java

@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
        throws IOException, ServletException {

    HttpServletRequest httpRequest = (HttpServletRequest) servletRequest;

    String xForwardedURL = constructForwardableURL(httpRequest);

    if (httpRequest.getRequestedSessionId() != null && !httpRequest.isRequestedSessionIdValid()) {
        synchronized (httpRequest.getServletContext()) {
            if (httpRequest.getServletContext().getAttribute(httpRequest.getRequestedSessionId()) != null
                    && "locallogin".equals(httpRequest.getServletContext()
                            .getAttribute(httpRequest.getRequestedSessionId()).toString())) {
                httpRequest.getSession().setAttribute("locallogin", "true");
                httpRequest.getServletContext().removeAttribute(httpRequest.getRequestedSessionId());
            }/*from   w  ww  . j a v a2 s. c  o m*/
        }
    }

    RangerSecurityContext context = RangerContextHolder.getSecurityContext();
    UserSessionBase session = context != null ? context.getUserSession() : null;
    boolean ssoEnabled = session != null ? session.isSSOEnabled()
            : PropertiesUtil.getBooleanProperty("ranger.sso.enabled", false);

    String userAgent = httpRequest.getHeader("User-Agent");
    if (httpRequest.getSession() != null) {
        if (httpRequest.getSession().getAttribute("locallogin") != null) {
            servletRequest.setAttribute("ssoEnabled", false);
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }
    }
    //If sso is enable and request is not for local login and is from browser then it will go inside and try for knox sso authentication
    if (ssoEnabled && !httpRequest.getRequestURI().contains(LOCAL_LOGIN_URL)) {
        //if jwt properties are loaded and is current not authenticated then it will go for sso authentication
        //Note : Need to remove !isAuthenticated() after knoxsso solve the bug from cross-origin script
        if (jwtProperties != null && !isAuthenticated()) {
            HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;
            String serializedJWT = getJWTFromCookie(httpRequest);
            // if we get the hadoop-jwt token from the cookies then will process it further
            if (serializedJWT != null) {
                SignedJWT jwtToken = null;
                try {
                    jwtToken = SignedJWT.parse(serializedJWT);
                    boolean valid = validateToken(jwtToken);
                    //if the public key provide is correct and also token is not expired the process token
                    if (valid) {
                        String userName = jwtToken.getJWTClaimsSet().getSubject();
                        LOG.info("SSO login user : " + userName);

                        String rangerLdapDefaultRole = PropertiesUtil.getProperty("ranger.ldap.default.role",
                                "ROLE_USER");
                        //if we get the userName from the token then log into ranger using the same user
                        if (userName != null && !userName.trim().isEmpty()) {
                            final List<GrantedAuthority> grantedAuths = new ArrayList<>();
                            grantedAuths.add(new SimpleGrantedAuthority(rangerLdapDefaultRole));
                            final UserDetails principal = new User(userName, "", grantedAuths);
                            final Authentication finalAuthentication = new UsernamePasswordAuthenticationToken(
                                    principal, "", grantedAuths);
                            WebAuthenticationDetails webDetails = new WebAuthenticationDetails(httpRequest);
                            ((AbstractAuthenticationToken) finalAuthentication).setDetails(webDetails);
                            RangerAuthenticationProvider authenticationProvider = new RangerAuthenticationProvider();
                            authenticationProvider.setSsoEnabled(ssoEnabled);
                            Authentication authentication = authenticationProvider
                                    .authenticate(finalAuthentication);
                            authentication = getGrantedAuthority(authentication);
                            SecurityContextHolder.getContext().setAuthentication(authentication);
                        }

                        filterChain.doFilter(servletRequest, httpServletResponse);
                    }
                    // if the token is not valid then redirect to knox sso
                    else {
                        if (isWebUserAgent(userAgent)) {
                            String ssourl = constructLoginURL(httpRequest, xForwardedURL);
                            if (LOG.isDebugEnabled()) {
                                LOG.debug("SSO URL = " + ssourl);
                            }
                            httpServletResponse.sendRedirect(ssourl);
                        } else {
                            filterChain.doFilter(servletRequest, httpServletResponse);
                        }
                    }
                } catch (ParseException e) {
                    LOG.warn("Unable to parse the JWT token", e);
                }
            }
            // if the jwt token is not available then redirect it to knox sso
            else {
                if (isWebUserAgent(userAgent)) {
                    String ssourl = constructLoginURL(httpRequest, xForwardedURL);
                    if (LOG.isDebugEnabled()) {
                        LOG.debug("SSO URL = " + ssourl);
                    }
                    httpServletResponse.sendRedirect(ssourl);
                } else {
                    filterChain.doFilter(servletRequest, httpServletResponse);
                }
            }
        }
        //if property is not loaded or is already authenticated then proceed further with next filter
        else {
            filterChain.doFilter(servletRequest, servletResponse);
        }
    } else if (ssoEnabled && ((HttpServletRequest) servletRequest).getRequestURI().contains(LOCAL_LOGIN_URL)
            && isWebUserAgent(userAgent) && isAuthenticated()) {
        //If already there's an active session with sso and user want's to switch to local login(i.e without sso) then it won't be navigated to local login
        // In this scenario the user as to use separate browser
        String url = ((HttpServletRequest) servletRequest).getRequestURI().replace(LOCAL_LOGIN_URL + "/", "");
        url = url.replace(LOCAL_LOGIN_URL, "");
        LOG.warn(
                "There is an active session and if you want local login to ranger, try this on a separate browser");
        ((HttpServletResponse) servletResponse).sendRedirect(url);
    }
    //if sso is not enable or the request is not from browser then proceed further with next filter
    else {
        filterChain.doFilter(servletRequest, servletResponse);
    }
}