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.apache.sling.etcd.client.impl.EtcdClientImplTest.java

@Test
public void testMultiValueHeader() throws Exception {
    HttpServlet servlet = new HttpServlet() {
        @Override/*from   w  w w.  jav a2s  .  c  o m*/
        protected void service(HttpServletRequest req, HttpServletResponse res)
                throws ServletException, IOException {
            res.addHeader("headerName", "value1");
            res.addHeader("headerName", "value2");
            res.getWriter().write(IOUtils.toString(getClass().getResourceAsStream("/action-1.json")));
        }
    };
    server1 = startServer(servlet, "/v2/keys/test");
    buildEtcdClient(serverPort(server1));
    KeyResponse response = etcdClient.putKey("/test", "test-data", EtcdParams.builder().ttl(10).build());
    Assert.assertNotNull(response.headers());
    Assert.assertNotNull(response.header("headerName"));
    List<String> headers = response.header("headerName");
    Assert.assertEquals(2, headers.size());
    Assert.assertEquals("value1", headers.get(0));
    Assert.assertEquals("value2", headers.get(1));
    Assert.assertEquals("value1", response.headerFirst("headerName"));
}

From source file:sys.core.manager.RecursosManager.java

public String viewReportePdf(HashMap hmParametros, String reporte, String nombreArchivo)
        throws FileNotFoundException, JRException, IOException, SQLException {
    InputStream ie = null;/*from ww  w  .ja va2s. c o m*/
    Connection c = null;
    try {
        ApplicationMBean applicationMBean = (ApplicationMBean) WebServletContextListener.getApplicationContext()
                .getBean("applicationMBean");
        File file = new File(applicationMBean.getRutaJaspers());
        ie = new FileInputStream(new File(file, reporte + ".jasper"));
        c = applicationMBean.obtenerConexionDataBase();
        if (c != null) {
            logger.info("P_DIRECTORIO_REPORTES: " + file.getCanonicalPath() + File.separator);
            hmParametros.put("P_DIRECTORIO_REPORTES", file.getCanonicalPath() + File.separator);
            hmParametros.put(JRParameter.REPORT_LOCALE, new Locale("es_PE"));
            hmParametros.put(JRParameter.REPORT_TIME_ZONE, applicationMBean.getTimeZone());
            JasperPrint jasperPrint = JasperFillManager.fillReport(ie, hmParametros, c);
            logger.info("el jasperProcesado: " + jasperPrint.toString());
            byte[] bytes = JasperExportManager.exportReportToPdf(jasperPrint);
            FacesContext context = FacesContext.getCurrentInstance();
            HttpServletResponse response = (HttpServletResponse) context.getExternalContext().getResponse();
            response.addHeader("Content-disposition", "attachment;filename=" + nombreArchivo);
            response.setContentLength(bytes.length);
            response.getOutputStream().write(bytes);
            response.setContentType("application/pdf");
            context.responseComplete();
        } else {
            logger.error("NO SE PUEDO EJECUTAR LA IMPRESION LA CONEXION ES NULA");
        }

        return null;
    } catch (JRException ex) {
        logger.error("Error al rellenar el reporte " + ex.getMessage());
        logger.error(ex);
    } catch (IOException ex) {
        logger.error("Error al leer el jasper " + ex.getMessage());
        logger.error(ex);
    } catch (Throwable ex) {
        logger.error("Otros errores con el jasper " + ex.getMessage());
        logger.error(ex);
    } finally {
        try {
            if (c != null) {
                c.close();
            }
            if (ie != null) {
                ie.close();
            }
        } catch (IOException ex) {
            logger.error(ex);
        }
        return null;
    }

}

From source file:com.gsr.myschool.server.reporting.bilan.SummaryController.java

@RequestMapping(method = RequestMethod.GET, produces = "application/vnd.ms-excel")
@ResponseStatus(HttpStatus.OK)/*from   www . j  a v a  2  s  .  c  o  m*/
public void generateBilan(@RequestParam(required = false) String annee, HttpServletResponse response) {
    ValueList anneeScolaire;

    try {
        anneeScolaire = valueListRepos.findByValueAndValueTypeCode(annee, ValueTypeCode.SCHOOL_YEAR);
        if (anneeScolaire == null) {
            anneeScolaire = getCurrentScholarYear();
        }
    } catch (Exception e) {
        return;
    }

    List<SummaryExcelDTO> dto = getReportSummary(anneeScolaire);

    try {
        response.addHeader("Content-Disposition", "attachment; filename=summary.xls");

        BufferedOutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
        xlsExportService.saveSpreadsheetRecords(SummaryExcelDTO.class, dto, outputStream);
        outputStream.flush();
        outputStream.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:ee.ria.xroad.proxy.serverproxy.ServerProxyHandler.java

@Override
public void handle(String target, Request baseRequest, final HttpServletRequest request,
        final HttpServletResponse response) throws IOException, ServletException {
    OpMonitoringData opMonitoringData = new OpMonitoringData(PRODUCER, getEpochMillisecond());

    long start = PerformanceLogger.log(log, "Received request from " + request.getRemoteAddr());

    if (!SystemProperties.isServerProxySupportClientsPooledConnections()) {
        // if the header is added, the connections are closed and cannot be reused on the client side
        response.addHeader("Connection", "close");
    }//  ww  w .  j  av  a 2  s .  c o m

    try {
        if (!request.getMethod().equalsIgnoreCase("POST")) {
            throw new CodedException(X_INVALID_HTTP_METHOD, "Must use POST request method instead of %s",
                    request.getMethod());
        }

        GlobalConf.verifyValidity();

        logProxyVersion(request);

        ServerMessageProcessor processor = createRequestProcessor(request, response, start, opMonitoringData);
        processor.process();
    } catch (Throwable e) { // We want to catch serious errors as well
        CodedException cex = translateWithPrefix(SERVER_SERVERPROXY_X, e);

        log.error("Request processing error ({})", cex.getFaultDetail(), e);

        opMonitoringData.setSoapFault(cex);

        failure(response, cex);
    } finally {
        baseRequest.setHandled(true);

        opMonitoringData.setResponseOutTs(getEpochMillisecond());
        OpMonitoring.store(opMonitoringData);

        PerformanceLogger.log(log, start, "Request handled");
    }
}

From source file:org.realityforge.proxy_servlet.AbstractProxyServlet.java

/**
 * Copy proxied response headers back to the servlet client.
 *///from w ww.j  a  v a2s  . co m
private void copyResponseHeaders(final HttpResponse proxyResponse, final HttpServletResponse servletResponse) {
    for (final Header header : proxyResponse.getAllHeaders()) {
        if (HOP_BY_HOP_HEADERS.containsHeader(header.getName())) {
            continue;
        }
        servletResponse.addHeader(header.getName(), header.getValue());
    }
}

From source file:at.gv.egovernment.moa.id.auth.servlet.VerifyCertificateServlet.java

/**
 * GET requested by security layer implementation to verify
 * that data URL resource is available.//from w ww .  j a  v  a  2s . co m
 * @see javax.servlet.http.HttpServlet#doGet(HttpServletRequest, HttpServletResponse)
 */
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    Logger.debug("GET VerifyCertificateServlet");

    resp.setHeader(MOAIDAuthConstants.HEADER_EXPIRES, MOAIDAuthConstants.HEADER_VALUE_EXPIRES);
    resp.setHeader(MOAIDAuthConstants.HEADER_PRAGMA, MOAIDAuthConstants.HEADER_VALUE_PRAGMA);
    resp.setHeader(MOAIDAuthConstants.HEADER_CACHE_CONTROL, MOAIDAuthConstants.HEADER_VALUE_CACHE_CONTROL);
    resp.addHeader(MOAIDAuthConstants.HEADER_CACHE_CONTROL, MOAIDAuthConstants.HEADER_VALUE_CACHE_CONTROL_IE);
}

From source file:com.google.ie.web.view.GsonView.java

@Override
protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    String jsonResult = getJsonString(filterModel(model));

    // Write the result to response
    response.setContentType(contentType);
    response.setStatus(statusCode);/*from  w  ww.  j a  v  a2 s  . com*/
    response.setCharacterEncoding(characterEncoding);
    response.setHeader("Cache-Control", "no-cache");
    response.setHeader("Expires", "0");
    response.setHeader("Pragma", "No-cache");
    if (isGzipInRequest(request)) {
        response.addHeader("Content-Encoding", "gzip");
        GZIPOutputStream out = null;
        try {
            out = new GZIPOutputStream(response.getOutputStream());
            out.write(jsonResult.getBytes(characterEncoding));
        } finally {
            if (out != null) {
                out.finish();
                out.close();
            }
        }
    } else {
        response.getWriter().print(jsonResult);
    }

}

From source file:com.kolich.havalo.controllers.api.ObjectApi.java

private static final void streamHeaders(final DiskObject object, final HashedFileObject hfo,
        final HttpServletResponse response) {
    checkNotNull(hfo, "Hashed file object cannot be null.");
    // Validate that the File object still exists.
    if (!object.getFile().exists()) {
        throw new ObjectNotFoundException("Object not " + "found (file=" + object.getFile().getAbsolutePath()
                + ", key=" + hfo.getName() + ")");
    }//from  w w  w.j a v  a2 s .  co  m
    // Extract any response headers from this objects' meta data.
    final Map<String, List<String>> headers = hfo.getHeaders();
    // Always set the Content-Length header to the actual length of the
    // file on disk -- effectively overriding any "Content-Length" meta
    // data header set by the user in the PUT request.
    headers.put(CONTENT_LENGTH, Arrays.asList(Long.toString(object.getFile().length())));
    // Set the Content-Type header to a default if one was not set by
    // the consumer in the meta data.
    if (headers.get(CONTENT_TYPE) == null) {
        headers.put(CONTENT_TYPE, Arrays.asList(OCTET_STREAM_TYPE));
    }
    // Now, send all headers to the response stream.
    for (final Map.Entry<String, List<String>> entry : headers.entrySet()) {
        final String key = entry.getKey();
        for (final String value : entry.getValue()) {
            response.addHeader(key, value);
        }
    }
}

From source file:com.delpac.bean.OrdenRetiroBean.java

public void download(OrdenRetiro ord) throws SQLException, JRException, IOException {
    conexion con = new conexion();
    try {/*from w w  w  . j a v  a 2  s.  c o  m*/
        HashMap<String, Object> parametros = new HashMap<String, Object>();
        //Contexto
        FacesContext context = FacesContext.getCurrentInstance();
        ServletContext servleContext = (ServletContext) context.getExternalContext().getContext();
        //Parametros
        parametros.put("RutaImagen", servleContext.getRealPath("/reportes/"));
        parametros.put("cod_ordenretiro", ord.getCod_ordenretiro());
        //String del jasper
        String temperatura = ord.getEs_temperado() == 1 ? "ReporteFreezer.jasper" : "ReporteNoFreezer.jasper";
        //            String jrxmlPath = temperatura.equals("ReporteFreezer.jasper") ? "ReporteFreezer.jrxml" : "ReporteNoFreezer.jrxml";//server
        //InputStream
        //            InputStream is = new FileInputStream(servleContext.getRealPath("/reportes/") + jrxmlPath);//server
        String dirReporte = servleContext.getRealPath("/reportes/" + temperatura);
        String nom_archivo = "OR_BK_" + ord.getBooking() + ".pdf";
        //            String exportDir = System.getProperty("catalina.base") + "/OrdenesRetiro/";//server
        //            String exportPath = exportDir + nom_archivo;//server
        //JasperDesign
        //            JasperDesign design = JRXmlLoader.load(is);//server
        //            JasperReport jasperReport = JasperCompileManager.compileReport(design);//server
        //Servlet Response
        HttpServletResponse response = (HttpServletResponse) context.getExternalContext().getResponse();
        response.addHeader("Content-disposition", "attachment;filename=" + nom_archivo);
        response.setContentType("application/pdf");
        //            JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, parametros, con.getConnection());//server
        JasperPrint jasperPrint = JasperFillManager.fillReport(dirReporte, parametros, con.getConnection());
        //            JasperExportManager.exportReportToPdfFile(jasperPrint, exportPath); //server
        JasperExportManager.exportReportToPdfStream(jasperPrint, response.getOutputStream());
        context.responseComplete();
    } catch (Exception e) {
        System.err.println(e);
    }
    listadoOrdenes = daoOrdenRetiro.findAllOrdenes();
}

From source file:mx.edu.um.mateo.rh.web.DiaFeriadoController.java

private void generaReporte(String tipo, List<DiaFeriado> diaFeriados, HttpServletResponse response)
        throws JRException, IOException {
    log.debug("Generando reporte {}", tipo);
    byte[] archivo = null;
    switch (tipo) {
    case "PDF":
        archivo = generaPdf(diaFeriados);
        response.setContentType("application/pdf");
        response.addHeader("Content-Disposition", "attachment; filename=clavesEmpleado.pdf");
        break;/*from www .j  ava2  s.co  m*/
    case "CSV":
        archivo = generaCsv(diaFeriados);
        response.setContentType("text/csv");
        response.addHeader("Content-Disposition", "attachment; filename=clavesEmpleado.csv");
        break;
    case "XLS":
        archivo = generaXls(diaFeriados);
        response.setContentType("application/vnd.ms-excel");
        response.addHeader("Content-Disposition", "attachment; filename=clavesEmpleado.xls");
    }
    if (archivo != null) {
        response.setContentLength(archivo.length);
        try (BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream())) {
            bos.write(archivo);
            bos.flush();
        }
    }

}