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.psikeds.common.config.ContextLoaderListener.java

/**
 * Servlet is shutting down. Close context and destroy Spring-Beans.
 *//*from w  w w.  j  a  v  a2 s.c o m*/
@Override
public void contextDestroyed(final ServletContextEvent event) {
    if (this.contextLoader != null) {
        this.contextLoader.closeWebApplicationContext(event.getServletContext());
    }
    final ServletContext sc = event.getServletContext();
    final Enumeration<?> attrNames = sc.getAttributeNames();
    while (attrNames.hasMoreElements()) {
        final String attrName = (String) attrNames.nextElement();
        if (attrName.startsWith("org.springframework.")) {
            final Object attrValue = sc.getAttribute(attrName);
            if (attrValue instanceof DisposableBean) {
                try {
                    ((DisposableBean) attrValue).destroy();
                } catch (final Exception ex) {
                    LOGGER.error("Couldn't invoke destroy method of attribute with name '" + attrName + "'",
                            ex);
                }
            }
        }
    }
}

From source file:nu.kelvin.jfileshare.servlets.AboutServlet.java

@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    ServletContext app = getServletContext();
    RequestDispatcher disp;/*from   w  w w .j  a v  a 2  s  .c  o m*/
    req.setAttribute("tab", "About");
    disp = app.getRequestDispatcher("/templates/About.jsp");
    HttpSession session = req.getSession();
    Conf conf = (Conf) app.getAttribute("conf");

    req.setAttribute("daysLogRetention", conf.getDaysLogRetention());

    if (session.getAttribute("user") != null) {
        Connection dbConn = null;
        PreparedStatement st = null;
        try {
            long bytesStoreAvailable = FileSystemUtils.freeSpaceKb(conf.getPathStore()) * 1024;
            req.setAttribute("bytesStoreAvailable", FileItem.humanReadable(bytesStoreAvailable));

            dbConn = ds.getConnection();
            st = dbConn.prepareStatement(
                    "select cast(count(1) as char) as logins, cast(count(distinct payload) as char) as uniqueLogins from Logs where action=\"login\" and date > (now() - INTERVAL ? DAY)");
            st.setInt(1, conf.getDaysLogRetention());
            ResultSet rs = st.executeQuery();
            if (rs.first()) {
                req.setAttribute("logins", rs.getString("logins"));
                req.setAttribute("uniqueLogins", rs.getString("uniqueLogins"));
            }

            st = dbConn.prepareStatement(
                    "select cast(count(1) as char) as downloads, sum(cast(payload as unsigned)) as bytesDownloads from Logs where action=\"download\" and date > (now() - INTERVAL ? DAY)");
            st.setInt(1, conf.getDaysLogRetention());
            rs = st.executeQuery();
            if (rs.first()) {
                req.setAttribute("downloads", rs.getString("downloads"));
                req.setAttribute("bytesDownloads", FileItem.humanReadable(rs.getLong("bytesDownloads")));
            }

            st = dbConn.prepareStatement(
                    "select cast(count(1) as char) as uploads, sum(cast(payload as unsigned)) as bytesUploads from Logs where action=\"upload\" and date > (now() - INTERVAL ? DAY)");
            st.setInt(1, conf.getDaysLogRetention());
            rs = st.executeQuery();
            if (rs.first()) {
                req.setAttribute("uploads", rs.getString("uploads"));
                req.setAttribute("bytesUploads", FileItem.humanReadable(rs.getLong("bytesUploads")));
            }
            st.close();
        } catch (SQLException e) {
            logger.severe(e.toString());
        } finally {
            if (dbConn != null) {
                try {
                    dbConn.close();
                } catch (SQLException ignore) {
                }
            }
        }
    }
    disp.forward(req, resp);
}

From source file:org.hdiv.config.multipart.AbstractMultipartConfig.java

/**
 * Returns the path to the temporary directory to be used for uploaded files which are written to disk. The
 * directory used is determined from the first of the following to be non-empty.
 * <ol>//ww w .j a v a 2 s  . co m
 * <li>A temp dir explicitly defined using the <code>saveDir</code> attribute of the &lt;multipartConfig&gt; element
 * in the Spring config file.</li>
 * <li>The temp dir specified by the <code>javax.servlet.context.tempdir</code> attribute.</li>
 * </ol>
 * 
 * @param servletContext
 *            servlet context
 * @return The path to the directory to be used to store uploaded files.
 */
public String getRepositoryPath(ServletContext servletContext) {

    // First, look for an explicitly defined temp dir.
    String saveDir = this.tempDir;

    if ((saveDir == null) || saveDir.equals("")) {
        File tempdir = (File) servletContext.getAttribute("javax.servlet.context.tempdir");
        log.info("Unable to find 'saveDir' property setting. Defaulting to javax.servlet.context.tempdir");

        if (tempdir != null) {
            saveDir = tempdir.toString();
        }

        // If none, look for a container specified temp dir.
        if (saveDir == null || saveDir.length() == 0) {
            saveDir = System.getProperty("java.io.tmpdir");
        }

    } else {
        File multipartSaveDir = new File(saveDir);

        if (!multipartSaveDir.exists()) {
            multipartSaveDir.mkdir();
        }
    }

    if (log.isTraceEnabled()) {
        log.trace("File upload temp dir: " + saveDir);
    }

    return saveDir;
}

From source file:org.apache.hadoop.http.HttpServer2.java

/**
 * check whether user is static and unauthenticated, if the
 * answer is TRUE, that means http sever is in non-security
 * environment./*from w  w  w.  java 2s .co m*/
 * @param servletContext the servlet context.
 * @param request the servlet request.
 * @return TRUE/FALSE based on the logic described above.
 */
public static boolean isStaticUserAndNoneAuthType(ServletContext servletContext, HttpServletRequest request) {
    Configuration conf = (Configuration) servletContext.getAttribute(CONF_CONTEXT_ATTRIBUTE);
    final String authType = request.getAuthType();
    final String staticUser = conf.get(CommonConfigurationKeys.HADOOP_HTTP_STATIC_USER,
            CommonConfigurationKeys.DEFAULT_HADOOP_HTTP_STATIC_USER);
    return authType == null && staticUser.equals(request.getRemoteUser());
}

From source file:org.apache.nifi.processors.standard.servlets.ListenHTTPServlet.java

@SuppressWarnings("unchecked")
@Override//from   w w  w  . j a v  a 2  s .co m
public void init(final ServletConfig config) throws ServletException {
    final ServletContext context = config.getServletContext();
    this.logger = (ComponentLog) context.getAttribute(ListenHTTP.CONTEXT_ATTRIBUTE_LOGGER);
    this.sessionFactoryHolder = (AtomicReference<ProcessSessionFactory>) context
            .getAttribute(ListenHTTP.CONTEXT_ATTRIBUTE_SESSION_FACTORY_HOLDER);
    this.processContext = (ProcessContext) context
            .getAttribute(ListenHTTP.CONTEXT_ATTRIBUTE_PROCESS_CONTEXT_HOLDER);
    this.authorizedPattern = (Pattern) context.getAttribute(ListenHTTP.CONTEXT_ATTRIBUTE_AUTHORITY_PATTERN);
    this.headerPattern = (Pattern) context.getAttribute(ListenHTTP.CONTEXT_ATTRIBUTE_HEADER_PATTERN);
    this.flowFileMap = (ConcurrentMap<String, FlowFileEntryTimeWrapper>) context
            .getAttribute(ListenHTTP.CONTEXT_ATTRIBUTE_FLOWFILE_MAP);
    this.streamThrottler = (StreamThrottler) context
            .getAttribute(ListenHTTP.CONTEXT_ATTRIBUTE_STREAM_THROTTLER);
    this.basePath = (String) context.getAttribute(ListenHTTP.CONTEXT_ATTRIBUTE_BASE_PATH);
}

From source file:org.red5.server.scope.WebScope.java

/**
 * Sets the local app context variable based on host id if available in the 
 * servlet context./*from ww  w  .  jav  a2s. c  o m*/
 */
private final void getAppContext() {
    //get the host id
    String hostId = null;
    //get host from servlet context
    if (servletContext != null) {
        ServletContext sctx = servletContext.getContext(contextPath);
        if (sctx != null) {
            hostId = (String) sctx.getAttribute("red5.host.id");
            log.trace("Host id from init param: {}", hostId);
        }
    }
    if (hostId != null) {
        appContext = LoaderBase.getRed5ApplicationContext(hostId + contextPath);
    } else {
        appContext = LoaderBase.getRed5ApplicationContext(contextPath);
    }
}

From source file:jeeves.monitor.MonitorManager.java

private HealthCheckRegistry lookUpHealthCheckRegistry(ServletContext context, String attributeKey) {
    HealthCheckRegistry tmpHealthCheckRegistry = (HealthCheckRegistry) context.getAttribute(attributeKey);
    if (tmpHealthCheckRegistry == null) {
        tmpHealthCheckRegistry = new HealthCheckRegistry();
    }/*www. java 2 s.  c om*/
    context.setAttribute(attributeKey, tmpHealthCheckRegistry);
    return tmpHealthCheckRegistry;
}

From source file:org.impalaframework.web.integration.ModuleProxyFilter.java

@Override
protected void processMapping(ServletContext context, HttpServletRequest request, HttpServletResponse response,
        FilterChain chain, RequestModuleMapping moduleMapping, String applicationId)
        throws IOException, ServletException {

    String attributeName = ModuleHttpServiceInvoker.class.getName() + "." + moduleMapping.getModuleName();
    Object attribute = context.getAttribute(attributeName);

    HttpServiceInvoker invoker = ObjectUtils.cast(attribute, HttpServiceInvoker.class);

    if (logger.isDebugEnabled()) {
        if (invoker != null) {
            logger.debug("Invoker for attribute '" + attributeName + "': " + invoker);
        } else {/*  w  w w  . j  a va  2s  .  c  om*/
            if (logger.isDebugEnabled())
                logger.debug("No invoker found for attribute '" + attributeName);
        }
    }

    if (invoker != null) {
        HttpServletRequest wrappedRequest = wrappedRequest(request, context, moduleMapping, applicationId);
        invoker.invoke(wrappedRequest, response, chain);
    } else {
        chain.doFilter(request, response);
    }
}

From source file:com.onehippo.gogreen.login.HstConcurrentLoginFilter.java

private void registerUserSession(HttpServletRequest request, String username) {
    log.debug("HstConcurrentLoginFilter will register session for {}", username);
    HttpSession session = request.getSession();
    session.setAttribute(USERNAME_ATTR, username);

    ServletContext servletContext = session.getServletContext();
    @SuppressWarnings("unchecked")
    Map<String, HttpSessionWrapper> map = (Map<String, HttpSessionWrapper>) servletContext
            .getAttribute(USERNAME_SESSIONID_MAP_ATTR);

    if (map != null) {
        String newSessionId = session.getId();
        HttpSessionWrapper oldHttpSessionWrapper = map.put(username,
                new HttpSessionWrapper(session, earlySessionInvalidation));
        log.debug("HstConcurrentLoginFilter registered session ({}) for {}.", newSessionId, username);

        if (oldHttpSessionWrapper != null) {
            oldHttpSessionWrapper.invalidate();
            log.debug("HstConcurrentLoginFilter kicked out session ({}) for {}.", oldHttpSessionWrapper.getId(),
                    username);//  w  w  w  . j a va  2  s .c o m
        }
    } else {
        log.error("HstConcurrentLoginFilter is in invalid state. The session ids map is not found.");
    }
}

From source file:org.apache.pluto.driver.tags.PortletModeDropDownTag.java

/**
 * Method invoked when the start tag is encountered.
 * @throws JspException  if an error occurs.
 *//*from  ww w . ja v  a 2  s  .  co m*/
public int doStartTag() throws JspException {

    // Ensure that the modeAnchor tag resides within a portlet tag.
    PortletTag parentTag = (PortletTag) TagSupport.findAncestorWithClass(this, PortletTag.class);
    if (parentTag == null) {
        throw new JspException("Portlet window controls may only reside " + "within a pluto:portlet tag.");
    }

    portletId = parentTag.getPortletId();
    // Evaluate portlet ID attribute.
    evaluatePortletId();

    // Retrieve the portlet window config for the evaluated portlet ID.
    ServletContext servletContext = pageContext.getServletContext();
    DriverConfiguration driverConfig = (DriverConfiguration) servletContext
            .getAttribute(AttributeKeys.DRIVER_CONFIG);

    // Retrieve the portal environment.
    PortalRequestContext portalEnv = PortalRequestContext
            .getContext((HttpServletRequest) pageContext.getRequest());

    //find the current mode for use in 'selected' attrib of select option
    PortalURL requestedPortalUrl = portalEnv.getRequestedPortalURL();
    PortletWindowConfig windowConfig = PortletWindowConfig.fromId(evaluatedPortletId);
    // Retrieve the portlet container from servlet context.
    PortletContainer container = (PortletContainer) servletContext
            .getAttribute(AttributeKeys.PORTLET_CONTAINER);

    // Create the portlet window to render.
    PortletWindow window = new PortletWindowImpl(container, windowConfig, requestedPortalUrl);

    PortletMode currentMode = requestedPortalUrl.getPortletMode(window.getId().getStringId());

    //start the markup
    StringBuffer tag = new StringBuffer();
    //        String strCurrentMode = currentMode.toString();        
    //        tag.append("Current mode: " + currentMode.toString());
    tag.append(
            "<form action=\"\" name=\"modeSelectionForm\" style=\"display:inline\"><select onchange=\"self.location=this.options[this.selectedIndex].value\">");
    Set<PortletMode> modeSet = null;
    try {
        modeSet = driverConfig.getSupportedPortletModes(evaluatedPortletId);
    } catch (PortletContainerException e) {
        throw new JspException(e);
    }

    if (modeSet != null) {
        Iterator<PortletMode> i = modeSet.iterator();
        while (i.hasNext()) {
            PortletMode mode = i.next();

            PortalURL portalUrl = portalEnv.createPortalURL();
            portalUrl.setPortletMode(evaluatedPortletId, mode);

            // Build a string buffer containing the anchor tag
            tag.append("<option value=\"" + portalUrl.toString() + "\"");
            //Add 'selected' attribute for current mode.
            if (mode.equals(currentMode)) {
                tag.append(" selected=\"true\"");
            }
            tag.append(">");
            if (driverConfig.isPortletManagedMode(evaluatedPortletId, mode.toString())) {
                tag.append(getCustomModeDecorationName(driverConfig, mode));
            } else {
                tag.append(mode.toString().toUpperCase());
            }
            //               tag.append(mode.toString().toUpperCase());
            tag.append("</option>");
        }
    }
    tag.append("</select></form>");
    // Print the mode anchor tag.
    try {
        JspWriter out = pageContext.getOut();
        out.print(tag.toString());
    } catch (IOException ex) {
        throw new JspException(ex);
    }

    // Continue to evaluate the tag body.
    return EVAL_BODY_INCLUDE;
}