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.dspace.app.webui.servlet.HandleServlet.java

protected void doDSGet(Context context, HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, SQLException, AuthorizeException {
    String handle = null;// w  w  w .j a v  a 2 s.  c o  m
    String extraPathInfo = null;
    DSpaceObject dso = null;

    // Original path info, of the form "1721.x/1234"
    // or "1721.x/1234/extra/stuff"
    String path = request.getPathInfo();

    if (path != null) {
        // substring(1) is to remove initial '/'
        path = path.substring(1);

        try {
            // Extract the Handle
            int firstSlash = path.indexOf('/');
            int secondSlash = path.indexOf('/', firstSlash + 1);

            if (secondSlash != -1) {
                // We have extra path info
                handle = path.substring(0, secondSlash);
                extraPathInfo = path.substring(secondSlash);
            } else {
                // The path is just the Handle
                handle = path;
            }
        } catch (NumberFormatException nfe) {
            // Leave handle as null
        }
    }

    // Find out what the handle relates to
    if (handle != null) {
        dso = HandleManager.resolveToObject(context, handle);
    }

    if (dso == null) {
        log.info(LogManager.getHeader(context, "invalid_id", "path=" + path));
        JSPManager.showInvalidIDError(request, response, StringEscapeUtils.escapeHtml(path), -1);

        return;
    }

    if ("/statistics".equals(extraPathInfo)) {
        // Check configuration properties, auth, etc.
        // Inject handle attribute
        log.info(LogManager.getHeader(context, "display_statistics",
                "handle=" + handle + ", path=" + extraPathInfo));
        request.setAttribute("handle", handle);

        // Forward to DisplayStatisticsServlet without changing path.
        RequestDispatcher dispatch = getServletContext().getNamedDispatcher("displaystats");
        dispatch.forward(request, response);

        // If we don't return here, we keep processing and end up
        // throwing a NPE when checking community authorization
        // and firing a usage event for the DSO we're reporting for
        return;

    }

    // OK, we have a valid Handle. What is it?
    if (dso.getType() == Constants.ITEM) {
        // do we actually want to display the item, or forward to another page?
        if ((extraPathInfo == null) || (extraPathInfo.equals("/"))) {
            Item item = (Item) dso;

            // Only use last-modified if this is an anonymous access
            // - caching content that may be generated under authorisation
            //   is a security problem

            if (context.getCurrentUser() == null) {
                response.setDateHeader("Last-Modified", item.getLastModified().getTime());

                // Check for if-modified-since header

                long modSince = request.getDateHeader("If-Modified-Since");

                if (modSince != -1 && item.getLastModified().getTime() < modSince) {
                    // Item has not been modified since requested date,
                    // hence bitstream has not been, either; return 304
                    response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
                } else {
                    // Display the item page
                    displayItem(context, request, response, item, handle);
                }
            } else {
                // Display the item page
                displayItem(context, request, response, item, handle);
            }
        } else {
            // Forward to another servlet
            request.getRequestDispatcher(extraPathInfo).forward(request, response);
        }

    } else if (dso.getType() == Constants.COLLECTION) {
        Collection c = (Collection) dso;

        // Store collection location in request
        request.setAttribute("dspace.collection", c);

        /*
         * Find the "parent" community the collection, mainly for
         * "breadcrumbs" FIXME: At the moment, just grab the first community
         * the collection is in. This should probably be more context
         * sensitive when we have multiple inclusion.
         */
        Community[] parents = c.getCommunities();
        request.setAttribute("dspace.community", parents[0]);

        /*
         * Find all the "parent" communities for the collection for
         * "breadcrumbs"
         */
        request.setAttribute("dspace.communities", getParents(parents[0], true));

        // home page, or forward to another page?
        if ((extraPathInfo == null) || (extraPathInfo.equals("/"))) {
            collectionHome(context, request, response, parents[0], c);
        } else {
            // Forward to another servlet
            request.getRequestDispatcher(extraPathInfo).forward(request, response);
        }
    } else if (dso.getType() == Constants.COMMUNITY) {
        Community c = (Community) dso;

        // Store collection location in request
        request.setAttribute("dspace.community", c);

        /*
         * Find all the "parent" communities for the community
         */
        request.setAttribute("dspace.communities", getParents(c, false));

        // home page, or forward to another page?
        if ((extraPathInfo == null) || (extraPathInfo.equals("/"))) {
            communityHome(context, request, response, c);
        } else {
            // Forward to another servlet
            request.getRequestDispatcher(extraPathInfo).forward(request, response);
        }
    } else {
        // Shouldn't happen. Log and treat as invalid ID
        log.info(LogManager.getHeader(context, "Handle not an item, collection or community",
                "handle=" + handle));
        JSPManager.showInvalidIDError(request, response, StringEscapeUtils.escapeHtml(path), -1);

        return;
    }
}

From source file:com.smartgwt.extensions.fileuploader.server.ProjectServlet.java

private void processFiles(HttpServletRequest request, HttpServletResponse response) {
    HashMap<String, String> args = new HashMap<String, String>();
    boolean isGWT = true;
    try {//from   w w  w  . j  av  a 2 s  .  c  o m
        if (log.isDebugEnabled())
            log.debug(request.getParameterMap());
        ServletFileUpload upload = new ServletFileUpload();
        FileItemIterator iter = upload.getItemIterator(request);
        // pick up parameters first and note actual FileItem
        while (iter.hasNext()) {
            FileItemStream item = iter.next();
            String name = item.getFieldName();
            if (item.isFormField()) {
                args.put(name, Streams.asString(item.openStream()));
            } else {
                args.put("contentType", item.getContentType());
                String fileName = item.getName();
                int slash = fileName.lastIndexOf("/");
                if (slash < 0)
                    slash = fileName.lastIndexOf("\\");
                if (slash > 0)
                    fileName = fileName.substring(slash + 1);
                args.put("fileName", fileName);
                // upload requests can come from smartGWT (args) or
                // FCKEditor (request)
                String contextName = args.get("context");
                String model = args.get("model");
                String path = args.get("path");
                if (contextName == null) {
                    isGWT = false;
                    contextName = request.getParameter("context");
                    model = request.getParameter("model");
                    path = request.getParameter("path");
                    if (log.isDebugEnabled())
                        log.debug("query=" + request.getQueryString());
                } else if (log.isDebugEnabled())
                    log.debug(args);
                // the following code stores the file based on your parameters
                /*               ProjectContext context = ContextService.get().getContext(
                                     contextName);
                               ProjectState state = (ProjectState) request.getSession()
                                     .getAttribute(contextName);
                               InputStream in = null;
                               try {
                                  in = item.openStream();
                                  state.getFileManager().storeFile(
                context.getModel(model), path + fileName, in);
                               } catch (Exception e) {
                                  e.printStackTrace();
                                  log.error("Fail to upload " + fileName + " to " + path);
                               } finally {
                                  if (in != null)
                                     try {
                in.close();
                                     } catch (Exception e) {
                                     }
                               }
                */
            }
        }
        // TODO: need to handle conversion options and error reporting
        response.setContentType("text/html");
        response.setHeader("Pragma", "No-cache");
        response.setDateHeader("Expires", 0);
        response.setHeader("Cache-Control", "no-cache");
        PrintWriter out = response.getWriter();
        out.println("<html>");
        out.println("<body>");
        if (isGWT) {
            out.println("<script type=\"text/javascript\">");
            out.println("if (parent.uploadComplete) parent.uploadComplete('" + args.get("fileName") + "');");
            out.println("</script>");
        } else
            out.println(getEditorResponse());
        out.println("</body>");
        out.println("</html>");
        out.flush();
    } catch (Exception e) {
        System.out.println(e.getMessage());
    }
}

From source file:de.innovationgate.wgpublisher.WGPDispatcher.java

private void dispatchFileDefaultImpl(WGPRequestPath path, HttpServletRequest request,
        HttpServletResponse response, WGDatabase database, WGDocument fileContainer)
        throws IOException, WGAPIException, HttpErrorException, WGException {
    response.setDateHeader("Date", System.currentTimeMillis());

    // Set expiration time
    int fileExpirationMinutes = ((Integer) _core.readPublisherOptionOrDefault(database,
            WGACore.DBATTRIB_FILEEXPIRATION_MINUTES)).intValue();
    if (fileContainer instanceof WGContent
            && ((WGContent) fileContainer).getStatus().equals(WGContent.STATUS_DRAFT)) {
        fileExpirationMinutes = 0;//from ww  w  . j  a  v  a 2 s  .c o m
    }

    if (fileExpirationMinutes > 0) {
        int fileExpirationSeconds = fileExpirationMinutes * 60;

        // check if file is anonymous accessible
        boolean isAnonymousAccessible = database.isAnonymousAccessible();
        if (isAnonymousAccessible) {
            // perform further document level checks
            if (fileContainer != null && fileContainer instanceof WGContent) {
                // check status
                if (!((WGContent) fileContainer).getStatus().equals(WGContent.STATUS_RELEASE)) {
                    isAnonymousAccessible = false;
                } else {
                    // check readers
                    isAnonymousAccessible = ((WGContent) fileContainer).isPublic();
                }
            }
        }

        if (isAnonymousAccessible) {
            response.setHeader("Cache-Control", "public, max-age=" + fileExpirationSeconds);
        } else
            response.setHeader("Cache-Control", "private, max-age=" + fileExpirationSeconds);
    }

    // Create publishing file object, which will provide the data
    PublishingFile publishingFile = new DocumentPublishingFile(this, fileContainer, path.getFileName());
    if (!publishingFile.isPublishable()) {
        throw new HttpErrorException(403, "Files from this container may not be published",
                path.getDatabaseKey());
    }

    String designEncoding = (String) database.getAttribute(WGACore.DBATTRIB_DESIGN_ENCODING);
    FileCache fileCache = (FileCache) database.getAttribute(WGACore.DBATTRIB_FILECACHE);

    dispatchPublishingFile(publishingFile, request, response, designEncoding, fileCache, path);
}

From source file:org.openhab.ui.cometvisu.servlet.CometVisuServlet.java

/**
 * Process the actual request./*from   w  w w. ja  v a  2  s  . c o  m*/
 *
 * @param request
 *            The request to be processed.
 * @param response
 *            The response to be created.
 * @param content
 *            Whether the request body should be written (GET) or not
 *            (HEAD).
 * @throws IOException
 *             If something fails at I/O level.
 *
 * @author BalusC
 * @link
 *       http://balusc.blogspot.com/2009/02/fileservlet-supporting-resume-and
 *       .html
 */
private void processStaticRequest(File file, HttpServletRequest request, HttpServletResponse response,
        boolean content) throws IOException {
    // Validate the requested file
    // ------------------------------------------------------------

    if (file == null) {
        // Get requested file by path info.
        String requestedFile = request.getPathInfo();

        // Check if file is actually supplied to the request URL.
        if (requestedFile == null) {
            // Do your thing if the file is not supplied to the request URL.
            // Throw an exception, or send 404, or show default/warning
            // page, or
            // just ignore it.
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }

        // URL-decode the file name (might contain spaces and on) and
        // prepare
        // file object.
        file = new File(rootFolder, URLDecoder.decode(requestedFile, "UTF-8"));
    }
    // Check if file actually exists in filesystem.
    if (!file.exists()) {
        // Do your thing if the file appears to be non-existing.
        // Throw an exception, or send 404, or show default/warning page, or
        // just ignore it.
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }

    // Prepare some variables. The ETag is an unique identifier of the file.
    String fileName = file.getName();
    long length = file.length();
    long lastModified = file.lastModified();
    String eTag = fileName + "_" + length + "_" + lastModified;
    long expires = System.currentTimeMillis() + DEFAULT_EXPIRE_TIME;

    // Validate request headers for caching
    // ---------------------------------------------------

    // If-None-Match header should contain "*" or ETag. If so, then return
    // 304.
    String ifNoneMatch = request.getHeader("If-None-Match");
    if (ifNoneMatch != null && matches(ifNoneMatch, eTag)) {
        response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
        response.setHeader("ETag", eTag); // Required in 304.
        response.setDateHeader("Expires", expires); // Postpone cache with 1
                                                    // week.
        return;
    }

    // If-Modified-Since header should be greater than LastModified. If so,
    // then return 304.
    // This header is ignored if any If-None-Match header is specified.
    long ifModifiedSince = request.getDateHeader("If-Modified-Since");
    if (ifNoneMatch == null && ifModifiedSince != -1 && ifModifiedSince + 1000 > lastModified) {
        response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
        response.setHeader("ETag", eTag); // Required in 304.
        response.setDateHeader("Expires", expires); // Postpone cache with 1
                                                    // week.
        return;
    }

    // Validate request headers for resume
    // ----------------------------------------------------

    // If-Match header should contain "*" or ETag. If not, then return 412.
    String ifMatch = request.getHeader("If-Match");
    if (ifMatch != null && !matches(ifMatch, eTag)) {
        response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
        return;
    }

    // If-Unmodified-Since header should be greater than LastModified. If
    // not, then return 412.
    long ifUnmodifiedSince = request.getDateHeader("If-Unmodified-Since");
    if (ifUnmodifiedSince != -1 && ifUnmodifiedSince + 1000 <= lastModified) {
        response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
        return;
    }

    // Validate and process range
    // -------------------------------------------------------------

    // Prepare some variables. The full Range represents the complete file.
    Range full = new Range(0, length - 1, length);
    List<Range> ranges = new ArrayList<Range>();

    // Validate and process Range and If-Range headers.
    String range = request.getHeader("Range");
    if (range != null) {

        // Range header should match format "bytes=n-n,n-n,n-n...". If not,
        // then return 416.
        if (!range.matches("^bytes=\\d*-\\d*(,\\d*-\\d*)*$")) {
            response.setHeader("Content-Range", "bytes */" + length); // Required
                                                                      // in
                                                                      // 416.
            response.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE);
            return;
        }

        // If-Range header should either match ETag or be greater then
        // LastModified. If not,
        // then return full file.
        String ifRange = request.getHeader("If-Range");
        if (ifRange != null && !ifRange.equals(eTag)) {
            try {
                long ifRangeTime = request.getDateHeader("If-Range"); // Throws
                                                                      // IAE
                                                                      // if
                                                                      // invalid.
                if (ifRangeTime != -1 && ifRangeTime + 1000 < lastModified) {
                    ranges.add(full);
                }
            } catch (IllegalArgumentException ignore) {
                ranges.add(full);
            }
        }

        // If any valid If-Range header, then process each part of byte
        // range.
        if (ranges.isEmpty()) {
            for (String part : range.substring(6).split(",")) {
                // Assuming a file with length of 100, the following
                // examples returns bytes at:
                // 50-80 (50 to 80), 40- (40 to length=100), -20
                // (length-20=80 to length=100).
                long start = sublong(part, 0, part.indexOf("-"));
                long end = sublong(part, part.indexOf("-") + 1, part.length());

                if (start == -1) {
                    start = length - end;
                    end = length - 1;
                } else if (end == -1 || end > length - 1) {
                    end = length - 1;
                }

                // Check if Range is syntactically valid. If not, then
                // return 416.
                if (start > end) {
                    response.setHeader("Content-Range", "bytes */" + length); // Required
                                                                              // in
                                                                              // 416.
                    response.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE);
                    return;
                }

                // Add range.
                ranges.add(new Range(start, end, length));
            }
        }
    }

    // Prepare and initialize response
    // --------------------------------------------------------

    // Get content type by file name and set default GZIP support and
    // content disposition.
    String contentType = getServletContext().getMimeType(fileName);
    boolean acceptsGzip = false;
    String disposition = "inline";

    // If content type is unknown, then set the default value.
    // For all content types, see:
    // http://www.w3schools.com/media/media_mimeref.asp
    // To add new content types, add new mime-mapping entry in web.xml.
    if (contentType == null) {
        contentType = "application/octet-stream";
    }

    // If content type is text, then determine whether GZIP content encoding
    // is supported by
    // the browser and expand content type with the one and right character
    // encoding.
    if (contentType.startsWith("text")) {
        String acceptEncoding = request.getHeader("Accept-Encoding");
        acceptsGzip = acceptEncoding != null && accepts(acceptEncoding, "gzip");
        contentType += ";charset=UTF-8";
    }

    // Else, expect for images, determine content disposition. If content
    // type is supported by
    // the browser, then set to inline, else attachment which will pop a
    // 'save as' dialogue.
    else if (!contentType.startsWith("image")) {
        String accept = request.getHeader("Accept");
        disposition = accept != null && accepts(accept, contentType) ? "inline" : "attachment";
    }

    // Initialize response.
    response.reset();
    response.setBufferSize(DEFAULT_BUFFER_SIZE);
    response.setHeader("Content-Disposition", disposition + ";filename=\"" + fileName + "\"");
    response.setHeader("Accept-Ranges", "bytes");
    response.setHeader("ETag", eTag);
    response.setDateHeader("Last-Modified", lastModified);
    response.setDateHeader("Expires", expires);

    // Send requested file (part(s)) to client
    // ------------------------------------------------

    // Prepare streams.
    RandomAccessFile input = null;
    OutputStream output = null;

    try {
        // Open streams.
        input = new RandomAccessFile(file, "r");
        output = response.getOutputStream();

        if (ranges.isEmpty() || ranges.get(0) == full) {

            // Return full file.
            Range r = full;
            response.setContentType(contentType);
            response.setHeader("Content-Range", "bytes " + r.start + "-" + r.end + "/" + r.total);

            if (content) {
                if (acceptsGzip) {
                    // The browser accepts GZIP, so GZIP the content.
                    response.setHeader("Content-Encoding", "gzip");
                    output = new GZIPOutputStream(output, DEFAULT_BUFFER_SIZE);
                } else {
                    // Content length is not directly predictable in case of
                    // GZIP.
                    // So only add it if there is no means of GZIP, else
                    // browser will hang.
                    response.setHeader("Content-Length", String.valueOf(r.length));
                }

                // Copy full range.
                copy(input, output, r.start, r.length);
            }

        } else if (ranges.size() == 1) {

            // Return single part of file.
            Range r = ranges.get(0);
            response.setContentType(contentType);
            response.setHeader("Content-Range", "bytes " + r.start + "-" + r.end + "/" + r.total);
            response.setHeader("Content-Length", String.valueOf(r.length));
            response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); // 206.

            if (content) {
                // Copy single part range.
                copy(input, output, r.start, r.length);
            }

        } else {

            // Return multiple parts of file.
            response.setContentType("multipart/byteranges; boundary=" + MULTIPART_BOUNDARY);
            response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); // 206.

            if (content) {
                // Cast back to ServletOutputStream to get the easy println
                // methods.
                ServletOutputStream sos = (ServletOutputStream) output;

                // Copy multi part range.
                for (Range r : ranges) {
                    // Add multipart boundary and header fields for every
                    // range.
                    sos.println();
                    sos.println("--" + MULTIPART_BOUNDARY);
                    sos.println("Content-Type: " + contentType);
                    sos.println("Content-Range: bytes " + r.start + "-" + r.end + "/" + r.total);

                    // Copy single part range of multi part range.
                    copy(input, output, r.start, r.length);
                }

                // End with multipart boundary.
                sos.println();
                sos.println("--" + MULTIPART_BOUNDARY + "--");
            }
        }
    } finally {
        // Gently close streams.
        close(output);
        close(input);
    }
}

From source file:org.polymap.core.mapeditor.services.SimpleWmsServer.java

protected void doGet(final HttpServletRequest request, final HttpServletResponse response)
        throws ServletException, IOException {
    log.debug("Request: " + request.getQueryString());

    final Map<String, String> kvp = parseKvpSet(request.getQueryString());

    try {//from ww  w . ja v a 2 s  . co  m
        sessionContext.execute(new Callable() {
            public Object call() throws Exception {
                final String layerRenderKey = kvp.get("LAYERS");
                assert !layerRenderKey.contains(INNER_DELIMETER);

                // width/height
                int width = Integer.parseInt(kvp.get("WIDTH"));
                int height = Integer.parseInt(kvp.get("HEIGHT"));

                // BBOX
                ReferencedEnvelope bbox = parseBBox(kvp.get("BBOX"));
                String srsCode = kvp.get("SRS");
                // XXX hack support for EPSG:3857 : send different srs and crs
                //                    CoordinateReferenceSystem crs = srsCode.equals( "EPSG:3857" )
                //                            ? CRS.decode( "EPSG:900913" )
                //                            : CRS.decode( srsCode );
                CoordinateReferenceSystem crs = CRS.decode(srsCode);
                bbox = new ReferencedEnvelope(bbox, crs);

                // FORMAT
                String format = kvp.get("FORMAT");
                format = format != null ? format : "image/png";

                log.debug("    --layers= " + layerRenderKey);
                log.debug("    --imageSize= " + width + "x" + height);
                log.debug("    --bbox= " + bbox);
                crs = bbox.getCoordinateReferenceSystem();
                log.debug("    --CRS= " + bbox.getCoordinateReferenceSystem().getName());

                // find/create pipeline
                final Pipeline pipeline = getOrCreatePipeline(layerRenderKey);
                //ILayer layer = Iterables.getOnlyElement( pipeline.getLayers() );

                long modifiedSince = request.getDateHeader("If-Modified-Since");
                final ProcessorRequest pr = new GetMapRequest(null, // layers 
                        srsCode, bbox, format, width, height, modifiedSince);

                // process
                final LazyInit<ServletOutputStream> out = new PlainLazyInit(
                        new Supplier<ServletOutputStream>() {
                            public ServletOutputStream get() {
                                try {
                                    return response.getOutputStream();
                                } catch (IOException e) {
                                    throw new RuntimeException(e);
                                }
                            }
                        });
                try {
                    pipeline.process(pr, new ResponseHandler() {
                        public void handle(ProcessorResponse pipeResponse) throws Exception {
                            if (pipeResponse == EncodedImageResponse.NOT_MODIFIED) {
                                response.setStatus(304);
                            } else {
                                long lastModified = ((EncodedImageResponse) pipeResponse).getLastModified();
                                // lastModified is only set if response comes from cache ->
                                // allow the browser to use a cached tile for max-age without a request
                                if (lastModified > 0) {
                                    response.setDateHeader("Last-Modified", lastModified);
                                    response.setHeader("Cache-Control", "max-age=180,must-revalidate");
                                }
                                // disable browser cache if there is no internal Cache for this layer 
                                else {
                                    response.setHeader("Cache-Control", "no-cache,no-store,must-revalidate");
                                    response.setDateHeader("Expires", 0);
                                    response.setHeader("Pragma", "no-cache");
                                }

                                byte[] chunk = ((EncodedImageResponse) pipeResponse).getChunk();
                                int len = ((EncodedImageResponse) pipeResponse).getChunkSize();
                                out.get().write(chunk, 0, len);
                            }
                        }
                    });
                } catch (Throwable e) {
                    log.warn("Pipeline exception: " + e, e);
                    response.setStatus(502);
                }
                if (out.isInitialized()) {
                    out.get().flush();
                }
                response.flushBuffer();
                return null;
            }
        });
    } catch (IOException e) {
        // assuming that this is an EOF exception
        log.info("Exception: " + e);
    } catch (Exception e) {
        log.warn(e.toString(), e);
    } finally {
        // XXX do I have to close out?
        //out.close();
    }
}

From source file:org.opencms.loader.CmsJspLoader.java

/**
 * Dispatches the current request to the OpenCms internal JSP.<p>
 * //from  w  w w.j  ava  2s . com
 * @param controller the current controller
 * 
 * @return the content of the processed JSP
 * 
 * @throws ServletException if inclusion does not work
 * @throws IOException if inclusion does not work
 */
protected byte[] dispatchJsp(CmsFlexController controller) throws ServletException, IOException {

    // get request / response wrappers
    CmsFlexRequest f_req = controller.getCurrentRequest();
    CmsFlexResponse f_res = controller.getCurrentResponse();

    try {
        f_req.getRequestDispatcher(controller.getCmsObject().getSitePath(controller.getCmsResource()))
                .include(f_req, f_res);
    } catch (SocketException e) {
        // uncritical, might happen if client (browser) does not wait until end of page delivery
        LOG.debug(Messages.get().getBundle().key(Messages.LOG_IGNORING_EXC_1, e.getClass().getName()), e);
    }

    byte[] result = null;
    HttpServletResponse res = controller.getTopResponse();

    if (!controller.isStreaming() && !f_res.isSuspended()) {
        try {
            // if a JSP error page was triggered the response will be already committed here
            if (!res.isCommitted() || m_errorPagesAreNotCommitted) {

                // check if the current request was done by a workplace user
                boolean isWorkplaceUser = CmsWorkplaceManager.isWorkplaceUser(f_req);

                // check if the content was modified since the last request
                if (controller.isTop() && !isWorkplaceUser
                        && CmsFlexController.isNotModifiedSince(f_req, controller.getDateLastModified())) {
                    if (f_req.getParameterMap().size() == 0) {
                        // only use "expires" header on pages that have no parameters,
                        // otherwise some browsers (e.g. IE 6) will not even try to request 
                        // updated versions of the page
                        CmsFlexController.setDateExpiresHeader(res, controller.getDateExpires(),
                                m_clientCacheMaxAge);
                    }
                    res.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
                    return null;
                }

                // get the result byte array
                result = f_res.getWriterBytes();
                HttpServletRequest req = controller.getTopRequest();
                if (req.getHeader(CmsRequestUtil.HEADER_OPENCMS_EXPORT) != null) {
                    // this is a non "on-demand" static export request, don't write to the response stream
                    req.setAttribute(CmsRequestUtil.HEADER_OPENCMS_EXPORT,
                            new Long(controller.getDateLastModified()));
                } else if (controller.isTop()) {
                    // process headers and write output if this is the "top" request/response                                  
                    res.setContentLength(result.length);
                    // check for preset error code
                    Integer errorCode = (Integer) req.getAttribute(CmsRequestUtil.ATTRIBUTE_ERRORCODE);
                    if (errorCode == null) {
                        // set last modified / no cache headers only if this is not an error page
                        if (isWorkplaceUser) {
                            res.setDateHeader(CmsRequestUtil.HEADER_LAST_MODIFIED, System.currentTimeMillis());
                            CmsRequestUtil.setNoCacheHeaders(res);
                        } else {
                            // set date last modified header                        
                            CmsFlexController.setDateLastModifiedHeader(res, controller.getDateLastModified());
                            if ((f_req.getParameterMap().size() == 0)
                                    && (controller.getDateLastModified() > -1)) {
                                // only use "expires" header on pages that have no parameters
                                // and that are cachable (i.e. 'date last modified' is set)
                                // otherwise some browsers (e.g. IE 6) will not even try to request 
                                // updated versions of the page
                                CmsFlexController.setDateExpiresHeader(res, controller.getDateExpires(),
                                        m_clientCacheMaxAge);
                            }
                        }
                        // set response status to "200 - OK" (required for static export "on-demand")
                        res.setStatus(HttpServletResponse.SC_OK);
                    } else {
                        // set previously saved error code
                        res.setStatus(errorCode.intValue());
                    }
                    // process the headers
                    CmsFlexResponse.processHeaders(f_res.getHeaders(), res);
                    res.getOutputStream().write(result);
                    res.getOutputStream().flush();
                }
            }
        } catch (IllegalStateException e) {
            // uncritical, might happen if JSP error page was used
            LOG.debug(Messages.get().getBundle().key(Messages.LOG_IGNORING_EXC_1, e.getClass().getName()), e);
        } catch (SocketException e) {
            // uncritical, might happen if client (browser) does not wait until end of page delivery
            LOG.debug(Messages.get().getBundle().key(Messages.LOG_IGNORING_EXC_1, e.getClass().getName()), e);
        }
    }

    return result;
}

From source file:gsn.http.OneShotQueryWithAddressingHandler.java

public void handle(HttpServletRequest request, HttpServletResponse response) throws IOException {

    SimpleDateFormat sdf = new SimpleDateFormat(Main.getInstance().getContainerConfig().getTimeFormat());

    String vsName = request.getParameter("name");
    String vsCondition = request.getParameter("condition");
    if (vsCondition == null || vsCondition.trim().length() == 0)
        vsCondition = " ";
    else/* w w w.j av  a  2 s  . c  om*/
        vsCondition = " where " + vsCondition;
    String vsFields = request.getParameter("fields");
    if (vsFields == null || vsFields.trim().length() == 0 || vsFields.trim().equals("*"))
        vsFields = "*";
    else
        vsFields += " , pk, timed";
    String windowSize = request.getParameter("window");
    if (windowSize == null || windowSize.trim().length() == 0)
        windowSize = "1";
    StringBuilder query = new StringBuilder("select " + vsFields + " from " + vsName + vsCondition
            + " order by timed DESC limit " + windowSize + " offset 0");
    DataEnumerator result;
    try {
        result = Main.getStorage(vsName).executeQuery(query, true);
    } catch (SQLException e) {
        logger.error("ERROR IN EXECUTING, query: " + query + " from " + request.getRemoteAddr() + "- "
                + request.getRemoteHost() + ": " + e.getMessage());
        return;
    }

    Iterator<VSensorConfig> vsIterator = Mappings.getAllVSensorConfigs();
    HashMap<String, String> fieldToUnitMap = new HashMap<String, String>();
    while (vsIterator.hasNext()) {
        VSensorConfig sensorConfig = vsIterator.next();
        if (vsName.equalsIgnoreCase(sensorConfig.getName())) {
            DataField[] dataFieldArray = sensorConfig.getOutputStructure();
            for (DataField df : dataFieldArray) {
                String unit = df.getUnit();
                if (unit == null || unit.trim().length() == 0)
                    unit = "";

                fieldToUnitMap.put(df.getName().toLowerCase(), unit);
            }
            break;
        }
    }

    StringBuilder sb = new StringBuilder("<result>\n");
    while (result.hasMoreElements()) {
        StreamElement se = result.nextElement();
        sb.append("<stream-element>\n");
        sb.append("<field name=\"time\" unit=\"\">").append(sdf.format(new Date(se.getTimeStamp())))
                .append("</field>\n");
        for (int i = 0; i < se.getFieldNames().length; i++) {
            sb.append("<field name=\"").append(se.getFieldNames()[i]).append("\"");
            sb.append(" unit=\"").append(fieldToUnitMap.get(se.getFieldNames()[i].toLowerCase()))
                    .append("\" >");
            if (se.getFieldTypes()[i] == DataTypes.BINARY)
                sb.append(se.getData()[i].toString()).append("</field>\n");
            else
                sb.append(StringEscapeUtils.escapeXml(se.getData()[i].toString())).append("</field>\n");
        }
        VSensorConfig sensorConfig = Mappings.getVSensorConfig(vsName);
        logger.info(new StringBuilder().append("Structure request for *").append(vsName).append("* received.")
                .toString());
        //StringBuilder statement = new StringBuilder( "<virtual-sensor name=\"" ).append( vsName ).append( "\" last-modified=\"" ).append( new File( sensorConfig.getFileName( ) ).lastModified( ) ).append( "\">\n" );
        for (KeyValue df : sensorConfig.getAddressing())
            sb.append("<field name=\"").append(StringEscapeUtils.escapeXml(df.getKey().toString()))
                    .append("\">").append(StringEscapeUtils.escapeXml(df.getValue().toString()))
                    .append("</field>\n");
        sb.append("</stream-element>\n");
    }
    result.close();
    sb.append("</result>");
    response.setHeader("Cache-Control", "no-store");
    response.setDateHeader("Expires", 0);
    response.setHeader("Pragma", "no-cache");
    response.getWriter().write(sb.toString());
}

From source file:de.innovationgate.wgpublisher.WGPDispatcher.java

private void dispatchTmlFormRequest(WGPRequestPath path, HttpServletRequest request,
        HttpServletResponse response) throws HttpErrorException, IOException, WGException {

    PCFile file = null;/*from ww  w  .j  a v a  2s .c o m*/
    ProcessContextRegistration contexts = (ProcessContextRegistration) request.getSession()
            .getAttribute(TMLContext.SESSIONATTRIB_PROCESSCONTEXTS);
    if (contexts != null) {
        TMLFormProcessContext pc = (TMLFormProcessContext) contexts.getProcessContext(path.getContainerKey());
        if (pc != null) {
            file = pc.getFiles().get(path.getFileName().toLowerCase());
        }
    }

    if (file == null) {
        throw new HttpErrorException(404, "No WebTML form file of name " + path.getFileName(), null);
    }

    file.openSession(request, _core);
    response.setDateHeader("Date", System.currentTimeMillis());

    // Create publishing file object, which will provide the data
    PublishingFile publishingFile = new TMLFormPublishingFile(this, file);
    if (!publishingFile.isPublishable()) {
        throw new HttpErrorException(403, "This WebTML form file may not be published", null);
    }

    dispatchPublishingFile(publishingFile, request, response, _core.getCharacterEncoding(), null, path);

}

From source file:org.openlaszlo.data.DataSource.java

/**
 * Determine the datasource from the incoming request,
 * get the data, convert it to SWF, and write it out
 * to the given response./*from  w ww  . j  a va2s  .  c  o m*/
 *
 * @param app absolute path name to app requesting data
 * @param req request
 * @param res response
 * @param converter converter to use
 * @throws DataSourceException if the data source encounters an error
 * @throws ConversionException if the conversion to SWF returns an error
 * @throws IOException if there is an IO error
 */
final public void getAsSWF(String app, HttpServletRequest req, HttpServletResponse res, Converter converter)
        throws DataSourceException, ConversionException, IOException {

    Data data = null;
    InputStream input = null;
    OutputStream output = null;
    long size = -1;
    long since = -1;

    // Check to see if client side caching is on
    boolean doClientCache = isClientCacheable(req);
    if (doClientCache) {
        String hdr = req.getHeader(LZHttpUtils.IF_MODIFIED_SINCE);
        if (hdr != null) {
            mLogger.debug(
                    /* (non-Javadoc)
                     * @i18n.test
                     * @org-mes="req last modified time: " + p[0]
                     */
                    org.openlaszlo.i18n.LaszloMessages.getMessage(DataSource.class.getName(), "051018-96",
                            new Object[] { hdr }));
            since = LZHttpUtils.getDate(hdr);
        }
    }

    mLogger.info(
            /* (non-Javadoc)
             * @i18n.test
             * @org-mes="requesting URL: '" + p[0] + "'"
             */
            org.openlaszlo.i18n.LaszloMessages.getMessage(DataSource.class.getName(), "051018-108",
                    new Object[] { DataSource.getURL(req) }));
    try {
        data = getData(app, req, res, since);

        if (data.notModified()) {
            mLogger.info(
                    /* (non-Javadoc)
                     * @i18n.test
                     * @org-mes="NOT_MODIFIED"
                     */
                    org.openlaszlo.i18n.LaszloMessages.getMessage(DataSource.class.getName(), "051018-120"));
            res.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
            return;
        }

        mLogger.debug("got data");

        if (!data.getMimeType().equals(MimeType.SWF)) {

            input = converter.convertToSWF(data, req, res);
            size = input.available();
            mLogger.debug(
                    /* (non-Javadoc)
                     * @i18n.test
                     * @org-mes="converted to " + p[0] + " bytes of SWF"
                     */
                    org.openlaszlo.i18n.LaszloMessages.getMessage(DataSource.class.getName(), "051018-138",
                            new Object[] { size }));
            // FIXME: [2003-09-22 bloch] input.available not realiable

            String enc = converter.chooseEncoding(req);
            if (enc != null && !enc.equals("")) {
                input = converter.encode(req, input, enc);
                res.setHeader(LZHttpUtils.CONTENT_ENCODING, enc);
                size = input.available();
            }

        } else {
            mLogger.debug(
                    /* (non-Javadoc)
                     * @i18n.test
                     * @org-mes="remote content was SWF"
                     */
                    org.openlaszlo.i18n.LaszloMessages.getMessage(DataSource.class.getName(), "051018-156"));
            input = data.getInputStream();
            size = data.size();
        }

        if (size != -1) {
            mLogger.debug(
                    /* (non-Javadoc)
                     * @i18n.test
                     * @org-mes="setting content length: " + p[0]
                     */
                    org.openlaszlo.i18n.LaszloMessages.getMessage(DataSource.class.getName(), "051018-169",
                            new Object[] { size }));
            //res.setContentLength((int)size);
        }

        if (doClientCache) {
            long t = data.lastModified();
            if (t != -1) {
                res.setDateHeader(LZHttpUtils.LAST_MODIFIED, t);
            }
        } else {
            LZHttpUtils.noStore(res);
        }

        try {
            output = res.getOutputStream();
            long n = FileUtils.sendToStream(input, output);
            mLogger.info(
                    /* (non-Javadoc)
                     * @i18n.test
                     * @org-mes=p[0] + " bytes sent"
                     */
                    org.openlaszlo.i18n.LaszloMessages.getMessage(DataSource.class.getName(), "051018-192",
                            new Object[] { n }));
        } catch (FileUtils.StreamWritingException e) {
            mLogger.warn(
                    /* (non-Javadoc)
                     * @i18n.test
                     * @org-mes="StreamWritingException while responding: " + p[0]
                     */
                    org.openlaszlo.i18n.LaszloMessages.getMessage(DataSource.class.getName(), "051018-201",
                            new Object[] { e.getMessage() }));
        }

    } finally {
        if (data != null) {
            data.release();
        }
        FileUtils.close(output);
        FileUtils.close(input);
    }
}

From source file:com.ibm.jaggr.service.impl.AggregatorImpl.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException {
    if (log.isLoggable(Level.FINEST))
        log.finest("doGet: URL=" + req.getRequestURI()); //$NON-NLS-1$

    req.setAttribute(AGGREGATOR_REQATTRNAME, this);
    ConcurrentMap<String, Object> concurrentMap = new ConcurrentHashMap<String, Object>();
    req.setAttribute(CONCURRENTMAP_REQATTRNAME, concurrentMap);

    try {//from  ww w . ja  v a2  s.  c om
        // Validate config last-modified if development mode is enabled
        if (getOptions().isDevelopmentMode()) {
            long lastModified = -1;
            URI configUri = getConfig().getConfigUri();
            if (configUri != null) {
                lastModified = configUri.toURL().openConnection().getLastModified();
            }
            if (lastModified > getConfig().lastModified()) {
                if (reloadConfig()) {
                    // If the config has been modified, then dependencies will be revalidated
                    // asynchronously.  Rather than forcing the current request to wait, return
                    // a response that will display an alert informing the user of what is 
                    // happening and asking them to reload the page.
                    String content = "alert('" + //$NON-NLS-1$ 
                            StringUtil.escapeForJavaScript(Messages.ConfigModified) + "');"; //$NON-NLS-1$
                    resp.addHeader("Cache-control", "no-store"); //$NON-NLS-1$ //$NON-NLS-2$
                    CopyUtil.copy(new StringReader(content), resp.getOutputStream());
                    return;
                }
            }
        }

        getTransport().decorateRequest(req);
        notifyRequestListeners(RequestNotifierAction.start, req, resp);

        ILayer layer = getLayer(req);
        long modifiedSince = req.getDateHeader("If-Modified-Since"); //$NON-NLS-1$
        long lastModified = (Math.max(getCacheManager().getCache().getCreated(), layer.getLastModified(req))
                / 1000) * 1000;
        if (modifiedSince >= lastModified) {
            if (log.isLoggable(Level.FINER)) {
                log.finer("Returning Not Modified response for layer in servlet" + //$NON-NLS-1$
                        getName() + ":" //$NON-NLS-1$
                        + req.getAttribute(IHttpTransport.REQUESTEDMODULES_REQATTRNAME).toString());
            }
            resp.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
        } else {
            // Get the InputStream for the response.  This call sets the Content-Type,
            // Content-Length and Content-Encoding headers in the response.
            InputStream in = layer.getInputStream(req, resp);
            // if any of the readers included an error response, then don't cache the layer.
            if (req.getAttribute(ILayer.NOCACHE_RESPONSE_REQATTRNAME) != null) {
                resp.addHeader("Cache-Control", "no-store"); //$NON-NLS-1$ //$NON-NLS-2$
            } else {
                resp.setDateHeader("Last-Modified", lastModified); //$NON-NLS-1$
                int expires = getConfig().getExpires();
                if (expires > 0) {
                    resp.addHeader("Cache-Control", "max-age=" + expires); //$NON-NLS-1$ //$NON-NLS-2$
                }
            }
            CopyUtil.copy(in, resp.getOutputStream());
        }
        notifyRequestListeners(RequestNotifierAction.end, req, resp);
    } catch (DependencyVerificationException e) {
        // clear the cache now even though it will be cleared when validateDeps has 
        // finished (asynchronously) so that any new requests will be forced to wait
        // until dependencies have been validated.
        getCacheManager().clearCache();
        getDependencies().validateDeps(false);

        resp.addHeader("Cache-control", "no-store"); //$NON-NLS-1$ //$NON-NLS-2$
        if (getOptions().isDevelopmentMode()) {
            String msg = StringUtil.escapeForJavaScript(MessageFormat.format(Messages.DepVerificationFailed,
                    new Object[] { e.getMessage(), AggregatorCommandProvider.EYECATCHER + " " + //$NON-NLS-1$
                            AggregatorCommandProvider.CMD_VALIDATEDEPS + " " + //$NON-NLS-1$
                            getName() + " " + //$NON-NLS-1$
                            AggregatorCommandProvider.PARAM_CLEAN,
                            getWorkingDirectory().toString().replace("\\", "\\\\") //$NON-NLS-1$ //$NON-NLS-2$
                    }));
            String content = "alert('" + msg + "');"; //$NON-NLS-1$ //$NON-NLS-2$
            try {
                CopyUtil.copy(new StringReader(content), resp.getOutputStream());
            } catch (IOException e1) {
                if (log.isLoggable(Level.SEVERE)) {
                    log.log(Level.SEVERE, e1.getMessage(), e1);
                }
                resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            }
        } else {
            resp.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
        }
    } catch (ProcessingDependenciesException e) {
        resp.addHeader("Cache-control", "no-store"); //$NON-NLS-1$ //$NON-NLS-2$
        if (getOptions().isDevelopmentMode()) {
            String content = "alert('" + StringUtil.escapeForJavaScript(Messages.Busy) + "');"; //$NON-NLS-1$ //$NON-NLS-2$
            try {
                CopyUtil.copy(new StringReader(content), resp.getOutputStream());
            } catch (IOException e1) {
                if (log.isLoggable(Level.SEVERE)) {
                    log.log(Level.SEVERE, e1.getMessage(), e1);
                }
                resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            }
        } else {
            resp.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
        }
    } catch (BadRequestException e) {
        exceptionResponse(req, resp, e, HttpServletResponse.SC_BAD_REQUEST);
    } catch (NotFoundException e) {
        exceptionResponse(req, resp, e, HttpServletResponse.SC_NOT_FOUND);
    } catch (Exception e) {
        exceptionResponse(req, resp, e, HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    } finally {
        concurrentMap.clear();
    }
}