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:org.apache.asterix.api.http.servlet.QueryServiceServlet.java

private void handleRequest(RequestParameters param, HttpServletResponse response) throws IOException {
    LOGGER.info(param.toString());/*from  www  .  j a  v a 2s. co  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:alluxio.proxy.s3.S3RestServiceHandler.java

/**
 * Constructs a new {@link S3RestServiceHandler}.
 *
 * @param context context for the servlet
 */// w  w w .  jav  a 2s . c o  m
public S3RestServiceHandler(@Context ServletContext context) {
    mFileSystem = (FileSystem) context.getAttribute(ProxyWebServer.FILE_SYSTEM_SERVLET_RESOURCE_KEY);
}

From source file:com.jdon.jivejdon.presentation.servlet.upload.ExtendedMultiPartRequestHandler.java

/**
 * Returns the path to the temporary directory to be used for uploaded files
 * which are written to disk. The directory used is determined from the
 * first of the following to be non-empty.
 * <ol>/*w w w  .j  a v  a2 s  .c  om*/
 * <li>A temp dir explicitly defined either using the <code>tempDir</code>
 * servlet init param, or the <code>tempDir</code> attribute of the
 * &lt;controller&gt; element in the Struts config file.</li>
 * <li>The container-specified temp dir, obtained from the
 * <code>javax.servlet.context.tempdir</code> servlet context attribute.</li>
 * <li>The temp dir specified by the <code>java.io.tmpdir</code> system
 * property.</li> (/ol>
 * 
 * @param mc
 *            The module config instance for which the path should be
 *            determined.
 * 
 * @return The path to the directory to be used to store uploaded files.
 */
protected String getRepositoryPath(ModuleConfig mc) {

    // First, look for an explicitly defined temp dir.
    String tempDir = mc.getControllerConfig().getTempDir();

    // If none, look for a container specified temp dir.
    if (tempDir == null || tempDir.length() == 0) {
        if (servlet != null) {
            ServletContext context = servlet.getServletContext();
            File tempDirFile = (File) context.getAttribute("javax.servlet.context.tempdir");
            tempDir = tempDirFile.getAbsolutePath();
        }

        // If none, pick up the system temp dir.
        if (tempDir == null || tempDir.length() == 0) {
            tempDir = System.getProperty("java.io.tmpdir");
        }
    }

    if (log.isTraceEnabled()) {
        log.trace("File upload temp dir: " + tempDir);
    }

    return tempDir;
}

From source file:net.wastl.webmail.server.WebMailServlet.java

public void init(ServletConfig config) throws ServletException {
    final ServletContext sc = config.getServletContext();
    log.debug("Init");
    final String depName = (String) sc.getAttribute("deployment.name");
    final Properties rtProps = (Properties) sc.getAttribute("meta.properties");
    log.debug("RT configs retrieved for application '" + depName + "'");
    srvlt_config = config;// w  w w  .  j  av a 2  s .  c om
    this.config = new Properties();
    final Enumeration enumVar = config.getInitParameterNames();
    while (enumVar.hasMoreElements()) {
        final String s = (String) enumVar.nextElement();
        this.config.put(s, config.getInitParameter(s));
        log.debug(s + ": " + config.getInitParameter(s));
    }

    /*
     * Issue a warning if webmail.basepath and/or webmail.imagebase are not
     * set.
     */
    if (config.getInitParameter("webmail.basepath") == null) {
        log.warn("webmail.basepath initArg should be set to the WebMail " + "Servlet's base path");
        basepath = "";
    } else {
        basepath = config.getInitParameter("webmail.basepath");
    }
    if (config.getInitParameter("webmail.imagebase") == null) {
        log.error("webmail.basepath initArg should be set to the WebMail " + "Servlet's base path");
        imgbase = "";
    } else {
        imgbase = config.getInitParameter("webmail.imagebase");
    }

    /*
     * Try to get the pathnames from the URL's if no path was given in the
     * initargs.
     */
    if (config.getInitParameter("webmail.data.path") == null) {
        this.config.put("webmail.data.path", sc.getRealPath("/data"));
    }
    if (config.getInitParameter("webmail.lib.path") == null) {
        this.config.put("webmail.lib.path", sc.getRealPath("/lib"));
    }
    if (config.getInitParameter("webmail.template.path") == null) {
        this.config.put("webmail.template.path", sc.getRealPath("/lib/templates"));
    }
    if (config.getInitParameter("webmail.xml.path") == null) {
        this.config.put("webmail.xml.path", sc.getRealPath("/lib/xml"));
    }
    if (config.getInitParameter("webmail.log.facility") == null) {
        this.config.put("webmail.log.facility", "net.wastl.webmail.logger.ServletLogger");
    }

    // Override settings with webmail.* meta.properties
    final Enumeration rte = rtProps.propertyNames();
    int overrides = 0;
    String k;
    while (rte.hasMoreElements()) {
        k = (String) rte.nextElement();
        if (!k.startsWith("webmail.")) {
            continue;
        }
        overrides++;
        this.config.put(k, rtProps.getProperty(k));
    }
    log.debug(Integer.toString(overrides) + " settings passed to WebMailServer, out of " + rtProps.size()
            + " RT properties");

    /*
     * Call the WebMailServer's initialization method and forward all
     * Exceptions to the ServletServer
     */
    try {
        doInit();
    } catch (final Exception e) {
        log.error("Could not intialize", e);
        throw new ServletException("Could not intialize: " + e.getMessage(), e);
    }
    Helper.logThreads("Bottom of WebMailServlet.init()");
}

From source file:org.apache.struts.upload.CommonsMultipartRequestHandler.java

/**
 * <p> Returns the path to the temporary directory to be used for uploaded
 * files which are written to disk. The directory used is determined from
 * the first of the following to be non-empty. <ol> <li>A temp dir
 * explicitly defined either using the <code>tempDir</code> servlet init
 * param, or the <code>tempDir</code> attribute of the &lt;controller&gt;
 * element in the Struts config file.</li> <li>The container-specified
 * temp dir, obtained from the <code>javax.servlet.context.tempdir</code>
 * servlet context attribute.</li> <li>The temp dir specified by the
 * <code>java.io.tmpdir</code> system property.</li> (/ol> </p>
 *
 * @param mc The module config instance for which the path should be
 *           determined.//  ww w. j  av  a 2 s .  com
 * @return The path to the directory to be used to store uploaded files.
 */
protected String getRepositoryPath(ModuleConfig mc) {
    // First, look for an explicitly defined temp dir.
    String tempDir = mc.getControllerConfig().getTempDir();

    // If none, look for a container specified temp dir.
    if ((tempDir == null) || (tempDir.length() == 0)) {
        if (servlet != null) {
            ServletContext context = servlet.getServletContext();
            File tempDirFile = (File) context.getAttribute("javax.servlet.context.tempdir");

            tempDir = tempDirFile.getAbsolutePath();
        }

        // If none, pick up the system temp dir.
        if ((tempDir == null) || (tempDir.length() == 0)) {
            tempDir = System.getProperty("java.io.tmpdir");
        }
    }

    if (log.isTraceEnabled()) {
        log.trace("File upload temp dir: " + tempDir);
    }

    return tempDir;
}

From source file:com.dhcc.framework.web.context.DhccContextLoader.java

/**
 * Initialize Spring's web application context for the given servlet context,
 * using the application context provided at construction time, or creating a new one
 * according to the "{@link #CONTEXT_CLASS_PARAM contextClass}" and
 * "{@link #CONFIG_LOCATION_PARAM contextConfigLocation}" context-params.
 * @param servletContext current servlet context
 * @return the new WebApplicationContext
 * @see #ContextLoader(WebApplicationContext)
 * @see #CONTEXT_CLASS_PARAM//from   w  ww.j a v  a 2 s.  c  o  m
 * @see #CONFIG_LOCATION_PARAM
 */
public WebApplicationContext initWebApplicationContext(ServletContext servletContext) {
    if (servletContext.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE) != null) {
        throw new IllegalStateException(
                "Cannot initialize context because there is already a root application context present - "
                        + "check whether you have multiple ContextLoader* definitions in your web.xml!");
    }

    Log logger = LogFactory.getLog(DhccContextLoader.class);
    servletContext.log("Initializing Spring root WebApplicationContext");
    if (logger.isInfoEnabled()) {
        logger.info("Root WebApplicationContext: initialization started");
    }
    long startTime = System.currentTimeMillis();

    try {
        // Store context in local instance variable, to guarantee that
        // it is available on ServletContext shutdown.
        if (this.context == null) {
            this.context = createWebApplicationContext(servletContext);
        }
        if (this.context instanceof ConfigurableWebApplicationContext) {
            ConfigurableWebApplicationContext cwac = (ConfigurableWebApplicationContext) this.context;
            if (!cwac.isActive()) {
                // The context has not yet been refreshed -> provide services such as
                // setting the parent context, setting the application context id, etc
                if (cwac.getParent() == null) {
                    // The context instance was injected without an explicit parent ->
                    // determine parent for root web application context, if any.
                    ApplicationContext parent = loadParentContext(servletContext);
                    cwac.setParent(parent);
                }
                configureAndRefreshWebApplicationContext(cwac, servletContext);
            }
        }
        servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, this.context);

        ClassLoader ccl = Thread.currentThread().getContextClassLoader();
        if (ccl == DhccContextLoader.class.getClassLoader()) {
            currentContext = this.context;
        } else if (ccl != null) {
            currentContextPerThread.put(ccl, this.context);
        }

        if (logger.isDebugEnabled()) {
            logger.debug("Published root WebApplicationContext as ServletContext attribute with name ["
                    + WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE + "]");
        }
        if (logger.isInfoEnabled()) {
            long elapsedTime = System.currentTimeMillis() - startTime;
            logger.info("Root WebApplicationContext: initialization completed in " + elapsedTime + " ms");
        }

        return this.context;
    } catch (RuntimeException ex) {
        logger.error("Context initialization failed", ex);
        servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, ex);
        throw ex;
    } catch (Error err) {
        logger.error("Context initialization failed", err);
        servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, err);
        throw err;
    }
}

From source file:uk.ac.ebi.ep.controller.SearchController.java

/**
 * Retrieves any previous searches stored in the application context.
 *
 * @param servletContext the application context.
 * @return a map of searches to results.
 *//*from   w w w .  j av a 2  s.c  o  m*/
@SuppressWarnings("unchecked")
protected Map<String, SearchResults> getPreviousSearches(ServletContext servletContext) {
    Map<String, SearchResults> prevSearches = (Map<String, SearchResults>) servletContext
            .getAttribute(Attribute.prevSearches.name());
    if (prevSearches == null) {
        // Map implementation which maintains the order of access:
        prevSearches = Collections.synchronizedMap(
                new LinkedHashMap<String, SearchResults>(searchConfig.getSearchCacheSize(), 1, true));

        servletContext.setAttribute(Attribute.prevSearches.getName(), prevSearches);

    }
    return prevSearches;
}

From source file:org.apache.struts.util.ModuleUtils.java

/**
 * Select the module to which the specified request belongs, and add
 * corresponding request attributes to this request.
 *
 * @param prefix  The module prefix of the desired module
 * @param request The servlet request we are processing
 * @param context The ServletContext for this web application
 *//*from  w w w  .j a  va 2  s . co m*/
public void selectModule(String prefix, HttpServletRequest request, ServletContext context) {
    // Expose the resources for this module
    ModuleConfig config = getModuleConfig(prefix, context);

    if (config != null) {
        request.setAttribute(Globals.MODULE_KEY, config);

        MessageResourcesConfig[] mrConfig = config.findMessageResourcesConfigs();

        for (int i = 0; i < mrConfig.length; i++) {
            String key = mrConfig[i].getKey();
            MessageResources resources = (MessageResources) context.getAttribute(key + prefix);

            if (resources != null) {
                request.setAttribute(key, resources);
            } else {
                request.removeAttribute(key);
            }
        }
    } else {
        request.removeAttribute(Globals.MODULE_KEY);
    }
}

From source file:com.mtgi.analytics.servlet.BehaviorTrackingListener.java

private synchronized void checkInit(ServletRequestEvent event) {
    if (!initialized) {

        ServletContext context = event.getServletContext();
        boolean hasFilter = BehaviorTrackingFilter.isFiltered(context);
        ArrayList<ServletRequestBehaviorTrackingAdapter> beans = new ArrayList<ServletRequestBehaviorTrackingAdapter>();

        //find registered request adapters in all mvc servlet contexts.
        for (Enumeration<?> atts = context.getAttributeNames(); atts.hasMoreElements();) {
            String name = (String) atts.nextElement();
            if (name.startsWith(FrameworkServlet.SERVLET_CONTEXT_PREFIX)) {
                Object value = context.getAttribute(name);
                if (value instanceof ListableBeanFactory)
                    addRequestAdapters(beans, (ListableBeanFactory) value, hasFilter);
            }//w ww .ja  va  2  s .  c  om
        }

        //look for shared application context, loaded by ContextLoaderListener.
        ListableBeanFactory parent = WebApplicationContextUtils.getWebApplicationContext(context);
        if (parent != null)
            addRequestAdapters(beans, parent, hasFilter);

        if (!beans.isEmpty()) {
            adapters = beans.toArray(new ServletRequestBehaviorTrackingAdapter[beans.size()]);
            log.info("BehaviorTracking for HTTP servlet requests started");
        }

        initialized = true;
    }
}

From source file:org.apache.pluto.driver.services.container.EventProviderImpl.java

/**
 * Fire all saved events Note, that the order isn't important
 * /*  w ww  . ja v  a 2s  . c om*/
 * @see PLT14.3.2
 * @param eventContainer
 *            The {@link PortletContainerImpl} to fire the events
 */
public void fireEvents(EventContainer eventContainer) {
    ServletContext containerServletContext = PortalRequestContext.getContext(request).getServletContext();
    DriverConfiguration driverConfig = (DriverConfiguration) containerServletContext
            .getAttribute(AttributeKeys.DRIVER_CONFIG);

    PortalURL portalURL = PortalURLParserImpl.getParser().parse(request);

    while (savedEvents.hasMoreEvents() && savedEvents.getSize() < Constants.MAX_EVENTS_SIZE) {

        Event eActual = getArbitraryEvent();

        this.savedEvents.setProcessed(eActual);

        List<String> portletNames = getAllPortletsRegisteredForEvent(eActual, driverConfig,
                containerServletContext);

        Collection<PortletWindowConfig> portlets = getAllPortlets(driverConfig);

        // iterate all portlets in the portal
        for (PortletWindowConfig config : portlets) {
            PortletWindow window = new PortletWindowImpl(container, config, portalURL);
            if (portletNames != null) {
                for (String portlet : portletNames) {
                    if (portlet.equals(config.getId())) {

                        // the thread now is a new one, with possible
                        // waiting,
                        // for the old to exit

                        PortletWindowThread portletWindowThread = getPortletWindowThread(eventContainer, config,
                                window, containerServletContext);

                        // is this event
                        portletWindowThread.addEvent(eActual);

                        portletWindowThread.start();
                    }
                }
            }
        }
        waitForEventExecution();
        try {
            Thread.sleep(WAITING_CYCLE);
        } catch (InterruptedException e) {
            LOG.warn(e);
        }
    }
    waitForEventExecution();
}