List of usage examples for javax.servlet ServletContext getResource
public URL getResource(String path) throws MalformedURLException;
From source file:com.liferay.portal.servlet.PortletContextListener.java
public void contextInitialized(ServletContextEvent sce) { try {/* w w w .ja v a 2 s .c o m*/ // Servlet context ServletContext ctx = sce.getServletContext(); _servletContextName = StringUtil.replace(ctx.getServletContextName(), StringPool.SPACE, StringPool.UNDERLINE); // Company ids _companyIds = StringUtil.split(ctx.getInitParameter("company_id")); // Class loader ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); // Initialize portlets String[] xmls = new String[] { Http.URLtoString(ctx.getResource("/WEB-INF/portlet.xml")), Http.URLtoString(ctx.getResource("/WEB-INF/liferay-portlet.xml")) }; _portlets = PortletManagerUtil.initWAR(_servletContextName, xmls); // Portlet context wrapper Iterator itr1 = _portlets.iterator(); while (itr1.hasNext()) { Portlet portlet = (Portlet) itr1.next(); javax.portlet.Portlet portletInstance = (javax.portlet.Portlet) contextClassLoader .loadClass(portlet.getPortletClass()).newInstance(); Indexer indexerInstance = null; if (Validator.isNotNull(portlet.getIndexerClass())) { indexerInstance = (Indexer) contextClassLoader.loadClass(portlet.getIndexerClass()) .newInstance(); } Scheduler schedulerInstance = null; if (Validator.isNotNull(portlet.getSchedulerClass())) { schedulerInstance = (Scheduler) contextClassLoader.loadClass(portlet.getSchedulerClass()) .newInstance(); } PreferencesValidator prefsValidator = null; if (Validator.isNotNull(portlet.getPreferencesValidator())) { prefsValidator = (PreferencesValidator) contextClassLoader .loadClass(portlet.getPreferencesValidator()).newInstance(); try { if (GetterUtil.getBoolean(PropsUtil.get(PropsUtil.PREFERENCE_VALIDATE_ON_STARTUP))) { prefsValidator.validate( PortletPreferencesSerializer.fromDefaultXML(portlet.getDefaultPreferences())); } } catch (Exception e1) { _log.warn("Portlet with the name " + portlet.getPortletId() + " does not have valid default preferences"); } } Map resourceBundles = null; if (Validator.isNotNull(portlet.getResourceBundle())) { resourceBundles = CollectionFactory.getHashMap(); Iterator itr2 = portlet.getSupportedLocales().iterator(); while (itr2.hasNext()) { String supportedLocale = (String) itr2.next(); Locale locale = new Locale(supportedLocale); try { ResourceBundle resourceBundle = ResourceBundle.getBundle(portlet.getResourceBundle(), locale, contextClassLoader); resourceBundles.put(locale.getLanguage(), resourceBundle); } catch (MissingResourceException mre) { _log.warn(mre.getMessage()); } } } Map customUserAttributes = CollectionFactory.getHashMap(); Iterator itr2 = portlet.getCustomUserAttributes().entrySet().iterator(); while (itr2.hasNext()) { Map.Entry entry = (Map.Entry) itr2.next(); String attrName = (String) entry.getKey(); String attrCustomClass = (String) entry.getValue(); customUserAttributes.put(attrCustomClass, contextClassLoader.loadClass(attrCustomClass).newInstance()); } PortletContextWrapper pcw = new PortletContextWrapper(portlet.getPortletId(), ctx, portletInstance, indexerInstance, schedulerInstance, prefsValidator, resourceBundles, customUserAttributes); PortletContextPool.put(portlet.getPortletId(), pcw); } // Portlet class loader String servletPath = ctx.getRealPath("/"); if (!servletPath.endsWith("/") && !servletPath.endsWith("\\")) { servletPath += "/"; } File servletClasses = new File(servletPath + "WEB-INF/classes"); File servletLib = new File(servletPath + "WEB-INF/lib"); List urls = new ArrayList(); if (servletClasses.exists()) { urls.add(new URL("file:" + servletClasses + "/")); } if (servletLib.exists()) { String[] jars = FileUtil.listFiles(servletLib); for (int i = 0; i < jars.length; i++) { urls.add(new URL("file:" + servletLib + "/" + jars[i])); } } URLClassLoader portletClassLoader = new URLClassLoader((URL[]) urls.toArray(new URL[0]), contextClassLoader); ctx.setAttribute(WebKeys.PORTLET_CLASS_LOADER, portletClassLoader); // Portlet display String xml = Http.URLtoString(ctx.getResource("/WEB-INF/liferay-display.xml")); Map newCategories = PortletManagerUtil.getWARDisplay(_servletContextName, xml); for (int i = 0; i < _companyIds.length; i++) { String companyId = _companyIds[i]; Map oldCategories = (Map) WebAppPool.get(companyId, WebKeys.PORTLET_DISPLAY); Map mergedCategories = PortalUtil.mergeCategories(oldCategories, newCategories); WebAppPool.put(companyId, WebKeys.PORTLET_DISPLAY, mergedCategories); } // Reinitialize portal properties PropsUtil.init(); } catch (Exception e2) { Logger.error(this, e2.getMessage(), e2); } }
From source file:RestrictedService.java
public void init() throws ServletException { if (!gateInited) { try {/* w w w .ja v a 2s.co m*/ // 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. // English financial module. ArrayList<URL> dictionaries = new ArrayList<URL>(); dictionaries.add((new RestrictedService()).getClass().getResource("/LoughranMcDonald/lists.def")); modules.put("enFinancial", new DictionaryBasedSentimentAnalyzer("SAGA - Sentiment Analyzer", dictionaries)); // English financial + emoticon module. ArrayList<URL> dictionaries2 = new ArrayList<URL>(); dictionaries2.add((new RestrictedService()).getClass().getResource("/LoughranMcDonald/lists.def")); dictionaries2.add((new RestrictedService()).getClass() .getResource("/resources/gazetteer/emoticon/lists.def")); modules.put("enFinancialEmoticon", new DictionaryBasedSentimentAnalyzer("SAGA - Sentiment Analyzer", dictionaries2)); // Mongo login String user = ""; String password = ""; MongoCredential credential = MongoCredential.createMongoCRCredential(user, "RestrictedDictionaries", password.toCharArray()); MongoClient mongoClient = new MongoClient(new ServerAddress("localhost"), Arrays.asList(credential)); db = mongoClient.getDB("RestrictedDictionaries"); gateInited = true; } catch (Exception ex) { throw new ServletException("Exception initialising GATE", ex); } } }
From source file:com.jaspersoft.jasperserver.war.xmla.XmlaServletImpl.java
public void init(ServletConfig config) throws ServletException { ServletContext servletContext = config.getServletContext(); // TODO it is meaningless to generate URLs here, but the XMLServlet requires it // Looks like XML/A clients ignore the URL try {/*from w ww . j av a2s .c om*/ InetAddress local = InetAddress.getLocalHost(); // We can override the default protocol and port with servlet init parameters String defaultProtocol = servletContext.getInitParameter("defaultProtocol"); if (defaultProtocol == null || defaultProtocol.trim().length() == 0) { defaultProtocol = "http"; } String defaultPort = servletContext.getInitParameter("defaultPort"); if (defaultPort == null || defaultPort.trim().length() == 0) { defaultPort = "-1"; } int port = Integer.parseInt(defaultPort); URL root = servletContext.getResource("/"); // Looks like the path will be /localhost/webapp int pastHost = root.getPath().indexOf("/", 1); String path = root.getPath().substring(pastHost, root.getPath().length()); SERVER_URL = (new URL(defaultProtocol, local.getCanonicalHostName(), port, path)).toString() + "xmla"; } catch (Exception e) { throw new RuntimeException(e); } super.init(config); }
From source file:com.ocpsoft.pretty.faces.el.resolver.FacesConfigBeanNameResolver.java
/** * Returns a collection of faces configuration files mentioned via the * default <code>javax.faces.CONFIG_FILES</code> init parameter * //from w w w . ja v a 2s . com * @param servletContext * The ServletContext * @return A collection of URLs (never null) */ private Collection<URL> getConfigFilesFromInitParameter(ServletContext servletContext) { // read init parameter String initParam = servletContext.getInitParameter(FacesServlet.CONFIG_FILES_ATTR); // empty? return empty set if (initParam == null || initParam.trim().length() == 0) { return Collections.emptySet(); } // split string at each comma String[] files = initParam.split(","); // the result Set<URL> result = new HashSet<URL>(); // process each single file for (String file : files) { // ignore empty entries if (file.trim().length() == 0) { continue; } try { // try get URL for this file URL url = servletContext.getResource(file.trim()); // add it to the result, if it exists if (url != null) { result.add(url); } } catch (MalformedURLException e) { // log on debug level, because the JSF implementation should // handle such a case log.debug("Invalid entry in javax.faces.CONFIG_FILES init parameter: " + file); } } return result; }
From source file:org.red5.logging.ContextLoggingListener.java
public void contextInitialized(ServletContextEvent event) { ServletContext servletContext = event.getServletContext(); String contextName = servletContext.getContextPath().replaceAll("/", ""); if ("".equals(contextName)) { contextName = "root"; }/*from w ww .j a va2s . c o m*/ System.out.printf("Context init: %s%n", contextName); ConfigurableWebApplicationContext appctx = (ConfigurableWebApplicationContext) servletContext .getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE); if (appctx != null) { System.out.printf( "ConfigurableWebApplicationContext is not null in ContextLoggingListener for: %s, this indicates a misconfiguration or load order problem%n", contextName); } try { // get the selector ContextSelector selector = Red5LoggerFactory.getContextSelector(); // get the logger context for this servlet / app context by name URL url = servletContext.getResource(String.format("/WEB-INF/classes/logback-%s.xml", contextName)); if (url != null && Files.exists(Paths.get(url.toURI()))) { System.out.printf("Context logger config found: %s%n", url.toURI()); } else { url = servletContext.getResource("/WEB-INF/classes/logback.xml"); if (url != null && Files.exists(Paths.get(url.toURI()))) { System.out.printf("Context logger config found: %s%n", url.toURI()); } } // get the logger context for the servlet context LoggerContext loggerContext = url != null ? ((LoggingContextSelector) selector).getLoggerContext(contextName, url) : selector.getLoggerContext(contextName); // set the logger context for use elsewhere in the servlet context servletContext.setAttribute(Red5LoggerFactory.LOGGER_CONTEXT_ATTRIBUTE, loggerContext); // get the root logger for this context Logger logger = Red5LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME, contextName); logger.info("Starting up context: {}", contextName); } catch (Exception e) { System.err.printf("LoggingContextSelector is not the correct type: %s%n", e.getMessage()); e.printStackTrace(); } }
From source file:be.ff.gui.web.struts.action.ActionPlugInPlugIn.java
/** * Loads and verifies (using a DTD) the action plug-in configuration file. Afterwards this * method initializes the <code>ActionPlugInChain</code>. * * @param config ApplicationConfig for the sub-application with which this plug in is associated * @exception ServletException if this <code>PlugIn</code> cannot be successfully initialized *///www.jav a 2 s . c o m public void init(ActionServlet config, ModuleConfig module) throws ServletException { if (ActionPlugInChain.foiInicializado()) { if (log.isDebugEnabled()) { log.debug("O ActionPlugInPlugIn j foi inicializado anteriormente. Ignorando."); } return; } if (log.isDebugEnabled()) { log.debug("Entrada no mtodo"); } // this value object will hold the values specified in the action plug-in config file ActionPlugInChainDefinition chainDefintion = new ActionPlugInChainDefinition(); // create a digester to scan through the action plug-in config file Digester digester = new Digester(); digester.push(chainDefintion); // try to find a local DTD to validate the configuration file ServletContext context = config.getServletContext(); if (getConfigDTD() == null) { String msg = "[ActionPlugInPlugIn::init] Please specify a valid context relative location of " + "the DTD for the action plug-in configuration file. Do this in the Struts configuration " + "file at the plug-in tag that initializes the Action Plug-in Extension."; log.warn(msg); digester.setValidating(false); // Although set to false the SAX based parser STILL wants to load the publicly // available DTD that is specified in the XML file!! This causes an error on // times when the DTD at the specified location is not available. // Why doesn't this statement turn this of???? } else { URL dtdURL = null; try { dtdURL = context.getResource(getConfigDTD()); if (dtdURL == null) { String msg = "[ActionPlugInPlugIn::init] The action plug-in configuration DTD was not found at the " + "context relative location '" + getConfigDTD() + "'. Please make sure that this DTD is available at " + "a context relative location, because the system identifier that is specified in the " + "configuration file might not be accessible."; log.warn(msg); digester.setValidating(false); // Although set to false the SAX based parser STILL wants to load the publicly // available DTD that is specified in the XML file!! This causes an error on // times when the DTD at the specified location is not available. // Why doesn't this statement turn this of???? } else { digester.register(DOCTYPE_PUBLIC_ID, dtdURL.toString()); digester.setValidating(true); } } catch (MalformedURLException e) { String msg = "[ActionPlugInPlugIn::init] The location of the DTD for the action plug-in configuration file was " + "invalid:'" + getConfigDTD() + "'. Please specify a valid context relative location for the DTD."; log.warn(msg); digester.setValidating(false); // Although set to false the SAX based parser STILL wants to load the publicly // available DTD that is specified in the XML file!! This causes an error on // times when the DTD at the specified location is not available. // Why doesn't this statement turn this of???? } } // add rules digester.addObjectCreate("action-plug-in-config/action-plug-in", ActionPlugInDefinition.class); digester.addSetNext("action-plug-in-config/action-plug-in", "addActionPlugInDefintion", ActionPlugInDefinition.class.getName()); digester.addCallMethod("action-plug-in-config/action-plug-in/class", "setClassName", 0); digester.addCallMethod("action-plug-in-config/action-plug-in/init-params/param", "addInitParam", 2); digester.addCallParam("action-plug-in-config/action-plug-in/init-params/param/name", 0); digester.addCallParam("action-plug-in-config/action-plug-in/init-params/param/value", 1); digester.addCallMethod("action-plug-in-config/action-plug-in/disabled-for/action-path", "addDisabledActionPath", 0); digester.addCallMethod("action-plug-in-config/action-plug-in/enabled-for/action-path", "addEnabledActionPath", 0); // point to the XML file InputStream input = context.getResourceAsStream(getConfigFile()); if (input == null) { String msg = "[ActionPlugInPlugIn::init] The action plug-in configuration file was not found " + "at location '" + getConfigFile() + "'. Please make sure that you have specified " + "the correct value for the 'configFile' property of the action plug-in Struts " + "plug-in that is defined in struts-config.xml. Please note that this path is Web " + "application context relative."; throw new ServletException(msg); } // run the digester try { digester.parse(new BufferedInputStream(input)); } catch (Exception e) { String msg = "[ActionPlugInPlugIn::init] An exception was thrown during the parsing of the " + "action plug-in configuration file (" + getConfigFile() + "). Make sure that " + "the configuration file refers to a DTD and that its content is valid according to " + "that DTD."; throw new ServletException(msg, e); } finally { if (input != null) { try { input.close(); } catch (IOException e) { log.error( "[ActionPlugInPlugIn::init] An IOException was thrown while trying to close the input stream of the action plug-in configuration file.", e); } } } // ask the action plug-in chain to initialize itself ActionPlugInChain.init(chainDefintion, context); }
From source file:com.aurel.track.dbase.HandleHome.java
/** * Obtain the Torque.properties from from TRACKPLUS_HOME or if not available from the WAR. * @return// w w w . j ava 2s . co m * @throws ServletException */ public static InputStream getStream(ServletContext servletContext, String fileName) throws ServletException { File file = null; InputStream in = null; try { // First check if we have a configuration file pointed to by the environment if (HandleHome.getTrackplus_Home() != null && !"".equals(HandleHome.getTrackplus_Home())) { String fname = HandleHome.getTrackplus_Home(); file = new File(fname + File.separator + fileName); LOGGER.debug("Probing for file " + fname + File.separator + fileName); if (file.exists() && file.canRead()) { LOGGER.info("Retrieving configuration from " + fname + File.separator + fileName); in = new FileInputStream(file); // must be closed by caller } } if (in == null) { // if we could not get it from the environment URL fileURL = servletContext.getResource("/WEB-INF/" + fileName); in = fileURL.openStream(); } } catch (Exception e) { LOGGER.error("Could not read " + fileName + ". Exiting. " + e.getMessage()); System.err.println("Could not read " + fileName + ". Exiting. " + e.getMessage()); throw new ServletException(e); } return in; }
From source file:com.liferay.portal.util.PortalInstances.java
private long _initCompany(ServletContext ctx, String webId) { // Begin initializing company if (_log.isDebugEnabled()) { _log.debug("Begin initializing company with web id " + webId); }//www . j a v a 2 s .c o m long companyId = 0; try { Company company = CompanyLocalServiceUtil.checkCompany(webId); companyId = company.getCompanyId(); } catch (Exception e) { _log.error(e, e); } CompanyThreadLocal.setCompanyId(companyId); // Initialize display if (_log.isDebugEnabled()) { _log.debug("Initialize display"); } try { String xml = Http.URLtoString(ctx.getResource("/WEB-INF/liferay-display.xml")); PortletCategory portletCategory = (PortletCategory) WebAppPool.get(String.valueOf(companyId), WebKeys.PORTLET_CATEGORY); if (portletCategory == null) { portletCategory = new PortletCategory(); } PortletCategory newPortletCategory = PortletLocalServiceUtil.getEARDisplay(xml); portletCategory.merge(newPortletCategory); WebAppPool.put(String.valueOf(companyId), WebKeys.PORTLET_CATEGORY, portletCategory); } catch (Exception e) { _log.error(e, e); } // Check journal content search if (_log.isDebugEnabled()) { _log.debug("Check journal content search"); } if (GetterUtil .getBoolean(PropsUtil.get(CompanyImpl.SYSTEM, PropsUtil.JOURNAL_SYNC_CONTENT_SEARCH_ON_STARTUP)) || GetterUtil.getBoolean(PropsUtil.get(PropsUtil.JOURNAL_SYNC_CONTENT_SEARCH_ON_STARTUP))) { try { JournalContentSearchLocalServiceUtil.checkContentSearches(companyId); } catch (Exception e) { _log.error(e, e); } } // Scheduler if (_log.isDebugEnabled()) { _log.debug("Scheduler"); } try { if (GetterUtil.getBoolean(PropsUtil.get(PropsUtil.SCHEDULER_ENABLED))) { Iterator itr = PortletLocalServiceUtil.getPortlets(companyId).iterator(); while (itr.hasNext()) { Portlet portlet = (Portlet) itr.next(); String className = portlet.getSchedulerClass(); if (portlet.isActive() && Validator.isNotNull(className)) { Scheduler scheduler = (Scheduler) InstancePool.get(className); scheduler.schedule(); } } } } catch (ObjectAlreadyExistsException oaee) { } catch (Exception e) { _log.error(e, e); } // SMTP message listener if (_log.isDebugEnabled()) { _log.debug("SMTP message listener"); } try { Iterator itr = PortletLocalServiceUtil.getPortlets(companyId).iterator(); while (itr.hasNext()) { Portlet portlet = (Portlet) itr.next(); MessageListener smtpMessageListener = portlet.getSmtpMessageListenerInstance(); if (portlet.isActive() && (smtpMessageListener != null)) { SMTPServerUtil.addListener(smtpMessageListener); } } } catch (ObjectAlreadyExistsException oaee) { } catch (Exception e) { _log.error(e, e); } // LDAP Import try { if (PortalLDAPUtil.isImportOnStartup(companyId)) { PortalLDAPUtil.importFromLDAP(companyId); } } catch (Exception e) { _log.error(e, e); } // Message resources if (_log.isDebugEnabled()) { _log.debug("Message resources"); } MultiMessageResources messageResources = (MultiMessageResources) ctx.getAttribute(Globals.MESSAGES_KEY); messageResources.setServletContext(ctx); WebAppPool.put(String.valueOf(companyId), Globals.MESSAGES_KEY, messageResources); // Process application startup events if (_log.isDebugEnabled()) { _log.debug("Process application startup events"); } try { EventsProcessor.process(PropsUtil.getArray(PropsUtil.APPLICATION_STARTUP_EVENTS), new String[] { String.valueOf(companyId) }); } catch (Exception e) { _log.error(e, e); } // End initializing company if (_log.isDebugEnabled()) { _log.debug("End initializing company with web id " + webId + " and company id " + companyId); } addCompanyId(companyId); return companyId; }
From source file:it.classhidra.core.controller.bsController.java
private static String getContextPathFor5(ServletContext servletContext) { // Get the context path without the request. String contextPath = ""; try {/*from ww w . j ava 2 s. c om*/ String path = servletContext.getResource("/").getPath(); contextPath = path.substring(0, path.lastIndexOf("/")); contextPath = contextPath.substring(contextPath.lastIndexOf("/")); } catch (Exception e) { e.printStackTrace(); } return contextPath; }