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:com.rapid.core.Page.java

public static Page load(ServletContext servletContext, File file)
        throws JAXBException, ParserConfigurationException, SAXException, IOException,
        TransformerFactoryConfigurationError, TransformerException {

    // get the logger
    Logger logger = (Logger) servletContext.getAttribute("logger");

    // trace log that we're about to load a page
    logger.trace("Loading page from " + file);

    // open the xml file into a document
    Document pageDocument = XML.openDocument(file);

    // specify the xmlVersion as -1
    int xmlVersion = -1;

    // look for a version node
    Node xmlVersionNode = XML.getChildElement(pageDocument.getFirstChild(), "XMLVersion");

    // if we got one update the version
    if (xmlVersionNode != null)
        xmlVersion = Integer.parseInt(xmlVersionNode.getTextContent());

    // if the version of this xml isn't the same as this class we have some work to do!
    if (xmlVersion != XML_VERSION) {

        // get the page name
        String name = XML.getChildElementValue(pageDocument.getFirstChild(), "name");

        // log the difference
        logger.debug("Page " + name + " with version " + xmlVersion + ", current version is " + XML_VERSION);

        ////from www  .ja va2s  .c  o m
        // Here we would have code to update from known versions of the file to the current version
        //

        // check whether there was a version node in the file to start with
        if (xmlVersionNode == null) {
            // create the version node
            xmlVersionNode = pageDocument.createElement("XMLVersion");
            // add it to the root of the document
            pageDocument.getFirstChild().appendChild(xmlVersionNode);
        }

        // set the xml to the latest version
        xmlVersionNode.setTextContent(Integer.toString(XML_VERSION));

        //
        // Here we would use xpath to find all controls and run the Control.upgrade method
        //

        //
        // Here we would use xpath to find all actions, each class has it's own upgrade method so
        // we need to identify the class, instantiate it and call it's upgrade method
        // it's probably worthwhile maintaining a map of instantiated classes to avoid unnecessary re-instantiation   
        //

        // save it
        XML.saveDocument(pageDocument, file);

        logger.debug("Updated " + name + " page version to " + XML_VERSION);

    }

    // get the unmarshaller from the context
    Unmarshaller unmarshaller = RapidHttpServlet.getUnmarshaller();

    // get a buffered reader for our page with UTF-8 file format
    BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"));

    // try the unmarshalling
    try {

        // unmarshall the page
        Page page = (Page) unmarshaller.unmarshal(br);

        // log that the page was loaded
        logger.debug("Loaded page " + page.getId() + " - " + page.getName() + " from " + file);

        // close the buffered reader
        br.close();

        // return the page      
        return page;

    } catch (JAXBException ex) {

        // close the buffered reader
        br.close();

        // log that the page had an error
        logger.error("Error loading page from " + file);

        // re-throw
        throw ex;

    }

}

From source file:org.hyperic.hq.ui.action.admin.user.RegisterAction.java

/**
 * Create the user with the attributes specified in the given
 * <code>NewForm</code> and save it into the session attribute
 * <code>Constants.USER_ATTR</code>.
 *//*from   ww  w  .  jav a  2  s .c  o m*/
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    final Log log = LogFactory.getLog(RegisterAction.class.getName());
    final boolean debug = log.isDebugEnabled();

    Integer sessionId = RequestUtils.getSessionId(request);
    EditForm userForm = (EditForm) form;
    HttpSession session = request.getSession(false);
    ActionForward forward = checkSubmit(request, mapping, form);

    if (forward != null) {
        return forward;
    }

    //get the spiderSubjectValue of the user to be deleated.
    ServletContext ctx = getServlet().getServletContext();
    WebUser webUser = RequestUtils.getWebUser(session);

    // password was saved off when the user logged in
    String password = (String) session.getAttribute(Constants.PASSWORD_SES_ATTR);

    session.removeAttribute(Constants.PASSWORD_SES_ATTR);

    // use the overlord to register the subject, and don't add
    // a principal
    if (debug)
        log.debug("registering subject [" + webUser.getUsername() + "]");

    Integer authzSubjectId = userForm.getId();
    AuthzSubject target = authzSubjectManager.findSubjectById(authzSubjectId);

    authzBoss.updateSubject(sessionId, target, Boolean.TRUE, HQConstants.ApplicationName,
            userForm.getDepartment(), userForm.getEmailAddress(), userForm.getFirstName(),
            userForm.getLastName(), userForm.getPhoneNumber(), userForm.getSmsAddress(), null);

    // nuke the temporary bizapp session and establish a new
    // one for this subject.. must be done before pulling the
    // new subject in order to do it with his own credentials
    // TODO need to make sure this is valid
    sessionManager.invalidate(sessionId);

    sessionId = sessionManager.put(authzSubjectManager.findSubjectById(authzSubjectId));

    if (debug)
        log.debug("finding subject [" + webUser.getUsername() + "]");

    // the new user has no prefs, but we still want to pick up
    // the defaults
    ConfigResponse preferences = (ConfigResponse) ctx.getAttribute(Constants.DEF_USER_PREFS);

    // look up the user's permissions
    if (debug)
        log.debug("getting all operations");

    Map<String, Boolean> userOpsMap = new HashMap<String, Boolean>();
    List<Operation> userOps = authzBoss.getAllOperations(sessionId);

    // TODO come back to this and see why this is done...
    for (Operation op : userOps) {
        userOpsMap.put(op.getName(), Boolean.TRUE);
    }

    // we also need to create up a new web user
    webUser = new WebUser(target, sessionId, preferences, false);

    session.setAttribute(Constants.WEBUSER_SES_ATTR, webUser);
    session.setAttribute(Constants.USER_OPERATIONS_ATTR, userOpsMap);

    Map<String, Object> parms = new HashMap<String, Object>(1);

    parms.put(Constants.USER_PARAM, target.getId());

    return returnSuccess(request, mapping, parms, false);
}

From source file:com.idega.core.accesscontrol.business.LoginBusinessBean.java

/**
 * The key is the login name and the value is
 * com.idega.core.accesscontrol.business.LoggedOnInfo
 *
 * @return Returns empty Map if no one is logged on
 *//*from w  ww.j  a  v a 2 s  .  co m*/
public Map<Object, Object> getLoggedOnInfoMap(HttpSession session) {
    ServletContext sc = session.getServletContext();
    Map<Object, Object> loggedOnMap = (Map<Object, Object>) sc.getAttribute(_APPADDRESS_LOGGED_ON_LIST);
    if (loggedOnMap == null) {
        loggedOnMap = new TreeMap<Object, Object>();
        sc.setAttribute(_APPADDRESS_LOGGED_ON_LIST, loggedOnMap);
    }
    return loggedOnMap;
}

From source file:org.artifactory.webapp.servlet.ArtifactoryContextConfigListener.java

@Override
public void contextInitialized(ServletContextEvent event) {
    final ServletContext servletContext = event.getServletContext();

    setSessionTrackingMode(servletContext);

    final Thread initThread = new Thread("art-init") {
        boolean success = true;

        @SuppressWarnings({ "unchecked" })
        @Override//  w ww .  j  a v  a2 s  . co  m
        public void run() {
            try {
                //Use custom logger
                String contextId = HttpUtils.getContextId(servletContext);
                //Build a partial config, since we expect the logger-context to exit in the selector cache by only contextId
                LoggerConfigInfo configInfo = new LoggerConfigInfo(contextId);
                LogbackContextSelector.bindConfig(configInfo);
                //No log field since needs to lazy initialize only after logback customization listener has run
                Logger log = getLogger();
                configure(servletContext, log);

                LogbackContextSelector.unbindConfig();
            } catch (Exception e) {
                getLogger().error(
                        "Application could not be initialized: " + ExceptionUtils.getRootCause(e).getMessage(),
                        e);
                success = false;
            } finally {
                if (success) {
                    //Run the waiting filters
                    BlockingQueue<DelayedInit> waitingFiltersQueue = (BlockingQueue<DelayedInit>) servletContext
                            .getAttribute(DelayedInit.APPLICATION_CONTEXT_LOCK_KEY);
                    List<DelayedInit> waitingInits = new ArrayList<>();
                    waitingFiltersQueue.drainTo(waitingInits);
                    for (DelayedInit filter : waitingInits) {
                        try {
                            filter.delayedInit();
                        } catch (ServletException e) {
                            getLogger().error("Could not init {}.", filter.getClass().getName(), e);
                            success = false;
                            break;
                        }
                    }
                }
                //Remove the lock and open the app to requests
                servletContext.removeAttribute(DelayedInit.APPLICATION_CONTEXT_LOCK_KEY);
            }
        }
    };
    initThread.setDaemon(true);
    servletContext.setAttribute(DelayedInit.APPLICATION_CONTEXT_LOCK_KEY,
            new LinkedBlockingQueue<DelayedInit>());
    initThread.start();
    if (Boolean.getBoolean("artifactory.init.useServletContext")) {
        try {
            getLogger().info("Waiting for servlet context initialization ...");
            initThread.join();
        } catch (InterruptedException e) {
            getLogger().error("Artifactory initialization thread got interrupted", e);
        }
    }
}

From source file:com.inverse2.ajaxtoaster.AjaxToasterServlet.java

public List getJDCBConnectionPoolList() {
    ServletContext context = getServletContext();
    DBConnectionPool pool = null;//w  ww .  jav a 2s  .c  o  m
    ArrayList poolList = new ArrayList();

    for (Enumeration e = context.getAttributeNames(); e.hasMoreElements();) {
        String attribName = (String) e.nextElement();
        if (attribName.startsWith(ATTRIB_JDBC_CONN_POOL)) {
            pool = (DBConnectionPool) context.getAttribute(attribName);
            if (pool != null) {
                poolList.add(pool);
            }
        }
    }

    return (poolList);
}

From source file:com.inverse2.ajaxtoaster.AjaxToasterServlet.java

public void freeServiceScript(ServiceOperationInterface toaster) throws Exception {

    ServletContext context = getServletContext();
    ServicePool pool = null;// ww  w. j a  v a2 s  .com
    DBConnectionPool dbpool = null;

    if (toaster != null) {

        Connection connection = toaster.getConnection();

        if (connection != null) {

            String attr = ATTRIB_JDBC_CONN_POOL + "." + toaster.getJDBCpoolname();

            dbpool = (DBConnectionPool) context.getAttribute(attr);

            toaster.setConnection(null);

            if (dbpool != null) {
                dbpool.freeConnection(connection);
            }

        }

        pool = (ServicePool) context.getAttribute(ATTRIB_SERVICE_POOL);

        pool.freeService(toaster.getScriptName(), toaster);

    }

    return;
}

From source file:com.inverse2.ajaxtoaster.AjaxToasterServlet.java

public ServiceOperationInterface getServiceScript(String scriptName) throws Exception {

    ServletContext context = getServletContext();
    ServicePool pool = null;/* w  ww.jav a 2  s.  c om*/
    ServiceOperationInterface toaster = null;
    Connection connection = null;
    DBConnectionPool dbpool = null;
    String db_jndi_name = null;
    String db_jdbc_poolname = null;

    try {
        pool = (ServicePool) context.getAttribute(ATTRIB_SERVICE_POOL);
    } catch (Exception ex) {
        log.error("Error getting the toaster pool from the servlet context [" + ATTRIB_SERVICE_POOL + "]");
        throw new Exception("ERROR - could not get toast pool from server context [" + ATTRIB_SERVICE_POOL
                + "]: " + ex.toString(), ex);
    }

    if (pool == null) {
        /* Toaster pool is not set-up - this is very bad...! */
        log.error("The toaster pool does not exists in the servlet context.");
        throw new Exception("The toaster pool does not exist in the servlet context.");
    }

    try {
        toaster = pool.getService(scriptName);
    } catch (Exception ex) {
        log.error("Exception getting a toaster instance: " + ex.toString());
        throw new Exception(
                "ERROR - could not get toaster instance from pool for " + scriptName + ": " + ex.toString(),
                ex);
    }

    /**
     * DATABASE CONNECTION...
     *   if the DbJDNI property is set to non null value, or the default connection is a JNDI one,
     *   then try to use JNDI.
     */

    println(">> Starting database connection");

    db_jndi_name = toaster.getDbJNDI(); // get jndi name from the scripts' properties file (if any)
    db_jdbc_poolname = toaster.getJDBCpoolname(); // get jdbc name from the scripts' properties file (if any)

    if (db_jndi_name != null || default_db_jndi_name != null) {

        // JNDI - Container managed connection pool.
        // Lookup the JNDI name for the connection pool and create the database connection.

        if (db_jndi_name == null) {
            db_jndi_name = default_db_jndi_name;
        }

        println("Looking up database connection for JNDI name " + db_jndi_name + "... "
                + "An exception here probably indicates that the JNDI name or corresponing connection pool isn't setup on your application server.");

        try {
            // The following code for Websphere 6...
            InitialContext ic = new InitialContext();
            DataSource dataSource = null;

            dataSource = (DataSource) ic.lookup(db_jndi_name);
            connection = dataSource.getConnection();
        } catch (Exception ex) {
            log.error("Exception getting JNDI database connection: " + ex.toString());
            throw new Exception("ERROR - getting a connection to the database (using JNDI name " + db_jndi_name
                    + "): " + ex.toString(), ex);
        }

    } else if (db_jdbc_poolname != null || default_db_jdbc_name != null) {

        if (db_jdbc_poolname == null) {
            db_jdbc_poolname = default_db_jdbc_name; // it isn't, so use the default one.
        }

        // find the connection pool in the servlet context
        try {
            String attr = ATTRIB_JDBC_CONN_POOL + "." + db_jdbc_poolname;
            println(">> Trying to get DB connection pool (" + attr + ")");
            dbpool = (DBConnectionPool) context.getAttribute(attr);
        } catch (Exception ex) {
            log.error("Could not get a database connection from the pool: " + ex.toString());
            throw new Exception("ERROR - could not get DB connection pool from server context ("
                    + ATTRIB_JDBC_CONN_POOL + "." + db_jdbc_poolname + ") " + ex.toString(), ex);
        }

        if (dbpool == null) {
            if (toaster != null) {
                pool.freeService(scriptName, toaster);
            }
            throw new Exception("ERROR - The database connection pool has not been created (dbpool for "
                    + ATTRIB_JDBC_CONN_POOL + "." + db_jdbc_poolname + " is null).");
        }
        try {
            connection = dbpool.getConnection();
        } catch (Exception ex) {
            if (toaster != null) {
                pool.freeService(scriptName, toaster);
            }
            throw new Exception("ERROR - could not get DB connection from DB connection pool. " + ex.toString(),
                    ex);
        }

    }

    /*
     *  Give the Toaster the database connection we created earlier...
     */
    toaster.setConnection(connection);

    return (toaster);
}

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();/*ww w .  j ava  2s.  co m*/

    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.jsmartframework.web.manager.BeanHandler.java

void finalizeWebBeans(ServletContext servletContext) {
    List<String> names = Collections.list(servletContext.getAttributeNames());
    for (String name : names) {
        Object bean = servletContext.getAttribute(name);
        if (bean == null) {
            continue;
        }//from   w ww  . jav a 2  s .c  o m
        if (bean.getClass().isAnnotationPresent(WebBean.class)) {
            finalizeWebBean(bean, servletContext);
        }
    }
}

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

/**
 * Method that will update the Java objects from the RMI registry.
 * @return/*from   w  w w  .  j ava 2s  . c  om*/
 */
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";
}