Example usage for javax.servlet ServletContext log

List of usage examples for javax.servlet ServletContext log

Introduction

In this page you can find the example usage for javax.servlet ServletContext log.

Prototype

public void log(String msg);

Source Link

Document

Writes the specified message to a servlet log file, usually an event log.

Usage

From source file:org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.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 ww  w  .  ja v  a2  s  .co m*/
protected void prepareWebApplicationContext(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 | Error ex) {
        logger.error("Context initialization failed", ex);
        servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, ex);
        throw ex;
    }
}

From source file:org.springframework.web.context.ContextLoader.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 www  . j av  a  2  s.co 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(ContextLoader.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 == ContextLoader.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:nl.strohalm.cyclos.http.LifecycleListener.java

/**
 * @see javax.servlet.ServletContextListener#contextInitialized(javax.servlet.ServletContextEvent)
 *///from ww w .j  av  a  2s  . c o m
@Override
public void contextInitialized(final ServletContextEvent event) {
    LoggedUser.runAsSystem(new Callable<Void>() {
        @Override
        public Void call() {
            try {
                final ServletContext context = event.getServletContext();

                final WebApplicationContext applicationContext = WebApplicationContextUtils
                        .getWebApplicationContext(context);
                SpringHelper.injectBeans(applicationContext, LifecycleListener.this);

                applicationService.initialize();

                context.setAttribute("systemOnline", applicationService.isOnline());
                context.setAttribute("cyclosVersion", applicationService.getCyclosVersion());

                // Run web initializations
                final Collection<LocalWebInitialization> initializations = applicationContext
                        .getBeansOfType(LocalWebInitialization.class).values();
                runAll(initializations);

                final LocalSettings settings = settingsService.getLocalSettings();
                context.log(settings.getApplicationName() + " initialized");

                // Suggest a GC in order to keep the heap low right after a startup
                System.gc();
            } catch (final Throwable e) {
                LOG.error("Error on LifecycleListener.contextInitialized()", e);
                throw new RuntimeException(e);
            }
            return null; // required by compiler
        }
    });
}

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/* www  .  ja v  a2s. com*/
 * @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:com.ecyrd.jspwiki.WikiEngine.java

/**
 *  Gets a WikiEngine related to the servlet. Works just like getInstance( ServletConfig )
 *
 *  @param context The ServletContext of the webapp servlet/JSP calling this method.
 *  @param props  A set of properties, or null, if we are to load JSPWiki's default
 *                jspwiki.properties (this is the usual case).
 *
 *  @return One fully functional, properly behaving WikiEngine.
 *  @throws InternalWikiException If the WikiEngine instantiation fails.
 *//*from  w  ww .j  a v  a 2  s  . co m*/

// FIXME: Potential make-things-easier thingy here: no need to fetch the wikiengine anymore
//        Wiki.jsp.jspInit() [really old code]; it's probably even faster to fetch it
//        using this method every time than go to pageContext.getAttribute().

public static synchronized WikiEngine getInstance(ServletContext context, Properties props)
        throws InternalWikiException {
    WikiEngine engine = (WikiEngine) context.getAttribute(ATTR_WIKIENGINE);

    if (engine == null) {
        String appid = Integer.toString(context.hashCode()); //FIXME: Kludge, use real type.

        context.log(" Assigning new engine to " + appid);
        try {
            if (props == null) {
                props = PropertyReader.loadWebAppProps(context);
            }

            engine = new WikiEngine(context, appid, props);
            context.setAttribute(ATTR_WIKIENGINE, engine);
        } catch (Exception e) {
            context.log("ERROR: Failed to create a Wiki engine: " + e.getMessage());
            throw new InternalWikiException("No wiki engine, check logs.");
        }

    }

    return engine;
}

From source file:org.apache.wiki.WikiEngine.java

/**
 *  Gets a WikiEngine related to the servlet. Works just like getInstance( ServletConfig )
 *
 *  @param context The ServletContext of the webapp servlet/JSP calling this method.
 *  @param props  A set of properties, or null, if we are to load JSPWiki's default
 *                jspwiki.properties (this is the usual case).
 *
 *  @return One fully functional, properly behaving WikiEngine.
 *  @throws InternalWikiException If the WikiEngine instantiation fails.
 *//*w  ww .j  a  v  a2s  .co m*/

// FIXME: Potential make-things-easier thingy here: no need to fetch the wikiengine anymore
//        Wiki.jsp.jspInit() [really old code]; it's probably even faster to fetch it
//        using this method every time than go to pageContext.getAttribute().

public static synchronized WikiEngine getInstance(ServletContext context, Properties props)
        throws InternalWikiException {
    WikiEngine engine = (WikiEngine) context.getAttribute(ATTR_WIKIENGINE);

    if (engine == null) {
        String appid = Integer.toString(context.hashCode()); //FIXME: Kludge, use real type.

        context.log(" Assigning new engine to " + appid);
        try {
            if (props == null) {
                props = PropertyReader.loadWebAppProps(context);
            }

            engine = new WikiEngine(context, appid, props);
            context.setAttribute(ATTR_WIKIENGINE, engine);
        } catch (Exception e) {
            context.log("ERROR: Failed to create a Wiki engine: " + e.getMessage());
            log.error("ERROR: Failed to create a Wiki engine, stacktrace follows ", e);
            throw new InternalWikiException("No wiki engine, check logs.");
        }

    }

    return engine;
}

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 w w w  . j av a 2s .c o m
 *  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.krawler.esp.servlets.ProfileImageServlet.java

public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    // Get the absolute path of the image
    ServletContext sc = getServletContext();
    String uri = req.getRequestURI();
    String servletBase = req.getServletPath();
    if (!StringUtil.isNullOrEmpty(req.getParameter("flag"))) {
        try {// w w w.  j a va2 s . c om
            // TODO: Fix hardcoded url
            if (!StringUtil.isNullOrEmpty(req.getParameter("trackid"))) {
                String url = "/remoteapi.jsp?action=100&data={\"iscommit\":true}&trackid="
                        + req.getParameter("trackid");
                RequestDispatcher rd = req.getRequestDispatcher(url);
                rd.include(req, resp);
            }
            String fileName = StorageHandler.GetProfileImgStorePath() + "blankImage.png";
            File file = new File(fileName);
            if (file.exists()) {
                FileInputStream in = new FileInputStream(file);
                OutputStream out = resp.getOutputStream();

                // Copy the contents of the file to the output stream
                byte[] buf = new byte[4096];
                int count = 0;
                while ((count = in.read(buf)) >= 0) {
                    out.write(buf, 0, count);
                }
                in.close();
                out.close();
            }
        } catch (Exception e) {
            logger.warn(e.getMessage(), e);
        }
    } else {
        boolean Companyflag = (req.getParameter("company") != null) ? true : false;
        String imagePath = defaultImgPath;
        String requestedFileName = "";
        if (Companyflag) {
            imagePath = defaultCompanyImgPath;
            String companyId = null;
            try {
                companyId = sessionHandlerImpl.getCompanyid(req);
            } catch (Exception ee) {
                logger.warn(ee.getMessage(), ee);
            }
            if (StringUtil.isNullOrEmpty(companyId)) {
                String domain = URLUtil.getDomainName(req);
                if (!StringUtil.isNullOrEmpty(domain)) {
                    //@@@
                    //                        companyId = sessionHandlerImpl.getCompanyid(domain);
                    requestedFileName = "/original_" + companyId + ".png";
                } else {
                    requestedFileName = "logo.gif";
                }
            } else {
                requestedFileName = "/" + companyId + ".png";
            }
        } else {
            requestedFileName = uri.substring(uri.lastIndexOf(servletBase) + servletBase.length());
        }
        String fileName = null;

        fileName = StorageHandler.GetProfileImgStorePath() + requestedFileName;
        // Get the MIME type of the image
        String mimeType = sc.getMimeType(fileName);
        if (mimeType == null) {
            sc.log("Could not get MIME type of " + fileName);
            resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            return;
        }

        // Set content type
        resp.setContentType(mimeType);

        // Set content size
        File file = new File(fileName);
        if (!file.exists()) {
            if (fileName.contains("_100.")) {
                file = new File(fileName.replaceAll("_100.", "."));
            }
            if (!file.exists()) {
                file = new File(sc.getRealPath(imagePath));
            }
        }

        resp.setContentLength((int) file.length());

        // Open the file and output streams
        FileInputStream in = new FileInputStream(file);
        OutputStream out = resp.getOutputStream();

        // Copy the contents of the file to the output stream
        byte[] buf = new byte[4096];
        int count = 0;
        while ((count = in.read(buf)) >= 0) {
            out.write(buf, 0, count);
        }
        in.close();
        out.close();
    }
}