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:au.edu.uq.cmm.paul.servlet.WebUIController.java

@Override
public void setServletContext(ServletContext servletContext) {
    LOG.debug("Setting the timezone (" + TimeZone.getDefault().getID() + ") in the servlet context");
    servletContext.setAttribute("javax.servlet.jsp.jstl.fmt.timeZone", TimeZone.getDefault());
    buildInfo = loadBuildInfo(servletContext);
}

From source file:com.concursive.connect.config.ApplicationPrefs.java

/**
 * Description of the Method//w  w w .ja  va  2s . co  m
 *
 * @param context     Description of the Parameter
 * @param fileLibrary Description of the Parameter
 */
private void verifyKey(ServletContext context, String fileLibrary) {
    // Configure the encryption key
    Key key = PrivateString.generateKeyFile(fileLibrary + "team.key");
    context.setAttribute(TEAM_KEY, key);
}

From source file:org.intermine.web.struts.InitialiserPlugin.java

/**
 *  Load user-friendly class description
 *///from ww  w .  j  a  va 2s  . c  o m
private void loadClassDescriptions(ServletContext servletContext) {
    Properties classDescriptions = new Properties();
    try {
        classDescriptions.load(servletContext.getResourceAsStream("/WEB-INF/classDescriptions.properties"));
    } catch (Exception e) {
        LOG.error("Error loading class descriptions", e);
        blockingErrorKeys.put("errors.init.classDescriptions", null);
    }
    servletContext.setAttribute("classDescriptions", classDescriptions);
}

From source file:org.ambraproject.configuration.WebAppListener.java

/**
 * Initialize the configuration singleton since this web application is getting deployed.<p>
 *
 * By default, WebAppListener uses the default ConfigurationStore initialization. This
 * usually means using /etc/.../ambra.xml. This can be overridden by setting the
 * org.ambraproject.configuration system property or webapp context variable to a URL or a name
 * resolvable as a resource.//from ww  w . j  a va2  s.c  o  m
 *
 * @param event The servlet event associated with initializing this context
 * @throws Error on non-recoverable config load error
 */
public void contextInitialized(ServletContextEvent event) {
    ServletContext context = event.getServletContext();
    FactoryConfig config = getFactoryConfig(context);

    try {
        URL url;

        // Locate the config url.
        if (config.name.startsWith("/WEB-INF")) {
            url = context.getResource(config.name);

            if (url == null)
                throw new MalformedURLException("'" + config.name + "' not found in the web-app context");
        } else {
            try {
                // First see if it is a valid URL
                url = new URL(config.name);
            } catch (MalformedURLException e) {
                // Otherwise, load as a resource
                url = WebAppListener.class.getResource(config.name);
                if (url == null)
                    throw e;
            }
        }

        // Now load the config
        log.info("Loading '" + url + "' (" + config.name + ") configured via " + config.source);
        ConfigurationStore.getInstance().loadConfiguration(url);

        // Setup an application scope attribute that something like freemarker or struts might use
        context.setAttribute("config", ConfigurationStore.getInstance().getConfiguration());
    } catch (MalformedURLException e) {
        log.fatal(config.name + " defined by " + config.source + " is not a valid URL or resource", e);
        throw new Error("Failed to load configuration", e);
    } catch (ConfigurationException e) {
        log.fatal("Failed to initialize configuration factory.", e);
        throw new Error("Failed to load configuration", e);
    }
}

From source file:org.sakaiproject.component.section.SectionManagerHibernateImpl.java

public ExternalIntegrationConfig getConfiguration(Object obj) {
    HttpServletRequest request = (HttpServletRequest) obj;
    ServletContext context = request.getSession(true).getServletContext();
    ExternalIntegrationConfig config = (ExternalIntegrationConfig) context.getAttribute(CONFIGURATION_KEY);

    // Set the default if the configuration string is missing
    if (config == null) {
        config = ExternalIntegrationConfig.MANUAL_DEFAULT;
        context.setAttribute(CONFIGURATION_KEY, config);
    }/*from   www. j  av a 2 s  . co m*/

    return config;
}

From source file:com.ikon.servlet.admin.PropertyGroupsServlet.java

/**
 * List property groups/*from  w w  w . ja v a  2  s  .c  om*/
 * @throws Exception 
 */
private void list(HttpServletRequest request, HttpServletResponse response) throws Exception {
    log.debug("list({}, {})", new Object[] { request, response });
    ServletContext sc = getServletContext();

    XMLUtils utils = new XMLUtils(PROPERTY_GROUPS_XML);
    if (utils.isPGXMLEmpty()) {
        sc.getRequestDispatcher("/admin/property_group_register.jsp").forward(request, response);
    } else {

        FormUtils.resetPropertyGroupsForms();
        OKMPropertyGroup okmPropGroups = OKMPropertyGroup.getInstance();
        List<PropertyGroup> groups = okmPropGroups.getAllGroups(null);
        Map<PropertyGroup, List<Map<String, String>>> pGroups = new LinkedHashMap<PropertyGroup, List<Map<String, String>>>();

        for (PropertyGroup group : groups) {
            List<FormElement> mData = okmPropGroups.getPropertyGroupForm(null, group.getName());
            List<Map<String, String>> fMaps = new ArrayList<Map<String, String>>();

            for (FormElement fe : mData) {
                fMaps.add(FormUtils.toString(fe));
            }

            pGroups.put(group, fMaps);
        }

        sc.setAttribute("pGroups", pGroups);
        sc.getRequestDispatcher("/admin/property_groups_list.jsp").forward(request, response);

        // Activity log
        UserActivity.log(request.getRemoteUser(), "ADMIN_PROPERTY_GROUP_LIST", null, null, null);
    }
    log.debug("list: void");
}

From source file:fll.web.developer.ReplaceChallengeDescriptor.java

protected void processRequest(final HttpServletRequest request, final HttpServletResponse response,
        final ServletContext application, final HttpSession session) throws IOException, ServletException {
    if (LOGGER.isTraceEnabled()) {
        LOGGER.trace("Top of ReplaceChallengeDescriptor.doPost");
    }/*from www  .ja  v  a2 s.  co  m*/

    final StringBuilder message = new StringBuilder();

    Connection connection = null;
    try {
        final DataSource datasource = ApplicationAttributes.getDataSource(application);
        connection = datasource.getConnection();

        final Document curDoc = ApplicationAttributes.getChallengeDocument(application);

        // must be first to ensure the form parameters are set
        UploadProcessor.processUpload(request);

        // create a new empty database from an XML descriptor
        final FileItem xmlFileItem = (FileItem) request.getAttribute("xmldoc");

        final Document newDoc = ChallengeParser
                .parse(new InputStreamReader(xmlFileItem.getInputStream(), Utilities.DEFAULT_CHARSET));

        final String compareMessage = ChallengeParser.compareStructure(curDoc, newDoc);
        if (null == compareMessage) {
            GenerateDB.insertOrUpdateChallengeDocument(newDoc, connection);
            application.setAttribute(ApplicationAttributes.CHALLENGE_DOCUMENT, newDoc);
            message.append("<p><i>Successfully replaced challenge descriptor</i></p>");
        } else {
            message.append("<p class='error'>");
            message.append(compareMessage);
            message.append("</p>");
        }
    } catch (final FileUploadException fue) {
        message.append("<p class='error'>Error handling the file upload: " + fue.getMessage() + "</p>");
        LOGGER.error(fue, fue);
    } catch (final SQLException sqle) {
        message.append("<p class='error'>Error talking to the database: " + sqle.getMessage() + "</p>");
        LOGGER.error(sqle, sqle);
        throw new RuntimeException("Error talking to the database", sqle);
    } finally {
        SQLFunctions.close(connection);
    }

    if (LOGGER.isTraceEnabled()) {
        LOGGER.trace("Top of ReplaceChallengeDescriptor.doPost");
    }

    session.setAttribute("message", message.toString());
    response.sendRedirect(response.encodeRedirectURL("index.jsp"));

}

From source file:org.pentaho.platform.web.http.context.HsqldbStartupListener.java

public void contextInitialized(ServletContextEvent sce) {
    ServletContext ctx = sce.getServletContext();

    logger.debug("Starting HSQLDB Embedded Listener"); //$NON-NLS-1$
    HsqlDatabaseStarterBean starterBean = new HsqlDatabaseStarterBean();
    String port = ctx.getInitParameter("hsqldb-port"); //$NON-NLS-1$
    int portNum = -1;
    if (port != null) {
        logger.debug(String.format("Port override specified: %s", port)); //$NON-NLS-1$
        try {/*from w ww  .  j ava  2 s. c o m*/
            portNum = Integer.parseInt(port);
            starterBean.setPort(portNum);
        } catch (NumberFormatException ex) {
            logger.error(Messages.getErrorString("HsqldbStartupListener.ERROR_0004_INVALID_PORT", "9001")); //$NON-NLS-1$
            port = null; // force check default port
        }
    }

    starterBean.setDatabases(getDatabases(ctx));

    String sampleDataAllowPortFailover = ctx.getInitParameter("hsqldb-allow-port-failover"); //$NON-NLS-1$
    if ((sampleDataAllowPortFailover != null) && (sampleDataAllowPortFailover.equalsIgnoreCase("true"))) { //$NON-NLS-1$
        logger.debug(String.format("Allow Port Failover specified")); //$NON-NLS-1$
        starterBean.setAllowPortFailover(true);
    }

    if (starterBean.start()) {
        ctx.setAttribute("hsqldb-starter-bean", starterBean); //$NON-NLS-1$
    }

}

From source file:org.apache.struts2.views.freemarker.FreemarkerManager.java

protected ScopesHashModel buildScopesHashModel(ServletContext servletContext, HttpServletRequest request,
        HttpServletResponse response, ObjectWrapper wrapper, ValueStack stack) {
    ScopesHashModel model = new ScopesHashModel(wrapper, servletContext, request, stack);

    // Create hash model wrapper for servlet context (the application)
    // only need one thread to do this once, per servlet context
    synchronized (servletContext) {
        ServletContextHashModel servletContextModel = (ServletContextHashModel) servletContext
                .getAttribute(ATTR_APPLICATION_MODEL);

        if (servletContextModel == null) {

            GenericServlet servlet = JspSupportServlet.jspSupportServlet;
            // TODO if the jsp support  servlet isn't load-on-startup then it won't exist
            // if it hasn't been accessed, and a JSP page is accessed
            if (servlet != null) {
                servletContextModel = new ServletContextHashModel(servlet, wrapper);
                servletContext.setAttribute(ATTR_APPLICATION_MODEL, servletContextModel);
                TaglibFactory taglibs = new TaglibFactory(servletContext);
                servletContext.setAttribute(ATTR_JSP_TAGLIBS_MODEL, taglibs);
            }//from  ww w .j a va 2 s  . c  o m

        }

        model.put(KEY_APPLICATION, servletContextModel);
        model.put(KEY_JSP_TAGLIBS, (TemplateModel) servletContext.getAttribute(ATTR_JSP_TAGLIBS_MODEL));
    }

    // Create hash model wrapper for session
    HttpSession session = request.getSession(false);
    if (session != null) {
        model.put(KEY_SESSION_MODEL, new HttpSessionHashModel(session, wrapper));
    } else {
        // no session means no attributes ???
        //            model.put(KEY_SESSION_MODEL, new SimpleHash());
    }

    // Create hash model wrapper for the request attributes
    HttpRequestHashModel requestModel = (HttpRequestHashModel) request.getAttribute(ATTR_REQUEST_MODEL);

    if ((requestModel == null) || (requestModel.getRequest() != request)) {
        requestModel = new HttpRequestHashModel(request, response, wrapper);
        request.setAttribute(ATTR_REQUEST_MODEL, requestModel);
    }

    model.put(KEY_REQUEST_MODEL, requestModel);

    // Create hash model wrapper for request parameters
    HttpRequestParametersHashModel reqParametersModel = (HttpRequestParametersHashModel) request
            .getAttribute(ATTR_REQUEST_PARAMETERS_MODEL);
    if (reqParametersModel == null || requestModel.getRequest() != request) {
        reqParametersModel = new HttpRequestParametersHashModel(request);
        request.setAttribute(ATTR_REQUEST_PARAMETERS_MODEL, reqParametersModel);
    }
    model.put(KEY_REQUEST_PARAMETER_MODEL, reqParametersModel);

    return model;
}