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:gov.nih.nci.ncicb.tcga.dcc.common.web.StaticContentServlet.java

private void prepareResponse(HttpServletResponse response, URL[] resources, String rawResourcePath)
        throws IOException {
    long lastModified = -1;
    int contentLength = 0;
    String mimeType = null;/*from   ww w . ja  v  a  2  s . c om*/
    for (int i = 0; i < resources.length; i++) {
        final URLConnection resourceConn = resources[i].openConnection();
        //Setting the last modified http for the requested resource
        if (resourceConn.getLastModified() > lastModified) {
            lastModified = resourceConn.getLastModified();
        }
        //Setting the mime type of the resource requested
        String currentMimeType = getServletContext().getMimeType(resources[i].getPath());
        if (log.isDebugEnabled()) {
            log.debug("Current MimeType: " + currentMimeType);
        }
        if (currentMimeType == null) {
            int index = resources[i].getPath().lastIndexOf('.');
            if (index > 0) {
                String extension = resources[i].getPath().substring(resources[i].getPath().lastIndexOf('.'));
                currentMimeType = (String) defaultMimeTypes.get(extension);
            } else {
                currentMimeType = "text/html"; //html will be the default mime.
            }
        }
        if (mimeType == null) {
            mimeType = currentMimeType;
        } else if (!mimeType.equals(currentMimeType)) {
            //This does not apply to us yet since we don't use combined resource url but maybe in the future ...
            throw new MalformedURLException("Combined resource path: " + rawResourcePath
                    + " is invalid. All resources in a combined resource path must be of the same mime type.");
        }
        contentLength += resourceConn.getContentLength();
    }
    response.setContentType(mimeType);
    response.setHeader(HTTP_CONTENT_LENGTH_HEADER, Long.toString(contentLength));
    response.setDateHeader(HTTP_LAST_MODIFIED_HEADER, lastModified);
    if (cacheTimeout > 0) {
        configureCaching(response, cacheTimeout);
    }
}

From source file:org.fao.geonet.api.groups.GroupsApi.java

/**
 * Writes the group logo image to the response. If no image is found it
 * writes a 1x1 transparent PNG. If the request contain cache related
 * headers it checks if the resource has changed and return a 304 Not
 * Modified response if not changed.//from w  ww . j av  a 2 s.  c om
 *
 * @param groupId    the group identifier.
 * @param webRequest the web request.
 * @param request    the native HTTP Request.
 * @param response   the servlet response.
 * @throws ResourceNotFoundException if no group exists with groupId.
 */
@ApiOperation(value = "Get the group logo image.", nickname = "get", notes = API_GET_LOGO_NOTE)
@RequestMapping(value = "/{groupId}/logo", method = RequestMethod.GET)
public void getGroupLogo(
        @ApiParam(value = "Group identifier", required = true) @PathVariable(value = "groupId") final Integer groupId,
        @ApiIgnore final WebRequest webRequest, HttpServletRequest request, HttpServletResponse response)
        throws ResourceNotFoundException {

    Locale locale = languageUtils.parseAcceptLanguage(request.getLocales());

    ApplicationContext context = ApplicationContextHolder.get();
    ServiceContext serviceContext = ApiUtils.createServiceContext(request, locale.getISO3Country());
    if (context == null) {
        throw new RuntimeException("ServiceContext not available");
    }

    GroupRepository groupRepository = context.getBean(GroupRepository.class);

    Group group = groupRepository.findOne(groupId);
    if (group == null) {
        throw new ResourceNotFoundException(
                messages.getMessage("api.groups.group_not_found", new Object[] { groupId }, locale));
    }
    try {
        final Path logosDir = Resources.locateLogosDir(serviceContext);
        final Path harvesterLogosDir = Resources.locateHarvesterLogosDir(serviceContext);
        final String logoUUID = group.getLogo();
        Path imagePath = null;
        FileTime lastModifiedTime = null;
        if (StringUtils.isNotBlank(logoUUID) && !logoUUID.startsWith("http://")
                && !logoUUID.startsWith("https//")) {
            imagePath = Resources.findImagePath(logoUUID, logosDir);
            if (imagePath == null) {
                imagePath = Resources.findImagePath(logoUUID, harvesterLogosDir);
            }
            if (imagePath != null) {
                lastModifiedTime = Files.getLastModifiedTime(imagePath);
                if (webRequest.checkNotModified(lastModifiedTime.toMillis())) {
                    // webRequest.checkNotModified sets the right HTTP headers
                    response.setDateHeader("Expires", System.currentTimeMillis() + SIX_HOURS * 1000L);

                    return;
                }
                response.setContentType(AttachmentsApi.getFileContentType(imagePath));
                response.setContentLength((int) Files.size(imagePath));
                response.addHeader("Cache-Control", "max-age=" + SIX_HOURS + ", public");
                response.setDateHeader("Expires", System.currentTimeMillis() + SIX_HOURS * 1000L);
                FileUtils.copyFile(imagePath.toFile(), response.getOutputStream());
            }
        }

        if (imagePath == null) {
            // no logo image found. Return a transparent 1x1 png
            lastModifiedTime = FileTime.fromMillis(0);
            if (webRequest.checkNotModified(lastModifiedTime.toMillis())) {
                return;
            }
            response.setContentType("image/png");
            response.setContentLength(TRANSPARENT_1_X_1_PNG.length);
            response.addHeader("Cache-Control", "max-age=" + SIX_HOURS + ", public");
            response.getOutputStream().write(TRANSPARENT_1_X_1_PNG);
        }

    } catch (IOException e) {
        Log.error(LOGGER,
                String.format("There was an error accessing the logo of the group with id '%d'", groupId));
        throw new RuntimeException(e);
    }
}

From source file:net.yacy.http.servlets.YaCyDefaultServlet.java

protected void sendDirectory(HttpServletRequest request, HttpServletResponse response, Resource resource,
        String pathInContext) throws IOException {
    if (!_dirAllowed) {
        response.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;//w w w  . java 2  s  . c  o m
    }

    String base = URIUtil.addPaths(request.getRequestURI(), URIUtil.SLASH);

    String dir = resource.getListHTML(base, pathInContext.length() > 1);
    if (dir == null) {
        response.sendError(HttpServletResponse.SC_FORBIDDEN, "No directory");
        return;
    }

    byte[] data = dir.getBytes(StandardCharsets.UTF_8);
    response.setContentType(MimeTypes.Type.TEXT_HTML_UTF_8.asString());
    response.setContentLength(data.length);
    response.setHeader(HeaderFramework.CACHE_CONTROL, "no-cache, no-store");
    response.setDateHeader(HeaderFramework.EXPIRES, System.currentTimeMillis() + 10000); // consider that directories are not modified that often
    response.setDateHeader(HeaderFramework.LAST_MODIFIED, resource.lastModified());
    response.getOutputStream().write(data);
}

From source file:net.sourceforge.subsonic.controller.RESTController.java

public ModelAndView download(HttpServletRequest request, HttpServletResponse response) throws Exception {
    request = wrapRequest(request);//from  w w w  .j  a  v a2 s. c om
    User user = securityService.getCurrentUser(request);
    if (!user.isDownloadRole()) {
        error(request, response, ErrorCode.NOT_AUTHORIZED,
                user.getUsername() + " is not authorized to download files.");
        return null;
    }

    long ifModifiedSince = request.getDateHeader("If-Modified-Since");
    long lastModified = downloadController.getLastModified(request);

    if (ifModifiedSince != -1 && lastModified != -1 && lastModified <= ifModifiedSince) {
        response.sendError(HttpServletResponse.SC_NOT_MODIFIED);
        return null;
    }

    if (lastModified != -1) {
        response.setDateHeader("Last-Modified", lastModified);
    }

    return downloadController.handleRequest(request, response);
}

From source file:com.sangupta.httpd.HttpdHandler.java

/**
 * Send file contents back to client/*w w  w .ja  va  2s.c om*/
 * 
 * @param request
 * @param response
 * @param uri
 * @throws IOException
 */
private void sendFileContents(HttpServletRequest request, HttpServletResponse response, String uri)
        throws IOException {
    File file = new File(documentRoot, uri);
    if (!file.exists() || file.isHidden()) {
        response.sendError(HttpStatusCode.NOT_FOUND);
        return;
    }

    if (file.isDirectory()) {
        response.sendRedirect("/" + uri + "/");
        return;
    }

    if (!file.isFile()) {
        response.sendError(HttpStatusCode.FORBIDDEN);
        return;
    }

    String etag = null;
    if (!this.httpdConfig.noEtag) {
        // compute the weak ETAG based on file time and size
        final long time = file.lastModified();
        final long size = file.length();
        final String name = file.getName();

        etag = "w/" + HashUtils.getMD5Hex(name + ":" + size + ":" + time);
    }

    // check for if-modified-since header name
    String ifModifiedSince = request.getHeader("If-Modified-Since");
    if (ifModifiedSince != null && !ifModifiedSince.isEmpty()) {
        Date ifModifiedSinceDate = parseDateHeader(ifModifiedSince);

        if (ifModifiedSinceDate != null) {
            // Only compare up to the second because the datetime format we send to the client
            // does not have milliseconds
            long ifModifiedSinceDateSeconds = ifModifiedSinceDate.getTime() / 1000;
            long fileLastModifiedSeconds = file.lastModified() / 1000;

            if (ifModifiedSinceDateSeconds == fileLastModifiedSeconds) {
                response.setStatus(HttpStatusCode.NOT_MODIFIED);
                return;
            }
        }
    }

    // add mime-header - based on the file extension
    response.setContentType(MimeUtils.getMimeTypeForFileExtension(FilenameUtils.getExtension(file.getName())));
    response.setDateHeader("Last-Modified", file.lastModified());

    // check for no cache
    if (this.httpdConfig.noCache) {
        response.addHeader("Cache-Control", "no-store, no-cache, must-revalidate");
    }

    // check for no-sniff
    if (this.httpdConfig.noSniff) {
        response.addHeader("X-Content-Type-Options", "nosniff");
    }

    // etag
    if (!this.httpdConfig.noEtag) {
        response.addHeader("Etag", etag);
    }

    // send back file contents
    response.setContentLength((int) file.length());
    IOUtils.copyLarge(FileUtils.openInputStream(file), response.getOutputStream());
}

From source file:helma.servlet.AbstractServletClient.java

private boolean checkNotModified(File file, HttpServletRequest req, HttpServletResponse res) {
    // we do two rounds of conditional requests:
    // first ETag based, then based on last modified date.
    // calculate ETag checksum on last modified date and content length.
    byte[] checksum = new byte[16];
    long n = file.lastModified();
    for (int i = 0; i < 8; i++) {
        checksum[i] = (byte) (n);
        n >>>= 8;/* w  w w .j av  a 2  s. c o  m*/
    }
    n = file.length();
    for (int i = 8; i < 16; i++) {
        checksum[i] = (byte) (n);
        n >>>= 8;
    }
    String etag = "\"" + new String(Base64.encode(checksum)) + "\"";
    res.setHeader("ETag", etag);
    String etagHeader = req.getHeader("If-None-Match");
    if (etagHeader != null) {
        StringTokenizer st = new StringTokenizer(etagHeader, ", \r\n");
        while (st.hasMoreTokens()) {
            if (etag.equals(st.nextToken())) {
                return true;
            }
        }
    }
    // as a fallback, since some browsers don't support ETag based
    // conditional GET for embedded images and stuff, check last modified date.
    // date headers don't do milliseconds, round to seconds
    long lastModified = (file.lastModified() / 1000) * 1000;
    long ifModifiedSince = req.getDateHeader("If-Modified-Since");
    if (lastModified == ifModifiedSince) {
        return true;
    }
    res.setDateHeader("Last-Modified", lastModified);
    return false;
}

From source file:net.oneandone.jasmin.main.Servlet.java

private void get(HttpServletRequest request, HttpServletResponse response, String path) throws IOException {
    String version;//w ww  . ja  va  2 s .co m
    boolean expire;
    int idx;
    long started;
    long duration;
    int bytes;
    boolean gzip;
    long date;

    idx = path.indexOf('/');
    if (idx == -1) {
        notFound(request, response);
        return;
    }
    started = System.currentTimeMillis();
    version = path.substring(0, idx);
    expire = !"no-expires".equals(version);
    if (expire && !VM_STARTUP_STR.equals(version)) {
        try {
            synchronized (FMT) {
                date = FMT.parse(version).getTime();
            }
        } catch (ParseException e) {
            notFound(request, response);
            return;
        }
        if (sameTime(VM_STARTUP, date) || sameTime(otherVmStartupDate, date)) {
            // ok
        } else if (date > otherVmStartupDate) {
            otherVmStartupDate = date;
        } else {
            // usually, otherVmStartupDate is smaller, but after switching back, VM_STARTUP will be smaller
            if (Math.min(otherVmStartupDate, VM_STARTUP) - date > SEVEN_DAYS) {
                gone(request, response);
                return;
            }
        }
    }
    path = path.substring(idx + 1);
    if (application.resolver.isLife()) {
        // unknown headers are ok: see http://tools.ietf.org/html/rfc2616#section-7.1
        response.addHeader("Hi", "Sie werden bedient von Jasmin, vielen Dank fuer ihren Request!");
    }
    checkCharset(request.getHeader("Accept-Charset"));
    if (expire && application.expires != null) {
        response.setDateHeader("Expires", started + 1000L * application.expires);
        response.addHeader("Cache-Control", "max-age=" + application.expires);
    }
    gzip = canGzip(request);
    bytes = engine.request(path, response, gzip);
    duration = System.currentTimeMillis() - started;
    LOG.info(path + "|" + bytes + "|" + duration + "|" + gzip + "|" + referer(request));
}

From source file:edu.chalmers.dat076.moviefinder.controller.FileController.java

/**
 * Process the actual request./*  w ww. j a  va 2s .com*/
 *
 * @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.
 */
private void processRequest(HttpServletRequest request, HttpServletResponse response, boolean content,
        String path, String defaultContentType) throws IOException {
    // Validate the requested file ------------------------------------------------------------

    // URL-decode the file name (might contain spaces and on) and prepare file object.
    File file = new File(path);

    // 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() + FileControllerUtils.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 && FileControllerUtils.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 && !FileControllerUtils.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<>();

    // 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 = FileControllerUtils.sublong(part, 0, part.indexOf("-"));
                long end = FileControllerUtils.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 = request.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 = defaultContentType;
    //}

    // 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 && FileControllerUtils.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 && FileControllerUtils.accepts(accept, contentType) ? "inline"
                : "attachment";
    }

    // Initialize response.
    response.reset();
    response.setBufferSize(FileControllerUtils.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, FileControllerUtils.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.
                FileControllerUtils.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.
                FileControllerUtils.copy(input, output, r.start, r.length);
            }

        } else {

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

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

From source file:com.ibm.jaggr.core.impl.AbstractAggregatorImpl.java

protected void processResourceRequest(HttpServletRequest req, HttpServletResponse resp, IResource res,
        String path) {/*from w w  w .  j a va 2s . c  o m*/
    final String sourceMethod = "processRequest"; //$NON-NLS-1$
    boolean isTraceLogging = log.isLoggable(Level.FINER);
    if (isTraceLogging) {
        log.entering(AbstractAggregatorImpl.class.getName(), sourceMethod,
                new Object[] { req, resp, res, path });
    }
    try {
        URI uri = res.getURI();
        if (path != null && path.length() > 0 && !uri.getPath().endsWith("/")) { //$NON-NLS-1$
            // Make sure we resolve against a folder path
            uri = new URI(uri.getScheme(), uri.getAuthority(), uri.getPath() + "/", uri.getQuery(), //$NON-NLS-1$
                    uri.getFragment());
            res = newResource(uri);
        }
        IResource resolved = res.resolve(path);
        if (!resolved.exists()) {
            throw new NotFoundException(resolved.getURI().toString());
        }
        resp.setDateHeader("Last-Modified", resolved.lastModified()); //$NON-NLS-1$
        int expires = getConfig().getExpires();
        resp.addHeader("Cache-Control", //$NON-NLS-1$
                "public" + (expires > 0 ? (", max-age=" + expires) : "") //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
        );
        InputStream is = res.resolve(path).getInputStream();
        OutputStream os = resp.getOutputStream();
        CopyUtil.copy(is, os);
    } catch (NotFoundException e) {
        if (log.isLoggable(Level.INFO)) {
            log.log(Level.INFO, e.getMessage() + " - " + req.getRequestURI(), e); //$NON-NLS-1$
        }
        resp.setStatus(HttpServletResponse.SC_NOT_FOUND);
    } catch (Exception e) {
        if (log.isLoggable(Level.WARNING)) {
            log.log(Level.WARNING, e.getMessage() + " - " + req.getRequestURI(), e); //$NON-NLS-1$
        }
        resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
    if (isTraceLogging) {
        log.exiting(AbstractAggregatorImpl.class.getName(), sourceMethod);
    }

}

From source file:ru.org.linux.user.WhoisController.java

@RequestMapping(value = "/people/{nick}/profile", method = { RequestMethod.GET, RequestMethod.HEAD })
public ModelAndView getInfoNew(@PathVariable String nick, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    Template tmpl = Template.getTemplate(request);

    User user = userDao.getUser(nick);//from  ww  w .j a  va 2 s  .  co m

    if (user.isBlocked() && !tmpl.isSessionAuthorized()) {
        throw new UserBanedException(user, userDao.getBanInfoClass(user));
    }

    ModelAndView mv = new ModelAndView("whois");
    mv.getModel().put("user", user);
    mv.getModel().put("userInfo", userDao.getUserInfoClass(user));

    mv.getModel().put("userpic",
            userService.getUserpic(user, request.isSecure(), tmpl.getProf().getAvatarMode()));

    if (user.isBlocked()) {
        mv.getModel().put("banInfo", userDao.getBanInfoClass(user));
    }

    boolean currentUser = tmpl.isSessionAuthorized() && tmpl.getNick().equals(nick);

    if (!user.isAnonymous()) {
        UserStatistics userStat = userDao.getUserStatisticsClass(user,
                currentUser || tmpl.isModeratorSession());
        mv.getModel().put("userStat", userStat);
        mv.getModel().put("sectionStat", prepareSectionStats(userStat));
    }

    mv.getModel().put("moderatorOrCurrentUser", currentUser || tmpl.isModeratorSession());
    mv.getModel().put("currentUser", currentUser);

    if (tmpl.isSessionAuthorized() && !currentUser) {
        Set<Integer> ignoreList = ignoreListDao.get(tmpl.getCurrentUser());

        mv.getModel().put("ignored", ignoreList.contains(user.getId()));

        mv.getModel().put("remark", userDao.getRemark(tmpl.getCurrentUser(), user));
    }

    if (tmpl.isSessionAuthorized() && currentUser) {
        mv.getModel().put("hasRemarks", (userDao.getRemarkCount(tmpl.getCurrentUser()) > 0));
    }

    String userinfo = userDao.getUserInfo(user);

    if (!Strings.isNullOrEmpty(userinfo)) {
        mv.getModel().put("userInfoText", lorCodeService.parseComment(userinfo, request.isSecure(),
                !topicPermissionService.followAuthorLinks(user)));
    }

    mv.addObject("favoriteTags", userTagService.favoritesGet(user));
    if (currentUser || tmpl.isModeratorSession()) {
        mv.addObject("ignoreTags", userTagService.ignoresGet(user));
    }
    response.setDateHeader("Expires", System.currentTimeMillis() + 120000);
    return mv;
}