Example usage for javax.servlet ServletContext getResource

List of usage examples for javax.servlet ServletContext getResource

Introduction

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

Prototype

public URL getResource(String path) throws MalformedURLException;

Source Link

Document

Returns a URL to the resource that is mapped to the given path.

Usage

From source file:edu.indiana.d2i.htrc.security.JWTServletFilter.java

@Override
public void init(FilterConfig filterConfig) throws ServletException {
    // TokenVerifierConfiguration should be HOCON file stored in somewhere in the file system.
    String filterConfigFile = filterConfig.getInitParameter(PARAM_FILTER_CONFIG);
    if (filterConfigFile == null) {
        log.warn(//ww  w  .java2  s.c o m
                "No configuration was specified for JWTServletFilter. Using default " + DEFAULT_JWTFILTER_CONF);
        filterConfigFile = DEFAULT_JWTFILTER_CONF;
    }

    URL configUrl;
    try {
        if (filterConfigFile.contains(":/")) {
            configUrl = new URL(filterConfigFile);
        } else if (!filterConfigFile.startsWith("/")) {
            ServletContext servletContext = filterConfig.getServletContext();
            configUrl = servletContext.getResource(filterConfigFile);
        } else {
            configUrl = new File(filterConfigFile).toURI().toURL();
        }
    } catch (MalformedURLException e) {
        throw new ServletException("Could not load JWTFilter configuration from: " + filterConfigFile, e);
    }

    JWTServletFilterConfiguration configuration = new JWTServletFilterConfiguration(configUrl);

    try {
        this.tokenVerifier = new TokenVerifier(configuration.getTokenVerifierConfiguration());
    } catch (InvalidAlgorithmParameterException e) {
        throw new ServletException("Could not initialize token verifier.", e);
    }

    // We map following JWT claims to HTRC specific request headers by default
    claimToHeaderMappings.put("email", "htrc-user-email");
    claimToHeaderMappings.put("sub", "htrc-user-id");
    claimToHeaderMappings.put("iss", "htrc-token-issuer");

    // Any extra claim mappings are loaded from configuration file
    claimToHeaderMappings.putAll(configuration.getClaimMappings());
}

From source file:com.aurel.track.dbase.HandleHome.java

public static void initGroovyPlugins(ServletContext servletContext) {
    URL groovyURL = null;/*from  w w w  .  j  a  v a  2 s .c  o m*/
    try {
        groovyURL = servletContext.getResource("/WEB-INF/" + TORQUE_FILE);
        String path = groovyURL.toExternalForm();
        path = path.substring(0, path.lastIndexOf(TORQUE_FILE) - 1) + File.separator + "classes"
                + File.separator + PLUGINS_DIR + File.separator + "groovy" + File.separator;
        groovyURL = new URL(path);
    } catch (Exception ge) {
        System.err.println("Can't get the Groovy URL"); // What can we do here?
    }

    Constants.setGroovyURL(groovyURL);
}

From source file:com.haulmont.cuba.web.controllers.StaticContentController.java

protected LookupResult lookupNoCache(HttpServletRequest req) {
    final String path = getPath(req);
    if (isForbidden(path))
        return new Error(HttpServletResponse.SC_FORBIDDEN, "Forbidden");

    ServletContext context = req.getSession().getServletContext();

    final URL url;
    try {/*from   w ww  .j  a  va2  s. c o  m*/
        url = context.getResource(path);
    } catch (MalformedURLException e) {
        return new Error(HttpServletResponse.SC_BAD_REQUEST, "Malformed path");
    }
    if (url == null)
        return new Error(HttpServletResponse.SC_NOT_FOUND, "Not found");

    final String mimeType = getMimeType(path);

    final String realpath = context.getRealPath(path);
    if (realpath != null) {
        // Try as an ordinary file
        File f = new File(realpath);
        if (!f.isFile())
            return new Error(HttpServletResponse.SC_FORBIDDEN, "Forbidden");
        else {
            return createLookupResult(req, f.lastModified(), mimeType, (int) f.length(), acceptsDeflate(req),
                    url);
        }
    } else {
        try {
            // Try as a JAR Entry
            final ZipEntry ze = ((JarURLConnection) url.openConnection()).getJarEntry();
            if (ze != null) {
                if (ze.isDirectory())
                    return new Error(HttpServletResponse.SC_FORBIDDEN, "Forbidden");
                else
                    return createLookupResult(req, ze.getTime(), mimeType, (int) ze.getSize(),
                            acceptsDeflate(req), url);
            } else
                // Unexpected?
                return new StaticFile(-1, mimeType, -1, acceptsDeflate(req), url);
        } catch (ClassCastException e) {
            // Unknown resource type
            return createLookupResult(req, -1, mimeType, -1, acceptsDeflate(req), url);
        } catch (IOException e) {
            return new Error(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal server error");
        }
    }
}

From source file:com.haulmont.cuba.web.sys.singleapp.SingleAppWebContextLoader.java

protected void registerFrontAppServlet(ServletContext servletContext) {
    boolean hasFrontApp = false;
    try {/*  w w w. jav  a 2 s.  c om*/
        hasFrontApp = servletContext.getResource("/" + FRONT_CONTEXT_NAME) != null;
    } catch (MalformedURLException e) {
        //Do nothing
    }
    if (hasFrontApp) {
        String contextPath = servletContext.getContextPath();
        String baseUrl = System.getProperty("cuba.front.baseUrl");
        if (baseUrl == null || baseUrl.length() == 0) {
            String path = "/" + FRONT_CONTEXT_NAME + "/";
            System.setProperty("cuba.front.baseUrl", "/".equals(contextPath) ? path : contextPath + path);
        }
        String apiUrl = System.getProperty("cuba.front.apiUrl");
        if (apiUrl == null || apiUrl.length() == 0) {
            String path = "/rest/";
            System.setProperty("cuba.front.apiUrl", "/".equals(contextPath) ? path : contextPath + path);
        }
        DispatcherServlet frontServlet;
        try {
            Class frontServletClass = ReflectionHelper.getClass("com.haulmont.cuba.web.sys.AppFrontServlet");
            frontServlet = (DispatcherServlet) ReflectionHelper.newInstance(frontServletClass,
                    FRONT_CONTEXT_NAME, (Supplier<ApplicationContext>) AppContext::getApplicationContext);
        } catch (NoSuchMethodException e) {
            throw new RuntimeException("Unable to instantiate app front servlet", e);
        }
        ServletRegistration.Dynamic cubaServletReg = servletContext.addServlet("app_front_servlet",
                frontServlet);
        cubaServletReg.setLoadOnStartup(3);
        cubaServletReg.setAsyncSupported(true);
        cubaServletReg.addMapping(String.format("/%s/*", FRONT_CONTEXT_NAME));
    }
}

From source file:com.afis.jx.ckfinder.connector.utils.FileUtils.java

/**
 * Gets an absolute path to CKFinder file or folder for which path was provided as parameter.
 *
 * @param path relative or absolute path to a CKFinder resource (file or folder).
 * @param isAbsolute flag indicating if path to resource is absolute e.g. /usr/john/userfiles or "C:\\userfiles". If this parameter is
 * set to true path will be returned as is.
 * @param shouldExist flag indicating if resource, represented by path parameter, should exist (e.g. configuration file) in file system
 * or not (e.g. userfiles folder).<br>
 * If this parameter is set to true, path to file will only be returned if such file exists. If file can't be found, method will return
 * null./* ww w .j  a  v  a2s . co m*/
 * @return an absolute path to a resource in CKFinder
 * @throws ConnectorException when {@code ServletContext} is {@code null} or full path to resource cannot be obtained.
 */
public static String getFullPath(String path, boolean isAbsolute, boolean shouldExist)
        throws ConnectorException {
    if (path != null && !path.equals("")) {
        if (isAbsolute) {
            if (path.startsWith("/")) {
                //Check if this isn't Windows Path.
                String temporary = PathUtils.removeSlashFromBeginning(path);
                if (isStartsWithPattern(drivePatt, temporary)) {
                    path = temporary;
                }
            }
            return checkAndReturnPath(shouldExist, path);
        } else {
            ServletContext sc = ServletContextFactory.getServletContext();
            String tempPath = PathUtils.addSlashToEnd(PathUtils.addSlashToBeginning(path));
            try {
                java.net.URL url = sc.getResource(tempPath);
                //For srevers like Tomcat 6-7 the getResource method returns JNDI URL.
                if (url != null && url.getProtocol() != null && url.getProtocol().equalsIgnoreCase("jndi")) {
                    //Assume file is inside application context and try to get path.
                    //This method will fail if war is not exploaded.
                    String result = sc.getRealPath(tempPath.replace(sc.getContextPath(), ""));
                    if (result != null) {
                        return result;
                    } else {
                        //If application is packed, we have to try constructing the path manually.
                        result = getClassPath();
                        if (tempPath.indexOf(sc.getContextPath() + "/") >= 0
                                && result.indexOf(sc.getContextPath() + "/") >= 0) {
                            result = result.substring(0, result.indexOf(sc.getContextPath()));
                            result = result + tempPath;
                        } else if (result.indexOf(sc.getContextPath() + "/") >= 0) {
                            result = result.substring(0,
                                    result.indexOf(sc.getContextPath()) + sc.getContextPath().length());
                            result = result + tempPath;
                        }

                        result = checkAndReturnPath(shouldExist, result);
                        if (result != null) {
                            return result;
                        }
                    }

                    //At this stage path is not in application context and is not absolute.
                    //We need to reset url as we cannot determine path from it.
                    if (result == null) {
                        url = null;
                    }
                }

                //For servers like Tomact 8 getResource method should return file:// url.
                if (path.startsWith("/") || isStartsWithPattern(drivePatt, path)) {
                    //This is most likely absolute path.
                    String absolutePath = checkAndReturnPath(shouldExist, path);
                    if (absolutePath != null && !absolutePath.equals("")) {
                        return absolutePath;
                    } else {
                        //If absolute path has failed, give it one last try with relative path.
                        //Either path or null will be returned.
                        return sc.getRealPath(path.replace(sc.getContextPath(), ""));
                    }
                }
            } catch (IOException ioex) {
                throw new ConnectorException(ioex);
            }
        }
    }
    return null;
}

From source file:edu.stanford.epad.epadws.listener.StartupListener.java

public void contextInitialized(ServletContextEvent event) {
    // Skip, if we are using same APP
    if (!Main.separateWebServicesApp)
        return;/*  w ww  .  j a  v  a 2 s .  c  o m*/
    log.info("#####################################################");
    log.info("############# Starting ePAD Web Service #############");
    log.info("#####################################################");

    // call Spring's context ContextLoaderListener to initialize
    // all the context files specified in web.xml
    super.contextInitialized(event);

    ServletContext servletContext = event.getServletContext();
    appContext = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);
    webAppPath = servletContext.getRealPath("/");
    try {
        URL url = servletContext.getResource("/");
        webAppURL = "http:/" + url.getPath(); // Does not look correct
        System.out.println("Context initialized , webAppUrl=" + webAppURL + " webappPath=" + webAppPath);
    } catch (Exception x) {
    }
    Main.checkPropertiesFile();
    Main.checkResourcesFolders();
    Main.checkPluginsFile();
    RemotePACService.checkPropertiesFile();
    Main.initializePlugins();
    Main.startSupportThreads();
    Main.loadPluginClasses();
    new ServerStatusHandler(); // Sets startup time
}

From source file:com.aurel.track.dbase.HandleHome.java

/**
 * Gets the PropertiesConfiguration for a property file from TRACKPLUS_HOME
 * @param propFile/*ww  w  .ja va  2  s .  c  o  m*/
 * Load a properties file from the class path
 * @param propFile
 * @param servletContext
 * @return
 * @throws ServletException
 */
public static Properties loadPropertiesFromClassPath(String propFile, ServletContext servletContext)
        throws ServletException {
    Properties props = null;
    InputStream in = null;
    try {

        URL torqueURL = servletContext.getResource("/WEB-INF/" + propFile);
        in = torqueURL.openStream();
        props = new Properties();
        props.load(in);
        in.close();

    } catch (Exception e) {
        LOGGER.error("Could not read " + propFile + ". Exiting. " + e.getMessage());
        System.err.println("Could not read " + propFile + ". Exiting. " + e.getMessage());
        throw new ServletException(e);
    }
    return props;
}

From source file:com.qualogy.qafe.web.ContextLoader.java

private static void create(ServletContext servletContext) throws MalformedURLException, URISyntaxException {
    String configLocation = servletContext.getInitParameter(CONFIG_FILE_PARAM);
    String contextPath = getContextPath(servletContext);
    QafeConfigurationManager contextInitialiser = new QafeConfigurationManager(contextPath);
    ApplicationContext springContext = WebApplicationContextUtils
            .getRequiredWebApplicationContext(servletContext);
    contextInitialiser.setSpringContext(springContext);
    qafeContext.putInstance(QafeConfigurationManager.class.getName(), contextInitialiser);

    StopWatch watch = new StopWatch();
    watch.start();//w ww. j ava  2  s.  c o m
    ApplicationContextLoader.unload();

    // The default way: works on JBoss/Tomcat/Jetty
    String configFileLocation = servletContext.getRealPath("/WEB-INF/");
    if (configFileLocation != null) {
        configFileLocation += File.separator + configLocation;
        logger.log(Level.INFO, "URL to config file on disk :" + configFileLocation + ")");
        ApplicationContextLoader.load(configFileLocation, true);
    } else {
        // This is how a weblogic explicitly wants the fetching of resources.
        URL url = servletContext.getResource("/WEB-INF/" + configLocation);
        logger.log(Level.INFO, "Fallback scenario" + url.toString());
        if (url != null) {
            logger.log(Level.INFO, "URL to config file " + url.toString());
            ApplicationContextLoader.load(url.toURI(), true);
        } else {
            throw new RuntimeException(
                    "Strange Error: /WEB-INF/ cannot be found. Check the appserver or installation directory.");
        }
    }

    watch.stop();
    logger.log(Level.INFO,
            "Root WebApplicationContext: initialization completed in " + watch.getTime() + " ms");
}

From source file:com.liferay.portal.deploy.hot.ExtHotDeployListener.java

protected void mergeServiceJS(String portalWebDir, ServletContext servletContext) throws Exception {
    URL pluginJSURL = servletContext.getResource("WEB-INF/ext-web/docroot/html/js/liferay/service.js");
    if (pluginJSURL == null) {
        if (_log.isDebugEnabled()) {
            _log.debug("Ext Plugin's service.js not found");
        }//from  w w  w .ja va 2  s .  co  m
        return;
    }
    if (_log.isDebugEnabled()) {
        _log.debug("Loading service.js from " + pluginJSURL);
    }
    // append
    FileOutputStream portalJS = new FileOutputStream(portalWebDir + "html/js/liferay/service.js", true);
    try {
        InputStream pluginJS = new UrlResource(pluginJSURL).getInputStream();
        try {
            byte[] buff = new byte[4096];
            int len = 0;
            portalJS.write(new byte[] { 13, 10 });
            while ((len = pluginJS.read(buff)) != -1) {
                portalJS.write(buff, 0, len);
            }
            portalJS.write(new byte[] { 13, 10 });
        } finally {
            pluginJS.close();
        }
    } finally {
        portalJS.close();
    }

}

From source file:com.aurel.track.dbase.HandleHome.java

/**
 * Gets the PropertiesConfiguration for a property file from TRACKPLUS_HOME
 * @param propFile//from   w ww. j a v a2  s  .c  o m
 * Load a properties file from the class path
 * @param propFile
 * @param servletContext
 * @return
 * @throws ServletException
 */
public static List<String> loadFileFromClassPath(String propFile, ServletContext servletContext)
        throws ServletException {
    ArrayList<String> lines = new ArrayList<String>(100);
    InputStream in = null;
    try {

        URL fileURL = servletContext.getResource("/WEB-INF/" + propFile);
        in = fileURL.openStream();

        BufferedReader reader = new BufferedReader(new InputStreamReader(in));

        String line;
        while ((line = reader.readLine()) != null) {
            lines.add(line);
        }
        reader.close();

        in.close();

    } catch (Exception e) {
        LOGGER.error("Could not read " + propFile + ". Exiting. " + e.getMessage());
        System.err.println("Could not read " + propFile + ". Exiting. " + e.getMessage());
        throw new ServletException(e);
    }
    return lines;
}