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.fabric8.apiman.ui.ConfigurationServlet.java

/**
 * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest,
 *      javax.servlet.http.HttpServletResponse)
 * Grabs the authToken from the user's sessions and sticks it in the config.js using
 * a token replacement of the token '@token@'.
 *///from   w  ww.j a va2  s .c o  m
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String authToken = (String) request.getSession().getAttribute(LinkServlet.AUTH_TOKEN);
    log.info("AuthToken = " + authToken);
    InputStream is = null;
    String configFile = null;
    if (authToken == null) {
        log.debug("No authToken in the user's session with id " + request.getSession().getId());
        is = getClass().getResourceAsStream("/apimanui/apiman/f8-config-bkwrds-compatible.js");
        configFile = IOUtils.toString(is);
    } else {
        is = getClass().getResourceAsStream("/apimanui/apiman/f8-config.js");
        configFile = IOUtils.toString(is);
        configFile = configFile.replace("@token@", authToken);
    }
    try {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/javascript");
        response.setHeader("Cache-Control", "private, no-store, no-cache, must-revalidate");
        response.setDateHeader("Expires", 0);
        response.getOutputStream().write(configFile.getBytes("UTF-8")); //$NON-NLS-1$ //$NON-NLS-2$
    } catch (Exception e) {
        throw new ServletException(e);
    } finally {
        IOUtils.closeQuietly(is);
    }
}

From source file:org.polymap.service.geoserver.spring.PipelineMapProducer.java

public void writeTo(final OutputStream out) throws ServiceException, IOException {
    Timer timer = new Timer();

    // single layer? -> request ENCODED_IMAGE
    if (mapContext.getLayerCount() == 1) {
        MapLayer mapLayer = mapContext.getLayers()[0];
        ILayer layer = loader.findLayer(mapLayer);
        try {//  ww w  .  j  av  a 2  s .c  o m
            Pipeline pipeline = loader.getOrCreatePipeline(layer, LayerUseCase.ENCODED_IMAGE);

            ProcessorRequest request = prepareProcessorRequest();
            pipeline.process(request, new ResponseHandler() {
                public void handle(ProcessorResponse pipeResponse) throws Exception {

                    HttpServletResponse response = GeoServerWms.response.get();
                    if (pipeResponse == EncodedImageResponse.NOT_MODIFIED) {
                        log.info("Response: 304!");
                        response.setStatus(304);
                    } else {
                        long lastModified = ((EncodedImageResponse) pipeResponse).getLastModified();
                        // allow caches and browser clients to cache for 1h
                        //response.setHeader( "Cache-Control", "public,max-age=3600" );
                        if (lastModified > 0) {
                            response.setHeader("Cache-Control", "no-cache,must-revalidate");
                            response.setDateHeader("Last-Modified", lastModified);
                        } else {
                            response.setHeader("Cache-Control", "no-cache,must-revalidate");
                            response.setDateHeader("Expires", 0);
                        }

                        byte[] chunk = ((EncodedImageResponse) pipeResponse).getChunk();
                        int len = ((EncodedImageResponse) pipeResponse).getChunkSize();
                        out.write(chunk, 0, len);
                    }
                }
            });
            log.debug("    flushing response stream. (" + timer.elapsedTime() + "ms)");
            out.flush();
        } catch (IOException e) {
            throw e;
        } catch (Exception e) {
            throw new IOException(e);
        }
    }

    // multiple layers -> render into one image
    else {
        List<Job> jobs = new ArrayList();
        final Map<MapLayer, Image> images = new HashMap();

        // run jobs for all layers
        for (final MapLayer mapLayer : mapContext.getLayers()) {
            final ILayer layer = loader.findLayer(mapLayer);
            // job
            UIJob job = new UIJob(getClass().getSimpleName() + ": " + layer.getLabel()) {
                protected void runWithException(IProgressMonitor monitor) throws Exception {
                    try {
                        // XXX this excludes Cache304 (which support EncodedImageResponse only)
                        Pipeline pipeline = loader.getOrCreatePipeline(layer, LayerUseCase.IMAGE);

                        GetMapRequest targetRequest = prepareProcessorRequest();
                        pipeline.process(targetRequest, new ResponseHandler() {
                            public void handle(ProcessorResponse pipeResponse) throws Exception {
                                Image layerImage = ((ImageResponse) pipeResponse).getImage();
                                images.put(mapLayer, layerImage);
                            }
                        });
                    } catch (Exception e) {
                        // XXX put a special image in the map
                        log.warn("", e);
                        images.put(mapLayer, null);
                        throw e;
                    }
                }
            };
            job.schedule();
            jobs.add(job);
        }

        // join jobs
        for (Job job : jobs) {
            try {
                job.join();
            } catch (InterruptedException e) {
                // XXX put a special image in the map
                log.warn("", e);
            }
        }

        // put images together (MapContext order)
        Graphics2D g = null;
        try {
            // result image
            BufferedImage result = ImageUtils.createImage(mapContext.getMapWidth(), mapContext.getMapHeight(),
                    null, true);
            g = result.createGraphics();

            // rendering hints
            RenderingHints hints = new RenderingHints(RenderingHints.KEY_RENDERING,
                    RenderingHints.VALUE_RENDER_QUALITY);
            hints.add(new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON));
            hints.add(new RenderingHints(RenderingHints.KEY_TEXT_ANTIALIASING,
                    RenderingHints.VALUE_TEXT_ANTIALIAS_ON));
            g.setRenderingHints(hints);

            for (MapLayer mapLayer : mapContext.getLayers()) {
                Image layerImage = images.get(mapLayer);

                // load image data
                //                  new javax.swing.ImageIcon( image ).getImage();

                ILayer layer = loader.findLayer(mapLayer);
                int rule = AlphaComposite.SRC_OVER;
                float alpha = ((float) layer.getOpacity()) / 100;

                g.setComposite(AlphaComposite.getInstance(rule, alpha));
                g.drawImage(layerImage, 0, 0, null);
            }
            encodeImage(result, out);
        } finally {
            if (g != null) {
                g.dispose();
            }
        }
    }
}

From source file:org.seasar.s2click.S2ClickPage.java

/**
 * ????/*  w  w  w.j  a  v a 2  s. com*/
 *
 * @param contentType 
 * @param contents ??
 */
protected void renderResponse(String contentType, InputStream contents) {
    HttpServletResponse res = getContext().getResponse();

    // ????????
    Map<String, Object> headers = getHeaders();

    for (Iterator<Map.Entry<String, Object>> i = headers.entrySet().iterator(); i.hasNext();) {
        Map.Entry<String, Object> entry = i.next();
        String name = entry.getKey().toString();
        Object value = entry.getValue();

        if (value instanceof String) {
            String strValue = (String) value;
            if (!strValue.equalsIgnoreCase("Content-Encoding")) {
                res.setHeader(name, strValue);
            }

        } else if (value instanceof Date) {
            long time = ((Date) value).getTime();
            res.setDateHeader(name, time);

        } else {
            int intValue = ((Integer) value).intValue();
            res.setIntHeader(name, intValue);
        }
    }

    OutputStream out = null;

    try {
        res.setContentLength(contents.available());
        res.setContentType(contentType);
        out = res.getOutputStream();
        IOUtils.copy(contents, out);
        res.flushBuffer();

    } catch (Exception ex) {
        throw new RuntimeException(ex);

    } finally {
        IOUtils.closeQuietly(contents);
        IOUtils.closeQuietly(out);
        getContext().setRequestAttribute(SKIP_RENDERING, "true");
    }
}

From source file:org.apache.abdera.protocol.server.servlet.AbderaServlet.java

private void output(HttpServletRequest request, HttpServletResponse response, ResponseContext context)
        throws IOException {
    if (context != null) {
        response.setStatus(context.getStatus());
        long cl = context.getContentLength();
        String cc = context.getCacheControl();
        if (cl > -1)
            response.setHeader("Content-Length", Long.toString(cl));
        if (cc != null && cc.length() > 0)
            response.setHeader("Cache-Control", cc);
        try {/*  w  ww. jav  a 2s .com*/
            MimeType ct = context.getContentType();
            if (ct != null)
                response.setContentType(ct.toString());
        } catch (Exception e) {
        }
        String[] names = context.getHeaderNames();
        for (String name : names) {
            Object[] headers = context.getHeaders(name);
            for (Object value : headers) {
                if (value instanceof Date)
                    response.setDateHeader(name, ((Date) value).getTime());
                else
                    response.setHeader(name, value.toString());
            }
        }
        if (!request.getMethod().equals("HEAD") && context.hasEntity()) {
            context.writeTo(response.getOutputStream());
        }
    } else {
        error("Internal Server Error", null, response);
    }
}

From source file:org.jolokia.http.AgentServlet.java

private void setNoCacheHeaders(HttpServletResponse pResp) {
    pResp.setHeader("Cache-Control", "no-cache");
    pResp.setHeader("Pragma", "no-cache");
    // Check for a date header and set it accordingly to the recommendations of
    // RFC-2616 (http://tools.ietf.org/html/rfc2616#section-14.21)
    ///*from   www  . j  av  a  2 s  .  c o  m*/
    //   "To mark a response as "already expired," an origin server sends an
    //    Expires date that is equal to the Date header value. (See the rules
    //  for expiration calculations in section 13.2.4.)"
    //
    // See also #71

    long now = System.currentTimeMillis();
    pResp.setDateHeader("Date", now);
    // 1h  in the past since it seems, that some servlet set the date header on their
    // own so that it cannot be guaranteed that these headers are really equals.
    // It happened on Tomcat that Date: was finally set *before* Expires: in the final
    // answers some times which seems to be an implementation peculiarity from Tomcat
    pResp.setDateHeader("Expires", now - 3600000);
}

From source file:edu.stanford.muse.webapp.JSPHelper.java

/**
 * makes the page un$able. warning: must be called before any part of the
 * response body is committed/*from   w ww. j  av a2s  .c om*/
 */
public static void setPageUncacheable(HttpServletResponse response) {
    // see http://stackoverflow.com/questions/5139785/how-to-prevent-the-result-of-servlets-from-being-cached
    response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
    response.setHeader("Pragma", "no-cache");
    response.setHeader("Expires", "-1");

    // Set IE extended HTTP/1.1 no-cache headers (use addHeader).
    response.addHeader("Cache-Control", "post-check=0, pre-check=0");

    // Set standard HTTP/1.0 no-cache header.
    response.setDateHeader("Expires", 0); //prevent caching at the proxy server
}

From source file:org.eclipse.smarthome.ui.icon.internal.IconServlet.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    if (req.getDateHeader("If-Modified-Since") > startupTime) {
        resp.setStatus(304);/* w  w  w.ja v a  2s  .c o m*/
        return;
    }

    String category = getCategory(req);
    Format format = getFormat(req);
    String state = getState(req);
    String iconSetId = getIconSetId(req);

    IconProvider topProvider = null;
    int maxPrio = Integer.MIN_VALUE;
    for (IconProvider provider : iconProvider) {
        Integer prio = provider.hasIcon(category, iconSetId, format);
        if (prio != null && prio > maxPrio) {
            maxPrio = prio;
            topProvider = provider;
        }
    }
    if (topProvider != null) {
        if (format.equals(Format.SVG)) {
            resp.setContentType("image/svg+xml");
        } else {
            resp.setContentType("image/png");
        }
        resp.setDateHeader("Last-Modified", new Date().getTime());
        ServletOutputStream os = resp.getOutputStream();
        try (InputStream is = topProvider.getIcon(category, iconSetId, state, format)) {
            IOUtils.copy(is, os);
            resp.flushBuffer();
        } catch (IOException e) {
            logger.error("Failed sending the icon byte stream as a response: {}", e.getMessage());
            resp.sendError(500, e.getMessage());
        }
    } else {
        resp.sendError(404);
    }
}

From source file:org.rhq.enterprise.gui.client.RemoteClientServlet.java

private void getDownload(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {
    int limit = getDownloadLimit();
    if (limit <= 0) {
        sendErrorDownloadDisabled(resp);
        return;/*from   ww  w .  j  ava2  s  .  co  m*/
    } else if (limit < numActiveDownloads) {
        sendErrorTooManyDownloads(resp);
        return;
    }

    try {
        File zip = getRemoteClientZip();
        if (!zip.exists()) {
            disableBrowserCache(resp);
            resp.sendError(HttpServletResponse.SC_NOT_FOUND,
                    "Remote Client binary does not exist: " + zip.getName());
            return;
        }

        resp.setContentType("application/octet-stream");
        resp.setHeader("Content-Disposition", "attachment; filename=" + zip.getName());
        resp.setContentLength((int) zip.length());
        resp.setDateHeader("Last-Modified", zip.lastModified());

        FileInputStream zipStream = new FileInputStream(zip);
        try {
            StreamUtil.copy(zipStream, resp.getOutputStream(), false);
        } finally {
            zipStream.close();
        }
    } catch (Throwable t) {
        log.error("Failed to stream remote client zip.", t);
        disableBrowserCache(resp);
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Failed to stream remote client zip");
    }

    return;
}

From source file:org.openmrs.web.servlet.AbstractGraphServlet.java

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

    try {/* w w  w.  j a va 2  s.co  m*/
        // Set default values
        Integer width = Integer.valueOf(500);
        Integer height = Integer.valueOf(300);
        String mimeType = PNG_MIME_TYPE;

        // Retrieve custom values
        try {
            width = Integer.parseInt(request.getParameter("width"));
        } catch (Exception e) {
            log.error("Error during width parseInt", e);
        }

        try {
            height = Integer.parseInt(request.getParameter("height"));
        } catch (Exception e) {
            log.error("Error during height parseInt", e);
        }

        if (request.getParameter("mimeType") != null) {
            mimeType = request.getParameter("mimeType");
        }

        JFreeChart chart = createChart(request, response);

        // Modify response to disable caching
        response.setHeader("Pragma", "No-cache");
        response.setDateHeader("Expires", 0);
        response.setHeader("Cache-Control", "no-cache");

        // Write chart out to response as image 
        try {
            if (JPG_MIME_TYPE.equalsIgnoreCase(mimeType)) {
                response.setContentType(JPG_MIME_TYPE);
                ChartUtilities.writeChartAsJPEG(response.getOutputStream(), chart, width, height);
            } else if (PNG_MIME_TYPE.equalsIgnoreCase(mimeType)) {
                response.setContentType(PNG_MIME_TYPE);
                ChartUtilities.writeChartAsPNG(response.getOutputStream(), chart, width, height);
            } else {
                // Throw exception: unsupported mime type
            }
        } catch (IOException e) {
            log.error(e);
        }

    }
    // Add error handling above and remove this try/catch 
    catch (Exception e) {
        log.error(e);
    }
}