private void applyLog4jConfiguration( ConfigurableEnvironment environment, ServletContext servletContext) { String log4jConfigLocation = "classpath:log4j.properties"; if (environment.containsProperty("logging.file")) { String location = environment.getProperty("logging.file"); servletContext.log("Setting LOG_FILE: " + location); System.setProperty("LOG_FILE", location); } else if (environment.containsProperty("logging.path")) { String location = environment.getProperty("logging.path"); servletContext.log("Setting LOG_PATH: " + location); System.setProperty("LOG_PATH", location); } else if (environment.containsProperty("logging.config")) { log4jConfigLocation = environment.getProperty("logging.config"); } try { servletContext.log("Loading log4j config from location: " + log4jConfigLocation); Log4jConfigurer.initLogging(log4jConfigLocation); } catch (FileNotFoundException e) { servletContext.log("Error loading log4j config from location: " + log4jConfigLocation, e); } MDC.put("context", servletContext.getContextPath()); }
public void run() { if (!isRunning) { isRunning = true; context.log("开始执行指定任务"); logger.info("开始执行指定任务 -- 上传文件过期删除记录"); String urlStr = SystemConfig.getSystemConfig().getFileSavePath() + "/sysAction.do?method=fileSystemDel"; String retstr = HttpUtils.callRPC(urlStr); System.out.println("retstr===" + retstr); if (retstr.equals("0")) { logger.info("开始执行指定任务 -- 删除成功"); } else { logger.info("开始执行指定任务 -- 删除失败"); } // 在这里编写自己的功能,例: // File file = new File("temp"); // file.mkdir(); // 启动tomcat,可以发现在tomcat根目录下,会自动创建temp文件夹 // -------------------结束 isRunning = false; context.log("指定任务执行结束"); } else { context.log("上一次任务执行还未结束"); } }
/** @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub application.log("--------- Received request!!"); init(); application.log("--------- Received request!!"); service(request, response); }
private Map<Object, Object> buildContext(ServletContext servletContext) { servletContext.log( "Loading plexus context properties from: '" + DEFAULT_PLEXUS_PROPERTIES + "'"); Map<Object, Object> context = new HashMap<Object, Object>(); String plexusPropertiesPath = servletContext.getInitParameter(PLEXUS_PROPERTIES_PARAM); if (plexusPropertiesPath == null) { plexusPropertiesPath = DEFAULT_PLEXUS_PROPERTIES; } try { URL url = servletContext.getResource(plexusPropertiesPath); // if the user has not specified the plexus.props file then just return the context if (url == null && plexusPropertiesPath == DEFAULT_PLEXUS_PROPERTIES) { return context; } Properties properties = PropertyUtils.loadProperties(url); if (properties == null) { throw new Exception("Could not locate url: " + url.toString()); } String baseDir = servletContext.getRealPath("/WEB-INF"); if (!StringUtils.isEmpty(baseDir)) { servletContext.log("Setting Plexus context variable " + PLEXUS_HOME + " to: " + baseDir); properties.put(PLEXUS_HOME, baseDir); } else { servletContext.log("CANNOT set Plexus basedir! (are we in unpacked WAR?)"); } RegexBasedInterpolator ip = new RegexBasedInterpolator(); ip.addValueSource(new MapBasedValueSource(properties)); ip.addValueSource(new MapBasedValueSource(System.getProperties())); for (Enumeration n = properties.propertyNames(); n.hasMoreElements(); ) { String propertyKey = (String) n.nextElement(); String propertyValue = ip.interpolate(properties.getProperty(propertyKey), ""); servletContext.log("Added '" + propertyKey + "=" + propertyValue + "' to Plexus context."); context.put(propertyKey, propertyValue); } } catch (Exception e) { throw new RuntimeException( "Could not load plexus context properties from: '" + plexusPropertiesPath + "'", e); } return context; }
private boolean isHeroku(ServletContext ctx) { String dbUrlStr = System.getenv("DATABASE_URL"); if (dbUrlStr == null || dbUrlStr.isEmpty()) { ctx.log("****" + "is not Heroku"); return false; } ctx.log("****" + "is Heroku"); return true; }
@Override public void initialize(ConfigurableWebApplicationContext applicationContext) { Resource resource = null; ServletContext servletContext = applicationContext.getServletContext(); WebApplicationContextUtils.initServletPropertySources( applicationContext.getEnvironment().getPropertySources(), servletContext, applicationContext.getServletConfig()); ServletConfig servletConfig = applicationContext.getServletConfig(); String locations = servletConfig == null ? null : servletConfig.getInitParameter(PROFILE_CONFIG_FILE_LOCATIONS); resource = getResource(servletContext, applicationContext, locations); if (resource == null) { servletContext.log( "No YAML environment properties from servlet. Defaulting to servlet context."); locations = servletContext.getInitParameter(PROFILE_CONFIG_FILE_LOCATIONS); resource = getResource(servletContext, applicationContext, locations); } try { servletContext.log("Loading YAML environment properties from location: " + resource); YamlMapFactoryBean factory = new YamlMapFactoryBean(); factory.setResolutionMethod(ResolutionMethod.OVERRIDE_AND_IGNORE); List<Resource> resources = new ArrayList<Resource>(); String defaultLocation = servletConfig == null ? null : servletConfig.getInitParameter(PROFILE_CONFIG_FILE_DEFAULT); if (defaultLocation != null) { Resource defaultResource = new ClassPathResource(defaultLocation); if (defaultResource.exists()) { resources.add(defaultResource); } } resources.add(resource); factory.setResources(resources.toArray(new Resource[resources.size()])); Map<String, Object> map = factory.getObject(); String yamlStr = (new Yaml()).dump(map); map.put(rawYamlKey, yamlStr); NestedMapPropertySource properties = new NestedMapPropertySource("servletConfigYaml", map); applicationContext.getEnvironment().getPropertySources().addLast(properties); applySpringProfiles(applicationContext.getEnvironment(), servletContext); applyLog4jConfiguration(applicationContext.getEnvironment(), servletContext); } catch (Exception e) { servletContext.log("Error loading YAML environment properties from location: " + resource, e); } }
public static Connection getConnection() { if (connection == null) { try { connect(); } catch (IOException e) { sc.log("connect ", e); } } if (connection == null) sc.log("BigtableHelper-No Connection"); return connection; }
public void contextInitialized(ServletContextEvent event) { // This will be invoked as part of a warmup request, or the first user // request if no warmup request was invoked. sc = event.getServletContext(); try { connect(); } catch (IOException e) { sc.log("BigtableHelper - connect ", e); } if (connection == null) sc.log("BigtableHelper-No Connection"); }
@Override public void onStartup(Set<Class<?>> c, ServletContext ctx) throws ServletException { ArrayList<String> portletNames = null; try { URL url = ctx.getResource("WEB-INF/portlet.xml"); // if (url != null) { // XPath to get the portlet names portletNames = new ArrayList<String>(); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.parse(url.openStream()); XPath xpath = XPathFactory.newInstance().newXPath(); XPathExpression expr = xpath.compile("//portlet-name/text()"); NodeList portletNameNodes = (NodeList) expr.evaluate(doc, XPathConstants.NODESET); for (int i = 0; i < portletNameNodes.getLength(); i++) { Text portletNameNode = (Text) portletNameNodes.item(i); portletNames.add(portletNameNode.getWholeText().trim()); } } else { ctx.log("No portlets inside this web application"); } } catch (Exception e) { ctx.log("Could not obtain a valid portlet.xml file", e); } // if (portletNames != null) { ctx.log( "Detected portlet XML file with portlets " + portletNames + " -> Bootstrapping GateIn Portlet Container"); // ServletRegistration.Dynamic embedRegistration = ctx.addServlet("EmbedServlet", EmbedServlet.class); embedRegistration.addMapping("/embed/*"); // ServletRegistration.Dynamic redirectRegistration = ctx.addServlet("RedirectServlet", new RedirectServlet(portletNames)); redirectRegistration.addMapping("/"); } }
public void contextInitialized(ServletContextEvent servletContextEvent) { ServletContext ctx = servletContextEvent.getServletContext(); try { Properties prop = getDbProperties(ctx); InputStream in1 = getClass().getResourceAsStream(WEBINIT_DBXML_PATH); DbScriptsManager.main(in1, prop); ctx.log("DB script executed"); } catch (Exception e) { ctx.log("Unable to execute DB script", e); StringWriter sw = new StringWriter(); e.printStackTrace(new PrintWriter(sw)); } }
public void contextInitialized(ServletContextEvent event) { ServletContext context = event.getServletContext(); String appPath = event.getServletContext().getRealPath(""); String config = context.getInitParameter(CONFIG_PARAM); String extensions = context.getInitParameter(CONFIG_EXTENSIONS_PARAM); if (config == null) { throw new RuntimeException( String.format("failure to specify context init-param - %s", CONFIG_PARAM)); } if (extensions == null) { throw new RuntimeException( String.format("failure to specify context init-param - %s", CONFIG_EXTENSIONS_PARAM)); } InputStream is = null; Properties properties = new Properties(); try { is = getResourceStream(appPath + config, context); properties.load(is); addCsrfExcludeProperties(appPath + extensions, properties); CsrfGuard.load(properties); } catch (Exception e) { throw new RuntimeException(e); } finally { Streams.close(is); } String printConfig = context.getInitParameter(CONFIG_PRINT_PARAM); if (printConfig != null && Boolean.parseBoolean(printConfig)) { context.log(CsrfGuard.getInstance().toString()); } }
private void loadDefaults() throws ServletException { try { loadDefaults(mProperties, new HashSet<String>()); } catch (Exception e) { mServletContext.log("unable to load defaults", e); } }
public void init(FilterConfig filterConfig) throws ServletException { boolean jetty_7_or_greater = "org.eclipse.jetty.servlet".equals(filterConfig.getClass().getPackage().getName()); _context = filterConfig.getServletContext(); String param = filterConfig.getInitParameter("debug"); _debug = param != null && Boolean.parseBoolean(param); if (_debug) __debug = true; param = filterConfig.getInitParameter("jetty6"); if (param == null) param = filterConfig.getInitParameter("partial"); if (param != null) _jetty6 = Boolean.parseBoolean(param); else _jetty6 = ContinuationSupport.__jetty6 && !jetty_7_or_greater; param = filterConfig.getInitParameter("faux"); if (param != null) _faux = Boolean.parseBoolean(param); else _faux = !(jetty_7_or_greater || _jetty6 || _context.getMajorVersion() >= 3); _filtered = _faux || _jetty6; if (_debug) _context.log( "ContinuationFilter " + " jetty=" + jetty_7_or_greater + " jetty6=" + _jetty6 + " faux=" + _faux + " filtered=" + _filtered + " servlet3=" + ContinuationSupport.__servlet3); _initialized = true; }
/** * Initialize logback, including setting the web app root system property. * * @param servletContext the current ServletContext * @see WebUtils#setWebAppRootSystemProperty */ public static void initLogging(ServletContext servletContext) { // Expose the web app root system property. if (exposeWebAppRoot(servletContext)) { WebUtils.setWebAppRootSystemProperty(servletContext); } // Only perform custom logback initialization in case of a config file. String location = servletContext.getInitParameter(CONFIG_LOCATION_PARAM); if (location != null) { // Perform actual logback initialization; else rely on logback's default initialization. try { // Return a URL (e.g. "classpath:" or "file:") as-is; // consider a plain file path as relative to the web application root directory. if (!ResourceUtils.isUrl(location)) { // Resolve system property placeholders before resolving real path. location = SystemPropertyUtils.resolvePlaceholders(location); location = WebUtils.getRealPath(servletContext, location); } // Write log message to server log. servletContext.log("Initializing logback from [" + location + "]"); // Initialize without refresh check, i.e. without logback's watchdog thread. LogbackConfigurer.initLogging(location); } catch (FileNotFoundException ex) { throw new IllegalArgumentException( "Invalid 'logbackConfigLocation' parameter: " + ex.getMessage()); } } }
@Override public void log(String message) { servletContext.log(MESSAGE_PREFIX + message); if (delegate != null) { delegate.log(message); } }
private void discoverProperties() throws ServletException { // load our class loader to resolve resources ClassLoader cloader = TeaServlet.class.getClassLoader(); // specify list of configs to load final String[] configNames = {"META-INF/teaservlet.xml", "META-INF/teaservlet.properties"}; // load each set of configs and process accordingly for (String configName : configNames) { if (mDebugEnabled) { mServletContext.log("Searching for " + configName + " configurations"); } // attempt to load all resources of given name Enumeration<URL> configs = null; try { configs = cloader.getResources(configName); } catch (IOException ioe) { throw new ServletException("unable to load " + configName + " from classpath", ioe); } while (configs.hasMoreElements()) { InputStream input = null; PropertyMap properties = null; // load associated properties of config URL url = configs.nextElement(); if (mDebugEnabled) { mServletContext.log("Loading configuration " + url.toExternalForm()); } try { input = url.openStream(); properties = mResourceFactory.getResourceAsProperties(url.getPath(), input); } catch (IOException ioe) { throw new ServletException("unable to load " + url.toExternalForm(), ioe); } // merge in properties into application properties mergeProperties(properties); // TODO: scan annotations within associated JAR/class path } } }
private void applySpringProfiles( ConfigurableEnvironment environment, ServletContext servletContext) { if (environment.containsProperty("spring_profiles")) { String profiles = environment.getProperty("spring_profiles"); servletContext.log("Setting active profiles: " + profiles); environment.setActiveProfiles(StringUtils.commaDelimitedListToStringArray(profiles)); } }
public void contextDestroyed(ServletContextEvent event) { // App Engine does not currently invoke this method. try { connection.close(); } catch (IOException io) { sc.log("contextDestroyed ", io); } connection = null; }
public void init(ServletContext servletContext) { if (!PlexusLifecycleListener.isLoaded()) { // uh oh! looks like the lifecycle listener wasn't installed. Let's inform the user servletContext.log(PLEXUS_NOT_LOADED_ERROR_MSG); return; } base = (PlexusContainer) servletContext.getAttribute(PlexusLifecycleListener.KEY); }
@Override public void logDebug(String message, Throwable t) { if (debug) { servletContext.log(MESSAGE_PREFIX + message, t); if (delegate != null) { delegate.logDebug(message, t); } } }
/** Initialized servlet */ public void init() { config = getServletConfig(); application = config.getServletContext(); application.log("Servlet is on!"); try { ba = new BuildAuto(); } catch (MyException e) { e.printStackTrace(); } }
public void contextInitialized(ServletContextEvent event) { this.servletContext = event.getServletContext(); String logFile = getDefaultConfigFile(); if (logFile == null) { servletContext.log( this.getClass().getName() + ": Could not find " + "a " + logSystem + " config file. Default configuration " + "will be used."); return; } servletContext.log( this.getClass().getName() + ": Initializing " + logSystem + " from " + logFile); configure(logFile); }
public void run() { Calendar cal = Calendar.getInstance(); if (!isRunning) { if (C_SCHEDULE_HOUR == cal.get(Calendar.HOUR_OF_DAY)) { isRunning = true; context.log("开始执行指定任务"); // TODO 添加自定义的详细任务,以下只是示例 int i = 0; while (i++ < 10) { context.log("已完成任务的" + i + "/" + 10); } isRunning = false; context.log("指定任务执行结束"); } } else { context.log("上一次任务执行还未结束"); } }
/** * Shut down logback, properly releasing all file locks and resetting the web app root system * property. * * @param servletContext the current ServletContext * @see WebUtils#removeWebAppRootSystemProperty */ public static void shutdownLogging(ServletContext servletContext) { servletContext.log("Shutting down logback"); try { LogbackConfigurer.shutdownLogging(); } finally { // Remove the web app root system property. if (exposeWebAppRoot(servletContext)) { WebUtils.removeWebAppRootSystemProperty(servletContext); } } }
/** * Close Spring's web application context for the given servlet context. If the default {@link * #loadParentContext(ServletContext)} implementation, which uses * ContextSingletonBeanFactoryLocator, has loaded any shared parent context, release one reference * to that shared parent context. * * <p>If overriding {@link #loadParentContext(ServletContext)}, you may have to override this * method as well. * * @param servletContext the ServletContext that the WebApplicationContext runs in */ public void closeWebApplicationContext(ServletContext servletContext) { servletContext.log("Closing Spring root WebApplicationContext"); try { if (this.context instanceof ConfigurableWebApplicationContext) { ((ConfigurableWebApplicationContext) this.context).close(); } } finally { if (this.parentContextRef != null) { this.parentContextRef.release(); } } }
private void checkAttribute( HttpSessionBindingEvent event, String orderAttributeName, String keyItemName, String message) { String currentAttributeName = event.getName(); String currentItemName = (String) event.getValue(); if (currentAttributeName.equals(orderAttributeName) && currentItemName.equals(keyItemName)) { ServletContext context = event.getSession().getServletContext(); context.log("Customer" + message + keyItemName + "."); } }
private PropertyMap loadProperties(PropertyMap factoryProps) throws Exception { String className = null; PropertyMapFactory factory = null; if (factoryProps != null && factoryProps.size() > 0 && (className = factoryProps.getString("class")) != null) { if (mDebugEnabled) { mServletContext.log("Using property factory: " + className); } // Load and use custom PropertyMapFactory. Class<?> factoryClass = Class.forName(className); java.lang.reflect.Constructor<?> ctor = factoryClass.getConstructor(new Class[] {Map.class}); factory = (PropertyMapFactory) ctor.newInstance(new Object[] {factoryProps.subMap("init")}); } else if (factoryProps == null) { if (mDebugEnabled) { mServletContext.log("factoryProps is null."); } } else if (factoryProps.size() == 0) { if (mDebugEnabled) { mServletContext.log("factory props size is 0."); } } else { if (mDebugEnabled) { mServletContext.log("className is null"); } } // return properties PropertyMap result = null; if (factory != null) { result = factory.createProperties(); if (mDebugEnabled) { mServletContext.log("properties: " + result); } } return result; }
private void deleteFiles(ServletRequest request) { ArrayList files = (ArrayList) request.getAttribute(FILES); if (files != null) { Iterator iter = files.iterator(); while (iter.hasNext()) { File file = (File) iter.next(); try { file.delete(); } catch (Exception e) { _context.log("failed to delete " + file, e); } } } }
/** * Initialize Spring's web application context for the given servlet context, 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 * @throws IllegalStateException if there is already a root application context present * @throws BeansException if the context failed to initialize * @see #CONTEXT_CLASS_PARAM * @see #CONFIG_LOCATION_PARAM */ public WebApplicationContext initWebApplicationContext(ServletContext servletContext) throws IllegalStateException, BeansException { 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!"); } servletContext.log("Initializing Spring root WebApplicationContext"); if (this.logger.isInfoEnabled()) { this.logger.info("Root WebApplicationContext: initialization started"); } long startTime = System.currentTimeMillis(); try { // Determine parent for root web application context, if any. ApplicationContext parent = loadParentContext(servletContext); // Store context in local instance variable, to guarantee that // it is available on ServletContext shutdown. this.context = createWebApplicationContext(servletContext, parent); servletContext.setAttribute( WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, this.context); if (this.logger.isDebugEnabled()) { this.logger.debug( "Published root WebApplicationContext as ServletContext attribute with name [" + WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE + "]"); } if (this.logger.isInfoEnabled()) { long elapsedTime = System.currentTimeMillis() - startTime; this.logger.info( "Root WebApplicationContext: initialization completed in " + elapsedTime + " ms"); } return this.context; } catch (RuntimeException ex) { this.logger.error("Context initialization failed", ex); servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, ex); throw ex; } catch (Error err) { this.logger.error("Context initialization failed", err); servletContext.setAttribute( WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, err); throw err; } }
public void contextInitialized(ServletContextEvent event) { ServletContext servletContext = event.getServletContext(); String location = servletContext.getInitParameter(CONFIG_LOCATION_PARAM); if (location != null) { try { servletContext.log("初始化 logback,配置文件[" + location + "]"); initLogging(location); } catch (JoranException ex) { throw new IllegalArgumentException("无效'logbackConfigLocation'参数: " + ex.getMessage()); } } }