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.gsr.myschool.server.reporting.excel.ExcelController.java

@RequestMapping(method = RequestMethod.GET, value = "/excel/multidossier", produces = "application/vnd.ms-excel")
public void generateMultiDossierExcel(@RequestParam String q, @RequestParam String annee,
        HttpServletResponse response) {
    DossierStatus status = Strings.isNullOrEmpty(q) ? null : DossierStatus.valueOf(q);
    List<DossierMultiple> dossierMultiples = dossierService.findMultipleDossierByStatus(status, annee);

    try {/*from   w  w  w .  j ava2 s . co  m*/
        response.addHeader("Content-Disposition",
                "attachment; filename=multidossier_" + System.currentTimeMillis() + ".xls");

        BufferedOutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
        xlsExportService.saveSpreadsheetRecords(DossierMultiple.class, dossierMultiples, outputStream);

        outputStream.flush();
        outputStream.close();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:tv.arte.resteventapi.core.presentation.decoration.ResponseHeadersAspect.java

@Around("execution(public * tv.arte.resteventapi.web.controllers.*.*(..)) && @annotation(tv.arte.resteventapi.core.presentation.decoration.HrefedLocationHeader)")
public Object handleLocationHeaders(ProceedingJoinPoint pjp) throws Throwable {

    Object result = pjp.proceed();

    if (result != null && result instanceof Locationable) {
        String href = RestEventApiDecorationProvider
                .getLocationUrl(((Locationable) result).getLocationableInstance());
        if (StringUtils.isNotBlank(href)) {

            HttpServletResponse response = null;

            if (pjp.getArgs() != null && pjp.getArgs().length > 0) {
                for (Object methodArg : pjp.getArgs()) {
                    if (methodArg instanceof HttpServletResponse) {
                        response = (HttpServletResponse) methodArg;
                        break;
                    }/*w w  w  .ja v  a2s .c o m*/
                }
            }

            if (response != null) {
                response.addHeader("Location", href);
            }
        }
    }

    return result;
}

From source file:com.boxedfolder.carrot.config.general.filter.CORSFilter.java

@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
        throws IOException, ServletException {
    HttpServletResponse response = (HttpServletResponse) res;
    HttpServletRequest request = (HttpServletRequest) req;

    response.setHeader("Access-Control-Allow-Origin", "*");
    response.setHeader("Access-Control-Allow-Methods", "POST, GET,  DELETE, PUT");
    response.setHeader("Access-Control-Max-Age", "3600");
    response.setHeader("Access-Control-Allow-Headers",
            "Accept, Content-Type, Origin, Authorization, x-auth-token");
    response.addHeader("Access-Control-Expose-Headers", "x-auth-token");

    if (request.getMethod().equals("OPTIONS")) {
        try {/*from  www . j  a  v a 2  s. c  o m*/
            response.getWriter().print("OK");
            response.getWriter().flush();
        } catch (IOException e) {
            Logger log = LoggerFactory.getLogger(getClass());
            log.error("Exception thrown: " + e.getMessage());
        }
    } else {
        chain.doFilter(request, response);
    }
}

From source file:com.jwt.exceptions.GlobalExceptionHandler.java

@ExceptionHandler()
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
@ResponseBody// w w w  . j  ava  2 s  .  c  om
public ErrorResponse handleException(Exception exception, HttpServletResponse httpResponse) {
    exception.printStackTrace();

    ErrorResponse errorResponse = errorResponseFactory.getErrorResponse();
    if (errorResponse != null && errorResponse.getMessage() == null) {
        String msg = messageProvider.getDefaultErrorMessage();
        errorResponse = ErrorResponse.of(msg, GlobalErrCodes.GLOBAL, HttpStatus.INTERNAL_SERVER_ERROR);
    }
    errorResponseFactory.unregisterErrorResponse();

    httpResponse.addHeader("IS-FLASH", "true");
    return errorResponse;
}

From source file:com.lingxiang2014.controller.shop.CommonController.java

@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();
    }//  w w w  .ja v a 2s .co  m
    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:edu.cornell.mannlib.vitro.webapp.filters.CachingResponseFilter.java

private void produceUncacheableResponse(HttpServletRequest req, HttpServletResponse resp, FilterChain chain)
        throws IOException, ServletException {
    String etag = generateArbitraryUniqueEtag(req);
    log.debug("Produce uncacheable response: etag='" + etag + "'");

    resp.addHeader("ETag", etag);
    resp.addHeader("Vary", "*");
    resp.addHeader("Cache-Control", "no-store");
    chain.doFilter(req, resp);/* ww  w .ja v  a2s  .co m*/
}

From source file:com.appleframework.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());
    }/*www .j a v  a 2  s.  co  m*/
}

From source file:org.epics.archiverappliance.utils.ui.GetUrlContent.java

/**
 * Get the contents of a redirect URL and use as reponse for the provided HttpServletResponse.
 * If possible, pass in error responses as well.
 * @param redirectURIStr  &emsp;  //from w w  w.  java2  s.c  o m
 * @param resp  HttpServletResponse 
 * @throws IOException  &emsp; 
 */
public static void proxyURL(String redirectURIStr, HttpServletResponse resp) throws IOException {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    HttpGet getMethod = new HttpGet(redirectURIStr);
    getMethod.addHeader("Connection", "close"); // https://www.nuxeo.com/blog/using-httpclient-properly-avoid-closewait-tcp-connections/
    try (CloseableHttpResponse response = httpclient.execute(getMethod)) {
        if (response.getStatusLine().getStatusCode() == 200) {
            HttpEntity entity = response.getEntity();

            HashSet<String> proxiedHeaders = new HashSet<String>();
            proxiedHeaders.addAll(Arrays.asList(MimeResponse.PROXIED_HEADERS));
            Header[] headers = response.getAllHeaders();
            for (Header header : headers) {
                if (proxiedHeaders.contains(header.getName())) {
                    logger.debug("Adding headerName " + header.getName() + " and value " + header.getValue()
                            + " when proxying request");
                    resp.addHeader(header.getName(), header.getValue());
                }
            }

            if (entity != null) {
                logger.debug("Obtained a HTTP entity of length " + entity.getContentLength());
                try (OutputStream os = resp.getOutputStream();
                        InputStream is = new BufferedInputStream(entity.getContent())) {
                    byte buf[] = new byte[10 * 1024];
                    int bytesRead = is.read(buf);
                    while (bytesRead > 0) {
                        os.write(buf, 0, bytesRead);
                        resp.flushBuffer();
                        bytesRead = is.read(buf);
                    }
                }
            } else {
                throw new IOException("HTTP response did not have an entity associated with it");
            }
        } else {
            logger.error("Invalid status code " + response.getStatusLine().getStatusCode()
                    + " when connecting to URL " + redirectURIStr + ". Sending the errorstream across");
            try (ByteArrayOutputStream os = new ByteArrayOutputStream()) {
                try (InputStream is = new BufferedInputStream(response.getEntity().getContent())) {
                    byte buf[] = new byte[10 * 1024];
                    int bytesRead = is.read(buf);
                    while (bytesRead > 0) {
                        os.write(buf, 0, bytesRead);
                        bytesRead = is.read(buf);
                    }
                }
                resp.addHeader(MimeResponse.ACCESS_CONTROL_ALLOW_ORIGIN, "*");
                resp.sendError(response.getStatusLine().getStatusCode(), new String(os.toByteArray()));
            }
        }
    }
}

From source file:fr.littlereddot.pocket.site.controller.account.ConnectAccountController.java

private void setNoCache(NativeWebRequest request) {
    HttpServletResponse response = request.getNativeResponse(HttpServletResponse.class);
    if (response != null) {
        response.setHeader("Pragma", "no-cache");
        response.setDateHeader("Expires", 1L);
        response.setHeader("Cache-Control", "no-cache");
        response.addHeader("Cache-Control", "no-store");
    }//from  w w  w. j a v a  2 s  . c om
}

From source file:org.apereo.openlrs.XAPIHeaderFilter.java

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
        FilterChain filterChain) throws ServletException, IOException {

    String allowedRequestHeaders = request.getHeader("Access-Control-Request-Headers");
    String responseHeader = Constants.XAPI_VERSION_HEADER;

    if (StringUtils.isNotBlank(allowedRequestHeaders)) {
        if (StringUtils.contains(allowedRequestHeaders, Constants.XAPI_VERSION_HEADER.toLowerCase())) {
            responseHeader = responseHeader.toLowerCase();
        }//  w ww  .  j  a va  2s. c  om
    }

    response.addHeader(responseHeader, version);
    filterChain.doFilter(request, response);
}