Example usage for javax.servlet.http HttpServletResponse setDateHeader

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

Introduction

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

Prototype

public void setDateHeader(String name, long date);

Source Link

Document

Sets a response header with the given name and date-value.

Usage

From source file:gsn.http.ContainerInfoHandler.java

public void handle(HttpServletRequest request, HttpServletResponse response) throws IOException {
    response.setStatus(HttpServletResponse.SC_OK);
    String reqName = request.getParameter("name");

    //Added by Behnaz
    HttpSession session = request.getSession();
    User user = (User) session.getAttribute("user");

    response.setHeader("Cache-Control", "no-store");
    response.setDateHeader("Expires", 0);
    response.setHeader("Pragma", "no-cache");

    String omitLatestValuesPar = request.getParameter("omit_latest_values");
    boolean omitLatestValues = false;
    if (omitLatestValuesPar != null && "true".equals(omitLatestValuesPar)) {
        omitLatestValues = true;// w  w  w . j a  v a 2s .c  o m
    }

    //System.out.println( "The handle was called" );
    // if (reqName != null) System.out.println("requst " + reqName);
    // if (user != null) System.out.println("User " + user.getUserName());
    response.getWriter().write(buildOutput(reqName, user, omitLatestValues));
}

From source file:org.openmrs.module.reporting.web.reports.ManageReportsController.java

/**
 * Provide all reports designs, optionally including those that are retired, to a page 
 * that lists them and provides options for working with them.
 *//*from   w  w  w  .  ja  va 2 s . c  om*/
@RequestMapping("/module/reporting/reports/viewReportDesignResource")
public void viewDesignContent(ModelMap model, HttpServletResponse response,
        @RequestParam(required = true, value = "designUuid") String designUuid,
        @RequestParam(required = true, value = "resourceUuid") String resourceUuid) {

    ReportDesign d = Context.getService(ReportService.class).getReportDesignByUuid(designUuid);
    ReportDesignResource r = d.getResourceByUuid(resourceUuid);

    response.setHeader("Pragma", "No-cache");
    response.setDateHeader("Expires", 0);
    response.setHeader("Cache-Control", "no-cache");
    response.setHeader("Content-Disposition", "attachment; filename=" + r.getResourceFilename());
    try {
        response.getOutputStream().write(r.getContents());
    } catch (Exception e) {
        throw new RuntimeException("Unable to render contents of file", e);
    }
}

From source file:io.awacs.demo.TestController.java

@RequestMapping("/img")
public void img(HttpServletRequest request, HttpServletResponse response) throws Exception {
    try {// ww  w .  j a va  2 s  .  c  om
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < 4; i++) {
            int r = random.nextInt(36);
            bis2();
            if (r < 10) {
                sb.append((char) ('0' + r));
            } else {
                sb.append((char) ('A' + r - 10));
            }
        }
        BufferedImage img = cage.drawImage(sb.toString());
        response.setHeader("Cache-Control", "no-store");
        response.setHeader("Pragma", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setContentType("image/jpeg");
        ServletOutputStream responseOutputStream = response.getOutputStream();
        ImageIO.write(img, "JPEG", responseOutputStream);
    } catch (Exception e) {
        throw e;
    }
}

From source file:org.broadleafcommerce.cms.web.file.StaticAssetView.java

@Override
public void render(Map<String, ?> model, HttpServletRequest request, HttpServletResponse response)
        throws Exception {
    String cacheFilePath = (String) model.get("cacheFilePath");
    BufferedInputStream bis = new BufferedInputStream(new FileInputStream(cacheFilePath));
    try {//from   w  w w.ja  va  2 s . c o m
        String mimeType = (String) model.get("mimeType");
        response.setContentType(mimeType);
        if (!browserAssetCachingEnabled) {
            response.setHeader("Cache-Control", "no-cache");
            response.setHeader("Pragma", "no-cache");
            response.setDateHeader("Expires", 0);
        } else {
            response.setHeader("Cache-Control", "public");
            response.setHeader("Pragma", "cache");
            if (!StringUtils.isEmpty(request.getHeader("If-Modified-Since"))) {
                long lastModified = request.getDateHeader("If-Modified-Since");
                Calendar last = Calendar.getInstance();
                last.setTime(new Date(lastModified));
                Calendar check = Calendar.getInstance();
                check.add(Calendar.SECOND, -2 * new Long(cacheSeconds).intValue());
                if (check.compareTo(last) < 0) {
                    response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
                    return;
                }
            } else {
                Calendar check = Calendar.getInstance();
                check.add(Calendar.SECOND, -1 * new Long(cacheSeconds).intValue());
                response.setDateHeader("Last-Modified", check.getTimeInMillis());
            }
            Calendar cal = Calendar.getInstance();
            cal.add(Calendar.SECOND, new Long(cacheSeconds).intValue());
            response.setDateHeader("Expires", cal.getTimeInMillis());
        }
        OutputStream os = response.getOutputStream();
        boolean eof = false;
        while (!eof) {
            int temp = bis.read();
            if (temp < 0) {
                eof = true;
            } else {
                os.write(temp);
            }
        }
        os.flush();
    } catch (Exception e) {
        if (e.getCause() instanceof SocketException) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Unable to stream asset", e);
            }
        } else {
            LOG.error("Unable to stream asset", e);
            throw e;
        }
    } finally {
        try {
            bis.close();
        } catch (Throwable e) {
            //do nothing
        }
    }
}

From source file:org.jsche.common.inteceptor.LoginInteceptor.java

@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
        throws Exception {
    if (handler.getClass().isAssignableFrom(HandlerMethod.class)) {
        RequiredLogin login = ((HandlerMethod) handler).getMethodAnnotation(RequiredLogin.class);
        if (login == null || !login.value()) {
            // ignore this session check
            return true;
        } else {//  w  w w  . j av a2s  .co  m
            if (request.getSession().getAttribute(Constants.LOGIN_USER) != null) {
                return true;
            } else {
                request.setAttribute(Constants.ERROR_ATTR_NAME, ErrorMessage.LOGIN_REQUIRED);
                response.setDateHeader("expries", -1);
                response.setHeader("Cache-Control", "no-cache");
                response.setHeader("Pragma", "no-cache");
                response.sendRedirect("/login");
                return false;
            }
        }
    }
    return true;
}

From source file:be.fedict.eid.dss.portal.DownloadServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    LOG.debug("doGet");
    HttpSession httpSession = request.getSession();
    byte[] document = (byte[]) httpSession.getAttribute(this.documentSessionAttribute);

    response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate, max-age=-1"); // http 1.1
    if (false == request.getScheme().equals("https")) {
        // else the download fails in IE
        response.setHeader("Pragma", "no-cache"); // http 1.0
    } else {/*from w  w w.j av  a  2 s.  com*/
        response.setHeader("Pragma", "public");
    }
    response.setDateHeader("Expires", -1);
    response.setContentLength(document.length);

    String contentType = (String) httpSession.getAttribute(this.contentTypeSessionAttribute);
    LOG.debug("content-type: " + contentType);
    response.setContentType(contentType);
    response.setContentLength(document.length);
    ServletOutputStream out = response.getOutputStream();
    out.write(document);
    out.flush();
}

From source file:org.polymap.core.mapeditor.services.SimpleJsonServer.java

protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    log.info("Accept-Encoding: " + request.getHeader("Accept-Encoding"));
    log.info("### JSON: about to encode JSON....");
    boolean gzip = request.getHeader("Accept-Encoding").toLowerCase().contains("gzip");

    // prevent caching
    response.setHeader("Cache-Control", "no-cache"); // HTTP 1.1
    response.setHeader("Pragma", "no-cache"); // HTTP 1.0
    response.setDateHeader("Expires", 0); // prevents caching at the proxy
    response.setCharacterEncoding("UTF-8");

    Timer timer = new Timer();
    log.debug("SimpleJsonServer Output: ");
    OutputStream debugOut = /*log.isDebugEnabled() 
                            ? new TeeOutputStream( response.getOutputStream(), System.out )
                            : */response.getOutputStream();

    CountingOutputStream out = null, cout2 = null;
    if (gzip) {//from w w w .  jav a2  s .co  m
        response.setHeader("Content-Encoding", "gzip");
        //response.setHeader( "Content-Type", "text/javascript" );
        cout2 = new CountingOutputStream(debugOut);
        out = new CountingOutputStream(new GZIPOutputStream(cout2));
    } else {
        out = new CountingOutputStream(debugOut);
    }

    String layerName = StringUtils.substringAfterLast(request.getPathInfo(), "/");
    JsonEncoder layer = null;
    synchronized (layers) {
        layer = layers.get(layerName);
    }
    layer.encode(out, response.getCharacterEncoding());
    out.close();

    log.info("    JSON bytes: " + out.getCount() + " (" + timer.elapsedTime() + "ms)");
    if (cout2 != null) {
        log.info("    GZIPed bytes written: " + cout2.getCount());
    }

    if (layer.isOneShot()) {
        removeLayer(layer);
        log.info("    Layer is oneShot -> removed.");
    }
}

From source file:org.efaps.ui.servlet.FileServlet.java

/**
 * Search for the requested file in the folder corresponding to the user of the context.
 *
 * @param _req request variable//ww w  .  ja  va2s. com
 * @param _resp response variable
 * @throws ServletException on error
 */
@Override
protected void doGet(final HttpServletRequest _req, final HttpServletResponse _resp) throws ServletException {
    String fileName = _req.getRequestURI();
    fileName = fileName.substring(fileName.lastIndexOf('/') + 1);
    try {
        final Person pers = Context.getThreadContext().getPerson();
        if (pers != null) {
            final File file = getFile(pers.getId(), fileName);
            if (file != null && file.exists()) {
                _resp.setContentType(getServletContext().getMimeType(file.getName()));
                _resp.setContentLength((int) file.length());
                _resp.setDateHeader("Last-Modified", System.currentTimeMillis());
                _resp.setDateHeader("Expires", System.currentTimeMillis());
                _resp.addHeader("Content-Disposition", "inline; filename=\"" + file.getName() + "\"");
                _resp.setHeader("Cache-Control", "max-age=10");
                final FileInputStream input = new FileInputStream(file);
                IOUtils.copy(input, _resp.getOutputStream());
            }
        }
    } catch (final EFapsException e) {
        FileServlet.LOG.error("EFapsException", e);
        throw new ServletException(e);
    } catch (final IOException e) {
        FileServlet.LOG.error("IOException", e);
        throw new ServletException(e);
    }
}

From source file:org.kuali.mobility.icons.controllers.WebIconsController.java

/**
 * Get the icon matching all the criteria of the request and write it the the HttpServletResponse.
 *
 * @param iconName Name of the icon to get.
 * @param theme    The theme to get the icon in.
 * @param size     Size to get the icon in.
 * @param request  The HttpServletRequest being handled.
 * @param response The HttpServletResponse that will reply.
 * @throws IOException Thrown if there is an exception creating the icon or writing it to the response.
 *//*  w  w  w.j a  v  a2  s . c  o m*/
private void writeIconToHttpResponse(String iconName, String theme, int size, HttpServletRequest request,
        HttpServletResponse response) throws IOException {
    long dateChanged = request.getDateHeader("If-Modified-Since") / 1000;
    File imageFile = iconService.getImageFile(iconName, theme, size);

    long mediaChanged = imageFile.lastModified() / 1000;
    if (dateChanged == mediaChanged) {
        response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
        return;
    }
    response.setContentType("image/png");
    InputStream imageInput = new FileInputStream(imageFile);
    response.setDateHeader("Last-Modified", imageFile.lastModified());

    int bytesWritten = IOUtils.copy(imageInput, response.getOutputStream());
    response.setContentLength(bytesWritten);
    response.flushBuffer();
}

From source file:org.apache.jasper.servlet.JspServletWrapper.java

public void service(HttpServletRequest request, HttpServletResponse response, boolean precompile)
        throws ServletException, IOException, FileNotFoundException {
    try {/*from   w ww . j  a  v a2 s  . com*/

        if (ctxt.isRemoved()) {
            throw new FileNotFoundException(jspUri);
        }

        if ((available > 0L) && (available < Long.MAX_VALUE)) {
            response.setDateHeader("Retry-After", available);
            response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE,
                    Localizer.getMessage("jsp.error.unavailable"));
        }

        if (options.getDevelopment() || firstTime) {
            synchronized (this) {
                ctxt.compile();
            }
        }

        if (reload) {
            getServlet();
        }

        // If a page is to only to be precompiled return.
        if (precompile) {
            return;
        }

        if (theServlet instanceof SingleThreadModel) {
            // sync on the wrapper so that the freshness
            // of the page is determined right before servicing
            synchronized (this) {
                theServlet.service(request, response);
            }
        } else {
            theServlet.service(request, response);
        }

    } catch (UnavailableException ex) {
        String includeRequestUri = (String) request.getAttribute("javax.servlet.include.request_uri");
        if (includeRequestUri != null) {
            // This file was included. Throw an exception as
            // a response.sendError() will be ignored by the
            // servlet engine.
            throw ex;
        } else {
            int unavailableSeconds = ex.getUnavailableSeconds();
            if (unavailableSeconds <= 0) {
                unavailableSeconds = 60; // Arbitrary default
            }
            available = System.currentTimeMillis() + (unavailableSeconds * 1000L);
            response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, ex.getMessage());
        }
    } catch (FileNotFoundException ex) {
        String includeRequestUri = (String) request.getAttribute("javax.servlet.include.request_uri");
        if (includeRequestUri != null) {
            // This file was included. Throw an exception as
            // a response.sendError() will be ignored by the
            // servlet engine.
            throw new ServletException(ex);
        } else {
            try {
                response.sendError(HttpServletResponse.SC_NOT_FOUND, ex.getMessage());
            } catch (IllegalStateException ise) {
                log.error(Localizer.getMessage("jsp.error.file.not.found", ex.getMessage()), ex);
            }
        }
    } catch (ServletException ex) {
        throw ex;
    } catch (IOException ex) {
        throw ex;
    } catch (IllegalStateException ex) {
        throw ex;
    } catch (Exception ex) {
        throw new JasperException(ex);
    }
}