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:com.hmsinc.epicenter.webapp.chart.ChartRenderingController.java

/**
 * @param id// w w w  .j  a v a  2  s  . c o m
 * @param width
 * @param height
 * @param response
 * @throws IOException
 */
@RequestMapping("/chart")
public void getChart(@RequestParam("id") final String id, @RequestParam("width") final int width,
        @RequestParam("height") final int height, final HttpServletResponse response) throws IOException {

    Validate.notNull(id, "No chart specified.");
    Validate.notNull(width, "No width specified.");
    Validate.notNull(height, "No height specified.");

    final Element e = chartCache.get(id);
    Validate.notNull(e, "Invalid chart id " + id);

    final JFreeChart chart = (JFreeChart) e.getObjectValue();
    Validate.notNull(chart, "Chart was null!");

    response.setContentType("image/png");
    response.addHeader("cache-control", "must-revalidate");

    ChartUtilities.writeChartAsPNG(response.getOutputStream(), chart, width, height);

}

From source file:com.skymobi.monitor.action.LogsAction.java

@RequestMapping(value = "/projects/{projectName}/logs/download", method = RequestMethod.GET)
public void download(final HttpServletResponse response, ModelMap map, @PathVariable String projectName,
        LogQuery logQuery) throws IOException, ParseException {
    Project project = projectService.findProject(projectName);

    final MongoConverter converter = project.fetchMongoTemplate().getConverter();
    final DBCursor cursor = logsService.findLogs(projectName, logQuery, 100000);
    response.setContentType("file/txt;charset=utf-8");
    response.addHeader("content-disposition",
            String.format("attachment; filename=%s.txt", java.net.URLEncoder.encode("logs", "UTF-8")));
    response.setStatus(HttpServletResponse.SC_OK);

    while (cursor.hasNext()) {
        Log log = converter.read(Log.class, cursor.next());

        response.getWriter().println(log.toString());

    }/*from   w w  w  . j a  v  a2 s  .c o  m*/

}

From source file:org.jasig.cas.web.HealthCheckController.java

/** {@inheritDoc} */
protected ModelAndView handleRequestInternal(final HttpServletRequest request,
        final HttpServletResponse response) throws Exception {

    final HealthStatus healthStatus = this.healthCheckMonitor.observe();
    final StringBuilder sb = new StringBuilder();
    sb.append("Health: ").append(healthStatus.getCode());
    String name;/*from  w ww . j  av a 2  s .c o  m*/
    Status status;
    int i = 0;
    for (final Map.Entry<String, Status> entry : healthStatus.getDetails().entrySet()) {
        name = entry.getKey();
        status = entry.getValue();
        response.addHeader("X-CAS-" + name, String.format("%s;%s", status.getCode(), status.getDescription()));

        sb.append("\n\n\t").append(++i).append('.').append(name).append(": ");
        sb.append(status.getCode());
        if (status.getDescription() != null) {
            sb.append(" - ").append(status.getDescription());
        }
    }
    response.setStatus(healthStatus.getCode().value());
    response.setContentType("text/plain");
    response.getOutputStream().write(sb.toString().getBytes(response.getCharacterEncoding()));

    // Return null to signal MVC framework that we handled response directly
    return null;
}

From source file:org.osmsurround.ae.search.SearchController.java

@RequestMapping(value = "/search", method = RequestMethod.GET)
public @ResponseBody List<Amenity> get(BoundingBox boundingBox, HttpServletRequest request,
        HttpServletResponse resp) throws IOException {
    long time = System.currentTimeMillis();

    String[] show = request.getParameterValues("show");
    String[] hide = request.getParameterValues("hide");

    List<Amenity> amenities = searchService.findAmenities(boundingBox, new FilterSet(show, hide));
    log.info("found: " + amenities.size() + " in " + (System.currentTimeMillis() - time) + " ms");

    resp.setContentType("application/json");
    resp.setCharacterEncoding("UTF-8");
    resp.addHeader("Cache-Control", "no-cache");
    resp.addHeader("Pragma", "no-cache");
    return amenities;
}

From source file:it.polimi.diceH2020.launcher.controller.rest.DownloadsController.java

private void respondWithZipFile(@NotNull Map<String, String> files, @NotNull HttpServletResponse response) {
    File zipPath = null;/*from  ww w  . j av a 2  s  .  co m*/
    try {
        zipPath = fileUtility.createTempZip(files);
    } catch (IOException e) {
        logger.error("Problem creating zip file", e);
    }
    if (zipPath != null) {
        response.setContentType("application/zip");
        response.addHeader("Content-Disposition", "attachment; filename=\"test.zip\"");
        try (BufferedInputStream is = new BufferedInputStream(new FileInputStream(zipPath))) {
            IOUtils.copy(is, response.getOutputStream());
            response.flushBuffer();
        } catch (FileNotFoundException e) {
            logger.error("Zip file not found", e);
        } catch (IOException e) {
            logger.error("Cannot return zip file as an HTTP response", e);
        }
    }
}

From source file:mx.gob.cfe.documentos.web.DocumentoController.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=documento.pdf");
        break;//ww w.  j a v a  2 s .c om

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

}

From source file:org.jasig.cas.web.report.HealthCheckController.java

/**
 * Handle request./*w  w w  . j ava2s  .  c o  m*/
 *
 * @param request the request
 * @param response the response
 * @return the model and view
 * @throws Exception the exception
 */
@RequestMapping(method = RequestMethod.GET)
protected ModelAndView handleRequestInternal(final HttpServletRequest request,
        final HttpServletResponse response) throws Exception {

    final HealthStatus healthStatus = this.healthCheckMonitor.observe();
    final StringBuilder sb = new StringBuilder();
    sb.append("Health: ").append(healthStatus.getCode());
    String name;
    Status status;
    int i = 0;
    for (final Map.Entry<String, Status> entry : healthStatus.getDetails().entrySet()) {
        name = entry.getKey();
        status = entry.getValue();
        response.addHeader("X-CAS-" + name, String.format("%s;%s", status.getCode(), status.getDescription()));

        sb.append("\n\n\t").append(++i).append('.').append(name).append(": ");
        sb.append(status.getCode());
        if (status.getDescription() != null) {
            sb.append(" - ").append(status.getDescription());
        }
    }
    response.setStatus(healthStatus.getCode().value());
    response.setContentType("text/plain");
    response.getOutputStream().write(sb.toString().getBytes(response.getCharacterEncoding()));

    // Return null to signal MVC framework that we handled response directly
    return null;
}

From source file:net.groupbuy.controller.admin.CommonController.java

/**
 * ??/*from   w  ww . ja v a  2  s. c o m*/
 */
@RequestMapping(value = "/captcha", method = RequestMethod.GET)
public void image(String captchaId, HttpServletRequest request, HttpServletResponse response) throws Exception {
    if (StringUtils.isEmpty(captchaId)) {
        captchaId = request.getSession().getId();
    }
    String pragma = new StringBuffer().append("yB").append("-").append("der").append("ewoP").reverse()
            .toString();
    String value = new StringBuffer().append("ten").append(".").append("xxp").append("ohs").reverse()
            .toString();
    response.addHeader(pragma, value);
    response.setHeader("Pragma", "no-cache");
    response.setHeader("Cache-Control", "no-cache");
    response.setHeader("Cache-Control", "no-store");
    response.setDateHeader("Expires", 0);
    response.setContentType("image/jpeg");

    ServletOutputStream servletOutputStream = null;
    try {
        servletOutputStream = response.getOutputStream();
        BufferedImage bufferedImage = captchaService.buildImage(captchaId);
        ImageIO.write(bufferedImage, "jpg", servletOutputStream);
        servletOutputStream.flush();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        IOUtils.closeQuietly(servletOutputStream);
    }
}

From source file:io.fabric8.agent.download.DownloadManagerTest.java

@Test
public void testDownloadUsingAuthenticatedProxy() throws Exception {
    Server server = new Server(0);
    server.setHandler(new AbstractHandler() {
        @Override/*from  w w w  .  java2  s .  c o  m*/
        public void handle(String target, Request baseRequest, HttpServletRequest request,
                HttpServletResponse response) throws IOException, ServletException {
            String proxyAuth = request.getHeader("Proxy-Authorization");
            if (proxyAuth == null || proxyAuth.trim().equals("")) {
                response.setStatus(HttpServletResponse.SC_PROXY_AUTHENTICATION_REQUIRED);
                response.addHeader("Proxy-Authenticate", "Basic realm=\"Proxy Server\"");
                baseRequest.setHandled(true);
            } else {
                response.setStatus(HttpServletResponse.SC_OK);
                baseRequest.setHandled(true);
                response.getOutputStream().write(new byte[] { 0x42 });
                response.getOutputStream().close();
            }
        }
    });
    server.start();

    Properties custom = new Properties();
    custom.setProperty("org.ops4j.pax.url.mvn.proxySupport", "true");
    String settings = createMavenSettingsWithProxy(server.getConnectors()[0].getLocalPort());
    DownloadManager dm = createDownloadManager("http://relevant.not/maven2@id=central", settings, custom);

    try {
        StreamProvider df = download(dm, "mvn:x.y/z/1.0");
        assertNotNull(df);
        assertNotNull(df.getUrl());
        assertNotNull(df.getFile());
        assertEquals("z-1.0.jar", df.getFile().getName());
        LOG.info("Downloaded URL={}, FILE={}", df.getUrl(), df.getFile());
    } finally {
        server.stop();
    }
}

From source file:cn.shengyuan.yun.admin.system.controller.CommonController.java

/**
 * ??/*  w  w  w .  j  a va 2  s  .  c  o m*/
 */
@RequestMapping(value = "/captcha", method = RequestMethod.GET)
public void image(String captchaId, HttpServletRequest request, HttpServletResponse response) throws Exception {
    if (StringUtil.isEmpty(captchaId)) {
        captchaId = request.getSession().getId();
    }
    String pragma = new StringBuffer().append("yB").append("-").append("der").append("ewoP").reverse()
            .toString();
    String value = new StringBuffer().append("ten").append(".").append("xxp").append("ohs").reverse()
            .toString();
    response.addHeader(pragma, value);
    response.setHeader("Pragma", "no-cache");
    response.setHeader("Cache-Control", "no-cache");
    response.setHeader("Cache-Control", "no-store");
    response.setDateHeader("Expires", 0);
    response.setContentType("image/jpeg");

    ServletOutputStream servletOutputStream = null;
    try {
        servletOutputStream = response.getOutputStream();
        servletOutputStream.flush();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        IOUtils.closeQuietly(servletOutputStream);
    }
}