List of usage examples for javax.servlet ServletContext getResource
public URL getResource(String path) throws MalformedURLException;
From source file:com.liferay.portal.deploy.hot.ExtHotDeployListener.java
protected void doInvokeUndeploy(HotDeployEvent event) throws Exception { ServletContext servletContext = event.getServletContext(); String servletContextName = servletContext.getServletContextName(); if (_log.isDebugEnabled()) { _log.debug("Invoking undeploy for " + servletContextName); }/*from w ww . j a v a2s. c o m*/ String xml = HttpUtil .URLtoString(servletContext.getResource("/WEB-INF/ext-" + servletContextName + ".xml")); if (xml == null) { return; } if (_log.isInfoEnabled()) { _log.info("Extension environment for " + servletContextName + " will not be undeployed"); } }
From source file:com.aurel.track.dbase.HandleHome.java
/** * This method copies resources/SSO folder and content from war into Trackplus_Home. * @param context/*w w w. j a va 2 s . co m*/ * @throws IOException * @throws ServletException */ public static void copySSOFolder(ServletContext context) { File ssoDirInHome = new File(HandleHome.getTrackplus_Home() + File.separator + SSO_DIR); if (!ssoDirInHome.exists()) { ssoDirInHome.mkdir(); LOGGER.info("Creating folder for SSO in Track home: " + ssoDirInHome.getPath()); URL rootTillFolder = null; String rootPathTillFolder = null; try { rootTillFolder = context.getResource("/WEB-INF/classes/resources/SSO"); } catch (IOException ioEx) { LOGGER.error("Some errors happened while copying SSO folder from war into Track_Home!"); LOGGER.error(ExceptionUtils.getStackTrace(ioEx)); } rootPathTillFolder = rootTillFolder.getPath(); rootPathTillFolder = rootPathTillFolder.substring(rootPathTillFolder.indexOf("/WEB-INF"), rootPathTillFolder.length()); Set<String> folderContent = context.getResourcePaths(rootPathTillFolder); String folderNameFound = null; for (String fileNameWithPath : folderContent) { if (fileNameWithPath.endsWith(".jar")) { LOGGER.info("Copying following jar file into Track_home/" + SSO_DIR + ": " + fileNameWithPath); String fileName = fileNameWithPath.replace("/WEB-INF/classes/resources/SSO/", ""); try { copyObject(context, "resources/SSO", fileName, SSO_DIR); } catch (ServletException servEx) { LOGGER.error("Some errors happened while copying SSO folder from war into Track_Home!"); LOGGER.error(ExceptionUtils.getStackTrace(servEx)); } } else { folderNameFound = fileNameWithPath.replace("/WEB-INF/classes/resources/SSO/", ""); } } try { rootTillFolder = context.getResource("/WEB-INF/classes/resources/SSO/" + folderNameFound); } catch (IOException ioEx) { LOGGER.error("Some errors happened while copying SSO folder from war into Track_Home!"); LOGGER.error(ExceptionUtils.getStackTrace(ioEx)); } rootPathTillFolder = rootTillFolder.getPath(); rootPathTillFolder = rootPathTillFolder.substring(rootPathTillFolder.indexOf("/WEB-INF"), rootPathTillFolder.length()); folderContent = context.getResourcePaths(rootPathTillFolder); File ssoSubDirInHome = new File( HandleHome.getTrackplus_Home() + File.separator + SSO_DIR + File.separator + folderNameFound); if (!ssoSubDirInHome.exists()) { LOGGER.info("Creating sub folder in Track_home/SSO: " + ssoSubDirInHome.getPath()); ssoSubDirInHome.mkdir(); } for (String fileNameWithPath : folderContent) { String fileName = fileNameWithPath.replace("/WEB-INF/classes/resources/SSO/" + folderNameFound, ""); LOGGER.info( "Copying following file into Track_home/SSO/" + folderNameFound + ": " + fileNameWithPath); try { copyObject(context, "resources/SSO" + "/" + folderNameFound, fileName, SSO_DIR + "/" + folderNameFound); } catch (ServletException servEx) { LOGGER.error("Some errors happened while copying SSO folder from war into Track_Home!"); LOGGER.error(ExceptionUtils.getStackTrace(servEx)); } } } }
From source file:com.haulmont.cuba.web.sys.singleapp.SingleAppWebServletListener.java
@Override public void contextInitialized(ServletContextEvent sce) { try {// ww w.ja va2 s. c o m ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); //need to put the following class to WebAppClassLoader, to share it between for web and core contextClassLoader.loadClass("com.haulmont.cuba.core.sys.remoting.LocalServiceDirectory"); ServletContext servletContext = sce.getServletContext(); String dependenciesFile; try { dependenciesFile = IOUtils.toString(servletContext.getResourceAsStream("/WEB-INF/web.dependencies"), "UTF-8"); } catch (IOException e) { throw new RuntimeException("An error occurred while loading dependencies file", e); } String[] dependenciesNames = dependenciesFile.split("\\n"); URL[] urls = Arrays.stream(dependenciesNames).map((String name) -> { try { return servletContext.getResource("/WEB-INF/lib/" + name); } catch (MalformedURLException e) { throw new RuntimeException("An error occurred while loading dependency " + name, e); } }).toArray(URL[]::new); URLClassLoader webClassLoader = new CubaSingleAppClassLoader(urls, contextClassLoader); Thread.currentThread().setContextClassLoader(webClassLoader); Class<?> appContextLoaderClass = webClassLoader.loadClass(getAppContextLoaderClassName()); appContextLoader = appContextLoaderClass.newInstance(); Method setJarsNamesMethod = ReflectionUtils.findMethod(appContextLoaderClass, "setJarNames", String.class); ReflectionUtils.invokeMethod(setJarsNamesMethod, appContextLoader, dependenciesFile); Method contextInitializedMethod = ReflectionUtils.findMethod(appContextLoaderClass, "contextInitialized", ServletContextEvent.class); ReflectionUtils.invokeMethod(contextInitializedMethod, appContextLoader, sce); Thread.currentThread().setContextClassLoader(contextClassLoader); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) { throw new RuntimeException("An error occurred while starting single WAR application", e); } }
From source file:com.liferay.portal.deploy.hot.ExtHotDeployListener.java
protected void doInvokeDeploy(HotDeployEvent event) throws Exception { ServletContext servletContext = event.getServletContext(); String servletContextName = servletContext.getServletContextName(); if (_log.isDebugEnabled()) { _log.debug("Invoking deploy for " + servletContextName); }// w w w .j av a 2s. c om String xml = HttpUtil .URLtoString(servletContext.getResource("/WEB-INF/ext-" + servletContextName + ".xml")); if (xml == null) { return; } if (_log.isInfoEnabled()) { _log.info("Registering extension environment for " + servletContextName); } if (ExtRegistry.isRegistered(servletContextName)) { if (_log.isInfoEnabled()) { _log.info("Extension environment for " + servletContextName + " has been applied."); } return; } Map<String, Set<String>> conflicts = ExtRegistry.getConflicts(servletContext); if (!conflicts.isEmpty()) { StringBundler sb = new StringBundler(); sb.append("Extension environment for " + servletContextName + " cannot be applied because of detected conflicts:"); Iterator<Map.Entry<String, Set<String>>> itr = conflicts.entrySet().iterator(); while (itr.hasNext()) { Map.Entry<String, Set<String>> entry = itr.next(); String conflictServletContextName = entry.getKey(); Set<String> conflictFiles = entry.getValue(); sb.append("\n\t"); sb.append(conflictServletContextName); sb.append(":"); for (String conflictFile : conflictFiles) { sb.append("\n\t\t"); sb.append(conflictFile); } } _log.error(sb.toString()); return; } installExt(servletContext, event.getContextClassLoader()); FileAvailabilityUtil.reset(); if (_log.isInfoEnabled()) { _log.info("Extension environment for " + servletContextName + " has been applied. You must reboot the server and " + "redeploy all other plugins."); } }
From source file:com.haulmont.cuba.core.sys.singleapp.SingleAppCoreServletListener.java
@Override public void contextInitialized(ServletContextEvent sce) { try {// w w w .j av a 2 s . c om ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); //need to put the following class to WebAppClassLoader, to share it between for web and core contextClassLoader.loadClass("com.haulmont.cuba.core.sys.remoting.LocalServiceDirectory"); ServletContext servletContext = sce.getServletContext(); String dependenciesFile; try { dependenciesFile = IOUtils .toString(servletContext.getResourceAsStream("/WEB-INF/core.dependencies"), "UTF-8"); } catch (IOException e) { throw new RuntimeException("An error occurred while loading dependencies file", e); } String[] dependenciesNames = dependenciesFile.split("\\n"); URL[] urls = Arrays.stream(dependenciesNames).map((String name) -> { try { return servletContext.getResource("/WEB-INF/lib/" + name); } catch (MalformedURLException e) { throw new RuntimeException("An error occurred while loading dependency " + name, e); } }).toArray(URL[]::new); URLClassLoader coreClassLoader = new CubaSingleAppClassLoader(urls, contextClassLoader); Thread.currentThread().setContextClassLoader(coreClassLoader); Class<?> appContextLoaderClass = coreClassLoader.loadClass(getAppContextLoaderClassName()); appContextLoader = appContextLoaderClass.newInstance(); Method setJarsNamesMethod = ReflectionUtils.findMethod(appContextLoaderClass, "setJarNames", String.class); ReflectionUtils.invokeMethod(setJarsNamesMethod, appContextLoader, dependenciesFile); Method contextInitializedMethod = ReflectionUtils.findMethod(appContextLoaderClass, "contextInitialized", ServletContextEvent.class); ReflectionUtils.invokeMethod(contextInitializedMethod, appContextLoader, sce); Thread.currentThread().setContextClassLoader(contextClassLoader); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) { throw new RuntimeException("An error occurred while starting single WAR application", e); } }
From source file:com.netspective.sparx.theme.basic.StandardTemplateNavigationSkin.java
public boolean templateAvailable(ServletContext servletContext, String name) throws IOException { // First try to open as plain file (to bypass servlet container resource caches). String realPath = servletContext.getRealPath(name); if (realPath != null) { File file = new File(realPath); if (!file.isFile()) return false; if (file.canRead()) return true; }/*from w w w . j ava 2s . co m*/ // If it fails, try to open it with servletContext.getResource. URL url = null; try { url = servletContext.getResource(name); } catch (MalformedURLException e) { return false; } return url == null ? false : true; }
From source file:com.concursive.connect.config.Dictionary.java
/** * Description of the Method//from w ww .j a v a2 s . co m * * @param context Description of the Parameter * @param languageFilePath Description of the Parameter * @param language Description of the Parameter * @throws Exception Description of the Exception */ public void load(ServletContext context, String languageFilePath, String language) throws Exception { if (languageFilePath == null) { throw new Exception("Dictionary file path not provided"); } if (!languageFilePath.endsWith("/") && !languageFilePath.endsWith(System.getProperty("file.separator"))) { languageFilePath += System.getProperty("file.separator"); } String languageFilename = "dictionary_" + language + ".xml"; LOG.debug("Loading dictionary preferences: " + languageFilePath + languageFilename); if (context != null) { load(context.getResource(languageFilePath + languageFilename)); } else { load(new File(languageFilePath + languageFilename).toURL()); } }
From source file:de.appsolve.padelcampus.utils.HtmlResourceUtil.java
private void copyResources(ServletContext context, String sourceFolder, File destinationFolder) throws MalformedURLException, IOException { Set<String> resourcePaths = context.getResourcePaths(sourceFolder); if (resourcePaths == null) { LOG.warn(String.format("Unable to find folder %s", sourceFolder)); } else {/*from w w w .j ava 2 s. co m*/ for (String resourcePath : resourcePaths) { if (resourcePath.endsWith("/")) { //must be a directory copyResources(context, resourcePath, destinationFolder); } else { URL resource = context.getResource(resourcePath); FileUtils.copyURLToFile(resource, new File(destinationFolder, resourcePath)); } } } }
From source file:com.ideo.jso.Group.java
/** * Merge the content of a list of resources * @param names the name of the resources to merge * @param servletContext/*w ww. jav a 2 s. c o m*/ * @return an array of byte[] representing the content merged * @throws IOException */ private byte[] getMergedContent(List names, ServletContext servletContext) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); for (Iterator iterator = names.iterator(); iterator.hasNext();) { String path = (String) iterator.next(); if (!path.startsWith("/")) path = "/" + path; // load in a folder URL url = servletContext.getResource(path); if (url == null) //load in a jar url = getClass().getResource(path); if (url == null) throw new IOException("The resources '" + path + "' could not be found neither in the webapp folder nor in a jar"); log.debug("Merging content of group : " + getName()); InputStream inputStream = url.openStream(); InputStreamReader r = new InputStreamReader(inputStream); IOUtils.copy(r, baos, "ASCII"); baos.write((byte) '\n'); inputStream.close(); } baos.close(); return baos.toByteArray(); }
From source file:Service.java
/** * Method that initializes the server variables. *//* w w w. ja va 2 s . com*/ public void init() throws ServletException { if (!gateInited) { //If GATE has been not initialized. try { // GATE home is setted, so it can be used by SAGA. ServletContext ctx = getServletContext(); File gateHome = new File(ctx.getRealPath("/WEB-INF")); Gate.setGateHome(gateHome); // GATE user configuration file is setted. Gate.setUserConfigFile(new File(gateHome, "user-gate.xml")); //GATE is initialized as non visible. Gate.init(); // We load the plugins that are going to be used by the SAGA modules. // Load ANNIE. Gate.getCreoleRegister().registerDirectories(ctx.getResource("/WEB-INF/plugins/ANNIE")); // Load processingResources (from SAGA) Gate.getCreoleRegister() .registerDirectories(ctx.getResource("/WEB-INF/plugins/processingResources")); // Load webProcessingResources (from SAGA) Gate.getCreoleRegister() .registerDirectories(ctx.getResource("/WEB-INF/plugins/webProcessingResources")); // Now we create the sentiment analysis modules that are going to be provided by the service. // Spanish financial module. ArrayList<URL> dictionaries = new ArrayList<URL>(); dictionaries.add((new Service()).getClass() .getResource("/resources/gazetteer/finances/spanish/paradigma/lists.def")); modules.put("spFinancial", new DictionaryBasedSentimentAnalyzer("SAGA - Sentiment Analyzer", dictionaries)); // Emoticon module. ArrayList<URL> dictionaries2 = new ArrayList<URL>(); dictionaries2 .add((new Service()).getClass().getResource("/resources/gazetteer/emoticon/lists.def")); modules.put("emoticon", new DictionaryBasedSentimentAnalyzer("SAGA - Sentiment Analyzer", dictionaries2)); // Spanish financial + emoticon module. ArrayList<URL> dictionaries3 = new ArrayList<URL>(); dictionaries3.add((new Service()).getClass() .getResource("/resources/gazetteer/finances/spanish/paradigma/lists.def")); dictionaries3 .add((new Service()).getClass().getResource("/resources/gazetteer/emoticon/lists.def")); modules.put("spFinancialEmoticon", new DictionaryBasedSentimentAnalyzer("SAGA - Sentiment Analyzer", dictionaries3)); // GATE has been initialized. gateInited = true; } catch (Exception ex) { throw new ServletException("Exception initialising GATE", ex); } } }