List of usage examples for javax.servlet ServletContext getRealPath
public String getRealPath(String path);
From source file:com.aurel.track.dbase.HandleHome.java
private static void copyLanguageProfiles(ServletContext context, String templateBaseDir) { String tpHome = getTrackplus_Home(); File templatesDir = new File(tpHome + File.separator + templateBaseDir); URL rootTillFolder = null;/*from ww w .ja v a 2s. com*/ String rootPathTillFolder = null; String templatePath = templateBaseDir.replace("\\", "/"); try { if (context.getResource("/WEB-INF/classes/resources/" + templatePath) != null) { rootTillFolder = context.getResource("/WEB-INF/classes/resources/" + templatePath); } else if (context.getResource("/WEB-INF/classes/" + templatePath) != null) { rootTillFolder = context.getResource("/WEB-INF/classes/" + templatePath); } else { rootTillFolder = new URL(context.getRealPath("../.")); } } catch (IOException ioEx) { LOGGER.error(ExceptionUtils.getStackTrace(ioEx)); } if (rootTillFolder != null) { rootPathTillFolder = rootTillFolder.getPath(); if (rootPathTillFolder.contains("/WEB-INF")) { rootPathTillFolder = rootPathTillFolder.substring(rootPathTillFolder.indexOf("/WEB-INF"), rootPathTillFolder.length()); } Set<String> folderContent = context.getResourcePaths(rootPathTillFolder); for (String fileNameWithPath : folderContent) { String fileName = fileNameWithPath.replace("/WEB-INF/classes/resources/" + templatePath + "/", ""); try { copyObject(context, "resources/" + templatePath, fileName, templateBaseDir); } catch (ServletException servEx) { LOGGER.error(ExceptionUtils.getStackTrace(servEx)); } } try { FileUtils.deleteQuietly(new File(HandleHome.getTrackplus_Home() + File.separator + LANGUAGE_PROFILES_DIR + File.separator + "hash.txt")); } catch (Exception e) { LOGGER.error(e.getMessage()); } } }
From source file:org.jbpm.designer.repository.VFSRepositoryGitFileSystemTest.java
@Test public void testCreateGlobalDirOnNewProject() throws Exception { ServletContext servletContext = mock(ServletContext.class); when(servletContext.getRealPath(anyString())).thenReturn(getClass().getResource("default.json").getFile()); HttpServletRequest servletRequest = mock(HttpServletRequest.class); when(servletRequest.getServletContext()).thenReturn(servletContext); VFSRepository repository = new VFSRepository(producer.getIoService()); repository.setDescriptor(descriptor); repository.setServletRequest(servletRequest); Directory testProjectDir = repository.createDirectory("/mytestproject"); final KieModule mockModule = mock(KieModule.class); when(mockModule.getRootPath()).thenReturn(Paths .convert(producer.getIoService().get(URI.create(decodeUniqueId(testProjectDir.getUniqueId()))))); final NewModuleEvent event = mock(NewModuleEvent.class); when(event.getModule()).thenReturn(mockModule); repository.createGlobalDirOnNewProject(event); boolean globalDirectoryExists = repository.directoryExists("/mytestproject/global"); assertTrue(globalDirectoryExists);//from w w w .j a va2 s. c om Collection<Asset> foundFormTemplates = repository.listAssets("/mytestproject/global", new FilterByExtension("fw")); assertNotNull(foundFormTemplates); assertEquals(0, foundFormTemplates.size()); Collection<Asset> foundJSONAssets = repository.listAssets("/mytestproject/global", new FilterByExtension("json")); assertNotNull(foundJSONAssets); assertEquals(3, foundJSONAssets.size()); Collection<Asset> foundWidAssets = repository.listAssets("/mytestproject", new FilterByExtension("wid")); assertNotNull(foundWidAssets); assertEquals(0, foundWidAssets.size()); // call again to try to trigger FileAlreadyExistsException repository.createGlobalDirOnNewProject(event); boolean globalDirectoryStillExists = repository.directoryExists("/mytestproject/global"); assertTrue(globalDirectoryStillExists); // no new files or copies were added Collection<Asset> foundFormTemplatesAfterSecondCall = repository.listAssets("/mytestproject/global", new FilterByExtension("fw")); assertNotNull(foundFormTemplatesAfterSecondCall); assertEquals(0, foundFormTemplatesAfterSecondCall.size()); Collection<Asset> foundJSONAssetsAfterSecondCall = repository.listAssets("/mytestproject/global", new FilterByExtension("json")); assertNotNull(foundJSONAssetsAfterSecondCall); assertEquals(3, foundJSONAssetsAfterSecondCall.size()); Collection<Asset> foundWidAssetsAfterSecondCall = repository.listAssets("/mytestproject", new FilterByExtension("wid")); assertNotNull(foundWidAssetsAfterSecondCall); assertEquals(0, foundWidAssetsAfterSecondCall.size()); }
From source file:org.jbpm.designer.repository.VFSRepositoryGitFileSystemTest.java
@Test public void testCreateGlobalDirOnNewProjectWithSpaces() throws Exception { ServletContext servletContext = mock(ServletContext.class); when(servletContext.getRealPath(anyString())).thenReturn(getClass().getResource("default.json").getFile()); HttpServletRequest servletRequest = mock(HttpServletRequest.class); when(servletRequest.getServletContext()).thenReturn(servletContext); VFSRepository repository = new VFSRepository(producer.getIoService()); repository.setDescriptor(descriptor); repository.setServletRequest(servletRequest); Directory testProjectDir = repository.createDirectory("/my test project"); final KieModule mockProject = mock(KieModule.class); when(mockProject.getRootPath()).thenReturn(Paths .convert(producer.getIoService().get(URI.create(decodeUniqueId(testProjectDir.getUniqueId()))))); NewModuleEvent event = mock(NewModuleEvent.class); when(event.getModule()).thenReturn(mockProject); repository.createGlobalDirOnNewProject(event); boolean globalDirectoryExists = repository.directoryExists("/my test project/global"); assertTrue(globalDirectoryExists);/*from ww w . j a v a 2 s. c o m*/ Collection<Asset> foundFormTemplates = repository.listAssets("/my test project/global", new FilterByExtension("fw")); assertNotNull(foundFormTemplates); assertEquals(0, foundFormTemplates.size()); Collection<Asset> foundJSONAssets = repository.listAssets("/my test project/global", new FilterByExtension("json")); assertNotNull(foundJSONAssets); assertEquals(3, foundJSONAssets.size()); Collection<Asset> foundWidAssets = repository.listAssets("/my test project", new FilterByExtension("wid")); assertNotNull(foundWidAssets); assertEquals(0, foundWidAssets.size()); // call again to try to trigger FileAlreadyExistsException repository.createGlobalDirOnNewProject(event); boolean globalDirectoryStillExists = repository.directoryExists("/my test project/global"); assertTrue(globalDirectoryStillExists); // no new files or copies were added Collection<Asset> foundFormTemplatesAfterSecondCall = repository.listAssets("/my test project/global", new FilterByExtension("fw")); assertNotNull(foundFormTemplatesAfterSecondCall); assertEquals(0, foundFormTemplatesAfterSecondCall.size()); Collection<Asset> foundJSONAssetsAfterSecondCall = repository.listAssets("/my test project/global", new FilterByExtension("json")); assertNotNull(foundJSONAssetsAfterSecondCall); assertEquals(3, foundJSONAssetsAfterSecondCall.size()); Collection<Asset> foundWidAssetsAfterSecondCall = repository.listAssets("/my test project", new FilterByExtension("wid")); assertNotNull(foundWidAssetsAfterSecondCall); assertEquals(0, foundWidAssetsAfterSecondCall.size()); }
From source file:org.apache.ofbiz.order.order.OrderEvents.java
public static String downloadDigitalProduct(HttpServletRequest request, HttpServletResponse response) { HttpSession session = request.getSession(); ServletContext application = session.getServletContext(); Delegator delegator = (Delegator) request.getAttribute("delegator"); GenericValue userLogin = (GenericValue) session.getAttribute("userLogin"); String dataResourceId = request.getParameter("dataResourceId"); try {/*from w ww .jav a2s. co m*/ // has the userLogin.partyId ordered a product with DIGITAL_DOWNLOAD content associated for the given dataResourceId? GenericValue orderRoleAndProductContentInfo = EntityQuery.use(delegator) .from("OrderRoleAndProductContentInfo") .where("partyId", userLogin.get("partyId"), "dataResourceId", dataResourceId, "productContentTypeId", "DIGITAL_DOWNLOAD", "statusId", "ITEM_COMPLETED") .queryFirst(); if (orderRoleAndProductContentInfo == null) { request.setAttribute("_ERROR_MESSAGE_", "No record of purchase for digital download found (dataResourceId=[" + dataResourceId + "])."); return "error"; } // TODO: check validity based on ProductContent fields: useCountLimit, useTime/useTimeUomId if (orderRoleAndProductContentInfo.getString("mimeTypeId") != null) { response.setContentType(orderRoleAndProductContentInfo.getString("mimeTypeId")); } OutputStream os = response.getOutputStream(); GenericValue dataResource = EntityQuery.use(delegator).from("DataResource") .where("dataResourceId", dataResourceId).cache().queryOne(); Map<String, Object> resourceData = DataResourceWorker.getDataResourceStream(dataResource, "", application.getInitParameter("webSiteId"), UtilHttp.getLocale(request), application.getRealPath("/"), false); os.write(IOUtils.toByteArray((ByteArrayInputStream) resourceData.get("stream"))); os.flush(); } catch (GenericEntityException e) { String errMsg = "Error downloading digital product content: " + e.toString(); Debug.logError(e, errMsg, module); request.setAttribute("_ERROR_MESSAGE_", errMsg); return "error"; } catch (GeneralException e) { String errMsg = "Error downloading digital product content: " + e.toString(); Debug.logError(e, errMsg, module); request.setAttribute("_ERROR_MESSAGE_", errMsg); return "error"; } catch (IOException e) { String errMsg = "Error downloading digital product content: " + e.toString(); Debug.logError(e, errMsg, module); request.setAttribute("_ERROR_MESSAGE_", errMsg); return "error"; } return "success"; }
From source file:com.aurel.track.dbase.HandleHome.java
private static void copyExportTemplates(ServletContext context, String templateBaseDir) { String tpHome = getTrackplus_Home(); File templatesDir = new File(tpHome + File.separator + templateBaseDir); URL rootTillFolder = null;/*www. java 2s . co m*/ String rootPathTillFolder = null; String templatePath = templateBaseDir.replace("\\", "/"); try { if (context.getResource("/WEB-INF/classes/resources/" + templatePath) != null) { rootTillFolder = context.getResource("/WEB-INF/classes/resources/" + templatePath); } else if (context.getResource("/WEB-INF/classes/" + templatePath) != null) { rootTillFolder = context.getResource("/WEB-INF/classes/" + templatePath); } else { rootTillFolder = new URL(context.getRealPath("../.")); } } catch (IOException ioEx) { LOGGER.error(ExceptionUtils.getStackTrace(ioEx)); } if (rootTillFolder != null) { rootPathTillFolder = rootTillFolder.getPath(); if (rootPathTillFolder.contains("/WEB-INF")) { rootPathTillFolder = rootPathTillFolder.substring(rootPathTillFolder.indexOf("/WEB-INF"), rootPathTillFolder.length()); } Set<String> folderContent = context.getResourcePaths(rootPathTillFolder); if (folderContent != null) { for (String fileNameWithPath : folderContent) { String fileName = fileNameWithPath.replace("/WEB-INF/classes/resources/" + templatePath + "/", ""); if (fileName.endsWith(".docx") || fileName.endsWith(".tex") || fileName.endsWith(".jpg") || fileName.endsWith(".png") || fileName.endsWith(".tlx") || fileName.endsWith(".sh") || fileName.endsWith(".cmd") || fileName.endsWith(".pdf")) { try { copyObject(context, "resources/" + templatePath, fileName, templateBaseDir); } catch (ServletException servEx) { LOGGER.error(ExceptionUtils.getStackTrace(servEx)); } } if (fileName.endsWith(".sh") || fileName.endsWith(".cmd")) { File fileToCopyInHome = new File( tpHome + File.separator + templateBaseDir + File.separator + fileName); fileToCopyInHome.setExecutable(true); } if (fileName.endsWith(".zip") || fileName.endsWith(".tlx")) { try { File fileToCopyInHome = new File( tpHome + File.separator + templateBaseDir + File.separator + fileName); copyObject(context, "resources/" + templatePath, fileName, templateBaseDir); File fileToUnzip = new File( tpHome + File.separator + templateBaseDir + File.separator + fileName); PluginUtils.unzipFileIntoDirectory(fileToUnzip, templatesDir); } catch (ServletException servEx) { LOGGER.error(ExceptionUtils.getStackTrace(servEx)); } } } } } }
From source file:com.gtwm.pb.servlets.AppController.java
/** * init() is called once automatically by the servlet container (e.g. * Tomcat) at servlet startup. We use it to initialise various things, * namely:/* ww w. ja v a 2s. c o m*/ * * a) create the DatabaseDefn object which is the top level application * object. The DatabaseDefn object will load the list of tables & reports * into memory when it is constructed. It will also configure and load the * object database * * b) create a DataSource object here to pass to the DatabaseDefn. This data * source then acts as a pool of connections from which a connection to the * relational database can be called up whenever needed. */ public void init() throws ServletException { logger.info("Initialising " + AppProperties.applicationName); ServletContext servletContext = getServletContext(); this.webAppRoot = servletContext.getRealPath("/"); // Create and cache a DatabaseDefn object which is an entry point to all // application logic // and schema information. The relational database is also gotten DataSource relationalDataSource = null; InitialContext initialContext = null; try { // Get a data source for the relational database to pass to the // DatabaseDefn object initialContext = new InitialContext(); relationalDataSource = (DataSource) initialContext.lookup("java:comp/env/jdbc/agileBaseData"); if (relationalDataSource == null) { throw new ServletException("Can't get data source"); } this.relationalDataSource = relationalDataSource; // Store 'global objects' data sources and webAppRoot in // databaseDefn this.databaseDefn = new DatabaseDefn(relationalDataSource, this.webAppRoot); // Store top level stuff in the context so that other servlets can // access it servletContext.setAttribute("com.gtwm.pb.servlets.databaseDefn", this.databaseDefn); servletContext.setAttribute("com.gtwm.pb.servlets.relationalDataSource", this.relationalDataSource); } catch (NullPointerException npex) { ServletUtilMethods.logException(npex, "Error initialising controller servlet"); throw new ServletException("Error initialising controller servlet", npex); } catch (SQLException sqlex) { ServletUtilMethods.logException(sqlex, "Database error loading schema"); throw new ServletException("Database error loading schema", sqlex); } catch (NamingException neex) { ServletUtilMethods.logException(neex, "Can't get initial context"); throw new ServletException("Can't get initial context"); } catch (RuntimeException rtex) { ServletUtilMethods.logException(rtex, "Runtime initialisation error"); throw new ServletException("Runtime initialisation error", rtex); } catch (Exception ex) { ServletUtilMethods.logException(ex, "General initialisation error"); throw new ServletException("General initialisation error", ex); } logger.info("Application fully loaded"); }
From source file:com.netspective.sparx.template.freemarker.FreeMarkerConfigurationAdapters.java
public void applyWebAppConfiguration(Configuration fmConfig, ServletContext servletContext) { String templatePathsText = servletContext .getInitParameter("com.netspective.sparx.template.freemarker.template-paths"); String templatePathsDelim = servletContext .getInitParameter("com.netspective.sparx.template.freemarker.template-path-delim"); List templateLoaders = new ArrayList(); templateLoaders.add(stringTemplateLoader); templateLoaders.add(new WebappTemplateLoader(servletContext)); try {/*from w w w . j a va 2 s . c o m*/ if (templatePathsText != null) { String[] templatePaths = TextUtils.getInstance().split(templatePathsText, templatePathsDelim == null ? File.pathSeparator : templatePathsDelim, true); for (int i = 0; i < templatePaths.length; i++) templateLoaders .add(new FileTemplateLoader(new File(servletContext.getRealPath(templatePaths[i])))); } } catch (Exception e) { log.error("Unable to setup file templates loader.", e); throw new NestableRuntimeException(e); } // allow stuff to be loaded from CLASSPATH too (like Console, etc) templateLoaders.add(new ClassTemplateLoader(com.netspective.sparx.ProductRelease.class)); templateLoaders.add(new ClassTemplateLoader(com.netspective.axiom.ProductRelease.class)); templateLoaders.add(new ClassTemplateLoader(com.netspective.commons.ProductRelease.class)); fmConfig.setTemplateLoader(new MultiTemplateLoader( (TemplateLoader[]) templateLoaders.toArray(new TemplateLoader[templateLoaders.size()]))); configureSharedVariables(fmConfig); }
From source file:org.apache.struts.tiles.xmlDefinition.I18nFactorySet.java
/** * Parse specified xml file and add definition to specified definitions set. * This method is used to load several description files in one instances list. * If filename exists and definition set is <code>null</code>, create a new set. Otherwise, return * passed definition set (can be <code>null</code>). * @param servletContext Current servlet context. Used to open file. * @param filename Name of file to parse. * @param xmlDefinitions Definitions set to which definitions will be added. If null, a definitions * set is created on request.// w w w . j av a 2 s . c o m * @return XmlDefinitionsSet The definitions set created or passed as parameter. * @throws DefinitionsFactoryException On errors parsing file. */ protected XmlDefinitionsSet parseXmlFile(ServletContext servletContext, String filename, XmlDefinitionsSet xmlDefinitions) throws DefinitionsFactoryException { try { InputStream input = servletContext.getResourceAsStream(filename); // Try to load using real path. // This allow to load config file under websphere 3.5.x // Patch proposed Houston, Stephen (LIT) on 5 Apr 2002 if (null == input) { try { input = new java.io.FileInputStream(servletContext.getRealPath(filename)); } catch (Exception e) { } } // If the config isn't in the servlet context, try the class loader // which allows the config files to be stored in a jar if (input == null) { input = getClass().getResourceAsStream(filename); } // If still nothing found, this mean no config file is associated if (input == null) { if (log.isDebugEnabled()) { log.debug("Can't open file '" + filename + "'"); } return xmlDefinitions; } // Check if parser already exist. // Doesn't seem to work yet. //if( xmlParser == null ) if (true) { xmlParser = new XmlParser(); xmlParser.setValidating(isValidatingParser); } // Check if definition set already exist. if (xmlDefinitions == null) { xmlDefinitions = new XmlDefinitionsSet(); } xmlParser.parse(input, xmlDefinitions); } catch (SAXException ex) { if (log.isDebugEnabled()) { log.debug("Error while parsing file '" + filename + "'."); ex.printStackTrace(); } throw new DefinitionsFactoryException("Error while parsing file '" + filename + "'. " + ex.getMessage(), ex); } catch (IOException ex) { throw new DefinitionsFactoryException( "IO Error while parsing file '" + filename + "'. " + ex.getMessage(), ex); } return xmlDefinitions; }
From source file:org.apache.tiles.xmlDefinition.I18nFactorySet.java
/** * Parse specified xml file and add definition to specified definitions set. * This method is used to load several description files in one instances list. * If filename exists and definition set is <code>null</code>, create a new set. Otherwise, return * passed definition set (can be <code>null</code>). * @param servletContext Current servlet context. Used to open file. * @param filename Name of file to parse. * @param xmlDefinitions Definitions set to which definitions will be added. If null, a definitions * set is created on request./* www. j ava 2 s . co m*/ * @return XmlDefinitionsSet The definitions set created or passed as parameter. * @throws DefinitionsFactoryException On errors parsing file. */ private XmlDefinitionsSet parseXmlFile(ServletContext servletContext, String filename, XmlDefinitionsSet xmlDefinitions) throws DefinitionsFactoryException { try { InputStream input = servletContext.getResourceAsStream(filename); // Try to load using real path. // This allow to load config file under websphere 3.5.x // Patch proposed Houston, Stephen (LIT) on 5 Apr 2002 if (null == input) { try { input = new java.io.FileInputStream(servletContext.getRealPath(filename)); } catch (Exception e) { } } // If still nothing found, this mean no config file is associated if (input == null) { if (log.isDebugEnabled()) { log.debug("Can't open file '" + filename + "'"); } return xmlDefinitions; } // Check if parser already exist. // Doesn't seem to work yet. //if( xmlParser == null ) if (true) { xmlParser = new XmlParser(); xmlParser.setValidating(isValidatingParser); } // Check if definition set already exist. if (xmlDefinitions == null) { xmlDefinitions = new XmlDefinitionsSet(); } xmlParser.parse(input, xmlDefinitions); } catch (SAXException ex) { if (log.isDebugEnabled()) { log.debug("Error while parsing file '" + filename + "'."); ex.printStackTrace(); } throw new DefinitionsFactoryException("Error while parsing file '" + filename + "'. " + ex.getMessage(), ex); } catch (IOException ex) { throw new DefinitionsFactoryException( "IO Error while parsing file '" + filename + "'. " + ex.getMessage(), ex); } return xmlDefinitions; }
From source file:com.ideo.jso.Group.java
/** * // w w w . j a v a 2 s . c o m * @param servletContext * @return the more recent modification date of the js file of this group and of its subgroups, as a long * @throws MalformedURLException */ private long getMaxJSTimestamp(ServletContext servletContext) throws MalformedURLException { long maxJSTimeStamp = 0; // check js files into the subgroups for (int i = 0; i < subgroups.size(); i++) { Group subGroup = (Group) subgroups.get(i); long mx = subGroup.getMaxJSTimestamp(servletContext); if (mx > maxJSTimeStamp) maxJSTimeStamp = mx; } List files = getJsNames(); //check js files into this group for (int i = 0; i < files.size(); i++) { String webPath = (String) files.get(i); String fileName = servletContext.getRealPath(webPath); long mx = getFileTimeStamp(fileName); if (mx > maxJSTimeStamp) maxJSTimeStamp = mx; } return maxJSTimeStamp; }