Example usage for javax.servlet.http HttpServletRequest isSecure

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

Introduction

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

Prototype

public boolean isSecure();

Source Link

Document

Returns a boolean indicating whether this request was made using a secure channel, such as HTTPS.

Usage

From source file:org.sakaiproject.util.RequestFilter.java

/**
 * Make sure we have a Sakai session./*w w w.  j  a v a 2 s  . c o  m*/
 *
 * @param req
 *        The request object.
 * @param res
 *        The response object.
 * @return The Sakai Session object.
 */
protected Session assureSession(HttpServletRequest req, HttpServletResponse res) {
    Session s = null;
    String sessionId = null;
    boolean allowSetCookieEarly = true;
    Cookie c = null;

    // automatic, i.e. not from user activity, request?
    boolean auto = req.getParameter(PARAM_AUTO) != null;

    // session id provided in a request parameter?
    boolean reqsession = m_sessionParamAllow && req.getParameter(ATTR_SESSION) != null;

    String suffix = getCookieSuffix();

    // try finding a non-cookie session based on the remote user / principal
    // Note: use principal instead of remote user to avoid any possible confusion with the remote user set by single-signon
    // auth.
    // Principal is set by our Dav interface, which this is designed to cover. -ggolden

    Principal principal = req.getUserPrincipal();

    if (m_checkPrincipal && (principal != null) && (principal.getName() != null)) {
        // set our session id to the remote user id
        sessionId = SessionManager.makeSessionId(req, principal);

        // don't supply this cookie to the client
        allowSetCookieEarly = false;

        // find the session
        s = SessionManager.getSession(sessionId);

        // if not found, make a session for this user
        if (s == null) {
            s = SessionManager.startSession(sessionId);
        }

        // Make these sessions expire after 10 minutes
        s.setMaxInactiveInterval(10 * 60);
    }

    // if no principal, check request parameter and cookie
    if (sessionId == null || s == null) {
        if (m_sessionParamAllow) {
            sessionId = req.getParameter(ATTR_SESSION);
        }

        // find our session id from our cookie
        c = findCookie(req, cookieName, suffix);

        if (sessionId == null && c != null) {
            // get our session id
            sessionId = c.getValue();
        }

        if (sessionId != null) {
            // remove the server id suffix
            final int dotPosition = sessionId.indexOf(DOT);
            if (dotPosition > -1) {
                sessionId = sessionId.substring(0, dotPosition);
            }
            if (M_log.isDebugEnabled()) {
                M_log.debug("assureSession found sessionId in cookie: " + sessionId);
            }

            // find the session
            s = SessionManager.getSession(sessionId);
        }

        // ignore the session id provided in a request parameter
        // if the session is not authenticated
        if (reqsession && s != null && s.getUserId() == null) {
            s = null;
        }
    }

    // if found and not automatic, mark it as active
    if ((s != null) && (!auto)) {
        synchronized (s) {
            s.setActive();
        }
    }
    if (s == null && sessionId != null) {
        // check to see if this session has already been built.  If not, rebuild
        RebuildBreakdownService rebuildBreakdownService = (RebuildBreakdownService) ComponentManager
                .get(RebuildBreakdownService.class);
        if (rebuildBreakdownService != null) {
            s = SessionManager.startSession(sessionId);
            if (!rebuildBreakdownService.rebuildSession(s)) {
                s.invalidate();
                s = null;
            }
        }
    }

    // if missing, make one
    if (s == null) {
        s = SessionManager.startSession();

        // if we have a cookie, but didn't find the session and are creating a new one, mark this
        if (c != null) {
            ThreadLocalManager.set(SessionManager.CURRENT_INVALID_SESSION,
                    SessionManager.CURRENT_INVALID_SESSION);
        }
    }

    // put the session in the request attribute
    req.setAttribute(ATTR_SESSION, s);

    // set this as the current session
    SessionManager.setCurrentSession(s);

    // Now that we know the session exists, regardless of whether it's new or not, lets see if there
    // is a UsageSession.  If so, we want to check it's serverId
    UsageSession us = null;
    // FIXME synchronizing on a changing value is a bad practice plus it is possible for s to be null according to the visible code -AZ
    synchronized (s) {
        us = (UsageSession) s.getAttribute(UsageSessionService.USAGE_SESSION_KEY);
        if (us != null) {
            // check the server instance id
            ServerConfigurationService configService = org.sakaiproject.component.cover.ServerConfigurationService
                    .getInstance();
            String serverInstanceId = configService.getServerIdInstance();
            if ((serverInstanceId != null) && (!serverInstanceId.equals(us.getServer()))) {
                // Log that the UsageSession server value is changing
                M_log.info("UsageSession: Server change detected: Old Server=" + us.getServer()
                        + "    New Server=" + serverInstanceId);
                // set the new UsageSession server value
                us.setServer(serverInstanceId);
            }
        }
    }

    // if we had a cookie and we have no session, clear the cookie TODO: detect closed session in the request
    if ((s == null) && (c != null)) {
        // remove the cookie
        c = new Cookie(cookieName, "");
        c.setPath("/");
        c.setMaxAge(0);
        if (cookieDomain != null) {
            c.setDomain(cookieDomain);
        }
        addCookie(res, c);
    }

    // if we have a session and had no cookie,
    // or the cookie was to another session id, set the cookie
    if ((s != null) && allowSetCookieEarly) {
        // the cookie value we need to use
        sessionId = s.getId() + DOT + suffix;

        if ((c == null) || (!c.getValue().equals(sessionId))) {
            // set the cookie
            c = new Cookie(cookieName, sessionId);
            c.setPath("/");
            c.setMaxAge(-1);
            if (cookieDomain != null) {
                c.setDomain(cookieDomain);
            }
            if (req.isSecure() == true) {
                c.setSecure(true);
            }
            addCookie(res, c);
        }
    }

    return s;
}

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 {// w w  w.j  a  va 2 s . 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:org.openqa.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 {//from w  ww .j  av a  2s  . c  o  m
            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:org.wyona.yanel.servlet.YanelServlet.java

/**
 * Check authorization and if not authorized then authenticate. Return null if authorization granted, otherwise return 401 and appropriate response such that client can provide credentials for authentication
 *
 * @return Null if access is granted and an authentication response if access is denied
 *//*from   w ww  .  ja v  a  2 s  .c  o m*/
private HttpServletResponse doAccessControl(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // INFO: Get identity, realm, path
    Identity identity;
    Realm realm;
    String pathWithoutQS;
    try {
        realm = map.getRealm(request.getServletPath());

        /* TBD: Check whether BASIC might be used and if so, then maybe handle things differently (also see https://github.com/wyona/yanel/issues/41)
                String authorizationHeader = request.getHeader("Authorization");
                if (authorizationHeader != null) {
                    if (authorizationHeader.toUpperCase().startsWith("BASIC")) {
        */

        identity = getIdentityFromRequest(request, realm);
        //log.warn("DEBUG: Identity retrieved from request (for realm '" + realm.getID() + "'): " + identity);
        pathWithoutQS = map.getPath(realm, request.getServletPath());
    } catch (Exception e) {
        throw new ServletException(e.getMessage(), e);
    }

    // INFO: Try Auto-Login
    if (identity == null || (identity != null && identity.isWorld())) {
        //log.debug("Not logged in yet, hence try auto login...");
        try {
            if (AutoLogin.tryAutoLogin(request, response, realm)) {
                log.debug("Auto login successful, hence set identity inside session...");
                String username = AutoLogin.getUsername(request);
                if (username != null) {
                    User user = realm.getIdentityManager().getUserManager().getUser(username);
                    setIdentity(new Identity(user, user.getEmail()), request.getSession(), realm);
                } else {
                    log.error("Auto login successful, but no username available!");
                }
            } else {
                //log.debug("No auto login.");
            }
        } catch (Exception e) {
            log.error(e, e);
        }
    }

    // INFO: Check Authorization
    boolean authorized = false;
    Usecase usecase = getUsecase(request);
    try {
        if (log.isDebugEnabled())
            log.debug("Check authorization: realm: " + realm + ", path: " + pathWithoutQS + ", identity: "
                    + identity + ", Usecase: " + usecase.getName());
        authorized = realm.getPolicyManager().authorize(pathWithoutQS, request.getQueryString(), identity,
                usecase);
        if (log.isDebugEnabled())
            log.debug("Check authorization result: " + authorized);
    } catch (Exception e) {
        throw new ServletException(e.getMessage(), e);
    }

    if (authorized) {
        if (identity != null && identity.getUsername() != null) {
            if (identity.getUsername() != null) {
                if (log.isDebugEnabled())
                    log.debug("Access for user '" + identity.getUsername() + "' granted: "
                            + getRequestURLQS(request, null, false));
                //response.setHeader("Cache-control", "no-cache"); // INFO: Do not allow browsers to cache content for users which are signed in, but we currently do not use this because of performance reasons. One can set the resource property 'yanel:no-cache' on specific pages though in order to prevent caching of protected pages. Related to this see how a timestamp is appened during logout (see doLogout())
            } else {
                if (log.isDebugEnabled())
                    log.debug("Access for anonymous user (aka WORLD) granted: "
                            + getRequestURLQS(request, null, false));
            }
        } else {
            if (log.isDebugEnabled())
                log.debug("Access for anonymous user (aka WORLD) granted: "
                        + getRequestURLQS(request, null, false));
        }
        return null; // INFO: Return null in order to indicate that access is granted
    } else {
        log.warn("Access denied: " + getRequestURLQS(request, null, false) + " (Path of request: "
                + pathWithoutQS + "; Identity: " + identity + "; Usecase: " + usecase + ")");
        // TODO: Implement HTTP BASIC/DIGEST response (see above)

        // INFO: If request is not via SSL and SSL is configured, then redirect to SSL connection.
        if (!request.isSecure()) {
            if (sslPort != null) {
                log.info("Redirect to SSL ...");
                try {
                    URL url = new URL(getRequestURLQS(request, null, false).toString());
                    url = new URL("https", url.getHost(), new Integer(sslPort).intValue(), url.getFile());
                    if (realm.isProxySet()) {
                        if (realm.getProxySSLPort() >= 0) {
                            log.debug("Use configured port: " + realm.getProxySSLPort());
                            url = new URL(url.getProtocol(), url.getHost(),
                                    new Integer(realm.getProxySSLPort()).intValue(), url.getFile());
                        } else {
                            log.debug("Use default port: " + url.getDefaultPort());
                            // NOTE: getDefaultPort depends on the Protocol (e.g. https is 443)
                            url = new URL(url.getProtocol(), url.getHost(), url.getDefaultPort(),
                                    url.getFile());
                        }
                    }
                    log.info("Redirect to SSL: " + url);
                    response.setHeader("Location", url.toString());
                    // TODO: Yulup has a bug re TEMPORARY_REDIRECT
                    //response.setStatus(javax.servlet.http.HttpServletResponse.SC_TEMPORARY_REDIRECT);
                    response.setStatus(javax.servlet.http.HttpServletResponse.SC_MOVED_PERMANENTLY);
                    return response;
                } catch (Exception e) {
                    log.error(e.getMessage(), e);
                }
            } else {
                log.warn("SSL does not seem to be configured!");
            }
        } else {
            log.info("This connection is already via SSL.");
        }

        if (doAuthenticate(request, response) != null) {
            log.info(
                    "Access denied and not authenticated correctly yet, hence return response of web authenticator...");
            /*
            NOTE: Such a response can have different reasons:
                - Either no credentials provided yet and web authenticator is generating a response to fetch credentials
                - Or authentication failed and web authenticator is resending response to fetch again credentials");
                - Or authentication was successful and web authenticator sends a redirect
            */

            // TODO: Check "would be mime type", etc.: if (logAccessIsApplicable(view.getMimeType())) {
            if (logAccessEnabled) { // INFO: Although authorization has been denied and user first needs to authenticate, let's log the request anyway
                if (usecase != null && usecase.getName().equals("introspection")) {
                    log.debug("Ignore introspection request: " + getRequestURLQS(request, null, false));
                } else {
                    log.info("Access denied and authentication not completed yet, hence let's log request '"
                            + getRequestURLQS(request, null, false) + "'");
                    doLogAccess(request, response, HttpServletResponse.SC_UNAUTHORIZED, null, null);
                }
            }

            //log.debug("Returned status code: " + response.getStatus()); // INFO: Only supported by servlet api 3.0 and higher
            return response;
        } else {
            try {
                //log.debug("Authentication was successful for user: " + getIdentity(request, map).getUsername());
            } catch (Exception e) {
                log.error(e.getMessage(), e);
            }

            URL url = new URL(getRequestURLQS(request, null, false).toString());
            if (sslPort != null) {
                url = new URL("https", url.getHost(), new Integer(sslPort).intValue(), url.getFile());
            }

            // INFO: Hash fragment is set by login screen, e.g. src/resources/login/htdocs/login-screen.xsl
            String hashFragment = request.getParameter("yanel.login.hash.fragment");
            if (hashFragment != null && hashFragment.length() > 0) {
                log.debug("Hash fragment: " + hashFragment);
                url = new URL(url.getProtocol(), url.getHost(), url.getPort(),
                        url.getFile() + "#" + hashFragment);
            }

            log.warn("DEBUG: Redirect to original request: " + url);

            //response.sendRedirect(url.toString()); // 302
            // TODO: Yulup has a bug re TEMPORARY_REDIRECT (or is the problem that the load balancer is rewritting 302 reponses?!)
            response.setHeader("Location", url.toString());
            response.setStatus(javax.servlet.http.HttpServletResponse.SC_MOVED_PERMANENTLY); // 301
            //response.setStatus(javax.servlet.http.HttpServletResponse.SC_TEMPORARY_REDIRECT); // 302

            return response;
        }
    }
}

From source file:org.openlaszlo.data.HTTPDataSource.java

/**
 * @param since last modified time to use
 * @param req//from w  ww.  j a  va  2s. c o m
 * @param url if null, ignored
 * @param redirCount number of redirs we've done
 */
public static HttpData getDataOnce(HttpServletRequest req, HttpServletResponse res, long since, String surl,
        int redirCount, int timeout)
        throws IOException, HttpException, DataSourceException, MalformedURLException {

    HttpMethodBase request = null;
    HostConfiguration hcfg = new HostConfiguration();

    /*
      [todo hqm 2006-02-01] Anyone know why this code was here? It is setting
      the mime type to something which just confuses the DHTML parser.
              
      if (res != null) {
    res.setContentType("application/x-www-form-urlencoded;charset=UTF-8");
    }
    */

    try {

        // TODO: [2002-01-09 bloch] cope with cache-control
        // response headers (no-store, no-cache, must-revalidate, 
        // proxy-revalidate).

        if (surl == null) {
            surl = getURL(req);
        }
        if (surl == null || surl.equals("")) {
            throw new MalformedURLException(
                    /* (non-Javadoc)
                     * @i18n.test
                     * @org-mes="url is empty or null"
                     */
                    org.openlaszlo.i18n.LaszloMessages.getMessage(HTTPDataSource.class.getName(),
                            "051018-312"));
        }

        String reqType = "";
        String headers = "";

        if (req != null) {
            reqType = req.getParameter("reqtype");
            headers = req.getParameter("headers");
        }

        boolean isPost = false;
        mLogger.debug("reqtype = " + reqType);

        if (reqType != null && reqType.equals("POST")) {
            request = new LZPostMethod();
            request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
            isPost = true;
            mLogger.debug("setting POST req method");
        } else if (reqType != null && reqType.equals("PUT")) {
            request = new LZPutMethod();
            // todo [hqm 2007] treat PUT like POST? 
            isPost = true;
            mLogger.debug("setting PUT req method");
        } else if (reqType != null && reqType.equals("DELETE")) {
            request = new LZDeleteMethod();
            mLogger.debug("setting DELETE req method");
        } else {
            mLogger.debug("setting GET (default) req method");
            request = new LZGetMethod();
        }

        request.getParams().setVersion(mUseHttp11 ? HttpVersion.HTTP_1_1 : HttpVersion.HTTP_1_0);

        // Proxy the request headers
        if (req != null) {
            LZHttpUtils.proxyRequestHeaders(req, request);
        }

        // Set headers from query string
        if (headers != null && headers.length() > 0) {
            StringTokenizer st = new StringTokenizer(headers, "\n");
            while (st.hasMoreTokens()) {
                String h = st.nextToken();
                int i = h.indexOf(":");
                if (i > -1) {
                    String n = h.substring(0, i);
                    String v = h.substring(i + 2, h.length());
                    request.setRequestHeader(n, v);
                    mLogger.debug(
                            /* (non-Javadoc)
                             * @i18n.test
                             * @org-mes="setting header " + p[0] + "=" + p[1]
                             */
                            org.openlaszlo.i18n.LaszloMessages.getMessage(HTTPDataSource.class.getName(),
                                    "051018-359", new Object[] { n, v }));
                }
            }
        }

        mLogger.debug("Parsing url");
        URI uri = LZHttpUtils.newURI(surl);
        try {
            hcfg.setHost(uri);
        } catch (Exception e) {
            throw new MalformedURLException(
                    /* (non-Javadoc)
                     * @i18n.test
                     * @org-mes="can't form uri from " + p[0]
                     */
                    org.openlaszlo.i18n.LaszloMessages.getMessage(HTTPDataSource.class.getName(), "051018-376",
                            new Object[] { surl }));
        }

        // This gets us the url-encoded (escaped) path and query string
        String path = uri.getEscapedPath();
        String query = uri.getEscapedQuery();
        mLogger.debug(
                /* (non-Javadoc)
                 * @i18n.test
                 * @org-mes="encoded path:  " + p[0]
                 */
                org.openlaszlo.i18n.LaszloMessages.getMessage(HTTPDataSource.class.getName(), "051018-389",
                        new Object[] { path }));
        mLogger.debug(
                /* (non-Javadoc)
                 * @i18n.test
                 * @org-mes="encoded query: " + p[0]
                 */
                org.openlaszlo.i18n.LaszloMessages.getMessage(HTTPDataSource.class.getName(), "051018-397",
                        new Object[] { query }));

        // This call takes a decoded (unescaped) path
        request.setPath(path);

        boolean hasQuery = (query != null && query.length() > 0);

        String rawcontent = null;
        // Newer rawpost protocol puts lzpostbody as a separate
        // top level query arg in the request.
        rawcontent = req.getParameter("lzpostbody");

        if (isPost) {
            // Older rawpost protocol put the "lzpostbody" arg
            // embedded in the "url" args's query args
            if (rawcontent == null && hasQuery) {
                rawcontent = findQueryArg("lzpostbody", query);
            }
            if (rawcontent != null) {
                // Get the unescaped query string
                ((EntityEnclosingMethod) request).setRequestEntity(new StringRequestEntity(rawcontent));
            } else if (hasQuery) {
                StringTokenizer st = new StringTokenizer(query, "&");
                while (st.hasMoreTokens()) {
                    String it = st.nextToken();
                    int i = it.indexOf("=");
                    if (i > 0) {
                        String n = it.substring(0, i);
                        String v = it.substring(i + 1, it.length());
                        // POST encodes values during request
                        ((PostMethod) request).addParameter(n, URLDecoder.decode(v, "UTF-8"));
                    } else {
                        mLogger.warn(
                                /* (non-Javadoc)
                                 * @i18n.test
                                 * @org-mes="ignoring bad token (missing '=' char) in query string: " + p[0]
                                 */
                                org.openlaszlo.i18n.LaszloMessages.getMessage(HTTPDataSource.class.getName(),
                                        "051018-429", new Object[] { it }));
                    }
                }
            }
        } else {
            // This call takes an encoded (escaped) query string
            request.setQueryString(query);
        }

        // Put in the If-Modified-Since headers
        if (since != -1) {
            String lms = LZHttpUtils.getDateString(since);
            request.setRequestHeader(LZHttpUtils.IF_MODIFIED_SINCE, lms);
            mLogger.debug(
                    /* (non-Javadoc)
                     * @i18n.test
                     * @org-mes="proxying lms: " + p[0]
                     */
                    org.openlaszlo.i18n.LaszloMessages.getMessage(HTTPDataSource.class.getName(), "051018-450",
                            new Object[] { lms }));
        }

        mLogger.debug(
                /* (non-Javadoc)
                 * @i18n.test
                 * @org-mes="setting up http client"
                 */
                org.openlaszlo.i18n.LaszloMessages.getMessage(HTTPDataSource.class.getName(), "051018-460"));
        HttpClient htc = null;
        if (mConnectionMgr != null) {
            htc = new HttpClient(mConnectionMgr);
        } else {
            htc = new HttpClient();
        }

        htc.setHostConfiguration(hcfg);

        // This is the data timeout
        mLogger.debug(
                /* (non-Javadoc)
                 * @i18n.test
                 * @org-mes="timeout set to " + p[0]
                 */
                org.openlaszlo.i18n.LaszloMessages.getMessage(HTTPDataSource.class.getName(), "051018-478",
                        new Object[] { timeout }));
        htc.getParams().setSoTimeout(timeout);

        // Set connection timeout the same
        htc.getHttpConnectionManager().getParams().setConnectionTimeout(mConnectionTimeout);

        // Set timeout for getting a connection
        htc.getParams().setConnectionManagerTimeout(mConnectionPoolTimeout);

        // TODO: [2003-03-05 bloch] this should be more configurable (per app?)
        if (!isPost) {
            request.setFollowRedirects(mFollowRedirects > 0);
        }

        long t1 = System.currentTimeMillis();
        mLogger.debug("starting remote request");
        int rc = htc.executeMethod(hcfg, request);
        String status = HttpStatus.getStatusText(rc);
        if (status == null) {
            status = "" + rc;
        }
        mLogger.debug(
                /* (non-Javadoc)
                 * @i18n.test
                 * @org-mes="remote response status: " + p[0]
                 */
                org.openlaszlo.i18n.LaszloMessages.getMessage(HTTPDataSource.class.getName(), "051018-504",
                        new Object[] { status }));

        HttpData data = null;
        if (isRedirect(rc) && mFollowRedirects > redirCount) {
            String loc = request.getResponseHeader("Location").toString();
            String hostURI = loc.substring(loc.indexOf(": ") + 2, loc.length());
            mLogger.info(
                    /* (non-Javadoc)
                     * @i18n.test
                     * @org-mes="Following URL from redirect: " + p[0]
                     */
                    org.openlaszlo.i18n.LaszloMessages.getMessage(HTTPDataSource.class.getName(), "051018-517",
                            new Object[] { hostURI }));
            long t2 = System.currentTimeMillis();
            if (timeout > 0) {
                timeout -= (t2 - t1);
                if (timeout < 0) {
                    throw new InterruptedIOException(
                            /* (non-Javadoc)
                             * @i18n.test
                             * @org-mes=p[0] + " timed out after redirecting to " + p[1]
                             */
                            org.openlaszlo.i18n.LaszloMessages.getMessage(HTTPDataSource.class.getName(),
                                    "051018-529", new Object[] { surl, loc }));
                }
            }

            data = getDataOnce(req, res, since, hostURI, redirCount++, timeout);
        } else {
            data = new HttpData(request, rc);
        }

        if (req != null && res != null) {
            // proxy response headers
            LZHttpUtils.proxyResponseHeaders(request, res, req.isSecure());
        }

        return data;

    } catch (ConnectTimeoutException ce) {
        // Transduce to an InterrupedIOException, since lps takes these to be timeouts.
        if (request != null) {
            request.releaseConnection();
        }
        throw new InterruptedIOException(
                /* (non-Javadoc)
                 * @i18n.test
                 * @org-mes="connecting to " + p[0] + ":" + p[1] + " timed out beyond " + p[2] + " msecs."
                 */
                org.openlaszlo.i18n.LaszloMessages.getMessage(HTTPDataSource.class.getName(), "051018-557",
                        new Object[] { hcfg.getHost(), hcfg.getPort(), mConnectionTimeout }));
    } catch (HttpRecoverableException hre) {
        if (request != null) {
            request.releaseConnection();
        }
        throw hre;
    } catch (HttpException e) {
        if (request != null) {
            request.releaseConnection();
        }
        throw e;
    } catch (IOException ie) {
        if (request != null) {
            request.releaseConnection();
        }
        throw ie;
    } catch (RuntimeException e) {
        if (request != null) {
            request.releaseConnection();
        }
        throw e;
    }
}

From source file:com.liferay.portal.events.ServicePreAction.java

public ThemeDisplay initThemeDisplay(HttpServletRequest request, HttpServletResponse response)
        throws Exception {

    HttpSession session = request.getSession();

    // Company/* w w  w.  j ava 2  s . c  o  m*/

    Company company = PortalUtil.getCompany(request);

    long companyId = company.getCompanyId();

    // CDN host

    String cdnHost = PortalUtil.getCDNHost(request);

    String dynamicResourcesCDNHost = StringPool.BLANK;

    boolean cdnDynamicResourceEnabled = PortalUtil.isCDNDynamicResourcesEnabled(request);

    if (cdnDynamicResourceEnabled) {
        dynamicResourcesCDNHost = cdnHost;
    }

    // Portal URL

    String portalURL = PortalUtil.getPortalURL(request);

    // Paths

    String contextPath = PortalUtil.getPathContext();
    String friendlyURLPrivateGroupPath = PortalUtil.getPathFriendlyURLPrivateGroup();
    String friendlyURLPrivateUserPath = PortalUtil.getPathFriendlyURLPrivateUser();
    String friendlyURLPublicPath = PortalUtil.getPathFriendlyURLPublic();
    String imagePath = dynamicResourcesCDNHost.concat(PortalUtil.getPathImage());
    String mainPath = PortalUtil.getPathMain();

    String i18nPath = (String) request.getAttribute(WebKeys.I18N_PATH);

    if (Validator.isNotNull(i18nPath)) {
        if (Validator.isNotNull(contextPath)) {
            String i18nContextPath = contextPath.concat(i18nPath);

            friendlyURLPrivateGroupPath = StringUtil.replaceFirst(friendlyURLPrivateGroupPath, contextPath,
                    i18nContextPath);
            friendlyURLPrivateUserPath = StringUtil.replaceFirst(friendlyURLPrivateUserPath, contextPath,
                    i18nContextPath);
            friendlyURLPublicPath = StringUtil.replaceFirst(friendlyURLPublicPath, contextPath,
                    i18nContextPath);
            mainPath = StringUtil.replaceFirst(mainPath, contextPath, i18nContextPath);
        } else {
            friendlyURLPrivateGroupPath = i18nPath.concat(friendlyURLPrivateGroupPath);
            friendlyURLPrivateUserPath = i18nPath.concat(friendlyURLPrivateUserPath);
            friendlyURLPublicPath = i18nPath.concat(friendlyURLPublicPath);
            mainPath = i18nPath.concat(mainPath);
        }
    }

    // Company logo

    StringBundler sb = new StringBundler(5);

    sb.append(imagePath);
    sb.append("/company_logo?img_id=");
    sb.append(company.getLogoId());
    sb.append("&t=");
    sb.append(WebServerServletTokenUtil.getToken(company.getLogoId()));

    String companyLogo = sb.toString();

    int companyLogoHeight = 0;
    int companyLogoWidth = 0;

    Image companyLogoImage = ImageLocalServiceUtil.getCompanyLogo(company.getLogoId());

    if (companyLogoImage != null) {
        companyLogoHeight = companyLogoImage.getHeight();
        companyLogoWidth = companyLogoImage.getWidth();
    }

    String realCompanyLogo = companyLogo;
    int realCompanyLogoHeight = companyLogoHeight;
    int realCompanyLogoWidth = companyLogoWidth;

    // User

    User user = null;

    try {
        user = PortalUtil.getUser(request);
    } catch (NoSuchUserException nsue) {
        if (_log.isWarnEnabled()) {
            _log.warn(nsue.getMessage());
        }

        long userId = PortalUtil.getUserId(request);

        if (userId > 0) {
            session.invalidate();
        }

        return null;
    }

    boolean signedIn = false;

    if (user == null) {
        user = company.getDefaultUser();
    } else if (!user.isDefaultUser()) {
        signedIn = true;
    }

    if (PropsValues.BROWSER_CACHE_DISABLED || (PropsValues.BROWSER_CACHE_SIGNED_IN_DISABLED && signedIn)) {

        response.setDateHeader(HttpHeaders.EXPIRES, 0);
        response.setHeader(HttpHeaders.CACHE_CONTROL, HttpHeaders.CACHE_CONTROL_NO_CACHE_VALUE);
        response.setHeader(HttpHeaders.PRAGMA, HttpHeaders.PRAGMA_NO_CACHE_VALUE);
    }

    User realUser = user;

    Long realUserId = (Long) session.getAttribute(WebKeys.USER_ID);

    if (realUserId != null) {
        if (user.getUserId() != realUserId.longValue()) {
            realUser = UserLocalServiceUtil.getUserById(realUserId.longValue());
        }
    }

    String doAsUserId = ParamUtil.getString(request, "doAsUserId");
    String doAsUserLanguageId = ParamUtil.getString(request, "doAsUserLanguageId");
    long doAsGroupId = ParamUtil.getLong(request, "doAsGroupId");

    long refererPlid = ParamUtil.getLong(request, "refererPlid");

    if (LayoutLocalServiceUtil.fetchLayout(refererPlid) == null) {
        refererPlid = 0;
    }

    String controlPanelCategory = ParamUtil.getString(request, "controlPanelCategory");

    // Permission checker

    PermissionChecker permissionChecker = PermissionCheckerFactoryUtil.create(user);

    PermissionThreadLocal.setPermissionChecker(permissionChecker);
    //Modification start (code changed and moved to the bottom)
    // Locale
    /*
        Locale locale = (Locale)session.getAttribute(Globals.LOCALE_KEY);
            
        if (Validator.isNotNull(doAsUserLanguageId)) {
          locale = LocaleUtil.fromLanguageId(doAsUserLanguageId);
        }
            
        String i18nLanguageId = (String)request.getAttribute(
              WebKeys.I18N_LANGUAGE_ID);
            
        if (Validator.isNotNull(i18nLanguageId)) {
          locale = LocaleUtil.fromLanguageId(i18nLanguageId);
        }
        else if (locale == null) {
          if (signedIn) {
              locale = user.getLocale();
          }
          else {
            
              // User previously set their preferred language
            
              String languageId = CookieKeys.getCookie(
          request, CookieKeys.GUEST_LANGUAGE_ID, false);
            
              if (Validator.isNotNull(languageId)) {
      locale = LocaleUtil.fromLanguageId(languageId);
              }
            
              // Get locale from the request
            
              if ((locale == null) && PropsValues.LOCALE_DEFAULT_REQUEST) {
      Enumeration<Locale> locales = request.getLocales();
            
      while (locales.hasMoreElements()) {
          Locale requestLocale = locales.nextElement();
            
          if (Validator.isNull(requestLocale.getCountry())) {
            
              // Locales must contain a country code
            
              requestLocale = LanguageUtil.getLocale(
                      requestLocale.getLanguage());
          }
            
          if (LanguageUtil.isAvailableLocale(requestLocale)) {
              locale = requestLocale;
            
              break;
          }
      }
              }
            
              // Get locale from the default user
            
              if (locale == null) {
      locale = user.getLocale();
              }
            
              if (Validator.isNull(locale.getCountry())) {
            
      // Locales must contain a country code
            
      locale = LanguageUtil.getLocale(locale.getLanguage());
              }
            
              if (!LanguageUtil.isAvailableLocale(locale)) {
      locale = user.getLocale();
              }
          }
            
          session.setAttribute(Globals.LOCALE_KEY, locale);
            
          LanguageUtil.updateCookie(request, response, locale);
        }*/
    //Modification end
    // Cookie support

    try {

        // LEP-4069

        CookieKeys.validateSupportCookie(request);
    } catch (Exception e) {
        CookieKeys.addSupportCookie(request, response);
    }

    // Time zone

    TimeZone timeZone = user.getTimeZone();

    if (timeZone == null) {
        timeZone = company.getTimeZone();
    }

    // Layouts

    if (signedIn) {
        updateUserLayouts(user);
    }

    Layout layout = null;
    List<Layout> layouts = null;

    long plid = ParamUtil.getLong(request, "p_l_id");

    if (plid > 0) {
        layout = LayoutLocalServiceUtil.getLayout(plid);

        long sourceGroupId = ParamUtil.getLong(request, "p_v_l_s_g_id");

        if ((sourceGroupId > 0) && (sourceGroupId != layout.getGroupId())) {
            Group sourceGroup = GroupLocalServiceUtil.getGroup(sourceGroupId);

            if (layout.isPublicLayout()
                    || SitesUtil.isUserGroupLayoutSetViewable(permissionChecker, layout.getGroup())) {

                layout = new VirtualLayout(layout, sourceGroup);
            } else {
                layout = null;
            }
        }
    } else {
        long groupId = ParamUtil.getLong(request, "groupId");
        boolean privateLayout = ParamUtil.getBoolean(request, "privateLayout");
        long layoutId = ParamUtil.getLong(request, "layoutId");

        if ((groupId > 0) && (layoutId > 0)) {
            layout = LayoutLocalServiceUtil.getLayout(groupId, privateLayout, layoutId);
        }
    }

    Boolean redirectToDefaultLayout = (Boolean) request.getAttribute(WebKeys.REDIRECT_TO_DEFAULT_LAYOUT);

    if (redirectToDefaultLayout == null) {
        redirectToDefaultLayout = Boolean.FALSE;
    }

    if (layout != null) {
        Group group = layout.getGroup();

        if (!signedIn && PropsValues.AUTH_FORWARD_BY_REDIRECT) {
            request.setAttribute(WebKeys.REQUESTED_LAYOUT, layout);
        }

        String ppid = ParamUtil.getString(request, "p_p_id");

        if (Validator.isNull(controlPanelCategory) && Validator.isNotNull(ppid)
                && (LiferayWindowState.isPopUp(request) || LiferayWindowState.isExclusive(request))) {

            controlPanelCategory = _CONTROL_PANEL_CATEGORY_PORTLET_PREFIX + ppid;
        }

        boolean viewableGroup = LayoutPermissionUtil.contains(permissionChecker, layout, controlPanelCategory,
                true, ActionKeys.VIEW);
        boolean viewableStaging = GroupPermissionUtil.contains(permissionChecker, group.getGroupId(),
                ActionKeys.VIEW_STAGING);

        if (viewableStaging) {
            layouts = LayoutLocalServiceUtil.getLayouts(layout.getGroupId(), layout.isPrivateLayout(),
                    LayoutConstants.DEFAULT_PARENT_LAYOUT_ID);
        } else if (!viewableGroup && group.isStagingGroup()) {
            layout = null;
        } else
        /* Permissions are managed by Mobile Portlet
        if (!isLoginRequest(request) &&
            (!viewableGroup ||
                (!redirectToDefaultLayout &&
          !LayoutPermissionUtil.contains(
              permissionChecker, layout, false,
              ActionKeys.VIEW)))) {
                
          if (user.isDefaultUser() &&
              PropsValues.AUTH_LOGIN_PROMPT_ENABLED) {
                
            throw new PrincipalException("User is not authenticated");
          }
                
          sb = new StringBundler(6);
                
          sb.append("User ");
          sb.append(user.getUserId());
          sb.append(" is not allowed to access the ");
          sb.append(layout.isPrivateLayout() ? "private" : "public");
          sb.append(" pages of group ");
          sb.append(layout.getGroupId());
                
          if (_log.isWarnEnabled()) {
            _log.warn(sb.toString());
          }
                
          throw new NoSuchLayoutException(sb.toString());
        } else*/ if (isLoginRequest(request) && !viewableGroup) {
            layout = null;
        } else if (group.isLayoutPrototype()) {
            layouts = new ArrayList<Layout>();
        } else {
            layouts = LayoutLocalServiceUtil.getLayouts(layout.getGroupId(), layout.isPrivateLayout(),
                    LayoutConstants.DEFAULT_PARENT_LAYOUT_ID);

            if (!group.isControlPanel()) {
                doAsGroupId = 0;
            }
        }
    }

    List<Layout> unfilteredLayouts = layouts;

    if (layout == null) {
        Object[] defaultLayout = getDefaultLayout(request, user, signedIn);

        layout = (Layout) defaultLayout[0];
        layouts = (List<Layout>) defaultLayout[1];

        request.setAttribute(WebKeys.LAYOUT_DEFAULT, Boolean.TRUE);
    }

    Object[] viewableLayouts = getViewableLayouts(request, user, permissionChecker, layout, layouts);

    String layoutSetLogo = null;

    layout = (Layout) viewableLayouts[0];
    layouts = (List<Layout>) viewableLayouts[1];

    Group group = null;

    if (layout != null) {
        group = layout.getGroup();

        if (!group.isControlPanel()) {
            rememberVisitedGroupIds(request, group.getGroupId());
        }
    }

    LayoutTypePortlet layoutTypePortlet = null;

    layouts = mergeAdditionalLayouts(request, user, permissionChecker, layout, layouts);

    LayoutSet layoutSet = null;

    boolean hasCustomizeLayoutPermission = false;
    boolean hasUpdateLayoutPermission = false;

    boolean customizedView = SessionParamUtil.getBoolean(request, "customized_view", true);

    if (layout != null) {
        hasCustomizeLayoutPermission = LayoutPermissionUtil.contains(permissionChecker, layout,
                ActionKeys.CUSTOMIZE);
        hasUpdateLayoutPermission = LayoutPermissionUtil.contains(permissionChecker, layout, ActionKeys.UPDATE);

        layoutSet = layout.getLayoutSet();

        if (company.isSiteLogo()) {
            long logoId = 0;

            if (layoutSet.isLogo()) {
                logoId = layoutSet.getLogoId();

                if (logoId == 0) {
                    logoId = layoutSet.getLiveLogoId();
                }
            } else {
                LayoutSet siblingLayoutSet = LayoutSetLocalServiceUtil.getLayoutSet(layout.getGroupId(),
                        !layout.isPrivateLayout());

                if (siblingLayoutSet.isLogo()) {
                    logoId = siblingLayoutSet.getLogoId();
                }
            }

            if (logoId > 0) {
                sb = new StringBundler(5);

                sb.append(imagePath);
                sb.append("/layout_set_logo?img_id=");
                sb.append(logoId);
                sb.append("&t=");
                sb.append(WebServerServletTokenUtil.getToken(logoId));

                layoutSetLogo = sb.toString();

                Image layoutSetLogoImage = ImageLocalServiceUtil.getCompanyLogo(logoId);

                companyLogo = layoutSetLogo;
                companyLogoHeight = layoutSetLogoImage.getHeight();
                companyLogoWidth = layoutSetLogoImage.getWidth();
            }
        }

        plid = layout.getPlid();

        // Updates to shared layouts are not reflected until the next time
        // the user logs in because group layouts are cached in the session

        layout = (Layout) layout.clone();

        layoutTypePortlet = (LayoutTypePortlet) layout.getLayoutType();

        boolean customizable = layoutTypePortlet.isCustomizable();

        if (!customizable || (group.isLayoutPrototype() || group.isLayoutSetPrototype())) {

            customizedView = false;
        }

        layoutTypePortlet.setCustomizedView(customizedView);
        layoutTypePortlet.setUpdatePermission(hasUpdateLayoutPermission);

        if (signedIn && customizable && customizedView && hasCustomizeLayoutPermission) {

            PortalPreferences portalPreferences = PortletPreferencesFactoryUtil.getPortalPreferences(companyId,
                    user.getUserId(), true);

            layoutTypePortlet.setPortalPreferences(portalPreferences);
        }

        LayoutClone layoutClone = LayoutCloneFactory.getInstance();

        if (layoutClone != null) {
            String typeSettings = layoutClone.get(request, plid);

            if (typeSettings != null) {
                UnicodeProperties typeSettingsProperties = new UnicodeProperties(true);

                typeSettingsProperties.load(typeSettings);

                String stateMax = typeSettingsProperties.getProperty(LayoutTypePortletConstants.STATE_MAX);
                String stateMin = typeSettingsProperties.getProperty(LayoutTypePortletConstants.STATE_MIN);
                String modeAbout = typeSettingsProperties.getProperty(LayoutTypePortletConstants.MODE_ABOUT);
                String modeConfig = typeSettingsProperties.getProperty(LayoutTypePortletConstants.MODE_CONFIG);
                String modeEdit = typeSettingsProperties.getProperty(LayoutTypePortletConstants.MODE_EDIT);
                String modeEditDefaults = typeSettingsProperties
                        .getProperty(LayoutTypePortletConstants.MODE_EDIT_DEFAULTS);
                String modeEditGuest = typeSettingsProperties
                        .getProperty(LayoutTypePortletConstants.MODE_EDIT_GUEST);
                String modeHelp = typeSettingsProperties.getProperty(LayoutTypePortletConstants.MODE_HELP);
                String modePreview = typeSettingsProperties
                        .getProperty(LayoutTypePortletConstants.MODE_PREVIEW);
                String modePrint = typeSettingsProperties.getProperty(LayoutTypePortletConstants.MODE_PRINT);

                layoutTypePortlet.setStateMax(stateMax);
                layoutTypePortlet.setStateMin(stateMin);
                layoutTypePortlet.setModeAbout(modeAbout);
                layoutTypePortlet.setModeConfig(modeConfig);
                layoutTypePortlet.setModeEdit(modeEdit);
                layoutTypePortlet.setModeEditDefaults(modeEditDefaults);
                layoutTypePortlet.setModeEditGuest(modeEditGuest);
                layoutTypePortlet.setModeHelp(modeHelp);
                layoutTypePortlet.setModePreview(modePreview);
                layoutTypePortlet.setModePrint(modePrint);
            }
        }

        request.setAttribute(WebKeys.LAYOUT, layout);
        request.setAttribute(WebKeys.LAYOUTS, layouts);
    }

    // Scope

    long scopeGroupId = PortalUtil.getScopeGroupId(request);

    if ((scopeGroupId <= 0) && (doAsGroupId > 0)) {
        scopeGroupId = doAsGroupId;
    }

    long parentGroupId = PortalUtil.getParentGroupId(scopeGroupId);

    // Theme and color scheme

    Theme theme = null;
    ColorScheme colorScheme = null;

    boolean wapTheme = BrowserSnifferUtil.isWap(request);

    if ((layout != null) && group.isControlPanel()) {
        String themeId = PrefsPropsUtil.getString(companyId, PropsKeys.CONTROL_PANEL_LAYOUT_REGULAR_THEME_ID);
        String colorSchemeId = ColorSchemeImpl.getDefaultRegularColorSchemeId();

        theme = ThemeLocalServiceUtil.getTheme(companyId, themeId, wapTheme);
        colorScheme = ThemeLocalServiceUtil.getColorScheme(companyId, theme.getThemeId(), colorSchemeId,
                wapTheme);

        if (!wapTheme && theme.isWapTheme()) {
            theme = ThemeLocalServiceUtil.getTheme(companyId, PropsValues.CONTROL_PANEL_LAYOUT_REGULAR_THEME_ID,
                    false);
            colorScheme = ThemeLocalServiceUtil.getColorScheme(companyId, theme.getThemeId(), colorSchemeId,
                    false);
        }

        request.setAttribute(WebKeys.THEME, theme);
        request.setAttribute(WebKeys.COLOR_SCHEME, colorScheme);
    }

    boolean themeCssFastLoad = SessionParamUtil.getBoolean(request, "css_fast_load",
            PropsValues.THEME_CSS_FAST_LOAD);
    boolean themeImagesFastLoad = SessionParamUtil.getBoolean(request, "images_fast_load",
            PropsValues.THEME_IMAGES_FAST_LOAD);

    boolean themeJsBarebone = PropsValues.JAVASCRIPT_BAREBONE_ENABLED;

    if (themeJsBarebone) {
        if (signedIn) {
            themeJsBarebone = false;
        }
    }

    boolean themeJsFastLoad = SessionParamUtil.getBoolean(request, "js_fast_load",
            PropsValues.JAVASCRIPT_FAST_LOAD);

    String lifecycle = ParamUtil.getString(request, "p_p_lifecycle", "0");

    lifecycle = ParamUtil.getString(request, "p_t_lifecycle", lifecycle);

    boolean isolated = ParamUtil.getBoolean(request, "p_p_isolated");

    String facebookCanvasPageURL = (String) request.getAttribute(WebKeys.FACEBOOK_CANVAS_PAGE_URL);

    boolean widget = false;

    Boolean widgetObj = (Boolean) request.getAttribute(WebKeys.WIDGET);

    if (widgetObj != null) {
        widget = widgetObj.booleanValue();
    }

    ////////// Modification start //////////

    // Locale
    Locale locale = null;
    String[] languageIds = request.getParameterMap().get("languageId");
    if (languageIds != null && languageIds.length > 0 && StringUtils.isNotEmpty(languageIds[0])) {
        Locale localeFromLanguageId = LocaleUtil.fromLanguageId(languageIds[0]);
        session.setAttribute(Globals.LOCALE_KEY, localeFromLanguageId);
    }
    try {
        locale = (Locale) session.getAttribute(Globals.LOCALE_KEY);
    } catch (IllegalStateException e) {
        _log.warn("Can't get locale from session, session is invalidated");
    }
    if (Validator.isNotNull(doAsUserLanguageId)) {
        locale = LocaleUtil.fromLanguageId(doAsUserLanguageId);
    }

    String i18nLanguageId = (String) request.getAttribute(WebKeys.I18N_LANGUAGE_ID);
    if (Validator.isNotNull(i18nLanguageId)) {
        locale = LocaleUtil.fromLanguageId(i18nLanguageId);
    }

    if (locale == null) {
        locale = LanguageDetectionUtil.detectLocale(request);
    }

    ////////// Modification end //////////

    // Theme display

    ThemeDisplay themeDisplay = ThemeDisplayFactory.create();
    //Modification start
    //    themeDisplay.setHttpServletRequest(request);
    //Modification end

    // Set the CDN host, portal URL, and Facebook application ID first
    // because other methods (setLookAndFeel) depend on them being set

    themeDisplay.setCDNHost(cdnHost);
    themeDisplay.setCDNDynamicResourcesHost(dynamicResourcesCDNHost);
    themeDisplay.setPortalURL(portalURL);
    themeDisplay.setFacebookCanvasPageURL(facebookCanvasPageURL);
    themeDisplay.setWidget(widget);

    themeDisplay.setCompany(company);
    themeDisplay.setCompanyLogo(companyLogo);
    themeDisplay.setCompanyLogoHeight(companyLogoHeight);
    themeDisplay.setCompanyLogoWidth(companyLogoWidth);
    themeDisplay.setRealCompanyLogo(realCompanyLogo);
    themeDisplay.setRealCompanyLogoHeight(realCompanyLogoHeight);
    themeDisplay.setRealCompanyLogoWidth(realCompanyLogoWidth);
    themeDisplay.setUser(user);
    themeDisplay.setRealUser(realUser);
    themeDisplay.setDoAsUserId(doAsUserId);
    themeDisplay.setDoAsUserLanguageId(doAsUserLanguageId);
    themeDisplay.setDoAsGroupId(doAsGroupId);
    themeDisplay.setRefererPlid(refererPlid);
    themeDisplay.setControlPanelCategory(controlPanelCategory);
    themeDisplay.setLayoutSet(layoutSet);
    themeDisplay.setLayoutSetLogo(layoutSetLogo);
    themeDisplay.setLayout(layout);
    themeDisplay.setLayouts(layouts);
    themeDisplay.setUnfilteredLayouts(unfilteredLayouts);
    themeDisplay.setPlid(plid);
    themeDisplay.setLayoutTypePortlet(layoutTypePortlet);
    themeDisplay.setScopeGroupId(scopeGroupId);
    themeDisplay.setParentGroupId(parentGroupId);
    themeDisplay.setSignedIn(signedIn);
    themeDisplay.setPermissionChecker(permissionChecker);
    themeDisplay.setLocale(locale);
    themeDisplay.setLanguageId(LocaleUtil.toLanguageId(locale));
    themeDisplay.setI18nLanguageId(i18nLanguageId);
    themeDisplay.setI18nPath(i18nPath);
    themeDisplay.setTimeZone(timeZone);
    themeDisplay.setLookAndFeel(theme, colorScheme);
    themeDisplay.setThemeCssFastLoad(themeCssFastLoad);
    themeDisplay.setThemeImagesFastLoad(themeImagesFastLoad);
    themeDisplay.setThemeJsBarebone(themeJsBarebone);
    themeDisplay.setThemeJsFastLoad(themeJsFastLoad);
    themeDisplay.setServerName(request.getServerName());
    themeDisplay.setServerPort(request.getServerPort());
    themeDisplay.setSecure(request.isSecure());
    themeDisplay.setLifecycle(lifecycle);
    themeDisplay.setLifecycleAction(lifecycle.equals("1"));
    themeDisplay.setLifecycleRender(lifecycle.equals("0"));
    themeDisplay.setLifecycleResource(lifecycle.equals("2"));
    themeDisplay.setStateExclusive(LiferayWindowState.isExclusive(request));
    themeDisplay.setStateMaximized(LiferayWindowState.isMaximized(request));
    themeDisplay.setStatePopUp(LiferayWindowState.isPopUp(request));
    themeDisplay.setIsolated(isolated);
    themeDisplay.setPathApplet(contextPath.concat("/applets"));
    themeDisplay.setPathCms(contextPath.concat("/cms"));
    themeDisplay.setPathContext(contextPath);
    themeDisplay.setPathFlash(contextPath.concat("/flash"));
    themeDisplay.setPathFriendlyURLPrivateGroup(friendlyURLPrivateGroupPath);
    themeDisplay.setPathFriendlyURLPrivateUser(friendlyURLPrivateUserPath);
    themeDisplay.setPathFriendlyURLPublic(friendlyURLPublicPath);
    themeDisplay.setPathImage(imagePath);
    themeDisplay.setPathJavaScript(contextPath.concat("/html/js"));
    themeDisplay.setPathMain(mainPath);
    themeDisplay.setPathSound(contextPath.concat("/html/sound"));

    // Icons

    themeDisplay.setShowAddContentIcon(false);
    themeDisplay.setShowControlPanelIcon(signedIn);
    themeDisplay.setShowHomeIcon(true);
    themeDisplay.setShowMyAccountIcon(signedIn);
    themeDisplay.setShowPageSettingsIcon(false);
    themeDisplay.setShowPortalIcon(true);
    themeDisplay.setShowSignInIcon(!signedIn);
    themeDisplay.setShowSignOutIcon(signedIn);

    boolean showSiteContentIcon = false;

    long controlPanelPlid = 0;

    if (signedIn) {
        Group controlPanelGroup = GroupLocalServiceUtil.getGroup(companyId, GroupConstants.CONTROL_PANEL);

        controlPanelPlid = LayoutLocalServiceUtil.getDefaultPlid(controlPanelGroup.getGroupId(), true);

        List<Portlet> siteContentPortlets = PortalUtil.getControlPanelPortlets(PortletCategoryKeys.CONTENT,
                themeDisplay);

        Portlet groupPagesPortlet = PortletLocalServiceUtil.getPortletById(PortletKeys.GROUP_PAGES);

        siteContentPortlets.remove(groupPagesPortlet);

        Portlet siteMembershipsAdminPortlet = PortletLocalServiceUtil
                .getPortletById(PortletKeys.SITE_MEMBERSHIPS_ADMIN);

        siteContentPortlets.remove(siteMembershipsAdminPortlet);

        Portlet siteSettingsPortlet = PortletLocalServiceUtil.getPortletById(PortletKeys.SITE_SETTINGS);

        siteContentPortlets.remove(siteSettingsPortlet);

        showSiteContentIcon = PortletPermissionUtil.contains(permissionChecker, scopeGroupId, controlPanelPlid,
                siteContentPortlets, ActionKeys.VIEW);
    }

    themeDisplay.setShowSiteContentIcon(showSiteContentIcon);

    themeDisplay.setShowStagingIcon(false);

    // Session

    if (PropsValues.SESSION_ENABLE_URL_WITH_SESSION_ID && !CookieKeys.hasSessionId(request)) {

        themeDisplay.setAddSessionIdToURL(true);
        themeDisplay.setSessionId(session.getId());
    }

    // URLs

    String urlControlPanel = friendlyURLPrivateGroupPath.concat(GroupConstants.CONTROL_PANEL_FRIENDLY_URL);

    if (Validator.isNotNull(doAsUserId)) {
        urlControlPanel = HttpUtil.addParameter(urlControlPanel, "doAsUserId", doAsUserId);
    }

    if (scopeGroupId > 0) {
        urlControlPanel = HttpUtil.addParameter(urlControlPanel, "doAsGroupId", scopeGroupId);
    }

    if (refererPlid > 0) {
        urlControlPanel = HttpUtil.addParameter(urlControlPanel, "refererPlid", refererPlid);
    } else if (plid > 0) {
        urlControlPanel = HttpUtil.addParameter(urlControlPanel, "refererPlid", plid);
    }

    if (themeDisplay.isAddSessionIdToURL()) {
        urlControlPanel = PortalUtil.getURLWithSessionId(urlControlPanel, session.getId());
    }

    themeDisplay.setURLControlPanel(urlControlPanel);

    String siteContentURL = urlControlPanel;

    siteContentURL = HttpUtil.addParameter(siteContentURL, "controlPanelCategory", PortletCategoryKeys.CONTENT);

    themeDisplay.setURLSiteContent(siteContentURL);

    String currentURL = PortalUtil.getCurrentURL(request);

    themeDisplay.setURLCurrent(currentURL);

    String urlHome = PortalUtil.getHomeURL(request);

    themeDisplay.setURLHome(urlHome);

    if (layout != null) {
        if (layout.isTypePortlet()) {
            boolean freeformLayout = layoutTypePortlet.getLayoutTemplateId().equals("freeform");

            themeDisplay.setFreeformLayout(freeformLayout);

            if (hasUpdateLayoutPermission) {
                themeDisplay.setShowAddContentIconPermission(true);

                if (!LiferayWindowState.isMaximized(request)) {
                    themeDisplay.setShowAddContentIcon(true);
                }

                themeDisplay.setShowLayoutTemplatesIcon(true);

                if (!group.isUser()) {
                    themeDisplay.setShowPageCustomizationIcon(true);
                }

                themeDisplay.setURLAddContent("Liferay.LayoutConfiguration.toggle('"
                        .concat(PortletKeys.LAYOUT_CONFIGURATION).concat("');"));

                themeDisplay.setURLLayoutTemplates("Liferay.LayoutConfiguration.showTemplates();");
            }

            if (hasCustomizeLayoutPermission && customizedView) {
                themeDisplay.setShowAddContentIconPermission(true);

                if (!LiferayWindowState.isMaximized(request)) {
                    themeDisplay.setShowAddContentIcon(true);
                }

                themeDisplay.setURLAddContent("Liferay.LayoutConfiguration.toggle('"
                        .concat(PortletKeys.LAYOUT_CONFIGURATION).concat("');"));
            }
        }

        if (hasUpdateLayoutPermission) {
            themeDisplay.setShowPageSettingsIcon(true);

            LiferayPortletURL pageSettingsURL = new PortletURLImpl(request, PortletKeys.LAYOUTS_ADMIN,
                    controlPanelPlid, PortletRequest.RENDER_PHASE);

            pageSettingsURL.setControlPanelCategory(
                    _CONTROL_PANEL_CATEGORY_PORTLET_PREFIX + PortletKeys.LAYOUTS_ADMIN);
            pageSettingsURL.setDoAsGroupId(scopeGroupId);
            pageSettingsURL.setParameter("struts_action", "/layouts_admin/edit_layouts");

            if (layout.isPrivateLayout()) {
                pageSettingsURL.setParameter("tabs1", "private-pages");
            } else {
                pageSettingsURL.setParameter("tabs1", "public-pages");
            }

            pageSettingsURL.setParameter("closeRedirect", currentURL);
            pageSettingsURL.setParameter("groupId", String.valueOf(scopeGroupId));
            pageSettingsURL.setParameter("selPlid", String.valueOf(plid));
            pageSettingsURL.setPortletMode(PortletMode.VIEW);
            pageSettingsURL.setWindowState(LiferayWindowState.POP_UP);

            themeDisplay.setURLPageSettings(pageSettingsURL);

            boolean site = group.isSite();

            if (!site && group.isStagingGroup()) {
                Group liveGroup = group.getLiveGroup();

                site = liveGroup.isSite();
            }

            if (site && GroupPermissionUtil.contains(permissionChecker, scopeGroupId,
                    ActionKeys.ASSIGN_MEMBERS)) {

                themeDisplay.setShowManageSiteMembershipsIcon(true);

                LiferayPortletURL manageSiteMembershipsURL = new PortletURLImpl(request,
                        PortletKeys.SITE_MEMBERSHIPS_ADMIN, controlPanelPlid, PortletRequest.RENDER_PHASE);

                manageSiteMembershipsURL.setControlPanelCategory(
                        _CONTROL_PANEL_CATEGORY_PORTLET_PREFIX + PortletKeys.SITE_MEMBERSHIPS_ADMIN);
                manageSiteMembershipsURL.setDoAsGroupId(scopeGroupId);
                manageSiteMembershipsURL.setParameter("struts_action", "/sites_admin/edit_site_assignments");
                manageSiteMembershipsURL.setParameter("groupId", String.valueOf(scopeGroupId));
                manageSiteMembershipsURL.setParameter("selPlid", String.valueOf(plid));
                manageSiteMembershipsURL.setPortletMode(PortletMode.VIEW);
                manageSiteMembershipsURL.setWindowState(LiferayWindowState.POP_UP);

                themeDisplay.setURLManageSiteMemberships(manageSiteMembershipsURL);
            } else {
                themeDisplay.setShowManageSiteMembershipsIcon(false);
            }
        }

        boolean hasAddLayoutGroupPermission = GroupPermissionUtil.contains(permissionChecker, scopeGroupId,
                ActionKeys.ADD_LAYOUT);
        boolean hasAddLayoutLayoutPermission = LayoutPermissionUtil.contains(permissionChecker, layout,
                ActionKeys.ADD_LAYOUT);
        boolean hasManageLayoutsGroupPermission = GroupPermissionUtil.contains(permissionChecker, scopeGroupId,
                ActionKeys.MANAGE_LAYOUTS);
        boolean hasManageStagingPermission = GroupPermissionUtil.contains(permissionChecker, scopeGroupId,
                ActionKeys.MANAGE_STAGING);
        boolean hasPublishStagingPermission = GroupPermissionUtil.contains(permissionChecker, scopeGroupId,
                ActionKeys.PUBLISH_STAGING);
        boolean hasUpdateGroupPermission = GroupPermissionUtil.contains(permissionChecker, scopeGroupId,
                ActionKeys.UPDATE);
        boolean hasViewStagingPermission = GroupPermissionUtil.contains(permissionChecker, scopeGroupId,
                ActionKeys.VIEW_STAGING);

        if (!group.isControlPanel() && !group.isUser() && !group.isUserGroup() && hasUpdateGroupPermission) {

            themeDisplay.setShowSiteSettingsIcon(true);

            LiferayPortletURL siteSettingsURL = new PortletURLImpl(request, PortletKeys.SITE_SETTINGS,
                    controlPanelPlid, PortletRequest.RENDER_PHASE);

            siteSettingsURL.setControlPanelCategory(
                    _CONTROL_PANEL_CATEGORY_PORTLET_PREFIX + PortletKeys.SITE_SETTINGS);
            siteSettingsURL.setDoAsGroupId(scopeGroupId);
            siteSettingsURL.setParameter("struts_action", "/sites_admin/edit_site");
            siteSettingsURL.setParameter("closeRedirect", currentURL);
            siteSettingsURL.setParameter("groupId", String.valueOf(scopeGroupId));
            siteSettingsURL.setPortletMode(PortletMode.VIEW);
            siteSettingsURL.setWindowState(LiferayWindowState.POP_UP);

            themeDisplay.setURLSiteSettings(siteSettingsURL);
        }

        if (!group.isLayoutPrototype() && (hasAddLayoutGroupPermission || hasAddLayoutLayoutPermission
                || hasManageLayoutsGroupPermission || hasUpdateGroupPermission)) {

            themeDisplay.setShowSiteMapSettingsIcon(true);

            LiferayPortletURL siteMapSettingsURL = new PortletURLImpl(request, PortletKeys.LAYOUTS_ADMIN,
                    controlPanelPlid, PortletRequest.RENDER_PHASE);

            siteMapSettingsURL.setControlPanelCategory(
                    _CONTROL_PANEL_CATEGORY_PORTLET_PREFIX + PortletKeys.LAYOUTS_ADMIN);
            siteMapSettingsURL.setDoAsGroupId(scopeGroupId);
            siteMapSettingsURL.setParameter("struts_action", "/layouts_admin/edit_layouts");

            if (layout.isPrivateLayout()) {
                siteMapSettingsURL.setParameter("tabs1", "private-pages");
            } else {
                siteMapSettingsURL.setParameter("tabs1", "public-pages");
            }

            siteMapSettingsURL.setParameter("closeRedirect", currentURL);
            siteMapSettingsURL.setParameter("groupId", String.valueOf(scopeGroupId));
            siteMapSettingsURL.setPortletMode(PortletMode.VIEW);
            siteMapSettingsURL.setWindowState(LiferayWindowState.POP_UP);

            themeDisplay.setURLSiteMapSettings(siteMapSettingsURL);
        }

        if (group.hasStagingGroup() && !group.isStagingGroup()) {
            themeDisplay.setShowAddContentIcon(false);
            themeDisplay.setShowLayoutTemplatesIcon(false);
            themeDisplay.setShowPageSettingsIcon(false);
            themeDisplay.setURLPublishToLive(null);
        }

        if (group.isControlPanel()) {
            themeDisplay.setShowPageSettingsIcon(false);
            themeDisplay.setURLPublishToLive(null);
        }

        // LEP-4987

        if (group.isStaged() || group.isStagingGroup()) {
            if (hasManageStagingPermission || hasPublishStagingPermission || hasUpdateLayoutPermission
                    || hasViewStagingPermission) {

                themeDisplay.setShowStagingIcon(true);
            }

            if (hasPublishStagingPermission) {
                PortletURL publishToLiveURL = new PortletURLImpl(request, PortletKeys.LAYOUTS_ADMIN, plid,
                        PortletRequest.RENDER_PHASE);

                publishToLiveURL.setParameter("struts_action", "/layouts_admin/publish_layouts");

                if (layout.isPrivateLayout()) {
                    publishToLiveURL.setParameter("tabs1", "private-pages");
                } else {
                    publishToLiveURL.setParameter("tabs1", "public-pages");
                }

                publishToLiveURL.setParameter("pagesRedirect", currentURL);
                publishToLiveURL.setParameter("groupId", String.valueOf(scopeGroupId));
                publishToLiveURL.setParameter("selPlid", String.valueOf(plid));
                publishToLiveURL.setPortletMode(PortletMode.VIEW);
                publishToLiveURL.setWindowState(LiferayWindowState.EXCLUSIVE);

                themeDisplay.setURLPublishToLive(publishToLiveURL);
            }
        }

        PortletURLImpl myAccountURL = new PortletURLImpl(request, PortletKeys.MY_ACCOUNT, controlPanelPlid,
                PortletRequest.RENDER_PHASE);

        if (scopeGroupId > 0) {
            myAccountURL.setDoAsGroupId(scopeGroupId);
        }

        myAccountURL.setParameter("struts_action", "/my_account/edit_user");
        myAccountURL.setPortletMode(PortletMode.VIEW);

        if (refererPlid > 0) {
            myAccountURL.setRefererPlid(refererPlid);
        } else {
            myAccountURL.setRefererPlid(plid);
        }

        myAccountURL.setWindowState(WindowState.MAXIMIZED);

        themeDisplay.setURLMyAccount(myAccountURL);
    }

    if (!user.isActive() || (PrefsPropsUtil.getBoolean(companyId, PropsKeys.TERMS_OF_USE_REQUIRED)
            && !user.isAgreedToTermsOfUse())) {

        themeDisplay.setShowAddContentIcon(false);
        themeDisplay.setShowMyAccountIcon(false);
        themeDisplay.setShowPageSettingsIcon(false);
    }

    if (layout.isLayoutPrototypeLinkActive()) {
        themeDisplay.setShowPageCustomizationIcon(false);
    }

    if (group.isLayoutPrototype()) {
        themeDisplay.setShowControlPanelIcon(false);
        themeDisplay.setShowHomeIcon(false);
        themeDisplay.setShowManageSiteMembershipsIcon(false);
        themeDisplay.setShowMyAccountIcon(false);
        themeDisplay.setShowPageCustomizationIcon(false);
        themeDisplay.setShowPageSettingsIcon(true);
        themeDisplay.setShowPortalIcon(false);
        themeDisplay.setShowSignInIcon(false);
        themeDisplay.setShowSignOutIcon(false);
        themeDisplay.setShowSiteContentIcon(false);
        themeDisplay.setShowSiteSettingsIcon(false);
        themeDisplay.setShowStagingIcon(false);
    }

    if (group.isLayoutSetPrototype()) {
        themeDisplay.setShowPageCustomizationIcon(false);
        themeDisplay.setShowSiteSettingsIcon(false);
    }

    if (group.hasStagingGroup() && !group.isStagingGroup()) {
        themeDisplay.setShowLayoutTemplatesIcon(false);
        themeDisplay.setShowPageCustomizationIcon(false);
        themeDisplay.setShowPageSettingsIcon(false);
        themeDisplay.setShowSiteContentIcon(false);
        themeDisplay.setShowSiteMapSettingsIcon(false);
        themeDisplay.setShowSiteSettingsIcon(false);
    }

    themeDisplay.setURLPortal(portalURL.concat(contextPath));

    String urlSignIn = mainPath.concat("/portal/login");

    urlSignIn = HttpUtil.addParameter(urlSignIn, "p_l_id", layout.getPlid());

    themeDisplay.setURLSignIn(urlSignIn);

    themeDisplay.setURLSignOut(mainPath.concat("/portal/logout"));

    PortletURL updateManagerURL = new PortletURLImpl(request, PortletKeys.UPDATE_MANAGER, plid,
            PortletRequest.RENDER_PHASE);

    updateManagerURL.setParameter("struts_action", "/update_manager/view");
    updateManagerURL.setPortletMode(PortletMode.VIEW);
    updateManagerURL.setWindowState(WindowState.MAXIMIZED);

    themeDisplay.setURLUpdateManager(updateManagerURL);

    return themeDisplay;
}