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:org.apache.wookie.server.ContextListener.java

public void contextInitialized(ServletContextEvent event) {
    try {/*  ww w .  ja va  2 s .c o m*/
        ServletContext context = event.getServletContext();

        /* 
         *  load the widgetserver.properties file and put it into this context
         *  as an attribute 'properties' available to all resources
         */
        PropertiesConfiguration configuration;
        File localPropsFile = new File(
                System.getProperty("user.dir") + File.separator + "local.widgetserver.properties");
        if (localPropsFile.exists()) {
            configuration = new PropertiesConfiguration(localPropsFile);
            _logger.info("Using local widget server properties file: " + localPropsFile.toString());
        } else {
            configuration = new PropertiesConfiguration("widgetserver.properties");
            configuration.setFile(localPropsFile);
            configuration.save();
            _logger.info("Using default widget server properties, configure your local server using: "
                    + localPropsFile.toString());
        }
        context.setAttribute("properties", (Configuration) configuration);

        /*
         * Merge in system properties overrides
         */
        Iterator<Object> systemKeysIter = System.getProperties().keySet().iterator();
        while (systemKeysIter.hasNext()) {
            String key = systemKeysIter.next().toString();
            if (configuration.containsKey(key) || key.startsWith("widget.")) {
                String setting = configuration.getString(key);
                String override = System.getProperty(key);
                if ((override != null) && (override.length() > 0) && !override.equals(setting)) {
                    configuration.setProperty(key, override);
                    if (setting != null) {
                        _logger.info("Overridden server configuration property: " + key + "=" + override);
                    }
                }
            }
        }

        /*
         * Initialize persistence manager factory now, not on first request
         */
        PersistenceManagerFactory.initialize(configuration);

        /*
         * Initialise the locale handler
         */
        LocaleHandler.getInstance().initialize(configuration);
        final Locale locale = new Locale(configuration.getString("widget.default.locale"));
        final Messages localizedMessages = LocaleHandler.getInstance().getResourceBundle(locale);

        /* 
        *  load the opensocial.properties file and put it into this context
        *  as an attribute 'opensocial' available to all resources
        */
        PropertiesConfiguration opensocialConfiguration;
        File localOpenSocialPropsFile = new File(
                System.getProperty("user.dir") + File.separator + "local.opensocial.properties");
        if (localOpenSocialPropsFile.exists()) {
            opensocialConfiguration = new PropertiesConfiguration(localOpenSocialPropsFile);
            _logger.info("Using local open social properties file: " + localOpenSocialPropsFile.toString());
        } else {
            opensocialConfiguration = new PropertiesConfiguration("opensocial.properties");
            opensocialConfiguration.setFile(localOpenSocialPropsFile);
            opensocialConfiguration.save();
            _logger.info("Using default open social properties, configure your local server using: "
                    + localOpenSocialPropsFile.toString());
        }
        context.setAttribute("opensocial", (Configuration) opensocialConfiguration);

        /*
         * Load installed features
         */
        PropertiesConfiguration featuresConfiguration;
        File localFeaturesPropsFile = new File(
                System.getProperty("user.dir") + File.separator + "local.features.properties");
        if (localFeaturesPropsFile.exists()) {
            featuresConfiguration = new PropertiesConfiguration(localFeaturesPropsFile);
            _logger.info("Loading local features file: " + localOpenSocialPropsFile.toString());
        } else {
            featuresConfiguration = new PropertiesConfiguration("features.properties");
            featuresConfiguration.setFile(localFeaturesPropsFile);
            featuresConfiguration.save();
            _logger.info("Loading default features, configure your local server using: "
                    + localFeaturesPropsFile.toString());
        }
        FeatureLoader.loadFeatures(featuresConfiguration);

        /*
         * Run diagnostics
         */
        Diagnostics.run(context, configuration);

        /*
         * Start hot-deploy widget watcher
         */
        if (configuration.getBoolean("widget.hot_deploy")) {
            startWatcher(context, configuration, localizedMessages);
        } else {
            _logger.info(localizedMessages.getString("WidgetHotDeploy.0"));
        }
    } catch (ConfigurationException ex) {
        _logger.error("ConfigurationException thrown: " + ex.toString());
    }
}

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

/**
 * Import into database/*from   ww w.  j a  va2  s .  com*/
 */
private void executeUpdate(Session session, byte[] data, ServletContext sc, HttpServletRequest request,
        HttpServletResponse response) throws SQLException, ServletException, IOException {
    log.debug("executeUpdate({}, {}, {})", new Object[] { session, request, response });
    List<DbQueryGlobalResult> globalResults = new ArrayList<DbQueryGlobalResult>();
    WorkerUpdate worker = new WorkerUpdate();
    worker.setData(data);
    session.doWork(worker);

    DbQueryGlobalResult gr = new DbQueryGlobalResult();
    gr.setColumns(null);
    gr.setResults(null);
    gr.setSql(null);
    gr.setRows(worker.getRows());
    gr.setErrors(worker.getErrors());
    globalResults.add(gr);

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

    log.debug("executeUpdate: void");
}

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

/**
 * Import into database/*from  ww w . jav  a 2  s .co m*/
 */
private void executeUpdate(Session session, byte[] data, ServletContext sc, HttpServletRequest request,
        HttpServletResponse response) throws SQLException, ServletException, IOException {
    log.debug("executeUpdate({}, {}, {})", new Object[] { session, request, response });
    List<GlobalResult> globalResults = new ArrayList<DatabaseQueryServlet.GlobalResult>();
    WorkerUpdate worker = new WorkerUpdate();
    worker.setData(data);
    session.doWork(worker);

    GlobalResult gr = new GlobalResult();
    gr.setColumns(null);
    gr.setResults(null);
    gr.setSql(null);
    gr.setRows(worker.getRows());
    gr.setErrors(worker.getErrors());
    globalResults.add(gr);

    sc.setAttribute("qs", null);
    sc.setAttribute("type", null);
    sc.setAttribute("globalResults", globalResults);
    sc.getRequestDispatcher("/admin/database_query.jsp").forward(request, response);

    log.debug("executeUpdate: void");
}

From source file:in.raster.oviyam.servlet.Validator.java

@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setCharacterEncoding("utf-8");
    response.setContentType("text/html;charset=utf-8");
    PrintWriter out = response.getWriter();

    /*AttributePrincipal principal = (AttributePrincipal) request.getUserPrincipal();
    String loginId=principal.getName();*/

    /*??*//*w  ww.  ja va 2 s.  co m*/
    String pid = (String) request.getParameter("PatientID").trim();
    if (pid == null || "".equals(pid)) {
        out.println("??!");
        out.close();
        return;
    }

    /*?????*/
    String r = dataAccess.getReportAddress(pid);
    /*?dcmpacs?*/
    //String r=dataAccess.addDicom("x");

    /*?*/
    Boolean a = dataAccess.checsIsExist(pid);
    if (!a) {
        out.println("?!");
        out.close();
        return;
    }

    /*????*/
    //boolean b=dataAccess.checkCheckId(loginId,pid);
    //if(!b)return;

    /**/
    /*PacsQueryLogModel pqlm = new PacsQueryLogModel();
    pqlm.setApplicationId(pid);
    pqlm.setDoctorId(loginId);
    dataAccess.addPacsLog(pqlm);*/

    AE ae;
    ServletContext servletContext = getServletContext();
    ServerConfiguration serverConfiguration;
    EchoService echoService;

    String agree = request.getParameter("agree");

    if (agree != null && agree.equals("agree")) {
        Cookie agreeCookie = new Cookie("agree", "agree");
        agreeCookie.setMaxAge(60 * 60 * 24 * 365);
        response.addCookie(agreeCookie);
    }

    try {
        ae = new AE();
        //assigns the serverConfiguration instance.         
        serverConfiguration = ae.getServerConfiguration();
        /*
         * writes the serverConfiguration instance in the servletContext (application scope).
         * So all the SERVLET classes and JSP pages can access the serverConfig attribute.
         * User can use either <jsp:useBean> tag or ${applicationScope.serverConfig} EL 
         * to access the serverConfig attribute. From SERVLET classes the User can use
         * the getServletContext().getAttribute("serverConfig") to access the serverConfiguration attribute.
         */
        servletContext.setAttribute("serverConfig", serverConfiguration);

        echoService = new EchoService();
        echoService.checkEcho();
        /*If the status of EchoService is failed then the request will be forwarded to 
         * EchoFailed.jsp. Otherwise, request is forwarded to oviyam7.jsp
         * 
         */
        if (echoService.getStatus().equals("Echo failed")) {
            /*
             * writes the echoURL(dcmProtocol://aeTitle@hostName:port) attribute in request instance.
             * and forwards the request and response object to EchoFailed.jsp .
             * echoFailed attribute can be accessed through either ${request.echoURL} or 
             * <% request.getAttribute("echoURL")%>
             */
            request.setAttribute("echoURL", ae.toString());
            request.getRequestDispatcher("EchoFailed.jsp").forward(request, response);
        } else {
            // forwards the request and response to oviyam7.jsp
            String studyUID = request.getParameter("studyUID");
            String seriesUID = request.getParameter("seriesUID");
            String patientID = request.getParameter("patientID");
            if (studyUID != null && studyUID.length() <= 0) {
                request.setAttribute("param", "studyUID");
                request.getRequestDispatcher("InvalidParam.jsp").forward(request, response);
                log.error("Invalid studyUID parameter for Oviyam.");
            } else if (seriesUID != null && seriesUID.length() <= 0) {
                request.setAttribute("param", "seriesUID");
                request.getRequestDispatcher("InvalidParam.jsp").forward(request, response);
                log.error("Invalid seriesUID parameter for Oviyam.");
            } else if (patientID != null && patientID.length() <= 0) {
                request.setAttribute("param", "patientID");
                request.getRequestDispatcher("InvalidParam.jsp").forward(request, response);
                log.error("Invalid patientID parameter for Oviyam.");
            } else {
                request.getRequestDispatcher("oviyam7.jsp").forward(request, response);
            }
        }

    } catch (Exception e) {
        log.error(e.getMessage());

    }
}

From source file:com.ibm.jaggr.service.impl.AggregatorImpl.java

@Override
public void init(ServletConfig servletConfig) throws ServletException {
    super.init(servletConfig);

    final ServletContext context = servletConfig.getServletContext();

    // Set servlet context attributes for access though the request
    context.setAttribute(IAggregator.AGGREGATOR_REQATTRNAME, this);
}

From source file:org.jpublish.servlet.JPublishServlet.java

/**
 * Initialize the servlet.// ww w.j  a  v a  2s . c  o  m
 *
 * @param servletConfig The Servlet configuration
 * @throws ServletException
 */

public void init(ServletConfig servletConfig) throws ServletException {

    super.init(servletConfig);

    log.info("Initializing JPublish servlet; " + SiteContext.JPUBLISH_VERSION);

    ServletContext servletContext = getServletContext();

    String configLocation = servletConfig.getInitParameter("config");
    if (log.isDebugEnabled())
        log.debug("Config location: " + configLocation);

    // find the WEB-INF root
    String rootDir = servletContext.getRealPath("/");
    File contextRoot = new File(rootDir);
    File webInfPath = new File(contextRoot, "WEB-INF");

    // create the site context
    try {
        siteContext = new SiteContext(contextRoot, configLocation);
        servletContext.setAttribute(SiteContext.NAME, siteContext);
        siteContext.setWebInfPath(webInfPath);
        siteContext.setServletContext(servletContext);
        siteContext.setServletConfig(servletConfig);
        siteContext.setJPublishServlet(this);
        siteContext.init();
        formatParameterSupported = siteContext.getFormatChangeParameterName() != null
                && siteContext.getFormatChangeParameterName().trim().length() > 0;
    } catch (Exception e) {
        log.error("Error creating SiteContext: " + e.getMessage());
        throw new ServletException(e);
    }

    // set the ActionManager classpath
    ActionManager actionManager = siteContext.getActionManager();

    // configure BSF
    configureBSF();

    // construct the classpath for scripting support
    String classPath = constructClasspath(webInfPath);

    // configure classpath
    configureClasspath(classPath);

    // execute startup actions
    try {
        actionManager.executeStartupActions();
    } catch (Exception e) {
        log.error("Error executing startup actions: " + e.getMessage());
        throw new ServletException(e);
    }

    log.info("JPublish servlet initialized.");
}

From source file:com.liangc.hq.base.web.ConfiguratorListener.java

private void loadBuildNumber(ServletContext ctx) {
    final String SNAPSHOT_IDENTIFIER = "BUILD-SNAPSHOT";
    final String BUILD_DATE_FORMAT_OUTPUT = "yyyy-MM-dd";
    final String BUILD_DATE_FORMAT_INPUT = "MMM dd, yyyy";

    try {/* www.j a  v  a2 s.  c  om*/
        String version = ProductProperties.getVersion();

        if (version.contains(SNAPSHOT_IDENTIFIER)) {
            try {
                // Get build date, format into Date object...
                String date = ProductProperties.getBuildDate();
                DateFormat format = new SimpleDateFormat(BUILD_DATE_FORMAT_INPUT);
                Date buildDate = format.parse(date);

                // Take date object and format into different format for
                // display...
                format = new SimpleDateFormat(BUILD_DATE_FORMAT_OUTPUT);

                version += "-" + format.format(buildDate);
            } catch (ParseException e) {
                // Couldn't parse the date, so we fall back to using just
                // the version string...
                log.info("Couldn't parse the build date for display", e);
            }
        }

        ctx.setAttribute(Constants.APP_VERSION, version);
        ctx.setAttribute(Constants.APP_BUILD, ProductProperties.getBuildNumber());
    } catch (Exception e) {
        error("Unable to load product version", e);
    }
}

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

/**
 * Utility for upgrading the application
 *
 * @param context//from   w w w.j  a v  a 2 s  .  c o  m
 */
private void performUpgrade(ServletContext context) {
    Connection db = null;
    ConnectionPool commonCP = (ConnectionPool) context.getAttribute(Constants.CONNECTION_POOL);
    try {
        LOG.info("Upgrading the database...");

        // Share the preferences with the upgrade scripts
        context.setAttribute(Constants.APPLICATION_PREFS, this);

        // Determine the database connection to use
        ConnectionElement ce = new ConnectionElement();
        ce.setDriver(this.get(CONNECTION_DRIVER));
        ce.setUrl(this.get(CONNECTION_URL));
        ce.setUsername(this.get(CONNECTION_USER));
        ce.setPassword(this.get(CONNECTION_PASSWORD));

        // Retrieve a database connection
        db = commonCP.getConnection(ce, true);

        // Perform the upgrade
        UpgradeUtils.performUpgrade(db, context);

        // Persist the new version info
        save();

    } catch (Exception e) {
        LOG.error("performUpgrade", e);
        e.printStackTrace(System.out);
    } finally {
        commonCP.free(db);
    }
}

From source file:org.rhq.enterprise.gui.admin.config.EditConfigAction.java

@Override
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    ActionForward forward = checkSubmit(request, mapping, form);
    if (forward != null) {
        return forward;
    }//from ww  w.java 2  s.  c  o m

    Subject whoami = WebUtility.getSubject(request);
    SystemConfigForm cForm = (SystemConfigForm) form;
    ServletContext ctx = getServlet().getServletContext();
    SystemManagerLocal systemManager = LookupUtil.getSystemManager();

    if (cForm.isOkClicked()) {
        try {
            log.trace("Getting config");
            Properties props = cForm.saveConfigProperties(
                    systemManager.getSystemConfiguration(LookupUtil.getSubjectManager().getOverlord()));

            log.trace("Setting config");
            if (LookupUtil.getAuthorizationManager().isSystemSuperuser(whoami)
                    && request.getParameter("debug") != null) {
                /* 
                 * if the superuser is logged in and the "debug" url parameter is present,
                 * validation will be skipped to enable special administration functions
                 * that might violate the standard restrictions
                 */
                systemManager.setSystemConfiguration(whoami, props, true);
            } else {
                systemManager.setSystemConfiguration(whoami, props, false);
            }

            log.trace("Restarting config service");

            systemManager.reconfigureSystem(whoami);

            if (cForm.getLdapEnabled() != null) {
                // cache in servlet context
                ctx.setAttribute(AttrConstants.JAAS_PROVIDER_CTX_ATTR, RHQConstants.LDAPJAASProvider);
            } else {
                ctx.setAttribute(AttrConstants.JAAS_PROVIDER_CTX_ATTR, RHQConstants.JDBCJAASProvider);
            }
        } catch (Exception e) {
            String throwableMsgs = ThrowableUtil.getAllMessages(e, true);
            log.error("Failed to store server settings. Cause: " + throwableMsgs);
            RequestUtils.setErrorObject(request, "admin.config.confirm.saveSettingsFailure", throwableMsgs);
            return returnFailure(request, mapping);
        }
    }

    RequestUtils.setConfirmation(request, "admin.config.confirm.saveSettings");
    return returnSuccess(request, mapping);
}