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.amplafi.jawr.maven.JawrMojo.java

private void setupJawrConfig(ServletConfig config, ServletContext context, final Map<String, Object> attributes,
        final Response respData) {
    expect(config.getServletContext()).andReturn(context).anyTimes();
    expect(config.getServletName()).andReturn("maven-jawr-plugin").anyTimes();

    context.log(isA(String.class));
    expectLastCall().anyTimes();/*from w  w w  .  j  a  va  2 s  .com*/

    expect(context.getResourcePaths(isA(String.class))).andAnswer(new IAnswer<Set>() {

        public Set<String> answer() throws Throwable {
            final Set<String> set = new HashSet<String>();

            // hack to disallow orphan bundles
            Exception e = new Exception();
            for (StackTraceElement trace : e.getStackTrace()) {
                if (trace.getClassName().endsWith("OrphanResourceBundlesMapper")) {
                    return set;
                }
            }

            String path = (String) EasyMock.getCurrentArguments()[0];
            File file = new File(getRootPath() + path);

            if (file.exists() && file.isDirectory()) {
                for (String one : file.list()) {
                    set.add(path + one);
                }
            }

            return set;
        }

    }).anyTimes();

    expect(context.getResourceAsStream(isA(String.class))).andAnswer(new IAnswer<InputStream>() {

        public InputStream answer() throws Throwable {
            String path = (String) EasyMock.getCurrentArguments()[0];
            File file = new File(getRootPath(), path);
            return new FileInputStream(file);
        }

    }).anyTimes();

    expect(context.getAttribute(isA(String.class))).andAnswer(new IAnswer<Object>() {

        public Object answer() throws Throwable {
            return attributes.get(EasyMock.getCurrentArguments()[0]);
        }

    }).anyTimes();

    context.setAttribute(isA(String.class), isA(Object.class));
    expectLastCall().andAnswer(new IAnswer<Object>() {

        public Object answer() throws Throwable {
            String key = (String) EasyMock.getCurrentArguments()[0];
            Object value = EasyMock.getCurrentArguments()[1];
            attributes.put(key, value);
            return null;
        }

    }).anyTimes();

    expect(config.getInitParameterNames()).andReturn(new Enumeration<String>() {

        public boolean hasMoreElements() {
            return false;
        }

        public String nextElement() {
            return null;
        }

    }).anyTimes();

    expect(config.getInitParameter(JawrConstant.TYPE_INIT_PARAMETER)).andAnswer(new IAnswer<String>() {
        public String answer() throws Throwable {
            return respData == null ? null : respData.getType();
        }
    }).anyTimes();

    expect(config.getInitParameter("configLocation")).andReturn(getConfigLocation()).anyTimes();
    expect(config.getInitParameter("configPropertiesSourceClass")).andReturn(null).anyTimes();
}

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

private void configureSystemSettings(ServletContext context) {
    LOG.info("configureSystemSettings");
    SystemSettings systemSettings = new SystemSettings();
    try {/*w  ww  .  jav  a  2 s . c  o m*/
        // Load the settings...
        InputStream source = null;
        // Look in build.properties, or use default
        String settingsFile = this.get(SYSTEM_SETTINGS_FILE);
        if (settingsFile != null) {
            LOG.info("SystemSettings path: " + this.get(FILE_LIBRARY_PATH) + settingsFile);
            source = new FileInputStream(this.get(FILE_LIBRARY_PATH) + settingsFile);
        } else {
            LOG.info("SystemSettings path: /WEB-INF/settings.xml");
            source = context.getResourceAsStream("/WEB-INF/settings.xml");
        }
        if (source != null) {
            LOG.info("Loading system settings...");
            XMLUtils xml = new XMLUtils(source);
            systemSettings.initialize(xml.getDocumentElement());
            source.close();
        }
    } catch (Exception e) {
        e.printStackTrace(System.out);
        LOG.error("System Settings Error", e);
    }
    context.setAttribute(Constants.SYSTEM_SETTINGS, systemSettings);
}

From source file:org.openmrs.web.Listener.java

/**
 * This method is called when the servlet context is initialized(when the Web Application is
 * deployed). You can initialize servlet context related data here.
 *
 * @param event//from w  w w.ja  va2 s  .  com
 */
@Override
public void contextInitialized(ServletContextEvent event) {
    Log log = LogFactory.getLog(Listener.class);

    log.debug("Starting the OpenMRS webapp");

    try {
        // validate the current JVM version
        OpenmrsUtil.validateJavaVersion();

        ServletContext servletContext = event.getServletContext();

        // pulled from web.xml.
        loadConstants(servletContext);

        // erase things in the dwr file
        clearDWRFile(servletContext);

        // Try to get the runtime properties
        Properties props = getRuntimeProperties();
        if (props != null) {
            // the user has defined a runtime properties file
            setRuntimePropertiesFound(true);
            // set props to the context so that they can be
            // used during sessionFactory creation
            Context.setRuntimeProperties(props);
        }

        Thread.currentThread().setContextClassLoader(OpenmrsClassLoader.getInstance());

        if (!setupNeeded()) {
            // must be done after the runtime properties are
            // found but before the database update is done
            copyCustomizationIntoWebapp(servletContext, props);

            //super.contextInitialized(event);
            // also see commented out line in contextDestroyed

            /** This logic is from ContextLoader.initWebApplicationContext.
             * Copied here instead of calling that so that the context is not cached
             * and hence not garbage collected
             */
            XmlWebApplicationContext context = (XmlWebApplicationContext) createWebApplicationContext(
                    servletContext);
            configureAndRefreshWebApplicationContext(context, servletContext);
            servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, context);

            WebDaemon.startOpenmrs(event.getServletContext());
        } else {
            setupNeeded = true;
        }

    } catch (Exception e) {
        setErrorAtStartup(e);
        log.fatal("Got exception while starting up: ", e);
    }

}

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

@Override
@SuppressWarnings("unchecked")
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    log.debug("doPost({}, {})", request, response);
    request.setCharacterEncoding("UTF-8");
    updateSessionManager(request);//from  w  w w .  j av  a2  s  . c o m
    String user = request.getRemoteUser();
    ServletContext sc = getServletContext();
    Session session = null;

    try {
        if (ServletFileUpload.isMultipartContent(request)) {
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            List<FileItem> items = upload.parseRequest(request);
            boolean showSql = false;
            String vtable = "";
            String type = "";
            String qs = "";
            byte[] data = null;

            for (Iterator<FileItem> it = items.iterator(); it.hasNext();) {
                FileItem item = it.next();

                if (item.isFormField()) {
                    if (item.getFieldName().equals("qs")) {
                        qs = item.getString("UTF-8");
                    } else if (item.getFieldName().equals("type")) {
                        type = item.getString("UTF-8");
                    } else if (item.getFieldName().equals("showSql")) {
                        showSql = true;
                    } else if (item.getFieldName().equals("vtables")) {
                        vtable = item.getString("UTF-8");
                    }
                } else {
                    data = item.get();
                }
            }

            if (!qs.equals("") && !type.equals("")) {
                session = HibernateUtil.getSessionFactory().openSession();
                sc.setAttribute("qs", qs);
                sc.setAttribute("type", type);

                if (type.equals("jdbc")) {
                    executeJdbc(session, qs, sc, request, response);

                    // Activity log
                    UserActivity.log(user, "ADMIN_DATABASE_QUERY_JDBC", null, null, qs);
                } else if (type.equals("hibernate")) {
                    executeHibernate(session, qs, showSql, sc, request, response);

                    // Activity log
                    UserActivity.log(user, "ADMIN_DATABASE_QUERY_HIBERNATE", null, null, qs);
                } else if (type.equals("metadata")) {
                    sc.setAttribute("vtable", vtable);
                    executeMetadata(session, qs, false, sc, request, response);

                    // Activity log
                    UserActivity.log(user, "ADMIN_DATABASE_QUERY_METADATA", null, null, qs);
                }
            } else if (data != null && data.length > 0) {
                sc.setAttribute("exception", null);
                session = HibernateUtil.getSessionFactory().openSession();
                executeUpdate(session, data, sc, request, response);

                // Activity log
                UserActivity.log(user, "ADMIN_DATABASE_QUERY_FILE", null, null, new String(data));
            } else {
                sc.setAttribute("qs", qs);
                sc.setAttribute("type", type);
                sc.setAttribute("showSql", showSql);
                sc.setAttribute("exception", null);
                sc.setAttribute("globalResults", new ArrayList<DbQueryGlobalResult>());
                sc.getRequestDispatcher("/admin/database_query.jsp").forward(request, response);
            }
        } else {
            // Edit table cell value
            String action = request.getParameter("action");
            String vtable = request.getParameter("vtable");
            String column = request.getParameter("column");
            String value = request.getParameter("value");
            String id = request.getParameter("id");

            if (action.equals("edit")) {
                int idx = column.indexOf('(');

                if (idx > 0) {
                    column = column.substring(idx + 1, idx + 6);
                }

                String hql = "update DatabaseMetadataValue dmv set dmv." + column + "='" + value
                        + "' where dmv.table='" + vtable + "' and dmv.id=" + id;
                log.info("HQL: {}", hql);
                session = HibernateUtil.getSessionFactory().openSession();
                int rows = session.createQuery(hql).executeUpdate();
                log.info("Rows affected: {}", rows);
            }
        }
    } catch (FileUploadException e) {
        sendError(sc, request, response, e);
    } catch (SQLException e) {
        sendError(sc, request, response, e);
    } catch (HibernateException e) {
        sendError(sc, request, response, e);
    } catch (DatabaseException e) {
        sendError(sc, request, response, e);
    } catch (IllegalAccessException e) {
        sendError(sc, request, response, e);
    } catch (InvocationTargetException e) {
        sendError(sc, request, response, e);
    } catch (NoSuchMethodException e) {
        sendError(sc, request, response, e);
    } finally {
        HibernateUtil.close(session);
    }
}

From source file:com.redsqirl.auth.UserInfoBean.java

/**
 * Method that will update the Java objects from the RMI registry.
 * @return/*  w w  w.j  a v  a2  s . com*/
 */
public String loginWithSessionSSH() {
    buildBackend = true;

    if (sessionSSH == null) {
        logger.error("SSH session null");
        return "failure";
    }

    FacesContext fCtx = FacesContext.getCurrentInstance();
    HttpSession session = (HttpSession) fCtx.getExternalContext().getSession(false);
    ServletContext sc = (ServletContext) fCtx.getExternalContext().getContext();

    //Make sure that tomcat reininitialize the session object after this function.
    fCtx.getExternalContext().getSessionMap().remove("#{canvasBean}");
    fCtx.getExternalContext().getSessionMap().remove("#{hdfsBean}");
    fCtx.getExternalContext().getSessionMap().remove("#{browserHdfsBean}");
    fCtx.getExternalContext().getSessionMap().remove("#{jdbcBean}");
    fCtx.getExternalContext().getSessionMap().remove("#{sshBean}");
    fCtx.getExternalContext().getSessionMap().remove("#{canvasModalBean}");
    fCtx.getExternalContext().getSessionMap().remove("#{configureTabsBean}");
    fCtx.getExternalContext().getSessionMap().remove("#{processManagerBean}");
    fCtx.getExternalContext().getSessionMap().remove("#{packageMngBean}");
    fCtx.getExternalContext().getSessionMap().remove("#{error}");
    fCtx.getExternalContext().getSessionMap().remove("#{helpBean}");
    fCtx.getExternalContext().getSessionMap().remove("#{settingsBean}");

    @SuppressWarnings("unchecked")
    Map<String, HttpSession> sessionLoginMap = (Map<String, HttpSession>) sc.getAttribute("sessionLoginMap");

    session.setAttribute("username", userName);
    sessionLoginMap.put(userName, session);
    sc.setAttribute("sessionLoginMap", sessionLoginMap);

    session.setAttribute("startInit", "s");
    logger.info("Authentication Success");

    logger.info("update progressbar");
    setValueProgressBar(7);

    // Init workflow preference
    WorkflowPrefManager.getInstance();
    logger.warn("Sys home is : " + WorkflowPrefManager.pathSysHome);

    // Create home folder for this user if it does not exist yet
    WorkflowPrefManager.createUserHome(userName);

    try {
        luceneIndex();
    } catch (Exception e) {
        logger.error("Fail creating index: " + e.getMessage(), e);
    }

    // error with rmi connection
    boolean succ = createRegistry();

    if (cancel) {
        if (th != null) {
            try {
                String pid = new WorkflowProcessesManager(userName).getPid();
                logger.warn("Kill the process " + pid);
                th.kill(pid);
            } catch (IOException e) {
                logger.warn("Fail killing job after canceling it");
            }
        }
        invalidateSession();
        buildBackend = false;
        return null;
    }

    /*if (!succ && getErrorNumberCluster() != null) {
       getBundleMessage("error_number_cluster");
       invalidateSession();
       buildBackend = false;
       return "failure";
    }*/

    if (!succ) {
        getBundleMessage("error.rmi.connection");
        invalidateSession();
        buildBackend = false;
        return "failure";
    }

    setMsnError(null);
    buildBackend = false;

    /* FIXME -used to restart doesn't work
    //Init some object here...
    HdfsBean hdfsBean = new HdfsBean();
    hdfsBean.openCanvasScreen();
            
    HdfsBrowserBean hdfsBrowserBean = new HdfsBrowserBean();
    hdfsBrowserBean.openCanvasScreen();
            
    HiveBean jdbcBean = new HiveBean();
    jdbcBean.openCanvasScreen();
            
    SshBean sshBean = new SshBean();
    sshBean.openCanvasScreen();
            
    fCtx.getExternalContext().getSessionMap().put("#{hdfsBean}", hdfsBean);
    fCtx.getExternalContext().getSessionMap().put("#{browserHdfsBean}", hdfsBrowserBean);
    fCtx.getExternalContext().getSessionMap().put("#{jdbcBean}", jdbcBean);
    fCtx.getExternalContext().getSessionMap().put("#{sshBean}", sshBean);
     */

    return "success";
}

From source file:org.apache.struts.action.ActionServlet.java

/**
 * <p>Saves a String[] of module prefixes in the ServletContext under
 * Globals.MODULE_PREFIXES_KEY.  <strong>NOTE</strong> - the "" prefix for
 * the default module is not included in this list.</p>
 *
 * @param context The servlet context./*from   w  w w  .ja  va  2  s . c om*/
 * @since Struts 1.2
 */
protected void initModulePrefixes(ServletContext context) {
    ArrayList prefixList = new ArrayList();

    Enumeration names = context.getAttributeNames();

    while (names.hasMoreElements()) {
        String name = (String) names.nextElement();

        if (!name.startsWith(Globals.MODULE_KEY)) {
            continue;
        }

        String prefix = name.substring(Globals.MODULE_KEY.length());

        if (prefix.length() > 0) {
            prefixList.add(prefix);
        }
    }

    String[] prefixes = (String[]) prefixList.toArray(new String[prefixList.size()]);

    context.setAttribute(Globals.MODULE_PREFIXES_KEY, prefixes);
}

From source file:com.redsqirl.auth.UserInfoBean.java

/**
 * createRegistry/* w w  w  .j a  va2  s.com*/
 * 
 * Method to create the connection to the server rmi. Retrieve objects and
 * places them in the context of the application.
 * 
 * @return
 * @author Igor.Souza
 */
public boolean createRegistry() {

    logger.warn("createRegistry");

    List<String> beans = new ArrayList<String>();
    beans.add("wfm");
    beans.add("ssharray");
    beans.add("jdbc");
    beans.add("hcat");
    beans.add("oozie");
    beans.add("hdfs");
    beans.add("prefs");
    beans.add("hdfsbrowser");
    beans.add("samanager");

    FacesContext fCtx = FacesContext.getCurrentInstance();
    ServletContext sc = (ServletContext) fCtx.getExternalContext().getContext();
    HttpSession session = (HttpSession) fCtx.getExternalContext().getSession(false);

    try {
        try {
            registry = LocateRegistry.getRegistry(port);
        } catch (Exception e) {
            registry = LocateRegistry.createRegistry(port);
        }

        Iterator<String> beanIt = beans.iterator();
        while (beanIt.hasNext()) {
            String bean = beanIt.next();
            try {
                registry.unbind(userName + "@" + beanIt.next());
            } catch (NotBoundException e) {
                logger.warn("Object " + bean + " unable to unbind: " + e.getMessage());
            } catch (Exception e) {
                logger.warn("Object " + bean + " unable to unbind: " + e.getMessage());
            }
        }

        if (th != null) {
            String pid = new WorkflowProcessesManager(userName).getPid();
            logger.warn("Kill the process " + pid);
            th.kill(pid);
        }

        th = new ServerProcess(port);
        logger.warn("Sys home is : " + WorkflowPrefManager.pathSysHome);
        th.run(userName, sessionSSH);
        logger.warn("Sys home is : " + WorkflowPrefManager.pathSysHome);

        if (sessionSSH != null) {
            sc.setAttribute("UserInfo", sessionSSH.getUserInfo());
        }

        logger.info("update progressbar");
        setValueProgressBar(10);

        session.setAttribute("serverThread", th);
        sc.setAttribute("registry", registry);
        Iterator<String> itBean = beans.iterator();
        while (itBean.hasNext() && !cancel) {
            String beanName = itBean.next();
            logger.warn("createRegistry - " + beanName);

            if (beanName.equalsIgnoreCase("wfm")) {
                boolean error = true;
                int tryNumb = 0;
                while (error && !cancel) {
                    ++tryNumb;
                    try {
                        DataFlowInterface dfi = (DataFlowInterface) registry.lookup(userName + "@" + beanName);
                        dfi.addWorkflow("test");
                        error = false;
                        dfi.removeWorkflow("test");

                        //FIXME size cluster aws
                        //                     if(!dfi.checkNumberCluster(getNumberCluster())){
                        //                        setErrorNumberCluster(getMessageResources("error_number_cluster"));
                        //                        return false;
                        //                     }

                        logger.warn("workflow is running ");
                    } catch (Exception e) {
                        logger.info("workflow not running ");
                        Thread.sleep(500);
                        if (tryNumb > 1 * 60 * 2000000) {
                            throw e;
                        }
                        if (getValueProgressBar() < 45) {
                            logger.info("update progressbar");
                            setValueProgressBar(Math.min(79, getValueProgressBar() + 3));
                        } else {
                            setValueProgressBar(Math.min(79, getValueProgressBar() + 2));
                        }
                    }
                }
                logger.info("update progressbar");
                setValueProgressBar(80);
            }

            boolean error = true;
            int cont = 0;

            while (error && !cancel) {
                cont++;
                try {
                    Remote remoteObject = registry.lookup(userName + "@" + beanName);
                    error = false;
                    session.setAttribute(beanName, remoteObject);
                } catch (Exception e) {
                    Thread.sleep(500);
                    logger.error(e.getMessage());
                    // Time out after 3 minutes
                    if (cont > 1 * 60 * 2000000) {
                        throw e;
                    }
                }
            }
        }

        return true;

    } catch (Exception e) {
        logger.error("Fail to initialise registry, Exception: " + e.getMessage(), e);
        return false;
    }

}

From source file:com.ecyrd.jspwiki.WikiEngine.java

/**
 *  Instantiate using this method when you're running as a servlet and
 *  WikiEngine will figure out where to look for the property
 *  file./*from   ww  w  .j  ava2 s .c om*/
 *  Do not use this method - use WikiEngine.getInstance() instead.
 *
 *  @param context A ServletContext.
 *  @param appid   An Application ID.  This application is an unique random string which
 *                 is used to recognize this WikiEngine.
 *  @param props   The WikiEngine configuration.
 *  @throws WikiException If the WikiEngine construction fails.
 */
protected WikiEngine(ServletContext context, String appid, Properties props) throws WikiException {
    super();
    m_servletContext = context;
    m_appid = appid;

    // Stash the WikiEngine in the servlet context
    if (context != null) {
        context.setAttribute(ATTR_WIKIENGINE, this);
        m_rootPath = context.getRealPath("/");
    }

    try {
        //
        //  Note: May be null, if JSPWiki has been deployed in a WAR file.
        //
        initialize(props);
        log.info("Root path for this Wiki is: '" + m_rootPath + "'");
    } catch (Exception e) {
        String msg = Release.APPNAME + ": Unable to load and setup properties from jspwiki.properties. "
                + e.getMessage();
        if (context != null) {
            context.log(msg);
        }
        throw new WikiException(msg, e);
    }
}

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

/**
 * List node properties and children/*w w w.  ja  v a 2 s . co m*/
 */
private void list(Session session, String path, HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, javax.jcr.PathNotFoundException, RepositoryException {
    log.debug("list({}, {}, {}, {})", new Object[] { session, path, request, response });
    String stats = WebUtils.getString(request, "stats");
    String uuid = WebUtils.getString(request, "uuid");
    ServletContext sc = getServletContext();
    ContentInfo ci = null;
    Node node = null;

    // Respository stats calculation
    if (!stats.equals("")) {
        if (stats.equals("0")) {
            request.getSession().removeAttribute("stats");
        } else {
            request.getSession().setAttribute("stats", true);
        }
    }

    // Handle path or uuid
    if (!path.equals("")) {
        if (path.equals("/")) {
            node = session.getRootNode();
        } else {
            node = session.getRootNode().getNode(path.substring(1));
        }
    } else if (!uuid.equals("")) {
        node = session.getNodeByUUID(uuid);
        path = node.getPath();
    } else {
        node = session.getRootNode();
    }

    if (request.getSession().getAttribute("stats") != null && node.isNodeType(Folder.TYPE)) {
        try {
            ci = OKMFolder.getInstance().getContentInfo(null, node.getPath());
        } catch (AccessDeniedException e) {
            log.warn(e.getMessage(), e);
        } catch (com.openkm.core.RepositoryException e) {
            log.warn(e.getMessage(), e);
        } catch (PathNotFoundException e) {
            log.warn(e.getMessage(), e);
        } catch (DatabaseException e) {
            log.warn(e.getMessage(), e);
        }
    }

    // Activity log
    if (node.isNodeType(JcrConstants.MIX_REFERENCEABLE)) {
        UserActivity.log(session.getUserID(), "ADMIN_REPOSITORY_LIST", node.getUUID(), node.getPath(), null);
    } else {
        UserActivity.log(session.getUserID(), "ADMIN_REPOSITORY_LIST", ((NodeImpl) node).getId().toString(),
                node.getPath(), null);
    }

    sc.setAttribute("contentInfo", ci);
    sc.setAttribute("node", node);
    sc.setAttribute("isFolder", node.isNodeType(Folder.TYPE));
    sc.setAttribute("isDocument", node.isNodeType(Document.TYPE));
    sc.setAttribute("isDocumentContent", node.isNodeType(Document.CONTENT_TYPE));
    sc.setAttribute("isScripting", node.isNodeType(Scripting.TYPE));
    sc.setAttribute("holdsLock", node.holdsLock());
    sc.setAttribute("breadcrumb", createBreadcrumb(node.getPath()));
    sc.setAttribute("properties", getProperties(node));
    sc.setAttribute("children", getChildren(node));
    sc.getRequestDispatcher("/admin/jcr_repository_list.jsp").forward(request, response);
    log.debug("list: void");
}