Java Code Examples for javax.servlet.ServletContext#getResourceAsStream()
The following examples show how to use
javax.servlet.ServletContext#getResourceAsStream() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ServletContextTemplateLocator.java From trimou with Apache License 2.0 | 6 votes |
@Override public Reader locate(String templatePath) { ServletContext ctx = getServletContext(); if (ctx == null) { throw new MustacheException(MustacheProblem.TEMPLATE_LOADING_ERROR, "Servlet context not available"); } String path = getRootPath() + addSuffix(toRealPath(templatePath)); InputStream in = ctx.getResourceAsStream(path); if (in == null) { LOGGER.debug("Template not found: {}", path); return null; } LOGGER.debug("Template located: {}", templatePath); try { return new InputStreamReader(in, getDefaultFileEncoding()); } catch (UnsupportedEncodingException e) { throw new MustacheException(MustacheProblem.TEMPLATE_LOADING_ERROR, e); } }
Example 2
Source File: DocumentStore.java From yawl with GNU Lesser General Public License v3.0 | 6 votes |
private Properties loadHibernateProperties(ServletContext context) { try { // for enterprise builds, hibernate.properties is in the 'classes' dir InputStream is = context.getResourceAsStream("/WEB-INF/classes/hibernate.properties"); // for installer builds, its in the 'yawllib' dir if (is == null) { File f = new File(System.getenv("CATALINA_HOME") + "/yawllib/hibernate.properties"); if (f != null && f.exists()) { is = new FileInputStream(f); } } if (is != null) { Properties p = new Properties(); p.load(is); return p; } } catch (Exception fallthough) { } return null; }
Example 3
Source File: AlbianResourceService.java From Albianj2 with BSD 3-Clause "New" or "Revised" License | 6 votes |
/** * 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 */ 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 { if (null != inputStream) { inputStream.close(); } // ClickUtils.close(inputStream); } }
Example 4
Source File: ConfigLoader.java From GeoTriples with Apache License 2.0 | 6 votes |
private Model loadMetadataTemplate(D2RServer server, ServletContext context, Property configurationFlag, String defaultTemplateName) { Model metadataTemplate; File userTemplateFile = MetadataCreator.findTemplateFile(server, configurationFlag); Model userResourceTemplate = MetadataCreator .loadTemplateFile(userTemplateFile); if (userResourceTemplate != null && userResourceTemplate.size() > 0) { metadataTemplate = userResourceTemplate; log.info("Using user-specified metadata template at '" + userTemplateFile + "'"); } else { // load default template InputStream drtStream = context.getResourceAsStream("/WEB-INF/" + defaultTemplateName); log.info("Using default metadata template."); metadataTemplate = MetadataCreator.loadMetadataTemplate(drtStream); } return metadataTemplate; }
Example 5
Source File: ApplicationInitialisationListener.java From gazpachoquest with GNU General Public License v3.0 | 6 votes |
private InputStream getResourceAsStream(ServletContext servletContext, String host, String contextPath, String fileName) { String paths[] = { String.format("/WEB-INF/config/%s/%s", host, fileName), String.format("/WEB-INF/config/%s%s/%s", host, contextPath, fileName), String.format("/WEB-INF/config/default/%s", fileName) }; InputStream is = null; int idx = 0; do { is = servletContext.getResourceAsStream(paths[idx]); idx++; } while (is == null && idx < paths.length); if (is != null) { logger.info("Loading {} file from path {}", fileName, paths[--idx]); } return is; }
Example 6
Source File: HealthCheck.java From aerogear-unifiedpush-server with Apache License 2.0 | 5 votes |
/** * Endpoint to verify scm and version details * * @return {@link Attributes} * @statuscode 200 Successful response for your request with manifest's attributes * @statuscode 404 Not found version information */ @GET @Path("/version") @Produces(MediaType.APPLICATION_JSON) public Response manifestDetails(@Context HttpServletRequest request) { final ServletContext context = request.getSession().getServletContext(); try (final InputStream manifestStream = context.getResourceAsStream("/META-INF/MANIFEST.MF")) { return Response.ok(new Manifest(manifestStream).getMainAttributes()).build(); } catch (Exception e) { return Response.status(Response.Status.NOT_FOUND).entity("Could not find version information").build(); } }
Example 7
Source File: ServletUtils.java From velocity-tools with Apache License 2.0 | 5 votes |
public static InputStream getInputStream(final String path, final ServletContext application) { InputStream inputStream = null; if (!isWebappResource(path)) { // search classpath except for WEB-INF/* inputStream = ClassUtils.getResourceAsStream(path, ServletUtils.class); } else { // then webapp only for WEB-INF/* if (System.getSecurityManager() != null) { inputStream = AccessController.doPrivileged( new PrivilegedAction<InputStream>() { @Override public InputStream run() { return application.getResourceAsStream(path); } }); } else { inputStream = application.getResourceAsStream(path); } } return inputStream; }
Example 8
Source File: Include.java From Bootstrap.jsp with GNU Lesser General Public License v2.1 | 5 votes |
@Override public void doTag() throws JspException, IOException { final JspWriter writer = this.getJspContext().getOut(); final PageContext pageContext = (PageContext) this.getJspContext(); final ServletContext sc = pageContext.getServletContext(); InputStream in = sc.getResourceAsStream(this.path); InputStreamReader reader = new InputStreamReader(in); this.write(reader, writer); }
Example 9
Source File: GuiGeneratorManager.java From entando-components with GNU Lesser General Public License v3.0 | 5 votes |
static protected String getText(String path, ServletContext servletContext) throws Throwable { String text = null; InputStream is = null; try { is = servletContext.getResourceAsStream(path); text = FileTextReader.getText(is); } catch (Throwable t) { throw new ApsSystemException("Error readind text", t); } finally { if (null != is) { is.close(); } } return text; }
Example 10
Source File: InfoServlet.java From mercury with Apache License 2.0 | 5 votes |
private String getVersion(ServletContext context) { InputStream in = context.getResourceAsStream(MANIFEST); if (in != null) { Properties p = new Properties(); try { p.load(new ByteArrayInputStream(Utility.getInstance().stream2bytes(in))); return p.getProperty(IMPL_VERSION); } catch (IOException e) { // nothing we can do } } return null; }
Example 11
Source File: Bug1261.java From spotbugs with GNU Lesser General Public License v2.1 | 5 votes |
@DesireNoWarning("NP_LOAD_OF_KNOWN_NULL_VALUE") public String falsePositive (ServletContext servletContext) throws IOException { try (InputStream inputStream = servletContext.getResourceAsStream("/META-INF/MANIFEST.MF")) { if (inputStream == null) { return "#InDevelopment#"; } return new Manifest(inputStream).getMainAttributes().getValue("Implementation-Version"); } }
Example 12
Source File: ConfigDAO.java From document-management-system with GNU General Public License v2.0 | 5 votes |
/** * Find by pk with a default value */ public static ConfigStoredFile getFile(String key, String path, ServletContext sc) throws DatabaseException, IOException { InputStream is = null; try { if (sc == null) { is = Thread.currentThread().getContextClassLoader().getResourceAsStream(path); } else { is = sc.getResourceAsStream(path); } ConfigStoredFile stFile = new ConfigStoredFile(); if (is == null) { stFile.setContent(""); } else { stFile.setContent(SecureStore.b64Encode(IOUtils.toByteArray(is))); } stFile.setName(PathUtils.getName(path)); stFile.setMime(MimeTypeConfig.mimeTypes.getContentType(stFile.getName())); // MIME still are not initialized from database if (MimeTypeConfig.MIME_UNDEFINED.equals(stFile.getMime())) { if (stFile.getName().toLowerCase().endsWith(".ico")) { stFile.setMime(MimeTypeConfig.MIME_ICO); } } String value = getProperty(key, new Gson().toJson(stFile), Config.FILE); return new Gson().fromJson(value, ConfigStoredFile.class); } finally { IOUtils.closeQuietly(is); } }
Example 13
Source File: StaticServletContextResourceConfigFactory.java From portals-pluto with Apache License 2.0 | 5 votes |
private static void init(ServletContext servletContext) { try { InputStream in = servletContext.getResourceAsStream(ResourceConfigReader.CONFIG_FILE); resourceConfig = ResourceConfigReader.getFactory().parse(in); resourceConfig.initialized(); // Lets the resource config set defaults } catch (Exception e) { throw new DriverConfigurationException(e); } }
Example 14
Source File: AbstractWebAppContextLoader.java From cuba with Apache License 2.0 | 4 votes |
protected void loadPropertiesFromConfig(ServletContext sc, Properties properties, String propsConfigName) { SpringProfileSpecificNameResolver nameResolver = new SpringProfileSpecificNameResolver(sc); DefaultResourceLoader resourceLoader = new DefaultResourceLoader(); StringTokenizer tokenizer = new StringTokenizer(propsConfigName); tokenizer.setQuoteChar('"'); for (String str : tokenizer.getTokenArray()) { log.trace("Processing properties location: {}", str); String baseName = StringSubstitutor.replaceSystemProperties(str); for (String name : nameResolver.getDerivedNames(baseName)) { InputStream stream = null; try { if (ResourceUtils.isUrl(name) || name.startsWith(ResourceLoader.CLASSPATH_URL_PREFIX)) { Resource resource = resourceLoader.getResource(name); if (resource.exists()) stream = resource.getInputStream(); } else { stream = sc.getResourceAsStream(name); } if (stream != null) { log.info("Loading app properties from {}", name); BOMInputStream bomInputStream = new BOMInputStream(stream); try (Reader reader = new InputStreamReader(bomInputStream, StandardCharsets.UTF_8)) { properties.load(reader); } } else { log.trace("Resource {} not found, ignore it", name); } } catch (IOException e) { throw new RuntimeException("Unable to read properties from stream", e); } finally { try { if (stream != null) { stream.close(); } } catch (final IOException ioe) { // ignore } } } } }
Example 15
Source File: ResourcesCache.java From AngularBeans with GNU Lesser General Public License v3.0 | 4 votes |
public String get(String resourceName,ServletContext servletContext) { String json=null; if(!cache.containsKey(resourceName)){ InputStream is = servletContext.getResourceAsStream( "/META-INF" +resourceName+ ".properties"); Properties properties = new Properties(); try { properties.load(is); json=util.getJson(properties); } catch (IOException e) { e.printStackTrace(); } } return json; }
Example 16
Source File: CubaVaadinServletService.java From cuba with Apache License 2.0 | 4 votes |
@Override protected InputStream getApplicationResourceAsStream(Class<?> contextClass, String fileName) { ServletContext servletContext = VaadinServlet.getCurrent().getServletContext(); return servletContext.getResourceAsStream("/VAADIN/" + fileName); }
Example 17
Source File: TestCollectorServletWithParts.java From javamelody with Apache License 2.0 | 4 votes |
/** * Initialisation. * @throws IOException e * @throws ServletException e */ @Before public void setUp() throws IOException, ServletException { tearDown(); Utils.initialize(); Utils.setProperty(Parameters.PARAMETER_SYSTEM_PREFIX + "mockLabradorRetriever", TRUE); Utils.setProperty(Parameter.SYSTEM_ACTIONS_ENABLED, TRUE); final ServletConfig config = createNiceMock(ServletConfig.class); final ServletContext context = createNiceMock(ServletContext.class); expect(config.getServletContext()).andReturn(context).anyTimes(); collectorServlet = new CollectorServlet(); InputStream webXmlStream = null; try { webXmlStream = getClass().getResourceAsStream("/WEB-INF/web.xml"); InputStream webXmlStream2 = null; try { webXmlStream2 = context.getResourceAsStream("/WEB-INF/web.xml"); expect(webXmlStream2).andReturn(webXmlStream).anyTimes(); final String javamelodyDir = "/META-INF/maven/net.bull.javamelody/"; final String webapp = javamelodyDir + "javamelody-test-webapp/"; expect(context.getResourcePaths("/META-INF/maven/")) .andReturn(Collections.singleton(javamelodyDir)).anyTimes(); expect(context.getResourcePaths(javamelodyDir)) .andReturn(Collections.singleton(webapp)).anyTimes(); expect(context.getResourceAsStream(webapp + "pom.xml")) .andReturn(getClass().getResourceAsStream("/pom.xml")).anyTimes(); replay(config); replay(context); collectorServlet.init(config); verify(config); verify(context); } finally { if (webXmlStream2 != null) { webXmlStream2.close(); } } } finally { if (webXmlStream != null) { webXmlStream.close(); } } }
Example 18
Source File: KeycloakConfigurationServletListener.java From keycloak with Apache License 2.0 | 4 votes |
@Override public void contextInitialized(ServletContextEvent sce) { ServletContext servletContext = sce.getServletContext(); String configResolverClass = servletContext.getInitParameter("keycloak.config.resolver"); SamlDeploymentContext deploymentContext = (SamlDeploymentContext) servletContext.getAttribute(SamlDeployment.class.getName()); if (deploymentContext == null) { if (configResolverClass != null) { try { SamlConfigResolver configResolver = (SamlConfigResolver) servletContext.getClassLoader().loadClass(configResolverClass).newInstance(); deploymentContext = new SamlDeploymentContext(configResolver); log.infov("Using {0} to resolve Keycloak configuration on a per-request basis.", configResolverClass); } catch (Exception ex) { log.errorv("The specified resolver {0} could NOT be loaded. Keycloak is unconfigured and will deny all requests. Reason: {1}", new Object[] { configResolverClass, ex.getMessage() }); deploymentContext = new SamlDeploymentContext(new DefaultSamlDeployment()); } } else { InputStream is = getConfigInputStream(servletContext); final SamlDeployment deployment; if (is == null) { log.warn("No adapter configuration. Keycloak is unconfigured and will deny all requests."); deployment = new DefaultSamlDeployment(); } else { try { ResourceLoader loader = new ResourceLoader() { @Override public InputStream getResourceAsStream(String resource) { return servletContext.getResourceAsStream(resource); } }; deployment = new DeploymentBuilder().build(is, loader); } catch (ParsingException e) { throw new RuntimeException(e); } } deploymentContext = new SamlDeploymentContext(deployment); log.debug("Keycloak is using a per-deployment configuration."); } } addTokenStoreUpdaters(servletContext); servletContext.setAttribute(ADAPTER_DEPLOYMENT_CONTEXT_ATTRIBUTE, deploymentContext); servletContext.setAttribute(ADAPTER_DEPLOYMENT_CONTEXT_ATTRIBUTE_ELYTRON, deploymentContext); servletContext.setAttribute(ADAPTER_SESSION_ID_MAPPER_ATTRIBUTE_ELYTRON, idMapper); servletContext.setAttribute(ADAPTER_SESSION_ID_MAPPER_UPDATER_ATTRIBUTE_ELYTRON, idMapperUpdater); }
Example 19
Source File: OpenshiftAuthServletExtension.java From hawkular-metrics with Apache License 2.0 | 4 votes |
@Override public void handleDeployment(DeploymentInfo deploymentInfo, ServletContext servletContext) { String componentName = ""; String resourceName = ""; Pattern insecureEndpointPattern = null; Pattern postQueryPattern = null; // file to contain configurations options for this Servlet Extension InputStream is = servletContext.getResourceAsStream(PROPERTY_FILE); if (is != null) { try { Properties props = new Properties(); props.load(is); componentName = props.getProperty("component"); resourceName = props.getProperty("resource-name"); String insecurePatternString = props.getProperty("unsecure-endpoints"); String postQueryPatternString = props.getProperty("post-query"); if (insecurePatternString != null) { insecureEndpointPattern = Pattern.compile(insecurePatternString); } if (postQueryPatternString != null) { postQueryPattern = Pattern.compile(postQueryPatternString); } } catch (Exception e) { throw new RuntimeException(e); } } if (componentName == null || componentName.isEmpty()) { throw new RuntimeException("Missing or empty 'component' key from the " + PROPERTY_FILE + " configuration file."); } if (resourceName == null || resourceName.isEmpty()) { throw new RuntimeException("Missing or empty 'resource-name' key from the " + PROPERTY_FILE + " configuratin file."); } final String cName = componentName; final String rName = resourceName; final Pattern insecurePattern = insecureEndpointPattern; final Pattern postQuery = postQueryPattern; if (DISABLE_NAMESPACE_FILTER.equalsIgnoreCase("true")) { log.info("The OpenShift Namespace Filter has been disabled via the 'DISABLE_NAMESPACE_FILTER' system property."); } else { log.info("Enabling the OpenShift Namespace Filter."); deploymentInfo.addInitialHandlerChainWrapper(containerHandler -> { namespaceHandler = new NamespaceHandler(containerHandler); return namespaceHandler; }); } ImmediateInstanceFactory<EventListener> instanceFactory = new ImmediateInstanceFactory<>(new SCListener()); deploymentInfo.addListener(new ListenerInfo(SCListener.class, instanceFactory)); deploymentInfo.addInitialHandlerChainWrapper(containerHandler -> { openshiftAuthHandler = new OpenshiftAuthHandler(containerHandler, cName, rName, insecurePattern, postQuery); return openshiftAuthHandler; }); }
Example 20
Source File: DocumentStore.java From yawl with GNU Lesser General Public License v3.0 | 4 votes |
/** * Increases the maximum column length for stored documents in H2 databases from 255 * to 5Mb. * <p/> * H2 defaults to 255 chars for binary types, and this default went out * with the 2.3 release. This method (1) checks if we are using a H2 database, then * if so (2) checks the relevant column length, then if it is 255 (3) increases it * to 5Mb maximum and (4) writes a flag file so that the method short-circuits on * future executions (i.e. it only runs once). * * @param context the current servlet context */ private void fixH2BinarySize(ServletContext context) { // if the flag files already exists, go no further if (context.getResourceAsStream("/WEB-INF/classes/dbfixed.bin") != null) { return; } // get the db properties from hibernate.properties Properties p = loadHibernateProperties(context); if (p == null) return; // couldn't find hibernate.properties Connection connection = null; try { String dialect = p.getProperty("hibernate.dialect"); // proceed only if this is a H2 database if (dialect != null && dialect.equals("org.hibernate.dialect.H2Dialect")) { Class.forName(p.getProperty("hibernate.connection.driver_class")); String url = p.getProperty("hibernate.connection.url"); if (url == null) return; // nothing to connect to url = url.replace("${catalina.base}", System.getenv("CATALINA_HOME")); connection = DriverManager.getConnection(url); if (connection != null) { // get the YDOC column size, and increase if required DatabaseMetaData dbmd = connection.getMetaData(); ResultSet rs = dbmd.getColumns(null, null, "YDOCUMENT", "YDOC"); rs.next(); if (rs.getInt("COLUMN_SIZE") <= 255) { connection.createStatement().executeUpdate( "ALTER TABLE ydocument ALTER COLUMN ydoc varbinary(5242880)"); // write flag file for next time new File(context.getRealPath("WEB-INF/classes/dbfixed.bin")).createNewFile(); } connection.close(); } } } catch (Exception e) { // can't update } if (connection != null) { try { connection.close(); } catch (SQLException sqle) { // } } }