Example usage for javax.servlet.http HttpServletResponse setHeader

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

Introduction

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

Prototype

public void setHeader(String name, String value);

Source Link

Document

Sets a response header with the given name and value.

Usage

From source file:net.duckling.ddl.web.bean.NginxAgent.java

/**
 * X-Accel-Redirectnignx// ww w .  j a  v  a 2 s. co  m
 * @param req
 * @param resp
 * @param fileName
 * @param fileSize
 * @param url
 */
public static void setRedirectUrl(HttpServletRequest req, HttpServletResponse resp, String fileName,
        long fileSize, String url) {
    if (fileSize > 0) {
        resp.addHeader(X_ACCEL_REDIRECT, url + "?agent="
                + Browser.recognizeBrowser(req.getHeader("USER-AGENT")).toString().toLowerCase());
    }

    // x_accel_redirect to nginx-clbs (gridfs) that
    // doesn't include Content-Disposition.
    // Set it here and the headers will be combined.
    resp.setHeader("Content-Disposition", Browser.encodeFileName(req.getHeader("USER-AGENT"), fileName));

}

From source file:org.ambraproject.wombat.util.HttpMessageUtil.java

/**
 * Copy content with whitelisted headers between responses. Headers already written to {@code responseTo} are
 * <em>not</em> overwritten if {@code responseFrom} has a header with the same name.
 *
 * @param responseFrom an incoming response to copy from
 * @param responseTo   an outgoing response to copy into
 * @param headerFilter describes whether and how to copy headers
 * @throws IOException// w ww. j  a  v a 2 s  .  c  o m
 */
public static void copyResponseWithHeaders(HttpResponse responseFrom, HttpServletResponse responseTo,
        HeaderFilter headerFilter) throws IOException {
    for (Header header : responseFrom.getAllHeaders()) {
        String headerName = header.getName();
        if (!responseTo.containsHeader(headerName)) {
            String newValue = headerFilter.getValue(header);
            if (newValue != null) {
                responseTo.setHeader(headerName, newValue);
            }
        }
    }
    copyResponse(responseFrom, responseTo);
}

From source file:org.openmrs.module.omodexport.util.OmodExportUtil.java

/**
 * Utility module for exporting all modules. The exported modules will be in a zip file called
 * "modules.zip"//from   w w  w.jav  a2s . c o  m
 * 
 * @param response
 * @throws IOException
 */
public static void exportAllModules(HttpServletResponse response) throws IOException {

    Collection<Module> modules = ModuleFactory.getStartedModules();
    List<File> files = new ArrayList<File>();
    for (Module module : modules) {
        files.add(module.getFile());
    }
    response.setContentType("application/zip");
    response.setHeader("Content-Disposition", "attachment; filename=\"modules.ZIP\"");

    ZipOutputStream out = new ZipOutputStream(response.getOutputStream());

    zipFiles(files, out);
}

From source file:com.jaspersoft.jasperserver.war.OlapGetChart.java

/**
 * Binary streams the specified file to the HTTP response in 1KB chunks
 *
 * @param file The file to be streamed.//from  ww w . j  a va2 s.  c o  m
 * @param response The HTTP response object.
 * @param mimeType The mime type of the file, null allowed.
 *
 * @throws IOException  if there is an I/O problem.
 * @throws FileNotFoundException  if the file is not found.
 */
public static void sendTempFile(File file, HttpServletResponse response, String mimeType)
        throws IOException, FileNotFoundException {

    if (file.exists()) {
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));

        //  Set HTTP headers
        if (mimeType != null) {
            response.setHeader("Content-Type", mimeType);
        }
        response.setHeader("Content-Length", String.valueOf(file.length()));
        SimpleDateFormat sdf = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z");
        response.setHeader("Last-Modified", sdf.format(new Date(file.lastModified())));

        BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream());
        byte[] input = new byte[1024];
        boolean eof = false;
        while (!eof) {
            int length = bis.read(input);
            if (length == -1) {
                eof = true;
            } else {
                bos.write(input, 0, length);
            }
        }
        bos.flush();
        bis.close();
        bos.close();
    } else {
        throw new FileNotFoundException(file.getAbsolutePath());
    }
    return;
}

From source file:jp.terasoluna.fw.web.struts.actions.FileDownloadUtil.java

/**
 * t@C?/*from   w ww  .  j  ava  2s  . com*/
 *
 * @param response X|X?B
 * @param name _E??[h?B
 * @param forceDownload ?_E??[h?B<code>true</code>???A??B
 */
protected static void setFileName(HttpServletResponse response, String name, boolean forceDownload) {

    if (forceDownload) {
        // LbV?IE?
        String contentDispositionValue = "attachment;" + " filename=" + name;
        response.setHeader(HEADER_CONTENT_DISPOSITION, contentDispositionValue);
    } else {
        String contentDispositionValue = "inline; filename=" + name;
        response.setHeader(HEADER_CONTENT_DISPOSITION, contentDispositionValue);
    }
}

From source file:ch.rasc.downloadchart.DownloadChartServlet.java

private static void handleJpg(HttpServletResponse response, byte[] imageData, Integer width, Integer height,
        String filename, JpegOptions options) throws IOException {

    response.setContentType("image/jpeg");
    response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + ".jpg\";");

    BufferedImage image = ImageIO.read(new ByteArrayInputStream(imageData));

    Dimension newDimension = calculateDimension(image, width, height);
    int imgWidth = image.getWidth();
    int imgHeight = image.getHeight();
    if (newDimension != null) {
        imgWidth = newDimension.width;// w  ww .  ja  v a 2  s  .  com
        imgHeight = newDimension.height;
    }

    BufferedImage newImage = new BufferedImage(imgWidth, imgHeight, BufferedImage.TYPE_INT_RGB);

    Graphics2D g = newImage.createGraphics();
    g.drawImage(image, 0, 0, imgWidth, imgHeight, Color.BLACK, null);
    g.dispose();

    if (newDimension != null) {
        g.setComposite(AlphaComposite.Src);
        g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
        g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    }

    try (ImageOutputStream ios = ImageIO.createImageOutputStream(response.getOutputStream())) {
        Iterator<ImageWriter> iter = ImageIO.getImageWritersByFormatName("jpg");
        ImageWriter writer = iter.next();
        ImageWriteParam iwp = writer.getDefaultWriteParam();
        iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
        if (options != null && options.quality != null && options.quality != 0 && options.quality != 100) {
            iwp.setCompressionQuality(options.quality / 100f);
        } else {
            iwp.setCompressionQuality(1);
        }
        writer.setOutput(ios);
        writer.write(null, new IIOImage(newImage, null, null), iwp);
        writer.dispose();
    }
}

From source file:com.adnature.framework.util.Struts2Utils.java

/**
 * .//  www  . j a  v  a 2s.c  o m
 * 
 * eg. <br/>
 * render("text/plain", "hello", "encoding:GBK"); <br/>
 * render("text/plain", "hello", "no-cache:false"); <br/>
 * render("text/plain", "hello", "encoding:GBK", "no-cache:false");
 * 
 * @param headers
 *            ??header??"encoding:""no-cache:",UTF-8true.
 */
public static void render(final String contentType, final String content, final String... headers) {
    try {
        // ?headers?
        String encoding = ENCODING_DEFAULT;
        boolean noCache = NOCACHE_DEFAULT;
        for (String header : headers) {
            String headerName = StringUtils.substringBefore(header, ":");
            String headerValue = StringUtils.substringAfter(header, ":");

            if (StringUtils.equalsIgnoreCase(headerName, ENCODING_PREFIX)) {
                encoding = headerValue;
            } else if (StringUtils.equalsIgnoreCase(headerName, NOCACHE_PREFIX)) {
                noCache = Boolean.parseBoolean(headerValue);
            } else {
                throw new IllegalArgumentException(headerName + "??header");
            }
        }

        HttpServletResponse response = ServletActionContext.getResponse();

        // headers?
        String fullContentType = contentType + ";charset=" + encoding;
        response.setContentType(fullContentType);
        if (noCache) {
            response.setHeader("Pragma", "No-cache");
            response.setHeader("Cache-Control", "no-cache");
            response.setDateHeader("Expires", 0);
        }

        response.getWriter().write(content);
        response.getWriter().flush();

    } catch (IOException e) {
        logger.error(e.getMessage(), e);
    }
}

From source file:ch.ralscha.extdirectspring.util.ExtDirectSpringUtil.java

/**
 * Adds Expires, ETag and Cache-Control response headers.
 *
 * @param response the HTTP servlet response
 * @param etag the calculated etag (md5) of the response
 * @param month number of months the response can be cached. Added to the Expires and
 * Cache-Control header. If null defaults to 6 months.
 *///from w  ww .  j  a v  a  2s  .  com
public static void addCacheHeaders(HttpServletResponse response, String etag, Integer month) {
    Assert.notNull(etag, "ETag must not be null");

    long seconds;
    if (month != null) {
        seconds = month * secondsInAMonth;
    } else {
        seconds = 6L * secondsInAMonth;
    }

    response.setDateHeader("Expires", System.currentTimeMillis() + seconds * 1000L);
    response.setHeader("ETag", etag);
    response.setHeader("Cache-Control", "public, max-age=" + seconds);
}

From source file:com.lushapp.common.web.utils.WebUtils.java

/**
 * ??Header./*from ww  w .  j a  v  a  2s  .  c  o  m*/
 *
 * @param fileName ???.
 */
public static void setDownloadableHeader(HttpServletRequest request, HttpServletResponse response,
        String fileName) {
    try {
        if (BrowserUtils.isIE(request)) {
            response.setHeader("content-disposition",
                    "attachment;filename=\"" + java.net.URLEncoder.encode(fileName, "UTF-8") + "\"");
        } else {
            //???
            String encodedfileName = new String(fileName.getBytes(), "ISO8859-1");
            response.setHeader("Content-Disposition", "attachment; filename=\"" + encodedfileName + "\"");
        }

    } catch (UnsupportedEncodingException e) {
    }
}

From source file:gov.nist.appvet.tool.synchtest.util.ReportUtil.java

/**
 * This method returns report information to the AppVet ToolAdapter as ASCII
 * text and cannot attach a file to the response.
 *///from   www . ja  va2s.c  om
public static boolean sendPDFInHttpResponse(HttpServletResponse response, String reportText,
        ToolStatus reportStatus) {
    try {
        File reportFile = new File(reportFilePath);
        String mimeType = new MimetypesFileTypeMap().getContentType(reportFile);
        log.debug("Sending mimetype: " + mimeType);
        response.setContentType(mimeType);
        response.setHeader("Content-Disposition", "attachment;filename=" + reportFile.getName());
        response.setStatus(HttpServletResponse.SC_OK); // HTTP 200
        response.setHeader("apprisk", reportStatus.name());

        FileInputStream inputStream = new FileInputStream(reportFile); //read the file

        try {
            int c;
            while ((c = inputStream.read()) != -1) {
                response.getWriter().write(c);
            }
        } finally {
            if (inputStream != null)
                inputStream.close();
            response.getWriter().close();
        }

        //         PrintWriter out = response.getWriter();
        //         out.println(reportText);
        //         out.flush();
        //         out.close();
        log.info("Returned report");
        return true;
    } catch (IOException e) {
        log.error("Report not sent: " + e.toString());
        return false;
    }
}