List of usage examples for javax.servlet ServletContext getRealPath
public String getRealPath(String path);
From source file:com.siacra.beans.AsignaturaBean.java
public void handleFileUpload(FileUploadEvent event) { try {// ww w.j a v a2 s .co m Asignatura asignatura = getAsignaturaService().getAsignaturaById(getIdAsignatura()); /* Obtenemos el path */ ServletContext context = (ServletContext) FacesContext.getCurrentInstance().getExternalContext() .getContext(); String path = context.getRealPath("/WEB-INF/files/"); /* Inicializamos el destino y el origen */ File targetFolder = new File(path); InputStream inputStream = event.getFile().getInputstream(); /* Escribimos en el destino, leyendo la data del origen */ OutputStream out = new FileOutputStream(new File(targetFolder, event.getFile().getFileName())); int read = 0; byte[] bytes = new byte[1024]; while ((read = inputStream.read(bytes)) != -1) { out.write(bytes, 0, read); } /* Cerramos los archivos */ inputStream.close(); out.flush(); out.close(); asignatura.setProgramaPDF(path + "\\" + event.getFile().getFileName()); getAsignaturaService().updateAsignatura(asignatura); RequestContext.getCurrentInstance().showMessageInDialog(new FacesMessage(FacesMessage.SEVERITY_INFO, "Informacion", "El archivo fue cargado correctamente")); } catch (IOException e) { RequestContext.getCurrentInstance().showMessageInDialog(new FacesMessage(FacesMessage.SEVERITY_FATAL, "Informacion", "El archivo no pudo ser cargado correctamente")); System.out.println(e.getMessage()); } }
From source file:nl.nn.adapterframework.webcontrol.ConfigurationServlet.java
@Override public void init() throws ServletException { super.init(); setUploadPathInServletContext();/*from w w w. j a va 2s . c o m*/ ibisContext = new IbisContext(); setDefaultApplicationServerType(ibisContext); ServletContext servletContext = getServletContext(); AppConstants appConstants = AppConstants.getInstance(); String attributeKey = appConstants.getResolvedProperty(KEY_CONTEXT); servletContext.setAttribute(attributeKey, ibisContext); log.debug("stored IbisContext [" + ClassUtils.nameOf(ibisContext) + "][" + ibisContext + "] in ServletContext under key [" + attributeKey + "]"); String realPath = servletContext.getRealPath("/"); if (realPath != null) { appConstants.put("webapp.realpath", realPath); } else { log.warn("Could not determine webapp.realpath"); } ibisContext.init(); log.debug("Servlet init finished"); }
From source file:com.rapid.server.RapidServletContextListener.java
public static int loadDatabaseDrivers(ServletContext servletContext) throws Exception { // create a schema object for the xsd Schema schema = _schemaFactory .newSchema(new File(servletContext.getRealPath("/WEB-INF/schemas/") + "/databaseDrivers.xsd")); // create a validator Validator validator = schema.newValidator(); // read the xml into a string String xml = Strings/*ww w . j av a 2s . c om*/ .getString(new File(servletContext.getRealPath("/WEB-INF/database/") + "/databaseDrivers.xml")); // validate the control xml file against the schema validator.validate(new StreamSource(new ByteArrayInputStream(xml.getBytes("UTF-8")))); // convert the xml string into JSON JSONObject jsonDatabaseDriverCollection = org.json.XML.toJSONObject(xml).getJSONObject("databaseDrivers"); // prepare the array we are going to popoulate JSONArray jsonDatabaseDrivers = new JSONArray(); JSONObject jsonDatabaseDriver; int index = 0; int count = 0; if (jsonDatabaseDriverCollection.optJSONArray("databaseDriver") == null) { jsonDatabaseDriver = jsonDatabaseDriverCollection.getJSONObject("databaseDriver"); } else { jsonDatabaseDriver = jsonDatabaseDriverCollection.getJSONArray("databaseDriver").getJSONObject(index); count = jsonDatabaseDriverCollection.getJSONArray("databaseDriver").length(); } do { _logger.info("Registering database driver " + jsonDatabaseDriver.getString("name") + " using " + jsonDatabaseDriver.getString("class")); try { // check this type does not already exist for (int i = 0; i < jsonDatabaseDrivers.length(); i++) { if (jsonDatabaseDriver.getString("name") .equals(jsonDatabaseDrivers.getJSONObject(i).getString("name"))) throw new Exception(" database driver type is loaded already. Type names must be unique"); } // get the class name String className = jsonDatabaseDriver.getString("class"); // get the current thread class loader (this should log better if there are any issues) ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); // check we got a class loader if (classLoader == null) { // register the class the old fashioned way so the DriverManager can find it Class.forName(className); } else { // register the class on this thread so we can catch any errors Class.forName(className, true, classLoader); } // add the jsonControl to our array jsonDatabaseDrivers.put(jsonDatabaseDriver); } catch (Exception ex) { _logger.error("Error registering database driver : " + ex.getMessage(), ex); } // inc the count of controls in this file index++; // get the next one if (index < count) jsonDatabaseDriver = jsonDatabaseDriverCollection.getJSONArray("databaseDriver") .getJSONObject(index); } while (index < count); // put the jsonControls in a context attribute (this is available via the getJsonActions method in RapidHttpServlet) servletContext.setAttribute("jsonDatabaseDrivers", jsonDatabaseDrivers); _logger.info(index + " database drivers loaded from databaseDrivers.xml file"); return index; }
From source file:org.apache.wookie.server.ContextListener.java
/** * Starts a watcher thread for hot-deploy of new widgets dropped into the deploy folder * this is controlled using the <code>widget.hot_deploy=true|false</code> property * and configured to look in the folder specified by the <code>widget.deployfolder</code> property * @param context the current servlet context * @param configuration the configuration properties *//*from ww w. j av a2s . c o m*/ private void startWatcher(ServletContext context, Configuration configuration, final Messages localizedMessages) { /* * Start watching for widget deployment */ final File deploy = new File(WidgetPackageUtils .convertPathToPlatform(context.getRealPath(configuration.getString("widget.deployfolder")))); final String UPLOADFOLDER = context.getRealPath(configuration.getString("widget.useruploadfolder")); final String WIDGETFOLDER = context.getRealPath(configuration.getString("widget.widgetfolder")); final String localWidgetFolderPath = configuration.getString("widget.widgetfolder"); final String[] locales = configuration.getStringArray("widget.locales"); final String contextPath = context.getContextPath(); Thread thr = new Thread() { public void run() { int interval = 5000; WgtWatcher watcher = new WgtWatcher(); watcher.setWatchDir(deploy); watcher.setListener(new WgtWatcher.FileChangeListener() { public void fileModified(File f) { // get persistence manager for this thread IPersistenceManager persistenceManager = PersistenceManagerFactory.getPersistenceManager(); try { persistenceManager.begin(); File upload = WidgetFileUtils.dealWithDroppedFile(UPLOADFOLDER, f); W3CWidgetFactory fac = new W3CWidgetFactory(); fac.setLocales(locales); fac.setLocalPath(contextPath + localWidgetFolderPath); fac.setOutputDirectory(WIDGETFOLDER); fac.setFeatures(persistenceManager.findServerFeatureNames()); fac.setStartPageProcessor(new StartPageProcessor()); W3CWidget model = fac.parse(upload); WidgetJavascriptSyntaxAnalyzer jsa = new WidgetJavascriptSyntaxAnalyzer( fac.getUnzippedWidgetDirectory()); if (persistenceManager.findWidgetByGuid(model.getIdentifier()) == null) { WidgetFactory.addNewWidget(model, true); String message = model.getLocalName("en") + "' - " + localizedMessages.getString("WidgetAdminServlet.19"); _logger.info(message); FlashMessage.getInstance().message(message); } else { String message = model.getLocalName("en") + "' - " + localizedMessages.getString("WidgetAdminServlet.20"); _logger.info(message); FlashMessage.getInstance().message(message); } persistenceManager.commit(); } catch (IOException e) { persistenceManager.rollback(); String error = f.getName() + ":" + localizedMessages.getString("WidgetHotDeploy.1"); FlashMessage.getInstance().error(error); _logger.error(error); } catch (BadWidgetZipFileException e) { persistenceManager.rollback(); String error = f.getName() + ":" + localizedMessages.getString("WidgetHotDeploy.2"); FlashMessage.getInstance().error(error); _logger.error(error); } catch (BadManifestException e) { persistenceManager.rollback(); String error = f.getName() + ":" + localizedMessages.getString("WidgetHotDeploy.3"); FlashMessage.getInstance().error(error); _logger.error(error); } catch (Exception e) { persistenceManager.rollback(); String error = f.getName() + ":" + e.getLocalizedMessage(); FlashMessage.getInstance().error(error); _logger.error(error); } finally { // close thread persistence manager PersistenceManagerFactory.closePersistenceManager(); } } public void fileRemoved(File f) { // Not implemented - the .wgt files are removed as part of the deployment process } }); try { while (true) { watcher.check(); Thread.sleep(interval); } } catch (InterruptedException iex) { } } }; thr.start(); }
From source file:org.iplantc.phyloviewer.viewer.server.ParseTreeService.java
@Override public void init() throws ServletException { ServletContext servletContext = this.getServletContext(); IImportTreeData treeImporter = (IImportTreeData) servletContext .getAttribute(Constants.IMPORT_TREE_DATA_KEY); ImportTreeLayout layoutImporter = (ImportTreeLayout) servletContext .getAttribute(Constants.IMPORT_TREE_LAYOUT_KEY); String path = servletContext.getInitParameter("treefile.path"); path = servletContext.getRealPath(path); parseTree = new ParseTree(treeImporter, layoutImporter); parseTree.setTreeBackupDir(path);/*ww w. jav a2 s .c om*/ Logger.getLogger("org.iplantc.phyloviewer").log(Level.INFO, "Setting parseTree file backup path to " + parseTree.getTreeBackupDir().getAbsolutePath()); }
From source file:controller.ClientController.java
@RequestMapping(value = "/facture", method = RequestMethod.POST) //public @ResponseBody String factureAction(HttpServletRequest request, HttpServletResponse response, HttpSession session, Model model) throws IOException { Client cli = (Client) session.getAttribute("UserConnected"); int idvideo = Integer.parseInt(request.getParameter("idvideo")); Facture facture = new Facture(); facture.Consulter(cli, vidBDD.VideoPrec(idvideo).get(0), request.getServletContext()); //if(request.getSession()){ //int test = Integer.parseInt(request.getParameter("select")) ; //request.setAttribute("Modify", this.modif.modifcontrat(id)); //}/* www.ja v a 2s. c o m*/ //session.setAttribute("Modify", this.modif.modifcontrat(id)); int BUFFER_SIZE = 4096; ServletContext context = request.getServletContext(); String appPath = context.getRealPath(""); System.out.println(appPath); try { File downloadFile = new File(appPath + "\\resources\\reports\\facture.pdf"); FileInputStream fis = new FileInputStream(downloadFile); // get MIME type of the file String mimeType = context.getMimeType(appPath + "\\resources\\reports\\facture.pdf"); if (mimeType == null) { // set to binary type if MIME mapping not found mimeType = "application/octet-stream"; } System.out.println("MIME type: " + mimeType); // set content attributes for the response response.setContentType(mimeType); response.setContentLength((int) downloadFile.length()); // set headers for the response String headerKey = "Content-Disposition"; String headerValue = String.format("attachment; filename=\"%s\"", downloadFile.getName()); response.setHeader(headerKey, headerValue); // get output stream of the response OutputStream outStream = response.getOutputStream(); byte[] buffer = new byte[BUFFER_SIZE]; int bytesRead = -1; // write bytes read from the input stream into the output stream while ((bytesRead = fis.read(buffer)) != -1) { outStream.write(buffer, 0, bytesRead); } fis.close(); outStream.close(); } catch (Exception ex) { ex.printStackTrace(); } return "/"; }
From source file:org.giavacms.base.controller.ResourceController.java
protected void setDimensions() { width = 0;/*from ww w.java 2s . c o m*/ height = 0; croppedImage = null; if (!ResourceType.IMAGE.equals(getElement().getResourceType())) { return; } ServletContext servletContext = (ServletContext) FacesContext.getCurrentInstance().getExternalContext() .getContext(); String folder = servletContext.getRealPath("") + File.separator; getElement().setBytes(FileUtils.getBytesFromFile( new File(new File(folder, ResourceType.IMAGE.getFolder()), getElement().getName()))); ImageIcon imageIcon = new ImageIcon(getElement().getBytes()); width = imageIcon.getIconWidth(); height = imageIcon.getIconHeight(); }
From source file:controller.ClientController.java
@RequestMapping(value = "/devis", method = RequestMethod.POST) //public @ResponseBody String devisAction(HttpServletRequest request, HttpServletResponse response, HttpSession session, Model model) throws IOException { Client cli = (Client) session.getAttribute("UserConnected"); int idvideo = Integer.parseInt(request.getParameter("idvideo")); Devis devis = new Devis(); devis.Consulter(cli, vidBDD.VideoPrec(idvideo).get(0), request.getServletContext()); //if(request.getSession()){ //int test = Integer.parseInt(request.getParameter("select")) ; //request.setAttribute("Modify", this.modif.modifcontrat(id)); //}//from w w w .j a v a 2s . c om //session.setAttribute("Modify", this.modif.modifcontrat(id)); // get your file as InputStream /** * Size of a byte buffer to read/write file */ int BUFFER_SIZE = 4096; ServletContext context = request.getServletContext(); String appPath = context.getRealPath(""); System.out.println(appPath); try { File downloadFile = new File(appPath + "\\resources\\reports\\devis.pdf"); FileInputStream fis = new FileInputStream(downloadFile); // get MIME type of the file String mimeType = context.getMimeType(appPath + "\\resources\\reports\\devis.pdf"); if (mimeType == null) { // set to binary type if MIME mapping not found mimeType = "application/octet-stream"; } System.out.println("MIME type: " + mimeType); // set content attributes for the response response.setContentType(mimeType); response.setContentLength((int) downloadFile.length()); // set headers for the response String headerKey = "Content-Disposition"; String headerValue = String.format("attachment; filename=\"%s\"", downloadFile.getName()); response.setHeader(headerKey, headerValue); // get output stream of the response OutputStream outStream = response.getOutputStream(); byte[] buffer = new byte[BUFFER_SIZE]; int bytesRead = -1; // write bytes read from the input stream into the output stream while ((bytesRead = fis.read(buffer)) != -1) { outStream.write(buffer, 0, bytesRead); } fis.close(); outStream.close(); } catch (Exception ex) { ex.printStackTrace(); } return "/"; }
From source file:edu.mum.cs545.recipebook.controller.MenuBean.java
public void saveImageFile(String fileName) { if (imageFile == null) { return;/*from ww w . j ava 2 s .c om*/ } try { ServletContext servletContext = (ServletContext) FacesContext.getCurrentInstance().getExternalContext() .getContext(); InputStream input = imageFile.getInputstream(); String newFileName = servletContext.getRealPath("") + File.separator + "resources" + File.separator + "images" + File.separator + fileName; File file = new File(newFileName); if (!file.exists()) { file.createNewFile(); } FileOutputStream output = new FileOutputStream(file, false); try { IOUtils.copy(input, output); } finally { IOUtils.closeQuietly(input); IOUtils.closeQuietly(output); } } catch (IOException ex) { Logger.getLogger(MenuBean.class.getName()).log(Level.SEVERE, null, ex); } finally { } }
From source file:com.ibm.util.merge.web.InitializeServlet.java
private void setup(String folder, ServletContext servletContext) { log.info("Setting up idmu folders"); ArrayList<String> folders = new ArrayList<String>(); folders.add("database"); folders.add("logs"); folders.add("output"); folders.add("packages"); folders.add("properties"); folders.add("templates"); folders.add("autoload"); for (String aFolder : folders) { File theSource = new File(servletContext.getRealPath("/WEB-INF" + File.separator + aFolder)); File theTarget = new File(folder + File.separator + aFolder); try {// www . j ava 2 s . c o m if (!theTarget.exists()) theTarget.mkdirs(); FileUtils.copyDirectory(theSource, theTarget); log.info("Copied files to " + theTarget.getAbsolutePath()); } catch (IOException e) { throw new RuntimeException("SETUP ERROR! - Unable to copy files from " + theSource + " to " + theTarget + ":" + e.getMessage()); } } }