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:org.apache.hadoop.gateway.dispatch.DefaultDispatch.java

protected HttpEntity createRequestEntity(HttpServletRequest request) throws IOException {

    String contentType = request.getContentType();
    int contentLength = request.getContentLength();
    InputStream contentStream = request.getInputStream();

    HttpEntity entity;//from w ww. jav  a 2  s.co  m
    if (contentType == null) {
        entity = new InputStreamEntity(contentStream, contentLength);
    } else {
        entity = new InputStreamEntity(contentStream, contentLength, ContentType.parse(contentType));
    }
    GatewayConfig config = (GatewayConfig) request.getServletContext()
            .getAttribute(GatewayConfig.GATEWAY_CONFIG_ATTRIBUTE);
    if (config != null && config.isHadoopKerberosSecured()) {
        //Check if delegation token is supplied in the request
        boolean delegationTokenPresent = false;
        String queryString = request.getQueryString();
        if (queryString != null) {
            delegationTokenPresent = queryString.startsWith("delegation=")
                    || queryString.contains("&delegation=");
        }
        if (replayBufferSize < 0) {
            replayBufferSize = config.getHttpServerRequestBuffer();
        }
        if (!delegationTokenPresent && replayBufferSize > 0) {
            entity = new PartiallyRepeatableHttpEntity(entity, replayBufferSize);
        }
    }

    return entity;
}

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

/**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
 *//*w  w w.  j a  v  a2s  . co m*/
@SuppressWarnings("unchecked")
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    String action = request.getParameter("action");
    String status = "", msg = "";

    PrintWriter out = response.getWriter();
    JSONObject respJson = new JSONObject();
    JSONObject messageJson = new JSONObject();

    response.setContentType("application/json");
    response.setCharacterEncoding("UTF-8");

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

    if (FormFieldValidator.isLogin(request.getSession())) {

        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);
                respJson = revJson;

            } catch (ParseException e) {

                status = "1";
                msg = "Unable to reach modsercurity service. Please try later";
                e.printStackTrace();

            }

        } else {

            status = "1";
            msg = "Unable to reach modsercurity service. Please try later";
            log.info("Message is not received......");

        }

        if (!status.equals("")) {

            respJson.put("status", status);
            respJson.put("message", msg);

        }
    } else {
        status = "2";
        msg = "User Session Expired";
        respJson.put("status", status);
        respJson.put("message", msg);
    }

    try {
        log.info("Sending Json : " + respJson.toString());
        out.print(respJson.toString());
    } finally {
        out.close();
    }

}

From source file:org.apache.nifi.web.ContentViewerController.java

/**
 * Gets the content and defers to registered viewers to generate the markup.
 *
 * @param request servlet request/*from w  w  w.  j  a  v a 2 s  .c o  m*/
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doGet(final HttpServletRequest request, final HttpServletResponse response)
        throws ServletException, IOException {
    // specify the charset in a response header
    response.addHeader("Content-Type", "text/html; charset=UTF-8");

    // get the content
    final ServletContext servletContext = request.getServletContext();
    final ContentAccess contentAccess = (ContentAccess) servletContext.getAttribute("nifi-content-access");

    final ContentRequestContext contentRequest;
    try {
        contentRequest = getContentRequest(request);
    } catch (final Exception e) {
        request.setAttribute("title", "Error");
        request.setAttribute("messages", "Unable to interpret content request.");

        // forward to the error page
        final ServletContext viewerContext = servletContext.getContext("/nifi");
        viewerContext.getRequestDispatcher("/message").forward(request, response);
        return;
    }

    if (contentRequest.getDataUri() == null) {
        request.setAttribute("title", "Error");
        request.setAttribute("messages", "The data reference must be specified.");

        // forward to the error page
        final ServletContext viewerContext = servletContext.getContext("/nifi");
        viewerContext.getRequestDispatcher("/message").forward(request, response);
        return;
    }

    // get the content
    final DownloadableContent downloadableContent;
    try {
        downloadableContent = contentAccess.getContent(contentRequest);
    } catch (final ResourceNotFoundException rnfe) {
        request.setAttribute("title", "Error");
        request.setAttribute("messages", "Unable to find the specified content");

        // forward to the error page
        final ServletContext viewerContext = servletContext.getContext("/nifi");
        viewerContext.getRequestDispatcher("/message").forward(request, response);
        return;
    } catch (final AccessDeniedException ade) {
        request.setAttribute("title", "Access Denied");
        request.setAttribute("messages",
                "Unable to approve access to the specified content: " + ade.getMessage());

        // forward to the error page
        final ServletContext viewerContext = servletContext.getContext("/nifi");
        viewerContext.getRequestDispatcher("/message").forward(request, response);
        return;
    } catch (final Exception e) {
        request.setAttribute("title", "Error");
        request.setAttribute("messages", "An unexpected error has occurred: " + e.getMessage());

        // forward to the error page
        final ServletContext viewerContext = servletContext.getContext("/nifi");
        viewerContext.getRequestDispatcher("/message").forward(request, response);
        return;
    }

    // determine how we want to view the data
    String mode = request.getParameter("mode");

    // if the name isn't set, use original
    if (mode == null) {
        mode = DisplayMode.Original.name();
    }

    // determine the display mode
    final DisplayMode displayMode;
    try {
        displayMode = DisplayMode.valueOf(mode);
    } catch (final IllegalArgumentException iae) {
        request.setAttribute("title", "Error");
        request.setAttribute("messages", "Invalid display mode: " + mode);

        // forward to the error page
        final ServletContext viewerContext = servletContext.getContext("/nifi");
        viewerContext.getRequestDispatcher("/message").forward(request, response);
        return;
    }

    // buffer the content to support resetting in case we need to detect the content type or char encoding
    try (final BufferedInputStream bis = new BufferedInputStream(downloadableContent.getContent());) {
        final String mimeType;
        final String normalizedMimeType;

        // when standalone and we don't know the type is null as we were able to directly access the content bypassing the rest endpoint,
        // when clustered and we don't know the type set to octet stream since the content was retrieved from the node's rest endpoint
        if (downloadableContent.getType() == null || StringUtils
                .startsWithIgnoreCase(downloadableContent.getType(), MediaType.OCTET_STREAM.toString())) {
            // attempt to detect the content stream if we don't know what it is ()
            final DefaultDetector detector = new DefaultDetector();

            // create the stream for tika to process, buffered to support reseting
            final TikaInputStream tikaStream = TikaInputStream.get(bis);

            // provide a hint based on the filename
            final Metadata metadata = new Metadata();
            metadata.set(Metadata.RESOURCE_NAME_KEY, downloadableContent.getFilename());

            // Get mime type
            final MediaType mediatype = detector.detect(tikaStream, metadata);
            mimeType = mediatype.toString();
        } else {
            mimeType = downloadableContent.getType();
        }

        // Extract only mime type and subtype from content type (anything after the first ; are parameters)
        // Lowercase so subsequent code does not need to implement case insensitivity
        normalizedMimeType = mimeType.split(";", 2)[0].toLowerCase();

        // add attributes needed for the header
        request.setAttribute("filename", downloadableContent.getFilename());
        request.setAttribute("contentType", mimeType);

        // generate the header
        request.getRequestDispatcher("/WEB-INF/jsp/header.jsp").include(request, response);

        // remove the attributes needed for the header
        request.removeAttribute("filename");
        request.removeAttribute("contentType");

        // generate the markup for the content based on the display mode
        if (DisplayMode.Hex.equals(displayMode)) {
            final byte[] buffer = new byte[BUFFER_LENGTH];
            final int read = StreamUtils.fillBuffer(bis, buffer, false);

            // trim the byte array if necessary
            byte[] bytes = buffer;
            if (read != buffer.length) {
                bytes = new byte[read];
                System.arraycopy(buffer, 0, bytes, 0, read);
            }

            // convert bytes into the base 64 bytes
            final String base64 = Base64.encodeBase64String(bytes);

            // defer to the jsp
            request.setAttribute("content", base64);
            request.getRequestDispatcher("/WEB-INF/jsp/hexview.jsp").include(request, response);
        } else {
            // lookup a viewer for the content
            final String contentViewerUri = servletContext.getInitParameter(normalizedMimeType);

            // handle no viewer for content type
            if (contentViewerUri == null) {
                request.getRequestDispatcher("/WEB-INF/jsp/no-viewer.jsp").include(request, response);
            } else {
                // create a request attribute for accessing the content
                request.setAttribute(ViewableContent.CONTENT_REQUEST_ATTRIBUTE, new ViewableContent() {
                    @Override
                    public InputStream getContentStream() {
                        return bis;
                    }

                    @Override
                    public String getContent() throws IOException {
                        // detect the charset
                        final CharsetDetector detector = new CharsetDetector();
                        detector.setText(bis);
                        detector.enableInputFilter(true);
                        final CharsetMatch match = detector.detect();

                        // ensure we were able to detect the charset
                        if (match == null) {
                            throw new IOException("Unable to detect character encoding.");
                        }

                        // convert the stream using the detected charset
                        return IOUtils.toString(bis, match.getName());
                    }

                    @Override
                    public ViewableContent.DisplayMode getDisplayMode() {
                        return displayMode;
                    }

                    @Override
                    public String getFileName() {
                        return downloadableContent.getFilename();
                    }

                    @Override
                    public String getContentType() {
                        return normalizedMimeType;
                    }

                    @Override
                    public String getRawContentType() {
                        return mimeType;
                    }
                });

                try {
                    // generate the content
                    final ServletContext viewerContext = servletContext.getContext(contentViewerUri);
                    viewerContext.getRequestDispatcher("/view-content").include(request, response);
                } catch (final Exception e) {
                    String message = e.getMessage() != null ? e.getMessage() : e.toString();
                    message = "Unable to generate view of data: " + message;

                    // log the error
                    logger.error(message);
                    if (logger.isDebugEnabled()) {
                        logger.error(StringUtils.EMPTY, e);
                    }

                    // populate the request attributes
                    request.setAttribute("title", "Error");
                    request.setAttribute("messages", message);

                    // forward to the error page
                    final ServletContext viewerContext = servletContext.getContext("/nifi");
                    viewerContext.getRequestDispatcher("/message").forward(request, response);
                    return;
                }

                // remove the request attribute
                request.removeAttribute(ViewableContent.CONTENT_REQUEST_ATTRIBUTE);
            }
        }

        // generate footer
        request.getRequestDispatcher("/WEB-INF/jsp/footer.jsp").include(request, response);
    }
}

From source file:org.codemine.smartgarden.controller.SmartGardenServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*w  ww  .j a v  a2  s .  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 {
    ObjectMapper mapper = new ObjectMapper();
    DateFormat dateFormat = new SimpleDateFormat("yyyy-MMM-dd HH:mm:ss");
    DateFormat chartDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    mapper.setDateFormat(chartDateFormat);
    mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    RequestResult requestResult = new RequestResult();
    SmartGardenService smartGardenService = (SmartGardenService) request.getServletContext()
            .getAttribute(SERVICE_KEY);
    String action = (String) request.getParameter("action");
    if (action.equalsIgnoreCase("get_image")) {
        String filename = (String) request.getParameter("filename");
        File imageFile = smartGardenService.getImage(filename);
        BufferedImage bufferedImage = ImageIO.read(imageFile);
        try (OutputStream outputStream = response.getOutputStream()) {
            ImageIO.write(bufferedImage, "jpg", outputStream);
        }
        return;
    }
    try {

        if (!StringUtils.isEmpty(action)) {
            if (action.equalsIgnoreCase("start_irrigation")) {
                logger.log(Level.INFO, "processRequest:start_irrigation");
                requestResult = new RequestResult<Integer>();
                Integer historyId = smartGardenService.startIrrigationAsync(this.getDataSource());
                requestResult.setSuccess(true);
                requestResult.setValue(historyId);
            }
            if (action.equalsIgnoreCase("get_irrigation_history")) {
                logger.log(Level.INFO, "processRequest:get_irrigation_history");
                List<IrrigationHistory> historyList = smartGardenService
                        .getIrrigationHistoryList(this.getDataSource(), 10);
                requestResult.setValue(historyList);
                requestResult.setSuccess(true);
            }

            if (action.equalsIgnoreCase("get_garden_status")) {
                logger.log(Level.INFO, "processRequest:get_garden_status");
                GardenStatus gardenStatus = smartGardenService.getGardenStatus(this.getDataSource());
                requestResult.setValue(gardenStatus);
                requestResult.setSuccess(true);
            }

            if (action.equalsIgnoreCase("stop_irrigation")) {
                logger.log(Level.INFO, "processRequest:stop_irrigation");

                String historyIdParam = request.getParameter("historyId");
                Integer historyId = null;
                if (!StringUtils.isEmpty(historyIdParam)) {
                    historyId = Integer.parseInt(historyIdParam);
                }
                smartGardenService.stopIrrigation(this.getDataSource(), historyId);
                requestResult.setSuccess(true);
            }

            if (action.equalsIgnoreCase("set_irrigation_duration")) {
                logger.log(Level.INFO, "processRequest:set_irrigation_duration");
                String irrigationDurationInSecond = (String) request.getParameter("duration");
                final long newIrrigationDurationInSecond = smartGardenService
                        .setIrrigationDuration(Integer.parseInt(irrigationDurationInSecond));
                requestResult.setSuccess(true);
                requestResult.setValue(newIrrigationDurationInSecond);
            }

            if (action.equalsIgnoreCase("get_soil_status_history")) {
                logger.log(Level.INFO, "processRequest:get_soil_status_history");
                List<SoilStatus> historyList = smartGardenService.getSoilStatusHistory(this.getDataSource(),
                        10);
                requestResult.setValue(historyList);
                requestResult.setSuccess(true);
            }

            if (action.equalsIgnoreCase("get_power_status_history")) {
                logger.log(Level.INFO, "processRequest:get_power_status_history");
                List<PowerStatus> historyList = smartGardenService.getPowerStatusHistory(this.getDataSource(),
                        10);
                requestResult.setValue(historyList);
                requestResult.setSuccess(true);
            }

            if (action.equalsIgnoreCase("take_photo")) {
                logger.log(Level.INFO, "processRequest:take_photo");
                String photoFilename = smartGardenService.takePhoto();
                requestResult.setValue(photoFilename);
                requestResult.setSuccess(true);
            }

        } else {
            request.getRequestDispatcher("/index.html").forward(request, response);
        }
    } catch (Throwable t) {
        logger.log(Level.ERROR, "processRequest", t);
        requestResult.setSuccess(false);
        requestResult.setErrorMessage(t.toString());
    } finally {
        response.setContentType("application/json");
        PrintWriter out = response.getWriter();
        String responseJSON = mapper.writeValueAsString(requestResult);
        out.print(responseJSON);
        out.flush();
        out.close();
    }

}

From source file:ea.ejb.AbstractFacade.java

public Map<String, String> obtenerDatosFormConImagen(HttpServletRequest request) {

    Map<String, String> mapDatos = new HashMap();

    final String SAVE_DIR = "uploadImages";

    // Parametros del form
    String description = null;//  w ww  .  ja v  a 2 s.co m
    String url_image = null;
    String id_grupo = null;

    boolean isMultiPart;
    String filePath;
    int maxFileSize = 50 * 1024;
    int maxMemSize = 4 * 1024;
    File file = null;
    InputStream inputStream = null;
    OutputStream outputStream = null;

    // gets absolute path of the web application
    String appPath = request.getServletContext().getRealPath("");
    // constructs path of the directory to save uploaded file
    filePath = appPath + File.separator + "assets" + File.separator + "img" + File.separator + SAVE_DIR;
    String filePathWeb = "assets/img/" + SAVE_DIR + "/";
    // creates the save directory if it does not exists
    File fileSaveDir = new File(filePath);

    if (!fileSaveDir.exists()) {
        fileSaveDir.mkdir();
    }
    // Check that we have a file upload request
    isMultiPart = ServletFileUpload.isMultipartContent(request);
    if (isMultiPart) {

        // Parse the request
        List<FileItem> items = getMultipartItems(request);

        // Process the uploaded items
        Iterator<FileItem> iter = items.iterator();
        int offset = 0;
        int leidos = 0;
        while (iter.hasNext()) {
            FileItem item = iter.next();

            if (item.isFormField()) {
                // ProcessFormField
                String name = item.getFieldName();
                String value = item.getString();
                if (name.equals("description_post_grupo") || name.equals("descripcion")) {
                    description = value;
                } else if (name.equals("id_grupo")) {
                    id_grupo = value;
                }
            } else {
                // ProcessUploadedFile
                try {
                    String itemName = item.getName();
                    if (!itemName.equals("")) {
                        url_image = filePathWeb + item.getName();
                        // read this file into InputStream
                        inputStream = item.getInputStream();
                        // write the inputStream to a FileOutputStream
                        if (file == null) {
                            String fileDirUpload = filePath + File.separator + item.getName();
                            file = new File(fileDirUpload);
                            // crea el archivo en el sistema
                            file.createNewFile();
                            if (file.exists()) {
                                outputStream = new FileOutputStream(file);
                            }
                        }

                        int read = 0;
                        byte[] bytes = new byte[1024];

                        while ((read = inputStream.read(bytes)) != -1) {
                            outputStream.write(bytes, offset, read);
                            leidos += read;
                        }
                        offset += leidos;
                        leidos = 0;
                        System.out.println("Done!");
                    } else {
                        url_image = "";
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    if (inputStream != null) {
                        try {
                            inputStream.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
        if (outputStream != null) {
            try {
                // outputStream.flush();
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }
    mapDatos.put("descripcion", description);
    mapDatos.put("imagen", url_image);
    mapDatos.put("id_grupo", id_grupo);

    return mapDatos;
}

From source file:edu.ucsd.library.xdre.web.ExcelImportController.java

public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
    String ds = request.getParameter("ts");
    String collectionId = request.getParameter("category");
    String unit = request.getParameter("unit");
    String message = request.getParameter("message");
    String fileStore = request.getParameter("fs");
    String licenseBeginDate = request.getParameter("licenseBeginDate");
    String licenseEndDate = request.getParameter("licenseEndDate");

    HttpSession session = request.getSession();
    DAMSClient damsClient = null;//  ww  w.j  a  v  a 2  s  .  c  o  m
    Map dataMap = new HashMap();
    try {

        // initiate column name and control values for validation
        String columns = request.getServletContext().getRealPath("files/valid_columns.xlsx");
        String cvs = request.getServletContext().getRealPath("files/valid_cv_values.xlsx");
        try {
            ExcelSource.initControlValues(new File(columns), new File(cvs));
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (ds == null)
            ds = Constants.DEFAULT_TRIPLESTORE;

        damsClient = new DAMSClient(Constants.DAMS_STORAGE_URL);
        damsClient.setTripleStore(ds);

        Map<String, String> collectionMap = damsClient.listCollections();
        Map<String, String> unitsMap = damsClient.listUnits();
        List<String> tsSrcs = damsClient.listTripleStores();
        List<String> fsSrcs = damsClient.listFileStores();
        String fsDefault = damsClient.defaultFilestore();
        if (fileStore == null || fileStore.length() == 0)
            fileStore = fsDefault;

        message = (!StringUtils.isBlank(message) || StringUtils.isBlank(collectionId)) ? message
                : (String) session.getAttribute("message");
        session.removeAttribute("message");

        JSONArray accessValues = new JSONArray();
        accessValues.addAll(Arrays.asList(RecordUtil.ACCESS_VALUES));

        Map<String, String> countryCodes = MarcModsImportController.getCountryCodes(request);

        dataMap.put("categories", collectionMap);
        dataMap.put("category", collectionId);
        dataMap.put("units", unitsMap);
        dataMap.put("unit", unit);
        dataMap.put("message", message);
        dataMap.put("triplestore", ds);
        dataMap.put("triplestores", tsSrcs);
        dataMap.put("filestores", fsSrcs);
        dataMap.put("filestore", fileStore);
        dataMap.put("filestoreDefault", fsDefault);
        dataMap.put("copyrightStatus", RecordUtil.COPYRIGHT_VALUES);
        dataMap.put("program", RecordUtil.PROGRAM_VALUES);
        dataMap.put("accessOverride", accessValues);
        dataMap.put("licenseBeginDate", licenseBeginDate);
        dataMap.put("licenseEndDate", licenseEndDate);
        dataMap.put("countryCodes", countryCodes);

    } catch (Exception e) {
        e.printStackTrace();
        message += e.getMessage();
    } finally {
        if (damsClient != null)
            damsClient.close();
    }
    return new ModelAndView("excelImport", "model", dataMap);
}

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 ww .  ja v a 2s. c  o m*/
    //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: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));
    //}//from   w  w  w  . j ava  2 s.c  om
    //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.everit.authentication.cas.CasAuthentication.java

/**
 * Processes the CAS (back channel) logout requests. It retrieves the invalidated service ticket
 * from the logout request and invalidates the {@link HttpSession} assigned to that service
 * ticket./*from   w  w w .j ava 2  s. c om*/
 */
private void processBackChannelLogout(final HttpServletRequest httpServletRequest) throws IOException {

    String logoutRequest = httpServletRequest.getParameter(requestParamNameLogoutRequest);
    String sessionIndex = getTextForElement(logoutRequest, SESSION_INDEX);

    ServletContext servletContext = httpServletRequest.getServletContext();
    CasHttpSessionRegistry casHttpSessionRegistry = CasHttpSessionRegistry.getInstance(servicePid,
            servletContext);

    casHttpSessionRegistry.removeByServiceTicket(sessionIndex).ifPresent((httpSession) -> {
        try {
            httpSession.invalidate();
        } catch (IllegalStateException e) {
            LOGGER.debug(e.getMessage(), e);
        }
    });
}

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

public String processarArquivo(HttpServletRequest request, String nameToSave)
        throws ServletException, IOException {

    boolean isMultipart = ServletFileUpload.isMultipartContent(request);

    if (isMultipart) {
        ServletFileUpload upload = new ServletFileUpload();
        try {//  w  ww.  j  av a  2s. c o m
            FileItemIterator itr = upload.getItemIterator(request);

            while (itr.hasNext()) {
                FileItemStream item = itr.next();
                if (!item.isFormField()) {
                    //                        pode ser tb sem a barra ????
                    //                        String path = request.getServletContext().getRealPath("");
                    String contextPath = request.getServletContext().getRealPath("/");

                    //refatorar aqui apenas para salvarimagem receber um pasta, inputStream e o nome
                    //aqui, criar um inputStream atravs do arquivo item antes de enviar
                    //diminuir 1 mtodo, deixando salvarImagem mais genrico
                    if (salvarImagem(contextPath + File.separator + folder, item, nameToSave)) {
                        return folder + "/" + nameToSave;
                    }
                }
            }

        } catch (FileUploadException ex) {
            System.out.println("erro ao obter informaoes sobre o arquivo");
        }

    } else {
        System.out.println("Erro no formulario!");
    }

    return null;
}