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:com.ikon.util.WebUtils.java

/**
 * Prepare to send the file.//from  w ww.j  a  v a  2 s  . co  m
 */
public static void prepareSendFile(HttpServletRequest request, HttpServletResponse response, String fileName,
        String mimeType, boolean inline) throws UnsupportedEncodingException {
    String agent = request.getHeader("USER-AGENT");

    // Disable browser cache
    response.setHeader("Expires", "Sat, 6 May 1971 12:00:00 GMT");
    response.setHeader("Cache-Control", "must-revalidate");
    response.addHeader("Cache-Control", "no-store, no-cache, must-revalidate");
    response.addHeader("Cache-Control", "post-check=0, pre-check=0");
    response.setHeader("Pragma", "no-cache");

    // Set MIME type
    response.setContentType(mimeType);

    if (null != agent && -1 != agent.indexOf("MSIE")) {
        log.debug("Agent: Explorer ({})", request.getServerPort());
        fileName = URLEncoder.encode(fileName, "UTF-8").replaceAll("\\+", " ");

        if (request.getServerPort() == 443) {
            log.debug("HTTPS detected! Apply IE workaround...");
            response.setHeader("Cache-Control", "max-age=1");
            response.setHeader("Pragma", "public");
        }
    } else if (null != agent && -1 != agent.indexOf("Mozilla")) {
        log.debug("Agent: Mozilla");
        fileName = MimeUtility.encodeText(fileName, "UTF-8", "B");
    } else {
        log.debug("Agent: Unknown");
    }

    if (inline) {
        response.setHeader("Content-disposition", "inline; filename=\"" + fileName + "\"");
    } else {
        response.setHeader("Content-disposition", "attachment; filename=\"" + fileName + "\"");
    }
}

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

/**
 * Utility method for exporting a set of selected modules. The select modules will be exported
 * in zip file called "modules.zip"/*from   w ww .  j  a va2  s .  com*/
 * 
 * @param moduleId -Dash-separated list of the module Ids
 * @param response
 * @throws IOException
 */
public static void exportSelectedModules(String moduleId, HttpServletResponse response) throws IOException {
    // Split the id string into an array of id's
    String[] moduleIds = moduleId.split("-");
    List<File> files = new ArrayList<File>();
    for (String mId : moduleIds) {
        Module m = ModuleFactory.getModuleById(mId);
        files.add(m.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:org.openmrs.module.omodexport.util.OmodExportUtil.java

/**
 * Utility method for exporting a module with its dependencies
 * // w  w  w.  j  a v  a  2  s  .c  o m
 * @param module -The module to export. It will be exported with all its dependencies and
 *            compressed in a file called "modules.zip"
 * @param response
 * @throws IOException
 */
public static void exportModuleWithDependecies(Module module, HttpServletResponse response) throws IOException {
    List<File> files = new ArrayList<File>();
    List<String> dependecies = module.getRequiredModules();
    for (String name : dependecies) {
        Module m = ModuleFactory.getModuleByPackage(name);
        files.add(m.getFile());
    }
    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:ch.rasc.downloadchart.DownloadChartServlet.java

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

    response.setContentType("application/pdf");
    response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + ".pdf\";");

    try (PDDocument document = new PDDocument()) {
        PDRectangle format = PDPage.PAGE_SIZE_A4;
        if (options != null) {
            if ("A3".equals(options.format)) {
                format = PDPage.PAGE_SIZE_A3;
            } else if ("A5".equals(options.format)) {
                format = PDPage.PAGE_SIZE_A5;
            } else if ("Letter".equals(options.format)) {
                format = PDPage.PAGE_SIZE_LETTER;
            } else if ("Legal".equals(options.format)) {
                format = new PDRectangle(215.9f * MM_TO_UNITS, 355.6f * MM_TO_UNITS);
            } else if ("Tabloid".equals(options.format)) {
                format = new PDRectangle(279 * MM_TO_UNITS, 432 * MM_TO_UNITS);
            } else if (options.width != null && options.height != null) {
                Float pdfWidth = convertToPixel(options.width);
                Float pdfHeight = convertToPixel(options.height);
                if (pdfWidth != null && pdfHeight != null) {
                    format = new PDRectangle(pdfWidth, pdfHeight);
                }//from  w w w . j  av  a  2s.c  o m
            }
        }

        PDPage page = new PDPage(format);

        if (options != null && "landscape".equals(options.orientation)) {
            page.setRotation(90);
        }

        document.addPage(page);

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

        try (PDPageContentStream contentStream = new PDPageContentStream(document, page)) {

            PDPixelMap ximage = new PDPixelMap(document, originalImage);

            Dimension newDimension = calculateDimension(originalImage, width, height);
            int imgWidth = ximage.getWidth();
            int imgHeight = ximage.getHeight();
            if (newDimension != null) {
                imgWidth = newDimension.width;
                imgHeight = newDimension.height;
            }

            Float border = options != null ? convertToPixel(options.border) : null;
            if (border == null) {
                border = 0.0f;
            }

            AffineTransform transform;

            if (page.getRotation() == null) {
                float scale = (page.getMediaBox().getWidth() - border * 2) / imgWidth;
                if (scale < 1.0) {
                    transform = new AffineTransform(imgWidth, 0, 0, imgHeight, border,
                            page.getMediaBox().getHeight() - border - imgHeight * scale);

                    transform.scale(scale, scale);
                } else {
                    transform = new AffineTransform(imgWidth, 0, 0, imgHeight, border,
                            page.getMediaBox().getHeight() - border - imgHeight);
                }

            } else {
                float scale = (page.getMediaBox().getHeight() - border * 2) / imgWidth;
                if (scale < 1.0) {
                    transform = new AffineTransform(imgHeight, 0, 0, imgWidth, imgHeight * scale + border,
                            border);

                    transform.scale(scale, scale);
                } else {
                    transform = new AffineTransform(imgHeight, 0, 0, imgWidth, imgHeight + border, border);
                }

                transform.rotate(1.0 * Math.PI / 2.0);
            }

            contentStream.drawXObject(ximage, transform);

        }

        try {
            document.save(response.getOutputStream());
        } catch (COSVisitorException e) {
            throw new IOException(e);
        }
    }
}

From source file:edu.harvard.med.screensaver.ui.arch.util.JSFUtils.java

/**
 * Performs the necessary steps to return server-side data, provided as an
 * InputStream, to an HTTP client. Must be called within a JSF-enabled servlet
 * environment./*from   w ww .  ja va2 s  .c  om*/
 *
 * @param facesContext the JSF FacesContext
 * @param dataInputStream an InputStream containing the data to send to the HTTP client
 * @param contentLocation set the "content-location" HTTP header to this value, allowing the downloaded file to be named
 * @param mimeType the MIME type of the file being sent
 * @throws IOException
 */
public static void handleUserDownloadRequest(FacesContext facesContext, InputStream dataInputStream,
        String contentLocation, String mimeType) throws IOException {
    HttpServletResponse response = (HttpServletResponse) facesContext.getExternalContext().getResponse();
    if (mimeType == null && contentLocation != null) {
        mimeType = MimetypesFileTypeMap.getDefaultFileTypeMap().getContentType(contentLocation);
    }
    if (mimeType != null) {
        response.setContentType(mimeType);
    }

    // NOTE: the second line does the trick with the filename. leaving first line in for posterity
    response.setHeader("Content-Location", contentLocation);
    response.setHeader("Content-disposition", "attachment; filename=\"" + contentLocation + "\"");

    OutputStream out = response.getOutputStream();
    IOUtils.copy(dataInputStream, out);
    out.close();

    // skip Render-Response JSF lifecycle phase, since we're generating a
    // non-Faces response
    facesContext.responseComplete();
}

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

/**
 * Header./*from   w  ww.j  av a  2s  .c om*/
 */
public static void setNoCacheHeader(HttpServletResponse response) {
    //Http 1.0 header
    response.setDateHeader("Expires", 1L);
    response.addHeader("Pragma", "no-cache");
    //Http 1.1 header
    response.setHeader("Cache-Control", "no-cache, no-store, max-age=0");
}

From source file:com.openkm.util.WebUtils.java

/**
 * Prepare to send the file.//  www  .  j av a2s.c  om
 */
public static void prepareSendFile(HttpServletRequest request, HttpServletResponse response, String fileName,
        String mimeType, boolean inline) throws UnsupportedEncodingException {
    String userAgent = WebUtils.getHeader(request, "user-agent").toLowerCase();

    // Disable browser cache
    response.setHeader("Expires", "Sat, 6 May 1971 12:00:00 GMT");
    response.setHeader("Cache-Control", "must-revalidate");
    response.addHeader("Cache-Control", "no-store, no-cache, must-revalidate");
    response.addHeader("Cache-Control", "post-check=0, pre-check=0");
    response.setHeader("Pragma", "no-cache");

    // Set MIME type
    response.setContentType(mimeType);

    if (userAgent.contains("msie") || userAgent.contains("trident")) {
        log.debug("Agent: Explorer ({})", request.getServerPort());
        fileName = URLEncoder.encode(fileName, "UTF-8").replaceAll("\\+", " ");

        if (request.getServerPort() == 443) {
            log.debug("HTTPS detected! Apply IE workaround...");
            response.setHeader("Cache-Control", "max-age=1");
            response.setHeader("Pragma", "public");
        }
    } else if (userAgent.contains("iphone") || userAgent.contains("ipad")) {
        log.debug("Agent: iPhone - iPad");
        // Do nothing
    } else if (userAgent.contains("android")) {
        log.debug("Agent: Android");
        fileName = URLEncoder.encode(fileName, "UTF-8").replaceAll("\\+", " ");
    } else if (userAgent.contains("mozilla")) {
        log.debug("Agent: Mozilla");
        fileName = MimeUtility.encodeText(fileName, "UTF-8", "B");
    } else {
        log.debug("Agent: Unknown");
    }

    if (inline) {
        response.setHeader("Content-disposition", "inline; filename=\"" + fileName + "\"");
    } else {
        response.setHeader("Content-disposition", "attachment; filename=\"" + fileName + "\"");
    }
}

From source file:com.github.thorqin.webapi.oauth2.OAuthServer.java

public static void responseGetResourceFailed(HttpServletResponse response, OAuthError error,
        String errorDescription, String errorUri) {
    String headContent = "Bearer ";
    headContent += "error=\"" + error.toString().toLowerCase() + "\"";
    if (errorDescription != null)
        headContent += "error_description=\"" + errorDescription + "\"";
    if (errorUri != null)
        headContent += "error_uri=\"" + errorUri + "\"";
    response.setHeader("WWW-Authenticate", headContent);

    switch (error) {
    case INVALID_REQUEST:
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        break;/*w  w  w.jav  a  2  s.  co m*/
    case UNAUTHORIZED_CLIENT:
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        break;
    case ACCESS_DENIED:
    case UNSUPPORTED_RESPONSE_TYPE:
    case INVALID_SCOPE:
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        break;
    case SERVER_ERROR:
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        break;
    case TEMPORARILY_UNAVAILABLE:
        response.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
        break;
    }
}

From source file:ie.wombat.rt.fireeagle.CookieConsumer.java

/**
 * Handle an exception that occurred while processing an HTTP request.
 * Depending on the exception, either send a response, redirect the client
 * or propagate an exception./*from   w  w w .  ja v a  2s.  c o m*/
 */
public static void handleException(Exception e, HttpServletRequest request, HttpServletResponse response,
        OAuthConsumer consumer) throws IOException, ServletException {
    if (e instanceof RedirectException) {
        RedirectException redirect = (RedirectException) e;
        String targetURL = redirect.getTargetURL();
        if (targetURL != null) {
            response.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY);
            response.setHeader("Location", targetURL);
        }
    } else if (e instanceof OAuthProblemException) {
        OAuthProblemException p = (OAuthProblemException) e;
        String problem = p.getProblem();
        if (consumer != null && RECOVERABLE_PROBLEMS.contains(problem)) {
            try {
                CookieMap cookies = new CookieMap(request, response);
                OAuthAccessor accessor = newAccessor(consumer, cookies);
                getAccessToken(request, cookies, accessor);
                // getAccessToken(request, consumer,
                // new CookieMap(request, response));
            } catch (Exception e2) {
                handleException(e2, request, response, null);
            }
        } else {
            try {
                StringWriter s = new StringWriter();
                PrintWriter pw = new PrintWriter(s);
                e.printStackTrace(pw);
                pw.flush();
                p.setParameter("stack trace", s.toString());
            } catch (Exception rats) {
            }
            response.setStatus(p.getHttpStatusCode());
            response.resetBuffer();
            request.setAttribute("OAuthProblemException", p);
            request.getRequestDispatcher //
            ("/OAuthProblemException.jsp").forward(request, response);
        }
    } else if (e instanceof IOException) {
        throw (IOException) e;
    } else if (e instanceof ServletException) {
        throw (ServletException) e;
    } else if (e instanceof RuntimeException) {
        throw (RuntimeException) e;
    } else {
        throw new ServletException(e);
    }
}

From source file:com.concursive.connect.web.webdav.WebdavManager.java

public static void askForAuthentication(HttpServletResponse res) throws Exception {
    String nonce = DefaultServlet.generateNonce();
    // determine the 'opaque' value which should be returned as-is by the client
    String opaque = DefaultServlet.generateOpaque();
    res.setHeader("WWW-Authenticate", "Digest realm=\"" + WebdavServlet.USER_REALM + "\", " + "nonce=\"" + nonce
            + "\", " + "opaque=\"" + opaque + "\"");
    res.sendError(HttpServletResponse.SC_UNAUTHORIZED);
}