List of usage examples for javax.servlet ServletContext getResource
public URL getResource(String path) throws MalformedURLException;
From source file:com.aurel.track.dbase.HandleHome.java
/** * Copies properties file from the WAR to TRACKPLUS_HOME if it does not exist there yet. * @return//w w w . j a va 2 s . c om * @throws ServletException */ public static void copyPropertiesFile(ServletContext servletContext, String rootDir, String propFile) throws ServletException { Boolean markForCopy = false; File props = null; File propsDir = null; try { // First check if we have a configuration file pointed to by the environment URL propFileURL = null; if (HandleHome.getTrackplus_Home() != null && !"".equals(HandleHome.getTrackplus_Home())) { props = new File(HandleHome.getTrackplus_Home() + File.separator + propFile); propsDir = new File(HandleHome.getTrackplus_Home()); if (props.exists() && props.canRead()) { propFileURL = new URL("file://" + HandleHome.getTrackplus_Home() + File.separator + propFile); } else { markForCopy = true; // We have a TRACKPLUS_HOME but no property file. We will copy it there. propFileURL = null; } } if (propFileURL == null) { propFileURL = servletContext.getResource(rootDir + "/" + propFile); } if (markForCopy) { // we copy the property file here when it does not exist yet if (propsDir != null && !propsDir.canWrite()) { LOGGER.error(propFile + " not writable to " + propsDir.getAbsolutePath() + " by user " + System.getProperty("user.name")); return; } if (props != null) { LOGGER.info("Copying configuration file " + propFile + " to " + props.getAbsolutePath()); InputStream from = null; FileOutputStream to = null; // Stream to write to destination try { from = propFileURL.openStream(); // Create input stream to = new FileOutputStream(props); // Create output stream byte[] buffer = new byte[4096]; // To hold file contents int bytes_read; // How many bytes in buffer while ((bytes_read = from.read(buffer)) != -1) // Read until EOF to.write(buffer, 0, bytes_read); // write } // Always close the streams, even if exceptions were thrown finally { if (from != null) try { from.close(); } catch (IOException e) { } if (to != null) try { to.close(); } catch (IOException e) { } } } } } catch (Exception e) { LOGGER.error("Could not read " + propFile + ". Exiting." + e.getMessage()); throw new ServletException(e); } }
From source file:com.aurel.track.util.PluginUtils.java
/** * Gets the classes from the specified classResourcePath and the specified servletContextResourcePath * which are in jars beginning with and ending with which extend/implement a class * @param servletContext/*from w w w .j av a 2 s. c o m*/ * @param superClass * @param jarStartsWith * @param jarEndsWith * @param classResourcePath * @param servletContextResourcePath * @return */ private static Set<String> getClassesFromLibJars(ServletContext servletContext, Class superClass, String jarStartsWith, String jarEndsWith, String classResourcePath, String servletContextResourcePath, Class[] constructorClasses, Object[] constructorParameters) { Set<String> foundAnalyzersSet = new TreeSet<String>(); try { File lib = PluginUtils.getFileFromURL(PluginUtils.class.getResource(classResourcePath)); //define the file filter FileFilterByStartAndEnd filter = new FileFilterByStartAndEnd(); filter.setStartsWith(jarStartsWith); filter.setEndsWith(jarEndsWith); //get the analyzers from the jars File[] foundJars = PluginUtils.getFilesFromDir(lib, filter); if (foundJars != null) { for (int i = 0; i < foundJars.length; i++) { foundAnalyzersSet.addAll(PluginUtils.getSubclassesFromJarInLib(foundJars[i], superClass, constructorClasses, constructorParameters)); } } //if .jars not yet found - probably because we use unexpaned .war (for ex. by weblogic) - try to get the resources through the servlet context if (foundJars == null || foundJars.length == 0) { URL urlLib = null; try { urlLib = servletContext.getResource(servletContextResourcePath); } catch (MalformedURLException e) { LOGGER.error("Getting the URL through getServletContext().getResource(path) failed with " + e.getMessage()); } lib = PluginUtils.getFileFromURL(urlLib); foundJars = PluginUtils.getFilesFromDir(lib, filter); if (foundJars != null) { for (int i = 0; i < foundJars.length; i++) { foundAnalyzersSet.addAll(PluginUtils.getSubclassesFromJarInLib(foundJars[i], superClass, constructorClasses, constructorParameters)); } } } } catch (Exception e) { LOGGER.warn("Getting the other lucene analysers failed with " + e.getMessage()); LOGGER.debug(ExceptionUtils.getStackTrace(e)); } return foundAnalyzersSet; }
From source file:com.aurel.track.ApplicationStarter.java
private void setVersionFromVersionProperties(ServletContext servletContext) { ApplicationBean applicationBean = ApplicationBean.getInstance(); String appTypeString = ""; Integer appType = -1;// w ww. ja v a2 s .co m String theVersion = ""; String theBuild = ""; String theVersionDate = ""; Integer theVersionNo = 370; try { URL versionURL = servletContext.getResource("/WEB-INF/Version.properties"); PropertiesConfiguration vcfg = new PropertiesConfiguration(); InputStream in = versionURL.openStream(); vcfg.load(in); theVersion = (String) vcfg.getProperty("version"); theBuild = (String) vcfg.getProperty("build"); if (theVersion == null) { theVersion = "4.X"; } if (theBuild == null) { theBuild = "1"; } theVersionDate = (String) vcfg.getProperty("date"); if (theVersionDate == null) { theVersionDate = "2015-01-01"; } theVersionNo = new Integer((String) vcfg.getProperty("app.version")); try { appType = new Integer((String) vcfg.getProperty("ntype")); } catch (Exception e) { appType = ApplicationBean.APPTYPE_FULL; } appTypeString = (String) vcfg.getProperty("type"); if (appTypeString == null) { appTypeString = "Genji"; } } catch (Exception e) { theVersion = "1.x"; theBuild = "0"; theVersionDate = "2015-01-01"; } applicationBean.setServletContext(servletContext); applicationBean.setVersion(theVersion); applicationBean.setVersionNo(theVersionNo); applicationBean.setBuild(theBuild); applicationBean.setVersionDate(theVersionDate); applicationBean.setAppType(appType); applicationBean.setAppTypeString(appTypeString); }
From source file:com.sun.faces.config.ConfigureListener.java
/** * <p>Return the URL for the given path.</p> * @param context the <code>ServletContext</code> of the current application * @param path the resource path//from w w w .ja va 2s .co m * @return the URL for the given resource or <code>null</code> */ private URL getContextURLForPath(ServletContext context, String path) { try { return context.getResource(path); } catch (MalformedURLException mue) { throw new FacesException(mue); } }
From source file:com.liferay.portal.servlet.MainServlet.java
public void init(ServletConfig config) throws ServletException { synchronized (MainServlet.class) { super.init(config); Config.initializeConfig();/*from ww w .j av a 2 s . co m*/ com.dotmarketing.util.Config.setMyApp(config.getServletContext()); // Need the plugin root dir before Hibernate comes up try { APILocator.getPluginAPI() .setPluginJarDir(new File(config.getServletContext().getRealPath("WEB-INF/lib"))); } catch (IOException e1) { Logger.debug(InitServlet.class, "IOException: " + e1.getMessage(), e1); } // Checking for execute upgrades try { StartupTasksExecutor.getInstance().executeUpgrades(config.getServletContext().getRealPath(".")); } catch (DotRuntimeException e1) { throw new ServletException(e1); } catch (DotDataException e1) { throw new ServletException(e1); } // Starting the reindexation threads ClusterThreadProxy.createThread(); if (Config.getBooleanProperty("DIST_INDEXATION_ENABLED")) { ClusterThreadProxy.startThread(Config.getIntProperty("DIST_INDEXATION_SLEEP", 500), Config.getIntProperty("DIST_INDEXATION_INIT_DELAY", 5000)); } ReindexThread.startThread(Config.getIntProperty("REINDEX_THREAD_SLEEP", 500), Config.getIntProperty("REINDEX_THREAD_INIT_DELAY", 5000)); try { EventsProcessor.process(new String[] { StartupAction.class.getName() }, true); } catch (Exception e) { Logger.error(this, e.getMessage(), e); } // Context path ServletConfig sc = getServletConfig(); ServletContext ctx = getServletContext(); String ctxPath = GetterUtil.get(sc.getInitParameter("ctx_path"), "/"); ctx.setAttribute(WebKeys.CTX_PATH, StringUtil.replace(ctxPath + "/c", "//", "/")); ctx.setAttribute(WebKeys.CAPTCHA_PATH, StringUtil.replace(ctxPath + "/captcha", "//", "/")); ctx.setAttribute(WebKeys.IMAGE_PATH, StringUtil.replace(ctxPath + "/image", "//", "/")); // Company id _companyId = ctx.getInitParameter("company_id"); ctx.setAttribute(WebKeys.COMPANY_ID, _companyId); // Initialize portlets try { String[] xmls = new String[] { Http.URLtoString(ctx.getResource("/WEB-INF/portlet.xml")), Http.URLtoString(ctx.getResource("/WEB-INF/portlet-ext.xml")), Http.URLtoString(ctx.getResource("/WEB-INF/liferay-portlet.xml")), Http.URLtoString(ctx.getResource("/WEB-INF/liferay-portlet-ext.xml")) }; PortletManagerUtil.initEAR(xmls); } catch (Exception e) { Logger.error(this, e.getMessage(), e); } // Initialize portlets display try { String xml = Http.URLtoString(ctx.getResource("/WEB-INF/liferay-display.xml")); Map oldCategories = (Map) WebAppPool.get(_companyId, WebKeys.PORTLET_DISPLAY); Map newCategories = PortletManagerUtil.getEARDisplay(xml); Map mergedCategories = PortalUtil.mergeCategories(oldCategories, newCategories); WebAppPool.put(_companyId, WebKeys.PORTLET_DISPLAY, mergedCategories); } catch (Exception e) { Logger.error(this, e.getMessage(), e); } // Initialize skins // // try { // String[] xmls = new String[] { Http.URLtoString(ctx.getResource("/WEB-INF/liferay-skin.xml")), // Http.URLtoString(ctx.getResource("/WEB-INF/liferay-skin-ext.xml")) }; // // SkinManagerUtil.init(xmls); // } catch (Exception e) { // Logger.error(this, e.getMessage(), e); // } // Check company try { CompanyLocalManagerUtil.checkCompany(_companyId); } catch (Exception e) { Logger.error(this, e.getMessage(), e); } // Check web settings try { String xml = Http.URLtoString(ctx.getResource("/WEB-INF/web.xml")); _checkWebSettings(xml); } catch (Exception e) { Logger.error(this, e.getMessage(), e); } // Scheduler // try { // Iterator itr = // PortletManagerUtil.getPortlets(_companyId).iterator(); // // while (itr.hasNext()) { // Portlet portlet = (Portlet)itr.next(); // // String className = portlet.getSchedulerClass(); // // if (portlet.isActive() && className != null) { // Scheduler scheduler = // (Scheduler)InstancePool.get(className); // // scheduler.schedule(); // } // } // } // catch (ObjectAlreadyExistsException oaee) { // } // catch (Exception e) { // Logger.error(this,e.getMessage(),e); // } // Message Resources MultiMessageResources messageResources = (MultiMessageResources) ctx.getAttribute(Globals.MESSAGES_KEY); messageResources.setServletContext(ctx); WebAppPool.put(_companyId, Globals.MESSAGES_KEY, messageResources); // Current users WebAppPool.put(_companyId, WebKeys.CURRENT_USERS, new TreeMap()); // HttpBridge TaskController.bridgeUserServicePath = "/httpbridge/home"; TaskController.bridgeHttpServicePath = "/httpbridge/http"; TaskController.bridgeGotoTag = "(goto)"; TaskController.bridgeThenTag = "(then)"; TaskController.bridgePostTag = "(post)"; // Process startup events try { EventsProcessor.process(PropsUtil.getArray(PropsUtil.GLOBAL_STARTUP_EVENTS), true); EventsProcessor.process(PropsUtil.getArray(PropsUtil.APPLICATION_STARTUP_EVENTS), new String[] { _companyId }); } catch (Exception e) { Logger.error(this, e.getMessage(), e); } PortalInstances.init(_companyId); } }
From source file:com.aurel.track.dbase.HandleHome.java
/** * Copies images, templates, etc. from the WAR to TRACKPLUS_HOME. Original files are * overwritten unless they have been modified. Modification is checked via an MD5 digest. * @throws ServletException//from www .ja v a 2 s .com */ public static void copyObject(ServletContext servletContext, String sourcePath, String file, String targetDir) throws ServletException { File targetFile = null; File targetDirAbsolutePath = null; try { // First check if we already have a file there if (HandleHome.getTrackplus_Home() != null && !"".equals(HandleHome.getTrackplus_Home())) { targetFile = new File( HandleHome.getTrackplus_Home() + File.separator + targetDir + File.separator + file); targetDirAbsolutePath = new File(HandleHome.getTrackplus_Home() + File.separator + targetDir); } if (targetDirAbsolutePath != null && !targetDirAbsolutePath.exists()) { targetDirAbsolutePath.mkdirs(); } if (targetDirAbsolutePath != null && !targetDirAbsolutePath.canWrite()) { LOGGER.error(file + " not writable to " + targetDirAbsolutePath.getAbsolutePath() + " by user " + System.getProperty("user.name")); return; } URL sourceURL = null; try { sourceURL = servletContext.getResource(sourcePath + "/" + file); } catch (Exception e) { LOGGER.debug( "Could not get file " + sourcePath + "/" + file + " from context. Now trying classpath."); } if (sourceURL == null) { ClassLoader cl = HandleHome.class.getClassLoader(); sourceURL = cl.getResource(sourcePath + "/" + file); } String hashTarget = ""; String hashSource = computeHash(sourceURL); boolean copy = true; if (targetFile.exists() && targetFile.canRead()) { hashTarget = computeHash(targetFile); if (!fileIsTheOriginal(targetFile, hashTarget) || hashSource.equals(hashTarget)) { copy = false; } } writeHash(targetFile, hashSource); if (copy) { LOGGER.info("Copying file " + sourcePath + "/" + file + " to " + targetFile.getAbsolutePath()); InputStream from = null; FileOutputStream to = null; // Stream to write to destination try { from = sourceURL.openStream(); // Create input stream to = new FileOutputStream(targetFile); // Create temporary output stream byte[] buffer = new byte[4096]; // To hold file contents int bytes_read; // How many bytes in buffer while ((bytes_read = from.read(buffer)) != -1) // Read until EOF to.write(buffer, 0, bytes_read); // write } // Always close the streams, even if exceptions were thrown finally { if (from != null) try { from.close(); } catch (IOException e) { } if (to != null) try { to.close(); } catch (IOException e) { } } } } catch (Exception e) { LOGGER.error("Could not read " + file + ". Exiting: " + e.getMessage()); LOGGER.error(ExceptionUtils.getStackTrace(e)); throw new ServletException(e); } }
From source file:com.liferay.portal.plugin.PluginPackageUtil.java
private PluginPackage _readPluginPackageServletContext(ServletContext servletContext) throws DocumentException, IOException { String servletContextName = servletContext.getServletContextName(); String xml = HttpUtil.URLtoString(servletContext.getResource("/WEB-INF/liferay-plugin-package.xml")); if (_log.isInfoEnabled()) { if (servletContextName == null) { _log.info("Reading plugin package for the root context"); } else {//from w w w . j a va 2s . com _log.info("Reading plugin package for " + servletContextName); } } PluginPackage pluginPackage = null; if (xml == null) { String propertiesString = HttpUtil .URLtoString(servletContext.getResource("/WEB-INF/liferay-plugin-package.properties")); if (propertiesString != null) { if (_log.isDebugEnabled()) { _log.debug("Reading plugin package from " + "liferay-plugin-package.properties"); } Properties properties = PropertiesUtil.load(propertiesString); String displayName = servletContextName; if (displayName.startsWith(StringPool.SLASH)) { displayName = displayName.substring(1); } pluginPackage = _readPluginPackageProperties(displayName, properties); } if (pluginPackage == null) { if (_log.isDebugEnabled()) { _log.debug("Reading plugin package from MANIFEST.MF"); } pluginPackage = _readPluginPackageServletManifest(servletContext); } } else { if (_log.isDebugEnabled()) { _log.debug("Reading plugin package from liferay-plugin-package.xml"); } pluginPackage = _readPluginPackageXml(xml); } pluginPackage.setContext(servletContextName); return pluginPackage; }
From source file:catalina.startup.ContextConfig.java
/** * Process the application configuration file, if it exists. *//* w w w. jav a2 s .c om*/ private void applicationConfig() { // Open the application web.xml file, if it exists InputStream stream = null; ServletContext servletContext = context.getServletContext(); if (servletContext != null) stream = servletContext.getResourceAsStream(Constants.ApplicationWebXml); if (stream == null) { log(sm.getString("contextConfig.applicationMissing")); return; } // Process the application web.xml file synchronized (webDigester) { try { URL url = servletContext.getResource(Constants.ApplicationWebXml); InputSource is = new InputSource(url.toExternalForm()); is.setByteStream(stream); webDigester.setDebug(getDebug()); if (context instanceof StandardContext) { ((StandardContext) context).setReplaceWelcomeFiles(true); } webDigester.clear(); webDigester.push(context); webDigester.parse(is); } catch (SAXParseException e) { log(sm.getString("contextConfig.applicationParse"), e); log(sm.getString("contextConfig.applicationPosition", "" + e.getLineNumber(), "" + e.getColumnNumber())); ok = false; } catch (Exception e) { log(sm.getString("contextConfig.applicationParse"), e); ok = false; } finally { try { if (stream != null) { stream.close(); } } catch (IOException e) { log(sm.getString("contextConfig.applicationClose"), e); } } } }
From source file:com.jsmartframework.web.manager.BeanHandler.java
private void checkWebXmlPath(ServletContext servletContext) { try {//from ww w .jav a 2 s . c o m URL webXml = servletContext.getResource("/WEB-INF/web.xml"); if (webXml != null) { throw new RuntimeException("JSmart framework is not compatible with [/WEB-INF/web.xml] file. " + "Please remove the web.xml and compile your project with [failOnMissingWebXml=false]"); } } catch (MalformedURLException ex) { LOGGER.log(Level.WARNING, "/WEB-INF/web.xml malformed Url: " + ex.getMessage()); } }
From source file:com.liferay.portal.service.impl.LayoutTemplateLocalServiceImpl.java
public void readLayoutTemplate(String servletContextName, ServletContext servletContext, Set<ObjectValuePair<String, Boolean>> layoutTemplateIds, com.liferay.portal.kernel.xml.Element el, boolean standard, String themeId, PluginPackage pluginPackage) { Map<String, LayoutTemplate> layoutTemplates = null; if (themeId != null) { if (standard) { layoutTemplates = _getThemesStandard(themeId); } else {/*from ww w. j ava 2 s .c o m*/ layoutTemplates = _getThemesCustom(themeId); } } else if (servletContextName != null) { if (standard) { layoutTemplates = _warStandard; } else { layoutTemplates = _warCustom; } } else { if (standard) { layoutTemplates = _portalStandard; } else { layoutTemplates = _portalCustom; } } Iterator<com.liferay.portal.kernel.xml.Element> itr = el.elements("layout-template").iterator(); while (itr.hasNext()) { com.liferay.portal.kernel.xml.Element layoutTemplate = itr.next(); String layoutTemplateId = layoutTemplate.attributeValue("id"); if (layoutTemplateIds != null) { ObjectValuePair<String, Boolean> ovp = new ObjectValuePair<String, Boolean>(layoutTemplateId, standard); layoutTemplateIds.add(ovp); } LayoutTemplate layoutTemplateModel = layoutTemplates.get(layoutTemplateId); if (layoutTemplateModel == null) { layoutTemplateModel = new LayoutTemplateImpl(layoutTemplateId); layoutTemplates.put(layoutTemplateId, layoutTemplateModel); } PluginSetting pluginSetting = pluginSettingLocalService.getDefaultPluginSetting(); layoutTemplateModel.setPluginPackage(pluginPackage); layoutTemplateModel.setServletContext(servletContext); if (servletContextName != null) { layoutTemplateModel.setServletContextName(servletContextName); } layoutTemplateModel.setStandard(standard); layoutTemplateModel.setThemeId(themeId); layoutTemplateModel.setName( GetterUtil.getString(layoutTemplate.attributeValue("name"), layoutTemplateModel.getName())); layoutTemplateModel.setTemplatePath(GetterUtil.getString(layoutTemplate.elementText("template-path"), layoutTemplateModel.getTemplatePath())); layoutTemplateModel.setWapTemplatePath(GetterUtil.getString( layoutTemplate.elementText("wap-template-path"), layoutTemplateModel.getWapTemplatePath())); layoutTemplateModel.setThumbnailPath(GetterUtil.getString(layoutTemplate.elementText("thumbnail-path"), layoutTemplateModel.getThumbnailPath())); String content = null; try { content = HttpUtil.URLtoString(servletContext.getResource(layoutTemplateModel.getTemplatePath())); } catch (Exception e) { _log.error("Unable to get content at template path " + layoutTemplateModel.getTemplatePath() + ": " + e.getMessage()); } if (Validator.isNull(content)) { _log.error("No content found at template path " + layoutTemplateModel.getTemplatePath()); } else { StringBundler sb = new StringBundler(3); sb.append(themeId); if (standard) { sb.append(LayoutTemplateConstants.STANDARD_SEPARATOR); } else { sb.append(LayoutTemplateConstants.CUSTOM_SEPARATOR); } sb.append(layoutTemplateId); String velocityTemplateId = sb.toString(); layoutTemplateModel.setContent(content); layoutTemplateModel.setColumns(_getColumns(velocityTemplateId, content)); } if (Validator.isNull(layoutTemplateModel.getWapTemplatePath())) { _log.error("The element wap-template-path is not defined for " + layoutTemplateId); } else { String wapContent = null; try { wapContent = HttpUtil .URLtoString(servletContext.getResource(layoutTemplateModel.getWapTemplatePath())); } catch (Exception e) { _log.error("Unable to get content at WAP template path " + layoutTemplateModel.getWapTemplatePath() + ": " + e.getMessage()); } if (Validator.isNull(wapContent)) { _log.error("No content found at WAP template path " + layoutTemplateModel.getWapTemplatePath()); } else { layoutTemplateModel.setWapContent(wapContent); } } com.liferay.portal.kernel.xml.Element rolesEl = layoutTemplate.element("roles"); if (rolesEl != null) { Iterator<com.liferay.portal.kernel.xml.Element> itr2 = rolesEl.elements("role-name").iterator(); while (itr2.hasNext()) { com.liferay.portal.kernel.xml.Element roleNameEl = itr2.next(); pluginSetting.addRole(roleNameEl.getText()); } } layoutTemplateModel.setDefaultPluginSetting(pluginSetting); } }