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:io.lavagna.web.support.ResourceController.java

private static void output(String file, ServletContext context, OutputStream os, BeforeAfter ba)
        throws IOException {
    ba.before(file, context, os);// w w  w  . ja  va 2 s.  c om
    try (InputStream is = context.getResourceAsStream(file)) {
        StreamUtils.copy(is, os);
    }
    ba.after(file, context, os);
    os.flush();
}

From source file:org.intermine.bio.webservice.GFFQueryService.java

/**
 * Read the SO term name to class name mapping file and return it as a Map from class name to
 * SO term name.  The Map is cached as the SO_CLASS_NAMES attribute in the servlet context.
 *
 * @throws ServletException if the SO class names properties file cannot be found
 * @param servletContext the ServletContext
 * @return a map//from w ww . j  a v  a2s.co  m
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
public static Map<String, String> getSoClassNames(ServletContext servletContext) throws ServletException {
    final String soClassNames = "SO_CLASS_NAMES";
    Properties soNameProperties;
    if (servletContext.getAttribute(soClassNames) == null) {
        soNameProperties = new Properties();
        try {
            InputStream is = servletContext.getResourceAsStream("/WEB-INF/soClassName.properties");
            soNameProperties.load(is);
        } catch (Exception e) {
            throw new ServletException("Error loading so class name mapping file", e);
        }

        servletContext.setAttribute(soClassNames, soNameProperties);
    } else {
        soNameProperties = (Properties) servletContext.getAttribute(soClassNames);
    }

    return new HashMap<String, String>((Map) soNameProperties);
}

From source file:org.zoxweb.server.http.servlet.HTTPServletUtil.java

public static String inputStreamToString(HttpServlet servlet, String resource)
        throws NullPointerException, IOException {
    log.info("resouce:" + resource);
    String content = null;/*from   w ww  . ja v a2  s .  co m*/
    try {
        content = (IOUtil.inputStreamToString(servlet.getClass().getResourceAsStream(resource), true));
    } catch (Exception e) {

    }
    if (content == null) {
        ServletContext context = servlet.getServletContext();

        URL url = context.getResource(resource);
        log.info("url:" + url);
        content = (IOUtil.inputStreamToString(context.getResourceAsStream(resource), true));
    }

    return content;
}

From source file:org.wso2.carbon.dynamic.client.web.app.registration.util.DynamicClientWebAppRegistrationUtil.java

public static JaggeryOAuthConfigurationSettings getJaggeryAppOAuthSettings(ServletContext servletContext) {
    JaggeryOAuthConfigurationSettings jaggeryOAuthConfigurationSettings = new JaggeryOAuthConfigurationSettings();
    try {//  w  w  w.ja va 2  s.  com
        InputStream inputStream = servletContext.getResourceAsStream(JAGGERY_APP_OAUTH_CONFIG_PATH);
        if (inputStream != null) {
            JsonReader reader = new JsonReader(new InputStreamReader(inputStream, CHARSET_UTF_8));
            reader.beginObject();
            while (reader.hasNext()) {
                String key = reader.nextName();
                switch (key) {
                case DynamicClientWebAppRegistrationConstants.DYNAMIC_CLIENT_REQUIRED_FLAG:
                    jaggeryOAuthConfigurationSettings.setRequireDynamicClientRegistration(reader.nextBoolean());
                    break;
                case DynamicClientWebAppRegistrationUtil.OAUTH_PARAM_GRANT_TYPE:
                    jaggeryOAuthConfigurationSettings.setGrantType(reader.nextString());
                    break;
                case DynamicClientWebAppRegistrationUtil.OAUTH_PARAM_TOKEN_SCOPE:
                    jaggeryOAuthConfigurationSettings.setTokenScope(reader.nextString());
                    break;
                case DynamicClientWebAppRegistrationUtil.OAUTH_PARAM_SAAS_APP:
                    jaggeryOAuthConfigurationSettings.setSaasApp(reader.nextBoolean());
                    break;
                case DynamicClientWebAppRegistrationUtil.OAUTH_PARAM_CALLBACK_URL:
                    jaggeryOAuthConfigurationSettings.setCallbackURL(reader.nextString());
                    break;
                case DynamicClientWebAppRegistrationUtil.AUDIENCE:
                    jaggeryOAuthConfigurationSettings.setAudience(reader.nextString());
                    break;
                case DynamicClientWebAppRegistrationUtil.ASSERTION_CONSUMER_URL:
                    jaggeryOAuthConfigurationSettings.setAssertionConsumerURL(reader.nextString());
                    break;
                case DynamicClientWebAppRegistrationUtil.RECEPIENT_VALIDATION_URL:
                    jaggeryOAuthConfigurationSettings.setRecepientValidationURL(reader.nextString());
                    break;
                }
            }
            return jaggeryOAuthConfigurationSettings;
        }
    } catch (UnsupportedEncodingException e) {
        log.error("Error occurred while initializing OAuth settings for the Jaggery app.", e);
    } catch (IOException e) {
        log.error("Error occurred while initializing OAuth settings for the Jaggery app.", e);
    }
    return jaggeryOAuthConfigurationSettings;
}

From source file:org.jbpm.designer.server.EditorHandler.java

/**
 * Returns the designer version from the manifest.
 *
 * @param context//from   w ww  .  j  a  va 2  s .  c o  m
 * @return version
 */
private static String readDesignerVersion(ServletContext context) {
    String retStr = "";
    BufferedReader br = null;
    try {
        InputStream inputStream = context.getResourceAsStream("/META-INF/MANIFEST.MF");
        br = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
        String line;
        while ((line = br.readLine()) != null) {
            if (line.startsWith(BUNDLE_VERSION)) {
                retStr = line.substring(BUNDLE_VERSION.length() + 1);
                retStr = retStr.trim();
            }
        }
        inputStream.close();
    } catch (Exception e) {
        _logger.error(e.getMessage(), e);
    } finally {
        if (br != null) {
            IOUtils.closeQuietly(br);
        }
    }
    return retStr;
}

From source file:com.thejustdo.util.Utils.java

/**
 * Reads the content of a file and returns it in a big string object.
 *
 * @param location Name and location to the plain file.
 * @param ctx Context to use./*  ww  w. java 2s.  co  m*/
 * @return
 */
public static String getPlainTextFileFromContext(String location, ServletContext ctx) {
    log.log(Level.INFO, "Loading contents of file: {0} and context: {1}.",
            new Object[] { location, ctx.getContextPath() });
    try {
        InputStream is = ctx.getResourceAsStream(location);
        StringBuilder answer = new StringBuilder();
        InputStreamReader isr = new InputStreamReader(is);
        BufferedReader reader = new BufferedReader(isr);

        // while there are more lines.
        String line;
        while (reader.ready()) {
            line = reader.readLine();
            answer.append(line).append("\n");
        }

        // closing resources.
        reader.close();

        return answer.toString();
    } catch (IOException ex) {
        log.log(Level.SEVERE, null, ex);
        return null;
    }
}

From source file:com.arm.connector.bridge.core.Utils.java

public static String readHTMLFileIntoString(HttpServlet svc, ErrorLogger err, String filename) {
    try {/*from  w ww  .  j a  v a2  s .com*/
        String text = null;
        String file = "";
        ServletContext context = svc.getServletContext();
        try (InputStream is = context.getResourceAsStream("/" + filename);
                InputStreamReader isr = new InputStreamReader(is);
                BufferedReader reader = new BufferedReader(isr)) {
            while ((text = reader.readLine()) != null) {
                file += text;
            }
        }
        return file;
    } catch (IOException ex) {
        err.critical("error while trying to read HTML template: " + filename, ex);
    }
    return null;
}

From source file:com.openkm.dao.ConfigDAO.java

/**
 * Find by pk with a default value//from  w w w  .ja v  a  2 s. co  m
 */
public static ConfigStoredFile getFile(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);
            }
        }

        return stFile;
    } finally {
        IOUtils.closeQuietly(is);
    }
}

From source file:com.openkm.dao.ConfigDAO.java

/**
 * Find by pk with a default value/*from   w  w w .ja  va 2s  .c o m*/
 */
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);
    }
}

From source file:de.highbyte_le.weberknecht.conf.WeberknechtConf.java

/**
 * reads weberknecht.xml or actions.xml if there is no weberknecht.xml
 * and creates new config instance//w w w .  ja va  2s  .c  o  m
 */
public static WeberknechtConf readConfig(ServletContext servletContext) throws ConfigurationException {
    WeberknechtConf conf = null;
    try {

        //read available actions from weberknecht.xml
        InputStream in = null;
        try {
            in = servletContext.getResourceAsStream("/WEB-INF/weberknecht.xml");
            if (in != null)
                conf = readConfig(in);
            else {
                in = servletContext.getResourceAsStream("/WEB-INF/actions.xml");
                if (in != null)
                    conf = readActions(in);
            }

        } finally {
            if (in != null)
                in.close();
        }

    } catch (IOException e) {
        log.error("readConfig() - IOException: " + e.getMessage(), e); //$NON-NLS-1$
    }

    if (null == conf)
        return new WeberknechtConf();
    return conf;
}