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:com.openkm.servlet.admin.PropertyGroupsServlet.java

/**
 * List property groups/*w ww .j  a  v  a 2 s. c o  m*/
 */
private void list(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, ParseException, RepositoryException, DatabaseException {
    log.debug("list({}, {})", new Object[] { request, response });
    ServletContext sc = getServletContext();
    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:org.restcomm.sbc.Bootstrapper.java

@Override
public void init(final ServletConfig config) throws ServletException {
    final ServletContext context = config.getServletContext();
    final String path = context.getRealPath("WEB-INF/conf/sbc.xml");
    // Initialize the configuration interpolator.
    final ConfigurationStringLookup strings = new ConfigurationStringLookup();
    strings.addProperty("home", home(config));
    strings.addProperty("uri", uri(config));
    ConfigurationInterpolator.registerGlobalLookup("sbc", strings);
    // Load the RestComm configuration file.
    Configuration xml = null;//from   w w  w.  ja  va2s .  c  o m
    try {
        xml = new XMLConfiguration(path);
    } catch (final ConfigurationException exception) {
        logger.error(exception);
    }
    xml.setProperty("runtime-settings.home-directory", home(config));
    xml.setProperty("runtime-settings.root-uri", uri(config));
    context.setAttribute(Configuration.class.getName(), xml);
    // Initialize global dependencies.
    final ClassLoader loader = getClass().getClassLoader();
    // Create the actor system.
    //final Config settings = ConfigFactory.load();
    ConfigFactory.load();
    // Create the storage system.
    DaoManager storage = null;
    try {
        storage = storage(xml, loader);
    } catch (final ObjectInstantiationException exception) {
        throw new ServletException(exception);
    }

    context.setAttribute(DaoManager.class.getName(), storage);
    ShiroResources.getInstance().set(DaoManager.class, storage);
    ShiroResources.getInstance().set(Configuration.class, xml.subset("runtime-settings"));
    // Create high-level restcomm configuration
    RestcommConfiguration.createOnce(xml);
    // Initialize identityContext
    IdentityContext identityContext = new IdentityContext(xml);
    context.setAttribute(IdentityContext.class.getName(), identityContext);

    logger.info("Extern IP:" + xml.getString("runtime-settings.external-ip"));

    Version.printVersion();

}

From source file:org.apache.asterix.api.http.servlet.QueryServiceServlet.java

private void handleRequest(RequestParameters param, HttpServletResponse response) throws IOException {
    LOGGER.info(param.toString());// w  w w  .j  av a 2 s  .c o m
    long elapsedStart = System.nanoTime();
    final StringWriter stringWriter = new StringWriter();
    final PrintWriter resultWriter = new PrintWriter(stringWriter);

    SessionConfig sessionConfig = createSessionConfig(param, resultWriter);
    response.setCharacterEncoding("utf-8");
    response.setContentType(MediaType.JSON.str());

    int respCode = HttpServletResponse.SC_OK;
    Stats stats = new Stats();
    long execStart = -1;
    long execEnd = -1;

    resultWriter.print("{\n");
    printRequestId(resultWriter);
    printClientContextID(resultWriter, param);
    printSignature(resultWriter);
    printType(resultWriter, sessionConfig);
    try {
        final IClusterManagementWork.ClusterState clusterState = ClusterStateManager.INSTANCE.getState();
        if (clusterState != IClusterManagementWork.ClusterState.ACTIVE) {
            // using a plain IllegalStateException here to get into the right catch clause for a 500
            throw new IllegalStateException("Cannot execute request, cluster is " + clusterState);
        }
        if (param.statement == null || param.statement.isEmpty()) {
            throw new AsterixException("Empty request, no statement provided");
        }
        IHyracksClientConnection hcc;
        IHyracksDataset hds;
        ServletContext context = getServletContext();
        synchronized (context) {
            hcc = (IHyracksClientConnection) context.getAttribute(HYRACKS_CONNECTION_ATTR);
            hds = (IHyracksDataset) context.getAttribute(HYRACKS_DATASET_ATTR);
            if (hds == null) {
                hds = new HyracksDataset(hcc, ResultReader.FRAME_SIZE, ResultReader.NUM_READERS);
                context.setAttribute(HYRACKS_DATASET_ATTR, hds);
            }
        }
        IParser parser = compilationProvider.getParserFactory().createParser(param.statement);
        List<Statement> aqlStatements = parser.parse();
        MetadataManager.INSTANCE.init();
        IStatementExecutor translator = statementExecutorFactory.create(aqlStatements, sessionConfig,
                compilationProvider);
        execStart = System.nanoTime();
        translator.compileAndExecute(hcc, hds, QueryTranslator.ResultDelivery.SYNC, stats);
        execEnd = System.nanoTime();
        printStatus(resultWriter, ResultStatus.SUCCESS);
    } catch (AsterixException | TokenMgrError | org.apache.asterix.aqlplus.parser.TokenMgrError pe) {
        GlobalConfig.ASTERIX_LOGGER.log(Level.SEVERE, pe.getMessage(), pe);
        printError(resultWriter, pe);
        printStatus(resultWriter, ResultStatus.FATAL);
        respCode = HttpServletResponse.SC_BAD_REQUEST;
    } catch (Exception e) {
        GlobalConfig.ASTERIX_LOGGER.log(Level.SEVERE, e.getMessage(), e);
        printError(resultWriter, e);
        printStatus(resultWriter, ResultStatus.FATAL);
        respCode = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
    } finally {
        if (execStart == -1) {
            execEnd = -1;
        } else if (execEnd == -1) {
            execEnd = System.nanoTime();
        }
    }
    printMetrics(resultWriter, System.nanoTime() - elapsedStart, execEnd - execStart, stats.getCount(),
            stats.getSize());
    resultWriter.print("}\n");
    resultWriter.flush();
    String result = stringWriter.toString();

    GlobalConfig.ASTERIX_LOGGER.log(Level.FINE, result);

    response.setStatus(respCode);
    response.getWriter().print(result);
    if (response.getWriter().checkError()) {
        LOGGER.warning("Error flushing output writer");
    }
}

From source file:cn.vlabs.umt.ui.UMTStartupListener.java

public void contextInitialized(ServletContextEvent event) {
    ServletContext context = event.getServletContext();
    PropertyConfigurator.configure(context.getRealPath("/WEB-INF/conf/log4j.properties"));
    String contextxml = context.getInitParameter("contextConfigLocation");
    if (contextxml == null) {
        contextxml = "/WEB-INF/conf/UMTContext.xml";
    }/*ww  w.  j a v a 2 s .  c o  m*/
    //FIX the bug in linux
    String realpath = context.getRealPath(contextxml);
    if (realpath != null && realpath.startsWith("/")) {
        realpath = "/" + realpath;
    }
    FileSystemXmlApplicationContext factory = new FileSystemXmlApplicationContext(realpath);
    PathMapper mapper = (PathMapper) factory.getBean("PathMapper");
    mapper.setContext(context);

    CreateTable createTable = (CreateTable) factory.getBean("CreateTable");
    if (!createTable.isTableExist()) {
        createTable.createTable();
    }
    factory.getBean("UMTCredUtil");
    context.setAttribute(Attributes.APPLICATION_CONTEXT_KEY, factory);
    UMTContext.setFactory(factory);

}

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

/**
 * Execute JDBC query/*from w  w  w  .j  a va 2s  .com*/
 */
private void executeJdbc(Session session, String qs, ServletContext sc, HttpServletRequest request,
        HttpServletResponse response) throws SQLException, ServletException, IOException {
    WorkerJdbc worker = new WorkerJdbc();
    worker.setQueryString(qs);
    session.doWork(worker);

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

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

/**
 * Load the application properties file (found at
 * <code>/WEB-INF/classes/hq.properties</code>) and configure
 * the web application. All properties in the file are exposed as
 * servlet context attributes./*from ww w. ja va2  s. com*/
 *
 */
public void loadConfig(ServletContext ctx) {
    Properties props = null;
    try {
        props = loadProperties(ctx, Constants.PROPS_FILE_NAME);
    } catch (Exception e) {
        error("unable to load application properties file [" + Constants.PROPS_FILE_NAME + "]", e);
        return;
    }

    if (props == null) {
        debug("application properties file [" + Constants.PROPS_FILE_NAME + "] does not exist");
        return;
    }

    Enumeration names = props.propertyNames();
    while (names.hasMoreElements()) {
        String name = (String) names.nextElement();
        if (name.startsWith(Constants.SYSTEM_VARIABLE_PATH)) {
            System.setProperty(name, props.getProperty(name));
        } else {
            ctx.setAttribute(name, props.getProperty(name));
        }
    }

    debug("loaded application configuration [" + Constants.PROPS_FILE_NAME + "]");
}

From source file:org.duracloud.duradmin.spaces.controller.SpaceController.java

private void setItemCount(final Space space, HttpServletRequest request) throws ContentStoreException {
    String key = formatItemCountCacheKey(space);
    final ServletContext appContext = request.getSession().getServletContext();
    ItemCounter listener = (ItemCounter) appContext.getAttribute(key);
    space.setItemCount(new Long(-1));
    if (listener != null) {
        if (listener.isCountComplete()) {
            space.setItemCount(listener.getCount());
        } else {/*w  w  w.j  a v a2 s  .co  m*/
            SpaceProperties properties = space.getProperties();
            Long interCount = listener.getIntermediaryCount();
            if (interCount == null) {
                interCount = 0l;
            }
            properties.setCount(String.valueOf(interCount) + "+");
            space.setProperties(properties);
        }
    } else {
        final ItemCounter itemCounterListener = new ItemCounter();
        appContext.setAttribute(key, itemCounterListener);
        final ContentStore contentStore = contentStoreManager.getContentStore(space.getStoreId());
        final StoreCaller<Iterator<String>> caller = new StoreCaller<Iterator<String>>() {
            protected Iterator<String> doCall() throws ContentStoreException {
                return contentStore.getSpaceContents(space.getSpaceId());
            }

            public String getLogMessage() {
                return "Error calling contentStore.getSpaceContents() for: " + space.getSpaceId();
            }
        };

        new Thread(new Runnable() {
            public void run() {
                ExtendedIteratorCounterThread runnable = new ExtendedIteratorCounterThread(caller.call(),
                        itemCounterListener);
                runnable.run();
            }
        }).start();
    }
}

From source file:org.rhq.enterprise.gui.startup.Configurator.java

/**
 * Load the internals properties file and configures the web application. All properties in the file are exposed as
 * servlet context attributes.// w ww .j av a2 s.  co  m
 */
private void loadConfig(ServletContext ctx) {
    Properties props;

    try {
        props = loadProperties(ctx, SERVER_INTERNALS_FILE);
    } catch (Exception e) {
        log.error("unable to load server internals file [" + SERVER_INTERNALS_FILE + "]", e);
        return;
    }

    if (props == null) {
        log.debug("server internals file [" + SERVER_INTERNALS_FILE + "] does not exist");
        return;
    }

    Enumeration names = props.propertyNames();

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

        // this is not currently used, but is interesting, it lets you define system properties in rhq-server-internals.properties
        if (name.startsWith(SYSPROP_KEY)) {
            System.setProperty(name, props.getProperty(name));
        } else {
            ctx.setAttribute(name, props.getProperty(name));
        }
    }

    log.debug("loaded server internals [" + SERVER_INTERNALS_FILE + "]");

    return;
}

From source file:com.murrayc.murraycgwtpexample.server.ThingServiceImpl.java

private Things getThings() {
    if (things != null) {
        return things;
    }// w  ww.j a v  a  2s .  c om

    final ServletConfig config = this.getServletConfig();
    if (config == null) {
        Log.error("getServletConfig() return null");
        return null;
    }

    final ServletContext context = config.getServletContext();
    if (context == null) {
        Log.error("getServletContext() return null");
        return null;
    }

    //Use the existing shared things if any:
    final Object object = context.getAttribute(LOADED_THINGS);
    if ((object != null) && !(object instanceof Things)) {
        Log.error("The loaded-things attribute is not of the expected type.");
        return null;
    }

    things = (Things) object;
    if (things != null) {
        return things;
    }

    //Load it for the first time:
    try {
        things = loadThings();
    } catch (final Exception e) {
        e.printStackTrace();
        return null;
    }

    context.setAttribute(LOADED_THINGS, things);

    return things;
}

From source file:org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.java

/**
 * Prepare the {@link WebApplicationContext} with the given fully loaded
 * {@link ServletContext}. This method is usually called from
 * {@link ServletContextInitializer#onStartup(ServletContext)} and is similar to the
 * functionality usually provided by a {@link ContextLoaderListener}.
 * @param servletContext the operational servlet context
 *///from w  w w .j  av  a  2s.  co  m
protected void prepareEmbeddedWebApplicationContext(ServletContext servletContext) {
    Object rootContext = servletContext
            .getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
    if (rootContext != null) {
        if (rootContext == this) {
            throw new IllegalStateException(
                    "Cannot initialize context because there is already a root application context present - "
                            + "check whether you have multiple ServletContextInitializers!");
        }
        return;
    }
    Log logger = LogFactory.getLog(ContextLoader.class);
    servletContext.log("Initializing Spring embedded WebApplicationContext");
    try {
        servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, this);
        if (logger.isDebugEnabled()) {
            logger.debug("Published root WebApplicationContext as ServletContext attribute with name ["
                    + WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE + "]");
        }
        setServletContext(servletContext);
        if (logger.isInfoEnabled()) {
            long elapsedTime = System.currentTimeMillis() - getStartupDate();
            logger.info("Root WebApplicationContext: initialization completed in " + elapsedTime + " ms");
        }
    } catch (RuntimeException ex) {
        logger.error("Context initialization failed", ex);
        servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, ex);
        throw ex;
    } catch (Error ex) {
        logger.error("Context initialization failed", ex);
        servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, ex);
        throw ex;
    }
}