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.rhq.enterprise.gui.startup.Configurator.java

/**
 * Determines the internal build/version number and puts it in a context attribute.
 *//*from   w w w.j a  va2s  .  c  om*/
private void loadBuildVersion(ServletContext servletContext) {
    String version = LookupUtil.getCoreServer().getVersion();
    servletContext.setAttribute(AttrConstants.RHQ_VERSION_ATTR, version);
}

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

/**
 * Create CSS/*from   w w w  .j  av a2  s  . c  om*/
 */
private void create(String userId, HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, DatabaseException {
    log.debug("create({}, {}, {})", new Object[] { userId, request, response });
    ServletContext sc = getServletContext();

    sc.setAttribute("action", WebUtils.getString(request, "action"));
    sc.setAttribute("persist", true);
    sc.setAttribute("css", null);
    sc.getRequestDispatcher("/admin/css_edit.jsp").forward(request, response);

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

From source file:com.trendmicro.hdfs.webdav.HDFSWebDAVServlet.java

@Override
public void init() throws ServletException {
    super.init();
    resourcePathPrefix = getInitParameter(INIT_PARAM_RESOURCE_PATH_PREFIX);
    if (resourcePathPrefix == null) {
        LOG.debug("Missing path prefix -> setting to empty string.");
        resourcePathPrefix = "";
    } else if (resourcePathPrefix.endsWith("/")) {
        LOG.debug("Path prefix ends with '/' -> removing trailing slash.");
        resourcePathPrefix = resourcePathPrefix.substring(0, resourcePathPrefix.length() - 1);
    }//from w  ww  .j a v  a 2s . com

    LOG.info("ServletName: " + getServletName());
    LOG.info("ServletInfo: " + getServletInfo());

    ServletContext context = getServletContext();

    context.setAttribute(CTX_ATTR_RESOURCE_PATH_PREFIX, resourcePathPrefix);
    LOG.info(INIT_PARAM_RESOURCE_PATH_PREFIX + " is '" + resourcePathPrefix + "'");

    String configParam = getInitParameter(INIT_PARAM_RESOURCE_CONFIG);
    if (configParam != null)
        try {
            getResourceConfig().parse(context.getResource(configParam));
        } catch (MalformedURLException e) {
            LOG.debug("Unable to build resource filter provider");
        }
}

From source file:org.springframework.cloud.netflix.eureka.server.EurekaServerBootstrap.java

public void contextInitialized(ServletContext context) {
    try {/*from w ww  . j  av  a  2  s .  com*/
        initEurekaEnvironment();
        initEurekaServerContext();

        context.setAttribute(EurekaServerContext.class.getName(), this.serverContext);
    } catch (Throwable e) {
        log.error("Cannot bootstrap eureka server :", e);
        throw new RuntimeException("Cannot bootstrap eureka server :", e);
    }
}

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

@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 .  ja  v  a2  s  .  c  o  m
    InputStream is = null;

    try {
        if (ServletFileUpload.isMultipartContent(request)) {
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            List<FileItem> items = upload.parseRequest(request);
            String docUuid = null;
            String repoPath = null;
            String text = null;
            String mimeType = null;
            String extractor = null;

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

                if (item.isFormField()) {
                    if (item.getFieldName().equals("docUuid")) {
                        docUuid = item.getString("UTF-8");
                    } else if (item.getFieldName().equals("repoPath")) {
                        repoPath = item.getString("UTF-8");
                    }
                } else {
                    is = item.getInputStream();
                    String name = FilenameUtils.getName(item.getName());
                    mimeType = MimeTypeConfig.mimeTypes.getContentType(name.toLowerCase());

                    if (!name.isEmpty() && item.getSize() > 0) {
                        docUuid = null;
                        repoPath = null;
                    } else if (docUuid.isEmpty() && repoPath.isEmpty()) {
                        mimeType = null;
                    }
                }
            }

            if (docUuid != null && !docUuid.isEmpty()) {
                repoPath = OKMRepository.getInstance().getNodePath(null, docUuid);
            }

            if (repoPath != null && !repoPath.isEmpty()) {
                String name = PathUtils.getName(repoPath);
                mimeType = MimeTypeConfig.mimeTypes.getContentType(name.toLowerCase());
                is = OKMDocument.getInstance().getContent(null, repoPath, false);
            }

            long begin = System.currentTimeMillis();

            if (is != null) {
                if (!MimeTypeConfig.MIME_UNDEFINED.equals(mimeType)) {
                    TextExtractor extClass = RegisteredExtractors.getTextExtractor(mimeType);

                    if (extClass != null) {
                        extractor = extClass.getClass().getCanonicalName();
                        text = RegisteredExtractors.getText(mimeType, null, is);
                    } else {
                        extractor = "Undefined text extractor";
                    }
                }
            }

            ServletContext sc = getServletContext();
            sc.setAttribute("docUuid", docUuid);
            sc.setAttribute("repoPath", repoPath);
            sc.setAttribute("text", text);
            sc.setAttribute("time", System.currentTimeMillis() - begin);
            sc.setAttribute("mimeType", mimeType);
            sc.setAttribute("extractor", extractor);
            sc.getRequestDispatcher("/admin/check_text_extraction.jsp").forward(request, response);
        }
    } catch (DatabaseException e) {
        sendErrorRedirect(request, response, e);
    } catch (FileUploadException e) {
        sendErrorRedirect(request, response, e);
    } catch (PathNotFoundException e) {
        sendErrorRedirect(request, response, e);
    } catch (AccessDeniedException e) {
        sendErrorRedirect(request, response, e);
    } catch (RepositoryException e) {
        sendErrorRedirect(request, response, e);
    } finally {
        IOUtils.closeQuietly(is);
    }
}

From source file:fi.helsinki.opintoni.config.WebConfigurer.java

/**
 * Initializes Metrics./* w  w  w . j a  v a  2s  .co m*/
 */
private void initMetrics(ServletContext servletContext, EnumSet<DispatcherType> disps) {
    log.debug("Initializing Metrics registries");
    servletContext.setAttribute(InstrumentedFilter.REGISTRY_ATTRIBUTE, metricRegistry);
    servletContext.setAttribute(MetricsServlet.METRICS_REGISTRY, metricRegistry);

    log.debug("Registering Metrics Filter");
    FilterRegistration.Dynamic metricsFilter = servletContext.addFilter("webappMetricsFilter",
            new InstrumentedFilter());

    metricsFilter.addMappingForUrlPatterns(disps, true, "/*");
    metricsFilter.setAsyncSupported(true);

    log.debug("Registering Metrics Servlet");
    ServletRegistration.Dynamic metricsAdminServlet = servletContext.addServlet("metricsServlet",
            new MetricsServlet());

    metricsAdminServlet.addMapping("/metrics/metrics/*");
    metricsAdminServlet.setAsyncSupported(true);
    metricsAdminServlet.setLoadOnStartup(2);
}

From source file:org.apache.synapse.core.axis2.SynapseAxisServlet.java

/**
 * Overrides init method so that avoid  starting listeners again
 *
 * @param config//w w  w .jav  a 2 s  .com
 * @throws ServletException
 */
public void init(ServletConfig config) throws ServletException {
    ServletContext servletContext = config.getServletContext();
    this.configContext = ServerManager.getInstance().getConfigurationContext();
    this.axisConfiguration = this.configContext.getAxisConfiguration();
    servletContext.setAttribute(this.getClass().getName(), this);
    this.servletConfig = config;

    // Initialize the agent field. Since it is declared private, we need to do
    // it using reflection.
    try {
        Field agentField = AxisServlet.class.getDeclaredField("agent");
        agentField.setAccessible(true);
        agentField.set(this, new ListingAgent(configContext));
    } catch (Throwable ex) {
        log.warn("Unable to initialize AxisServlet#agent. Published WSDL documents may be inaccessible.");
    }

    initParams();
}

From source file:com.anhao.market.web.listener.ServletListener.java

@Override
public void contextInitialized(ServletContextEvent sce) {
    logger.info("ServletListener Starting...");
    springContext = WebApplicationContextUtils.getWebApplicationContext(sce.getServletContext());
    //start/*  w  w w. ja  v  a2 s. co m*/
    ServletContext sc = sce.getServletContext();
    //?
    ConfigService configService = (ConfigService) springContext.getBean("configService");
    logger.info("this is config {}", configService.getSystemConfig());
    sc.setAttribute("systemName", "??");
    sc.setAttribute("systemConfig", configService.getSystemConfig());
    logger.info("ServletListener Started now");
}

From source file:org.apache.myfaces.webapp.StartupServletContextListener.java

public static void initFaces(ServletContext servletContext) {
    try {/* w  w w.j  a va 2s  . c om*/
        Boolean b = (Boolean) servletContext.getAttribute(FACES_INIT_DONE);

        if (b == null || b.booleanValue() == false) {
            log.trace("Initializing MyFaces");

            //Load the configuration
            ExternalContext externalContext = new ServletExternalContextImpl(servletContext, null, null);

            //And configure everything
            new FacesConfigurator(externalContext).configure();

            if ("true".equals(servletContext.getInitParameter(FacesConfigValidator.VALIDATE_CONTEXT_PARAM))
                    || "true".equals(servletContext
                            .getInitParameter(FacesConfigValidator.VALIDATE_CONTEXT_PARAM.toLowerCase()))) {
                List list = FacesConfigValidator.validate(externalContext, servletContext.getRealPath("/"));

                Iterator iterator = list.iterator();

                while (iterator.hasNext())
                    log.warn(iterator.next());

            }

            // parse web.xml
            WebXml.init(externalContext);

            servletContext.setAttribute(FACES_INIT_DONE, Boolean.TRUE);
        } else {
            log.info("MyFaces already initialized");
        }
    } catch (Exception ex) {
        log.error("Error initializing ServletContext", ex);
        ex.printStackTrace();
    }
    log.info("ServletContext '" + servletContext.getRealPath("/") + "' initialized.");

    if (servletContext.getInitParameter(StateUtils.INIT_SECRET) != null
            || servletContext.getInitParameter(StateUtils.INIT_SECRET.toLowerCase()) != null)
        StateUtils.initSecret(servletContext);
}

From source file:org.josso.gateway.signon.SSOContextListener.java

public void contextInitialized(ServletContextEvent event) {
    try {/*from   w ww . ja  v a  2s. c  o  m*/
        // This will initialize all needed components

        Lookup lookup = Lookup.getInstance();
        lookup.init("josso-gateway-config.xml");
        lookup.lookupSSOGateway();

        // Build and initialize the SSO Gateway
        ServletContext ctx = event.getServletContext();
        SSOGateway g = (SSOGateway) ctx.getAttribute(KEY_JOSSO_GATEWAY);
        if (g == null) {
            g = Lookup.getInstance().lookupSSOGateway();
            ctx.setAttribute(KEY_JOSSO_GATEWAY, g);
        }

    } catch (Exception e) {
        logger.error(e.getMessage(), e);
    }

}