Example usage for javax.servlet ServletContext setAttribute

List of usage examples for javax.servlet ServletContext setAttribute

Introduction

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

Prototype

public void setAttribute(String name, Object object);

Source Link

Document

Binds an object to a given attribute name in this ServletContext.

Usage

From source file:net.naijatek.myalumni.modules.admin.presentation.action.MaintainSystemModuleAction.java

public ActionForward updateServerUrl(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    logger.debug("in updateServerUrl...");
    if (!isTokenValid(request)) {
        return mapping.findForward(BaseConstants.FWD_INVALID_TOKEN);
    }/*from   ww w .j a  va 2 s . co m*/
    ActionMessages msgs = new ActionMessages();
    SystemConfigForm rssForm = (SystemConfigForm) form;

    ServletContext sCtx = request.getSession().getServletContext();
    systemConfigService.updateServerUrl(rssForm.getServerUrl(), getLastModifiedBy(request));
    sCtx.setAttribute(BaseConstants.SERVER_URL, rssForm.getServerUrl());
    msgs.add(BaseConstants.INFO_KEY, new ActionMessage("message.record.updated"));
    saveMessages(request, msgs);
    resetToken(request);
    return mapping.findForward(BaseConstants.FWD_SUCCESS);
}

From source file:com.aurel.track.ApplicationStarter.java

private void updateVersions(ServletContext servletContext) {

    try {/*from  w w  w  . j a  v  a2 s. com*/
        LabelValueBean versionBean = new LabelValueBean(appBean.getVersion(), "");
        LabelValueBean versionDateBean = new LabelValueBean(appBean.getVersionDate(), "");
        // Update the version in the database
        Map<Integer, Object> siteBeanValues = new HashMap<Integer, Object>();
        siteBeanValues.put(TSiteBean.COLUMNIDENTIFIERS.TRACKVERSION, appBean.getVersion());
        siteDAO.loadAndSaveSynchronized(siteBeanValues);

        servletContext.setAttribute("TVERSION", versionBean);
        servletContext.setAttribute("TVERSIONDATE", versionDateBean);

    } catch (Exception e) {
        // no version
        servletContext.setAttribute("TVERSION", new LabelValueBean("4.X", ""));
        servletContext.setAttribute("TVERSIONDATE", new LabelValueBean("?", ""));
    }

}

From source file:com.sun.faces.util.Util.java

/**
 * Verify the existence of all the factories needed by faces.  Create
 * and install the default RenderKit into the ServletContext. <P>
 *
 * @see javax.faces.FactoryFinder/* w ww  .  ja v a  2  s. c  o m*/
 */

public static void verifyFactoriesAndInitDefaultRenderKit(ServletContext context) throws FacesException {
    RenderKitFactory renderKitFactory = null;
    LifecycleFactory lifecycleFactory = null;
    FacesContextFactory facesContextFactory = null;
    ApplicationFactory applicationFactory = null;
    RenderKit defaultRenderKit = null;

    renderKitFactory = (RenderKitFactory) FactoryFinder.getFactory(FactoryFinder.RENDER_KIT_FACTORY);
    Util.doAssert(null != renderKitFactory);

    lifecycleFactory = (LifecycleFactory) FactoryFinder.getFactory(FactoryFinder.LIFECYCLE_FACTORY);
    Util.doAssert(null != lifecycleFactory);

    facesContextFactory = (FacesContextFactory) FactoryFinder.getFactory(FactoryFinder.FACES_CONTEXT_FACTORY);
    Util.doAssert(null != facesContextFactory);

    applicationFactory = (ApplicationFactory) FactoryFinder.getFactory(FactoryFinder.APPLICATION_FACTORY);
    Util.doAssert(null != applicationFactory);

    defaultRenderKit = renderKitFactory.getRenderKit(null, RenderKitFactory.HTML_BASIC_RENDER_KIT);
    if (defaultRenderKit == null) {
        // create default renderkit if doesn't exist
        //
        defaultRenderKit = new RenderKitImpl();
        renderKitFactory.addRenderKit(RenderKitFactory.HTML_BASIC_RENDER_KIT, defaultRenderKit);
    }

    context.setAttribute(RIConstants.HTML_BASIC_RENDER_KIT, defaultRenderKit);

    context.setAttribute(RIConstants.ONE_TIME_INITIALIZATION_ATTR, RIConstants.ONE_TIME_INITIALIZATION_ATTR);
}

From source file:uk.ac.open.kmi.forge.ptAnywhere.api.http.APIApplication.java

protected void configSwagger(ServletContext context, String appPath) {
    register(ApiListingResource.class);
    register(SwaggerSerializers.class);

    final ReflectiveJaxrsScanner scanner = new ReflectiveJaxrsScanner();
    scanner.setResourcePackage(getClass().getPackage().getName());
    ScannerFactory.setScanner(scanner);//from   w  w w  .j  a  va2  s .  c  o  m

    // It would be clearer to use the SwaggerDefinition annotation, but I does not seem to work
    // and I cannot find a working example in the official documentation.
    final Info info = new Info().title("PTAnywhere API").description("API for consuming PTAnywhere.")
            .version("1.0.1")
            //.termsOfService("http://swagger.io/terms/")
            .contact(new Contact().name("Aitor Gomez-Goiri").email(
                    "aitor.gomez-goiri@open.ac.uk"));/*
                                                     .license(new License()
                                                     .name("Apache 2.0")
                                                     .url("http://www.apache.org/licenses/LICENSE-2.0.html"));*/
    final Swagger swagger = new Swagger().info(info).basePath(appPath + "v1");
    swagger.tag(new Tag().name("session").description("Operations to manage sessions"));
    swagger.tag(new Tag().name("network").description("Network topology related operations"));
    swagger.tag(new Tag().name("device").description("Device-centric operations"));
    context.setAttribute("swagger", swagger);
}

From source file:be.fedict.eid.idp.protocol.openid.AbstractOpenIDProtocolService.java

private ServerManager getServerManager(HttpServletRequest request) {

    HttpSession httpSession = request.getSession();
    ServletContext servletContext = httpSession.getServletContext();
    ServerManager serverManager = (ServerManager) servletContext.getAttribute(getServiceManagerAttribute());
    if (null != serverManager) {
        return serverManager;
    }/* www  . j a  v  a 2 s .  com*/
    LOG.debug("creating an OpenID server manager");
    serverManager = new ServerManager();
    /*
     * Important that the shared association store and the private
     * association store are different. See also:
     * http://code.google.com/p/openid4java/source/detail?r=738
     */
    serverManager.setSharedAssociations(new InMemoryServerAssociationStore());
    serverManager.setPrivateAssociations(new InMemoryServerAssociationStore());
    String location = "https://" + request.getServerName();
    if (request.getServerPort() != 443) {
        location += ":" + request.getServerPort();
    }
    location += "/eid-idp";
    String opEndpointUrl = location + "/protocol/" + getPath();
    LOG.debug("OP endpoint URL: " + opEndpointUrl);
    serverManager.setOPEndpointUrl(opEndpointUrl);
    servletContext.setAttribute(getServiceManagerAttribute(), serverManager);
    return serverManager;
}

From source file:org.apache.velocity.tools.view.UiDependencyTool.java

public void configure(Map params) {
    ServletContext app = (ServletContext) params.get(ViewContext.SERVLET_CONTEXT_KEY);
    LOG = (Log) params.get(ToolContext.LOG_KEY);

    HttpServletRequest request = (HttpServletRequest) params.get(ViewContext.REQUEST);
    context = request.getContextPath();/*from   ww w .  ja v a  2  s .  c o m*/

    String file = (String) params.get(SOURCE_FILE_KEY);
    if (file == null) {
        file = DEFAULT_SOURCE_FILE;
    } else {
        debug("Loading file: %s", file);
    }

    synchronized (app) {
        // first, see if we've already read this file
        groups = (Map<String, Group>) app.getAttribute(GROUPS_KEY_SPACE + file);
        if (groups == null) {
            groups = new LinkedHashMap<String, Group>();
            // only require file presence, if one is specified
            read(file, (file != DEFAULT_SOURCE_FILE));
            app.setAttribute(GROUPS_KEY_SPACE + file, groups);
            if (types != DEFAULT_TYPES) {
                app.setAttribute(TYPES_KEY_SPACE + file, types);
            }
        } else {
            // load any custom types too
            List<Type> alt = (List<Type>) app.getAttribute(TYPES_KEY_SPACE + file);
            if (alt != null) {
                types = alt;
            }
        }
    }
}

From source file:org.apache.catalina.loader.WebappLoader.java

/**
 * Set the appropriate context attribute for our class path.  This
 * is required only because Jasper depends on it.
 *///from   w  ww .j  a v  a 2 s .  co m
private void setClassPath() {

    // Validate our current state information
    if (!(container instanceof Context))
        return;
    ServletContext servletContext = ((Context) container).getServletContext();
    if (servletContext == null)
        return;

    if (container instanceof StandardContext) {
        String baseClasspath = ((StandardContext) container).getCompilerClasspath();
        if (baseClasspath != null) {
            servletContext.setAttribute(Globals.CLASS_PATH_ATTR, baseClasspath);
            return;
        }
    }

    StringBuffer classpath = new StringBuffer();

    // Assemble the class path information from our class loader chain
    ClassLoader loader = getClassLoader();
    int layers = 0;
    int n = 0;
    while (loader != null) {
        if (!(loader instanceof URLClassLoader)) {
            String cp = getClasspath(loader);
            if (cp == null) {
                log.info("Unknown loader " + loader + " " + loader.getClass());
                break;
            } else {
                if (n > 0)
                    classpath.append(File.pathSeparator);
                classpath.append(cp);
                n++;
            }
            break;
            //continue;
        }
        URL repositories[] = ((URLClassLoader) loader).getURLs();
        for (int i = 0; i < repositories.length; i++) {
            String repository = repositories[i].toString();
            if (repository.startsWith("file://"))
                repository = repository.substring(7);
            else if (repository.startsWith("file:"))
                repository = repository.substring(5);
            else if (repository.startsWith("jndi:"))
                repository = servletContext.getRealPath(repository.substring(5));
            else
                continue;
            if (repository == null)
                continue;
            if (n > 0)
                classpath.append(File.pathSeparator);
            classpath.append(repository);
            n++;
        }
        loader = loader.getParent();
        layers++;
    }

    this.classpath = classpath.toString();

    // Store the assembled class path as a servlet context attribute
    servletContext.setAttribute(Globals.CLASS_PATH_ATTR, classpath.toString());

}

From source file:org.iterx.miru.support.servlet.dispatcher.context.BootstrapServletContextListener.java

public void contextInitialized(ServletContextEvent servletContextEvent) {

    try {/*from   w  ww  .  ja v  a 2  s . co m*/
        DispatcherApplicationContext applicationContext;
        ApplicationContext parentApplicationContext;
        ServletContext servletContext;
        String parameter;
        String path;
        int next;

        parentApplicationContext = null;
        servletContext = servletContextEvent.getServletContext();

        path = resolveContextPath(servletContext);
        next = path.length();
        while ((next = path.lastIndexOf('/', next - 1)) > -1) {
            if ((parentApplicationContext = (ApplicationContext) contexts.get(path.substring(0, next))) != null)
                break;
        }

        applicationContext = ((parentApplicationContext != null)
                ? new ServletDispatcherApplicationContext(parentApplicationContext, servletContext)
                : new ServletDispatcherApplicationContext(servletContext));

        if ((parameter = servletContext.getInitParameter(ServletDispatcherApplicationContext.BEANS)) != null
                && applicationContext instanceof Loadable) {
            URL url;

            if ((url = (servletContext.getResource(parameter))) != null)
                ((Loadable) applicationContext).load(new UriStreamResource(url.toURI()));
            else
                throw new IOException("Invalid stream [" + parameter + "]");

        }
        if (inheritable) {
            synchronized (contexts) {
                contexts.put(path, applicationContext);
            }
        }

        servletContext.setAttribute((DispatcherApplicationContext.class).getName(), applicationContext);
    } catch (Exception e) {
        e.printStackTrace();
        LOGGER.error("Initialisation failed.", e);
        throw new RuntimeException("Initialisation failed.", e);
    }

}

From source file:org.mifos.framework.ApplicationInitializer.java

public void setAttributesOnContext(ServletContext servletContext) throws TaskSystemException {
    // FIXME: replace with Spring-managed beans
    final MifosScheduler mifosScheduler = new MifosScheduler();
    final ShutdownManager shutdownManager = new ShutdownManager();

    Configuration.getInstance();//  w ww .  j av a  2s .  co  m
    configureAuditLogValues(Localization.getInstance().getConfiguredLocale());
    LocaleSetting configLocale = new LocaleSetting();

    @SuppressWarnings("deprecation")
    final UserLocale userLocale = new UserLocale(
            ApplicationContextProvider.getBean(PersonnelServiceFacade.class));

    if (servletContext != null) {
        mifosScheduler.initialize();
        servletContext.setAttribute(MifosScheduler.class.getName(), mifosScheduler);
        servletContext.setAttribute(ShutdownManager.class.getName(), shutdownManager);
        servletContext.setAttribute(LocaleSetting.class.getSimpleName(), configLocale);
        servletContext.setAttribute(UserLocale.class.getSimpleName(), userLocale);
    }
}

From source file:com.openkm.servlet.admin.DatabaseQueryServlet.java

/**
 * Execute Hibernate query//from ww w . j a v a  2 s. c  om
 */
private void executeHibernate(Session session, String qs, boolean showSql, ServletContext sc,
        HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, HibernateException, DatabaseException, IllegalAccessException,
        InvocationTargetException, NoSuchMethodException {
    StringTokenizer st = new StringTokenizer(qs, "\n\r");
    List<DbQueryGlobalResult> globalResults = new ArrayList<DbQueryGlobalResult>();

    // For each query line
    while (st.hasMoreTokens()) {
        String tk = st.nextToken().trim();

        if (tk.toUpperCase().startsWith("--") || tk.equals("") || tk.equals("\r")) {
            // Is a comment, so ignore it
        } else {
            if (tk.endsWith(";")) {
                tk = tk.substring(0, tk.length() - 1);
            }

            globalResults.add(executeHQL(session, tk, showSql, null));
        }
    }

    sc.setAttribute("exception", null);
    sc.setAttribute("showSql", showSql);
    sc.setAttribute("globalResults", globalResults);
    sc.getRequestDispatcher("/admin/database_query.jsp").forward(request, response);
}