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:it.polimi.diceH2020.launcher.controller.DownloadsController.java

private void respondWithZipFile(@NotNull Map<String, String> files, @NotNull HttpServletResponse response) {
    File zipPath = null;/*from  w  ww.j av a2  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 {
            InputStream is = 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:fr.xebia.servlet.filter.ExpiresFilterTest.java

@Test
public void testExcludedResponseStatusCode() throws Exception {
    HttpServlet servlet = new HttpServlet() {
        private static final long serialVersionUID = 1L;

        @Override/*from  www  .  j ava 2 s  .  co m*/
        protected void service(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
            response.addHeader("ETag", "W/\"1934-1269208821000\"");
            response.addDateHeader("Date", System.currentTimeMillis());
        }
    };

    validate(servlet, null, HttpServletResponse.SC_NOT_MODIFIED);
}

From source file:com.yunmel.syncretic.utils.io.IOUtils.java

/**
 * /* w w w . j  a  v  a  2s . c  o m*/
 * 
 * @param filePath 
 * @param fileName ??
 * @param inline ??
 * @throws Exception
 */
public static void downloadFile(HttpServletResponse response, File file, String fileName, boolean inline)
        throws Exception {

    OutputStream outp = null;
    FileInputStream br = null;
    int len = 0;
    try {
        br = new FileInputStream(file);
        response.reset();
        outp = response.getOutputStream();
        outp.flush();
        response.setContentType("application/octet-stream");
        response.setContentLength((int) file.length());
        String header = (inline ? "inline" : "attachment") + ";filename="
                + new String(fileName.getBytes(), "ISO8859-1");
        response.addHeader("Content-Disposition", header);
        byte[] buf = new byte[1024];
        while ((len = br.read(buf)) != -1) {
            outp.write(buf, 0, len);
        }
        outp.flush();
        outp.close();
    } finally {
        if (br != null) {
            if (0 == br.available()) {
                br.close();
            }
        }
    }

}

From source file:com.adobe.acs.commons.http.headers.impl.AbstractDispatcherCacheHeaderFilter.java

@Override
public final void doFilter(final ServletRequest servletRequest, final ServletResponse servletResponse,
        final FilterChain filterChain) throws IOException, ServletException {

    if (!(servletRequest instanceof HttpServletRequest) || !(servletResponse instanceof HttpServletResponse)) {
        filterChain.doFilter(servletRequest, servletResponse);
        return;//from   ww  w .jav  a2  s. com
    }

    final HttpServletRequest request = (HttpServletRequest) servletRequest;
    final HttpServletResponse response = (HttpServletResponse) servletResponse;

    if (this.accepts(request)) {
        String header = getHeaderName();
        String val = getHeaderValue();
        String attributeName = AbstractDispatcherCacheHeaderFilter.class.getName() + ".header." + header;
        if (request.getAttribute(attributeName) == null) {
            log.debug("Adding header {}: {}", header, val);
            response.addHeader(header, val);
            request.setAttribute(attributeName, MARKER);
        } else {
            log.debug("Header {} was already set. Skipping.", header);
        }
    }
    filterChain.doFilter(request, response);
}

From source file:com.groupon.odo.controllers.BackupController.java

/**
 * API call to backup active overreides and active server group for a client
 * Can also backup entire odo configuration
 *
 * @param model//from w  w w. j  a  va 2  s  .co m
 * @param response
 * @param profileID Id of profile to backup
 * @param clientUUID Client Id to backup
 * @param odoExport Flag to also include whole odo backup in client backpu
 * @return
 * @throws Exception
 */

@SuppressWarnings("deprecation")
@RequestMapping(value = "/api/backup/profile/{profileID}/{clientUUID}", method = RequestMethod.GET)
public @ResponseBody String getSingleProfileConfiguration(Model model, HttpServletResponse response,
        @PathVariable int profileID, @PathVariable String clientUUID,
        @RequestParam(value = "odoExport", defaultValue = "false") boolean odoExport) throws Exception {
    response.setContentType("application/json");

    ObjectMapper objectMapper = new ObjectMapper();
    ObjectWriter writer = objectMapper.writerWithDefaultPrettyPrinter();

    if (odoExport) {
        response.addHeader("Content-Disposition", "attachment; filename=Config_and_Profile_Backup.json");
        ConfigAndProfileBackup configAndProfileBackup = BackupService.getInstance()
                .getConfigAndProfileData(profileID, clientUUID);
        return writer.withView(ViewFilters.Default.class).writeValueAsString(configAndProfileBackup);
    } else {
        response.addHeader("Content-Disposition", "attachment; filename=Enabled_Endpoints.json");
        SingleProfileBackup singleProfileBackup = BackupService.getInstance().getProfileBackupData(profileID,
                clientUUID);
        return writer.withView(ViewFilters.Default.class).writeValueAsString(singleProfileBackup);
    }
}

From source file:tds.student.web.filter.ConcurrentRequestLimitFilter.java

@Override
protected void doFilterInternal(final HttpServletRequest request, final HttpServletResponse response,
        final FilterChain filterChain) throws ServletException, IOException {
    final int currentRequest = concurrentRequests.incrementAndGet();
    try {//ww  w  . ja  v  a2s . c  o  m
        if (maxConcurrentRequests < 0 || currentRequest <= maxConcurrentRequests) {
            filterChain.doFilter(request, response);
        } else {
            LOG.error("Rejecting request due to too many concurrent requests: {}, {}/{}",
                    request.getRequestURI(), currentRequest, maxConcurrentRequests);
            response.addHeader(HttpHeaders.RETRY_AFTER, "30");
            response.sendError(503, "Too many requests");
        }
    } finally {
        concurrentRequests.decrementAndGet();
    }
}

From source file:org.jdal.samples.mvc.BookController.java

@RequestMapping("/getData")
public void getData(HttpServletResponse response, @ModelAttribute DataTableModel dtm,
        @ModelAttribute Filter filter) throws IOException {

    Page<Object> page = dtm.buildPage();
    page.setFilter(filter);/* w ww . j  a  va 2 s  . c  om*/
    bookService.getPage(page);
    dtm.setRecords(bookModelMapper.fromModel(page.getData()));
    dtm.setTotalRecords(page.getCount());

    JSON json = JSONSerializer.toJSON(dtm);
    // write json string to response
    response.addHeader("Pragma", "no-cache");
    response.addHeader("Cache-Control", "no-cache"); // HTTP/1.1
    response.addHeader("Cache-Control", "no-store"); // HTTP/1.1
    response.addHeader("Cache-Control", "must-revalidate"); // HTTP/1.1

    response.setContentType("application/x-json;charset=UTF-8");

    json.write(response.getWriter());
}

From source file:eu.semlibproject.annotationserver.filters.CORSFilter.java

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    if (filterEnabled) {
        HttpServletResponse resp = (HttpServletResponse) response;
        HttpServletRequest req = (HttpServletRequest) request;

        // Try to set the servlet context path (used to overcome
        // limit of servlet containers that does not support sevlet
        // specification >= 2.5
        super.setServletContextPath(req);

        String origin = req.getHeader("Origin");
        if (origin != null && !origin.equals("")) {
            allowOrigin = origin;/*from   ww  w  .  j  a  v a2 s .  c o m*/
        }

        resp.addHeader("Access-Control-Allow-Origin", allowOrigin);
        resp.addHeader("Access-Control-Allow-Methods", supportedMethods);
        resp.addHeader("Access-Control-Allow-Headers", supportedHeaders);
        resp.addHeader("Access-Control-Allow-Credentials", supportsCredentials);
        chain.doFilter(request, resp);
    } else {
        chain.doFilter(request, response);
    }
}

From source file:com.sammyun.controller.console.CommonController.java

/**
 * ??/*from w  ww.  j a v a2s .co  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("moc").append(".").append("oc-om.").append("www").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);
    }
}