Example usage for javax.servlet.http HttpServletResponse addDateHeader

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

Introduction

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

Prototype

public void addDateHeader(String name, long date);

Source Link

Document

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

Usage

From source file:org.craftercms.studio.impl.v1.util.spring.mvc.BinaryView.java

@Override
protected void prepareResponse(HttpServletRequest request, HttpServletResponse response) {
    response.setContentType(getContentType());
    response.setCharacterEncoding(DEFAULT_CHARACTER_ENCODING);
    if (disableCaching) {
        response.addHeader(PRAGMA_HEADER_NAME, DISABLED_CACHING_PRAGMA_HEADER_VALUE);
        response.addHeader(CACHE_CONTROL_HEADER_NAME, DISABLED_CACHING_CACHE_CONTROL_HEADER_VALUE);
        response.addDateHeader(EXPIRES_HEADER_NAME, DISABLED_CACHING_EXPIRES_HEADER_VALUE);
    }/*from  w  ww .  ja v a  2s.  c o  m*/
}

From source file:org.cruxframework.crux.core.server.crawling.CrawlingFilter.java

/**
 * /*from  w ww . jav  a2 s .  c om*/
 */
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException {
    try {
        if (!Environment.isProduction()) {
            chain.doFilter(req, res);
            return;
        }
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response;
        String ae = request.getHeader(ACCEPT_ENCODING);
        boolean gzipped = false;
        if (ae != null && ae.indexOf("gzip") != -1) {
            response = new GZIPResponseWrapper((HttpServletResponse) res);
            gzipped = true;
        } else {
            response = (HttpServletResponse) res;
        }

        response.setContentType("text/html");
        response.setCharacterEncoding("UTF-8");
        String escapedFragmentEncoded = request.getParameter("_escaped_fragment_");
        if (escapedFragmentEncoded != null) {
            if (logger.isInfoEnabled()) {
                logger.info("A Snapshot for an application page was requested.");
            }
            if (escapedFragmentEncoded.length() == 0 && defaultSnaphot != null && defaultSnaphot.length() > 0) {
                escapedFragmentEncoded = defaultSnaphot;
            }

            String escapedFragment = URLDecoder.decode(escapedFragmentEncoded, "UTF-8");
            String page = getRequestedPage(request);
            String pagePath = CrawlingUtils.getStaticPageFor(page, escapedFragment);
            if (pagePath != null && pagePath.length() > 0) {
                if (StringUtils.isNotBlank(baseFolder)) {
                    pagePath = baseFolder + "/" + pagePath;
                }
                InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream(pagePath);
                if (in == null) {
                    logger.error("snapshot for requested page [" + pagePath + "] not found.");
                } else {
                    try {
                        StreamUtils.write(in, response.getOutputStream(), true);
                        if (logger.isInfoEnabled()) {
                            logger.info("Snapshot for page [" + pagePath + "] was sent.");
                        }
                        return;
                    } catch (IOException e) {
                        logger.error("Error reading requested page [" + pagePath + "].", e);
                    }
                }
            } else {
                logger.error("A snapshot was requested, but it is not possible to realize the target page.");
            }
        }
        long current = System.currentTimeMillis();
        long expires = current + EXPIRES_DELTA;
        HttpServletResponse httpResponse = ((HttpServletResponse) response);
        httpResponse.addDateHeader("Expires", expires);
        httpResponse.addDateHeader("Last-Modified", current);
        response.addHeader("Cache-Control", "public, max-age=" + (EXPIRES_DELTA / 1000));// seconds
        chain.doFilter(request, response);
        if (gzipped) {
            ((GZIPResponseWrapper) response).finishResponse();
        }
    } catch (ServletException e) {
        logger.error("Error processing request", e);
    }
}

From source file:org.cruxframework.crux.core.server.offline.AppcacheFilter.java

private void sendRequestedFile(FilterChain chain, HttpServletRequest request, HttpServletResponse response,
        long dateModified) throws IOException, ServletException {
    String ae = request.getHeader(HttpHeaderNames.ACCEPT_ENCODING);
    if (ae != null && ae.indexOf("gzip") != -1) {
        response = new GZIPResponseWrapper(response);
    }/*  www .j a  v a2 s  .co m*/
    response = new ResponseWrapper(response, request.getContextPath());

    response.setContentType("text/cache-manifest");
    response.setCharacterEncoding("UTF-8");
    CacheControl cache = new CacheControl();
    cache.setNoCache(true);
    response.addHeader(HttpHeaderNames.CACHE_CONTROL, CacheControlHeaderParser.toString(cache));
    response.addDateHeader(HttpHeaderNames.EXPIRES, System.currentTimeMillis());
    if (dateModified > 0) {
        response.addDateHeader(HttpHeaderNames.LAST_MODIFIED, dateModified);
    }
    chain.doFilter(request, response);
    ((ResponseWrapper) response).finishResponse();
}

From source file:org.dspace.app.webui.jsptag.LayoutTag.java

public int doEndTag() throws JspException {
    // Context objects
    ServletRequest request = pageContext.getRequest();
    HttpServletResponse response = (HttpServletResponse) pageContext.getResponse();
    ServletConfig config = pageContext.getServletConfig();

    // header file
    String header = templatePath + "header-default.jsp";

    // Choose default style unless one is specified
    if (style != null) {
        header = templatePath + "header-" + style.toLowerCase() + ".jsp";
    }//ww w.  j  a  v a 2 s .c om

    if (sidebar != null) {
        request.setAttribute("dspace.layout.sidebar", sidebar);
    }

    // Now include the header
    try {
        // Set headers to prevent browser caching, if appropriate
        if ((noCache != null) && noCache.equalsIgnoreCase("true")) {
            response.addDateHeader("expires", 1);
            response.addHeader("Pragma", "no-cache");
            response.addHeader("Cache-control", "no-store");
        }

        // Ensure the HTTP header will declare that UTF-8 is used
        // in the response.
        response.setContentType("text/html; charset=UTF-8");

        RequestDispatcher rd = config.getServletContext().getRequestDispatcher(header);

        rd.include(request, response);

        //pageContext.getOut().write(getBodyContent().getString());
        getBodyContent().writeOut(pageContext.getOut());
    } catch (IOException ioe) {
        throw new JspException("Got IOException: " + ioe);
    } catch (ServletException se) {
        log.warn("Exception", se.getRootCause());
        throw new JspException("Got ServletException: " + se);
    }

    // Footer file to use
    String footer = templatePath + "footer-default.jsp";

    // Choose default flavour unless one is specified
    if (style != null) {
        footer = templatePath + "footer-" + style.toLowerCase() + ".jsp";
    }

    try {
        // Ensure body is included before footer
        pageContext.getOut().flush();

        RequestDispatcher rd = config.getServletContext().getRequestDispatcher(footer);

        rd.include(request, response);
    } catch (ServletException se) {
        throw new JspException("Got ServletException: " + se);
    } catch (IOException ioe) {
        throw new JspException("Got IOException: " + ioe);
    }

    style = null;
    title = null;
    sidebar = null;
    navbar = null;
    locbar = null;
    parentTitle = null;
    parentLink = null;
    noCache = null;
    feedData = null;
    return EVAL_PAGE;
}

From source file:org.dspace.webmvc.utils.Authenticate.java

/**
 * Start the authentication process. This packages up the request that led
 * to authentication being required, and then invokes the site-specific
 * authentication method.//from   w  ww.j a v  a 2 s . c o  m
 * 
 * If it returns true, the user was authenticated without any
 * redirection (e.g. by an X.509 certificate or other implicit method) so
 * the process that called this can continue and send its own response.
 * A "false" result means this method has sent its own redirect.
 *
 * @param context
 *            current DSpace context
 * @param request
 *            current HTTP request - the one that prompted authentication
 * @param response
 *            current HTTP response
 *
 * @return true if authentication is already finished (implicit method)
 */
public static boolean startAuthentication(Context context, HttpServletRequest request,
        HttpServletResponse response) throws ServletException, IOException {
    HttpSession session = request.getSession();

    /*
     * Authenticate:
     * 1. try implicit methods first, since that may work without
     *    a redirect. return true if no redirect needed.
     * 2. if those fail, redirect to enter credentials.
     *    return false.
     */
    if (AuthenticationManager.authenticateImplicit(context, null, null, null,
            request) == AuthenticationMethod.SUCCESS) {
        loggedIn(context, request, context.getCurrentUser());
        log.info(LogManager.getHeader(context, "login", "type=implicit"));
        return true;
    } else {
        // Since we may be doing a redirect, make sure the redirect is not
        // cached
        response.addDateHeader("expires", 1);
        response.addHeader("Pragma", "no-cache");
        response.addHeader("Cache-control", "no-store");

        // Store the data from the request that led to authentication
        RequestInfo info = new RequestInfo(request);
        session.setAttribute("interrupted.request.info", info);

        // Store the URL of the request that led to authentication
        session.setAttribute("interrupted.request.url", getOriginalURL(request));

    } //end else 

    return false;
}

From source file:org.etudes.ambrosia.impl.UiServiceImpl.java

/**
 * {@inheritDoc}/*from w  w w . j a va 2s .co  m*/
 */
public Context prepareGet(HttpServletRequest req, HttpServletResponse res, String home) throws IOException {
    // get the Tool session
    ToolSession toolSession = m_sessionManager.getCurrentToolSession();

    // record the current destination before this request; i.e. the previous destination
    String previousDestination = (String) toolSession.getAttribute(ActiveTool.TOOL_ATTR_CURRENT_DESTINATION);
    m_threadLocalManager.set("ambrosia_" + ActiveTool.TOOL_ATTR_CURRENT_DESTINATION, previousDestination);

    // keep track (manually, for now) of our current destination
    String destination = req.getPathInfo();
    if (destination == null)
        destination = "/" + ((home != null) ? home : "");
    toolSession.setAttribute(ActiveTool.TOOL_ATTR_CURRENT_DESTINATION, destination);

    // fragment or not?
    boolean fragment = Boolean.TRUE.toString().equals(req.getAttribute(Tool.FRAGMENT));

    if (!fragment) {
        // setup type and no caching
        res.setContentType("text/html; charset=UTF-8");
        res.addDateHeader("Expires", System.currentTimeMillis() - (1000L * 60L * 60L * 24L * 365L));
        res.addDateHeader("Last-Modified", System.currentTimeMillis());
        res.addHeader("Cache-Control",
                "no-store, no-cache, must-revalidate, max-age=0, post-check=0, pre-check=0");
        res.addHeader("Pragma", "no-cache");
    }

    // our response writer
    PrintWriter out = res.getWriter();

    UiContext context = new UiContext(this);
    context.setDestination(destination);
    context.setPreviousDestination(previousDestination);
    context.setResponseWriter(out);
    context.put(UiContext.FRAGMENT, Boolean.valueOf(fragment));
    context.put("sakai.html.head", req.getAttribute("sakai.html.head"));
    //   context.put("sakai.html.head.no.wiris", req.getAttribute("sakai.html.head.no.wiris"));
    context.put("sakai.html.body.onload", req.getAttribute("sakai.html.body.onload"));
    context.put("sakai.return.url", Web.returnUrl(req, ""));
    context.put("sakai.server.url", Web.serverUrl(req));

    String destinationUrl = Web.returnUrl(req, destination);
    context.put("sakai.destination.url", destinationUrl);
    context.put("sakai_destination", destination);

    context.put("sakai_prev_destination", (previousDestination == null ? "/" : previousDestination));

    // setup that a POST to this destination will be expected
    String previousExpected = (String) toolSession
            .getAttribute(ActiveTool.TOOL_ATTR_CURRENT_DESTINATION + ".expected");
    m_threadLocalManager.set("ambrosia_" + ActiveTool.TOOL_ATTR_CURRENT_DESTINATION + ".expected",
            previousExpected);
    toolSession.setAttribute(ActiveTool.TOOL_ATTR_CURRENT_DESTINATION + ".expected", destination);

    // // setup a valid POST receipt for this tool destination
    // Object postCoordinator = toolSession.getAttribute("sakai.post.coordinator");
    // if (postCoordinator == null)
    // {
    // postCoordinator = new Object();
    // toolSession.setAttribute("sakai.post.coordinator", postCoordinator);
    // }
    // synchronized (postCoordinator)
    // {
    // toolSession.setAttribute(destinationUrl, destinationUrl);
    // }

    return context;
}

From source file:org.etudes.ambrosia.util.AmbrosiaServlet.java

/**
 * Send a redirect so our "top" ends up at the url, via javascript.
 * /*from   w ww  .j  a  v  a2 s .co m*/
 * @param url
 *        The redirect url
 */
protected void sendTopRedirect(HttpServletResponse res, String url) throws IOException {
    res.setContentType("text/html; charset=UTF-8");
    res.addDateHeader("Expires", System.currentTimeMillis() - (1000L * 60L * 60L * 24L * 365L));
    res.addDateHeader("Last-Modified", System.currentTimeMillis());
    res.addHeader("Cache-Control", "no-store, no-cache, must-revalidate, max-age=0, post-check=0, pre-check=0");
    res.addHeader("Pragma", "no-cache");

    // get the writer
    PrintWriter out = res.getWriter();

    // we are on deep under the main portal window
    out.println("<html><head></head><body><script language=\"JavaScript\">parent.location.replace('" + url
            + "');</script></body></html>");
}

From source file:org.etudes.tool.melete.MeleteJsfTool.java

/**
 * Respond to requests./*from  w  w w .  j a v  a2 s.c  o  m*/
 * 
 * @param req
 *        The servlet request.
 * @param res
 *        The servlet response.
 * @throws ServletException.
 * @throws IOException.
 */
protected void dispatch(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    // NOTE: this is a simple path dispatching, taking the path as the view id = jsp file name for the view,
    // with default used if no path and a path prefix as configured.
    // TODO: need to allow other sorts of dispatching, such as pulling out drill-down ids and making them
    // available to the JSF

    // build up the target that will be dispatched to
    String target = req.getPathInfo();

    // see if we have a resource request - i.e. a path with an extension, and one that is not the JSF_EXT
    if (isResourceRequest(target)) {
        // get a dispatcher to the path
        RequestDispatcher resourceDispatcher = getServletContext().getRequestDispatcher(target);
        if (resourceDispatcher != null) {
            resourceDispatcher.forward(req, res);
            return;
        }
    }

    if ("Title".equals(req.getParameter("panel"))) {
        // This allows only one Title JSF for each tool
        target = "/title.jsf";
    } else {
        ToolSession session = SessionManager.getCurrentToolSession();

        if (target == null || "/".equals(target)) {
            target = computeDefaultTarget();

            // make sure it's a valid path
            if (!target.startsWith("/")) {
                target = "/" + target;
            }

            // now that we've messed with the URL, send a redirect to make it official
            res.sendRedirect(Web.returnUrl(req, target));
            return;
        }

        // see if we want to change the specifically requested view
        String newTarget = redirectRequestedTarget(target);

        // make sure it's a valid path
        if (!newTarget.startsWith("/")) {
            newTarget = "/" + newTarget;
        }

        if (!newTarget.equals(target)) {
            // now that we've messed with the URL, send a redirect to make it official
            res.sendRedirect(Web.returnUrl(req, newTarget));
            return;
        }
        target = newTarget;

        // store this
        if (m_defaultToLastView) {
            String params = req.getQueryString();
            if (params != null) {
                session.setAttribute(LAST_VIEW_VISITED, target + "?" + params);
            } else {
                session.setAttribute(LAST_VIEW_VISITED, target);
            }
        }
    }

    // these URL paths have the module id encoded in the URL - remove it and place it in threadLocal
    if (target.startsWith("/view_module/") || target.startsWith("/edit_module/")) {
        String[] parts = StringUtil.split(target, "/");

        if (parts.length == 6) {
            String id = parts[2];
            ThreadLocalManager.set("MELETE_MODULE_ID", id);
            String returnBackUrl = "/portal/directtool/" + parts[4] + "/" + parts[5];
            ThreadLocalManager.set("MELETE_NAVIGATE_BACK", returnBackUrl);
            target = "/" + parts[1];
        }
    }

    // Add variable to autosave module and section changes
    if (target.startsWith("/edit_module")) {
        ThreadLocalManager.set("MELETE_SAVE_FROM", "editModule");
    } else if (target.startsWith("/add_module")) {
        ThreadLocalManager.set("MELETE_SAVE_FROM", "addModule");
    } else if (target.startsWith("/editmodulesections")) {
        ThreadLocalManager.set("MELETE_SAVE_FROM", "Section");
    } else if (target.startsWith("/list_auth_modules")) {
        ThreadLocalManager.set("MELETE_SAVE_FROM", "listAuth");
    } else if (target.startsWith("/author_preference")) {
        ThreadLocalManager.set("MELETE_SAVE_FROM", "authPref");
    }

    // add the configured folder root and extension (if missing)
    target = m_path + target;

    // add the default JSF extension (if we have no extension)
    int lastSlash = target.lastIndexOf("/");
    int lastDot = target.lastIndexOf(".");
    if (lastDot < 0 || lastDot < lastSlash) {
        target += JSF_EXT;
    }

    // set the information that can be removed from return URLs
    req.setAttribute(URL_PATH, m_path);
    req.setAttribute(URL_EXT, ".jsp");

    // set the sakai request object wrappers to provide the native, not Sakai set up, URL information
    // - this assures that the FacesServlet can dispatch to the proper view based on the path info
    req.setAttribute(Tool.NATIVE_URL, Tool.NATIVE_URL);

    // TODO: Should setting the HTTP headers be moved up to the portal level as well?
    res.setContentType("text/html; charset=UTF-8");
    res.setCharacterEncoding("UTF-8");
    res.addDateHeader("Expires", System.currentTimeMillis() - (1000L * 60L * 60L * 24L * 365L));
    res.addDateHeader("Last-Modified", System.currentTimeMillis());
    res.addHeader("Cache-Control", "no-store, no-cache, must-revalidate, max-age=0, post-check=0, pre-check=0");
    res.addHeader("Pragma", "no-cache");

    // dispatch to the target
    M_log.debug("dispatching path: " + req.getPathInfo() + " to: " + target + " context: "
            + getServletContext().getServletContextName());
    RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(target);
    dispatcher.forward(req, res);

    // restore the request object
    req.removeAttribute(Tool.NATIVE_URL);
    req.removeAttribute(URL_PATH);
    req.removeAttribute(URL_EXT);
}

From source file:org.guanxi.sp.sakai.portal.tool.GuanxiPortal.java

/**
 * Produces an HTML error page/*from w  w w.  j a  v  a 2  s.co  m*/
 *
 * @param req Standard HttpServletRequest
 * @param res Standard HttpServletResponse
 * @param pageTitle The large text for the error summary
 * @param errorText The smaller text describing the error
 * @throws IOException If an error occurs
 */
protected void doError(HttpServletRequest req, HttpServletResponse res, String pageTitle, String errorText)
        throws IOException {
    res.setContentType("text/html; charset=UTF-8");
    res.addDateHeader("Expires", System.currentTimeMillis() - (1000L * 60L * 60L * 24L * 365L));
    res.addDateHeader("Last-Modified", System.currentTimeMillis());
    res.addHeader("Cache-Control", "no-store, no-cache, must-revalidate, max-age=0, post-check=0, pre-check=0");
    res.addHeader("Pragma", "no-cache");

    PrintWriter out = res.getWriter();

    out.println("<html><head><title>Sakai Shibboleth Portal</title></head><body>");

    // Show session information
    out.println("<H2>" + pageTitle + "</H2>");
    out.println("<p>" + errorText + "</p>");

    // close the response
    out.println("</body></html>");

    out.close();
}

From source file:org.infoscoop.web.KeywordRankingServlet.java

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    String uid = (String) request.getSession().getAttribute("Uid");

    if (log.isInfoEnabled()) {
        log.info("uid:[" + uid + "]: doPost");
    }//from ww w. j ava 2s. c  om

    response.setHeader("Pragma", "no-cache");
    response.setHeader("Cache-Control", "no-cache");

    OutputStream out = null;

    int rankingPeriod;
    int rankingNum;
    String endDate;
    int offset = UserContext.instance().getUserInfo().getClientTimezoneOffset() / 60;
    String cacheName = "keywordRanking_UTC" + offset;

    try {
        String param_baseDate = request.getParameter("baseDate");

        // If baseDate is null, it is behavior of TODAY.
        endDate = (param_baseDate == null) ? TODAY : param_baseDate;

        Cache cache = CacheDAO.newInstance().getCacheById(cacheName);

        String rss;
        // We do cash only in case that appoined "TODAY".
        if (TODAY.equals(endDate) && cache != null && DateUtility.isToday(cache.getTimestamp())) {
            List<Header> headerList = cache.getHeaderList();
            for (Header header : headerList) {
                if (header.getName().equalsIgnoreCase("Last-Modified")) {
                    String lastModified = header.getValue();
                    if (lastModified != null && lastModified.equals(request.getHeader("If-Modified-Since"))) {
                        response.setStatus(304);
                        return;
                    }
                    response.addHeader("Last-Modified", lastModified);
                }
            }

            rss = new String(cache.getBodyBytes(), "UTF-8");
            log.info("get keywordRanking from cache.");
        } else {
            String param_period = request.getParameter("period");
            String param_rankingNum = request.getParameter("rankingNum");

            try {
                rankingPeriod = Integer.parseInt(param_period);
            } catch (NumberFormatException e) {
                log.warn("rankingPeriod [" + param_period + "] is not integer !");
                rankingPeriod = RANKING_PERIOD_DEFAULT;
            }
            try {
                rankingNum = Integer.parseInt(param_rankingNum);
            } catch (NumberFormatException e) {
                log.warn("rankingNum[" + param_rankingNum + "] is not integer !");
                rankingNum = RANKING_NUM_DEFAULT;
            }

            // check of the maximum
            rankingPeriod = (rankingPeriod > RANKING_PERIOD_MAX) ? RANKING_PERIOD_MAX : rankingPeriod;
            rankingNum = (rankingNum > RANKING_NUM_MAX) ? RANKING_NUM_MAX : rankingNum;

            boolean saveCache = true;
            SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
            sdf.setTimeZone(TimeZone.getTimeZone("UTC"));

            if (TODAY.equals(endDate)) {
                Calendar yesterday = Calendar.getInstance();
                yesterday.setTimeZone(TimeZone.getTimeZone("UTC"));
                yesterday.set(Calendar.HOUR_OF_DAY, 0);
                endDate = sdf.format(yesterday.getTime());
            } else if (NOW.equals(endDate)) {
                endDate = sdf.format(new Date());
                saveCache = false; // When it is appointed "NOW", we don't do cash.
            }

            Map countMap = KeywordLogDAO.newInstance().getCountMap(getStartDate(endDate, rankingPeriod),
                    endDate, new Integer(0));
            if (countMap.size() == 0) {
                response.setStatus(204);
                return;
            }

            response.addDateHeader("Last-Modified", new Date().getTime());
            rss = makeRss(countMap, rankingPeriod, rankingNum);

            if (saveCache)
                insertRss(cacheName, rss);
        }

        boolean noProxy = false;
        Enumeration headers = request.getHeaderNames();
        while (headers.hasMoreElements()) {
            String headerName = (String) headers.nextElement();
            if (headerName.equalsIgnoreCase("X-IS-NOPROXY")) {
                noProxy = true;
                break;
            }
        }

        byte[] resByte;
        if (noProxy) {
            response.setContentType("text/plain; charset=UTF-8");
            String requestURL = request.getRequestURL() != null ? request.getRequestURL().toString() : "";
            ProxyRequest proxyRequest = new ProxyRequest(requestURL, "RSSReader");
            proxyRequest.setPortalUid((String) request.getSession().getAttribute("Uid"));

            resByte = RssFilter.process(proxyRequest, new ByteArrayInputStream(rss.getBytes("UTF-8")));
        } else {
            response.setContentType("text/xml; charset=UTF-8");
            resByte = rss.getBytes("UTF-8");
        }

        out = response.getOutputStream();
        out.write(resByte);
    } catch (Exception e) {
        log.error("--- unexpected error occurred.", e);
        response.sendError(500);
    } finally {
        if (out != null) {
            out.flush();
            out.close();
        }
    }
}