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.josso.wls92.agent.WLSSessionEnforcementServletFilter.java

public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
        throws IOException, ServletException {

    HttpServletRequest hreq = (HttpServletRequest) request;

    HttpServletResponse hres = (HttpServletResponse) response;

    HttpSession session = hreq.getSession(true);

    if (log.isDebugEnabled())
        log.debug("Processing : " + hreq.getContextPath());

    String contextPath = hreq.getContextPath();
    String vhost = hreq.getServerName();
    SSOPartnerAppConfig cfg = _agent.getPartnerAppConfig(vhost, contextPath);

    // ------------------------------------------------------------------
    // Check for the single sign on cookie
    // ------------------------------------------------------------------
    if (log.isDebugEnabled())
        log.debug("Checking for SSO cookie");
    Cookie cookie = null;//from ww  w .  j  a  va  2 s.  co  m
    Cookie cookies[] = hreq.getCookies();
    if (cookies == null)
        cookies = new Cookie[0];
    for (int i = 0; i < cookies.length; i++) {
        if (org.josso.gateway.Constants.JOSSO_SINGLE_SIGN_ON_COOKIE.equals(cookies[i].getName())) {
            cookie = cookies[i];
            break;
        }
    }
    if (cookie != null && !cookie.getValue().equals("-")) {

        String jossoSessionId = cookie.getValue();

        if (log.isDebugEnabled())
            log.debug("asserting SSO session for : " + jossoSessionId);

        SSOAgentRequest sessionAssertionRequest;

        sessionAssertionRequest = doMakeSSOAgentRequest(cfg.getId(), SSOAgentRequest.ACTION_ASSERT_SESSION,
                jossoSessionId, null, null, hreq, hres);

        // TODO: Agents should be able to pass back responses corresponding to the submitted request.
        try {
            _agent.processRequest(sessionAssertionRequest);
            if (log.isDebugEnabled())
                log.debug("asserted successfully SSO session for : " + jossoSessionId);
        } catch (FatalSSOSessionException e) {
            if (log.isDebugEnabled())
                log.debug("error asserting SSO session : " + jossoSessionId);

            String requestedResourceUrl;

            // Clear previous COOKIE ...
            Cookie ssoCookie = _agent.newJossoCookie(hreq.getContextPath(), "-", hreq.isSecure());
            hres.addCookie(ssoCookie);
            session.invalidate();
            requestedResourceUrl = _agent.buildBackToURL(hreq, "");
            hres.sendRedirect(hres.encodeRedirectURL(requestedResourceUrl));
            return;
        }

    }

    filterChain.doFilter(hreq, hres);

}

From source file:org.dspace.authenticate.ShibAuthentication.java

/**
 * Get login page to which to redirect. Returns URL (as string) to which to
 * redirect to obtain credentials (either password prompt or e.g. HTTPS port
 * for client cert.); null means no redirect.
 * //from   w  w w  . j  a v a  2s .  c  om
 * @param context
 *            DSpace context, will be modified (ePerson set) upon success.
 * 
 * @param request
 *            The HTTP request that started this operation, or null if not
 *            applicable.
 * 
 * @param response
 *            The HTTP response from the servlet method.
 * 
 * @return fully-qualified URL or null
 */
@Override
public String loginPageURL(Context context, HttpServletRequest request, HttpServletResponse response) {
    // If this server is configured for lazy sessions then use this to
    // login, otherwise default to the protected shibboleth url.

    boolean lazySession = configurationService.getBooleanProperty("authentication-shibboleth.lazysession",
            false);

    if (lazySession) {
        String shibURL = configurationService.getProperty("authentication-shibboleth.lazysession.loginurl");
        boolean forceHTTPS = configurationService
                .getBooleanProperty("authentication-shibboleth.lazysession.secure", true);

        // Shibboleth authentication initiator 
        if (shibURL == null || shibURL.length() == 0)
            shibURL = "/Shibboleth.sso/Login";
        shibURL = shibURL.trim();

        // Determine the return URL, where shib will send the user after authenticating. We need it to go back
        // to DSpace's shibboleth-login url so the we will extract the user's information and locally
        // authenticate them.
        String host = request.getServerName();
        int port = request.getServerPort();
        String contextPath = request.getContextPath();

        String returnURL;
        if (request.isSecure() || forceHTTPS)
            returnURL = "https://";
        else
            returnURL = "http://";

        returnURL += host;
        if (!(port == 443 || port == 80))
            returnURL += ":" + port;
        returnURL += "/" + contextPath + "/shibboleth-login";

        try {
            shibURL += "?target=" + URLEncoder.encode(returnURL, "UTF-8");
        } catch (UnsupportedEncodingException uee) {
            log.error("Unable to generate lazysession authentication", uee);
        }

        log.debug("Redirecting user to Shibboleth initiator: " + shibURL);

        return response.encodeRedirectURL(shibURL);
    } else {
        // If we are not using lazy sessions rely on the protected URL.
        return response.encodeRedirectURL(request.getContextPath() + "/shibboleth-login");
    }
}

From source file:net.nan21.dnet.core.web.controller.ui.extjs.AbstractUiExtjsController.java

protected void _prepare(Map<String, Object> model, HttpServletRequest request, HttpServletResponse response)
        throws Exception {

    request.setCharacterEncoding("UTF-8");
    response.setCharacterEncoding("UTF-8");

    if (logger.isInfoEnabled()) {
        logger.info("Handling request for ui.extjs: ", request.getPathInfo());
    }/*  w  ww.  j av a2 s.  c  o m*/

    String server = request.getServerName();
    int port = request.getServerPort();
    // String contextPath = request.getContextPath();
    // String path = request.getServletPath();

    String userRolesStr = null;

    try {
        ISessionUser su = (ISessionUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        IUser user = su.getUser();

        IUserSettings prefs = user.getSettings();

        Session.user.set(user);

        model.put("constantsJsFragment", this.getConstantsJsFragment());
        model.put("user", user);

        DateFormatAttribute[] masks = DateFormatAttribute.values();
        Map<String, String> dateFormatMasks = new HashMap<String, String>();
        for (int i = 0, len = masks.length; i < len; i++) {
            DateFormatAttribute mask = masks[i];
            if (mask.isForJs()) {
                dateFormatMasks.put(mask.name().replace("EXTJS_", ""), prefs.getDateFormat(mask.name()));
            }
        }

        model.put("dateFormatMasks", dateFormatMasks);

        model.put("modelDateFormat", this.getSettings().get(Constants.PROP_EXTJS_MODEL_DATE_FORMAT));

        model.put("decimalSeparator", prefs.getDecimalSeparator());
        model.put("thousandSeparator", prefs.getThousandSeparator());

        StringBuffer sb = new StringBuffer();
        int i = 0;
        for (String role : user.getProfile().getRoles()) {
            if (i > 0) {
                sb.append(",");
            }
            sb.append("\"" + role + "\"");
            i++;
        }
        userRolesStr = sb.toString();

    } catch (ClassCastException e) {
        // not authenticated
    }
    String hostUrl = ((request.isSecure()) ? "https" : "http") + "://" + server
            + ((port != 80) ? (":" + port) : "");// + contextPath;

    model.put("productName", this.getSettings().getProductName());
    model.put("productVersion", this.getSettings().getProductVersion());
    model.put("hostUrl", hostUrl);

    // themes
    model.put("urlUiExtjsThemes", getUiExtjsSettings().getUrlThemes());

    // DNet extjs components in core and modules
    model.put("urlUiExtjsCore", getUiExtjsSettings().getUrlCore());
    model.put("urlUiExtjsModules", getUiExtjsSettings().getUrlModules());
    model.put("urlUiExtjsModuleSubpath", getUiExtjsSettings().getModuleSupath());

    // translations for core and modules
    model.put("urlUiExtjsCoreI18n", getUiExtjsSettings().getUrlCoreI18n());
    model.put("urlUiExtjsModulesI18n", getUiExtjsSettings().getUrlModulesI18n());

    model.put("shortLanguage", this.resolveLang(request, response));
    model.put("theme", this.resolveTheme(request, response));
    model.put("sysCfg_workingMode", this.getSettings().get(Constants.PROP_WORKING_MODE));

    model.put("userRolesStr", userRolesStr);

}

From source file:ru.org.linux.topic.TopicListController.java

private ModelAndView mainTopicsFeedHandler(HttpServletRequest request, TopicListRequest topicListForm,
        HttpServletResponse response, @Nullable Group group) throws Exception {
    Section section = null;//from  w w  w  . ja  va  2s . c  o  m
    if (topicListForm.getSection() != null && topicListForm.getSection() != 0) {
        section = sectionService.getSection(topicListForm.getSection());
    }

    checkRequestConditions(section, group, topicListForm);
    Template tmpl = Template.getTemplate(request);

    ModelAndView modelAndView = new ModelAndView("view-news");

    modelAndView.addObject("group", group);

    if (!Strings.isNullOrEmpty(topicListForm.getTag()) || topicListForm.getSection() != null) {
        URLUtil.QueryString queryString = new URLUtil.QueryString();
        queryString.add("section", topicListForm.getSection());
        modelAndView.addObject("params", queryString.toString());
    }

    modelAndView.addObject("url", "view-news.jsp");
    if (section != null) {
        modelAndView.addObject("section", section);

        if (Strings.isNullOrEmpty(topicListForm.getTag())) {
            modelAndView.addObject("archiveLink", section.getArchiveLink());
        }
    }

    setExpireHeaders(response, topicListForm);

    modelAndView.addObject("ptitle", calculatePTitle(section, group, topicListForm));
    modelAndView.addObject("navtitle", calculateNavTitle(section, group, topicListForm));

    topicListForm.setOffset(topicListService.fixOffset(topicListForm.getOffset()));

    List<Topic> messages = topicListService.getTopicsFeed(section, group, topicListForm.getTag(),
            topicListForm.getOffset(), topicListForm.getYear(), topicListForm.getMonth());

    modelAndView.addObject("messages", prepareService.prepareMessagesForUser(messages, request.isSecure(),
            tmpl.getCurrentUser(), tmpl.getProf(), false));

    modelAndView.addObject("offsetNavigation", topicListForm.getMonth() == null);

    if (section != null && Strings.isNullOrEmpty(topicListForm.getTag())) {
        String rssLink = "/section-rss.jsp?section=" + section.getId();
        if (group != null) {
            rssLink += "&group=" + group.getId();
        }

        modelAndView.addObject("rssLink", rssLink);
    }

    return modelAndView;
}

From source file:org.metis.pull.WdsResourceBean.java

/**
 * This method gets called by the WdsRdbMapper bean to handle a HTTP
 * request. This method must be multi-thread capable. Note that since we're
 * not using Views, this method must return null.
 * /*from ww w .ja va2  s .c om*/
 * @param request
 *            the http request that is being serviced
 * @param response
 *            the response that will be sent back to the service consumer
 * @return must return null since we're not using a view
 * @throws Exception
 */
@SuppressWarnings("unchecked")
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
        throws Exception {

    LOG.debug(getBeanName() + ": handleRequestInternal - **** new request ****");

    // dump the request if trace is on
    if (LOG.isTraceEnabled()) {
        LOG.trace(getBeanName() + ":handleRequestInternal - method = " + request.getMethod());
        LOG.trace(getBeanName() + ":handleRequestInternal - uri  = " + request.getRequestURI());
        LOG.trace(getBeanName() + ":handleRequestInternal - protocol  = " + request.getProtocol());
        LOG.trace(getBeanName() + ":handleRequestInternal - secure  = " + request.isSecure());

        // dump all the http headers and their values
        Enumeration<String> headerNames = request.getHeaderNames();
        if (headerNames != null) {
            while (headerNames.hasMoreElements()) {
                String headerName = headerNames.nextElement();
                LOG.trace(getBeanName() + ":handleRequestInternal - " + headerName + " = "
                        + request.getHeader(headerName));
            }
        }

        if (request.getQueryString() != null) {
            LOG.trace(getBeanName() + ":handleRequestInternal - queryString  = " + request.getQueryString());
        }
    }

    long currentTime = System.currentTimeMillis();

    // give the response a Date header with the current time
    response.setDateHeader(DATE_HDR, currentTime);

    // assign the Server header this container's info
    response.setHeader(SERVER_HDR, getServerInfo());

    // determine the HTTP protocol version being used by the client
    // default version will be 0
    int protocolVersion = 0;
    try {
        protocolVersion = Integer
                .parseInt(request.getProtocol().split(FORWARD_SLASH_STR)[1].split(ESC_DOT_STR)[1]);
    } catch (Exception exc) {
        LOG.warn(getBeanName() + ": handleRequestInternal - unable to get http protocol "
                + "version, stack trace follows: ");
        LOG.error(getBeanName() + ": exception stack trace follows:");
        dumpStackTrace(exc.getStackTrace());
    }

    LOG.trace(getBeanName() + ":handleRequestInternal - using this " + "protocol version: " + protocolVersion);

    /*
     * Ok, the request first needs to run the security gauntlet
     * 
     * We do not want to send any error messages back to the client that
     * would give it a hint that we're invoking SQL statements. This is a
     * countermeasure for SQL injection probes.
     */

    // see if this RDB is restricting user agents and if so, validate user
    // agent
    if ((getAllowedAgents() != null && !getAllowedAgents().isEmpty())
            || (getNotAllowedAgents() != null && !getNotAllowedAgents().isEmpty())) {

        String userAgent = request.getHeader(USER_AGENT_HDR);

        if (userAgent != null && userAgent.length() > 0) {
            LOG.debug(
                    getBeanName() + ": handleRequestInternal - validating this " + "user agent: " + userAgent);

            // Convert to lower case as allowed agents have been
            // converted to lower case as well
            userAgent = userAgent.toLowerCase();

            boolean allow = false;
            if (getAllowedAgents() != null && !getAllowedAgents().isEmpty()) {
                for (String agent : getAllowedAgents()) {
                    LOG.trace(getBeanName() + ": handleRequestInternal - comparing to this "
                            + "allowed agent : " + agent);
                    if (userAgent.indexOf(agent) >= 0) {
                        LOG.trace(getBeanName() + ": handleRequestInternal - this allowed agent "
                                + "was found: " + agent);
                        allow = true;
                        break;
                    }
                }
            } else {
                allow = true;
                for (String agent : getNotAllowedAgents()) {
                    LOG.trace(getBeanName() + ": handleRequestInternal - comparing to this "
                            + "non-allowed agent : " + agent);
                    if (userAgent.indexOf(agent) >= 0) {
                        LOG.trace(getBeanName() + ": handleRequestInternal - this non-allowed "
                                + "agent was found: " + agent);
                        allow = false;
                        break;
                    }
                }
            }
            if (!allow) {
                response.sendError(SC_UNAUTHORIZED, "ERROR, user agent " + "is not authorized");
                LOG.error(getBeanName() + ": handleRequestInternal - ERROR, user agent is " + "not authorized");
                return null;
            }
        } else {
            response.sendError(SC_UNAUTHORIZED,
                    "ERROR, user agent info " + "was not received and is required!");
            LOG.error(getBeanName() + ": handleRequestInternal - ERROR, user agent header "
                    + "is required but was not provided by the client");
            return null;
        }
    }

    // we do not support chunked transfer encoding, which is a http
    // 1.1 feature.
    if (request.getHeader(TRANSFER_ENCODING_HDR) != null
            && request.getHeader(TRANSFER_ENCODING_HDR).equalsIgnoreCase(CHUNKED)) {
        response.sendError(SC_BAD_REQUEST, "Chunked tranfer encoding is not " + "supported");
        return null;
    }

    /*
     * isSecure returns a boolean indicating whether this request was made
     * using a secure channel, such as HTTPS. so, if the channel must be
     * secure, but it is not, then throw an exception and return an error.
     */
    if (isSecure() && !request.isSecure()) {
        response.sendError(SC_UNAUTHORIZED, "ERROR, channel is not secure");
        LOG.error(getBeanName() + ": handleRequestInternal - ERROR, channel is not secure");
        return null;
    }

    /*
     * getUserPrincipal() returns a java.security.Principal containing the
     * name of the user making this request, else it returns null if the
     * user has not been authenticated. so, if it is mandated that the user
     * be authenticated, but has not been authenticated, then throw an
     * exception and return an error
     */
    if (isAuthenticated() && request.getUserPrincipal() == null) {
        response.sendError(SC_UNAUTHORIZED, "ERROR, user is not authenticated");
        LOG.error(getBeanName() + ": handleRequestInternal - ERROR, user is not authenticated");
        return null;
    }

    /*
     * Check for valid method - the only supported http methods are GET,
     * POST, PUT, and DELETE. Here are some good descriptions regarding the
     * methods and their use with respect to this servlet.
     * 
     * The GET method is used for projecting data from the DB. So it maps to
     * a select statement.
     * 
     * The PUT and POST methods are used for inserting or updating an entity
     * in the DB. So they map to either an update or insert.
     * 
     * The DELETE is used for removing one or more entities from the DB. So
     * it maps to a delete.
     * 
     * The bean must be assigned at least one of the methods to service
     */
    Method method = null;
    try {
        method = Enum.valueOf(Method.class, request.getMethod().toUpperCase());
        LOG.debug(getBeanName() + ": handleRequestInternal - processing this method: " + method.toString());
    } catch (IllegalArgumentException e) {
        LOG.error(getBeanName() + ":handleRequestInternal - This method is not allowed [" + request.getMethod()
                + "]");
        response.setHeader("Allow", allowedMethodsRsp);
        response.sendError(SC_METHOD_NOT_ALLOWED, "This method is not allowed [" + request.getMethod() + "]");
        return null;
    }

    // do some more method validation; i.e., make sure requested method has
    // been assigned a SQL statement
    //
    // TODO: we may be able to remove this block of code
    String s1 = null;
    if (method.isGet() && sqlStmnts4Get == null || method.isPost() && sqlStmnts4Post == null
            || method.isPut() && sqlStmnts4Put == null || method.isDelete() && sqlStmnts4Delete == null) {
        response.setHeader("Allow", allowedMethodsRsp);
        s1 = "HTTP method [" + method + "] is not supported";
        response.sendError(SC_METHOD_NOT_ALLOWED, s1);
        LOG.error(getBeanName() + ":handleRequestInternal - " + s1);
        return null;
    }

    // If the client has specified an 'Accept' header field, then determine
    // if it is willing or capable of accepting JSON or anything (*/*)
    //
    // TODO: what about the client accepting urlencoded strings??
    s1 = request.getHeader(ACCEPT_HDR);
    if (s1 != null && s1.length() > 0) {
        LOG.debug(getBeanName() + ":handleRequestInternal - client-specified media "
                + "type in accept header = " + s1);
        // parse the accept header's content
        String[] mediaTypes = s1.trim().split(COMMA_STR);
        boolean match = false;
        for (String mediaType : mediaTypes) {
            mediaType = mediaType.trim().toLowerCase();
            if (mediaType.startsWith(anyContentType) || mediaType.startsWith(jsonContentType)) {
                match = true;
                break;
            }
        }
        if (!match) {
            LOG.error(getBeanName() + ":handleRequestInternal - client-specified media type of '" + s1
                    + "' does not include '" + "'" + jsonContentType);
            response.sendError(SC_NOT_ACCEPTABLE, "client-specified media " + "type of '" + s1
                    + "' does not include '" + "'" + jsonContentType);
            return null;
        }
    }

    // pick up the corresponding list of SQL statements for this request
    List<SqlStmnt> sqlStmnts = null;
    switch (method) {
    case GET:
        sqlStmnts = getSqlStmnts4Get();
        break;
    case DELETE:
        sqlStmnts = getSqlStmnts4Delete();
        break;
    case PUT:
        sqlStmnts = getSqlStmnts4Put();
        break;
    case POST:
        sqlStmnts = getSqlStmnts4Post();
        break;
    default:
        response.sendError(SC_METHOD_NOT_ALLOWED, "ERROR, unsupported method type: " + method);
        LOG.error(getBeanName() + ": handleRequestInternal - ERROR, encountered unknown " + "method type: "
                + method);
        return null;
    }

    // ~~~~~~ EXTRACT PARAMERTERS, IF ANY ~~~~~~~~~~~

    // GETs with entity bodies are illegal
    if (method.isGet() && request.getContentLength() > 0) {
        response.sendError(SC_BAD_REQUEST,
                "Client has issued a malformed or illegal request; " + "GET cannot include entity body");
        return null;
    }

    // the DELETE method also cannot include an entity body; however, the
    // servlet containers already ignore them. so no need to check for that

    // see if json object arrived
    boolean jsonObjectPresent = (method.isPost() || method.isPut())
            && (request.getContentLength() > 0 && request.getContentType().equalsIgnoreCase(jsonContentType));

    LOG.debug(getBeanName() + ": jsonObjectPresent = " + jsonObjectPresent);

    // see if this is a PUT with entity. we've learned that for PUTs,
    // getParameterMap does not work the same across all servlet containers.
    // so we need take care of this ourselves
    boolean putWithBodyPresent = (method.isPut()) && (request.getContentLength() > 0
            && request.getContentType().equalsIgnoreCase(urlEncodedContentType));

    LOG.debug(getBeanName() + ": putWithBodyPresent = " + putWithBodyPresent);

    // collect incoming parameters and place them in a common bucket
    //
    // ~~~~ ALL PARAMETER KEY NAMES MUST BE FORCED TO LOWER CASE ~~~
    //
    List<Map<String, String>> cParams = new ArrayList<Map<String, String>>();

    // first, get the incoming query or form parameters (if any); we will
    // assume that each key has only one parameter. in other words,
    // we're not dealing with drop-down boxes or things similar
    if (!putWithBodyPresent && !jsonObjectPresent) {
        Map<String, String[]> qParams = request.getParameterMap();
        if (qParams != null && !qParams.isEmpty()) {
            Map<String, String> qMap = new HashMap<String, String>();
            for (String key : qParams.keySet()) {
                qMap.put(key.toLowerCase(), qParams.get(key)[0]);
            }
            if (!qMap.isEmpty()) {
                cParams.add(qMap);
                LOG.debug(getBeanName() + ": query params = " + qMap.toString());
            }
        }
    }

    // a put with entity body arrived, so get the parameters from the
    // body and place them in the common bucket
    else if (putWithBodyPresent) {

        try {
            Map<String, String> putParams = null;
            // parseUrlEncoded will force keys to lower case
            putParams = Utils.parseUrlEncoded(request.getInputStream());
            if (putParams != null && !putParams.isEmpty()) {
                cParams.add(putParams);
            }
        } catch (Exception exc) {
            LOG.error(getBeanName() + ": ERROR, caught this " + "exception while parsing urlencoded string: "
                    + exc.toString());
            LOG.error(getBeanName() + ": exception stack trace follows:");
            dumpStackTrace(exc.getStackTrace());
            if (exc.getCause() != null) {
                LOG.error(getBeanName() + ": Caused by " + exc.getCause().toString());
                LOG.error(getBeanName() + ": causing exception stack trace follows:");
                dumpStackTrace(exc.getCause().getStackTrace());
            }
            response.sendError(SC_BAD_REQUEST, "urlencoded string parsing error: " + exc.getMessage());
            return null;
        }
    }

    // ok, a json object arrived, so get parameters defined in that object
    // and place them in the common bucket
    else {
        // its a json object, so parse it to extract params from it
        try {
            List<Map<String, String>> jParams = null;
            // parseJson will ensure that all passed-in JSON objects have
            // the same set of identical keys
            jParams = Utils.parseJson(request.getInputStream());
            if (jParams != null && !jParams.isEmpty()) {
                // if we also got query params then ensure they have the
                // same set of keys as the json params. why anyone would
                // ever do this is beyond me, but I'll leave it in for now
                if (!cParams.isEmpty()) {
                    Map<String, String> cMap = cParams.get(0);
                    Map<String, String> jMap = jParams.get(0);
                    for (String key : cMap.keySet()) {
                        if (jMap.get(key) == null) {
                            String eStr = getBeanName() + ": ERROR, json "
                                    + "object key set does not match query " + "param key set";
                            LOG.error(eStr);
                            response.sendError(SC_BAD_REQUEST, eStr);
                            return null;
                        }
                    }
                    // place the passed in query params in the jParams
                    // bucket
                    jParams.add(cMap);
                }
                // assign the jParams bucket to the common bucket
                cParams = jParams;
            }
        } catch (Exception exc) {
            LOG.error(getBeanName() + ": ERROR, caught this " + "exception while parsing json object: "
                    + exc.toString());
            LOG.error(getBeanName() + ": exception stack trace follows:");
            dumpStackTrace(exc.getStackTrace());
            if (exc.getCause() != null) {
                LOG.error(getBeanName() + ": Caused by " + exc.getCause().toString());
                LOG.error(getBeanName() + ": causing exception stack trace follows:");
                dumpStackTrace(exc.getCause().getStackTrace());
            }
            response.sendError(SC_BAD_REQUEST, "json parsing error: " + exc.getMessage());
            return null;
        }
    }

    // if trace is on, dump the params (if any) to the log
    if (LOG.isDebugEnabled()) {
        if (!cParams.isEmpty()) {
            for (int i = 0; i < cParams.size(); i++) {
                LOG.debug(getBeanName() + ": handleRequestInternal - received these params: "
                        + cParams.get(i).toString());
            }
        } else {
            LOG.debug(getBeanName() + ": handleRequestInternal - did not receive any params");
        }
    }

    // ensure none of the params' values have been black listed
    if (!cParams.isEmpty() && getBlackList().length() > 0) {
        char[] bl = getBlackList().toCharArray();
        for (int i = 0; i < cParams.size(); i++) {
            for (String value : cParams.get(i).values()) {
                if (Utils.isOnBlackList(value, bl)) {
                    response.sendError(SC_BAD_REQUEST,
                            "encountered black listed character in this param " + "value: " + value);
                    LOG.error(getBeanName() + "handleRequestInternal - encountered black listed "
                            + "character in this param value: " + value);
                    return null;
                }

            }
        }
    }

    // find the proper SQL statement based on the incoming parameters' (if
    // any) keys
    SqlStmnt sqlStmnt = null;
    try {
        // getMatch will try and find a match, even if no params were
        // provided.
        // @formatter:off
        sqlStmnt = (cParams.isEmpty()) ? SqlStmnt.getMatch(sqlStmnts, null)
                : SqlStmnt.getMatch(sqlStmnts, cParams.get(0).keySet());
        // @formatter:on

        if (sqlStmnt == null && !cParams.isEmpty()) {
            LOG.error(getBeanName() + ":ERROR, unable to find sql " + "statement with this incoming param set: "
                    + cParams.toString());
            response.sendError(SC_INTERNAL_SERVER_ERROR, "internal server error: mapping error");
            return null;
        } else if (sqlStmnt == null) {
            LOG.warn(getBeanName() + ": warning, unable to find sql "
                    + "statement on first pass, will use extra path info");
        } else {
            LOG.debug(getBeanName() + ": handleRequestInternal - matching sql stmt = " + sqlStmnt.toString());
        }
    } catch (Exception exc) {
        LOG.error(getBeanName() + ":ERROR, caught this exception " + "while mapping sql to params: "
                + exc.toString());
        LOG.error(getBeanName() + ": exception stack trace follows:");
        dumpStackTrace(exc.getStackTrace());
        if (exc.getCause() != null) {
            LOG.error(getBeanName() + ": Caused by " + exc.getCause().toString());
            LOG.error(getBeanName() + ": causing exception stack trace follows:");
            dumpStackTrace(exc.getCause().getStackTrace());
        }
        response.sendError(SC_INTERNAL_SERVER_ERROR, "mapping error");
        return null;
    }

    // if getMatch could not find a match - perhaps input params were not
    // provided - then use the URI's 'extended path' information as an input
    // param
    if (sqlStmnt == null) {
        LOG.debug(getBeanName() + ": invoking getExtraPathInfo");
        String[] xtraPathInfo = Utils.getExtraPathInfo(request.getPathInfo());
        if (xtraPathInfo != null && xtraPathInfo.length >= 2) {
            LOG.debug(getBeanName() + ": extra path key:value = " + xtraPathInfo[0] + ":" + xtraPathInfo[1]);
        } else {
            LOG.error(getBeanName() + ":ERROR, getExtraPathInfo failed to find info");
            response.sendError(SC_INTERNAL_SERVER_ERROR, "internal server error: mapping error");
            return null;
        }
        // put the xtra path info in the common param bucket and try again
        cParams.clear();
        Map<String, String> xMap = new HashMap<String, String>();
        xMap.put(xtraPathInfo[0], xtraPathInfo[1]);
        cParams.add(xMap);
        // try again with the extra path info
        sqlStmnt = SqlStmnt.getMatch(sqlStmnts, xMap.keySet());
        if (sqlStmnt == null) {
            LOG.error(getBeanName() + ":ERROR, unable to find sql " + "statement with this xtra path info: "
                    + cParams.toString());
            response.sendError(SC_NOT_FOUND, "internal server error: mapping error");
            return null;
        }
    }

    // if we've gotten this far, we've gotten past the security gauntlet and
    // we have a SQL statement to work with.
    SqlResult sqlResult = null;
    try {
        // get the output stream
        OutputStream os = response.getOutputStream();

        // FIRE IN THE DB HOLE :)
        if ((sqlResult = sqlStmnt.execute(cParams)) == null) {
            // execute will have logged the necessary debug/error info
            response.sendError(SC_INTERNAL_SERVER_ERROR);
            return null;
        }

        // execute went through ok, lets see how to respond
        switch (method) {
        case GET:
            // if a resultset was returned, then set the content type,
            // convert it to json, and write it out
            List<Map<String, Object>> listMap = sqlResult.getResultSet();
            if (listMap != null) {
                // tell the client the content type
                response.setContentType(rspJsonContentType);
                String jsonOutput = Utils.generateJson(sqlResult.getResultSet());
                LOG.trace(getBeanName() + ": returning this payload - " + jsonOutput);
                os.write(jsonOutput.getBytes());

                // ensure that only the client can cache the data and tell
                // the client how long the data can remain active
                response.setHeader(CACHE_CNTRL_HDR,
                        (getCacheControl() != null) ? getCacheControl() : DFLT_CACHE_CNTRL_STR);
                response.setHeader(PRAGMA_HDR, PRAGMA_NO_CACHE_STR);
                response.setDateHeader(EXPIRES_HDR, currentTime + (getExpires() * 1000));
            } else {
                LOG.debug(getBeanName() + ": NOT returning json message");
            }
            response.setStatus(SC_OK);
            break;
        case DELETE:
            // a DELETE should not send back an entity body
            response.setStatus(SC_NO_CONTENT);
            break;
        case PUT:
            /*
             * PUTs are idempotent; therefore, they must provide ALL the
             * properties that pertain to the resource/entity that they are
             * creating or updating. Updates cannot be partial updates; they
             * must be full updates. A PUT is issued by a client that knows
             * the identifier (in our case, primary key) of the
             * resource/entity. Therefore, we do not have to send back a
             * Location header in response to a PUT that has created a
             * resource.
             */
            if (sqlStmnt.isInsert()) {
                response.setStatus(SC_CREATED);
            } else {
                response.setStatus(SC_OK);
            }
            break;
        case POST:
            /*
             * A POST is not idempotent; therefore, it can be used to
             * perform a 'partial' update, as well as a full create. When
             * creating a resource via POST, the client does not know the
             * primary key, and it assumes it will be auto-generated;
             * therefore, a Location header with auto-generated key must be
             * returned to client.
             */
            if (sqlStmnt.isInsert()) {
                response.setStatus(SC_CREATED);
                // we need to return the new key, but only if it was not a
                // batch insert. the new key should be returned via the
                // location header

                // check if a key holder exists; if not, then table was not
                // configured with auto-generated key.
                String locationPath = request.getRequestURL().toString();
                if (sqlResult.getKeyHolder() != null) {
                    // key holder exists, check and see if a key is
                    // present
                    if (sqlResult.getKeyHolder().getKey() != null) {
                        String id = sqlResult.getKeyHolder().getKey().toString();
                        LOG.debug(getBeanName() + ": getKey() returns " + id);
                        locationPath += ("/" + id);
                        LOG.debug(getBeanName() + ": locationPath = " + locationPath);
                        response.setHeader(LOCATION_HDR, locationPath);
                    }
                    // no key, check for multiple keys
                    // TODO: should we send back all keys?
                    else if (sqlResult.getKeyHolder().getKeys() != null) {
                        Map<String, Object> keyMap = sqlResult.getKeyHolder().getKeys();
                        LOG.debug(getBeanName() + ": getKeys() returns " + keyMap);
                    }
                    // maybe map of keys?
                    // TODO: should we send back all keys?
                    else if (sqlResult.getKeyHolder().getKeyList() != null) {
                        for (Map<String, Object> map : sqlResult.getKeyHolder().getKeyList()) {
                            LOG.debug(getBeanName() + ": Map from getKeyList(): " + map);
                        }
                    }
                } else {
                    // if it was not an insert, then it was an update.
                    LOG.debug(getBeanName() + ": key holder was not returned for the insert");
                }
            } else {
                // it was not an insert, so just send back an OK for the
                // update
                response.setStatus(SC_OK);
            }
            break;
        default:
            response.setStatus(SC_OK);
            break;
        }
    } catch (JsonProcessingException exc) {
        LOG.error(getBeanName() + ":ERROR, caught this " + "JsonProcessingException while trying to gen json "
                + "message: " + exc.toString());
        LOG.error(getBeanName() + ": exception stack trace follows:");
        dumpStackTrace(exc.getStackTrace());
        if (exc.getCause() != null) {
            LOG.error(getBeanName() + ": Caused by " + exc.getCause().toString());
            LOG.error(getBeanName() + ": causing exception stack trace follows:");
            dumpStackTrace(exc.getCause().getStackTrace());
        }
        response.sendError(SC_INTERNAL_SERVER_ERROR, "parsing error");
        return null;
    } catch (Exception exc) {
        LOG.error(getBeanName() + ":ERROR, caught this " + "Exception while trying to gen json " + "message: "
                + exc.toString());
        LOG.error(getBeanName() + ": exception stack trace follows:");
        dumpStackTrace(exc.getStackTrace());
        if (exc.getCause() != null) {
            LOG.error(getBeanName() + ": Caused by " + exc.getCause().toString());
            LOG.error(getBeanName() + ": causing exception stack trace follows:");
            dumpStackTrace(exc.getCause().getStackTrace());
        }
        response.sendError(SC_INTERNAL_SERVER_ERROR, "parsing error");
        return null;

    } finally {
        if (sqlResult != null) {
            SqlResult.enqueue(sqlResult);
        }
    }

    // must return null, because we're not using views!
    return null;
}

From source file:seava.j4e.web.controller.ui.extjs.AbstractUiExtjsController.java

protected void _prepare(Map<String, Object> model, HttpServletRequest request, HttpServletResponse response)
        throws Exception {

    response.setContentType("text/html;charset=UTF-8");

    if (logger.isInfoEnabled()) {
        logger.info("Handling request for ui.extjs: ", request.getPathInfo());
    }/*w  w  w.  ja  v  a 2s .co m*/

    String server = request.getServerName();
    int port = request.getServerPort();

    String userRolesStr = null;

    this.prepareRequest(request, response);

    try {
        ISessionUser su = (ISessionUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        IUser user = su.getUser();

        IUserSettings prefs = user.getSettings();

        Session.user.set(user);

        model.put("statics", BeansWrapper.getDefaultInstance().getStaticModels());
        model.put("constantsJsFragment", this.getConstantsJsFragment());
        model.put("user", user);

        DateFormatAttribute[] masks = DateFormatAttribute.values();
        Map<String, String> dateFormatMasks = new HashMap<String, String>();
        for (int i = 0, len = masks.length; i < len; i++) {
            DateFormatAttribute mask = masks[i];
            if (mask.isForJs()) {
                dateFormatMasks.put(mask.name().replace("EXTJS_", ""), prefs.getDateFormatMask(mask.name()));
            }
        }

        model.put("dateFormatMasks", dateFormatMasks);

        model.put("modelDateFormat", this.getSettings().get(Constants.PROP_EXTJS_MODEL_DATE_FORMAT));

        model.put("decimalSeparator", prefs.getDecimalSeparator());
        model.put("thousandSeparator", prefs.getThousandSeparator());

        StringBuffer sb = new StringBuffer();
        int i = 0;
        for (String role : user.getProfile().getRoles()) {
            if (i > 0) {
                sb.append(",");
            }
            sb.append("\"" + role + "\"");
            i++;
        }
        userRolesStr = sb.toString();

    } catch (ClassCastException e) {
        // not authenticated
    }
    String hostUrl = ((request.isSecure()) ? "https" : "http") + "://" + server
            + ((port != 80) ? (":" + port) : "");// + contextPath;

    model.put("productName", StringEscapeUtils.escapeJavaScript(this.getSettings().getProductName()));
    model.put("productDescription", this.getSettings().getProductDescription());
    model.put("productVersion", this.getSettings().getProductVersion());
    model.put("productVendor", this.getSettings().getProductVendor());
    model.put("productUrl", this.getSettings().getProductUrl());
    model.put("hostUrl", hostUrl);
    model.put("ctxpath", this.getSettings().get(Constants.PROP_CTXPATH));

    // themes
    model.put("urlUiExtjsThemes", getUiExtjsSettings().getUrlThemes());

    // DNet extjs components in core and modules
    model.put("urlUiExtjsLib", getUiExtjsSettings().getUrlLib());
    model.put("urlUiExtjsCore", getUiExtjsSettings().getUrlCore());
    model.put("urlUiExtjsCoreI18n", getUiExtjsSettings().getUrlCoreI18n());

    model.put("urlUiExtjsModules", getUiExtjsSettings().getUrlModules());
    model.put("urlUiExtjsModuleSubpath", getUiExtjsSettings().getModuleSubpath());
    model.put("urlUiExtjsModuleUseBundle", getUiExtjsSettings().isModuleUseBundle());

    String lang = this.resolveLang(request, response);
    model.put("shortLanguage", StringEscapeUtils.escapeJavaScript(lang));

    String theme = this.resolveTheme(request, response);
    model.put("theme", StringEscapeUtils.escapeJavaScript(theme));

    model.put("sysCfg_workingMode", this.getSettings().get(Constants.PROP_WORKING_MODE));

    model.put("userRolesStr", userRolesStr);

}

From source file:de.innovationgate.wgpublisher.WGPDispatcher.java

public static String getPublisherURL(javax.servlet.http.HttpServletRequest request, boolean absolute) {

    if (absolute) {
        String protocol = request.getProtocol().substring(0, request.getProtocol().indexOf("/")).toLowerCase();
        if (protocol.equals("http") && request.isSecure()) {
            protocol = "https";
        }//  w w  w .  ja  v  a  2s .  c o m

        int port = request.getServerPort();
        if (port != -1) {
            if (protocol.equals("http") && port == 80) {
                port = -1;
            } else if (protocol.equals("https") && port == 443) {
                port = -1;
            }
        }

        return protocol + "://" + request.getServerName() + (port != -1 ? ":" + port : "")
                + request.getContextPath();
    } else {
        return request.getContextPath();
    }

}

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

protected void servicePre(HttpServletRequest request, HttpServletResponse response) throws Exception {

    HttpSession session = request.getSession();

    // Company/*from   ww  w  . j av a  2 s . c o  m*/

    Company company = PortalUtil.getCompany(request);

    long companyId = company.getCompanyId();

    // CDN host

    String cdnHost = null;

    if (request.isSecure()) {
        cdnHost = PortalUtil.getCDNHostHttps();
    } else {
        cdnHost = PortalUtil.getCDNHostHttp();
    }

    cdnHost = ParamUtil.getString(request, "cdn_host", 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 = cdnHost.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(ImageServletTokenUtil.getToken(company.getLogoId()));

    String companyLogo = sb.toString();

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

    int companyLogoHeight = companyLogoImage.getHeight();
    int 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;
    }

    boolean signedIn = false;

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

    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");

    // Permission checker

    PermissionChecker permissionChecker = PermissionCheckerFactoryUtil.create(user, true);

    PermissionThreadLocal.setPermissionChecker(permissionChecker);

    // 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);

            if (Validator.isNotNull(languageId)) {
                locale = LocaleUtil.fromLanguageId(languageId);
            }

            // Get locale from the request

            if ((locale == null) && PropsValues.LOCALE_DEFAULT_REQUEST) {
                locale = request.getLocale();
            }

            // 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);
    }

    // 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);
    } 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);
        }
    }

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

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

            boolean isViewableCommunity = isViewableGroup(user, layout.getGroupId(), layout.isPrivateLayout(),
                    layout.getLayoutId(), permissionChecker);

            if (!isViewableCommunity && group.isStagingGroup()) {
                layout = null;
            } else if (!isViewableCommunity) {
                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 PrincipalException(sb.toString());
            } else if (isViewableCommunity
                    && !LayoutPermissionUtil.contains(permissionChecker, layout, ActionKeys.VIEW)) {

                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;
                }
            }
        } catch (NoSuchLayoutException nsle) {
        }
    }

    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);

    if (layout != null) {
        if (company.isCommunityLogo()) {
            long logoId = 0;

            LayoutSet layoutSet = layout.getLayoutSet();

            if (layoutSet.isLogo()) {
                logoId = layoutSet.getLogoId();
            } 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(ImageServletTokenUtil.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) ((LayoutImpl) layout).clone();

        layoutTypePortlet = (LayoutTypePortlet) layout.getLayoutType();

        LayoutClone layoutClone = LayoutCloneFactory.getInstance();

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

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

                props.load(typeSettings);

                String stateMax = props.getProperty(LayoutTypePortletConstants.STATE_MAX);
                String stateMin = props.getProperty(LayoutTypePortletConstants.STATE_MIN);
                String modeAbout = props.getProperty(LayoutTypePortletConstants.MODE_ABOUT);
                String modeConfig = props.getProperty(LayoutTypePortletConstants.MODE_CONFIG);
                String modeEdit = props.getProperty(LayoutTypePortletConstants.MODE_EDIT);
                String modeEditDefaults = props.getProperty(LayoutTypePortletConstants.MODE_EDIT_DEFAULTS);
                String modeEditGuest = props.getProperty(LayoutTypePortletConstants.MODE_EDIT_GUEST);
                String modeHelp = props.getProperty(LayoutTypePortletConstants.MODE_HELP);
                String modePreview = props.getProperty(LayoutTypePortletConstants.MODE_PREVIEW);
                String modePrint = props.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);

        if (layout.isPrivateLayout()) {
            permissionChecker.setCheckGuest(false);
        }
    }

    // Scope

    long scopeGroupId = PortalUtil.getScopeGroupId(request);
    long parentGroupId = PortalUtil.getParentGroupId(scopeGroupId);

    // Device
    Device device = DevicesUtil.getDeviceFromRequest(request);
    _log.debug(" Device is: " + device);

    // 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);
        }
    } else {
        DeviceAction deviceAction = DeviceRulesUtil.getAction(device, companyId, group.getGroupId(),
                layout.getPlid());
        if (deviceAction != null && !(deviceAction instanceof NoAction)) {
            if (deviceAction instanceof ChangeThemeAction) {
                ChangeThemeAction changeThemeAction = (ChangeThemeAction) deviceAction;
                ThemeAndColorScheme themeAndColorScheme = changeThemeAction.getThemeAndColorScheme();
                if (themeAndColorScheme != null && themeAndColorScheme.getThemeId() != null) {
                    theme = themeAndColorScheme.getTheme(companyId);
                    _log.debug("Changing theme to " + theme.getThemeId());
                    if (themeAndColorScheme.getColorSchemeId() != null) {
                        colorScheme = themeAndColorScheme.getColorScheme(companyId);
                        _log.debug("Changing color scheme to " + colorScheme.getColorSchemeId());
                    }
                }
            }
            if (deviceAction instanceof RedirectAction) {
                RedirectAction redirectAction = (RedirectAction) deviceAction;
                String url = redirectAction.getUrl();
                if (url != null && !url.trim().isEmpty()) {
                    _log.debug("Redirecting to " + url);
                    response.sendRedirect(url);
                    return;
                }
            }
        } else if (layout != null) {
            if (wapTheme) {
                theme = layout.getWapTheme();
                colorScheme = layout.getWapColorScheme();
            } else {
                theme = layout.getTheme();
                colorScheme = layout.getColorScheme();
            }
        } else {
            String themeId = null;
            String colorSchemeId = null;

            if (wapTheme) {
                themeId = ThemeImpl.getDefaultWapThemeId(companyId);
                colorSchemeId = ColorSchemeImpl.getDefaultWapColorSchemeId();
            } else {
                themeId = ThemeImpl.getDefaultRegularThemeId(companyId);
                colorSchemeId = ColorSchemeImpl.getDefaultRegularColorSchemeId();
            }

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

    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");
    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();
    }

    // Theme display

    ThemeDisplay themeDisplay = ThemeDisplayFactory.create();

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

    themeDisplay.setCDNHost(cdnHost);
    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.setLayoutSetLogo(layoutSetLogo);
    themeDisplay.setLayout(layout);
    themeDisplay.setLayouts(layouts);
    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(contextPath, 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(cdnHost.concat(contextPath).concat("/html/js"));
    themeDisplay.setPathMain(mainPath);
    themeDisplay.setPathSound(contextPath.concat("/html/sound"));

    // URLs

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

    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);
    }

    themeDisplay.setURLControlPanel(urlControlPanel);

    PortletURL createAccountURL = new PortletURLImpl(request, PortletKeys.LOGIN, plid,
            PortletRequest.ACTION_PHASE);

    createAccountURL.setWindowState(WindowState.MAXIMIZED);
    createAccountURL.setPortletMode(PortletMode.VIEW);

    createAccountURL.setParameter("saveLastPath", "0");
    createAccountURL.setParameter("struts_action", "/login/create_account");

    themeDisplay.setURLCreateAccount(createAccountURL);

    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);

            boolean hasUpdateLayoutPermission = LayoutPermissionUtil.contains(permissionChecker, layout,
                    ActionKeys.UPDATE);

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

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

                themeDisplay.setShowLayoutTemplatesIcon(true);

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

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

        boolean hasManageLayoutsPermission = GroupPermissionUtil.contains(permissionChecker, scopeGroupId,
                ActionKeys.MANAGE_LAYOUTS);

        if (group.isUser()) {
            if ((layout.isPrivateLayout() && !PropsValues.LAYOUT_USER_PRIVATE_LAYOUTS_MODIFIABLE)
                    || (layout.isPublicLayout() && !PropsValues.LAYOUT_USER_PUBLIC_LAYOUTS_MODIFIABLE)) {

                hasManageLayoutsPermission = false;
            }
        }

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

            PortletURL pageSettingsURL = new PortletURLImpl(request, PortletKeys.LAYOUT_MANAGEMENT, plid,
                    PortletRequest.RENDER_PHASE);

            pageSettingsURL.setWindowState(WindowState.MAXIMIZED);
            pageSettingsURL.setPortletMode(PortletMode.VIEW);

            pageSettingsURL.setParameter("struts_action", "/layout_management/edit_pages");

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

            pageSettingsURL.setParameter("redirect", currentURL);
            pageSettingsURL.setParameter("groupId", String.valueOf(scopeGroupId));
            pageSettingsURL.setParameter("selPlid", String.valueOf(plid));

            themeDisplay.setURLPageSettings(pageSettingsURL);
        }

        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()) {
            boolean hasApproveProposalPermission = GroupPermissionUtil.contains(permissionChecker, scopeGroupId,
                    ActionKeys.APPROVE_PROPOSAL);

            boolean hasPublishStagingPermission = GroupPermissionUtil.contains(permissionChecker, scopeGroupId,
                    ActionKeys.PUBLISH_STAGING);

            if (hasApproveProposalPermission || hasManageLayoutsPermission || hasPublishStagingPermission) {

                themeDisplay.setShowStagingIcon(true);
            }

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

                publishToLiveURL.setWindowState(LiferayWindowState.EXCLUSIVE);
                publishToLiveURL.setPortletMode(PortletMode.VIEW);

                publishToLiveURL.setParameter("struts_action", "/layout_management/export_pages");

                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));

                themeDisplay.setURLPublishToLive(publishToLiveURL);
            }
        }

        String myAccountNamespace = PortalUtil.getPortletNamespace(PortletKeys.MY_ACCOUNT);

        String myAccountRedirect = ParamUtil.getString(request, myAccountNamespace.concat("backURL"),
                currentURL);

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

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

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

        myAccountURL.setWindowState(WindowState.MAXIMIZED);
        myAccountURL.setPortletMode(PortletMode.VIEW);
        myAccountURL.setRefererPlid(plid);

        myAccountURL.setParameter("struts_action", "/my_account/edit_user");
        myAccountURL.setParameter("backURL", myAccountRedirect);

        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 (group.isLayoutPrototype()) {
        themeDisplay.setShowControlPanelIcon(false);
        themeDisplay.setShowHomeIcon(false);
        themeDisplay.setShowMyAccountIcon(false);
        themeDisplay.setShowPageSettingsIcon(true);
        themeDisplay.setShowPortalIcon(false);
        themeDisplay.setShowSignInIcon(false);
        themeDisplay.setShowSignOutIcon(false);
        themeDisplay.setShowStagingIcon(false);
    }

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

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

    if (layout != null) {
        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.setWindowState(WindowState.MAXIMIZED);
    updateManagerURL.setPortletMode(PortletMode.VIEW);

    updateManagerURL.setParameter("struts_action", "/update_manager/view");

    themeDisplay.setURLUpdateManager(updateManagerURL);

    request.setAttribute(WebKeys.THEME_DISPLAY, themeDisplay);

    // Parallel render

    boolean parallelRenderEnable = true;

    if (layout != null) {
        List<String> portletIds = layoutTypePortlet.getPortletIds();

        if (portletIds.size() == 1) {
            String portletId = portletIds.get(0);

            Portlet portlet = PortletLocalServiceUtil.getPortletById(portletId);

            if ((portlet != null) && !portlet.isAjaxable()) {
                parallelRenderEnable = false;
            }
        }
    }

    Boolean parallelRenderEnableObj = Boolean
            .valueOf(ParamUtil.getBoolean(request, "p_p_parallel", parallelRenderEnable));

    request.setAttribute(WebKeys.PORTLET_PARALLEL_RENDER, parallelRenderEnableObj);
}

From source file:ru.org.linux.user.UserEventController.java

@RequestMapping(value = "/show-replies.jsp", method = RequestMethod.GET)
public ModelAndView showReplies(HttpServletRequest request, HttpServletResponse response,
        @RequestParam(value = "nick", required = false) String nick,
        @RequestParam(value = "offset", defaultValue = "0") int offset,
        @ModelAttribute("notifications") Action action) throws Exception {
    Template tmpl = Template.getTemplate(request);
    boolean feedRequested = request.getParameterMap().containsKey("output");

    if (nick == null) {
        if (tmpl.isSessionAuthorized()) {
            return new ModelAndView(new RedirectView("/notifications"));
        }// ww  w.ja  va2  s. c  o  m
        throw new AccessViolationException("not authorized");
    } else {
        User.checkNick(nick);
        if (!tmpl.isSessionAuthorized() && !feedRequested) {
            throw new AccessViolationException("not authorized");
        }
        if (tmpl.isSessionAuthorized() && nick.equals(tmpl.getCurrentUser().getNick()) && !feedRequested) {
            return new ModelAndView(new RedirectView("/notifications"));
        }
        if (!feedRequested && !tmpl.isModeratorSession()) {
            throw new AccessViolationException(
                    "? ?  ?");
        }
    }

    Map<String, Object> params = new HashMap<>();
    params.put("nick", nick);

    if (offset < 0) {
        offset = 0;
    }

    boolean firstPage = offset == 0;
    int topics = tmpl.getProf().getTopics();
    if (feedRequested) {
        topics = 50;
    }

    if (topics > 200) {
        topics = 200;
    }

    params.put("firstPage", firstPage);
    params.put("topics", topics);
    params.put("offset", offset);

    /* define timestamps for caching */
    long time = System.currentTimeMillis();
    int delay = firstPage ? 90 : 60 * 60;
    response.setDateHeader("Expires", time + 1000 * delay);

    User user = userDao.getUser(nick);

    boolean showPrivate = tmpl.isModeratorSession();

    User currentUser = tmpl.getCurrentUser();
    params.put("currentUser", currentUser);

    if (currentUser != null && currentUser.getId() == user.getId()) {
        showPrivate = true;
        params.put("unreadCount", user.getUnreadEvents());
        response.addHeader("Cache-Control", "no-cache");
    }

    List<UserEvent> list = userEventService.getRepliesForUser(user, showPrivate, topics, offset,
            UserEventFilterEnum.ALL);
    List<PreparedUserEvent> prepared = userEventService.prepare(list, feedRequested, request.isSecure());

    params.put("isMyNotifications", false);
    params.put("topicsList", prepared);
    params.put("hasMore", list.size() == topics);

    ModelAndView result = new ModelAndView("show-replies", params);

    if (feedRequested) {
        result.addObject("feed-type", "rss");
        if ("atom".equals(request.getParameter("output"))) {
            result.addObject("feed-type", "atom");
        }
        result.setView(feedView);
    }
    return result;
}