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.novartis.pcs.ontology.rest.servlet.SynonymsServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String mediaType = getExpectedMediaType(request);
    String pathInfo = StringUtils.trimToNull(request.getPathInfo());
    if (mediaType == null || !MEDIA_TYPE_JSON.equals(mediaType)) {
        response.setStatus(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE);
        response.setContentLength(0);
    } else if (pathInfo == null || pathInfo.length() == 1) {
        response.setStatus(HttpServletResponse.SC_NOT_FOUND);
        response.setContentLength(0);/*from  ww w . ja  v a2 s . c  o  m*/
    } else {
        String datasourceAcronym = null;
        String vocabRefId = null;
        boolean pending = Boolean.parseBoolean(request.getParameter("pending"));
        int i = pathInfo.indexOf('/', 1);
        if (i != -1) {
            datasourceAcronym = pathInfo.substring(1, i);
            vocabRefId = pathInfo.substring(i + 1);
        } else {
            datasourceAcronym = pathInfo.substring(1);
        }
        serialize(datasourceAcronym, vocabRefId, pending, response);
    }
}

From source file:com.ikon.servlet.MimeIconServlet.java

/**
 * /* w  ww. ja  v  a2 s  . c  o  m*/
 */
public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    String mime = request.getPathInfo();
    OutputStream os = null;

    try {
        if (mime.length() > 1) {
            MimeType mt = MimeTypeDAO.findByName(mime.substring(1));

            if (mt != null) {
                byte[] img = SecureStore.b64Decode(new String(mt.getImageContent()));
                response.setContentType(mt.getImageMime());
                response.setContentLength(img.length);
                os = response.getOutputStream();
                os.write(img);
                os.flush();
            }
        }
    } catch (DatabaseException e) {
        log.error(e.getMessage(), e);
    } finally {
        IOUtils.closeQuietly(os);
    }
}

From source file:org.openmrs.module.emtfrontend.web.controller.EmtFrontendFormController.java

private void returnPdf(HttpServletResponse response, File pdfFile, String filenameToReturn)
        throws FileNotFoundException, IOException {
    response.setContentType("application/pdf");
    response.addHeader("Content-Disposition", "attachment; filename=" + filenameToReturn);
    response.setContentLength((int) pdfFile.length());

    FileInputStream fileInputStream = null;
    OutputStream responseOutputStream = null;
    try {/*from www  . j av a2  s. c o m*/
        fileInputStream = new FileInputStream(pdfFile);
        responseOutputStream = response.getOutputStream();
        int bytes;
        while ((bytes = fileInputStream.read()) != -1) {
            responseOutputStream.write(bytes);
        }
    } finally {
        if (fileInputStream != null)
            fileInputStream.close();
    }
}

From source file:org.openmrs.module.emtfrontend.web.controller.EmtFrontendFormController.java

private void returnCsv(HttpServletResponse response, File csvFile, String filenameToReturn)
        throws FileNotFoundException, IOException {
    response.setContentType("application/csv");
    response.addHeader("Content-Disposition", "attachment; filename=" + filenameToReturn);
    response.setContentLength((int) csvFile.length());

    FileInputStream fileInputStream = null;
    OutputStream responseOutputStream = null;
    try {//from www  .ja  va2s . c  om
        fileInputStream = new FileInputStream(csvFile);
        responseOutputStream = response.getOutputStream();
        int bytes;
        while ((bytes = fileInputStream.read()) != -1) {
            responseOutputStream.write(bytes);
        }
    } finally {
        if (fileInputStream != null)
            fileInputStream.close();
    }
}

From source file:com.esri.ArcGISController.java

@RequestMapping(value = "/rest/services/InfoUSA/MapServer", method = RequestMethod.GET)
public void doMapServer(final HttpServletResponse response) throws IOException {
    response.setStatus(HttpServletResponse.SC_OK);
    response.setContentType("application/json");
    response.setContentLength(m_byteArrayOutputStream.size());
    m_byteArrayOutputStream.writeTo(response.getOutputStream());
    response.getOutputStream().flush();//w  w  w .j  a  v  a 2  s. com
}

From source file:net.sourceforge.fenixedu.presentationTier.Action.base.FenixDispatchAction.java

protected void writeFile(final HttpServletResponse response, final String filename, final String contentType,
        final byte[] content) throws IOException {

    response.setContentLength(content.length);
    response.setContentType(contentType);
    response.addHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");

    try (ServletOutputStream outputStream = response.getOutputStream()) {
        outputStream.write(content);/*from  w w w  .j  a v a2s.c o m*/
        outputStream.flush();
        response.flushBuffer();
    }
}

From source file:mx.edu.um.mateo.general.web.ImagenController.java

@RequestMapping("/producto/{id}")
public String producto(HttpServletRequest request, HttpServletResponse response, @PathVariable Long id) {
    log.debug("Buscando imagen del producto {}", id);
    Query query = currentSession().createQuery(
            "select imagen from Producto p left outer join p.imagenes as imagen where p.id = :productoId");
    query.setLong("productoId", id);
    Imagen imagen = (Imagen) query.uniqueResult();
    if (imagen != null) {
        response.setContentType(imagen.getTipoContenido());
        response.setContentLength(imagen.getTamano().intValue());
        try {/*  w  w w.  j  a  v a  2s .c o  m*/
            response.getOutputStream().write(imagen.getArchivo());
        } catch (IOException e) {
            log.error("No se pudo escribir el archivo", e);
            throw new RuntimeException("No se pudo escribir el archivo en el outputstream");
        }
    } else {
        try {
            response.sendRedirect(request.getContextPath() + "/images/sin-foto.jpg");
        } catch (IOException e) {
            log.error("No se pudo obtener la imagen", e);
        }
    }
    return null;
}

From source file:net.acesinc.convergentui.BaseFilter.java

protected void writeResponse(BufferedImage image, MediaType type) throws Exception {
    RequestContext context = RequestContext.getCurrentContext();
    // there is no body to send
    if (image == null) {
        return;/*from   w ww.ja  v  a  2 s.c om*/
    }
    HttpServletResponse servletResponse = context.getResponse();
    //        servletResponse.setCharacterEncoding("UTF-8");
    servletResponse.setContentType(type.toString());

    ByteArrayOutputStream tmp = new ByteArrayOutputStream();
    ImageIO.write(image, type.getSubtype(), tmp);
    tmp.close();
    Integer contentLength = tmp.size();

    servletResponse.setContentLength(contentLength);

    OutputStream outStream = servletResponse.getOutputStream();
    ByteArrayOutputStream os = new ByteArrayOutputStream();

    ImageIO.write(image, type.getSubtype(), os);
    InputStream is = new ByteArrayInputStream(os.toByteArray());

    try {
        writeResponse(is, outStream);
    } finally {
        try {
            if (is != null) {
                is.close();
            }
            outStream.flush();
            outStream.close();
        } catch (IOException ex) {
        }
    }
}

From source file:it.eng.spagobi.analiticalmodel.execution.service.PrintNotesAction.java

public void doService() {
    logger.debug("IN");

    ExecutionInstance executionInstance;
    executionInstance = getContext().getExecutionInstance(ExecutionInstance.class.getName());
    String executionIdentifier = new BIObjectNotesManager()
            .getExecutionIdentifier(executionInstance.getBIObject());
    Integer biobjectId = executionInstance.getBIObject().getId();
    List globalObjNoteList = null;
    try {//www .j  a  v  a  2 s.co m
        globalObjNoteList = DAOFactory.getObjNoteDAO().getListExecutionNotes(biobjectId, executionIdentifier);
    } catch (EMFUserError e1) {
        logger.error("Error in retrieving obj notes", e1);
        return;
    } catch (Exception e1) {
        logger.error("Error in retrieving obj notes", e1);
        return;
    }
    //mantains only the personal notes and others one only if they have PUBLIC status
    List objNoteList = new ArrayList();
    UserProfile profile = (UserProfile) this.getUserProfile();
    String userId = (String) profile.getUserId();
    for (int i = 0, l = globalObjNoteList.size(); i < l; i++) {
        ObjNote objNote = (ObjNote) globalObjNoteList.get(i);
        if (objNote.getIsPublic()) {
            objNoteList.add(objNote);
        } else if (objNote.getOwner().equalsIgnoreCase(userId)) {
            objNoteList.add(objNote);
        }
    }

    String outputType = "PDF";
    RequestContainer requestContainer = getRequestContainer();
    SourceBean sb = requestContainer.getServiceRequest();
    outputType = (String) sb.getAttribute(SBI_OUTPUT_TYPE);
    if (outputType == null)
        outputType = "PDF";

    String templateStr = getTemplateTemplate();

    //JREmptyDataSource conn=new JREmptyDataSource(1);
    //Connection conn = getConnection("SpagoBI",getHttpSession(),profile,obj.getId().toString());      
    JRBeanCollectionDataSource datasource = new JRBeanCollectionDataSource(objNoteList);

    HashedMap parameters = new HashedMap();
    parameters.put("PARAM_OUTPUT_FORMAT", outputType);
    parameters.put("TITLE", executionInstance.getBIObject().getLabel());

    UUIDGenerator uuidGen = UUIDGenerator.getInstance();
    UUID uuid_local = uuidGen.generateTimeBasedUUID();
    String executionId = uuid_local.toString();
    executionId = executionId.replaceAll("-", "");
    //Creta etemp file
    String dirS = System.getProperty("java.io.tmpdir");
    File dir = new File(dirS);
    dir.mkdirs();
    String fileName = "notes" + executionId;
    OutputStream out = null;
    File tmpFile = null;
    try {
        tmpFile = File.createTempFile(fileName, "." + outputType, dir);
        out = new FileOutputStream(tmpFile);
        StringBufferInputStream sbis = new StringBufferInputStream(templateStr);
        logger.debug("compiling report");
        JasperReport report = JasperCompileManager.compileReport(sbis);
        //report.setProperty("", )
        logger.debug("filling report");
        JasperPrint jasperPrint = JasperFillManager.fillReport(report, parameters, datasource);
        JRExporter exporter = null;
        if (outputType.equalsIgnoreCase("PDF")) {
            exporter = (JRExporter) Class.forName("net.sf.jasperreports.engine.export.JRPdfExporter")
                    .newInstance();
            if (exporter == null)
                exporter = new JRPdfExporter();
        } else {
            exporter = (JRExporter) Class.forName("net.sf.jasperreports.engine.export.JRRtfExporter")
                    .newInstance();
            if (exporter == null)
                exporter = new JRRtfExporter();
        }

        exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
        exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, out);
        logger.debug("exporting report");
        exporter.exportReport();

    } catch (Throwable e) {
        logger.error("An exception has occured", e);
        return;
    } finally {
        try {
            out.flush();
            out.close();
        } catch (IOException e) {
            logger.error("Error closing output", e);
        }
    }

    String mimeType;
    if (outputType.equalsIgnoreCase("RTF")) {
        mimeType = "application/rtf";
    } else {
        mimeType = "application/pdf";
    }

    HttpServletResponse response = getHttpResponse();
    response.setContentType(mimeType);
    response.setHeader("Content-Disposition", "filename=\"report." + outputType + "\";");
    response.setContentLength((int) tmpFile.length());
    try {
        BufferedInputStream in = new BufferedInputStream(new FileInputStream(tmpFile));
        int b = -1;
        while ((b = in.read()) != -1) {
            response.getOutputStream().write(b);
        }
        response.getOutputStream().flush();
        in.close();
    } catch (Exception e) {
        logger.error("Error while writing the content output stream", e);
    } finally {
        tmpFile.delete();
    }

    logger.debug("OUT");

}

From source file:com.doculibre.constellio.servlets.DownloadFileServlet.java

@Override
public final void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    String file = request.getParameter("file");
    String mimetype = request.getParameter("mimetype");

    String filePathFound = getFilePathFor(file);
    if (filePathFound == null) {
        response.sendError(404);// www .  j av a2  s .c o m
    } else {
        File fileFound = new File(filePathFound);
        response.setContentType((mimetype != null) ? mimetype : "application/octet-stream");
        response.setContentLength((int) fileFound.length());
        response.setHeader("Content-Disposition", "attachment; filename=\"" + fileFound.getName() + "\"");

        InputStream is = new BufferedInputStream(new FileInputStream(fileFound));
        IOUtils.copy(is, response.getOutputStream());
    }
}