Example usage for javax.servlet.http HttpServletRequest getServletContext

List of usage examples for javax.servlet.http HttpServletRequest getServletContext

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletRequest getServletContext.

Prototype

public ServletContext getServletContext();

Source Link

Document

Gets the servlet context to which this ServletRequest was last dispatched.

Usage

From source file:br.edu.ifpb.sislivros.model.ProcessadorFotos.java

public String processarFotoPerfil(HttpServletRequest request, Part fotoPart, String nameToSave)
        throws ServletException, IOException {

    if (fotoPart != null & nameToSave != null) {
        InputStream fileContent = fotoPart.getInputStream();
        String contextPath = request.getServletContext().getRealPath("/");

        if (salvarImagemCapa(contextPath + File.separator + folder, fileContent, nameToSave)) {
            return folder + "/" + nameToSave;
        }//  ww  w .j a v  a 2  s .  co  m
    }

    return null;
}

From source file:com.arcadian.loginservlet.CourseContentServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    if (request.getParameter("filename") != null) {
        String fileName = request.getParameter("filename");
        File file = new File(request.getServletContext().getAttribute("FILES_DIR") + File.separator + fileName);
        System.out.println("File location on server::" + file.getAbsolutePath());
        ServletContext ctx = getServletContext();
        InputStream fis = new FileInputStream(file);
        String mimeType = ctx.getMimeType(file.getAbsolutePath());
        System.out.println("mime type=" + mimeType);
        response.setContentType(mimeType != null ? mimeType : "application/octet-stream");
        response.setContentLength((int) file.length());
        response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");

        ServletOutputStream os = response.getOutputStream();
        byte[] bufferData = new byte[102400];
        int read = 0;
        while ((read = fis.read(bufferData)) != -1) {
            os.write(bufferData, 0, read);
        }/* w  ww  .j  a  va  2s. c o  m*/
        os.flush();
        os.close();
        fis.close();
        System.out.println("File downloaded at client successfully");
    }
    processRequest(request, response);
}

From source file:io.lavagna.web.api.ApplicationConfigurationController.java

@RequestMapping(value = "/api/check-https-config", method = RequestMethod.GET)
public List<String> checkHttpsConfiguration(HttpServletRequest req) {

    List<String> status = new ArrayList<>(2);

    Map<Key, String> configuration = configurationRepository
            .findConfigurationFor(of(Key.USE_HTTPS, Key.BASE_APPLICATION_URL));

    final boolean useHttps = "true".equals(configuration.get(Key.USE_HTTPS));
    if (req.getServletContext().getSessionCookieConfig().isSecure() != useHttps) {
        status.add("SessionCookieConfig is not aligned with settings. The application must be restarted.");
    }/* ww  w.j a va2s.c om*/

    final String baseApplicationUrl = configuration.get(Key.BASE_APPLICATION_URL);

    if (useHttps && !baseApplicationUrl.startsWith("https://")) {
        status.add(format(
                "The base application url %s does not begin with https:// . It's a mandatory requirement if you want to enable full https mode.",
                baseApplicationUrl));
    }

    return status;
}

From source file:com.apt.ajax.controller.AjaxUpload.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from   w  w w. j ava 2  s . c o  m*/
 *
 * @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("application/json");

    String uploadDir = request.getServletContext().getRealPath(File.separator) + "upload";
    Gson gson = new Gson();
    MessageBean messageBean = new MessageBean();
    try (PrintWriter out = response.getWriter()) {
        /* TODO output your page here. You may use following sample code. */
        File x = new File(uploadDir);
        if (!x.exists()) {
            x.mkdir();
        }
        boolean isMultiplePart = ServletFileUpload.isMultipartContent(request);

        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        if (!isMultiplePart) {

        } else {
            List items = null;

            try {
                items = upload.parseRequest(request);
                if (items != null) {
                    Iterator iterator = items.iterator();
                    String assignmentId = "";
                    String stuid = "";
                    while (iterator.hasNext()) {
                        FileItem item = (FileItem) iterator.next();
                        if (item.isFormField()) {
                            String fieldName = item.getFieldName();
                            if (fieldName.equals("assignmentid")) {
                                assignmentId = item.getString();
                                File c = new File(uploadDir + File.separator + assignmentId);
                                if (!c.exists()) {
                                    c.mkdir();
                                }
                                uploadDir = c.getPath();
                                if (request.getSession().getAttribute("studentId") != null) {
                                    stuid = request.getSession().getAttribute("studentId").toString();
                                    File stuDir = new File(uploadDir + File.separator + stuid);
                                    if (!stuDir.exists()) {
                                        stuDir.mkdir();
                                    }
                                    uploadDir = stuDir.getPath();
                                }
                            }
                        } else {
                            String itemname = item.getName();
                            if (itemname == null || itemname.equals("")) {
                            } else {
                                String filename = FilenameUtils.getName(itemname);
                                File f = new File(uploadDir + File.separator + filename);
                                String[] split = f.getPath().split(Pattern.quote(File.separator) + "upload"
                                        + Pattern.quote(File.separator));
                                String save = split[split.length - 1];
                                if (assignmentId != null && !assignmentId.equals("")) {
                                    if (stuid != null && !stuid.equals("")) {

                                    } else {
                                        Assignment assignment = new AssignmentFacade()
                                                .findAssignment(Integer.parseInt(assignmentId));
                                        assignment.setUrl(save);
                                        new AssignmentFacade().updateAssignment(assignment);
                                    }
                                }
                                item.write(f);
                                messageBean.setStatus(0);
                                messageBean.setMessage("File " + f.getName() + " sucessfuly uploaded");

                            }
                        }
                    }
                }

                gson.toJson(messageBean, out);
            } catch (Exception ex) {
                messageBean.setStatus(1);
                messageBean.setMessage(ex.getMessage());
                gson.toJson(messageBean, out);
            }

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

From source file:com.github.cxt.Myjersey.jerseycore.FileResource.java

@Path("download")
@GET//from  w  ww.j  ava  2s  .  c  o m
public Response downloadFile(@Context HttpServletRequest request) throws IOException {
    File file = new File(request.getServletContext().getRealPath("index.html"));
    String mt = new MimetypesFileTypeMap().getContentType(file);
    return Response.ok(file, mt).header("Content-disposition", "attachment;filename=" + file.getName())
            .header("ragma", "No-cache").header("Cache-Control", "no-cache").build();

}

From source file:net.swas.explorer.servlet.ms.GetMSConfig.java

/**
 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
 */// www .  j  a  v  a 2 s . c om
@SuppressWarnings("unchecked")
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    JSONObject messageJson = new JSONObject();

    messageJson.put("action", "readMSConfig");
    this.prod.send(messageJson.toJSONString());

    String revMsg = this.cons.getReceivedMessage(request.getServletContext());
    log.info("Received Message :" + revMsg);
    if (revMsg != null) {

        JSONParser parser = new JSONParser();
        JSONObject revJson = null;
        try {

            revJson = (JSONObject) parser.parse(revMsg);
            request.removeAttribute("msConfig");
            request.setAttribute("msConfig", revJson);

        } catch (ParseException e) {

            e.printStackTrace();

        }

    }

    RequestDispatcher rd = request.getRequestDispatcher("/msConfigForm.jsp");
    rd.forward(request, response);

}

From source file:com.github.cxt.Myjersey.jerseycore.FileResource.java

@Path("put/{path}")
@PUT//from  www .j a v  a2  s.  com
@Consumes(MediaType.APPLICATION_OCTET_STREAM)
@Produces(MediaType.APPLICATION_JSON)
public String putFile(InputStream inputStream, @PathParam("path") String name,
        @Context HttpServletRequest request) throws IOException {
    String path = request.getServletContext().getRealPath("/");
    path += File.separator + "data" + File.separator + name;
    File file = new File(path);
    try {
        FileUtils.copyInputStreamToFile(inputStream, file);
    } catch (IOException ex) {
        ex.printStackTrace();
        return "{\"success\": false}";
    }
    return "{\"success\": true}";
}

From source file:com.arcadian.loginservlet.StudentAssignmentServlet.java

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

    if (request.getParameter("filename") != null) {
        String fileName = request.getParameter("filename");
        File file = new File(request.getServletContext().getAttribute("FILES_DIR") + File.separator + fileName);
        System.out.println("File location on server::" + file.getAbsolutePath());
        ServletContext ctx = getServletContext();
        InputStream fis = new FileInputStream(file);
        String mimeType = ctx.getMimeType(file.getAbsolutePath());
        System.out.println("mime type=" + mimeType);
        response.setContentType(mimeType != null ? mimeType : "application/octet-stream");
        response.setContentLength((int) file.length());
        response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");

        ServletOutputStream os = response.getOutputStream();
        byte[] bufferData = new byte[102400];
        int read = 0;
        while ((read = fis.read(bufferData)) != -1) {
            os.write(bufferData, 0, read);
        }
        os.flush();
        os.close();
        fis.close();
        System.out.println("File downloaded at client successfully");
    }
    processRequest(request, response);
}

From source file:servlets.Handler.java

/**
 * /*from   w w w .  j  av a  2s  .c  o m*/
 * @param request
 * @return 
 */
private Response send_email(HttpServletRequest request) {

    UserDTO user = (UserDTO) request.getSession().getAttribute("user");
    if (user != null) {

        int maxFileSize = 5000 * 1024;
        int maxMemSize = 5000 * 1024;
        ServletContext context = request.getServletContext();
        String contentType = request.getContentType();
        if ((contentType.indexOf("multipart/form-data") >= 0)) {

            String email = "";
            String subject = "";
            try {
                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("c:\\temp"));

                ServletFileUpload upload = new ServletFileUpload(factory);
                upload.setSizeMax(maxFileSize);

                List fileItems = upload.parseRequest(request);
                FileItem fi = (FileItem) fileItems.get(0);
                ;

                subject = request.getParameter("subject");
                email = java.net.URLDecoder.decode(request.getParameter("email"), "UTF-8");
                //ARREGLAR ESTOOOOOOOOOOOOOOOOO
                return this.facade.sendEmail(user, subject, email, fi);

            } catch (FileUploadException ex) {
                ex.printStackTrace();
                return ResponseHelper.getResponse(-3, "No se pudo subir el archivo", null);
            } catch (UnsupportedEncodingException ex) {
                ex.printStackTrace();
                System.out.println("email:" + email);
                return ResponseHelper.getResponse(-3, "No se pudo parsear el email", null);
            } catch (Exception ex) {
                ex.printStackTrace();
                return ResponseHelper.getResponse(-3, "No se pudo escribir el archivo en el disco", null);
            }

        } else {
            return ResponseHelper.getResponse(-2, "Cabecera HTTP erronea", null);
        }
    }

    return ResponseHelper.getResponse(-2, "Login is required", null);
}

From source file:utils.GeradorDePDF.java

public void GeraPDF(HttpServletRequest request, HttpServletResponse response)
        throws AlertException, ErrorException {
    try {//w w  w.j  ava2  s  .c  o m
        session = request.getSession();
        int idProjeto = Integer.parseInt("" + (String) session.getAttribute("idProjeto"));
        ProjetoModel modelProj = new ProjetoModel();
        String caminho = request.getServletContext().getRealPath("") + "\\casos_de_uso\\"
                + modelProj.buscar(request).get(0).getImagem();

        String jasper = (request.getContextPath() + "/view/relatorio/teste.jasper");
        String host = "http://" + request.getServerName() + ":" + request.getServerPort();
        URL jasperUrl = new URL(host + jasper);

        HashedMap params = new HashedMap();

        BufferedImage image = ImageIO.read(new FileInputStream(caminho));

        // tem que ser maiusculo o parametro, porque la no xml do ireport eh maiusculo tambem
        params.put("IMAGEM", image);
        params.put("idProjeto", idProjeto);

        byte[] bytes = JasperRunManager.runReportToPdf(jasperUrl.openStream(), params, super.conn);
        if (bytes != null) {
            response.setContentType("application/pdf");
            OutputStream ops = null;
            ops = response.getOutputStream();
            ops.write(bytes);
        }
    } catch (FilterCreationException ex) {
        throw new AlertException(ex.getMessage());
    } catch (Exception ex) {
        throw new ErrorException();
    }

}