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:mp.platform.cyclone.webservices.AuthInterceptor.java

public void handleMessage(final SoapMessage message) throws Fault {
    final HttpServletRequest request = WebServiceHelper.requestOf(message);
    ServiceClient client = null;/*from   w  ww.  ja va2s.  c  o  m*/
    final ServletContext servletContext = servletContextOf(message);
    try {
        if (!applicationService.isOnline()) {
            WebServiceFaultsEnum.APPLICATION_OFFLINE.throwFault();
        }

        // Check non-secure access when HTTP is enabled
        if (Boolean.TRUE.equals(servletContext.getAttribute("cyclos.httpEnabled"))) {
            final String protocol = StringUtils.split(request.getRequestURL().toString(), "://")[0];
            if (!"https".equalsIgnoreCase(protocol)) {
                WebServiceFaultsEnum.SECURE_ACCESS_REQUIRED.throwFault();
            }
        }

        boolean allowed = false;
        // Find the service client
        client = resolveClient(request);
        if (client != null) {
            // Find the requested operation
            final ServiceOperation[] operations = resolveOperations(message);
            if (operations.length == 0) {
                // When there are no operations, access is granted to anyone
                allowed = true;
            } else {
                // Check whether the client has access to the requested operation
                final Set<ServiceOperation> permissions = client.getPermissions();
                for (final ServiceOperation serviceOperation : operations) {
                    if (permissions.contains(serviceOperation)) {
                        allowed = true;
                        break;
                    }
                }
            }
        }
        if (!allowed) {
            WebServiceFaultsEnum.UNAUTHORIZED_ACCESS.throwFault();
        } else {
            loggingHandler.traceWebService(request.getRemoteAddr(), client,
                    WebServiceHelper.getWebServiceOperationName(message),
                    WebServiceHelper.getParameters(message));
        }

        // Ensure the LoggedUser state is consistent
        final Member member = client.getMember();
        if (member != null) {
            // Initialize the LoggedUser when restricted to a member
            LoggedUser.init(member.getUser(), request.getRemoteAddr());
        } else {
            // Not restricted: ensure there's no user logged in
            LoggedUser.cleanup();
        }
    } finally {
        // Initialize the context
        WebServiceContext.set(client, servletContext, request, message);
    }
}

From source file:com.rapid.forms.RapidFormAdapter.java

protected Map<String, Boolean> getUserFormCompleteValues(RapidRequest rapidRequest) {
    // get the servlet context
    ServletContext servletContext = rapidRequest.getRapidServlet().getServletContext();
    // get the map of completed values
    Map<String, Boolean> userFormCompleteValues = (Map<String, Boolean>) servletContext
            .getAttribute(USER_FORM_COMPLETE_VALUES);
    // if there aren't any yet
    if (userFormCompleteValues == null) {
        // make some
        userFormCompleteValues = new HashMap<String, Boolean>();
        // store them
        servletContext.setAttribute(USER_FORM_COMPLETE_VALUES, userFormCompleteValues);
    }/*from   w  w w .ja  v  a2s.  c  o  m*/
    // return
    return userFormCompleteValues;
}

From source file:com.sonicle.webtop.core.app.ContextLoader.java

public void initApp(ServletContext servletContext) throws IllegalStateException {
    String webappName = ContextUtils.getWebappFullName(servletContext, false);
    servletContext.setAttribute(WEBAPPNAME_ATTRIBUTE_KEY, webappName);
    if (servletContext.getAttribute(WEBTOPAPP_ATTRIBUTE_KEY) != null) {
        throw new IllegalStateException(
                "There is already a WebTop application associated with the current ServletContext.");
    }//from  ww  w. j ava 2 s  .  c  o  m

    try {
        WebTopApp wta = new WebTopApp(servletContext);
        wta.boot();
        servletContext.setAttribute(WEBTOPAPP_ATTRIBUTE_KEY, wta);
        servletContext.setAttribute(JWTSignatureVerifier.SECRET_CONTEXT_ATTRIBUTE,
                wta.getDocumentServerSecretIn());

        Dynamic atmosphereServlet = servletContext.addServlet("AtmosphereServlet",
                com.sonicle.webtop.core.app.atmosphere.AtmosphereServlet.class);
        atmosphereServlet.setInitParameter("org.atmosphere.cpr.AtmosphereFramework.analytics", "false");
        atmosphereServlet.setInitParameter("org.atmosphere.cpr.broadcasterCacheClass",
                "com.sonicle.webtop.core.app.atmosphere.UUIDBroadcasterCache");
        atmosphereServlet.setInitParameter("org.atmosphere.cpr.broadcasterLifeCyclePolicy",
                "BroadcasterLifeCyclePolicy.EMPTY");
        atmosphereServlet.setInitParameter("org.atmosphere.cpr.asyncSupport",
                "org.atmosphere.container.JSR356AsyncSupport");
        //atmosphereServlet.setInitParameter("org.atmosphere.cpr.asyncSupport", "org.atmosphere.container.Tomcat7CometSupport");
        atmosphereServlet.setInitParameter("org.atmosphere.cpr.sessionSupport", "true");
        atmosphereServlet.setInitParameter("org.atmosphere.cpr.sessionCreate", "false");
        atmosphereServlet.setInitParameter("org.atmosphere.cpr.broadcaster.shareableThreadPool", "true");
        atmosphereServlet.setInitParameter("org.atmosphere.cpr.AtmosphereInterceptor",
                "org.atmosphere.interceptor.ShiroInterceptor");
        atmosphereServlet.setLoadOnStartup(1);
        atmosphereServlet.setAsyncSupported(true);
        atmosphereServlet.addMapping(com.sonicle.webtop.core.app.atmosphere.AtmosphereServlet.URL + "/*");

        Dynamic resourcesServlet = servletContext.addServlet("ResourcesServlet",
                com.sonicle.webtop.core.app.servlet.ResourceRequest.class);
        resourcesServlet.setLoadOnStartup(1);
        resourcesServlet.addMapping(com.sonicle.webtop.core.app.servlet.ResourceRequest.URL + "/*");

        Dynamic loginServlet = servletContext.addServlet("LoginServlet",
                com.sonicle.webtop.core.app.servlet.Login.class);
        loginServlet.setLoadOnStartup(1);
        loginServlet.addMapping(com.sonicle.webtop.core.app.servlet.Login.URL + "/*");

        Dynamic logoutServlet = servletContext.addServlet("LogoutServlet",
                com.sonicle.webtop.core.app.servlet.Logout.class);
        logoutServlet.setLoadOnStartup(1);
        logoutServlet.addMapping(com.sonicle.webtop.core.app.servlet.Logout.URL + "/*");

        Dynamic otpServlet = servletContext.addServlet("OtpServlet",
                com.sonicle.webtop.core.app.servlet.Otp.class);
        otpServlet.setLoadOnStartup(1);
        otpServlet.addMapping(com.sonicle.webtop.core.app.servlet.Otp.URL + "/*");

        Dynamic uiPrivateServlet = servletContext.addServlet("UIPrivateServlet",
                com.sonicle.webtop.core.app.servlet.UIPrivate.class);
        uiPrivateServlet.setLoadOnStartup(1);
        uiPrivateServlet.addMapping(com.sonicle.webtop.core.app.servlet.UIPrivate.URL + "/*");

        Dynamic privateRequestServlet = servletContext.addServlet("PrivateRequestServlet",
                com.sonicle.webtop.core.app.servlet.PrivateRequest.class);
        privateRequestServlet.setLoadOnStartup(1);
        privateRequestServlet.addMapping(com.sonicle.webtop.core.app.servlet.PrivateRequest.URL + "/*");
        privateRequestServlet.addMapping(com.sonicle.webtop.core.app.servlet.PrivateRequest.URL_LEGACY + "/*");

        Dynamic publicRequestServlet = servletContext.addServlet("PublicRequestServlet",
                com.sonicle.webtop.core.app.servlet.PublicRequest.class);
        publicRequestServlet.setLoadOnStartup(1);
        publicRequestServlet.addMapping(com.sonicle.webtop.core.app.servlet.PublicRequest.URL + "/*");

        Dynamic docEditorServlet = servletContext.addServlet("DocEditorServlet",
                com.sonicle.webtop.core.app.servlet.DocEditor.class);
        docEditorServlet.setLoadOnStartup(1);
        docEditorServlet.addMapping(com.sonicle.webtop.core.app.servlet.DocEditor.URL + "/*");

        // Adds RestApiServlets dynamically
        ServiceManager svcMgr = wta.getServiceManager();
        for (String serviceId : svcMgr.listRegisteredServices()) {
            ServiceDescriptor desc = svcMgr.getDescriptor(serviceId);

            if (desc.hasOpenApiDefinitions() || desc.hasRestApiEndpoints()) {
                addRestApiServlet(servletContext, desc);
            }
        }

    } catch (Throwable t) {
        servletContext.removeAttribute(WEBTOPAPP_ATTRIBUTE_KEY);
        logger.error("Error initializing WTA [{}]", webappName, t);
    }
}

From source file:nl.strohalm.cyclos.webservices.interceptor.AuthInterceptor.java

@Override
public void handleMessage(final SoapMessage message) throws Fault {
    final HttpServletRequest request = WebServiceHelper.requestOf(message);
    request.setAttribute(ContextType.class.getName(), ContextType.SERVICE_CLIENT);
    ServiceClient client = null;//from   w  w  w .  ja v  a  2  s  .c  o m
    final ServletContext servletContext = servletContextOf(message);
    try {
        if (!applicationServiceLocal.isOnline()) {
            throw WebServiceHelper.fault(WebServiceFaultsEnum.APPLICATION_OFFLINE);
        }

        // Check non-secure access when HTTP is enabled
        if (Boolean.TRUE.equals(servletContext.getAttribute("cyclos.httpEnabled"))) {
            final String protocol = StringUtils.split(request.getRequestURL().toString(), "://")[0];
            if (!"https".equalsIgnoreCase(protocol)) {
                throw WebServiceHelper.fault(WebServiceFaultsEnum.SECURE_ACCESS_REQUIRED);
            }
        }

        boolean allowed = false;
        // Find the service client
        client = resolveClient(request);
        if (client != null) {
            // Find the requested operation
            final ServiceOperation[] operations = resolveOperations(message);
            if (operations.length == 0) {
                // When there are no operations, access is granted to anyone
                allowed = true;
            } else {
                // Check whether the client has access to the requested operation
                final Set<ServiceOperation> permissions = client.getPermissions();
                for (final ServiceOperation serviceOperation : operations) {
                    if (permissions.contains(serviceOperation)) {
                        allowed = true;
                        break;
                    }
                }
            }
        }
        if (!allowed) {
            throw WebServiceHelper.fault(WebServiceFaultsEnum.UNAUTHORIZED_ACCESS);
        }

        // Initialize the logged user
        LoggedUser.init(client, request.getRemoteAddr(), null);

        // Initialize the context
        WebServiceContext.set(client, servletContext, request, message);
    } catch (Exception e) {
        WebServiceHelper.initializeContext(message);
        if (e instanceof SoapFault) {
            throw (SoapFault) e;
        } else {
            throw WebServiceHelper.fault(e);
        }
    }
}

From source file:org.h3270.web.SessionState.java

public void valueUnbound(HttpSessionBindingEvent event) {
    // disconnect all s3270 sessions when the HttpSession times out and release
    // associated logical units in the pool
    for (Iterator i = terminalStates.iterator(); i.hasNext();) {
        TerminalState ts = (TerminalState) i.next();
        if (ts.getTerminal() != null && ts.getTerminal().isConnected()) {
            if (logger.isInfoEnabled())
                logger.info("Session unbound, disconnecting terminal " + ts.getTerminal());
            ts.getTerminal().disconnect();

            String logicalUnit = ts.getTerminal().getLogicalUnit();
            if (logicalUnit != null) {
                ServletContext servletContext = event.getSession().getServletContext();
                LogicalUnitPool pool = (LogicalUnitPool) servletContext
                        .getAttribute(LogicalUnitPool.SERVLET_CONTEXT_KEY);
                pool.releaseLogicalUnit(logicalUnit);
            }/*from   w  ww .  ja  v a2s .  com*/
        }
    }
}

From source file:com.murrayc.murraycgwtpexample.server.ThingServiceImpl.java

private Things getThings() {
    if (things != null) {
        return things;
    }/*from w  w w  .j a v  a2  s  .co  m*/

    final ServletConfig config = this.getServletConfig();
    if (config == null) {
        Log.error("getServletConfig() return null");
        return null;
    }

    final ServletContext context = config.getServletContext();
    if (context == null) {
        Log.error("getServletContext() return null");
        return null;
    }

    //Use the existing shared things if any:
    final Object object = context.getAttribute(LOADED_THINGS);
    if ((object != null) && !(object instanceof Things)) {
        Log.error("The loaded-things attribute is not of the expected type.");
        return null;
    }

    things = (Things) object;
    if (things != null) {
        return things;
    }

    //Load it for the first time:
    try {
        things = loadThings();
    } catch (final Exception e) {
        e.printStackTrace();
        return null;
    }

    context.setAttribute(LOADED_THINGS, things);

    return things;
}

From source file:com.concursive.connect.web.listeners.ContextListener.java

/**
 * All objects that should not be persistent can be removed from the context
 * before the next reload//from  ww w. j ava  2 s. c  om
 *
 * @param event Description of the Parameter
 */
public void contextDestroyed(ServletContextEvent event) {
    ServletContext context = event.getServletContext();
    LOG.info("Shutting down");

    // Remove scheduler
    try {
        Scheduler scheduler = (Scheduler) context.getAttribute(Constants.SCHEDULER);
        if (scheduler != null) {
            // Remove the App connection pool
            ConnectionPool appCP = (ConnectionPool) scheduler.getContext().get("ConnectionPool");
            // Interrupt any interruptable jobs
            scheduler.interrupt("directoryIndexer",
                    (String) scheduler.getContext().get(ScheduledJobs.CONTEXT_SCHEDULER_GROUP));
            // Cleanup the scheduler
            scheduler.getContext().remove(appCP);
            int count = scheduler.getCurrentlyExecutingJobs().size();
            if (count > 0) {
                LOG.info("Waiting for scheduler jobs to finish executing... (" + count + ")");
            }
            scheduler.shutdown(true);
            LOG.info("Scheduler shutdown");
            if (appCP != null) {
                appCP.closeAllConnections();
                appCP.destroy();
            }
            context.removeAttribute(Constants.SCHEDULER);
        }
    } catch (Exception e) {
        LOG.error("Scheduler error", e);
    }

    // Remove the tracker
    context.removeAttribute(Constants.USER_SESSION_TRACKER);

    // Stop the object hook manager
    ObjectHookManager hookManager = (ObjectHookManager) context.getAttribute(Constants.OBJECT_HOOK_MANAGER);
    if (hookManager != null) {
        hookManager.reset();
        hookManager.shutdown();
        context.removeAttribute(Constants.OBJECT_HOOK_MANAGER);
    }

    // Stop the work flow manager
    WorkflowManager wfManager = (WorkflowManager) context.getAttribute(Constants.WORKFLOW_MANAGER);
    if (wfManager != null) {
        context.removeAttribute(Constants.WORKFLOW_MANAGER);
    }

    // Unregister the remote wsrp producer
    ProducerRegistry producerRegistry = ProducerRegistryImpl.getInstance();
    ProducerImpl producer = (ProducerImpl) producerRegistry
            .getProducer(PortletManager.CONCURSIVE_WSRP_PRODUCER_ID);
    if (producer != null) {
        try {
            producer.deregister();
            LOG.info("Successfully deregistered remote wsrp producer");
        } catch (WSRPException e) {
            LOG.error("Unable to de-register the remote wsrp producer");
        }
    }

    // Stop the portlet container
    PortletContainer container = (PortletContainer) context.getAttribute(Constants.PORTLET_CONTAINER);
    if (container != null) {
        try {
            container.destroy();
        } catch (Exception e) {
            LOG.error("PortletContainer error", e);
        }
        context.removeAttribute(Constants.PORTLET_CONTAINER);
    }

    // Remove the cache manager
    CacheManager.getInstance().shutdown();

    // TODO: Create a connection pool array
    // Remove the connection pool
    ConnectionPool cp = (ConnectionPool) context.getAttribute(Constants.CONNECTION_POOL);
    if (cp != null) {
        cp.closeAllConnections();
        cp.destroy();
        context.removeAttribute(Constants.CONNECTION_POOL);
    }

    // Remove the RSS connection pool
    ConnectionPool rssCP = (ConnectionPool) context.getAttribute(Constants.CONNECTION_POOL_RSS);
    if (rssCP != null) {
        rssCP.closeAllConnections();
        rssCP.destroy();
        context.removeAttribute(Constants.CONNECTION_POOL_RSS);
    }

    // Remove the API connection pool
    ConnectionPool apiCP = (ConnectionPool) context.getAttribute(Constants.CONNECTION_POOL_API);
    if (apiCP != null) {
        apiCP.closeAllConnections();
        apiCP.destroy();
        context.removeAttribute(Constants.CONNECTION_POOL_API);
    }

    // Shutdown the indexer service
    IIndexerService indexer = IndexerFactory.getInstance().getIndexerService();
    if (indexer != null) {
        try {
            indexer.shutdown();
        } catch (Exception e) {
            LOG.error("Error shutting down indexer", e);
        }
    }

    // Remove system settings
    context.removeAttribute(Constants.SYSTEM_SETTINGS);

    // Remove the logger
    ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
    LogFactory.release(contextClassLoader);

    LOG.info("Shutdown complete");
}

From source file:com.adito.core.CoreUtil.java

/**
 * Get message resources given the ID and the session. <code>null</code>
 * will be returned if no such resources exist.
 * /*  w w w.j  a v a  2 s  .co m*/
 * @param context session
 * @param key bundle key
 * @return resources
 */
public static MessageResources getMessageResources(ServletContext context, String key) {
    ModuleConfig moduleConfig = ModuleUtils.getInstance().getModuleConfig("", context);
    return (MessageResources) context.getAttribute(key + moduleConfig.getPrefix());
}

From source file:com.concursive.connect.web.controller.hooks.SecurityHook.java

/**
 * Description of the Method//from   w w  w  . j ava2 s .  com
 *
 * @param context Description of the Parameter
 * @param db      Description of the Parameter
 */
protected void freeConnection(ServletContext context, Connection db) {
    if (db != null) {
        ConnectionPool sqlDriver = (ConnectionPool) context.getAttribute("ConnectionPool");
        sqlDriver.free(db);
    }
    db = null;
}

From source file:com.concursive.connect.web.controller.hooks.SecurityHook.java

/**
 * Gets the connection attribute of the SecurityHook object
 *
 * @param context Description of the Parameter
 * @param request Description of the Parameter
 * @return The connection value//from ww  w  .  ja  v  a  2s  .  com
 * @throws SQLException Description of the Exception
 */
protected Connection getConnection(ServletContext context, HttpServletRequest request) throws SQLException {
    ConnectionPool sqlDriver = (ConnectionPool) context.getAttribute("ConnectionPool");
    ConnectionElement ce = (ConnectionElement) request.getSession().getAttribute("ConnectionElement");
    if (sqlDriver == null || ce == null) {
        return null;
    }
    return sqlDriver.getConnection(ce);
}