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:ostepu.cconfig.help.java

/**
 * der Aufruf des help-Befehls/*from  www  . ja  va2s .  c  om*/
 *
 * @param context  der Kontext des Servlet
 * @param request  die eingehende Anfrage
 * @param response das Antwortobjekt
 */
public static void request(ServletContext context, HttpServletRequest request, HttpServletResponse response) {
    String pathInfo = request.getPathInfo();

    if (pathInfo == null) {
        try {
            response.sendError(404);
        } catch (IOException ex) {
            Logger.getLogger(help.class.getName()).log(Level.SEVERE, null, ex);
            response.setStatus(500);
        }
        return;
    }

    if (!"GET".equals(request.getMethod())) {
        try {
            response.sendError(404);
        } catch (IOException ex) {
            Logger.getLogger(help.class.getName()).log(Level.SEVERE, null, ex);
            response.setStatus(500);
        }
        return;
    }

    ServletOutputStream out;
    try {
        out = response.getOutputStream();
    } catch (IOException ex) {
        Logger.getLogger(help.class.getName()).log(Level.SEVERE, null, ex);
        response.setStatus(500);
        return;
    }

    String[] helpPath = pathInfo.split("/");
    String extension = FilenameUtils.getExtension(pathInfo);
    String language = helpPath[1];
    helpPath[helpPath.length - 1] = helpPath[helpPath.length - 1].substring(0,
            helpPath[helpPath.length - 1].length() - extension.length() - 1);
    helpPath = Arrays.copyOfRange(helpPath, 2, helpPath.length);

    Path helpFile = Paths.get(
            context.getRealPath("/data/help/" + String.join("_", helpPath) + "_" + language + "." + extension));

    try {
        if (Files.exists(helpFile)) {
            InputStream inp = new FileInputStream(helpFile.toFile());
            byte[] res = IOUtils.toByteArray(inp);
            inp.close();
            out.write(res);
            response.setStatus(200);
            response.setHeader("Content-Type", "charset=utf-8");
        } else {
            response.sendError(404);
        }
    } catch (IOException ex) {
        Logger.getLogger(help.class.getName()).log(Level.SEVERE, null, ex);
        response.setStatus(500);
    } finally {
        try {
            out.close();
        } catch (IOException ex) {
            Logger.getLogger(help.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

From source file:info.magnolia.init.DefaultMagnoliaInitPaths.java

/**
 * Figures out the root path where the webapp is deployed.
 *///from  w w  w  .  j  a va  2s  .  com
protected String determineRootPath(ServletContext context) {
    final String retroCompatMethodCall = magnoliaServletContextListener.initRootPath(context);
    if (retroCompatMethodCall != null) {
        DeprecationUtil.isDeprecated(
                "You should update your code and override determineRootPath(ServletContext) instead of initRootPath(ServletContext)");
        return retroCompatMethodCall;
    }

    String realPath = StringUtils.replace(context.getRealPath(StringUtils.EMPTY), "\\", "/");
    realPath = StringUtils.removeEnd(realPath, "/");
    if (realPath == null) {
        // don't use new java.io.File("x").getParentFile().getAbsolutePath() to find out real directory, could throw
        // a NPE for unexpanded war
        throw new RuntimeException(
                "Magnolia is not configured properly and therefore unable to start: real path can't be obtained [ctx real path:"
                        + context.getRealPath(StringUtils.EMPTY)
                        + "]. Please refer to the Magnolia documentation for installation instructions specific to your environment.");
    }
    return realPath;
}

From source file:com.cyclopsgroup.waterview.jsp.JspEngine.java

/**
 * @param path Absolute JSP path/*from   w ww.  j  av  a2  s .  c  om*/
 * @param data Runtime data
 * @param viewContext View context
 * @throws Exception Throw it out
 */
public void renderJsp(String path, RuntimeData data, Context viewContext) throws Exception {
    HttpServletRequest request = (HttpServletRequest) data.getRequestContext().get("request");
    HttpServletResponse response = (HttpServletResponse) data.getRequestContext().get("response");
    ServletContext servletContext = (ServletContext) data.getRequestContext().get("servletContext");
    if (request == null || response == null || servletContext == null) {
        data.getOutput().println("Jsp " + path + " is not rendered correctly with request " + request
                + ", response " + response + ", context " + servletContext);
    }
    request.setAttribute("viewContext", viewContext);
    RequestDispatcher dispatcher = servletContext.getRequestDispatcher(path);
    File jspFile = new File(servletContext.getRealPath(path));
    if (dispatcher == null || !jspFile.isFile()) {
        data.getOutput().println("Jsp " + path + " doesn't exist");
    } else {
        dispatcher.include(request, response);
        response.getWriter().flush();
    }
    request.removeAttribute("viewContext");
}

From source file:org.apache.cocoon.components.axis.SoapServerImpl.java

/**
 * Place the Request message in the MessagContext object - notice
 * that we just leave it as a 'ServletRequest' object and let the
 * Message processing routine convert it - we don't do it since we
 * don't know how it's going to be used - perhaps it might not
 * even need to be parsed.//  w  ww.j  av  a2  s  . c  o  m
 */
public MessageContext createMessageContext(HttpServletRequest req, HttpServletResponse res,
        ServletContext con) {

    MessageContext msgContext = new MessageContext(m_axisServer);
    String webInfPath = con.getRealPath("/WEB-INF");
    String homeDir = con.getRealPath("/");

    // Set the Transport
    msgContext.setTransportName(m_transportName);

    // Add Avalon specifics to MessageContext
    msgContext.setProperty(LOGGER, getLogger());
    msgContext.setProperty(AvalonProvider.COMPONENT_MANAGER, this.manager);

    // Save some HTTP specific info in the bag in case someone needs it
    msgContext.setProperty(Constants.MC_JWS_CLASSDIR, m_jwsClassDir);
    msgContext.setProperty(Constants.MC_HOME_DIR, homeDir);
    msgContext.setProperty(Constants.MC_RELATIVE_PATH, req.getServletPath());
    msgContext.setProperty(HTTPConstants.MC_HTTP_SERVLET, this);
    msgContext.setProperty(HTTPConstants.MC_HTTP_SERVLETREQUEST, req);
    msgContext.setProperty(HTTPConstants.MC_HTTP_SERVLETRESPONSE, res);
    msgContext.setProperty(HTTPConstants.MC_HTTP_SERVLETLOCATION, webInfPath);
    msgContext.setProperty(HTTPConstants.MC_HTTP_SERVLETPATHINFO, req.getPathInfo());
    msgContext.setProperty(HTTPConstants.HEADER_AUTHORIZATION,
            req.getHeader(HTTPConstants.HEADER_AUTHORIZATION));
    msgContext.setProperty(Constants.MC_REMOTE_ADDR, req.getRemoteAddr());

    // Set up a javax.xml.rpc.server.ServletEndpointContext
    ServletEndpointContextImpl sec = new ServletEndpointContextImpl();
    msgContext.setProperty(Constants.MC_SERVLET_ENDPOINT_CONTEXT, sec);

    // Save the real path
    String realpath = con.getRealPath(req.getServletPath());

    if (realpath != null) {
        msgContext.setProperty(Constants.MC_REALPATH, realpath);
    }

    msgContext.setProperty(Constants.MC_CONFIGPATH, webInfPath);

    if (m_securityProvider != null) {
        msgContext.setProperty("securityProvider", m_securityProvider);
    }

    // write out the contents of the message context for debugging purposes
    if (getLogger().isDebugEnabled()) {
        debugMessageContext(msgContext);
    }

    return msgContext;
}

From source file:edu.pitt.servlets.processAddMedia.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request/*ww w  . j a v a 2  s .c  om*/
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    HttpSession session = request.getSession();
    String userID = (String) session.getAttribute("userID");

    String error = "select correct format ";
    session.setAttribute("error", error);

    response.setContentType("text/html;charset=UTF-8");
    try (PrintWriter out = response.getWriter()) {
        // Process only if its multipart content
        // Create a factory for disk-based file items
        File file;
        // We might need to play with the file sizes
        int maxFileSize = 50000 * 1024;
        int maxMemSize = 50000 * 1024;
        ServletContext context = this.getServletContext();
        // Note that this file path refers to a virtual path
        // relative to this servlet.  The uploads directory
        // is part of this project.  The physical path varies 
        // from the virtual path

        String filePath = context.getRealPath("/uploads") + "/";
        out.println("Physical folder is located at: " + filePath + "<br />");

        // Verify the content type
        String contentType = request.getContentType();
        // This is very important - make sure that the web form that 
        // uploads the file is actually set to enctype="multipart/form-data"
        // An example of upload form for this project is in index.html
        if ((contentType.indexOf("multipart/form-data") >= 0)) {

            DiskFileItemFactory factory = new DiskFileItemFactory();
            // maximum size that will be stored in memory
            factory.setSizeThreshold(maxMemSize);
            // Location to save data that is larger than maxMemSize.
            factory.setRepository(new File(filePath));

            // Create a new file upload handler
            ServletFileUpload upload = new ServletFileUpload(factory);
            // maximum file size to be uploaded.
            upload.setSizeMax(maxFileSize);
            try {
                // Parse the request to get file items.
                List fileItems = upload.parseRequest(request);

                // Process the uploaded file items
                Iterator i = fileItems.iterator();
                while (i.hasNext()) {
                    FileItem fi = (FileItem) i.next();
                    if (!fi.isFormField()) {
                        // Get the uploaded file parameters
                        String fieldName = fi.getFieldName();

                        out.println("field name" + fieldName);
                        String fileName = fi.getName();

                        out.println("file name" + fileName); // file name is present

                        boolean isInMemory = fi.isInMemory();
                        long sizeInBytes = fi.getSize();
                        //  out.println("file size"+ sizeInBytes);
                        // Write the file
                        if (fileName.lastIndexOf("\\") >= 0) {
                            file = new File(filePath + fileName.substring(fileName.lastIndexOf("\\")));
                        } else {
                            file = new File(filePath + fileName.substring(fileName.lastIndexOf("\\") + 1));
                        }
                        fi.write(file);
                        //  out.println("Uploaded Filename: " + filePath  + fileName + "<br />");
                        String savepath = filePath + fileName;

                        // to check correct format is entered or not 
                        int dotindex = fileName.indexOf(".");
                        if (!(fileName.substring(dotindex).matches(".ogv|.webm|.mp4|.png|.jpeg|.jpg|.gif"))) {
                            response.sendRedirect("./pages/addMedia.jsp");

                        }

                        // receives projectID from listProjects.jsp from edit href link , adding in existing project 
                        // corresponding constructor is used          
                        if (session.getAttribute("projectID") != null) {
                            Integer projectID = (Integer) session.getAttribute("projectID");

                            media = new Media(projectID, fileName);
                        }
                        // first time when user enters media for project , this constructor is used          
                        else {
                            media = new Media(userID, fileName);
                        }

                        System.out.println("Into the media constructor");
                        // redirected to listProject
                        response.sendRedirect("./pages/listProject.jsp");

                        // media constructor

                        // response.redirect(listprojects.jsp);

                        processRequest(request, response);
                    }

                }

            }

            catch (FileUploadException ex) {
                Logger.getLogger(processAddMedia.class.getName()).log(Level.SEVERE, null, ex);
            } catch (Exception ex) {
                Logger.getLogger(processAddMedia.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
}

From source file:org.jboss.bpm.report.ReportFacade.java

@POST
@Path("render/{fileName}")
@Produces("text/html")
public Response renderReportHtml(@PathParam("fileName") String fileName, @Context HttpServletRequest request,
        @Context ServletContext servletContext) {

    assertBirtAvailability();// w w w .  ja  va 2s  .  c  om

    try {
        RenderMetaData renderMeta = defaultRenderMetaData(fileName, request);
        Map<String, String> postParams = convertRequestParametersToMap(request);
        renderMeta.getParameters().putAll(postParams);

        String outputFileName = birtService.render(renderMeta);
        String absoluteFile = servletContext.getRealPath(
                "/WEB-INF" + birtService.getIntegrationConfig().getOutputDir()) + "/" + outputFileName;
        log.debug("Render " + absoluteFile);

        return Response.ok().type("text/html").build();
    } catch (Throwable e1) {
        return gracefulException(e1);
    }
}

From source file:Bean.CAT.ModifTestBean.java

public List<TerminoLamina>[] deserializarNuevosTermAsocDiccGlobal()
        throws FileNotFoundException, IOException, ClassNotFoundException {

    List<TerminoLamina>[] term;

    ServletContext servletContext = (ServletContext) FacesContext.getCurrentInstance().getExternalContext()
            .getContext();// w w w .ja  va2  s  .  com
    String realPath = (String) servletContext.getRealPath("/"); // Sustituye "/" por el directorio ej: "/upload"

    //recuperar los terminos // setearle el rut del examinado para obtenerlo
    ObjectInputStream entrada = new ObjectInputStream(
            new FileInputStream(realPath + "/Terminos/NuevosTermAsocDiccGlobal.obj"));
    term = (List<TerminoLamina>[]) entrada.readObject();

    return term;
}

From source file:Bean.CAT.ModifTestBean.java

public List<TerminoLamina>[] deserializarlistNuevosTermDiccGlobal()
        throws FileNotFoundException, IOException, ClassNotFoundException {

    List<TerminoLamina>[] term;

    ServletContext servletContext = (ServletContext) FacesContext.getCurrentInstance().getExternalContext()
            .getContext();/*  www.j a va  2 s .c o m*/
    String realPath = (String) servletContext.getRealPath("/"); // Sustituye "/" por el directorio ej: "/upload"

    //recuperar los terminos // setearle el rut del examinado para obtenerlo
    ObjectInputStream entrada = new ObjectInputStream(
            new FileInputStream(realPath + "/Terminos/NuevosTermDiccGlobal.obj"));
    term = (List<TerminoLamina>[]) entrada.readObject();

    return term;
}

From source file:Bean.CAT.ModifTestBean.java

public void serializarListasCambiosDiccionario() throws FileNotFoundException, IOException {
    System.out.println(" entrando a serializar listas cambios diccionario");
    //serializacin
    ServletContext servletContext = (ServletContext) FacesContext.getCurrentInstance().getExternalContext()
            .getContext();/*from   w  w  w.j a  va  2 s. c o  m*/
    String realPath = (String) servletContext.getRealPath("/"); // Sustituye "/" por el directorio ej: "/upload"

    //serializacin
    try (ObjectOutputStream salida = new ObjectOutputStream(
            new FileOutputStream(realPath + "/Terminos/NuevosTermAsocDiccGlobal.obj"))) {
        salida.writeObject(listNuevosTermAsocDiccGlobal);
        // RecuperacionInformacion.setListaTerminosLaminas2(term);
        System.out.println(" se serializ lista de  nuevos terminos asoc Global");

    }

    try (ObjectOutputStream salida = new ObjectOutputStream(
            new FileOutputStream(realPath + "/Terminos/NuevosTermDiccGlobal.obj"))) {
        salida.writeObject(listNuevosTermDiccGlobal);
        // RecuperacionInformacion.setListaTerminosLaminas2(term);
        System.out.println(" se serializ nuevos terminos global dicc");

    }
    System.out.println(" saliendo serializar listas cambios diccionario");
}

From source file:Bean.CAT.ModifTestBean.java

public void serializarListaTemp() throws FileNotFoundException, IOException {
    System.out.println(" entrando a serializar listas cambios diccionario");
    //serializacin
    ServletContext servletContext = (ServletContext) FacesContext.getCurrentInstance().getExternalContext()
            .getContext();//w  w  w  .j  a  v  a 2 s . com
    String realPath = (String) servletContext.getRealPath("/"); // Sustituye "/" por el directorio ej: "/upload"

    //serializacin
    try (ObjectOutputStream salida = new ObjectOutputStream(
            new FileOutputStream(realPath + "/Terminos/NuevosTermAsocDiccGlobal.obj"))) {
        salida.writeObject(listNuevosTermAsocDiccGlobalTemp);
        // RecuperacionInformacion.setListaTerminosLaminas2(term);
        System.out.println(" se serializ lista de  nuevos terminos asoc Global");

    }

    try (ObjectOutputStream salida = new ObjectOutputStream(
            new FileOutputStream(realPath + "/Terminos/NuevosTermDiccGlobal.obj"))) {
        salida.writeObject(listNuevosTermDiccGlobalTemp);
        // RecuperacionInformacion.setListaTerminosLaminas2(term);
        System.out.println(" se serializ nuevos terminos global dicc");

    }
    System.out.println(" saliendo serializar listas cambios diccionario");
}