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:org.opencms.flex.CmsFlexController.java

/**
 * Sets the <code>Expires</code> date header for a given http request.<p>
 * // w w  w  .ja v  a2s.co m
 * Also sets the <code>cache-control: max-age</code> header to the time of the expiration.
 * A certain upper limit is imposed on the expiration date parameter to ensure the resources are
 * not cached to long in proxies. This can be controlled by the <code>maxAge</code> parameter. 
 * If <code>maxAge</code> is lower then 0, then a default max age of 86400000 msec (1 day) is used.<p> 
 * 
 * @param res the response to set the "Expires" date header for
 * @param maxAge maximum amount of time in milliseconds the response remains valid
 * @param dateExpires the date to set (if this is not in the future, it is ignored)
 */
public static void setDateExpiresHeader(HttpServletResponse res, long dateExpires, long maxAge) {

    long now = System.currentTimeMillis();
    if ((dateExpires > now) && (dateExpires != CmsResource.DATE_EXPIRED_DEFAULT)) {

        // important: many caches (browsers or proxy) use the "Expires" header
        // to avoid re-loading of pages that are not expired
        // while this is right in general, no changes before the expiration date
        // will be displayed
        // therefore it is better to not use an expiration to far in the future 

        // if no valid max age is set, restrict it to 24 hrs
        if (maxAge < 0L) {
            maxAge = 86400000;
        }

        if ((dateExpires - now) > maxAge) {
            // set "Expires" header max one day into the future
            dateExpires = now + maxAge;
        }
        res.setDateHeader(CmsRequestUtil.HEADER_EXPIRES, dateExpires);

        // setting the "Expires" header only is not sufficient - even expired documents seems to be cached
        // therefore, the "cache-control: max-age" is also set
        res.setHeader(CmsRequestUtil.HEADER_CACHE_CONTROL,
                CmsRequestUtil.HEADER_VALUE_MAX_AGE + (maxAge / 1000L));
    }
}

From source file:mx.com.quadrum.contratos.controller.busquedas.MuestraPdf.java

@RequestMapping(value = "muestraPdf/{idContrato}", method = RequestMethod.GET)
public void muestraPdf(@PathVariable("idContrato") Integer idContrato, HttpSession session,
        HttpServletRequest request, HttpServletResponse response) {
    if (session.getAttribute(USUARIO) == null && session.getAttribute(CLIENTE) == null) {
        return;/*from ww  w.  ja va  2  s  . c o  m*/
    }
    Contrato contrato = contratoService.buscarPorId(idContrato);

    Usuario usuario = (Usuario) session.getAttribute(USUARIO);
    response.setContentType("application/pdf");

    response.setHeader("Cache-Control", "no-cache");
    response.setHeader("Pragma", "no-cache");
    response.setDateHeader("Expires", 0);
    File pdf = new File(
            USUARIOS + usuario.getMail() + "\\" + contrato.getNombre() + "\\" + contrato.getNombre() + ".pdf");
    try {
        InputStream in = new FileInputStream(pdf);
        byte[] data = new byte[in.available()];
        in.read(data);
        javax.servlet.ServletOutputStream servletoutputstream = response.getOutputStream();

        servletoutputstream.write(data);
        servletoutputstream.flush();
        servletoutputstream.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

}

From source file:ru.org.linux.topic.UncommitedTopicsController.java

@RequestMapping
public ModelAndView viewAll(
        @RequestParam(value = "section", required = false, defaultValue = "0") int sectionId,
        HttpServletRequest request, HttpServletResponse response) {
    Template tmpl = Template.getTemplate(request);

    ModelAndView modelAndView = new ModelAndView("view-all");

    Section section = null;/*from   w  w w .  ja v  a  2s .  co  m*/
    if (sectionId != 0) {
        section = sectionService.getSection(sectionId);
        modelAndView.addObject("section", section);
        modelAndView.addObject("addlink", AddTopicController.getAddUrl(section));
    }

    response.setDateHeader("Expires", new Date(System.currentTimeMillis() - 20 * 3600 * 1000).getTime());
    response.setDateHeader("Last-Modified", new Date(System.currentTimeMillis() - 120 * 1000).getTime());

    String title;

    switch (sectionId) {
    case Section.SECTION_NEWS:
        title = "? ?";
        break;
    case Section.SECTION_POLLS:
        title = "? ?";
        break;
    case Section.SECTION_GALLERY:
        title = "? ?";
        break;
    case 0:
        title = "?  ?";
        break;
    default:
        title = "?: " + section.getName();
        break;
    }

    modelAndView.addObject("title", title);

    Calendar calendar = Calendar.getInstance();
    calendar.setTime(new Date());
    calendar.add(Calendar.MONTH, -3);

    List<Topic> messages = topicListService.getAllTopicsFeed(section, calendar.getTime());
    modelAndView.addObject("messages", prepareService.prepareMessagesForUser(messages, request.isSecure(),
            tmpl.getCurrentUser(), tmpl.getProf(), false));

    List<TopicListDto.DeletedTopic> deleted = topicListService.getDeletedTopics(sectionId,
            !tmpl.isModeratorSession());

    modelAndView.addObject("deletedTopics", deleted);
    modelAndView.addObject("sections", sectionService.getSectionList());

    return modelAndView;
}

From source file:org.apache.qpid.server.management.plugin.servlet.rest.SaslServlet.java

@Override
protected void doPostWithSubjectAndActor(final HttpServletRequest request, final HttpServletResponse response)
        throws IOException {
    checkSaslAuthEnabled(request);// www  .java  2  s  .com

    try {
        response.setContentType("application/json");
        response.setHeader("Cache-Control", "no-cache");
        response.setHeader("Pragma", "no-cache");
        response.setDateHeader("Expires", 0);

        HttpSession session = request.getSession();

        String mechanism = request.getParameter("mechanism");
        String id = request.getParameter("id");
        String saslResponse = request.getParameter("response");

        SubjectCreator subjectCreator = getSubjectCreator(request);

        if (mechanism != null) {
            if (id == null) {
                if (LOGGER.isDebugEnabled()) {
                    LOGGER.debug("Creating SaslServer for mechanism: " + mechanism);
                }
                SaslServer saslServer = subjectCreator.createSaslServer(mechanism, request.getServerName(),
                        null/*TODO*/);
                evaluateSaslResponse(request, response, session, saslResponse, saslServer, subjectCreator);
            } else {
                response.setStatus(HttpServletResponse.SC_EXPECTATION_FAILED);
                session.removeAttribute(ATTR_ID);
                session.removeAttribute(ATTR_SASL_SERVER);
                session.removeAttribute(ATTR_EXPIRY);
            }
        } else {
            if (id != null) {
                if (id.equals(session.getAttribute(ATTR_ID))
                        && System.currentTimeMillis() < (Long) session.getAttribute(ATTR_EXPIRY)) {
                    SaslServer saslServer = (SaslServer) session.getAttribute(ATTR_SASL_SERVER);
                    evaluateSaslResponse(request, response, session, saslResponse, saslServer, subjectCreator);
                } else {
                    response.setStatus(HttpServletResponse.SC_EXPECTATION_FAILED);
                    session.removeAttribute(ATTR_ID);
                    session.removeAttribute(ATTR_SASL_SERVER);
                    session.removeAttribute(ATTR_EXPIRY);
                }
            } else {
                response.setStatus(HttpServletResponse.SC_EXPECTATION_FAILED);
                session.removeAttribute(ATTR_ID);
                session.removeAttribute(ATTR_SASL_SERVER);
                session.removeAttribute(ATTR_EXPIRY);
            }
        }
    } catch (IOException e) {
        LOGGER.error("Error processing SASL request", e);
        throw e;
    } catch (RuntimeException e) {
        LOGGER.error("Error processing SASL request", e);
        throw e;
    }
}

From source file:com.yanbang.portal.controller.PortalController.java

/**
 * ???/*w  w w  . ja  v a2s  .  c  o  m*/
 * 
 * @param request
 * @param response
 * @return
 * @throws Exception
 */
@RequestMapping(params = "action=handleRnd")
public void handleRnd(HttpServletRequest request, HttpServletResponse response) throws Exception {
    response.setHeader("Cache-Control", "no-store");
    response.setHeader("Pragma", "no-cache");
    response.setDateHeader("Expires", 0L);
    response.setContentType("image/jpeg");
    BufferedImage image = new BufferedImage(65, 25, BufferedImage.TYPE_INT_RGB);
    Graphics g = image.getGraphics();
    g.setColor(Color.GRAY);
    g.fillRect(0, 0, 65, 25);
    g.setColor(Color.yellow);
    Font font = new Font("", Font.BOLD, 20);
    g.setFont(font);
    Random r = new Random();
    String rnd = "";
    int ir = r.nextInt(10);
    rnd = rnd + "" + ir;
    g.drawString("" + ir, 5, 18);
    g.setColor(Color.red);
    ir = r.nextInt(10);
    rnd = rnd + "" + ir;
    g.drawString("" + ir, 20, 18);
    g.setColor(Color.blue);
    ir = r.nextInt(10);
    rnd = rnd + "" + ir;
    g.drawString("" + ir, 35, 18);
    g.setColor(Color.green);
    ir = r.nextInt(10);
    rnd = rnd + "" + ir;
    g.drawString("" + ir, 50, 18);
    request.getSession().setAttribute("RND", rnd);
    ServletOutputStream out = response.getOutputStream();
    out.write(ImageUtil.imageToBytes(image, "gif"));
    out.flush();
    out.close();
}

From source file:org.openxdata.server.servlet.MultimediaServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    //Setting header from hear ensures that user is not given a blank page
    //if there is not data
    response.setHeader("Cache-Control", "no-cache");
    response.setHeader("Pragma", "no-cache");
    response.setDateHeader("Expires", -1);
    response.setHeader("Cache-Control", "no-store");

    String sFormId = request.getParameter("formId");
    String xpath = request.getParameter("xpath");
    String contentType = request.getParameter("contentType");
    String name = request.getParameter("name");

    if ("recentbinary".equals(request.getParameter("action"))) {
        byte[] postData = (byte[]) getSessionData(request, sFormId,
                KEY_MULTIMEDIA_POST_DATA + getFieldKey(sFormId, xpath)); //(byte[])session.getAttribute(KEY_MULTIMEDIA_POST_DATA+getFieldKey(sFormId,xpath));
        if (postData != null) {
            response.setContentType((String) getSessionData(request, sFormId,
                    KEY_MULTIMEDIA_POST_CONTENT_TYPE + getFieldKey(sFormId, xpath)));
            response.getOutputStream().write(postData);

            setSessionData(request, sFormId, KEY_MULTIMEDIA_POST_CONTENT_TYPE + getFieldKey(sFormId, xpath),
                    null);//from  w  ww  .j a  va 2s  .c  o  m
            setSessionData(request, sFormId, KEY_MULTIMEDIA_POST_DATA + getFieldKey(sFormId, xpath), null);
        }
        return;
    }

    try {
        if (name == null || name.trim().length() == 0)
            name = "multimedia.3gp";

        if (sFormId == null || sFormId.trim().length() == 0)
            return;

        if (xpath == null || xpath.trim().length() == 0)
            return;

        byte[] bytes = (byte[]) getSessionData(request, sFormId,
                KEY_MULTIMEDIA_POST_DATA + getFieldKey(sFormId, xpath));

        String value = null;

        if (bytes == null) {
            int id = Integer.parseInt(sFormId);
            FormData formData = studyManagerService.getFormData(id);
            if (formData == null)
                return;

            String xml = formData.getData();
            if (xml == null || xml.trim().length() == 0)
                return;

            Document doc = XmlUtil.fromString2Doc(xml);
            if (doc == null)
                return;

            value = XmlUtil.getNodeValue(doc, xpath);
        }
        if (bytes != null || (value != null && value.trim().length() > 0)) {
            if (bytes == null)
                bytes = Base64.decodeBase64(value.getBytes());

            if (bytes != null) {
                if (contentType != null && contentType.trim().length() > 0) {
                    response.setContentType(contentType);

                    //Send it as an attachement such that atleast firefox can also detect it
                    if (contentType.contains("video") || contentType.contains("audio"))
                        response.setHeader(OpenXDataConstants.HTTP_HEADER_CONTENT_DISPOSITION,
                                OpenXDataConstants.HTTP_HEADER_CONTENT_DISPOSITION_VALUE + name + "\"");
                }

                response.getOutputStream().write(bytes);
            }
        } //This elese if is to prevent a blank page if there is no data.
        else if (contentType != null && (contentType.contains("video") || contentType.contains("audio")))
            response.setHeader(OpenXDataConstants.HTTP_HEADER_CONTENT_DISPOSITION,
                    OpenXDataConstants.HTTP_HEADER_CONTENT_DISPOSITION_VALUE + name + "\"");
    } catch (Exception ex) {
        log.error(ex.getLocalizedMessage(), ex);
    }
}

From source file:org.bahmni.module.bahmnicore.web.filter.CacheHeadersFilter.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {

    chain.doFilter(request, response);/*from   w  w  w  . j  av a  2 s  .  c  o m*/

    if (response instanceof HttpServletResponse) {
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        if ("GET".equals(httpRequest.getMethod()) && httpResponse.getStatus() == 200) {
            int expiresDuration = NumberUtils.toInt(Context.getAdministrationService()
                    .getGlobalProperty("bahmni.cacheHeadersFilter.expiresDuration"), 0);
            log.debug(String.format("Setting expires header with duration %s", expiresDuration));
            httpResponse.setDateHeader("Expires", DateUtils.addMinutes(new Date(), expiresDuration).getTime());
        }
    }
}

From source file:org.kuali.mobility.writer.controllers.WriterMediaController.java

@RequestMapping(value = "/{mediaId}", method = RequestMethod.GET)
public void getMedia(@PathVariable int mediaId,
        @RequestParam(value = "thumb", required = false, defaultValue = "false") boolean thumb,
        HttpServletRequest request, HttpServletResponse response) throws IOException {

    long dateChanged = request.getDateHeader("If-Modified-Since") / 1000;

    File mediaFile = service.getMediaFile(mediaId, thumb);
    long mediaChanged = mediaFile.lastModified() / 1000;
    if (dateChanged == mediaChanged) {
        response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
        return;//from ww  w  .  j ava 2 s  . co  m
    }
    Media media = service.getMedia(mediaId);
    response.setContentType(media.getMimeType());
    response.setDateHeader("Last-Modified", mediaFile.lastModified());

    int bytesWritten = IOUtils.copy(new FileInputStream(mediaFile), response.getOutputStream());
    response.setContentLength(bytesWritten);

}

From source file:org.openxdata.server.servlet.FormSaveServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    HttpSession session = request.getSession();

    response.setHeader(OpenXDataConstants.HTTP_HEADER_CONTENT_DISPOSITION,
            OpenXDataConstants.HTTP_HEADER_CONTENT_DISPOSITION_VALUE + session.getAttribute(KEY_FILE_NAME));
    response.setContentType(OpenXDataConstants.HTTP_HEADER_CONTENT_TYPE_XML);

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

    response.getOutputStream().print((String) session.getAttribute(KEY_FILE_CONTENTS));
}

From source file:org.apache.ofbiz.base.util.UtilHttp.java

public static void setResponseBrowserProxyNoCache(HttpServletResponse response) {
    long nowMillis = System.currentTimeMillis();
    response.setDateHeader("Expires", nowMillis);
    response.setDateHeader("Last-Modified", nowMillis); // always modified
    response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate"); // HTTP/1.1
    response.addHeader("Cache-Control", "post-check=0, pre-check=0, false");
    response.setHeader("Pragma", "no-cache"); // HTTP/1.0
}