Example usage for javax.servlet ServletContext getResourceAsStream

List of usage examples for javax.servlet ServletContext getResourceAsStream

Introduction

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

Prototype

public InputStream getResourceAsStream(String path);

Source Link

Document

Returns the resource located at the named path as an InputStream object.

Usage

From source file:org.intermine.web.struts.InitialiserPlugin.java

/**
 *  Load user-friendly class description
 *//* ww  w.jav  a 2s  . c om*/
private void loadClassDescriptions(ServletContext servletContext) {
    Properties classDescriptions = new Properties();
    try {
        classDescriptions.load(servletContext.getResourceAsStream("/WEB-INF/classDescriptions.properties"));
    } catch (Exception e) {
        LOG.error("Error loading class descriptions", e);
        blockingErrorKeys.put("errors.init.classDescriptions", null);
    }
    servletContext.setAttribute("classDescriptions", classDescriptions);
}

From source file:org.intermine.web.struts.InitialiserPlugin.java

/**
 * Object and widget display configuration
 *///w w  w .j  av a 2s .  com
private WebConfig loadWebConfig(ServletContext servletContext, ObjectStore os) {
    WebConfig retval = null;
    InputStream xmlInputStream = servletContext.getResourceAsStream("/WEB-INF/webconfig-model.xml");
    InputStream xmlInputStreamForValidation = servletContext
            .getResourceAsStream("/WEB-INF/webconfig-model.xml");
    if (xmlInputStream == null) {
        LOG.error("Unable to find /WEB-INF/webconfig-model.xml.");
        blockingErrorKeys.put("errors.init.webconfig.notfound", null);
    } else {
        StringWriter writer = new StringWriter();
        try {
            IOUtils.copy(xmlInputStreamForValidation, writer);
        } catch (IOException ioe) {
            LOG.error("Problems converting xmlInputStream into a String ", ioe);
            blockingErrorKeys.put("errors.init.webconfig.generic", ioe.getMessage());
        }
        String xml = writer.toString();
        String xmlSchemaUrl = "";
        try {
            xmlSchemaUrl = servletContext.getResource("/WEB-INF/webconfig-model.xsd").toString();
        } catch (MalformedURLException mue) {
            LOG.warn("Problems retrieving url fo aspects.xsd ", mue);
        }
        if (validateXML(xml, xmlSchemaUrl, "errors.init.webconfig.validation")) {
            try {
                retval = WebConfig.parse(servletContext, os.getModel());
                String validationMessage = retval.validateWidgetsConfig(os.getModel());
                if (validationMessage.isEmpty()) {
                    SessionMethods.setWebConfig(servletContext, retval);
                } else {
                    blockingErrorKeys.put("errors.init.webconfig.validation", validationMessage);
                }
            } catch (FileNotFoundException fnf) {
                LOG.error("Problem to find the webconfig-model.xml file.", fnf);
                blockingErrorKeys.put("errors.init.webconfig.notfound", null);
            } catch (ClassNotFoundException cnf) {
                LOG.error("Classes mentioned in the webconfig-model.xml" + " file aren't in the Model", cnf);
                blockingErrorKeys.put("errors.init.webconfig.classnotfound", cnf.getMessage());
            } catch (Exception e) {
                LOG.error("Problem to parse the webconfig-model.xml file", e);
                blockingErrorKeys.put("errors.init.webconfig.parsing", e.getMessage());
            }
        }
    }
    return retval;
}

From source file:de.xwic.sandbox.server.ServletLifecycleListener.java

@Override
public void contextInitialized(ServletContextEvent event) {
    HibernateDAOProvider hbnDP = new HibernateDAOProvider();

    DAOFactory factory = CommonConfiguration.createCommonDaoFactory(hbnDP);

    DAOSystem.setDAOFactory(factory);/* ww  w .  jav  a  2 s. c o m*/
    DAOSystem.setSecurityManager(new ServerSecurityManager());
    DAOSystem.setUseCaseService(new DefaultUseCaseService(hbnDP));
    DAOSystem.setFileHandler(new HbnFileOracleFixDAO());

    SandboxModelConfig.register(factory);
    StartModelConfig.register(factory);

    DemoAppModelConfig.register(factory);

    final ServletContext context = event.getServletContext();
    SandboxModelConfig.setWebRootDirectory(new File(context.getRealPath("/")));

    final String rootPath = context.getRealPath("");

    final File path = new File(rootPath + "/config");
    Setup setup;
    try {
        setup = XmlConfigLoader.loadSetup(path.toURI().toURL());
    } catch (Exception e) {
        log.error("Error loading product configuration", e);
        throw new RuntimeException("Error loading product configuration: " + e, e);
    }
    ConfigurationManager.setSetup(setup);

    if (!HibernateUtil.isInitialized()) {
        Configuration configuration = new Configuration();
        configuration.configure(); // load configuration settings from hbm file.
        // load properties
        Properties prop = new Properties();
        InputStream in = context.getResourceAsStream("WEB-INF/hibernate.properties");
        if (in == null) {
            in = context.getResourceAsStream("/WEB-INF/hibernate.properties");
        }
        if (in != null) {
            try {
                prop.load(in);
                configuration.setProperties(prop);
            } catch (IOException e) {
                log.error("Error loading hibernate.properties. Skipping this step! : " + e);
            }
        }
        HibernateUtil.initialize(configuration);
    }

    File prefStorePath = new File(new File(rootPath), "WEB-INF/prefstore");
    if (!prefStorePath.exists() && !prefStorePath.mkdirs()) {
        throw new IllegalStateException("Error initializing preference store: can not create directory "
                + prefStorePath.getAbsolutePath());
    }
    Platform.initialize(new StorageProvider(prefStorePath), new UserContextPreferenceProvider());

}

From source file:org.intermine.web.struts.InitialiserPlugin.java

/**
 * Summarize the ObjectStore to get class counts
 *///from   w  w  w .  java2  s .  c o  m
private ObjectStoreSummary summariseObjectStore(ServletContext servletContext) {
    Properties objectStoreSummaryProperties = new Properties();
    InputStream objectStoreSummaryPropertiesStream = servletContext
            .getResourceAsStream("/WEB-INF/objectstoresummary.properties");
    if (objectStoreSummaryPropertiesStream == null) {
        // there are no model specific properties
        LOG.error("Unable to find objectstoresummary.properties");
        blockingErrorKeys.put("errors.init.objectstoresummary", null);
    }
    try {
        objectStoreSummaryProperties.load(objectStoreSummaryPropertiesStream);
    } catch (Exception e) {
        LOG.error("Unable to read objectstoresummary.properties", e);
        blockingErrorKeys.put("errors.init.objectstoresummary.loading", null);
    }

    final ObjectStoreSummary oss = new ObjectStoreSummary(objectStoreSummaryProperties);
    return oss;
}

From source file:org.intermine.web.struts.InitialiserPlugin.java

/**
 * Load keys that describe how objects should be uniquely identified
 *//*from   ww  w  . j a v  a2s.c o m*/
private BagQueryConfig loadBagQueries(ServletContext servletContext, ObjectStore os, Properties webProperties) {
    BagQueryConfig bagQueryConfig = null;
    InputStream is = servletContext.getResourceAsStream("/WEB-INF/bag-queries.xml");
    if (is != null) {
        try {
            bagQueryConfig = BagQueryHelper.readBagQueryConfig(os.getModel(), is);
        } catch (Exception e) {
            Log.error("Error loading class bag queries. ", e);
            blockingErrorKeys.put("errors.init.bagqueries", e.getMessage());
        }
        InputStream isBag = getClass().getClassLoader().getResourceAsStream("extraBag.properties");
        Properties bagProperties = new Properties();
        if (isBag != null) {
            try {
                bagProperties.load(isBag);
                bagQueryConfig.setConnectField(bagProperties.getProperty("extraBag.connectField"));
                bagQueryConfig.setExtraConstraintClassName(bagProperties.getProperty("extraBag.className"));
                bagQueryConfig.setConstrainField(bagProperties.getProperty("extraBag.constrainField"));
            } catch (IOException e) {
                Log.error("Error loading extraBag.properties. ", e);
                blockingErrorKeys.put("errors.init.extrabagloading", null);
            }
        } else {
            LOG.error("Could not find extraBag.properties file");
            blockingErrorKeys.put("errors.init.extrabag", null);
        }
    } else {
        // can used defaults so just log a warning
        LOG.warn("No custom bag queries found - using default query");
    }
    return bagQueryConfig;
}

From source file:org.entando.entando.plugins.jpcomponentinstaller.aps.system.services.installer.DefaultComponentInstaller.java

private Set<String> discoverJars(String path, ServletContext servletContext) {
    Set<String> plugins = new HashSet<String>();
    Set<String> directory = servletContext.getResourcePaths(path);
    Iterator<String> itr = directory.iterator();
    // ITERATE OVER PATHS
    while (null != itr && itr.hasNext()) {
        String currentJar = itr.next();
        InputStream is = servletContext.getResourceAsStream(currentJar);
        plugins.addAll(discoverJarPlugin(is));
    }//  w  w  w.jav a  2s .  c o  m
    return plugins;
}

From source file:de.appsolve.padelcampus.utils.HtmlResourceUtil.java

private String concatenateCss(ServletContext context, Path path, Path outFile)
        throws FileNotFoundException, IOException {
    DirectoryStream<Path> cssFiles = Files.newDirectoryStream(path, "*.css");
    if (Files.exists(outFile)) {
        Files.delete(outFile);/*w ww  . java2 s  .co m*/
    }
    List<Path> sortedFiles = new ArrayList<>();
    for (Path cssFile : cssFiles) {
        sortedFiles.add(cssFile);
    }

    Collections.sort(sortedFiles, new PathByFileNameComparator());

    for (Path cssFile : sortedFiles) {
        Files.write(outFile, Files.readAllBytes(cssFile), StandardOpenOption.CREATE, StandardOpenOption.APPEND);
    }

    byte[] cssData;
    if (Files.exists(outFile)) {
        cssData = Files.readAllBytes(outFile);
    } else {
        //read from classpath
        InputStream is = context.getResourceAsStream(ALL_MIN_CSS);
        cssData = IOUtils.toByteArray(is);
    }
    String css = new String(cssData, Constants.UTF8);
    return css;
}

From source file:com.datascience.gal.service.Service.java

private void setup(ServletContext scontext) throws IOException, ClassNotFoundException, SQLException {
    if (dscache == null) {
        logger.info("loading props file with context:" + scontext.getContextPath());
        Properties props = new Properties();
        props.load(scontext.getResourceAsStream("/WEB-INF/classes/dawidskene.properties"));
        dscache = new DawidSkeneCache(props);
    }/*from www .j  a v a 2s  . com*/
}

From source file:com.socialmarketing.config.ApplicationPrefs.java

/**
 * Initializes preferences/* ww w  . ja va2 s.  c om*/
 *
 * @param context ServletContext
 */
public void initializePrefs(ServletContext context) {
    LOG.info("Initializing...");
    // Load the application node name, if any
    try {
        Properties instanceProperties = new Properties();
        instanceProperties.load(context.getResourceAsStream("/WEB-INF/instance.property"));
        node = instanceProperties.getProperty("node", DEFAULT_NODE);
        LOG.info("Node: " + node);
    } catch (Exception e) {
        LOG.info("Default Node: " + DEFAULT_NODE);
        node = DEFAULT_NODE;
    }
    // Determine the file library
    String fileLibrary = retrieveFileLibraryLocation(context);
    if (fileLibrary != null) {
        loadProperties(fileLibrary);
        this.add(FILE_LIBRARY_PATH, fileLibrary);
        configureDebug();
        // verifyKey(context, fileLibrary);
        // configureConnectionPool(context);
        // configureFreemarker(context);
        // configureWebdavManager(context);
        // configureSystemSettings(context);
        // configureCache(context);
        if (isConfigured()) {
            if (ApplicationVersion.isOutOfDate(this)) {
                LOG.info("Upgrade triggered... obtaining lock to continue");
                // Use a lock file to to start upgrading
                File upgradeLockFile = new File(fileLibrary + "upgrade.lock");
                FileChannel fileChannel = null;
                FileLock fileLock = null;
                try {
                    // Configure the file for locking
                    fileChannel = new RandomAccessFile(upgradeLockFile, "rw").getChannel();
                    // Use fileChannel.lock which blocks until the lock is obtained
                    fileLock = fileChannel.lock();
                    // Reload the prefs to make sure the upgrade isn't already complete
                    loadProperties(fileLibrary);
                    if (ApplicationVersion.isOutOfDate(this)) {
                        // The application needs an update
                        LOG.info("Installed version " + ApplicationVersion.getInstalledVersion(this)
                                + " will be upgraded to " + ApplicationVersion.VERSION);
                        //         performUpgrade(context);
                    }
                } catch (Exception e) {
                    LOG.error("initializePrefs-> performUpgrade", e);
                } finally {
                    try {
                        if (fileLock != null) {
                            fileLock.release();
                        }
                        if (fileChannel != null) {
                            fileChannel.close();
                        }
                    } catch (Exception eclose) {
                        LOG.error("initializePrefs-> lock", eclose);
                    }
                }
            }
            if (!ApplicationVersion.isOutOfDate(this)) {
                // Start the services now that everything is ready
                initializeServices(context);
            }
        }
    }
    configureDefaultBehavior(context);
    loadApplicationDictionaries(context);
}

From source file:org.openspaces.pu.container.jee.context.BootstrapWebApplicationContextListener.java

public void contextInitialized(ServletContextEvent servletContextEvent) {
    ServletContext servletContext = servletContextEvent.getServletContext();

    Boolean bootstraped = (Boolean) servletContext.getAttribute(BOOTSTRAP_CONTEXT_KEY);
    if (bootstraped != null && bootstraped) {
        logger.debug("Already performed bootstrap, ignoring");
        return;/*from  w ww  . jav a 2s . c  o  m*/
    }
    servletContext.setAttribute(BOOTSTRAP_CONTEXT_KEY, true);

    logger.info("Booting OpenSpaces Web Application Support");
    logger.info(ClassLoaderUtils.getCurrentClassPathString("Web Class Loader"));
    final ProcessingUnitContainerConfig config = new ProcessingUnitContainerConfig();

    InputStream is = servletContext.getResourceAsStream(MARSHALLED_CLUSTER_INFO);
    if (is != null) {
        try {
            config.setClusterInfo((ClusterInfo) objectFromByteBuffer(FileCopyUtils.copyToByteArray(is)));
            servletContext.setAttribute(JeeProcessingUnitContainerProvider.CLUSTER_INFO_CONTEXT,
                    config.getClusterInfo());
        } catch (Exception e) {
            logger.warn("Failed to read cluster info from " + MARSHALLED_CLUSTER_INFO, e);
        }
    } else {
        logger.debug("No cluster info found at " + MARSHALLED_CLUSTER_INFO);
    }
    is = servletContext.getResourceAsStream(MARSHALLED_BEAN_LEVEL_PROPERTIES);
    if (is != null) {
        try {
            config.setBeanLevelProperties(
                    (BeanLevelProperties) objectFromByteBuffer(FileCopyUtils.copyToByteArray(is)));
            servletContext.setAttribute(JeeProcessingUnitContainerProvider.BEAN_LEVEL_PROPERTIES_CONTEXT,
                    config.getBeanLevelProperties());
        } catch (Exception e) {
            logger.warn("Failed to read bean level properties from " + MARSHALLED_BEAN_LEVEL_PROPERTIES, e);
        }
    } else {
        logger.debug("No bean level properties found at " + MARSHALLED_BEAN_LEVEL_PROPERTIES);
    }

    Resource resource = null;
    String realPath = servletContext.getRealPath("/META-INF/spring/pu.xml");
    if (realPath != null) {
        resource = new FileSystemResource(realPath);
    }
    if (resource != null && resource.exists()) {
        logger.debug("Loading [" + resource + "]");
        // create the Spring application context
        final ResourceApplicationContext applicationContext = new ResourceApplicationContext(
                new Resource[] { resource }, null, config);
        // "start" the application context
        applicationContext.refresh();

        servletContext.setAttribute(JeeProcessingUnitContainerProvider.APPLICATION_CONTEXT_CONTEXT,
                applicationContext);
        String[] beanNames = applicationContext.getBeanDefinitionNames();
        for (String beanName : beanNames) {
            if (applicationContext.getType(beanName) != null)
                servletContext.setAttribute(beanName, applicationContext.getBean(beanName));
        }

        if (config.getClusterInfo() != null && SystemBoot.isRunningWithinGSC()) {
            final String key = config.getClusterInfo().getUniqueName();

            SharedServiceData.addServiceDetails(key, new Callable() {
                public Object call() throws Exception {
                    ArrayList<ServiceDetails> serviceDetails = new ArrayList<ServiceDetails>();
                    Map map = applicationContext.getBeansOfType(ServiceDetailsProvider.class);
                    for (Iterator it = map.values().iterator(); it.hasNext();) {
                        ServiceDetails[] details = ((ServiceDetailsProvider) it.next()).getServicesDetails();
                        if (details != null) {
                            for (ServiceDetails detail : details) {
                                serviceDetails.add(detail);
                            }
                        }
                    }
                    return serviceDetails.toArray(new Object[serviceDetails.size()]);
                }
            });

            SharedServiceData.addServiceMonitors(key, new Callable() {
                public Object call() throws Exception {
                    ArrayList<ServiceMonitors> serviceMonitors = new ArrayList<ServiceMonitors>();
                    Map map = applicationContext.getBeansOfType(ServiceMonitorsProvider.class);
                    for (Iterator it = map.values().iterator(); it.hasNext();) {
                        ServiceMonitors[] monitors = ((ServiceMonitorsProvider) it.next())
                                .getServicesMonitors();
                        if (monitors != null) {
                            for (ServiceMonitors monitor : monitors) {
                                serviceMonitors.add(monitor);
                            }
                        }
                    }
                    return serviceMonitors.toArray(new Object[serviceMonitors.size()]);
                }
            });

            Map map = applicationContext.getBeansOfType(MemberAliveIndicator.class);
            for (Iterator it = map.values().iterator(); it.hasNext();) {
                final MemberAliveIndicator memberAliveIndicator = (MemberAliveIndicator) it.next();
                if (memberAliveIndicator.isMemberAliveEnabled()) {
                    SharedServiceData.addMemberAliveIndicator(key, new Callable<Boolean>() {
                        public Boolean call() throws Exception {
                            return memberAliveIndicator.isAlive();
                        }
                    });
                }
            }

            map = applicationContext.getBeansOfType(ProcessingUnitUndeployingListener.class);
            for (Iterator it = map.values().iterator(); it.hasNext();) {
                final ProcessingUnitUndeployingListener listener = (ProcessingUnitUndeployingListener) it
                        .next();
                SharedServiceData.addUndeployingEventListener(key, new Callable() {
                    public Object call() throws Exception {
                        listener.processingUnitUndeploying();
                        return null;
                    }
                });
            }

            map = applicationContext.getBeansOfType(InternalDumpProcessor.class);
            for (Iterator it = map.values().iterator(); it.hasNext();) {
                SharedServiceData.addDumpProcessors(key, it.next());
            }
        }
    } else {
        logger.debug("No [" + ApplicationContextProcessingUnitContainerProvider.DEFAULT_PU_CONTEXT_LOCATION
                + "] to load");
    }

    // load jee specific context listener
    if (config.getBeanLevelProperties() != null) {
        String jeeContainer = JeeProcessingUnitContainerProvider
                .getJeeContainer(config.getBeanLevelProperties());
        String className = "org.openspaces.pu.container.jee." + jeeContainer + "."
                + StringUtils.capitalize(jeeContainer) + "WebApplicationContextListener";
        Class clazz = null;
        try {
            clazz = Thread.currentThread().getContextClassLoader().loadClass(className);
        } catch (ClassNotFoundException e) {
            // no class, ignore
        }
        if (clazz != null) {
            try {
                jeeContainerContextListener = (ServletContextListener) clazz.newInstance();
            } catch (Exception e) {
                throw new RuntimeException(
                        "Failed to create JEE specific context listener [" + clazz.getName() + "]", e);
            }
            jeeContainerContextListener.contextInitialized(servletContextEvent);
        }
    }

    // set the class loader used so the service bean can use it
    if (config.getClusterInfo() != null && SystemBoot.isRunningWithinGSC()) {
        SharedServiceData.putWebAppClassLoader(config.getClusterInfo().getUniqueName(),
                Thread.currentThread().getContextClassLoader());
    }
}