Example usage for javax.servlet.http HttpServletResponse setContentLength

List of usage examples for javax.servlet.http HttpServletResponse setContentLength

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletResponse setContentLength.

Prototype

public void setContentLength(int len);

Source Link

Document

Sets the length of the content body in the response In HTTP servlets, this method sets the HTTP Content-Length header.

Usage

From source file:com.rplt.studioMusik.controller.OwnerController.java

@RequestMapping(value = "/lihatlaporan")
public String lihatLaporan(ModelMap model, HttpServletResponse response) {
    String tanggalAwal = request.getParameter("tanggalAwal").toUpperCase();
    String tanggalAkhir = request.getParameter("tanggalAkhir").toUpperCase();

    //        List<PersewaanStudioMusik> dataListByMonth = persewaanStudioMusik.getDataListByMonth(tanggalAwal, tanggalAkhir);
    //        //from   w  w w.  j  a v  a  2  s . c o m
    //        model.addAttribute("bulan", tanggalAwal);
    //        model.addAttribute("tahun", tanggalAkhir);
    //        model.addAttribute("dataListByMonth", dataListByMonth);

    Connection conn = DatabaseConnection.getmConnection();
    //            File reportFile = new File(application.getRealPath("Coba.jasper"));//your report_name.jasper file
    File reportFile = new File(
            servletConfig.getServletContext().getRealPath("/resources/report/laporan_pemasukan.jasper"));

    Map parameters = new HashMap();
    Map<String, Object> params = new HashMap<String, Object>();
    params.put("TANGGAL_AWAL", tanggalAwal);
    params.put("TANGGAL_AKHIR", tanggalAkhir);
    byte[] bytes = null;
    try {
        bytes = JasperRunManager.runReportToPdf(reportFile.getPath(), params, conn);
    } catch (JRException ex) {
        Logger.getLogger(OperatorController.class.getName()).log(Level.SEVERE, null, ex);
    }

    response.setContentType("application/pdf");
    response.setContentLength(bytes.length);

    try {
        ServletOutputStream outStream = response.getOutputStream();
        outStream.write(bytes, 0, bytes.length);
        outStream.flush();
        outStream.close();
    } catch (IOException ex) {
        Logger.getLogger(OperatorController.class.getName()).log(Level.SEVERE, null, ex);
    }

    return "halaman-cetakReport-owner";
}

From source file:org.overlord.sramp.server.servlets.MavenRepositoryServlet.java

/**
 * Do get.//ww  w.j ava  2s .  c o m
 *
 * @param req
 *            the req
 * @param resp
 *            the resp
 * @throws ServletException
 *             the servlet exception
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest,
 *      javax.servlet.http.HttpServletResponse)
 */
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    // Get the URL request and prepare it to obtain the maven metadata
    // information
    String url = req.getRequestURI();
    String maven_url = ""; //$NON-NLS-1$
    if (url.contains(URL_CONTEXT_STR)) {
        maven_url = url.substring(url.indexOf(URL_CONTEXT_STR) + URL_CONTEXT_STR.length());
    } else {
        maven_url = url;
    }

    if (maven_url.startsWith("/")) { //$NON-NLS-1$
        maven_url = maven_url.substring(1);
    }

    // Builder class that converts the url into a Maven MetaData Object
    MavenMetaData metadata = MavenMetaDataBuilder.build(maven_url);

    // If it is possible to detect a maven metadata information and it is
    // found an artifact information
    if (metadata.isArtifact()) {

        // Here we have the gav info. So let's go to Sramp to
        // obtain the InputStream with the info
        MavenArtifactWrapper artifact = null;
        try {
            artifact = service.getArtifactContent(metadata);
            if (artifact != null) {
                resp.setContentLength(artifact.getContentLength());
                resp.addHeader("Content-Disposition", //$NON-NLS-1$
                        "attachment; filename=" + artifact.getFileName()); //$NON-NLS-1$
                resp.setContentType(artifact.getContentType());
                IOUtils.copy(artifact.getContent(), resp.getOutputStream());
            } else {
                listItemsResponse(req, resp, maven_url);
            }
        } catch (MavenRepositoryException e) {
            logger.info(Messages.i18n.format("maven.servlet.artifact.content.get.exception", //$NON-NLS-1$
                    metadata.getGroupId(), metadata.getArtifactId(), metadata.getVersion(),
                    metadata.getFileName()));
            // Send a 500 error if there's an exception
            resp.sendError(500);
        } finally {
            if (artifact != null) {
                IOUtils.closeQuietly(artifact.getContent());
            }
        }

    } else {
        // In case the metadata information is not an artifact, then the
        // maven url is listed
        listItemsResponse(req, resp, maven_url);
    }
}

From source file:com.tasktop.c2c.server.internal.wiki.server.WikiServiceController.java

@Section(value = "Attachments")
@Title("Retrieve Image")
@Documentation("Retrieve an Image from a Page")
@RequestMapping(value = "{pageId}/attachment/{name:.*}", method = RequestMethod.GET)
public void getImage(@PathVariable(value = "pageId") Integer pageId,
        @PathVariable(value = "name") String imageName, HttpServletRequest request,
        HttpServletResponse response) throws IOException {
    String etag = request.getHeader("If-None-Match");
    if (etag != null && etag.length() > 1 && etag.charAt(0) == '"' && etag.charAt(etag.length() - 1) == '"') {
        etag = etag.substring(1, etag.length() - 1);
    }/*from  ww  w . j a  v  a2s  . c  om*/
    Attachment attachment;
    try {
        attachment = service.retrieveAttachmentByNameWithETag(pageId, imageName, etag);
    } catch (EntityNotFoundException e) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }
    if (attachment.getContent() == null) {
        // ETag match
        response.sendError(HttpServletResponse.SC_NOT_MODIFIED);
        return;
    }
    String modified = formatRFC2822(attachment.getModificationDate());
    if (modified.equals(request.getHeader("If-Modified-Since"))) {
        response.sendError(HttpServletResponse.SC_NOT_MODIFIED);
        return;
    }
    response.setStatus(HttpServletResponse.SC_OK);
    response.setContentLength(attachment.getSize());
    response.setContentType(attachment.getMimeType());
    response.setHeader("ETag", "\"" + attachment.getEtag() + "\"");
    response.setHeader("Modified", modified);

    ServletOutputStream outputStream = response.getOutputStream();
    try {
        outputStream.write(attachment.getContent());
    } finally {
        outputStream.close();
    }
}

From source file:architecture.ee.web.spring.controller.DownloadController.java

@RequestMapping(value = "/file/{attachmentId}/{filename:.+}", method = RequestMethod.GET)
@ResponseBody/*  w  w w  .j  av a 2 s .c  o  m*/
public void handleFile(@PathVariable("attachmentId") Long attachmentId,
        @PathVariable("filename") String filename,
        @RequestParam(value = "thumbnail", defaultValue = "false", required = false) boolean thumbnail,
        @RequestParam(value = "width", defaultValue = "150", required = false) Integer width,
        @RequestParam(value = "height", defaultValue = "150", required = false) Integer height,
        HttpServletResponse response) throws IOException {

    log.debug(" ------------------------------------------");
    log.debug("attachment:" + attachmentId);
    log.debug("filename:" + filename);
    log.debug("thumbnail:" + thumbnail);
    log.debug("------------------------------------------");
    try {
        if (attachmentId > 0 && StringUtils.isNotEmpty(filename)) {
            Attachment attachment = attachmentManager.getAttachment(attachmentId);
            if (StringUtils.equals(filename, attachment.getName())) {

                if (thumbnail) {
                    if (StringUtils.startsWithIgnoreCase(attachment.getContentType(), "image")
                            || StringUtils.endsWithIgnoreCase(attachment.getContentType(), "pdf")) {
                        InputStream input = attachmentManager.getAttachmentImageThumbnailInputStream(attachment,
                                width, height);
                        response.setContentType(attachment.getThumbnailContentType());
                        response.setContentLength(attachment.getThumbnailSize());
                        IOUtils.copy(input, response.getOutputStream());
                        response.flushBuffer();
                    }
                } else {
                    InputStream input = attachmentManager.getAttachmentInputStream(attachment);
                    response.setContentType(attachment.getContentType());
                    response.setContentLength(attachment.getSize());
                    IOUtils.copy(input, response.getOutputStream());
                    response.setHeader("contentDisposition",
                            "attachment;filename=" + getEncodedFileName(attachment));
                    response.flushBuffer();
                }
            } else {
                throw new NotFoundException();
            }
        } else {
            throw new NotFoundException();
        }
    } catch (NotFoundException e) {
        response.sendError(404);
    }
}

From source file:dk.dma.msinm.web.OsmStaticMap.java

/**
 * Main GET method//from  w w w.j  av a 2s . c  om
 *
 * @param request  servlet request
 * @param response servlet response
 */
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {

    // Sanity checks
    if (StringUtils.isBlank(request.getParameter("zoom")) || StringUtils.isBlank(request.getParameter("center"))
            || StringUtils.isBlank(request.getParameter("size"))) {
        throw new IllegalArgumentException("Must provide zoom, size and center parameters");
    }

    MapImageCtx ctx = new MapImageCtx();

    parseParams(ctx, request);
    if (useMapCache) {
        // use map cache, so check cache for map
        if (!checkMapCache(ctx)) {
            // map is not in cache, needs to be build
            BufferedImage image = makeMap(ctx);

            Path path = repositoryService.getRepoRoot().resolve(mapCacheIDToFilename(ctx));
            Files.createDirectories(path.getParent());
            ImageIO.write(image, "png", path.toFile());

            // And write to response
            sendHeader(response);
            ImageIO.write(image, "png", response.getOutputStream());

        } else {
            // map is in cache
            sendHeader(response);
            Path path = repositoryService.getRepoRoot().resolve(mapCacheIDToFilename(ctx));
            response.setContentLength((int) path.toFile().length());

            FileInputStream fileInputStream = new FileInputStream(path.toFile());
            OutputStream responseOutputStream = response.getOutputStream();
            int bytes;
            while ((bytes = fileInputStream.read()) != -1) {
                responseOutputStream.write(bytes);
            }
        }

    } else {
        // no cache, make map, send headers and deliver png
        BufferedImage image = makeMap(ctx);
        sendHeader(response);
        ImageIO.write(image, "png", response.getOutputStream());
    }
}

From source file:edu.northwestern.bioinformatics.studycalendar.web.template.ExportActivitiesController.java

@Override
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
        throws Exception {
    String identifier = extractIdentifier(request.getPathInfo(), ID_PATTERN);
    String fullPath = request.getPathInfo();
    String extension = fullPath.substring(fullPath.lastIndexOf(".") + 1).toLowerCase();

    if (identifier == null) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Could not extract study identifier");
        return null;
    }/*from  w  ww.  j  a  v  a 2 s.co  m*/
    Source source = sourceDao.getByName(identifier);
    if (source == null) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return null;
    }
    if (!(extension.equals("csv") || extension.equals("xls") || extension.equals("xml"))) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Wrong extension type");
        return null;
    }
    String elt;

    if (extension.equals("xml")) {
        response.setContentType("text/xml");
        elt = activitySourceXmlSerializer.createDocumentString(source);
    } else {
        if (extension.equals("csv")) {
            response.setContentType("text/plain");
            elt = sourceSerializer.createDocumentString(source, ',');
        } else {
            response.setContentType("text");
            elt = sourceSerializer.createDocumentString(source, '\t');
        }
    }

    byte[] content = elt.getBytes();
    response.setContentLength(content.length);
    response.setHeader("Content-Disposition", "attachment");
    FileCopyUtils.copy(content, response.getOutputStream());
    return null;
}

From source file:cl.cla.web.firma.servlet.ServletDetalleDocumentoPdf.java

private void generarPdf(HttpServletRequest request, HttpServletResponse response) throws IOException {
    String p = request.getParameter("p") != null ? request.getParameter("p") : "";
    System.out.println("p " + p);
    String nombreArchivo = "";
    switch (p) {/* w  w  w  .j a  v  a2 s .c  o  m*/
    case "1-1BSUGWN":
        nombreArchivo = "C:\\pdf\\a.txt";
        break;
    case "1-1BSUGWR":
        nombreArchivo = "C:\\pdf\\b.txt";
        break;
    case "1-1BSUGWP":
        nombreArchivo = "C:\\pdf\\c.txt";
        break;
    default:
    }
    System.out.println("nombreArchivo " + nombreArchivo);
    FileReader fr = null;

    String base64File = generarBase64(nombreArchivo);

    System.out.println(base64File);
    System.out.println("detalleRepController " + detalleRepController);
    byte[] encoded = Base64.decodeBase64(base64File);

    //        try {
    //            DetalleDocumentoVO detalleDocumentoVO = detalleRepController.detalleRepINOperation(p);
    //            encoded=detalleDocumentoVO.getArchivo();
    //        } catch (Exception ex) {
    //            encoded =Base64.decodeBase64(generarBase64Vacio());
    //        }

    File pdfFile = new File("c.pdf");
    FileUtils.writeByteArrayToFile(pdfFile, encoded);

    response.setContentType("application/pdf");
    response.addHeader("Content-Disposition", "inline; filename=a.pdf");
    response.setContentLength((int) pdfFile.length());

    FileInputStream fileInputStream = new FileInputStream(pdfFile);
    OutputStream responseOutputStream = response.getOutputStream();
    int bytes;
    while ((bytes = fileInputStream.read()) != -1) {
        responseOutputStream.write(bytes);
    }
    fileInputStream.close();
    responseOutputStream.close();

}

From source file:edu.emory.cci.aiw.cvrg.eureka.servlet.JobSubmitServlet.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    Principal principal = request.getUserPrincipal();
    if (principal == null) {
        throw new ServletException("Spreadsheet upload attempt: no user associated with the request");
    }//  w ww.j ava 2 s. c  o m
    SubmitJobResponse jobResponse = new SubmitJobResponse();
    String value;
    try {
        Long jobId = submitJob(request, principal);
        jobResponse.setJobId(jobId);
    } catch (ParseException ex) {
        jobResponse.setMessage("The date range you specified is invalid.");
        jobResponse.setStatusCode(HttpServletResponse.SC_BAD_REQUEST);
        jobResponse.setErrorThrown("Bad request");
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
    } catch (ClientException | FileUploadException | IOException ex) {
        String msg = "Upload failed due to an internal error";
        jobResponse.setMessage(msg);
        jobResponse.setStatusCode(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        jobResponse.setErrorThrown("Internal server error");
        log("Upload failed for user " + principal.getName(), ex);
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
    value = MAPPER.writeValueAsString(jobResponse);
    response.setContentLength(value.length());
    response.setContentType("application/json");
    PrintWriter out = response.getWriter();
    out.println(value);
}

From source file:com.novartis.pcs.ontology.rest.servlet.SynonymsServlet.java

private void serialize(String datasourceAcronym, String vocabRefId, boolean pending,
        HttpServletResponse response) {
    try {//  w  w  w . j a  v a2  s. c  o m
        List<SynonymDTO> dtos = new ArrayList<SynonymDTO>(1024);
        Datasource datasource = datasourceDAO.loadByAcronym(datasourceAcronym);
        if (datasource != null) {
            Collection<Synonym> synonyms = vocabRefId != null
                    ? synonymDAO.loadByCtrldVocabRefId(datasource, vocabRefId)
                    : synonymDAO.loadByDatasource(datasource);
            EnumSet<Status> statusSet = pending ? EnumSet.of(Status.PENDING, Status.APPROVED)
                    : EnumSet.of(Status.APPROVED);

            for (Synonym synonym : synonyms) {
                if (statusSet.contains(synonym.getStatus())) {
                    dtos.add(new SynonymDTO(synonym));
                }
            }
        }

        if (!dtos.isEmpty()) {
            response.setStatus(HttpServletResponse.SC_OK);
            response.setHeader("Access-Control-Allow-Origin", "*");
            response.setContentType(MEDIA_TYPE_JSON + ";charset=utf-8");
            response.setHeader("Cache-Control", "public, max-age=0");

            // As per jackson javadocs - Encoding will be UTF-8
            mapper.writeValue(response.getOutputStream(), dtos);
        } else {
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
            response.setContentLength(0);
        }
    } catch (Exception e) {
        log("Failed to serialize synonyms to JSON", e);
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        response.setContentLength(0);
    }
}