List of usage examples for javax.servlet ServletContext getResourceAsStream
public InputStream getResourceAsStream(String path);
InputStream
object. From source file:org.tonguetied.web.servlet.ServletContextInitializer.java
/** * Load the SQL schema files used to create the database. * //from w w w . j av a 2 s . co m * @param servletContext * @param dialect the SQL dialect * @param administrationService the administration service * @return a string representation of each SQL file */ private String[] loadSchemas(ServletContext servletContext, final String dialect, AdministrationService administrationService) { InputStream is = null; try { List<String> schemas = new ArrayList<String>(); final String schemaFile = DIR_SQL + "/" + administrationService.getSchemaFileName(dialect); is = servletContext.getResourceAsStream(schemaFile); schemas.add(IOUtils.toString(is)); is = servletContext.getResourceAsStream(DIR_SQL + "/initial-data.sql"); schemas.add(IOUtils.toString(is)); return schemas.toArray(new String[schemas.size()]); } catch (IOException ioe) { logger.error("failed to load file", ioe); throw new IllegalStateException("failed to load schemas", ioe); } finally { IOUtils.closeQuietly(is); } }
From source file:org.apache.struts.webapp.tiles.channel.ChannelFactorySet.java
/** * Parse specified xml file and add definition to specified definitions set. * This method is used to load several description files in one instances list. * If filename exist and definition set is null, create a new set. Otherwise, return * passed definition set (can be null)./* w w w. ja va 2 s .co m*/ * @param servletContext Current servlet context. Used to open file. * @param filename Name of file to parse. * @param xmlDefinitions Definitions set to which definitions will be added. If null, a definitions * set is created on request. * @return XmlDefinitionsSet The definitions set created or passed as parameter. * @throws DefinitionsFactoryException If an error happen during file parsing. */ private XmlDefinitionsSet parseXmlFile(ServletContext servletContext, String filename, XmlDefinitionsSet xmlDefinitions) throws DefinitionsFactoryException { try { log.debug("Trying to load '" + filename + "'."); InputStream input = servletContext.getResourceAsStream(filename); if (input == null) { return xmlDefinitions; } xmlParser = new XmlParser(); // Check if definition set already exist. if (xmlDefinitions == null) { xmlDefinitions = new XmlDefinitionsSet(); } xmlParser.parse(input, xmlDefinitions); } catch (SAXException ex) { log.debug("Error while parsing file '" + filename + "'.", ex); throw new DefinitionsFactoryException("Error while parsing file '" + filename + "'. " + ex.getMessage(), ex); } catch (IOException ex) { throw new DefinitionsFactoryException( "IO Error while parsing file '" + filename + "'. " + ex.getMessage(), ex); } return xmlDefinitions; }
From source file:org.apache.jasper.compiler.JspConfig.java
private void processWebDotXml(ServletContext ctxt) throws JasperException { InputStream is = ctxt.getResourceAsStream(WEB_XML); if (is == null) { // no web.xml return;// w w w .j a v a 2s . c o m } ParserUtils pu = new ParserUtils(); TreeNode webApp = pu.parseXMLDocument(WEB_XML, is); if (webApp == null || !"2.4".equals(webApp.findAttribute("version"))) { defaultIsELIgnored = "true"; return; } TreeNode jspConfig = webApp.findChild("jsp-config"); if (jspConfig == null) { return; } jspProperties = new Vector(); Iterator jspPropertyList = jspConfig.findChildren("jsp-property-group"); while (jspPropertyList.hasNext()) { TreeNode element = (TreeNode) jspPropertyList.next(); Iterator list = element.findChildren(); Vector urlPatterns = new Vector(); String pageEncoding = null; String scriptingInvalid = null; String elIgnored = null; String isXml = null; Vector includePrelude = new Vector(); Vector includeCoda = new Vector(); while (list.hasNext()) { element = (TreeNode) list.next(); String tname = element.getName(); if ("url-pattern".equals(tname)) urlPatterns.addElement(element.getBody()); else if ("page-encoding".equals(tname)) pageEncoding = element.getBody(); else if ("is-xml".equals(tname)) isXml = element.getBody(); else if ("el-ignored".equals(tname)) elIgnored = element.getBody(); else if ("scripting-invalid".equals(tname)) scriptingInvalid = element.getBody(); else if ("include-prelude".equals(tname)) includePrelude.addElement(element.getBody()); else if ("include-coda".equals(tname)) includeCoda.addElement(element.getBody()); } if (urlPatterns.size() == 0) { continue; } // Add one JspPropertyGroup for each URL Pattern. This makes // the matching logic easier. for (int p = 0; p < urlPatterns.size(); p++) { String urlPattern = (String) urlPatterns.elementAt(p); String path = null; String extension = null; if (urlPattern.indexOf('*') < 0) { // Exact match path = urlPattern; } else { int i = urlPattern.lastIndexOf('/'); String file; if (i >= 0) { path = urlPattern.substring(0, i + 1); file = urlPattern.substring(i + 1); } else { file = urlPattern; } // pattern must be "*", or of the form "*.jsp" if (file.equals("*")) { extension = "*"; } else if (file.startsWith("*.")) { extension = file.substring(file.indexOf('.') + 1); } else { if (log.isWarnEnabled()) { log.warn(Localizer.getMessage("jsp.warning.bad.urlpattern.propertygroup", urlPattern)); } continue; } } JspProperty property = new JspProperty(isXml, elIgnored, scriptingInvalid, pageEncoding, includePrelude, includeCoda); JspPropertyGroup propertyGroup = new JspPropertyGroup(path, extension, property); jspProperties.addElement(propertyGroup); } } }
From source file:com.tenduke.example.scribeoauth.BaseServlet.java
/** * Reads a JSON configuration from WEB-INF/[resourceName] * @param resourceName Name of resource in WEB-INF folder. * @param servletContext used to access resource as stream. * @return JSON configuration object./*from ww w.j av a 2 s . com*/ */ protected JSONObject readConfiguration(final String resourceName, final ServletContext servletContext) { // JSONObject retValue; // JSONObject cached = Configuration.get(resourceName); if (cached != null) { // // return a copy (not trusting concurrent access to a JSONObject), of cource the next line // will make concurrent read access to the JSONObject (map). retValue = new JSONObject(cached, JSONObject.getNames(cached)); } else { // try (InputStream is = servletContext .getResourceAsStream(new StringBuilder("/WEB-INF/").append(resourceName).toString()); InputStreamReader reader = new InputStreamReader(is); BufferedReader bufferedReader = new BufferedReader(reader);) { // StringBuilder sb = new StringBuilder(2048); String line; while ((line = bufferedReader.readLine()) != null) { // sb.append(line); } // bufferedReader.close(); reader.close(); is.close(); // cached = new JSONObject(sb.toString()); Configuration.set(resourceName, cached); // // return a copy (not trusting concurrent access to a JSONObject), of cource the next line // will make concurrent read access to the JSONObject (map). retValue = new JSONObject(cached, JSONObject.getNames(cached)); } catch (IOException ex) { // throw new ConfigurationException("Failed to initialize OAuth configuration from oauth.json", ex); } } // return retValue; }
From source file:com.liferay.portal.deploy.hot.ExtHotDeployListener.java
protected void copyJar(ServletContext servletContext, String dir, String jarName) throws Exception { String servletContextName = servletContext.getServletContextName(); String jarFullName = "/WEB-INF/" + jarName + "/" + jarName + ".jar"; InputStream is = servletContext.getResourceAsStream(jarFullName); if (is == null) { throw new HotDeployException(jarFullName + " does not exist"); }//from ww w . jav a2 s . c om String newJarFullName = dir + "ext-" + servletContextName + jarName.substring(3) + ".jar"; StreamUtil.transfer(is, new FileOutputStream(new File(newJarFullName))); }
From source file:org.apache.click.extras.control.Menu.java
/** * Return a copy of the Applications root Menu as defined in the * configuration file "<tt>/WEB-INF/menu.xml</tt>", with the Control * name <tt>"rootMenu"</tt>. * <p/>/*from w ww . ja v a 2s .com*/ * The returned root menu is always selected. * * @deprecated use * {@link MenuFactory#loadFromMenuXml(java.lang.String, java.lang.String, org.apache.click.extras.security.AccessController, java.lang.Class)} * instead * * @param accessController the menu access controller * @return a copy of the application's root Menu */ @Deprecated protected static Menu loadRootMenu(AccessController accessController) { if (accessController == null) { throw new IllegalArgumentException("Null accessController parameter"); } Context context = Context.getThreadLocalContext(); Menu menu = new Menu("rootMenu"); menu.setAccessController(accessController); ServletContext servletContext = context.getServletContext(); InputStream inputStream = servletContext.getResourceAsStream(DEFAULT_CONFIG_FILE); if (inputStream == null) { inputStream = ClickUtils.getResourceAsStream("/menu.xml", Menu.class); if (inputStream == null) { String msg = "could not find configuration file:" + DEFAULT_CONFIG_FILE + " or menu.xml on classpath"; throw new RuntimeException(msg); } } Document document = ClickUtils.buildDocument(inputStream); Element rootElm = document.getDocumentElement(); NodeList list = rootElm.getChildNodes(); for (int i = 0; i < list.getLength(); i++) { Node node = list.item(i); if (node instanceof Element) { Menu childMenu = new Menu((Element) node, accessController); menu.add(childMenu); } } return menu; }
From source file:HackathonSupporter.java
@Override /**//from ww w . ja va2s .c o m * Returns the banner after searching in the file. * @param advId The forced advertisement id you get from GET request * @param width the requested width * @param height the request height * @param segmentId the segment ID you get by reading the cookie * @context object of ServletContext which is needed to read the config.properties file */ public String readFromFile(String advId, int width, int height, int segmentId, ServletContext context, int callingFlag) { File file = null; Scanner fis = null; String banner = null; try { //read the filename and mappingFilename form the config.properties file Properties prop = new Properties(); if (callingFlag == 0) { prop.load(new InputStreamReader(context.getResourceAsStream("/WEB-INF/config.properties"))); } else if (callingFlag == 1) { prop.load(new FileReader( "/home/sankalpkulshrestha/NetBeansProjects/AdServer/web/WEB-INF/config.properties")); } else { return DEFAULT_BANNER; } //filename contains the list of advId, width, height, banner,segmentID. The filename is input.txt String filename = prop.getProperty("filename"); //mappingFilename contains the mapping of the advId and the default banner address String mappingFilename = prop.getProperty("mappingFilename"); file = new File(filename); fis = new Scanner(file); String line = null; //read the each line of input.txt, split it by comma and store it in param String array String[] param = new String[5]; //w and h hold the width and height respectively. //flag keeps track of whether a corresponding advId is found for a segnment ID, in case the advId is null int w = -1, h = -1, flag = 0; while (fis.hasNextLine()) { //read each line and split by comma line = fis.nextLine(); param = line.split(","); //read the width and height from the input.txt w = Integer.parseInt(param[1]); h = Integer.parseInt(param[2]); //in case we are not getting and forced advertisement ID, we keep searching for the corresponding advId is found for a segnment ID if ((advId == null || advId.length() == 0) && flag == 0 && segmentId == Integer.parseInt(param[4])) { flag = 1; advId = param[0]; } //in case segment ID is not 0 and segmentId is same as the segment ID found from the file of same width //and height as the requested width and height, we set the corresponding banner from the file and break away if (segmentId != 0 && segmentId == Integer.parseInt(param[4]) && w == width && h == height) { banner = param[3]; break; } } //close the input.txt file if (fis != null) { fis.close(); } //if till now the banner is still null and the advId is not null //then we check the mapping.txt file for finding the default banner of the campaign //the advId points to if (banner == null && advId != null) { File file2 = new File(mappingFilename); Scanner fis2 = null; fis2 = new Scanner(file2); param = new String[2]; while (fis2.hasNextLine()) { line = fis2.nextLine(); param = line.split(","); if (param[0].equals(advId)) { banner = param[1]; break; } } //close the mapping.txt file if (fis2 != null) { fis2.close(); } } else if (banner == null && advId == null) { //in case the banner is null and the advId is null, we return the default banner return DEFAULT_BANNER; } } catch (IOException e) { //in case of any exception, we return the default banner return DEFAULT_BANNER; } finally { //close the file if (fis != null) { fis.close(); } } return banner; }
From source file:io.lavagna.web.support.ResourceController.java
@RequestMapping(value = { "/", // "user/{provider}/{username}", "user/{provider}/{username}/projects/", "user/{provider}/{username}/activity/", // "about", "about/third-party", // "search", // "search/" + PROJ_SHORT_NAME + "/" + BOARD_SHORT_NAME + "-" + CARD_SEQ, // PROJ_SHORT_NAME + "", // PROJ_SHORT_NAME + "/search", // PROJ_SHORT_NAME + "/search/" + BOARD_SHORT_NAME + "-" + CARD_SEQ, // / PROJ_SHORT_NAME + "/" + BOARD_SHORT_NAME, // PROJ_SHORT_NAME + "/statistics", // PROJ_SHORT_NAME + "/milestones", // PROJ_SHORT_NAME + "/milestones/" + BOARD_SHORT_NAME + "-" + CARD_SEQ, // PROJ_SHORT_NAME + "/" + BOARD_SHORT_NAME + "-" + CARD_SEQ }, method = RequestMethod.GET) public void handleIndex(HttpServletRequest request, HttpServletResponse response) throws IOException { ServletContext context = request.getServletContext(); if (contains(env.getActiveProfiles(), "dev") || indexTopTemplate.get() == null) { ByteArrayOutputStream indexTop = new ByteArrayOutputStream(); try (InputStream is = context.getResourceAsStream("/WEB-INF/views/index-top.html")) { StreamUtils.copy(is, indexTop); }//w ww . j a v a 2 s . c o m indexTopTemplate.set(Mustache.compiler().escapeHTML(false) .compile(indexTop.toString(StandardCharsets.UTF_8.name()))); } if (contains(env.getActiveProfiles(), "dev") || indexCache.get() == null) { ByteArrayOutputStream index = new ByteArrayOutputStream(); output("/WEB-INF/views/index.html", context, index, new BeforeAfter()); Map<String, Object> data = new HashMap<>(); data.put("contextPath", request.getServletContext().getContextPath() + "/"); data.put("version", version); List<String> inlineTemplates = prepareTemplates(context, "/app/"); inlineTemplates.addAll(prepareTemplates(context, "/partials/")); data.put("inlineTemplates", inlineTemplates); indexCache.set( Mustache.compiler().escapeHTML(false).compile(index.toString(StandardCharsets.UTF_8.name())) .execute(data).getBytes(StandardCharsets.UTF_8)); } try (OutputStream os = response.getOutputStream()) { response.setContentType("text/html; charset=UTF-8"); Map<String, Object> localizationData = new HashMap<>(); Locale currentLocale = ObjectUtils.firstNonNull(request.getLocale(), Locale.ENGLISH); localizationData.put("firstDayOfWeek", Calendar.getInstance(currentLocale).getFirstDayOfWeek()); StreamUtils.copy(indexTopTemplate.get().execute(localizationData).getBytes(StandardCharsets.UTF_8), os); StreamUtils.copy(indexCache.get(), os); } }
From source file:org.jahia.services.applications.ServletContextManager.java
/** * Returns a ApplicationContext bean with the information loaded from the web.xml * file of a given context/*from w ww .ja v a 2 s . co m*/ * * @param context , the context * * @return an ApplicationContext or null on error * @param applicationID id of the application * @param filename the directory of the application to read from */ private WebAppContext loadContextInfoFromDisk(String applicationID, String context) { ServletContext dispatchedContext = mContext.getContext(context); if (dispatchedContext == null) { logger.error("Error getting dispatch context [" + context + "]"); return null; } InputStream is = null; // extract data from the web.xml file WebAppContext appContext; Web_App_Xml webXmlDoc; try { is = dispatchedContext.getResourceAsStream(WEB_XML_FILE); webXmlDoc = Web_App_Xml.parse(is); } catch (Exception e) { logger.error("Error during loading of web.xml file for application " + context, e); return null; } finally { IOUtils.closeQuietly(is); } appContext = new WebAppContext(context, webXmlDoc.getDisplayName(), webXmlDoc.getdesc(), null, webXmlDoc.getServletMappings(), null, webXmlDoc.getWelcomeFiles()); List<Servlet_Element> servlets = webXmlDoc.getServlets(); Servlet_Element servlet; ServletBean servletBean; for (int i = 0; i < servlets.size(); i++) { servlet = servlets.get(i); servletBean = new ServletBean(applicationID, servlet.getType(), servlet.getDisplayName(), servlet.getName(), servlet.getSource(), context, servlet.getdesc()); appContext.addServlet(servletBean); } List<Security_Role> roles = webXmlDoc.getRoles(); Security_Role role; for (int i = 0; i < roles.size(); i++) { role = roles.get(i); appContext.addRole(role.getName()); } return appContext; }
From source file:com.pronoiahealth.olhie.server.services.BookCoverImageService.java
/** * Assists in preloading images/*from w w w . j a va 2 s. co m*/ * * @param resourceLocation * @param loaderClass * @return * @throws Exception */ private byte[] readResourceToByteArray(String resourceLocation, ServletContext servletContext) throws Exception { return IOUtils.toByteArray(servletContext.getResourceAsStream(resourceLocation)); }