Example usage for javax.servlet.http HttpServletResponse SC_NOT_MODIFIED

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

Introduction

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

Prototype

int SC_NOT_MODIFIED

To view the source code for javax.servlet.http HttpServletResponse SC_NOT_MODIFIED.

Click Source Link

Document

Status code (304) indicating that a conditional GET operation found that the resource was available and not modified.

Usage

From source file:com.mikenimer.familydam.services.photos.ThumbnailService.java

/**
 * First check for the etag and see if we can return a 302 not modified response. If not, set the etag for next time.
 * @param request/*from  www.  j  a v  a2  s .co  m*/
 * @param response
 * @param resource
 * @return
 */
private boolean checkAndSetCacheHeaders(SlingHttpServletRequest request, SlingHttpServletResponse response,
        Resource resource) {
    ResourceMetadata meta = resource.getResourceMetadata();
    String hash = new Integer(request.getPathInfo().hashCode()).toString();
    String eTag = request.getHeader(HttpConstants.HEADER_ETAG);
    if (hash.equals(eTag)) {
        response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
        return true;
    } else {
        response.setHeader(HttpConstants.HEADER_ETAG, hash);
        response.setHeader("Cache-Control", "600");
    }
    return false;
}

From source file:ru.frostman.web.dispatch.Dispatcher.java

private void sendNotModified(HttpServletResponse response, String eTag) {
    try {//from ww w. jav  a 2  s .co m
        response.setHeader(HEADER_E_TAG, eTag); // Required in 304.
        response.sendError(HttpServletResponse.SC_NOT_MODIFIED);
    } catch (IOException e) {
        throw new JavinRuntimeException("Exception while sending 304: Not modified", e);
    }
}

From source file:org.messic.server.facade.controllers.rest.SongController.java

@ApiMethod(path = "/services/songs/{songSid}/audio", verb = ApiVerb.GET, description = "Get the audio binary from a song resource of an album", produces = {
        MediaType.APPLICATION_OCTET_STREAM_VALUE })
@ApiErrors(apierrors = { @ApiError(code = UnknownMessicRESTException.VALUE, description = "Unknown error"),
        @ApiError(code = NotAuthorizedMessicRESTException.VALUE, description = "Forbidden access"),
        @ApiError(code = IOMessicRESTException.VALUE, description = "IO error trying to get the audio resource") })
@RequestMapping(value = "/{songSid}/audio", method = { RequestMethod.GET, RequestMethod.HEAD })
@ResponseStatus(HttpStatus.OK)//  w  w  w.java 2s.c  o  m
public void getSongWithRanges(
        @ApiParam(name = "songSid", description = "SID of the song resource we want to download", paramType = ApiParamType.PATH, required = true) @PathVariable Long songSid,
        HttpServletRequest request, HttpServletResponse response)
        throws NotAuthorizedMessicRESTException, IOMessicRESTException, UnknownMessicRESTException {
    User user = SecurityUtil.getCurrentUser();

    try {
        //http://balusc.blogspot.com.es/2009/02/fileservlet-supporting-resume-and.html
        // Whether the request body should be written (GET) or not (HEAD).
        boolean content = request.getMethod().equalsIgnoreCase("GET");
        APISong.AudioSongStream ass = songAPI.getAudioSong(user, songSid);

        // Validate and process Range and If-Range headers.
        String eTag = songSid + "_" + ass.contentLength + "_" + ass.lastModified;
        long expires = System.currentTimeMillis() + Range.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 && Range.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 > ass.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 && !Range.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 <= ass.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, ass.contentLength - 1, ass.contentLength);
        List<Range> ranges = new ArrayList<Range>();

        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 */" + ass.contentLength); // 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 < ass.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 = Range.sublong(part, 0, part.indexOf("-"));
                    long end = Range.sublong(part, part.indexOf("-") + 1, part.length());

                    if (start == -1) {
                        start = ass.contentLength - end;
                        end = ass.contentLength - 1;
                    } else if (end == -1 || end > ass.contentLength - 1) {
                        end = ass.contentLength - 1;
                    }

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

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

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

        // Get content type by file name and set default GZIP support and content disposition.
        String contentType = "audio/mpeg";
        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 && Range.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 && Range.accepts(accept, contentType) ? "inline" : "attachment";
        }

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

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

        // Prepare streams.
        OutputStream output = null;

        try {
            // Open streams.
            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, Range.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.
                    Range.copy(ass.raf, 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.
                    Range.copy(ass.raf, output, r.start, r.length);
                }

            } else {

                // Return multiple parts of file.
                response.setContentType("multipart/byteranges; boundary=" + Range.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("--" + Range.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.
                        Range.copy(ass.raf, output, r.start, r.length);
                    }

                    // End with multipart boundary.
                    sos.println();
                    sos.println("--" + Range.MULTIPART_BOUNDARY + "--");
                }
            }
        } finally {
            // Gently close streams.
            Range.close(output);
            Range.close(ass.is);
            Range.close(ass.raf);
        }
        return;
    } catch (IOException ioe) {
        log.error("failed!", ioe);
        throw new IOMessicRESTException(ioe);
    } catch (Exception e) {
        throw new UnknownMessicRESTException(e);
    }
}

From source file:org.jboss.seam.wiki.core.ui.FeedServlet.java

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

    String feedIdParam = request.getParameter("feedId");
    String areaNameParam = request.getParameter("areaName");
    String nodeNameParam = request.getParameter("nodeName");
    String aggregateParam = request.getParameter("aggregate");
    log.debug(">>> feed request id: '" + feedIdParam + "' area name: '" + areaNameParam + "' node name: '"
            + nodeNameParam + "'");

    Contexts.getSessionContext().set("LAST_ACCESS_ACTION",
            "Feed: " + feedIdParam + " area: '" + areaNameParam + "' node: '" + nodeNameParam + "'");

    // Feed type//from www. j a v  a  2s . c  o  m
    String pathInfo = request.getPathInfo();
    log.debug("requested feed type: " + pathInfo);
    if (!feedTypes.containsKey(pathInfo)) {
        log.debug("can not render this feed type, returning BAD REQUEST");
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Unsupported feed type " + pathInfo);
        return;
    }
    SyndFeedType syndFeedType = feedTypes.get(pathInfo);

    // Comments
    String commentsParam = request.getParameter("comments");
    Comments comments = Comments.include;
    if (commentsParam != null && commentsParam.length() > 0) {
        try {
            comments = Comments.valueOf(commentsParam);
        } catch (IllegalArgumentException ex) {
            log.info("invalid comments request parameter: " + commentsParam);
        }
    }
    log.debug("feed rendering handles comments: " + comments);

    // Tag
    String tagParam = request.getParameter("tag");
    String tag = null;
    if (tagParam != null && tagParam.length() > 0) {
        log.debug("feed rendering restricts on tag: " + tagParam);
        tag = tagParam;
    }

    Feed feed = resolveFeed(aggregateParam, feedIdParam, areaNameParam, nodeNameParam);

    if (feed == null) {
        log.debug("feed not found, returning NOT FOUND");
        response.sendError(HttpServletResponse.SC_NOT_FOUND, "Feed");
        return;
    }

    log.debug("checking permissions of " + feed);
    // Authenticate and authorize, first with current user (session) then with basic HTTP authentication
    Integer currentAccessLevel = (Integer) Component.getInstance("currentAccessLevel");
    if (feed.getReadAccessLevel() > currentAccessLevel) {
        boolean loggedIn = ((Authenticator) Component.getInstance(Authenticator.class))
                .authenticateBasicHttp(request);
        currentAccessLevel = (Integer) Component.getInstance("currentAccessLevel");
        if (!loggedIn || feed.getReadAccessLevel() > currentAccessLevel) {
            log.debug("requiring authentication, feed has higher access level than current");
            response.setHeader("WWW-Authenticate",
                    "Basic realm=\"" + feed.getTitle().replace("\"", "'") + "\"");
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
            return;
        }
    }

    Date lastFeedEntryDate = null;
    if (feed.getId() != null) {

        // Ask the database what the latest feed entry is for that feed, then use its updated timestamp hash
        FeedDAO feedDAO = (FeedDAO) Component.getInstance(FeedDAO.class);
        List<FeedEntry> result = feedDAO.findLastFeedEntries(feed.getId(), 1);
        if (result.size() > 0) {
            lastFeedEntryDate = result.get(0).getUpdatedDate();
        }

    } else {

        // Get the first (latest) entry of the aggregated feed and use its published timestamp hash (ignoring updates!)
        // There is a wrinkle hidden here: What if a feed entry is updated? Then the published timestamp should also
        // be different because the "first latest" feed entry in the list is sorted by both published and updated
        // timestamps. So even though we only use published timestamp hash as an ETag, this timestamp also changes
        // when a feed entry is updated because the collection order changes as well.
        if (feed.getFeedEntries().size() > 0) {
            lastFeedEntryDate = feed.getFeedEntries().iterator().next().getPublishedDate();
        }
    }
    if (lastFeedEntryDate != null) {
        String etag = calculateEtag(lastFeedEntryDate);
        log.debug("setting etag header: " + etag);
        response.setHeader("ETag", etag);
        String previousToken = request.getHeader("If-None-Match");
        if (previousToken != null && previousToken.equals(etag)) {
            log.debug("found matching etag in request header, returning 304 Not Modified");
            response.sendError(HttpServletResponse.SC_NOT_MODIFIED);
            return;
        }
    }

    // TODO: Refactor this parameter mess a little
    log.debug("finally rendering feed");
    SyndFeed syndFeed = createSyndFeed(request.getRequestURL().toString(), syndFeedType, feed,
            currentAccessLevel, tag, comments, aggregateParam);

    // If we have an entry on this feed, take the last entry's update timestamp and use it as
    // the published timestamp of the feed. The Rome library does not have a setUpdatedDate()
    // method and abuses the published date to write <updated> into the Atom <feed> element.
    if (lastFeedEntryDate != null) {
        syndFeed.setPublishedDate(lastFeedEntryDate);
    }

    // Write feed to output
    response.setContentType(syndFeedType.contentType);
    response.setCharacterEncoding("UTF-8");
    SyndFeedOutput output = new SyndFeedOutput();
    try {
        output.output(syndFeed, response.getWriter());
    } catch (FeedException ex) {
        throw new ServletException(ex);
    }
    response.getWriter().flush();

    log.debug("<<< feed rendering complete");
}

From source file:org.shredzone.cilla.view.FeedView.java

/**
 * Fetches the pages by query and returns a feed.
 *
 * @param filter/*  w w  w.  j a v a 2 s  .com*/
 *            {@link FilterModel} with the query parameters
 * @param context
 *            {@link ViewContext} with the view context
 * @param req
 *            the {@link HttpServletRequest}
 * @param resp
 *            the {@link HttpServletResponse}
 * @param selfUrl
 *            freshly generated link to this feed
 * @param feedId
 *            a unique id for this feed
 * @param type
 *            feed type, any type supported by ROME.
 */
@SuppressWarnings("unchecked")
private void fetchPages(FilterModel filter, ViewContext context, HttpServletRequest req,
        HttpServletResponse resp, String selfUrl, String feedId, String type)
        throws ViewException, CillaServiceException {
    Date lastModified = pageDao.fetchMinMaxModification()[1];

    if (isNotModifiedSince(req, lastModified)) {
        throw new ErrorResponseException(HttpServletResponse.SC_NOT_MODIFIED);
    }

    SearchResult result = searchService.search(filter);
    result.setPaginator(new PaginatorModel(maxEntries));

    String contentType = "application/xml";
    if (type.startsWith("atom_")) {
        contentType = "application/atom+xml";
    } else if (type.startsWith("rss_")) {
        contentType = "application/rss+xml";
    }

    String uriPrefix = context.getRequestServerUrl() + '/';

    SyndFeed feed = new SyndFeedImpl();
    feed.setFeedType(type);
    feed.setTitle(title);
    feed.setDescription(description);
    feed.setLink(linkService.linkTo().absolute().toString());
    feed.setUri(uriPrefix + feedId);
    feed.setPublishedDate(lastModified);

    SyndLink selfLink = new SyndLinkImpl();
    selfLink.setRel("self");
    selfLink.setType(contentType);
    selfLink.setHref(selfUrl);
    feed.getLinks().add(selfLink);
    feed.getEntries().addAll(result.getPages().stream().filter(page -> !page.isRestricted()) // do not show restricted pages
            .map(page -> createEntry(page, uriPrefix)).collect(Collectors.toList()));

    resp.setContentType(contentType);
    resp.setDateHeader("Last-Modified", lastModified.getTime());
    resp.setCharacterEncoding("utf-8");

    try {
        SyndFeedOutput output = new SyndFeedOutput();
        output.output(feed, resp.getWriter());
    } catch (FeedException | IOException ex) {
        throw new ViewException("Could not create feed", ex);
    }
}

From source file:com.openedit.generators.FileGenerator.java

protected boolean checkCache(WebPageRequest inContext, Page contentpage, HttpServletRequest req,
        HttpServletResponse res) {/*from www  . j av a  2s .c om*/
    long now = System.currentTimeMillis();
    boolean cache = true;
    String nocache = inContext.findValue("cache");
    if (nocache != null) {
        cache = Boolean.parseBoolean(nocache);
    } else {
        //is this recenlty modified?
        //3333333recent99  + 24 hours (mil * sec * min * hours) will be more than now
        cache = contentpage.lastModified() + (1000 * 60 * 60 * 24) < now;
    }
    if (cache && req != null) {
        String since = req.getHeader("If-Modified-Since");
        if (since != null && since.endsWith("GMT")) {
            //304 Not Modified
            try {
                Date old = getLastModFormat().parse(since);
                if (!contentpage.getLastModified().after(old)) {
                    //log.info("if since"  + since);
                    res.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
                    return true;
                }
            } catch (Exception ex) {
                log.error(since);
            }
        }

    }
    res.setDateHeader("Last-Modified", contentpage.getLastModified().getTime());

    if (cache) {
        res.setDateHeader("Expires", now + (1000 * 60 * 60 * 24)); //sec * min * hour * 48 Hours            
    } else {
        res.setDateHeader("Expires", now - (1000 * 60 * 60 * 24)); //expired 24 hours ago
    }
    return false;
}

From source file:org.ambraproject.wombat.controller.StaticResourceController.java

/**
 * Serves a .js or .css asset that has already been concatenated and minified. See {@link AssetService} for details on
 * this process.// www  .jav a  2  s.c  o  m
 *
 * @param filePath the path to the file (relative to the theme)
 * @param response response object
 * @throws IOException
 */
private void serveCompiledAsset(String filePath, HttpServletRequest request, HttpServletResponse response)
        throws IOException {

    // The hash is already included in the compiled asset's filename, so we take advantage
    // of that here and use it as the etag.
    Matcher matcher = COMPILED_ASSET_PATTERN.matcher(filePath);
    if (!matcher.matches()) {
        throw new IllegalArgumentException(filePath + " is not a valid compiled asset path");
    }
    String basename = filePath.substring(COMPILED_NAMESPACE.length());

    // This is a "strong" etag since it's based on a fingerprint of the contents.
    String etag = String.format("\"%s\"", matcher.group(1));
    long lastModified = assetService.getLastModifiedTime(basename);
    if (HttpMessageUtil.checkIfModifiedSince(request, lastModified, etag)) {
        response.setHeader("Etag", etag);
        response.setDateHeader(HttpHeaders.LAST_MODIFIED, lastModified);
        assetService.serveCompiledAsset(basename, response.getOutputStream());
    } else {
        response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
        response.setHeader("Etag", etag);
    }
}

From source file:ru.org.linux.topic.TopicController.java

private ModelAndView getMessageNew(Section section, WebRequest webRequest, HttpServletRequest request,
        HttpServletResponse response, int page, String filter, String groupName, int msgid) throws Exception {
    Topic topic = messageDao.getById(msgid);
    Template tmpl = Template.getTemplate(request);

    PreparedTopic preparedMessage = messagePrepareService.prepareTopic(topic, request.isSecure(),
            tmpl.getCurrentUser());//from w  w w.  ja  v a 2  s  .co  m
    Group group = preparedMessage.getGroup();

    if (!group.getUrlName().equals(groupName) || group.getSectionId() != section.getId()) {
        return new ModelAndView(new RedirectView(topic.getLink()));
    }

    Map<String, Object> params = new HashMap<>();

    boolean showDeleted = request.getParameter("deleted") != null;
    if (showDeleted) {
        page = -1;
    }

    boolean rss = request.getParameter("output") != null && "rss".equals(request.getParameter("output"));

    if (rss && topic.isExpired()) {
        throw new MessageNotFoundException(topic.getId(), "no more comments");
    }

    if (!tmpl.isModeratorSession()) {
        if (showDeleted && !"POST".equals(request.getMethod())) {
            return new ModelAndView(new RedirectView(topic.getLink()));
        }
    }

    if (page == -1 && !tmpl.isSessionAuthorized()) {
        return new ModelAndView(new RedirectView(topic.getLink()));
    }

    int pages = topic.getPageCount(tmpl.getProf().getMessages());

    if (page >= pages && (page > 0 || pages > 0)) {
        if (pages == 0) {
            return new ModelAndView(new RedirectView(topic.getLink()));
        } else {
            return new ModelAndView(new RedirectView(topic.getLinkPage(pages - 1)));
        }
    }

    if (showDeleted) {
        if (!tmpl.isSessionAuthorized()) {
            throw new BadInputException("    ??");
        }
    }

    params.put("showDeleted", showDeleted);

    User currentUser = AuthUtil.getCurrentUser();

    if (topic.isExpired() && showDeleted && !tmpl.isModeratorSession()) {
        throw new MessageNotFoundException(topic.getId(),
                "? ?    ? ");
    }

    permissionService.checkView(topic, currentUser);

    if (group.getCommentsRestriction() == -1 && !tmpl.isSessionAuthorized()) {
        throw new AccessViolationException(" ? ? ?");
    }

    params.put("message", topic);
    params.put("preparedMessage", preparedMessage);

    if (topic.isExpired()) {
        response.setDateHeader("Expires", System.currentTimeMillis() + 30 * 24 * 60 * 60 * 1000L);
    }

    CommentList comments = commentService.getCommentList(topic, showDeleted);

    if (!rss) {
        params.put("page", page);
        params.put("group", group);
        params.put("showAdsense", !tmpl.isSessionAuthorized() || !tmpl.getProf().isHideAdsense());

        if (!tmpl.isSessionAuthorized()) { // because users have IgnoreList and memories
            String etag = getEtag(topic, tmpl);
            response.setHeader("Etag", etag);

            if (request.getHeader("If-None-Match") != null) {
                if (etag.equals(request.getHeader("If-None-Match"))) {
                    response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
                    return null;
                }
            } else if (checkLastModified(webRequest, topic)) {
                return null;
            }
        }

        params.put("messageMenu", messagePrepareService.getTopicMenu(preparedMessage, currentUser,
                request.isSecure(), tmpl.getProf(), true));

        Set<Integer> ignoreList;

        if (currentUser != null) {
            ignoreList = ignoreListDao.get(currentUser);
        } else {
            ignoreList = ImmutableSet.of();
        }

        int defaultFilterMode = getDefaultFilter(tmpl.getProf(), ignoreList.isEmpty());
        int filterMode;

        if (filter != null) {
            filterMode = CommentFilter.parseFilterChain(filter);

            if (!ignoreList.isEmpty() && filterMode == CommentFilter.FILTER_ANONYMOUS) {
                filterMode += CommentFilter.FILTER_IGNORED;
            }
        } else {
            filterMode = defaultFilterMode;
        }

        params.put("filterMode", CommentFilter.toString(filterMode));
        params.put("defaultFilterMode", CommentFilter.toString(defaultFilterMode));

        loadTopicScroller(params, topic, currentUser, !ignoreList.isEmpty());

        Set<Integer> hideSet = commentService.makeHideSet(comments, filterMode, ignoreList);

        CommentFilter cv = new CommentFilter(comments);

        boolean reverse = tmpl.getProf().isShowNewFirst();

        List<Comment> commentsFiltred = cv.getCommentsForPage(reverse, page, tmpl.getProf().getMessages(),
                hideSet);
        List<Comment> commentsFull = cv.getCommentsForPage(reverse, page, tmpl.getProf().getMessages(),
                ImmutableSet.<Integer>of());

        params.put("unfilteredCount", commentsFull.size());

        List<PreparedComment> commentsPrepared = prepareService.prepareCommentList(comments, commentsFiltred,
                request.isSecure(), tmpl, topic);

        params.put("commentsPrepared", commentsPrepared);

        IPBlockInfo ipBlockInfo = ipBlockDao.getBlockInfo(request.getRemoteAddr());
        params.put("ipBlockInfo", ipBlockInfo);

        if (pages > 1 && !showDeleted) {
            params.put("pages",
                    buildPages(topic, tmpl.getProf().getMessages(), filterMode, defaultFilterMode, page));
        }
    } else {
        CommentFilter cv = new CommentFilter(comments);

        List<Comment> commentsFiltred = cv.getCommentsForPage(true, 0, RSS_DEFAULT, ImmutableSet.<Integer>of());

        List<PreparedRSSComment> commentsPrepared = prepareService.prepareCommentListRSS(commentsFiltred,
                request.isSecure());

        params.put("commentsPrepared", commentsPrepared);
        LorURL lorURL = new LorURL(configuration.getMainURI(), configuration.getMainUrl());
        params.put("mainURL", lorURL.fixScheme(request.isSecure()));
    }

    return new ModelAndView(rss ? "view-message-rss" : "view-message", params);
}

From source file:v7db.files.buckets.BucketsServletTest.java

public void testFormPostGET() throws IOException, SAXException {

    BasicBSONObject bucket = prepareBucket("1", "FormPost", null, null);
    MongoContentStorage storage = new MongoContentStorage(getMongo().getDB("test"));
    ContentSHA sha = storage.storeContent(new ByteArrayInputStream("test".getBytes()));
    ServletUnitClient sc = sr.newClient();
    {//ww w  .  ja  v a  2  s .c om
        WebRequest request = new GetMethodWebRequest("http://test/myServlet/1");
        request.setParameter("sha", sha.getDigest());
        try {
            sc.getResponse(request);
            fail("bucket not found => 404");
        } catch (HttpNotFoundException e) {
            assertEquals(String.format("Bucket '1' does not have a file matching digest '%s'", sha.getDigest()),
                    e.getResponseMessage());
        }
    }

    bucket.append("FormPost",
            new BasicBSONObject("data", new BasicBSONObject("files", new BasicBSONObject("file",
                    new BasicBSONObject("filename", "a.txt").append("sha", sha.getSHA())))));

    {
        WebRequest request = new GetMethodWebRequest("http://test/myServlet/1");
        request.setParameter("sha", sha.getDigest());
        WebResponse response = sc.getResponse(request);
        assertEquals("test", response.getText());
        assertEquals(sha.getDigest(), response.getHeaderField("ETag"));
        assertEquals(4, response.getContentLength());
        assertEquals("attachment; filename=\"a.txt\"", response.getHeaderField("Content-Disposition"));
    }

    {
        WebRequest request = new GetMethodWebRequest("http://test/myServlet/1");
        request.setParameter("sha", sha.getDigest());
        request.setParameter("filename", "x.txt");
        WebResponse response = sc.getResponse(request);
        assertEquals("test", response.getText());
        assertEquals(sha.getDigest(), response.getHeaderField("ETag"));
        assertEquals(4, response.getContentLength());
        assertEquals("attachment; filename=\"x.txt\"", response.getHeaderField("Content-Disposition"));
    }

    {
        WebRequest request = new GetMethodWebRequest("http://test/myServlet/1");
        request.setParameter("sha", sha.getDigest());
        request.setHeaderField("If-None-Match", sha.getDigest());
        WebResponse response = sc.getResponse(request);
        assertEquals(HttpServletResponse.SC_NOT_MODIFIED, response.getResponseCode());
    }

}

From source file:be.milieuinfo.core.proxy.controller.ProxyServlet.java

private boolean doResponseRedirectOrNotModifiedLogic(HttpServletRequest servletRequest,
        HttpServletResponse servletResponse, HttpResponse proxyResponse, int statusCode)
        throws ServletException, IOException {
    // Check if the proxy response is a redirect
    // The following code is adapted from org.tigris.noodle.filters.CheckForRedirect
    if (statusCode >= HttpServletResponse.SC_MULTIPLE_CHOICES /* 300 */
            && statusCode < HttpServletResponse.SC_NOT_MODIFIED /* 304 */) {
        Header locationHeader = proxyResponse.getLastHeader(HttpHeaders.LOCATION);
        if (locationHeader == null) {
            throw new ServletException("Received status code: " + statusCode + " but no " + HttpHeaders.LOCATION
                    + " header was found in the response");
        }//w  ww . j  a  v a 2 s .c  o m
        // Modify the redirect to go to this proxy servlet rather that the proxied host
        String locStr = rewriteUrlFromResponse(servletRequest, locationHeader.getValue());

        servletResponse.sendRedirect(locStr);
        return true;
    }
    // 304 needs special handling.  See:
    // http://www.ics.uci.edu/pub/ietf/http/rfc1945.html#Code304
    // We get a 304 whenever passed an 'If-Modified-Since'
    // header and the data on disk has not changed; server
    // responds w/ a 304 saying I'm not going to send the
    // body because the file has not changed.
    if (statusCode == HttpServletResponse.SC_NOT_MODIFIED) {
        servletResponse.setIntHeader(HttpHeaders.CONTENT_LENGTH, 0);
        servletResponse.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
        return true;
    }
    return false;
}