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:io.cfp.auth.MainCtrl.java

@RequestMapping("/")
public String main(HttpServletResponse response, @CookieValue(required = false) String token,
        @RequestParam(required = false, value = "target") String targetParam,
        @CookieValue(required = false) String returnTo,
        @RequestHeader(required = false, value = REFERER) String referer) {
    response.setHeader(CACHE_CONTROL, "no-cache,no-store,must-revalidate");
    response.setHeader(PRAGMA, "no-cache");
    response.setDateHeader(EXPIRES, 0);

    String target = "http://www.cfp.io";
    if (targetParam != null) {
        target = targetParam;/*w  w  w  .  j ava2s.  c  o m*/
    } else if (returnTo != null) {
        target = returnTo;
    } else if (referer != null) {
        target = referer;
    }

    response.addCookie(new Cookie("returnTo", target));

    if (token == null || !tokenSrv.isValid(token)) {
        return "login";
    }

    // token is valid
    return "redirect:" + target;
}

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

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try {// w w  w .j a v  a2  s  .  c o  m
        String action = request.getParameter(OpenXDataConstants.REQUEST_PARAMETER_ACTION);

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

        if (action == null) {
            new FormsServer(formDownloadService).processConnection(request.getInputStream(),
                    response.getOutputStream());
        } else {

            if (OpenXDataConstants.ACTION_DOWNLOAD_STUDIES.equalsIgnoreCase(action)) {
                downloadStudies(response);
            } else if (OpenXDataConstants.REQUEST_ACTION_DOWNLOAD_FORMS.equalsIgnoreCase(action)) {
                String studyId = request.getParameter("studyid");
                if (studyId != null && studyId.length() > 0) {
                    downloadForms(response, Integer.parseInt(studyId));
                }
            } else if (OpenXDataConstants.REQUEST_ACTION_UPLOAD_DATA.equalsIgnoreCase(action)) {
                // do nothing???
            }
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

From source file:org.artificer.ui.server.servlets.AbstractDownloadServlet.java

/**
 * Do download content.//w  w  w  . j  a v  a 2  s .  co m
 *
 * @param content
 *            the content
 * @param contentType
 *            the content type
 * @param disposition
 *            the disposition
 * @param httpResponse
 *            the http response
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 */
protected void doDownloadContent(InputStream content, String contentType, String disposition,
        HttpServletResponse httpResponse) throws IOException {
    if (StringUtils.isNotBlank(disposition)) {
        httpResponse.setHeader("Content-Disposition", disposition);
    }
    if (StringUtils.isNotBlank(contentType)) {
        httpResponse.setHeader("Content-Type", contentType);
    }

    // Make sure the browser doesn't cache it
    Date now = new Date();
    httpResponse.setDateHeader("Date", now.getTime());
    httpResponse.setDateHeader("Expires", now.getTime() - 86400000L);
    httpResponse.setHeader("Pragma", "no-cache");
    httpResponse.setHeader("Cache-control", "no-cache, no-store, must-revalidate");
    try {
        IOUtils.copy(content, httpResponse.getOutputStream());
    } finally {
        IOUtils.closeQuietly(content);
    }
}

From source file:fi.aluesarjat.prototype.AreasServlet.java

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

    long ifModifiedSince = request.getDateHeader("If-Modified-Since");
    if (ifModifiedSince >= LAST_MODIFIED) {
        response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
        return;/*from w  w w .java 2  s.  co m*/
    }

    response.setContentType("application/json");
    response.setCharacterEncoding("UTF-8");
    response.setDateHeader("Last-Modified", System.currentTimeMillis());
    response.setHeader("Cache-Control", "max-age=86400");

    String level = request.getParameter("level");
    String content;
    if (level == null) {
        content = areas;
    } else if ("1".equals(level)) {
        content = areas1;
    } else if ("2".equals(level)) {
        content = areas2;
    } else if ("3".equals(level)) {
        content = areas3;
    } else if ("4".equals(level)) {
        content = areas4;
    } else {
        throw new IllegalArgumentException("Illegal level " + level);
    }
    response.getWriter().append(content);
    response.getWriter().flush();

}

From source file:org.ambraproject.cas.filter.GetGuidReturnEmailFilter.java

/**
 * For the HttpServletRequest Parameter <em>guid</em>, query the user database for that
 *   user's Email Address, write that Email Address to the HttpServletResponse, and then exit.
 * <p/>/*from   w w  w.  j a  va2  s .  c  om*/
 * Returns <strong>only</strong> the user's Email Address.
 * <p/>
 * <strong>Caveat</strong>: Does <strong>not</strong> call <em>FilterChain.doFilter(...)</em>,
 *   but rather simply writes the String (which it hopes is the Email Address) to the Response
 *   and exits.
 *
 * @param request The incoming HttpServletRequest from which the Parameter <em>guid</em> is read
 * @param response The HttpServletResponse to which the results String is written
 * @param filterChain Passed in, but not used;
 *   <em>FilterChain.doFilter(...)</em> is <strong>never called</strong>.
 * @throws IOException Unlikely to be thrown except for an infrastructure failure
 * @throws ServletException Potentially thrown by interactions with <em>request</em>
 *   and <em>response</em>, but never explicitly raised in this method
 */
public void doFilter(final ServletRequest request, final ServletResponse response,
        final FilterChain filterChain) throws IOException, ServletException {

    HttpServletResponse httpResponse = (HttpServletResponse) response;

    if (log.isDebugEnabled()) {
        log.debug("Received the guid parameter: " + request.getParameter("guid"));
    }

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

    final PrintWriter writer = response.getWriter();
    try {
        String emailFromGuid = databaseService.getEmailAddressFromGuid(request.getParameter("guid"));
        if (log.isDebugEnabled()) {
            log.debug("Now passing back the email address: " + emailFromGuid);
        }

        if (emailFromGuid != null) {
            writer.write(emailFromGuid);
        } else {
            writer.write(
                    "Unable to lookup email address from the CAS server. Please contact the system administrator.");
        }
    } catch (Exception e) {
        log.error("Unable to query an email address or to write that email address to ServletResponse."
                + "  Attempted to query an email address for the guid = " + request.getParameter("guid"), e);
        //  TODO: Replace this with some clever logic.  This is NOT something to show to the user.
        writer.write("fake_guid_returned_from_cas");
    }

    // This next command is somewhat unfortunate.  A Filter should always invoke "doFilter(...)" at this point, but doing so can break this fragile email lookup.
    //   A typical failure mode is to see the login page in the middle of the Edit User Profile page, where the user's Email Address should be.
    // The core issue is that one of the other Filters may require authentication, so it calls the "/login" URL and the default behavior
    //   for that URL is to send the user to the Login page.  Ambra is querying for a single String (the user's email address), so it takes the String
    //   (which might be the entire Login page) and shows it to the user.
    // It is, therefore, recommended that Ambra acquire its users' email addresses in a different manner.
    return;
    // filterChain.doFilter(httpRequest, response);
}

From source file:eu.europeana.corelib.europeanastatic.controllers.ImageController.java

private void setImageCacheControlHeaders(HttpServletResponse response) {
    long now = System.currentTimeMillis();
    response.addHeader("Cache-Control", "max-age=" + CACHE_DURATION_IN_SECOND);
    response.addHeader("Cache-Control", "must-revalidate"); //optional
    response.setDateHeader("Last-Modified", now);
    response.setDateHeader("Expires", now + CACHE_DURATION_IN_SECOND * 1000);
}

From source file:org.opencms.frontend.templateone.form.CmsCaptchaField.java

/**
 * Writes a Captcha JPEG image to the servlet response output stream.
 * <p>/*  ww  w .j  a  v a  2  s . c o  m*/
 * 
 * @param cms an initialized Cms JSP action element
 * @throws IOException if something goes wrong
 */
public void writeCaptchaImage(CmsJspActionElement cms) throws IOException {

    ByteArrayOutputStream captchaImageOutput = new ByteArrayOutputStream();
    ServletOutputStream out = null;
    BufferedImage captchaImage = null;
    int maxTries = 10;
    do {
        try {

            maxTries--;
            String sessionId = cms.getRequest().getSession().getId();
            Locale locale = cms.getRequestContext().getLocale();

            captchaImage = CmsCaptchaServiceCache.getSharedInstance()
                    .getCaptchaService(m_captchaSettings, cms.getCmsObject())
                    .getImageChallengeForID(sessionId, locale);
        } catch (CaptchaException cex) {
            if (LOG.isErrorEnabled()) {
                LOG.error(cex);
                LOG.error(Messages.get().getBundle().key(Messages.LOG_ERR_CAPTCHA_CONFIG_IMAGE_SIZE_2,
                        new Object[] { m_captchaSettings.getPresetPath(), new Integer(maxTries) }));
            }
            m_captchaSettings.setImageHeight(m_captchaSettings.getImageHeight() + 40);
            m_captchaSettings.setImageWidth(m_captchaSettings.getImageWidth() + 80);
        }
    } while (captchaImage == null && maxTries > 0);
    try {

        ImageIO.write(captchaImage, "jpg", captchaImageOutput);
        CmsFlexController controller = CmsFlexController.getController(cms.getRequest());
        HttpServletResponse response = controller.getTopResponse();
        response.setHeader("Cache-Control", "no-store");
        response.setHeader("Pragma", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setContentType("image/jpeg");

        out = cms.getResponse().getOutputStream();
        out.write(captchaImageOutput.toByteArray());
        out.flush();

    } catch (Exception e) {

        if (LOG.isErrorEnabled()) {
            LOG.error(e.getLocalizedMessage(), e);
        }

        cms.getResponse().sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    } finally {

        try {
            if (out != null) {
                out.close();
            }
        } catch (Throwable t) {
            // intentionally left blank
        }
    }
}

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

@RequestMapping(value = "muestraPdf/{idContrato}/{idEmpleado}", method = RequestMethod.GET)
public void muestraPdf(@PathVariable("idContrato") Integer idContrato,
        @PathVariable("idEmpleado") Integer idEmpleado, HttpSession session, HttpServletRequest request,
        HttpServletResponse response) {

    if (session.getAttribute(USUARIO) == null && session.getAttribute(CLIENTE) == null) {
        return;//from  w ww .  ja v a2s . co  m
    }
    Contrato contrato = contratoService.buscarPorId(idContrato);
    response.setContentType("application/pdf");

    response.setHeader("Cache-Control", "no-cache");
    response.setHeader("Pragma", "no-cache");
    response.setDateHeader("Expires", 0);
    Usuario usuario = usuarioService.buscarPorId(idEmpleado);
    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:com.alkacon.opencms.formgenerator.CmsCaptchaField.java

/**
 * Writes a Captcha JPEG image to the servlet response output stream.
 * <p>// w w w  . j av  a 2 s.com
 * 
 * @param cms an initialized Cms JSP action element
 * @throws IOException if something goes wrong
 */
public void writeCaptchaImage(CmsJspActionElement cms) throws IOException {

    // remove eventual session attribute containing captcha settings
    cms.getRequest().getSession().removeAttribute(SESSION_PARAM_CAPTCHASETTINGS);
    String sessionId = cms.getRequest().getSession().getId();
    Locale locale = cms.getRequestContext().getLocale();
    BufferedImage captchaImage = null;
    int maxTries = 10;
    do {
        try {
            maxTries--;
            captchaImage = ((ImageCaptchaService) CmsCaptchaServiceCache.getSharedInstance()
                    .getCaptchaService(m_captchaSettings, cms.getCmsObject())).getImageChallengeForID(sessionId,
                            locale);
        } catch (CaptchaException cex) {
            // image size is too small, increase dimensions and try it again
            if (LOG.isInfoEnabled()) {
                LOG.info(cex);
                LOG.info(Messages.get().getBundle().key(Messages.LOG_ERR_CAPTCHA_CONFIG_IMAGE_SIZE_2,
                        new Object[] { m_captchaSettings.getPresetPath(), new Integer(maxTries) }));
            }
            m_captchaSettings.setImageHeight((int) (m_captchaSettings.getImageHeight() * 1.1));
            m_captchaSettings.setImageWidth((int) (m_captchaSettings.getImageWidth() * 1.1));
            // IMPORTANT: store changed captcha settings in session, they have to be used when validating the phrase
            cms.getRequest().getSession().setAttribute(SESSION_PARAM_CAPTCHASETTINGS,
                    m_captchaSettings.clone());
        }
    } while ((captchaImage == null) && (maxTries > 0));

    ServletOutputStream out = null;
    try {
        CmsFlexController controller = CmsFlexController.getController(cms.getRequest());
        HttpServletResponse response = controller.getTopResponse();
        response.setHeader("Cache-Control", "no-store");
        response.setHeader("Pragma", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setContentType("image/jpeg");

        ByteArrayOutputStream captchaImageOutput = new ByteArrayOutputStream();
        ImageIO.write(captchaImage, "jpg", captchaImageOutput);
        out = cms.getResponse().getOutputStream();
        out.write(captchaImageOutput.toByteArray());
        out.flush();
    } catch (Exception e) {
        if (LOG.isErrorEnabled()) {
            LOG.error(e.getLocalizedMessage(), e);
        }
        cms.getResponse().sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    } finally {
        try {
            if (out != null) {
                out.close();
            }
        } catch (Throwable t) {
            // intentionally left blank
        }
    }
}

From source file:org.overlord.sramp.ui.server.servlets.AbstractDownloadServlet.java

/**
 * Do download content./*from w  w  w. j a  v a2s  .c o m*/
 *
 * @param content
 *            the content
 * @param contentType
 *            the content type
 * @param disposition
 *            the disposition
 * @param httpResponse
 *            the http response
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 */
protected void doDownloadContent(InputStream content, String contentType, String disposition,
        HttpServletResponse httpResponse) throws IOException {
    if (StringUtils.isNotBlank(disposition)) {
        httpResponse.setHeader("Content-Disposition", disposition); //$NON-NLS-1$
    }
    if (StringUtils.isNotBlank(contentType)) {
        httpResponse.setHeader("Content-Type", contentType); //$NON-NLS-1$
    }

    // Make sure the browser doesn't cache it
    Date now = new Date();
    httpResponse.setDateHeader("Date", now.getTime()); //$NON-NLS-1$
    httpResponse.setDateHeader("Expires", now.getTime() - 86400000L); //$NON-NLS-1$
    httpResponse.setHeader("Pragma", "no-cache"); //$NON-NLS-1$ //$NON-NLS-2$
    httpResponse.setHeader("Cache-control", "no-cache, no-store, must-revalidate"); //$NON-NLS-1$ //$NON-NLS-2$
    try {
        IOUtils.copy(content, httpResponse.getOutputStream());
    } finally {
        IOUtils.closeQuietly(content);
    }
}