List of usage examples for javax.servlet ServletContext getResourceAsStream
public InputStream getResourceAsStream(String path);
InputStream
object. From source file:com.xpn.xwiki.web.XWikiConfigurationService.java
public synchronized static String getProperty(String propertyKey, String defaultValue, ServletContext context) { if (config == null) { // Make XWikiRequestProcessor own configuration loader since XWiki of Configuration component are not // initialized at this time InputStream xwikicfgis = null; String configurationLocation; try {/*from w w w .j av a 2 s . c o m*/ configurationLocation = XWiki.getConfigPath(); // First try loading from a file. File f = new File(configurationLocation); try { if (f.exists()) { xwikicfgis = new FileInputStream(f); } } catch (Exception e) { // Error loading the file. Most likely, the Security Manager prevented it. // We'll try loading it as a resource below. LOG.debug("Failed to load the file [" + configurationLocation + "] using direct " + "file access. The error was [" + e.getMessage() + "]. Trying to load it " + "as a resource using the Servlet Context..."); } // Second, try loading it as a resource using the Servlet Context if (xwikicfgis == null) { xwikicfgis = context.getResourceAsStream(configurationLocation); LOG.debug("Failed to load the file [" + configurationLocation + "] as a resource " + "using the Servlet Context. Trying to load it as classpath resource..."); } // Third, try loading it from the classloader used to load this current class if (xwikicfgis == null) { xwikicfgis = XWiki.class.getClassLoader().getResourceAsStream("xwiki.cfg"); } config = new XWikiConfig(xwikicfgis); } catch (Exception e) { LOG.error("Faile to lod configuration", e); config = new XWikiConfig(); } } return config.getProperty(propertyKey, defaultValue); }
From source file:org.tonguetied.web.servlet.ServletContextInitializer.java
/** * Load the jdbc properties for communication with the database. * /*from w w w .j a v a 2 s .co m*/ * @param servletContext * @param fileName the file name and location of the resource to load * * @return the jdbc properties */ private Properties loadProperties(ServletContext servletContext, final String fileName) { InputStream is = null; Properties props = new Properties(); try { is = servletContext.getResourceAsStream(fileName); props.load(is); } catch (IOException ioe) { logger.error("failed to load properties file", ioe); } finally { IOUtils.closeQuietly(is); } return props; }
From source file:de.appsolve.padelcampus.utils.HtmlResourceUtil.java
private void replaceVariables(ServletContext context, List<CssAttribute> cssAttributes, String FILE_NAME, File destDir) throws IOException { InputStream lessIs = context.getResourceAsStream(FILE_NAME); Path outputPath = new File(destDir, FILE_NAME).toPath(); String content = IOUtils.toString(lessIs, Constants.UTF8); for (CssAttribute attribute : cssAttributes) { if (!StringUtils.isEmpty(attribute.getCssValue())) { content = content.replaceAll(attribute.getCssDefaultValue(), attribute.getCssValue()); }/*w w w . j a v a2s . co m*/ } //overwrite variables.less in data directory if (!Files.exists(outputPath)) { if (!Files.exists(outputPath.getParent())) { Files.createDirectory(outputPath.getParent()); } Files.createFile(outputPath); } Files.write(outputPath, content.getBytes(Constants.UTF8), StandardOpenOption.CREATE, StandardOpenOption.WRITE); }
From source file:com.almende.eve.deploy.EveListener.java
@Override public void contextInitialized(ServletContextEvent sce) { final ServletContext sc = sce.getServletContext(); // Get the eve.yaml file: String path = sc.getInitParameter("eve_config"); if (path != null && !path.isEmpty()) { final String fullname = "/WEB-INF/" + path; LOG.info("loading configuration file '" + sc.getRealPath(fullname) + "'..."); final InputStream is = sc.getResourceAsStream(fullname); if (is == null) { LOG.warning("Can't find the given configuration file:" + sc.getRealPath(fullname)); return; }// ww w . j a v a2 s .c om myConfig = Boot.boot(is); } }
From source file:org.openflamingo.engine.util.VersionConfigurer.java
/** * Notification that the web application initialization * process is starting./*from ww w. java 2s .co m*/ * All ServletContextListeners are notified of context * initialization before any filter or servlet in the web * application is initialized. * * @param servletContextEvent {@link javax.servlet.ServletContextEvent} */ @Override public void contextInitialized(ServletContextEvent servletContextEvent) { Log4jWebConfigurer.initLogging(servletContextEvent.getServletContext()); Properties properties = new Properties(); ServletContext context = servletContextEvent.getServletContext(); InputStream inputStream = null; try { inputStream = context.getResourceAsStream("/WEB-INF/version.properties"); properties.load(inputStream); } catch (Exception ex) { throw new IllegalArgumentException("Cannot load a '/WEB/INF/version.properties' file.", ex); } finally { IOUtils.closeQuietly(inputStream); } StringBuilder builder = new StringBuilder(); printHeader(builder, "Application Information"); Properties appProps = new Properties(); appProps.put("Application", "Flamingo Workflow Engine"); appProps.put("Version", properties.get("version")); appProps.put("Build Date", properties.get("build.timestamp")); appProps.put("Build Number", properties.get("build.number")); appProps.put("Revision Number", properties.get("revision.number")); appProps.put("Build Key", properties.get("build.key")); if (context != null) { appProps.put("Application Server", context.getServerInfo() + " - Servlet API " + context.getMajorVersion() + "." + context.getMinorVersion()); } Properties systemProperties = System.getProperties(); appProps.put("Java Version", systemProperties.getProperty("java.version", UNKNOWN) + " - " + systemProperties.getProperty("java.vendor", UNKNOWN)); appProps.put("Current Working Directory", systemProperties.getProperty("user.dir", UNKNOWN)); print(builder, appProps); printHeader(builder, "JVM Heap Information"); Properties memPros = new Properties(); final Runtime rt = Runtime.getRuntime(); final long maxMemory = rt.maxMemory() / MEGA_BYTES; final long totalMemory = rt.totalMemory() / MEGA_BYTES; final long freeMemory = rt.freeMemory() / MEGA_BYTES; final long usedMemory = totalMemory - freeMemory; memPros.put("Maximum Allowable Memory", maxMemory + "MB"); memPros.put("Total Memory", totalMemory + "MB"); memPros.put("Free Memory", freeMemory + "MB"); memPros.put("Used Memory", usedMemory + "MB"); print(builder, memPros); printHeader(builder, "Java System Properties"); Properties sysProps = new Properties(); for (final Map.Entry<Object, Object> entry : systemProperties.entrySet()) { sysProps.put(entry.getKey(), entry.getValue()); } print(builder, sysProps); printHeader(builder, "System Environments"); Map<String, String> getenv = System.getenv(); Properties envProps = new Properties(); Set<String> strings = getenv.keySet(); for (String key : strings) { String message = getenv.get(key); envProps.put(key, message); } print(builder, envProps); logger.info("================================================="); logger.info(" Flamingo Workflow Engine starting..."); logger.info("=================================================\n{}", builder.toString()); }
From source file:org.trimou.servlet.locator.ServletContextTemplateLocator.java
@Override public Reader locate(String templatePath) { ServletContext ctx = getServletContext(); if (ctx == null) { throw new MustacheException(MustacheProblem.TEMPLATE_LOADING_ERROR, "Servlet context not available"); }//from w ww.j av a2 s.c om InputStream in = ctx.getResourceAsStream(getRootPath() + addSuffix(toRealPath(templatePath))); if (in == null) { return null; } logger.debug("Template located: {}", templatePath); try { return new InputStreamReader(in, getDefaultFileEncoding()); } catch (UnsupportedEncodingException e) { throw new MustacheException(MustacheProblem.TEMPLATE_LOADING_ERROR, e); } }
From source file:net.morphbank.mbsvc3.webservices.RestService.java
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { if (!isIPAllowed(request.getRemoteAddr())) { response.sendError(HttpServletResponse.SC_FORBIDDEN, "This IP is not allowed. Current IP used:" + request.getRemoteAddr()); return;// w w w. j a va2 s . com } PrintWriter out = response.getWriter(); MorphbankConfig.SYSTEM_LOGGER.info("starting post from ip:" + request.getRemoteAddr()); MorphbankConfig.ensureWorkingConnection(); response.setContentType("text/xml"); MorphbankConfig.SYSTEM_LOGGER.info("<!-- persistence: " + MorphbankConfig.getPersistenceUnit() + " -->"); MorphbankConfig.SYSTEM_LOGGER.info("<!-- filepath: " + folderPath + " -->"); boolean isMultipart = ServletFileUpload.isMultipartContent(request); FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); // response.setContentType("text/html"); String parameter = request.getParameter("uploadxml"); if (parameter != null) { ServletContext context = getServletContext(); InputStream fis = context.getResourceAsStream(parameter); processRequest(fis, out, request.getParameter("fileName")); } else { try { // Process the uploaded items List<?> /* FileItem */ items = upload.parseRequest(request); Iterator<?> iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (item.isFormField()) { // processFormField(item); } else { // processUploadedFile(item); String paramName = item.getFieldName(); String fileName = item.getName(); InputStream stream = item.getInputStream(); MorphbankConfig.SYSTEM_LOGGER.info("Processing file " + fileName); processRequest(stream, out, fileName); MorphbankConfig.SYSTEM_LOGGER.info("Processing complete"); } } } catch (FileUploadException e) { e.printStackTrace(); } } }
From source file:com.ocpsoft.pretty.faces.config.spi.ContextSpecifiedConfigurationProvider.java
public PrettyConfig loadConfiguration(ServletContext servletContext) { final PrettyConfigBuilder builder = new PrettyConfigBuilder(); PrettyConfigParser configParser = new DigesterPrettyConfigParser(); final List<String> configFilesList = getConfigFilesList(servletContext); for (final String configFilePath : configFilesList) { final InputStream is = servletContext.getResourceAsStream(configFilePath); if (is == null) { log.error("Pretty Faces config resource [" + configFilePath + "] not found."); continue; }//from w ww . java 2s . co m log.trace("Reading config [" + configFilePath + "]."); try { configParser.parse(builder, is); } catch (Exception e) { throw new PrettyException("Failed to parse PrettyFaces configuration from " + configFilePath, e); } finally { try { is.close(); } catch (IOException ignored) { } } } return builder.build(); }
From source file:org.apache.click.service.ClickResourceService.java
/** * Load the resource for the given resourcePath from the servlet context. * * @param servletContext the application servlet context * @param resourcePath the path of the resource to load * @return the byte array for the given resource path * @throws IOException if the resource could not be loaded *///from w w w. j av a 2 s. com private byte[] getServletResourceData(ServletContext servletContext, String resourcePath) throws IOException { InputStream inputStream = null; try { inputStream = servletContext.getResourceAsStream(resourcePath); if (inputStream != null) { return IOUtils.toByteArray(inputStream); } else { return null; } } finally { ClickUtils.close(inputStream); } }
From source file:org.pepstock.jem.gwt.server.listeners.StartUp.java
/** * Starts Hazelcast client.// w ww. j av a 2 s . c o m * * @param filename * Hazelast config file * @throws ConfigurationException * if a config error occurs */ private void startHazelcastClient(ServletContext context, String hazelcastFile) throws ConfigurationException { LogAppl.getInstance().emit(UserInterfaceMessage.JEMG006I); //String filename = contextPath + hazelcastFile; InputStream input = context.getResourceAsStream(hazelcastFile); StringWriter sw = new StringWriter(); // loads configuration file from XML file InMemoryXmlConfig config; try { IOUtils.copy(input, sw, CharSet.DEFAULT); //config = new FileSystemXmlConfig(filename); config = new InMemoryXmlConfig(sw.toString()); } catch (Exception e) { throw new ConfigurationException(e); } // start connector service try { SharedObjects.getInstance().setHazelcastConfig(config); try { SharedObjects.getInstance().setNetworkInterface(InterfacesUtils.getInterface(config)); // Overrides the NetworkConfig network = config.getNetworkConfig(); Interfaces interfaces = network.getInterfaces(); // overrides network only if is not set if (interfaces == null) { network.getInterfaces().setEnabled(true) .addInterface(Main.getNetworkInterface().getAddress().getHostAddress()); } LogAppl.getInstance().emit(NodeMessage.JEMC273I, SharedObjects.getInstance().getNetworkInterface()); } catch (MessageException e) { throw new ConfigurationException(e); } Service connectorService = ConnectorServiceFactory.getConnectorService(); SharedObjects.getInstance().setConnectorService(connectorService); SharedObjects.getInstance().getConnectorService().start(); } catch (Exception e) { throw new ConfigurationException(e); } }