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.xwiki.resource.servlet.AbstractServletResourceReferenceHandler.java

/**
 * Sets the response headers needed to cache the resource permanently, if the resource can be cached.
 * /*from  w  w  w.j  a va  2  s  .  c om*/
 * @param response the response
 * @param resourceReference the resource that is being served
 */
private void setResponseHeaders(Response response, R resourceReference) {
    // Cache the resource if possible.
    if (response instanceof ServletResponse && isResourceCacheable(resourceReference)) {
        HttpServletResponse httpResponse = ((ServletResponse) response).getHttpServletResponse();
        httpResponse.setHeader(HttpHeaders.CACHE_CONTROL, "public");
        httpResponse.setDateHeader(HttpHeaders.EXPIRES, new Date().getTime() + CACHE_DURATION);
        // Even if the resource is cached permanently, most browsers are still sending a request if the user reloads
        // the page using F5. We send back the "Last-Modified" header in the response so that the browser will send
        // us an "If-Modified-Since" request for any subsequent call for this static resource. When this happens we
        // return a 304 to tell the browser to use its cached version.
        httpResponse.setDateHeader(HttpHeaders.LAST_MODIFIED, new Date().getTime());
    }
}

From source file:nl.b3p.viewer.stripes.CombineImageActionBean.java

/**
 * Combines the image settings to a new image.
 * @return a image./*from   www  .  j  a v a 2s  .c o m*/
 * @throws Exception 
 */
public Resolution getImage() throws Exception {
    if (imageId == null || imageSettings.get(imageId) == null) {
        throw new Exception("No imageId given");
    }
    //final CombineImageSettings settings = (CombineImageSettings) getContext().getRequest().getSession().getAttribute(imageId);
    final CombineImageSettings settings = imageSettings.get(imageId);
    //if these settings are given then overwrite those in the CombineImageSettings
    if (this.getWidth() != null && this.getWidth() > 0) {
        settings.setWidth(getWidth());
    }
    if (this.getHeight() != null && this.getHeight() > 0) {
        settings.setHeight(getHeight());
    }
    if (this.getBbox() != null) {
        settings.setBbox(getBbox());
    }
    if (this.getGeom() != null) {
        String firstChar = geom.substring(0, 1);
        try {
            int test = Integer.parseInt(firstChar);
            // This is a bounding box, so parse it into a linestring
            String[] tokens = geom.split(",");
            String minx = tokens[0];
            String miny = tokens[1];
            String maxx = tokens[2];
            String maxy = tokens[3];
            String wkt = "LINESTRING(";
            wkt += minx + " " + miny + ", ";
            wkt += maxx + " " + miny + ", ";
            wkt += maxx + " " + maxy + ", ";
            wkt += minx + " " + maxy + ", ";
            wkt += minx + " " + miny + ")";
            this.geom = wkt;
        } catch (NumberFormatException e) {
            // this is not a boundingbox
        }
        CombineImageWkt ciw = new CombineImageWkt(geom);
        ciw.setStrokeWidth(8f);
        if (settings.getWktGeoms() == null) {
            settings.setWktGeoms(new ArrayList());
        }
        settings.getWktGeoms().add(ciw);
    }

    //stream the result.
    StreamingResolution res = new StreamingResolution(settings.getMimeType()) {
        @Override
        public void stream(HttpServletResponse response) throws Exception {
            OutputStream out = response.getOutputStream();
            response.setDateHeader("Expires", System.currentTimeMillis() + (1000 * 60 * 60 * 24));
            CombineImagesHandler.combineImage(out, settings, settings.getMimeType(), maxResponseTime);
        }
    };
    return res;
}

From source file:biz.webgate.dominoext.poi.component.kernel.CSVProcessor.java

public void generateNewFile(UICSV csvDef, HttpServletResponse httpResponse, FacesContext context) {

    try {// www  .j av a2s.  c  o  m
        // First getting the File

        ByteArrayOutputStream csvBAOS = generateCSV(csvDef, context);

        httpResponse.setContentType("text/csv");
        httpResponse.setHeader("Cache-Control", "no-cache");
        httpResponse.setDateHeader("Expires", -1);
        httpResponse.setContentLength(csvBAOS.size());
        httpResponse.addHeader("Content-disposition",
                "inline; filename=\"" + csvDef.getDownloadFileName() + "\"");
        OutputStream os = httpResponse.getOutputStream();
        csvBAOS.writeTo(os);
        os.close();
    } catch (Exception e) {
        ErrorPageBuilder.getInstance().processError(httpResponse, "Error during CSV-Generation", e);
    }

}

From source file:org.javarebel.chart.ChartComponentListener.java

@Override
public void beforePhase(PhaseEvent arg0) {
    FacesContext context = arg0.getFacesContext();
    ExternalContext eCtx = context.getExternalContext();

    HttpServletRequest req = (HttpServletRequest) eCtx.getRequest();
    String data_KEY = req.getParameter("data_KEY");
    logger.info("Chart Data Key is " + data_KEY);

    HttpSession session = req.getSession();
    if (data_KEY != null) {
        Object chartData = session.getAttribute(data_KEY);

        if (chartData != null) {

            ChartData data = ChartData.class.cast(chartData);
            logger.info("Chart Type received is " + data.getType());
            IChartGenerator chartGen = ChartGeneratorFactory.getChartGenerator(data.getType());
            logger.info("ChartGenerator in use -> " + chartGen.getClass().getName());
            JFreeChart chart = chartGen.generateChart(data);

            BufferedImage img = chart.createBufferedImage(Integer.valueOf(data.getWidth()),
                    Integer.valueOf(data.getHeight()));
            try {
                HttpServletResponse response = (HttpServletResponse) eCtx.getResponse();
                response.setContentType("image/png");
                response.setHeader("Cache-Control", "no-store");
                response.setHeader("Pragma", "no-cache");
                response.setDateHeader("Expires", 0L);

                ServletOutputStream output = response.getOutputStream();
                ImageIO.write(img, "png", output);

                session.removeAttribute(data_KEY);

                context.responseComplete();
            } catch (Exception e) {
                logger.log(Level.SEVERE, e.getMessage(), e);
                throw new IllegalStateException(e);
            }/*from   ww w  . j  ava  2  s.  co  m*/
        }
    }
}

From source file:nl.strohalm.cyclos.utils.ResponseHelper.java

/**
 * Writes a file contents to the response
 *//*  w ww  .j  av  a 2  s .co  m*/
public void writeFile(final HttpServletResponse response, final File file) throws IOException {
    if (file.exists()) {
        response.setContentLength((int) file.length());
        response.setDateHeader("Last-Modified", file.lastModified());
        final InputStream in = new FileInputStream(file);
        try {
            IOUtils.copy(in, response.getOutputStream());
        } finally {
            IOUtils.closeQuietly(in);
        }
    }
}

From source file:org.apereo.portal.security.mvc.LoginController.java

/**
 * Process the incoming HttpServletRequest.  Note that this processing occurs after
 * PortalPreAuthenticatedProcessingFilter has run and performed pre-processing.
 * @param request//w w w. ja  va 2s .c  o m
 * @param response
 * @exception ServletException
 * @exception IOException
 */
@RequestMapping
public void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setHeader("Pragma", "no-cache");
    response.setHeader("Cache-Control", "no-cache");
    response.setDateHeader("Expires", 0);

    // create the redirect URL, adding fname and args parameters if necessary
    String redirectTarget = null;

    final String refUrl = request.getParameter(REFERER_URL_PARAM);
    final URL redirectLocation = parseLocalRefUrl(request, refUrl);
    if (redirectLocation != null) {
        redirectTarget = redirectLocation.toString();
    }

    if (redirectTarget == null) {
        /* Grab the target functional name, if any, off the login request.
         * Also any arguments for the target. We will pass them  along after authentication.
         */
        String targetFname = request.getParameter("uP_fname");

        if (targetFname == null) {
            final IPortalUrlBuilder defaultUrl = this.portalUrlProvider.getDefaultUrl(request);
            redirectTarget = defaultUrl.getUrlString();
        } else {
            try {
                final IPortalUrlBuilder urlBuilder = this.portalUrlProvider
                        .getPortalUrlBuilderByPortletFName(request, targetFname, UrlType.RENDER);

                Enumeration<String> e = request.getParameterNames();
                while (e.hasMoreElements()) {
                    String paramName = e.nextElement();
                    if (!paramName.equals("uP_fname")) {
                        urlBuilder.addParameter(paramName, request.getParameterValues(paramName));
                    }
                }

                redirectTarget = urlBuilder.getUrlString();
            } catch (IllegalArgumentException e) {
                final IPortalUrlBuilder defaultUrl = this.portalUrlProvider.getDefaultUrl(request);
                redirectTarget = defaultUrl.getUrlString();
            }
        }
    }

    IPerson person = null;

    final Object authError = request.getSession(false).getAttribute(LoginController.AUTH_ERROR_KEY);
    if (authError == null || !((Boolean) authError)) {
        person = this.personManager.getPerson(request);
    }

    if (person == null || !person.getSecurityContext().isAuthenticated()) {
        if (request.getMethod().equals("POST"))
            request.getSession(false).setAttribute(AUTH_ATTEMPTED_KEY, "true");
        // Preserve the attempted username so it can be redisplayed to the user
        String attemptedUserName = request.getParameter("userName");
        if (attemptedUserName != null)
            request.getSession(false).setAttribute(ATTEMPTED_USERNAME_KEY, request.getParameter("userName"));
    }

    final String encodedRedirectURL = response.encodeRedirectURL(redirectTarget);

    if (log.isDebugEnabled()) {
        log.debug("Redirecting to " + redirectTarget);
    }

    response.sendRedirect(encodedRedirectURL);
}

From source file:org.rhq.enterprise.gui.agentupdate.AgentUpdateServlet.java

private void getVersion(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    try {// w  w w . j  a v a 2 s .c o  m
        File versionFile = getAgentUpdateVersionFile();
        resp.setContentType("text/plain");
        resp.setDateHeader("Last-Modified", versionFile.lastModified());

        FileInputStream stream = new FileInputStream(versionFile);
        byte[] versionData = StreamUtil.slurp(stream);
        resp.getOutputStream().write(versionData);
    } catch (Throwable t) {
        log.error("Failed to stream version info.", t);
        disableBrowserCache(resp);
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Failed to stream version info");
    }

    return;
}

From source file:nl.strohalm.cyclos.utils.ResponseHelper.java

/**
 * Set the response header to use no cache
 *///  w  w  w.  ja va2s.c  o  m
public void setNoCache(final HttpServletResponse response) {
    response.setHeader("Pragma", "No-cache");
    response.setHeader("Cache-Control", "must-revalidate,no-cache,no-store,max-age=0");
    response.setDateHeader("Expires", 1);
}

From source file:com.nsano.uat.Imtservlet.java

/**
 *
 * @param request/*from   ww w .  j av a2  s. c om*/
 * @param response
 * @throws ServletException , IOException
 */
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    OutputStream out = response.getOutputStream();

    response.setContentType("text/plain;charset=UTF-8");
    response.setDateHeader("Expires", new Date().getTime()); // Expiration
    // date
    response.setDateHeader("Date", new Date().getTime()); // Date and time
    try {
        // that the
        // message was
        // sent
        out.write(moneytransfer(request).getBytes());
    } catch (JSONException ex) {
        Logger.getLogger(IMTCredit.class.getName()).log(Level.SEVERE, null, ex);
    } catch (NoSuchAlgorithmException ex) {
        Logger.getLogger(Imtservlet.class.getName()).log(Level.SEVERE, null, ex);
    }
    out.flush();
    out.close();
}

From source file:be.fedict.eid.idp.sp.PhotoServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    LOG.debug("doGet");
    response.setContentType("image/jpg");
    response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate, max-age=-1"); // http 1.1
    response.setHeader("Pragma", "no-cache, no-store"); // http 1.0
    response.setDateHeader("Expires", -1);
    ServletOutputStream out = response.getOutputStream();
    HttpSession session = request.getSession();

    byte[] photoData = (byte[]) session.getAttribute(PHOTO_SESSION_ATTRIBUTE);

    if (null != photoData) {
        BufferedImage photo = ImageIO.read(new ByteArrayInputStream(photoData));
        if (null == photo) {
            /*//from  w w w .j  av  a2  s  . c  o m
             * In this case we render a photo containing some error message.
             */
            photo = new BufferedImage(140, 200, BufferedImage.TYPE_INT_RGB);
            Graphics2D graphics = (Graphics2D) photo.getGraphics();
            RenderingHints renderingHints = new RenderingHints(RenderingHints.KEY_TEXT_ANTIALIASING,
                    RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
            graphics.setRenderingHints(renderingHints);
            graphics.setColor(Color.WHITE);
            graphics.fillRect(1, 1, 140 - 1 - 1, 200 - 1 - 1);
            graphics.setColor(Color.RED);
            graphics.setFont(new Font("Dialog", Font.BOLD, 20));
            graphics.drawString("Photo Error", 0, 200 / 2);
            graphics.dispose();
            ImageIO.write(photo, "jpg", out);
        } else {
            out.write(photoData);
        }
    }
    out.close();
}