Example usage for javax.servlet ServletContext getAttribute

List of usage examples for javax.servlet ServletContext getAttribute

Introduction

In this page you can find the example usage for javax.servlet ServletContext getAttribute.

Prototype

public Object getAttribute(String name);

Source Link

Document

Returns the servlet container attribute with the given name, or null if there is no attribute by that name.

Usage

From source file:org.getobjects.servlets.WOServletAdaptor.java

@Override
public void init(final ServletConfig _cfg) throws ServletException {
    // Jetty: org.mortbay.jetty.servlet.ServletHolder$Config@114024
    super.init(_cfg);

    String an = this.valueFromServletConfig(_cfg, "WOAppName");
    String ac = this.valueFromServletConfig(_cfg, "WOAppClass");
    if (ac == null)
        ac = an;/* w  w  w.ja v  a 2s .com*/
    if (an == null && ac != null) {
        /* if only the class is set, we use the shortname of the class */
        int dotidx = ac.lastIndexOf('.');
        an = dotidx < 1 ? ac : ac.substring(dotidx + 1);
    }

    if (an == null) {
        log.warn("no WOAppName specified in servlet context: " + _cfg);
        an = WOApplication.class.getName();
    }

    /* Construct properties for the volatile "domain" from servlet init
     * parameters and context init parameters and attributes.
     * It's probably best to have a real UserDefaults concept, but for the
     * time being this is better than nothing.
     */
    final Properties properties = new Properties();
    Enumeration parameterNamesEnum = _cfg.getInitParameterNames();
    while (parameterNamesEnum.hasMoreElements()) {
        final String name = (String) parameterNamesEnum.nextElement();
        final String value = _cfg.getInitParameter(name);
        if (name != null && value != null)
            properties.put(name, value);
        else if (value == null)
            log.error("Got no value for init parameter: " + name);
    }

    /* The ServletContext may override the previous init parameters.
     * ServletContext init parameters will be overridden by attributes.
     */
    final ServletContext sctx = _cfg.getServletContext();
    if (sctx != null) {
        parameterNamesEnum = sctx.getInitParameterNames();
        while (parameterNamesEnum.hasMoreElements()) {
            final String name = (String) parameterNamesEnum.nextElement();
            properties.put(name, sctx.getInitParameter(name));
        }
        final Enumeration attributeNamesEnum = sctx.getAttributeNames();
        while (attributeNamesEnum.hasMoreElements()) {
            final String name = (String) attributeNamesEnum.nextElement();
            properties.put(name, sctx.getAttribute(name));
        }
    }

    this.initApplicationWithName(an, ac, properties);
}

From source file:org.acmsl.commons.utils.http.HttpServletUtils.java

/**
 * Retrieves an object from the repository.
 * @param key the key./*from   www  . ja  v a2  s  .  c  om*/
 * @param request the request.
 * @param session the session.
 * @param context the context.
 * @return the object if it's found.
 */
@Nullable
public Object retrieve(@NotNull final String key, @Nullable final ServletRequest request,
        @Nullable final HttpSession session, @Nullable final ServletContext context) {
    @Nullable
    Object result = null;

    // Thanks Sun for had missed an interface for
    // all classes that export setAttribute().
    if (request != null) {
        result = request.getAttribute(key);
    }

    if ((result == null) && (session != null)) {
        result = session.getAttribute(key);
    }

    if ((result == null) && (context != null)) {
        result = context.getAttribute(key);
    }

    return result;
}

From source file:com.liferay.portal.servlet.MainServlet.java

public void service(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException {

    if (!PortalInstances.matches()) {
        String html = ContentUtil.get("messages/en_US/init.html");

        res.getOutputStream().print(html);

        return;/*  ww  w  .j a va2 s  .co  m*/
    }

    if (ShutdownUtil.isShutdown()) {
        String html = ContentUtil.get("messages/en_US/shutdown.html");

        res.getOutputStream().print(html);

        return;
    }
    req.setAttribute("dotcache", "no");
    // Shared session

    HttpSession ses = req.getSession();

    if (!GetterUtil.getBoolean(PropsUtil.get(PropsUtil.TCK_URL))) {
        String sharedSessionId = CookieUtil.get(req.getCookies(), CookieKeys.SHARED_SESSION_ID);

        _log.debug("Shared session id is " + sharedSessionId);

        if (sharedSessionId == null) {
            sharedSessionId = PwdGenerator.getPassword(PwdGenerator.KEY1 + PwdGenerator.KEY2, 12);

            Cookie sharedSessionIdCookie = new Cookie(CookieKeys.SHARED_SESSION_ID, sharedSessionId);
            sharedSessionIdCookie.setPath("/");
            sharedSessionIdCookie.setMaxAge(86400);

            res.addCookie(sharedSessionIdCookie);

            _log.debug("Shared session id is " + sharedSessionId);
        }

        // if (ses.getAttribute(WebKeys.SHARED_SESSION_ID) == null) {
        ses.setAttribute(WebKeys.SHARED_SESSION_ID, sharedSessionId);
        // }

        HttpSession portalSes = (HttpSession) SharedSessionPool.get(sharedSessionId);

        if ((portalSes == null) || (ses != portalSes)) {
            if (portalSes == null) {
                _log.debug("No session exists in pool");
            } else {
                _log.debug("Session " + portalSes.getId() + " in pool is old");
            }

            _log.debug("Inserting current session " + ses.getId() + " in pool");

            SharedSessionPool.put(sharedSessionId, ses);
        }
    }

    // Test CAS auto login

    /*
     * ses.setAttribute(
     * com.liferay.portal.auth.CASAutoLogin.CAS_FILTER_USER,
     * "liferay.com.1");
     */

    // CTX

    ServletContext ctx = getServletContext();
    ServletContext portalCtx = ctx.getContext(PropsUtil.get(PropsUtil.PORTAL_CTX));
    if (portalCtx == null) {
        portalCtx = ctx;
    }

    req.setAttribute(WebKeys.CTX, portalCtx);

    // CTX_PATH variable

    String ctxPath = (String) ctx.getAttribute(WebKeys.CTX_PATH);

    if (portalCtx.getAttribute(WebKeys.CTX_PATH) == null) {
        portalCtx.setAttribute(WebKeys.CTX_PATH, ctxPath);
    }

    if (ses.getAttribute(WebKeys.CTX_PATH) == null) {
        ses.setAttribute(WebKeys.CTX_PATH, ctxPath);
    }

    req.setAttribute(WebKeys.CTX_PATH, ctxPath);

    // CAPTCHA_PATH variable

    String captchaPath = (String) ctx.getAttribute(WebKeys.CAPTCHA_PATH);

    if (portalCtx.getAttribute(WebKeys.CAPTCHA_PATH) == null) {
        portalCtx.setAttribute(WebKeys.CAPTCHA_PATH, captchaPath);
    }

    if (ses.getAttribute(WebKeys.CAPTCHA_PATH) == null) {
        ses.setAttribute(WebKeys.CAPTCHA_PATH, captchaPath);
    }

    req.setAttribute(WebKeys.CAPTCHA_PATH, captchaPath);

    // IMAGE_PATH variable

    String imagePath = (String) ctx.getAttribute(WebKeys.IMAGE_PATH);

    if (portalCtx.getAttribute(WebKeys.IMAGE_PATH) == null) {
        portalCtx.setAttribute(WebKeys.IMAGE_PATH, imagePath);
    }

    if (ses.getAttribute(WebKeys.IMAGE_PATH) == null) {
        ses.setAttribute(WebKeys.IMAGE_PATH, imagePath);
    }

    req.setAttribute(WebKeys.IMAGE_PATH, imagePath);

    // WebKeys.COMPANY_ID variable

    String companyId = (String) ctx.getAttribute(WebKeys.COMPANY_ID);

    if (portalCtx.getAttribute(WebKeys.COMPANY_ID) == null) {
        portalCtx.setAttribute(WebKeys.COMPANY_ID, companyId);
    }

    if (ses.getAttribute(WebKeys.COMPANY_ID) == null) {
        ses.setAttribute(WebKeys.COMPANY_ID, companyId);
    }

    req.setAttribute(WebKeys.COMPANY_ID, companyId);

    // Portlet Request Processor

    PortletRequestProcessor portletReqProcessor = (PortletRequestProcessor) portalCtx
            .getAttribute(WebKeys.PORTLET_STRUTS_PROCESSOR);

    if (portletReqProcessor == null) {
        portletReqProcessor = new PortletRequestProcessor(this, getModuleConfig(req));

        portalCtx.setAttribute(WebKeys.PORTLET_STRUTS_PROCESSOR, portletReqProcessor);
    }

    // Tiles definitions factory

    if (portalCtx.getAttribute(TilesUtilImpl.DEFINITIONS_FACTORY) == null) {
        portalCtx.setAttribute(TilesUtilImpl.DEFINITIONS_FACTORY,
                ctx.getAttribute(TilesUtilImpl.DEFINITIONS_FACTORY));
    }

    // Set character encoding

    String strutsCharEncoding = PropsUtil.get(PropsUtil.STRUTS_CHAR_ENCODING);

    req.setCharacterEncoding(strutsCharEncoding);

    /*
     * if (!BrowserSniffer.is_wml(req)) { res.setContentType(
     * Constants.TEXT_HTML + "; charset=" + strutsCharEncoding); }
     */

    // Determine content type

    String contentType = req.getHeader("Content-Type");

    if ((contentType != null) && (contentType.startsWith("multipart/form-data"))) {

        req = new UploadServletRequest(req);
    } else if (ParamUtil.get(req, WebKeys.ENCRYPT, false)) {
        try {
            Company company = CompanyLocalManagerUtil.getCompany(companyId);

            req = new EncryptedServletRequest(req, company.getKeyObj());
        } catch (Exception e) {
        }
    }

    // Current URL

    String completeURL = Http.getCompleteURL(req);
    if (completeURL.indexOf("j_security_check") != -1) {
        completeURL = ctxPath;
    } else {
        completeURL = completeURL.substring(completeURL.indexOf("://") + 3, completeURL.length());

        completeURL = completeURL.substring(completeURL.indexOf("/"), completeURL.length());
    }

    req.setAttribute(WebKeys.CURRENT_URL, completeURL);

    // Chat server

    // Login

    String userId = PortalUtil.getUserId(req);

    if ((userId != null)) {
        PrincipalThreadLocal.setName(userId);
    }

    if (userId == null) {
        try {
            User user = UserManagerUtil.getDefaultUser(companyId);
            if (ses.getAttribute(Globals.LOCALE_KEY) == null)
                ses.setAttribute(Globals.LOCALE_KEY, user.getLocale());

        } catch (Exception e) {
            Logger.error(this, e.getMessage(), e);
        }
    }

    // Process pre service events

    try {
        EventsProcessor.process(PropsUtil.getArray(PropsUtil.SERVLET_SERVICE_EVENTS_PRE), req, res);
    } catch (Exception e) {
        Logger.error(this, e.getMessage(), e);

        req.setAttribute(PageContext.EXCEPTION, e);

        StrutsUtil.forward(PropsUtil.get(PropsUtil.SERVLET_SERVICE_EVENTS_PRE_ERROR_PAGE), portalCtx, req, res);
    }

    // Struts service

    callParentService(req, res);

    // Process post service events

    try {
        EventsProcessor.process(PropsUtil.getArray(PropsUtil.SERVLET_SERVICE_EVENTS_POST), req, res);
    } catch (Exception e) {
        Logger.error(this, e.getMessage(), e);
    }

    // Clear the principal associated with this thread

    PrincipalThreadLocal.setName(null);
}

From source file:com.google.gwt.dev.shell.GWTShellServlet.java

private synchronized WorkDirs getShellWorkDirs() {
    if (workDirs == null) {
        ServletContext servletContext = getServletContext();
        final String attr = "com.google.gwt.dev.shell.workdirs";
        workDirs = (WorkDirs) servletContext.getAttribute(attr);
        assert (workDirs != null);
    }/*from   w  ww .  j  av a  2  s  . co  m*/
    return workDirs;
}

From source file:jp.or.openid.eiwg.scim.servlet.Schemas.java

/**
 * GET?//from   w w  w .  j a va2 s  .co m
 *
 * @param request 
 * @param response ?
 * @throws ServletException
 * @throws IOException
 */
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // ?
    ServletContext context = getServletContext();

    // ??
    Operation op = new Operation();
    boolean result = op.Authentication(context, request);

    if (!result) {
        // 
        errorResponse(response, op.getErrorCode(), op.getErrorType(), op.getErrorMessage());
    } else {
        // location?URL?
        String location = request.getScheme() + "://" + request.getServerName();
        int serverPort = request.getServerPort();
        if (serverPort != 80 && serverPort != 443) {
            location += ":" + Integer.toString(serverPort);
        }
        location += request.getContextPath();

        // ?
        @SuppressWarnings("unchecked")
        ArrayList<LinkedHashMap<String, Object>> schemas = (ArrayList<LinkedHashMap<String, Object>>) context
                .getAttribute("Schemas");

        // location?
        Iterator<LinkedHashMap<String, Object>> schemasIt = schemas.iterator();
        while (schemasIt.hasNext()) {
            LinkedHashMap<String, Object> schemaInfo = schemasIt.next();
            // meta?
            Object metaObject = SCIMUtil.getAttribute(schemaInfo, "meta");
            if (metaObject != null && metaObject instanceof LinkedHashMap) {
                @SuppressWarnings("unchecked")
                LinkedHashMap<String, Object> metaInfo = (LinkedHashMap<String, Object>) metaObject;
                Object locationInfo = SCIMUtil.getAttribute(metaInfo, "location");
                if (locationInfo != null && locationInfo instanceof String) {
                    String locationValue = String.format(locationInfo.toString(), location);
                    metaInfo.put("location", locationValue);
                    schemaInfo.put("meta", metaInfo);
                }
            }
        }

        try {
            // javaJSON??
            ObjectMapper mapper = new ObjectMapper();
            StringWriter writer = new StringWriter();
            mapper.writeValue(writer, schemas);

            // ??
            String listResponse = "{\"schemas\":[\"urn:ietf:params:scim:api:messages:2.0:ListResponse\"],";
            listResponse += "\"totalResults\":" + schemas.size();
            if (schemas.size() > 0) {
                listResponse += ",\"Resources\":";
                listResponse += writer.toString();
            }
            listResponse += "}";

            response.setContentType("application/scim+json;charset=UTF-8");
            PrintWriter out = response.getWriter();
            out.println(listResponse);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

From source file:com.google.gwt.dev.shell.GWTShellServlet.java

private synchronized TreeLogger getLogger() {
    if (topLogger == null) {
        ServletContext servletContext = getServletContext();
        final String attr = "com.google.gwt.dev.shell.logger";
        topLogger = (TreeLogger) servletContext.getAttribute(attr);
        if (topLogger == null) {
            // No shell available, so wrap the regular servlet context logger.
            ///*from w ww  .ja  v  a  2s  . com*/
            topLogger = new ServletContextTreeLogger(servletContext);
        }
    }
    return topLogger;
}

From source file:org.apache.pluto.driver.services.container.EventProviderImpl.java

private boolean isDeclaredAsPublishingEvent(QName qname) {
    ServletContext servletContext = PortalRequestContext.getContext(request).getServletContext();
    String applicationId = PortletWindowConfig.parseContextPath(portletWindow.getId().getStringId());
    String applicationName = applicationId;
    if (applicationId.length() > 0) {
        applicationName = applicationId.substring(1);
    }/* w  w w.j av  a 2  s  .c  o  m*/

    String portletName = PortletWindowConfig.parsePortletName(portletWindow.getId().getStringId());
    if (portletRegistry == null) {
        portletRegistry = ((PortletContainer) servletContext.getAttribute(AttributeKeys.PORTLET_CONTAINER))
                .getOptionalContainerServices().getPortletRegistryService();
    }
    List<? extends EventDefinitionReference> events = null;
    try {
        events = portletRegistry.getPortlet(applicationName, portletName).getSupportedPublishingEvents();
    } catch (PortletContainerException e1) {
        e1.printStackTrace();
    }
    if (events != null) {
        String defaultNamespace = portletWindow.getPortletEntity().getPortletDefinition().getApplication()
                .getDefaultNamespace();
        for (EventDefinitionReference ref : events) {
            QName name = ref.getQualifiedName(defaultNamespace);
            if (name == null) {
                continue;
            }
            if (qname.equals(name)) {
                return true;
            }
        }
    }
    return false;
}

From source file:jp.or.openid.eiwg.scim.servlet.ResourceTypes.java

/**
 * GET?// w ww. jav  a2s  .  c om
 *
 * @param request 
 * @param response ?
 * @throws ServletException
 * @throws IOException
 */
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // ?
    ServletContext context = getServletContext();

    // ??
    Operation op = new Operation();
    boolean result = op.Authentication(context, request);

    if (!result) {
        // 
        errorResponse(response, op.getErrorCode(), op.getErrorType(), op.getErrorMessage());
    } else {
        // location?URL?
        String location = request.getScheme() + "://" + request.getServerName();
        int serverPort = request.getServerPort();
        if (serverPort != 80 && serverPort != 443) {
            location += ":" + Integer.toString(serverPort);
        }
        location += request.getContextPath();

        // ?
        @SuppressWarnings("unchecked")
        ArrayList<LinkedHashMap<String, Object>> resourceTypes = (ArrayList<LinkedHashMap<String, Object>>) context
                .getAttribute("ResourceTypes");

        // location?
        Iterator<LinkedHashMap<String, Object>> resourceTypesIt = resourceTypes.iterator();
        while (resourceTypesIt.hasNext()) {
            LinkedHashMap<String, Object> resourceTypeInfo = resourceTypesIt.next();
            // meta?
            Object metaObject = SCIMUtil.getAttribute(resourceTypeInfo, "meta");
            if (metaObject != null && metaObject instanceof LinkedHashMap) {
                @SuppressWarnings("unchecked")
                LinkedHashMap<String, Object> metaInfo = (LinkedHashMap<String, Object>) metaObject;
                Object locationInfo = SCIMUtil.getAttribute(metaInfo, "location");
                if (locationInfo != null && locationInfo instanceof String) {
                    String locationValue = String.format(locationInfo.toString(), location);
                    metaInfo.put("location", locationValue);
                    resourceTypeInfo.put("meta", metaInfo);
                }
            }
        }

        try {
            // javaJSON??
            ObjectMapper mapper = new ObjectMapper();
            StringWriter writer = new StringWriter();
            mapper.writeValue(writer, resourceTypes);

            // ??
            String listResponse = "{\"schemas\":[\"urn:ietf:params:scim:api:messages:2.0:ListResponse\"],";
            listResponse += "\"totalResults\":" + resourceTypes.size();
            if (resourceTypes.size() > 0) {
                listResponse += ",\"Resources\":";
                listResponse += writer.toString();
            }
            listResponse += "}";

            response.setContentType("application/scim+json;charset=UTF-8");
            PrintWriter out = response.getWriter();
            out.println(listResponse);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

From source file:org.amplafi.jawr.maven.JawrMojo.java

public void createBundles() throws IOException {
    Map<String, Object> contextAttributes = new HashMap<String, Object>();
    contextAttributes.put("javax.servlet.context.tempdir", new File(System.getProperty("java.io.tmpdir")));
    Response respData = new Response();

    ServletConfig config = createMock(ServletConfig.class);
    ServletContext context = createMock(ServletContext.class);
    HttpServletRequest req = createMock(HttpServletRequest.class);
    HttpServletResponse resp = createMock(HttpServletResponse.class);

    setupJawrConfig(config, context, contextAttributes, respData);
    setupRequest(req, resp, respData);//w  ww  . j av  a2 s. co m

    replay(config, context, req, resp);

    try {

        for (String bundle : getBundles()) {
            respData.clear();
            respData.setTypeFromBundle(bundle);

            JawrServlet jawr = new JawrServlet();
            jawr.init(config);
            String attrName = "css".equals(respData.getType()) ? JawrConstant.CSS_CONTEXT_ATTRIBUTE
                    : JawrConstant.JS_CONTEXT_ATTRIBUTE;
            ResourceBundlesHandler handler = (ResourceBundlesHandler) context.getAttribute(attrName);

            respData.setPath(createLinkToBundle(handler, bundle));
            jawr.service(req, resp);
            System.out.println(respData);
            File file = new File(getRootPath() + bundle);
            FileUtils.writeStringToFile(file, respData.getData());
        }

    } catch (ServletException ex) {
        Logger.getLogger(JawrMojo.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(JawrMojo.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:com.google.gwt.dev.shell.GWTShellServlet.java

private boolean shouldAutoGenerateResources() {
    ServletContext servletContext = getServletContext();
    final String attr = "com.google.gwt.dev.shell.shouldAutoGenerateResources";
    Boolean attrValue = (Boolean) servletContext.getAttribute(attr);
    if (attrValue == null) {
        return true;
    }//from   w w w.j a  v a2s .c o m
    return attrValue;
}