List of usage examples for javax.servlet ServletContext getResource
public URL getResource(String path) throws MalformedURLException;
From source file:com.aurel.track.dbase.JobScheduler.java
/** * @param application//from w ww. j a v a2s . co m * @param torqueConfig * * This will instantiate and configure a Quartz scheduler. Database related * configuration items are taken from the Torque configuration such as not * to duplicate JDBC URLs, database type, user, and password entries. * Some properties can be configured in file /WEB-INF/Quartz.properties, * for example configuration parameters for clustering. * */ public static void init(ServletContext application, PropertiesConfiguration torqueConfig) { Properties qcfg = null; servletContext = application; try { URL quartzURL = application.getResource("/WEB-INF/Quartz.properties"); qcfg = new Properties(); InputStream in = quartzURL.openStream(); qcfg.load(in); in.close(); } catch (Exception e) { LOGGER.error("Getting the Quartz.properties failed with " + e.getMessage()); LOGGER.debug(ExceptionUtils.getStackTrace(e)); } if (qcfg == null) { LOGGER.error("qcfg is null"); return; } quartzProperties = qcfg; }
From source file:de.betterform.agent.web.WebFactory.java
/** * allow absolute paths otherwise resolve relative to the servlet context * * @param resolvePath XPath locationpath * @return the absolute path or path relative to the servlet context * @deprecated/*from ww w . ja v a 2 s.c o m*/ */ public static final String resolvePath(String resolvePath, ServletContext servletContext) { String path = resolvePath; try { if (path != null && !(path.startsWith("/"))) { path = "/" + path; } URL pathURL = servletContext.getResource(path); if (pathURL != null) { path = java.net.URLDecoder.decode(pathURL.getPath(), StandardCharsets.UTF_8.name()); } } catch (MalformedURLException e) { e.printStackTrace(); } catch (UnsupportedEncodingException ex) { ex.printStackTrace(); } return path; }
From source file:com.qualogy.qafe.web.ContextLoader.java
public static String getContextPath(ServletContext servletContext) throws MalformedURLException, URISyntaxException { // The default way: works on JBoss/Tomcat/Jetty String contextPath = servletContext.getRealPath("/WEB-INF/"); // This is how a weblogic explicitly wants the fetching of resources. if (contextPath == null) { URL url = servletContext.getResource("/WEB-INF/"); logger.log(Level.INFO, "Fallback scenario " + url.toString()); if (url != null) { logger.log(Level.INFO, "URL to config file " + url.toString()); contextPath = url.toURI().toString(); } else {/* w ww . j a v a2 s . com*/ throw new RuntimeException( "Strange Error: /WEB-INF/ cannot be found. Check the appserver or installation directory."); } } return contextPath; }
From source file:com.concursive.connect.scheduler.ScheduledJobs.java
/** * Scans the jobs path for the given ServletContext * * @param scheduler/*w w w . j a v a 2s . c o m*/ * @param context * @throws SchedulerException */ public static void addJobs(Scheduler scheduler, ServletContext context) throws SchedulerException { // Determine the ApplicationPrefs ApplicationPrefs prefs = (ApplicationPrefs) scheduler.getContext().get("ApplicationPrefs"); // Find job files in the jobs path Set<String> jobFiles = context.getResourcePaths("/WEB-INF/jobs/"); if (jobFiles != null && jobFiles.size() > 0) { for (String thisFile : jobFiles) { if (thisFile.endsWith(".xml")) { try { LOG.debug("Adding jobs from... " + thisFile); QuartzUtils.addJobs(scheduler, context.getResource(thisFile), prefs.getPrefs()); } catch (Exception e) { LOG.error("addJobs exception", e); } } } } }
From source file:de.betterform.agent.web.WebFactory.java
/** * get the absolute file path for a given relative path in the webapp. Handles some differences in server behavior * with the execution of context.getRealPath on various servers/operating systems * * @param path a path relative to the context root of the webapp * @param context the servletcontext/*from w w w. ja va2 s .c om*/ * @return the absolute file path for given relative webapp path */ public static String getRealPath(String path, ServletContext context) throws XFormsConfigException { if (path == null) { path = "/"; } if (!path.startsWith("/")) { path = "/" + path; } try { URI resourceURI = null; String computedRealPath = null; URL rootURL = Thread.currentThread().getContextClassLoader().getResource("/"); URL resourceURL = context.getResource(path); if (rootURL != null) { resourceURI = rootURL.toURI(); } if (resourceURI != null && resourceURI.getScheme().equalsIgnoreCase("file")) { String resourcePath = rootURL.getPath(); String rootPath = new File(resourcePath).getParentFile().getParent(); computedRealPath = new File(rootPath, path).getAbsolutePath(); } else if (resourceURL != null) { computedRealPath = new File(resourceURL.toExternalForm(), path).getAbsolutePath(); } else { String resourcePath = context.getRealPath("/"); computedRealPath = new File(resourcePath, path).getAbsolutePath(); } return java.net.URLDecoder.decode(computedRealPath, StandardCharsets.UTF_8.name()); } catch (UnsupportedEncodingException e) { throw new XFormsConfigException("path could not be resolved: " + path, e); } catch (URISyntaxException e) { throw new XFormsConfigException("path could not be resolved: " + path, e); } catch (MalformedURLException e) { throw new XFormsConfigException("path could not be resolved: " + path, e); } }
From source file:com.aurel.track.util.PropertiesConfigurationHelper.java
/** * Gets the PropertiesConfiguration for a property file from servlet context * @param servletContext/*ww w . j a v a 2s. c o m*/ * @param pathWithinContext * @param propFile * @return * @throws ServletException */ public static PropertiesConfiguration loadServletContextPropFile(ServletContext servletContext, String pathWithinContext, String propFile) throws ServletException { PropertiesConfiguration propertiesConfiguration = null; InputStream in = null; URL propFileURL = null; try { if (servletContext != null && pathWithinContext != null) { if (!pathWithinContext.startsWith("/")) { pathWithinContext = "/" + pathWithinContext; } if (!pathWithinContext.endsWith("/")) { pathWithinContext = pathWithinContext + "/"; } propFileURL = servletContext.getResource(pathWithinContext + propFile); in = propFileURL.openStream(); propertiesConfiguration = new PropertiesConfiguration(); propertiesConfiguration.load(in); in.close(); } } catch (Exception e) { LOGGER.error("Could not read " + propFile + " from servlet context " + propFileURL == null ? "" : propFileURL.toExternalForm() + ". Exiting. " + e.getMessage()); throw new ServletException(e); } return propertiesConfiguration; }
From source file:com.meltmedia.cadmium.core.util.LogUtils.java
/** * <p>Reconfigures the logging context.</p> * <p>The LoggerContext gets configured with "/WEB-INF/context-logback.xml". There is a <code>logDir</code> property set here which is expected to be the directory that the log file is written to.</p> * <p>The <code>logDir</code> property gets set on the LoggerContext with the following logic.</p> * <ul>// w ww . j av a 2 s .c om * <li>{@link LOG_DIR_INIT_PARAM} context parameter will be created and checked if it is writable.</li> * <li>The File object passed in is used as a fall-back if it can be created and written to.</li> * </ul> * @see {@link LoggerContext} * @param servletContext The current servlet context. * @param logDirFallback The fall-back directory to log to. * @param vHostName * @param log * @throws FileNotFoundException Thrown if no logDir can be written to. * @throws MalformedURLException * @throws IOException */ public static void configureLogback(ServletContext servletContext, File logDirFallback, String vHostName, Logger log) throws FileNotFoundException, MalformedURLException, IOException { log.debug("Reconfiguring Logback!"); String systemLogDir = System.getProperty(LOG_DIRECTORY_OVERRIDE, System.getProperty(JBOSS_LOG_DIR)); if (systemLogDir != null) { systemLogDir += "/" + vHostName; } File logDir = FileSystemManager.getWritableDirectoryWithFailovers(systemLogDir, servletContext.getInitParameter(LOG_DIR_INIT_PARAM), logDirFallback.getAbsolutePath()); if (logDir != null) { log.debug("Resetting logback context."); URL configFile = servletContext.getResource("/WEB-INF/context-logback.xml"); log.debug("Configuring logback with file, {}", configFile); LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory(); try { JoranConfigurator configurator = new JoranConfigurator(); configurator.setContext(context); context.stop(); context.reset(); context.putProperty("logDir", logDir.getCanonicalPath()); configurator.doConfigure(configFile); } catch (JoranException je) { // StatusPrinter will handle this } finally { context.start(); log.debug("Done resetting logback."); } StatusPrinter.printInCaseOfErrorsOrWarnings(context); } }
From source file:com.aurel.track.admin.customize.category.report.execute.ReportExecuteBL.java
/** * Serializes the data source into the response's output stream using a * ReportExporter/*from w ww. ja v a 2 s.c om*/ * * @param templateID * @param datasource * @return */ static String prepareReportResponse(HttpServletResponse response, Integer templateID, Map<String, Object> contextMap, Map<String, Object> description, Object datasource, Map<String, Object> parameters, ServletContext servletContext, TPersonBean personBean, Locale locale) { URL baseURL = null; String logoFolder = null; URL completeURL = null; String baseFileName = null; if (templateID == null) { final String baseFolder = "/design/silver/"; // direct pdf/xls from report overview try { // set the baseURL to take some standard icons from // "/design/silver/icons" // which ale already used by the report overview anyway baseURL = servletContext.getResource(baseFolder + "16x16"); LOGGER.debug("baseURL: " + baseURL.toString()); } catch (final MalformedURLException e) { LOGGER.error("Getting the baseURL for " + baseFolder + "16x16 failed with " + e.getMessage()); LOGGER.debug(ExceptionUtils.getStackTrace(e)); } // set the baseURL to take some standard icons from // "/design/silver/icons" // which ale already used by the report overview anyway logoFolder = HandleHome.getTrackplus_Home() + File.separator + HandleHome.LOGOS_DIR + File.separator; } else { // template exists final File template = ReportBL.getDirTemplate(templateID); final ILabelBean templateBean = ReportFacade.getInstance().getByKey(templateID); if (templateBean != null) { baseFileName = templateBean.getLabel(); } try { baseURL = template.toURL(); LOGGER.debug("baseURL: " + baseURL.toString()); } catch (final MalformedURLException e) { LOGGER.error("Wrong template URL for " + template.getName() + e.getMessage()); LOGGER.debug(ExceptionUtils.getStackTrace(e)); return null; } try { completeURL = new URL(baseURL.toExternalForm() /* * + * "/"File.separator */ + description.get(IDescriptionAttributes.MASTERFILE)); completeURL.openStream(); LOGGER.debug("completeURL: " + completeURL.toString()); } catch (final Exception me) { LOGGER.error(LocalizeUtil.getParametrizedString( "report.reportExportManager.err.masterFileTemplateNotFound", new String[] { me.getMessage() }, locale) + me); return null; } } if (parameters == null) { parameters = new HashMap<String, Object>(); } parameters.put(JasperReportExporter.REPORT_PARAMETERS.BASE_URL, baseURL); if (logoFolder != null) { parameters.put(JasperReportExporter.REPORT_PARAMETERS.LOGO_FOLDER_URL, logoFolder); } if (completeURL != null) { parameters.put(JasperReportExporter.REPORT_PARAMETERS.COMPLETE_URL, completeURL); } if (baseFileName == null) { baseFileName = "TrackReport"; } baseFileName += DateTimeUtils.getInstance().formatISODateTime(new Date()); response.reset(); final String format = (String) description.get(IDescriptionAttributes.FORMAT); if (ReportExporter.FORMAT_PDF.equals(format)) { response.setHeader("Content-Type", "application/pdf"); response.setHeader("Content-Disposition", "attachment; filename=\"" + baseFileName + ".pdf\""); } else if (ReportExporter.FORMAT_RTF.equals(format)) { response.setHeader("Content-Type", "application/rtf"); response.setHeader("Content-Disposition", "attachment; filename=\"" + baseFileName + ".rtf\""); } else if (ReportExporter.FORMAT_XML.equals(format)) { response.setHeader("Content-Type", "text/xml"); response.setHeader("Content-Disposition", "attachment; filename=\"" + baseFileName + ".xml\""); } else if (ReportExporter.FORMAT_HTML.equals(format)) { response.setHeader("Content-Type", "text/html"); response.setHeader("Content-Disposition", "attachment; filename=\"" + baseFileName + ".html\""); } else if (ReportExporter.FORMAT_ZIP.equals(format)) { response.setHeader("Content-Type", "application/octet-stream"); response.setHeader("Content-Disposition", "attachment; filename=\"" + baseFileName + ".zip\""); } else if (ReportExporter.FORMAT_XLS.equals(format)) { response.setHeader("Content-Type", "application/xls"); response.setHeader("Content-Disposition", "attachment; filename=\"" + baseFileName + ".xls\""); } else if (ReportExporter.FORMAT_CSV.equals(format)) { final String csvEncoding = personBean.getCsvEncoding(); LOGGER.debug("csvEncoding is " + csvEncoding); if (csvEncoding != null) { response.setContentType("text/plain; " + csvEncoding); } else { response.setContentType("text/plain; charset=UTF-8"); } response.setHeader("Content-Disposition", "attachment; filename=\"" + baseFileName + ".csv\""); } else if (ReportExporter.FORMAT_DOCX.equals(format)) { response.setHeader("Content-Type", "application/vnd.openxmlformats-officedocument.wordprocessingml.document"); response.setHeader("Content-Disposition", "attachment; filename=\"" + baseFileName + ".docx\""); } DownloadUtil.prepareCacheControlHeader(ServletActionContext.getRequest(), response); OutputStream outputStream = null; try { outputStream = response.getOutputStream(); } catch (final IOException e) { LOGGER.error("Getting the output stream failed with " + e.getMessage()); if (LOGGER.isDebugEnabled()) { LOGGER.debug(ExceptionUtils.getStackTrace(e)); } } try { LOGGER.debug("Exporter type is " + description.get(IDescriptionAttributes.TYPE) + " exporter format is " + description.get(IDescriptionAttributes.FORMAT)); final ReportExporter exporter = ReportExecuteBL .getExporter((String) description.get(IDescriptionAttributes.TYPE)); exporter.exportReport((Document) datasource, personBean, locale, parameters, outputStream, contextMap, description); LOGGER.debug("Export done..."); } catch (final ReportExportException e) { LOGGER.error("Exporting the report failed with " + e.getMessage()); String actionMessage = ""; if (e.getCause() != null) { actionMessage = LocalizeUtil.getParametrizedString(e.getMessage(), new String[] { e.getCause().getMessage() }, locale); } else { actionMessage = LocalizeUtil.getLocalizedTextFromApplicationResources(e.getMessage(), locale); } LOGGER.error(actionMessage); if (LOGGER.isDebugEnabled()) { LOGGER.debug(ExceptionUtils.getStackTrace(e)); } } catch (final Exception e) { LOGGER.error("Exporting the report failed with throwable " + e.getMessage()); if (LOGGER.isDebugEnabled()) { LOGGER.debug(ExceptionUtils.getStackTrace(e)); } } return null; }
From source file:ie.wombat.rt.fireeagle.CookieConsumer.java
public static OAuthConsumer getConsumer(String name, ServletContext context) throws IOException { synchronized (CookieConsumer.class) { if (consumers == null) { String resourceName = "/" + CookieConsumer.class.getPackage().getName().replace(".", "/") + "/consumer.properties"; consumerProperties = ConsumerProperties.getProperties( ConsumerProperties.getResource(resourceName, CookieConsumer.class.getClassLoader())); consumers = new ConsumerProperties(consumerProperties); }/*from w w w.j av a 2 s . c om*/ } if (context != null) { synchronized (consumerProperties) { String key = name + ".callbackURL"; String value = consumerProperties.getProperty(key); if (value == null) { // Compute the callbackURL from the servlet context. URL resource = context.getResource(Callback.PATH); if (resource != null) { value = resource.toExternalForm(); } else { value = Callback.PATH; } consumerProperties.setProperty(key, value); } } } OAuthConsumer consumer = consumers.getConsumer(name); return consumer; }
From source file:com.vaadin.tests.push.TrackMessageSizeUI.java
private URL findResourceURL(String filename, VaadinServletService service) { ServletContext sc = service.getServlet().getServletContext(); URL resourceUrl;//from w w w . ja v a 2 s . c o m try { resourceUrl = sc.getResource(filename); } catch (MalformedURLException e) { throw new RuntimeException(e); } if (resourceUrl == null) { // try if requested file is found from classloader // strip leading "/" otherwise stream from JAR wont work if (filename.startsWith("/")) { filename = filename.substring(1); } resourceUrl = service.getClassLoader().getResource(filename); } return resourceUrl; }