Example usage for javax.servlet ServletContext getRealPath

List of usage examples for javax.servlet ServletContext getRealPath

Introduction

In this page you can find the example usage for javax.servlet ServletContext getRealPath.

Prototype

public String getRealPath(String path);

Source Link

Document

Gets the real path corresponding to the given virtual path.

Usage

From source file:com.almende.eve.deploy.EveListener.java

@Override
public void contextInitialized(ServletContextEvent sce) {
    final ServletContext sc = sce.getServletContext();

    // Get the eve.yaml file:
    String path = sc.getInitParameter("eve_config");
    if (path != null && !path.isEmpty()) {
        final String fullname = "/WEB-INF/" + path;
        LOG.info("loading configuration file '" + sc.getRealPath(fullname) + "'...");
        final InputStream is = sc.getResourceAsStream(fullname);
        if (is == null) {
            LOG.warning("Can't find the given configuration file:" + sc.getRealPath(fullname));
            return;
        }/*from w  w w . j a  v  a  2  s . c  o  m*/

        myConfig = Boot.boot(is);
    }

}

From source file:org.nyu.edu.dlts.server.SchematronServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from w  w w.  jav  a  2s  .c om
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();

    // Create a factory for disk-based file items
    DiskFileItemFactory factory = new DiskFileItemFactory();

    // Configure a repository (to ensure a secure temp location is used)
    ServletContext servletContext = this.getServletConfig().getServletContext();

    String schematronFilename = servletContext.getRealPath("/schematrons/ArchivesSpace-EAD-validator.sch");
    schematronFile = new File(schematronFilename);

    File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir");
    factory.setRepository(repository);

    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload(factory);
    try {
        // Parse the request
        List<FileItem> items = upload.parseRequest(request);
        Iterator<FileItem> iter = items.iterator();
        File[] uploadedFiles = new File[4];
        String format = null;

        int fileIndex = 0;
        while (iter.hasNext()) {
            FileItem item = iter.next();

            if (item.isFormField()) {
                format = item.getString();
            } else {
                String fieldName = item.getFieldName();
                String fileName = item.getName();

                if (!fileName.trim().isEmpty()) {
                    uploadedFiles[fileIndex] = new File(repository, fileName);
                    item.write(uploadedFiles[fileIndex]);
                }

                fileIndex++;
            }
        }

        // if we have files the process them
        if (uploadedFiles[0] != null && format != null) {
            String results = "";

            for (int i = 0; i < uploadedFiles.length; i++) {
                File file = uploadedFiles[i];
                if (file != null) {
                    results += validateUsingSchematron(format, file);
                }
            }

            out.println(results);
        } else {
            out.println("<!DOCTYPE html>");
            out.println("<html>");
            out.println("<head>");
            out.println("<title>SchematronServlet Error</title>");
            out.println("</head>");
            out.println("<body>");
            out.println("<h1>Error, missing upload file ...</h1>");
            out.println("</body>");
            out.println("</html>");
        }
    } catch (FileUploadException ex) {
        Logger.getLogger(SchematronServlet.class.getName()).log(Level.SEVERE, null, ex);
    } catch (Exception ex) {
        Logger.getLogger(SchematronServlet.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        out.close();
    }
}

From source file:org.jahia.bin.Export.java

@Override
public void setServletContext(ServletContext servletContext) {
    cleanupXsl = servletContext.getRealPath("/WEB-INF/etc/repository/export/" + "cleanup.xsl");
    templatesCleanupXsl = servletContext
            .getRealPath("/WEB-INF/etc/repository/export/" + "templatesCleanup.xsl");
}

From source file:com.elearing.admin.DescriptiveQuesWithImage.java

public void upload() {

    if (file != null) {
        try {//from   ww w .  java  2  s  .  c  o m

            FacesContext context = FacesContext.getCurrentInstance();
            ServletContext servletContext = (ServletContext) context.getExternalContext().getContext();
            String bdpath = servletContext.getRealPath("/");
            String webcut = bdpath.substring(0, bdpath.lastIndexOf("\\"));
            String buildcut = webcut.substring(0, webcut.lastIndexOf("\\"));
            String mainUrlPath = buildcut.substring(0, buildcut.lastIndexOf("\\"));

            //this code for web main logic cut            
            //HttpServletRequest request = (HttpServletRequest)context.getExternalContext().getRequest();
            //String requestURL = request.getRequestURL().toString();
            //String url = requestURL.substring(0, requestURL.lastIndexOf("/"));      
            //get content
            InputStream inputStr = file.getInputstream();
            imagePath = mainUrlPath + "\\web\\resources\\image\\userImage\\" + file.getFileName();
            //upload file copy to project folder
            File destFile = new File(imagePath);
            if (!destFile.exists()) {
                FileUtils.copyInputStreamToFile(inputStr, destFile);
            }
            imageName = file.getFileName();
            System.out.println(imageName);
        } catch (Exception ex) {
            Logger.getLogger(DescriptiveQuesWithImage.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

From source file:edu.stanford.epad.epadws.listener.StartupListener.java

public void contextInitialized(ServletContextEvent event) {
    // Skip, if we are using same APP
    if (!Main.separateWebServicesApp)
        return;//from   w  w w  .  j  ava 2s  . c om
    log.info("#####################################################");
    log.info("############# Starting ePAD Web Service #############");
    log.info("#####################################################");

    // call Spring's context ContextLoaderListener to initialize
    // all the context files specified in web.xml
    super.contextInitialized(event);

    ServletContext servletContext = event.getServletContext();
    appContext = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);
    webAppPath = servletContext.getRealPath("/");
    try {
        URL url = servletContext.getResource("/");
        webAppURL = "http:/" + url.getPath(); // Does not look correct
        System.out.println("Context initialized , webAppUrl=" + webAppURL + " webappPath=" + webAppPath);
    } catch (Exception x) {
    }
    Main.checkPropertiesFile();
    Main.checkResourcesFolders();
    Main.checkPluginsFile();
    RemotePACService.checkPropertiesFile();
    Main.initializePlugins();
    Main.startSupportThreads();
    Main.loadPluginClasses();
    new ServerStatusHandler(); // Sets startup time
}

From source file:org.accada.epcis.repository.capture.CaptureOperationsServlet.java

/**
 * Loads the application properties and populates a java.util.Properties
 * instance.//from   ww w.j  a v a  2  s .c o  m
 * 
 * @param servletConfig
 *            The ServletConfig used to locate the application property
 *            file.
 * @return The application properties.
 */
private Properties loadApplicationProperties(ServletConfig servletConfig) {
    // read application properties from servlet context
    ServletContext ctx = servletConfig.getServletContext();
    String path = ctx.getRealPath("/");
    String appConfigFile = ctx.getInitParameter(APP_CONFIG_LOCATION);
    Properties properties = new Properties();
    try {
        InputStream is = new FileInputStream(path + appConfigFile);
        properties.load(is);
        is.close();
        LOG.info("Loaded application properties from " + path + appConfigFile);
    } catch (IOException e) {
        LOG.error("Unable to load application properties from " + path + appConfigFile, e);
    }
    return properties;
}

From source file:org.geowebcache.diskquota.ConfigLoaderTest.java

@Override
protected void setUp() throws Exception {
    cacheDir = new File("target" + File.separator + getClass().getSimpleName());
    if (!cacheDir.getParentFile().exists()) {
        throw new IllegalStateException(cacheDir.getParentFile().getAbsolutePath() + " does not exist");
    }//from  ww  w  . j a v  a  2 s  .co m
    FileUtils.rmFileCacheDir(cacheDir, null);
    cacheDir.mkdirs();
    // copy configuration file to cache directory
    {
        InputStream in = getClass().getResourceAsStream("/geowebcache-diskquota.xml");
        FileOutputStream out = new FileOutputStream(new File(cacheDir, "geowebcache-diskquota.xml"));
        int c;
        while ((c = in.read()) != -1) {
            out.write(c);
        }
        in.close();
        out.close();
    }
    storageFinder = EasyMock.createMock(DefaultStorageFinder.class);
    EasyMock.expect(storageFinder.getDefaultPath()).andReturn(cacheDir.getAbsolutePath()).anyTimes();
    EasyMock.replay(storageFinder);

    ServletContext mockServletCtx = EasyMock.createMock(ServletContext.class);
    String tmpPath = System.getProperty("java.io.tmpdir");
    EasyMock.expect(mockServletCtx.getRealPath(EasyMock.eq(""))).andReturn(tmpPath).anyTimes();
    EasyMock.replay(mockServletCtx);

    WebApplicationContext appContext = EasyMock.createMock(WebApplicationContext.class);
    EasyMock.expect(appContext.getServletContext()).andReturn(mockServletCtx).anyTimes();
    EasyMock.replay(appContext);

    contextProvider = new ApplicationContextProvider();
    contextProvider.setApplicationContext(appContext);

    tld = EasyMock.createMock(TileLayerDispatcher.class);
    TileLayer toppStates = createMockLayer("topp:states");
    TileLayer raster = createMockLayer("raster test layer");
    EasyMock.expect(tld.getTileLayer(EasyMock.eq("topp:states"))).andReturn(toppStates).anyTimes();
    EasyMock.expect(tld.getTileLayer(EasyMock.eq("raster test layer"))).andReturn(raster).anyTimes();

    List<TileLayer> tileLayers = new ArrayList<TileLayer>();
    tileLayers.add(toppStates);
    tileLayers.add(raster);
    EasyMock.expect(tld.getLayerList()).andReturn(tileLayers).anyTimes();
    EasyMock.replay(tld);

    loader = new ConfigLoader(storageFinder, contextProvider, tld);
}

From source file:org.pentaho.platform.web.http.context.SolutionContextListener.java

/**
 * Provide a simple extension point for someone to be able to override the behavior of the WebApplicationContext. To
 * extend or change behavior, you will need to extend WebApplicationContext, and extend SolutionContextListener to
 * override the createWebApplicationContext method. The subclassing is currently required because the initialization
 * code above makes a specific setProperties call on the returned ApplicationContext method by casting it to a
 * WebApplicationContext.//from w w  w . j a va 2  s .c o  m
 * <p/>
 * Tangible example where this would be needed - context.getRealPath("") doesn't work the same way on all platforms.
 * In some cases, you need to pass in a null, not an empty string. For other servers that don't unpack the war, the
 * realPath call may need to be replaced with a parameter defined in the web.xml
 *
 * @param fullyQualifiedServerUrl
 * @param context
 * @return
 */
protected WebApplicationContext createWebApplicationContext(String fullyQualifiedServerUrl,
        ServletContext context) {
    return new WebApplicationContext(SolutionContextListener.solutionPath, fullyQualifiedServerUrl,
            context.getRealPath(""), context); //$NON-NLS-1$
}

From source file:com.hzc.framework.ssh.controller.WebUtil.java

/**
 * +?????//from w  ww  . j a  v  a 2  s . co  m
 *
 * @param path
 * @param c
 * @param ufc
 * @param <T>
 * @return
 * @throws Exception
 */
public static <T> T upload(String path, Class<T> c, UploadFileCall ufc) throws RuntimeException {
    try {
        HttpServletRequest request = getReq();

        ServletContext servletContext = getServletContext();
        File file = new File(servletContext.getRealPath(path));
        if (!file.exists())
            file.mkdir();

        MultipartRequest multi = new MultipartRequest(request, file.getAbsolutePath(), 1024 * 1024 * 1024,
                "UTF-8", new DefaultFileRenamePolicy());
        Enumeration params = multi.getParameterNames();
        T obj = c.newInstance();
        Field[] declaredFields = c.getDeclaredFields();

        // ??,??
        labelNext: while (params.hasMoreElements()) {
            String name = (String) params.nextElement();
            for (Field field : declaredFields) {
                field.setAccessible(true);
                String fieldName = field.getName();
                if (name.equals(fieldName)) {
                    String value = multi.getParameter(name);
                    if (null == value) {
                        continue;
                    }
                    Class<?> type = field.getType();
                    if (type == Long.class) {
                        field.set(obj, Long.parseLong(value));
                    } else if (type == String.class) {
                        field.set(obj, value);
                    } else if (type == Byte.class) {
                        field.set(obj, Byte.parseByte(value));
                    } else if (type == Integer.class) {
                        field.set(obj, Integer.parseInt(value));
                    } else if (type == Character.class) {
                        field.set(obj, value.charAt(0));
                    } else if (type == Boolean.class) {
                        field.set(obj, Boolean.parseBoolean(value));
                    } else if (type == Double.class) {
                        field.set(obj, Double.parseDouble(value));
                    } else if (type == Float.class) {
                        field.set(obj, Float.parseFloat(value));
                    }
                    continue labelNext;
                }
            }
        }
        ufc.form(obj, multi);
        Enumeration files = multi.getFileNames();
        while (files.hasMoreElements()) {
            String name = (String) files.nextElement();
            String filename = multi.getFilesystemName(name);
            String originalFilename = multi.getOriginalFileName(name);
            String type = multi.getContentType(name);
            File f = multi.getFile(name);
            ufc.file(obj, f, filename, originalFilename, type);
        }
        return obj;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:com.elearing.admin.DescriptiveCRUD.java

public void upload() {

        if (file != null) {
            try {

                FacesContext context = FacesContext.getCurrentInstance();
                ServletContext servletContext = (ServletContext) context.getExternalContext().getContext();
                String bdpath = servletContext.getRealPath("/");
                String webcut = bdpath.substring(0, bdpath.lastIndexOf("\\"));
                String buildcut = webcut.substring(0, webcut.lastIndexOf("\\"));
                String mainUrlPath = buildcut.substring(0, buildcut.lastIndexOf("\\"));

                //this code for web main logic cut            
                //HttpServletRequest request = (HttpServletRequest)context.getExternalContext().getRequest();
                //String requestURL = request.getRequestURL().toString();
                //String url = requestURL.substring(0, requestURL.lastIndexOf("/"));      
                //get content
                InputStream inputStr = file.getInputstream();
                imagePath = mainUrlPath + "\\web\\resources\\image\\descriptiveImage\\" + file.getFileName();
                //upload file copy to project folder
                File destFile = new File(imagePath);
                if (!destFile.exists()) {
                    FileUtils.copyInputStreamToFile(inputStr, destFile);
                }//  w w w .  ja  v  a  2s  . c  o m
                imageName = file.getFileName();
                System.out.println(imageName);
            } catch (Exception ex) {
                Logger.getLogger(DescriptiveCRUD.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }