Example usage for javax.servlet.http HttpServletResponse addHeader

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

Introduction

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

Prototype

public void addHeader(String name, String value);

Source Link

Document

Adds a response header with the given name and value.

Usage

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 {/*  w w  w  . ja v a 2 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  w  ww.  j a v a 2  s  .  c  o m
        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:co.com.realtech.mariner.util.jsf.file.FileDownloader.java

/**
 * Descargar archivo a travs del FacesContext.
 *
 * @param context/*  w  w w  .  java  2  s .  co m*/
 * @param bytes
 * @param nombreArchivo
 */
public void descargarArchivoFacesContext(FacesContext context, byte[] bytes, String nombreArchivo) {
    ExternalContext externalContext = context.getExternalContext();
    HttpServletResponse response = (HttpServletResponse) externalContext.getResponse();
    try {
        if (bytes == null) {
            System.out.println("Bytes nulos en respuesta de PDF");
        } else {
            try (ServletOutputStream servletOutputStream = response.getOutputStream()) {
                response.addHeader("Content-Type", "application/pdf");
                response.addHeader("Content-Disposition", "attachment; filename=" + nombreArchivo + ".pdf");
                response.setContentLength(bytes.length);
                response.setContentType("application/pdf");
                servletOutputStream.write(bytes);
                servletOutputStream.flush();
                context.responseComplete();
            }
        }
    } catch (Exception e) {
        System.out.println("Error enviando archivo PDF, error causado por " + e);
    }
}

From source file:net.gplatform.sudoor.server.captcha.model.CaptchaEngine.java

public void renderCapcha(HttpServletRequest request, HttpServletResponse response) throws Exception {
    // Set to expire far in the past.
    response.setDateHeader("Expires", 0);
    // Set standard HTTP/1.1 no-cache headers.
    response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
    // Set IE extended HTTP/1.1 no-cache headers (use addHeader).
    response.addHeader("Cache-Control", "post-check=0, pre-check=0");
    // Set standard HTTP/1.0 no-cache header.
    response.setHeader("Pragma", "no-cache");

    // return a jpeg
    response.setContentType("image/jpeg");

    // create the text for the image
    String capText = captchaProducer.createText();

    // store the text in the session
    request.getSession().setAttribute(Constants.KAPTCHA_SESSION_KEY, capText);
    logger.debug("Save Captcha: {} in Session:{}", capText, request.getSession().getId());

    // create the image with the text
    BufferedImage bi = captchaProducer.createImage(capText);

    ServletOutputStream out = response.getOutputStream();

    // write the data out
    ImageIO.write(bi, "jpg", out);
    try {//w  w  w  .j  ava  2s.  c om
        out.flush();
    } finally {
        out.close();
    }
}

From source file:se.inera.certificate.proxy.mappings.remote.RemoteDispatcher.java

private void doDispatch(HttpServletRequest httpRequest, HttpServletResponse httpResponse) throws IOException {
    URI newUrl = buildNewURL(httpRequest, remoteMapping);

    HttpResponse resp = makeRequest(httpRequest, newUrl);

    httpResponse.setStatus(resp.getStatusLine().getStatusCode());
    for (Header h : resp.getAllHeaders()) {
        httpResponse.addHeader(h.getName(), h.getValue());
    }//from  w  ww .j a va2  s.  c om

    sendResponseEntity(httpResponse, resp.getEntity());
}

From source file:mx.gob.cfe.documentos.web.SobreController.java

private void generaReporte(String tipo, List<Sobre> diezmos, HttpServletResponse response)
        throws JRException, IOException {
    log.debug("Generando reporte {}", tipo);
    byte[] archivo = null;
    switch (tipo) {
    case "PDF":
        archivo = generaPdf(diezmos);//w w w .  j  ava 2 s .co  m
        response.setContentType("application/pdf");
        response.addHeader("Content-Disposition", "attachment; filename=diezmos.pdf");
        break;

    }
    if (archivo != null) {
        response.setContentLength(archivo.length);
        try (BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream())) {
            bos.write(archivo);
            bos.flush();
        }
    }

}

From source file:com.usefullc.platform.common.utils.IOUtils.java

/**
 * /*from w  ww  . j  a  v a 2  s.com*/
 * 
 * @param path
 * @param fileName
 * @param response
 * @return
 */
public static void download(String path, String fileName, HttpServletResponse response) {
    try {

        if (StringUtils.isEmpty(path)) {
            throw new IllegalArgumentException("?");
        } else {
            File file = new File(path);
            if (!file.exists()) {
                throw new IllegalArgumentException("??");
            }
        }
        if (StringUtils.isEmpty(fileName)) {
            throw new IllegalArgumentException("???");
        }
        if (response == null) {
            throw new IllegalArgumentException("response ?");
        }

        // path
        File file = new File(path);

        // ??
        InputStream fis = new BufferedInputStream(new FileInputStream(path));
        byte[] buffer = new byte[fis.available()];
        fis.read(buffer);
        fis.close();
        // response
        response.reset();

        // ??linux ?  linux utf-8,windows  GBK)
        String defaultEncoding = System.getProperty("file.encoding");
        if (defaultEncoding != null && defaultEncoding.equals("UTF-8")) {

            response.addHeader("Content-Disposition",
                    "attachment;filename=" + new String(fileName.getBytes("GBK"), "iso-8859-1"));
        } else {
            response.addHeader("Content-Disposition",
                    "attachment;filename=" + new String(fileName.getBytes(), "iso-8859-1"));
        }

        // responseHeader
        response.addHeader("Content-Length", "" + file.length());
        response.setContentType("application/octet-stream");
        OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
        toClient.write(buffer);
        toClient.flush();
        toClient.close();
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

From source file:org.fcrepo.http.commons.api.HttpHeaderInjector.java

/**
 * Add additional Http Headers/*from  www . j a  v  a2 s.  c om*/
 *
 * @param servletResponse the response
 * @param uriInfo the URI context
 * @param resource the resource
 */
public void addHttpHeaderToResponseStream(final HttpServletResponse servletResponse, final UriInfo uriInfo,
        final FedoraResource resource) {

    getUriAwareHttpHeaderFactories().forEach((bean, factory) -> {
        LOGGER.debug("Adding HTTP headers using: {}", bean);
        final Multimap<String, String> h = factory.createHttpHeadersForResource(uriInfo, resource);

        h.entries().forEach(entry -> {
            servletResponse.addHeader(entry.getKey(), entry.getValue());
        });
    });
}

From source file:mx.gob.cfe.documentos.web.OficioController.java

private void generaReporte(String tipo, List<Documento> documentos, HttpServletResponse response)
        throws JRException, IOException {
    log.debug("Generando reporte {}", tipo);
    byte[] archivo = null;
    switch (tipo) {
    case "PDF":
        archivo = generaPdf(documentos);
        response.setContentType("application/pdf");
        response.addHeader("Content-Disposition", "attachment; filename=oficio.pdf");
        break;/*www . j a va 2s.c o m*/

    }
    if (archivo != null) {
        response.setContentLength(archivo.length);
        try (BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream())) {
            bos.write(archivo);
            bos.flush();
        }
    }

}

From source file:org.ow2.proactive.workflow_catalog.rest.controller.WorkflowController.java

@ApiOperation(value = "Gets a workflow's metadata by IDs", notes = "Returns metadata associated to the latest revision of the workflow.")
@ApiResponses(value = @ApiResponse(code = 404, message = "Bucket or workflow not found"))
@RequestMapping(value = "/buckets/{bucketId}/workflows/{idList}", method = GET)
public ResponseEntity<?> get(@PathVariable Long bucketId, @PathVariable List<Long> idList,
        @ApiParam(value = "Force response to return workflow XML content when set to 'xml'. Or extract workflows as ZIP when set to 'zip'.") @RequestParam(required = false) Optional<String> alt,
        HttpServletResponse response) throws MalformedURLException {
    if (alt.isPresent() && ZIP_EXTENSION.equals(alt.get())) {
        byte[] zip = workflowService.getWorkflowsAsArchive(bucketId, idList);

        response.setStatus(HttpServletResponse.SC_OK);
        response.setContentType("application/zip");
        response.addHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"archive.zip\"");
        response.addHeader(HttpHeaders.CONTENT_ENCODING, "binary");
        try {// w ww. j a v a  2 s  .c o m
            response.getOutputStream().write(zip);
            response.getOutputStream().flush();
        } catch (IOException ioe) {
            throw new RuntimeException(ioe);
        }
        return ResponseEntity.ok().build();
    } else {
        if (idList.size() == 1) {
            return workflowService.getWorkflowMetadata(bucketId, idList.get(0), alt);
        } else {
            return ResponseEntity.badRequest().build();
        }
    }
}