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:it.jugpadova.controllers.EventController.java

@RequestMapping
public ModelAndView badge(HttpServletRequest req, HttpServletResponse res) throws Exception {
    try {//from w  ww .  j  av  a  2s.  co  m
        String locale = req.getParameter("lang");
        if (StringUtils.isBlank(locale)) {
            locale = (String) req.getAttribute("lang");
        }
        if (StringUtils.isBlank(locale)) {
            locale = "en";
        }
        java.text.DateFormat dateFormat = java.text.DateFormat.getDateInstance(java.text.DateFormat.DEFAULT,
                new Locale(locale));
        String baseUrl = Utilities.getBaseUrl(req);
        EventSearch eventSearch = buildEventSearch(req);
        List<Event> events = eventBo.search(eventSearch);
        boolean showJUGName = Boolean.parseBoolean(req.getParameter("jeb_showJUGName"));
        boolean showCountry = Boolean.parseBoolean(req.getParameter("jeb_showCountry"));
        boolean showDescription = Boolean.parseBoolean(req.getParameter("jeb_showDescription"));
        boolean showParticipants = Boolean.parseBoolean(req.getParameter("jeb_showParticipants"));
        String badgeStyle = req.getParameter("jeb_style");
        String result = eventBo.getBadgeCode(eventBo.getBadgeHtmlCode(events, dateFormat, baseUrl, showJUGName,
                showCountry, showDescription, showParticipants, badgeStyle, locale));
        // flush it in the res
        res.setHeader("Cache-Control", "no-store");
        res.setHeader("Pragma", "no-cache");
        res.setDateHeader("Expires", 0);
        res.setContentType("text/javascript");
        ServletOutputStream resOutputStream = res.getOutputStream();
        Writer writer = new OutputStreamWriter(resOutputStream, "UTF-8");
        writer.write(result);
        writer.flush();
        writer.close();
    } catch (Exception exception) {
        logger.error("Error producing badge", exception);
        throw exception;
    }
    return null;
}

From source file:grails.plugin.cache.web.filter.PageFragmentCachingFilter.java

/**
 * Set the headers in the response object, excluding the Gzip header
 * @param pageInfo//  w  ww.  j a  v a2 s  .  c o  m
 * @param response
 */
protected void setHeaders(final PageInfo pageInfo, final HttpServletResponse response) {

    Collection<Header<? extends Serializable>> headers = pageInfo.getHeaders();

    // Track which headers have been set so all headers of the same name
    // after the first are added
    TreeSet<String> setHeaders = new TreeSet<String>(String.CASE_INSENSITIVE_ORDER);

    for (Header<? extends Serializable> header : headers) {
        String name = header.getName();

        switch (header.getType()) {
        case STRING:
            if (setHeaders.contains(name)) {
                response.addHeader(name, (String) header.getValue());
            } else {
                setHeaders.add(name);
                response.setHeader(name, (String) header.getValue());
            }
            break;
        case DATE:
            if (setHeaders.contains(name)) {
                response.addDateHeader(name, (Long) header.getValue());
            } else {
                setHeaders.add(name);
                response.setDateHeader(name, (Long) header.getValue());
            }
            break;
        case INT:
            if (setHeaders.contains(name)) {
                response.addIntHeader(name, (Integer) header.getValue());
            } else {
                setHeaders.add(name);
                response.setIntHeader(name, (Integer) header.getValue());
            }
            break;
        default:
            throw new IllegalArgumentException("No mapping for Header: " + header);
        }
    }
}

From source file:org.mycore.common.content.util.MCRServletContentHelper.java

/**
 * Serve the specified content, optionally including the data content.
 * This method handles both GET and HEAD requests.
 *///  w w w .  j  a v a 2s  .c om
public static void serveContent(final MCRContent content, final HttpServletRequest request,
        final HttpServletResponse response, final ServletContext context, final Config config,
        final boolean withContent) throws IOException {

    boolean serveContent = withContent;

    final String path = getRequestPath(request);
    if (LOGGER.isDebugEnabled()) {
        if (serveContent) {
            LOGGER.debug("Serving '" + path + "' headers and data");
        } else {
            LOGGER.debug("Serving '" + path + "' headers only");
        }
    }

    if (response.isCommitted()) {
        //getContent has access to response
        return;
    }

    final boolean isError = response.getStatus() >= HttpServletResponse.SC_BAD_REQUEST;

    if (content == null && !isError) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND, request.getRequestURI());
        return;
    }

    //Check if all conditional header validate
    if (!isError && !checkIfHeaders(request, response, content)) {
        return;
    }

    // Find content type.
    String contentType = content.getMimeType();
    final String filename = getFileName(request, content);
    if (contentType == null) {
        contentType = context.getMimeType(filename);
        content.setMimeType(contentType);
    }
    String enc = content.getEncoding();
    if (enc != null) {
        contentType = String.format(Locale.ROOT, "%s; charset=%s", contentType, enc);
    }

    String eTag = null;
    ArrayList<Range> ranges = null;
    if (!isError) {
        eTag = content.getETag();
        if (config.useAcceptRanges) {
            response.setHeader("Accept-Ranges", "bytes");
        }

        ranges = parseRange(request, response, content);

        response.setHeader("ETag", eTag);

        long lastModified = content.lastModified();
        if (lastModified >= 0) {
            response.setDateHeader("Last-Modified", lastModified);
        }
        if (serveContent) {
            String dispositionType = request.getParameter("dl") == null ? "inline" : "attachment";
            response.setHeader("Content-Disposition", dispositionType + ";filename=\"" + filename + "\"");
        }
    }

    final long contentLength = content.length();
    //No Content to serve?
    if (contentLength == 0) {
        serveContent = false;
    }

    if (content.isUsingSession()) {
        response.addHeader("Cache-Control", "private, max-age=0, must-revalidate");
        response.addHeader("Vary", "*");
    }

    try (ServletOutputStream out = serveContent ? response.getOutputStream() : null) {
        if (serveContent) {
            try {
                response.setBufferSize(config.outputBufferSize);
            } catch (final IllegalStateException e) {
                //does not matter if we fail
            }
        }
        if (response instanceof ServletResponseWrapper) {
            if (request.getHeader("Range") != null) {
                LOGGER.warn("Response is wrapped by ServletResponseWrapper, no 'Range' requests supported.");
            }
            ranges = FULL;
        }

        if (isError || (ranges == null || ranges.isEmpty()) && request.getHeader("Range") == null
                || ranges == FULL) {
            //No ranges
            if (contentType != null) {
                if (LOGGER.isDebugEnabled()) {
                    LOGGER.debug("contentType='" + contentType + "'");
                }
                response.setContentType(contentType);
            }
            if (contentLength >= 0) {
                if (LOGGER.isDebugEnabled()) {
                    LOGGER.debug("contentLength=" + contentLength);
                }
                setContentLengthLong(response, contentLength);
            }

            if (serveContent) {
                copy(content, out, config.inputBufferSize, config.outputBufferSize);
            }

        } else {

            if (ranges == null || ranges.isEmpty()) {
                return;
            }

            // Partial content response.

            response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);

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

                final Range range = ranges.get(0);
                response.addHeader("Content-Range",
                        "bytes " + range.start + "-" + range.end + "/" + range.length);
                final long length = range.end - range.start + 1;
                setContentLengthLong(response, length);

                if (contentType != null) {
                    if (LOGGER.isDebugEnabled()) {
                        LOGGER.debug("contentType='" + contentType + "'");
                    }
                    response.setContentType(contentType);
                }

                if (serveContent) {
                    copy(content, out, range, config.inputBufferSize, config.outputBufferSize);
                }

            } else {

                response.setContentType("multipart/byteranges; boundary=" + MIME_BOUNDARY);

                if (serveContent) {
                    copy(content, out, ranges.iterator(), contentType, config.inputBufferSize,
                            config.outputBufferSize);
                }
            }
        }
    }
}

From source file:eionet.webq.web.controller.FileDownloadController.java

/**
 * Writes project file to response.//from w ww .  j a v a 2  s  .com
 *
 * @param name        file name
 * @param projectFile project file object
 * @param response    http response
 * @param disposition inline or attachment
 */
private void writeProjectFileToResponse(String name, ProjectFile projectFile, HttpServletResponse response,
        String disposition, String format) {

    ConfigurableMimeFileTypeMap mimeTypesMap = new ConfigurableMimeFileTypeMap();
    String contentType = mimeTypesMap.getContentType(name);

    // check if default
    if (mimeTypesMap.getContentType("").equals(contentType)) {
        if (name.endsWith(".xhtml")) {
            contentType = MediaType.APPLICATION_XHTML_XML_VALUE;
        } else if (name.endsWith(".js")) {
            contentType = "application/javascript";
        } else if (name.endsWith(".json")) {
            contentType = MediaType.APPLICATION_JSON_VALUE;
        } else {
            contentType = MediaType.APPLICATION_XML_VALUE;
        }
        // TODO check if there are more missing mime types
    }

    byte[] fileContent = projectFile.getFileContent();

    if ("json".equals(format)) {
        fileContent = jsonXMLConverter.convertXmlToJson(projectFile.getFileContent());
        contentType = MediaType.APPLICATION_JSON_VALUE;
        disposition = "inline";
    }

    if (contentType.startsWith("text") || contentType.startsWith("application")) {
        contentType += ";charset=UTF-8";
    }
    response.setContentType(contentType);
    setContentDisposition(response, disposition + ";filename=" + name);
    if (projectFile.getUpdated() != null) {
        response.setDateHeader("Last-Modified", projectFile.getUpdated().getTime());
    } else if (projectFile.getCreated() != null) {
        response.setDateHeader("Last-Modified", projectFile.getCreated().getTime());
    }
    writeToResponse(response, fileContent);
}

From source file:org.massyframework.assembly.base.web.HttpResourceProcessorManagement.java

/**
 * ???Http?//w  ww  .j a  v  a  2s  .  c  o  m
 * @param req http
 * @param resp http?
 * @param resourcePath ?
 * @param resourceURL ?URL
 * @throws IOException ?IO
 */
private void writeResource(final HttpServletRequest req, final HttpServletResponse resp, final String pathInfo,
        final URL resourceURL) throws IOException {
    URLConnection connection = resourceURL.openConnection();
    long lastModified = connection.getLastModified();
    int contentLength = connection.getContentLength();

    String etag = null;
    if (lastModified != -1 && contentLength != -1)
        etag = "W/\"" + contentLength + "-" + lastModified + "\""; //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$

    // Check for cache revalidation.
    // We should prefer ETag validation as the guarantees are stronger and all HTTP 1.1 clients should be using it
    String ifNoneMatch = req.getHeader(IF_NONE_MATCH);
    if (ifNoneMatch != null && etag != null && ifNoneMatch.indexOf(etag) != -1) {
        resp.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
    }

    long ifModifiedSince = req.getDateHeader(IF_MODIFIED_SINCE);
    // for purposes of comparison we add 999 to ifModifiedSince since the fidelity
    // of the IMS header generally doesn't include milli-seconds
    if (ifModifiedSince > -1 && lastModified > 0 && lastModified <= (ifModifiedSince + 999)) {
        resp.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
    }

    // return the full contents regularly
    if (contentLength != -1)
        resp.setContentLength(contentLength);

    String contentType = getServletContext().getMimeType(pathInfo);
    if (contentType != null)
        resp.setContentType(contentType);

    if (lastModified > 0)
        resp.setDateHeader(LAST_MODIFIED, lastModified);

    if (etag != null)
        resp.setHeader(ETAG, etag);

    if (contentLength != 0) {
        // open the input stream
        InputStream is = null;
        try {
            is = connection.getInputStream();
            // write the resource
            try {
                OutputStream os = resp.getOutputStream();
                int writtenContentLength = writeResourceToOutputStream(is, os);
                if (contentLength == -1 || contentLength != writtenContentLength)
                    resp.setContentLength(writtenContentLength);
            } catch (IllegalStateException e) { // can occur if the response output is already open as a Writer
                Writer writer = resp.getWriter();
                writeResourceToWriter(is, writer);
                // Since ContentLength is a measure of the number of bytes contained in the body
                // of a message when we use a Writer we lose control of the exact byte count and
                // defer the problem to the Servlet Engine's Writer implementation.
            }
        } catch (FileNotFoundException e) {
            // FileNotFoundException may indicate the following scenarios
            // - url is a directory
            // - url is not accessible
            sendError(resp, HttpServletResponse.SC_FORBIDDEN);
        } catch (SecurityException e) {
            // SecurityException may indicate the following scenarios
            // - url is not accessible
            sendError(resp, HttpServletResponse.SC_FORBIDDEN);
        } finally {
            if (is != null)
                try {
                    is.close();
                } catch (IOException e) {
                    // ignore
                }
        }
    }

}

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

/**
 *  ? ?  ?// www  . j a va2s. co  m
 *
 * @param request    ?
 * @param response   
 * @param offset     ?
 * @param forceReset ? ?? 
 * @return 
 * @throws Exception  ? ? :-(
 */
@RequestMapping("/notifications")
public ModelAndView showNotifications(HttpServletRequest request, HttpServletResponse response,
        @ModelAttribute("notifications") Action action,
        @RequestParam(value = "offset", defaultValue = "0") int offset,
        @RequestParam(value = "forceReset", defaultValue = "false") boolean forceReset) throws Exception {
    Template tmpl = Template.getTemplate(request);
    if (!tmpl.isSessionAuthorized()) {
        throw new AccessViolationException("not authorized");
    }

    String filterAction = action.getFilter();
    UserEventFilterEnum eventFilter;
    if (filterValues.contains(filterAction)) {
        eventFilter = UserEventFilterEnum.valueOf(filterAction.toUpperCase());
    } else {
        eventFilter = UserEventFilterEnum.ALL;
    }

    User currentUser = tmpl.getCurrentUser();
    String nick = currentUser.getNick();

    Map<String, Object> params = new HashMap<>();
    params.put("nick", nick);
    params.put("forceReset", forceReset);
    if (eventFilter != UserEventFilterEnum.ALL) {
        params.put("addition_query", "&filter=" + eventFilter.getValue());
    } else {
        params.put("addition_query", "");
    }

    if (offset < 0) {
        offset = 0;
    }

    boolean firstPage = offset == 0;
    int topics = tmpl.getProf().getTopics();

    if (topics > 200) {
        topics = 200;
    }

    params.put("firstPage", firstPage);
    params.put("topics", topics);
    params.put("offset", offset);

    params.put("disable_event_header", true);

    /* define timestamps for caching */
    long time = System.currentTimeMillis();
    int delay = firstPage ? 90 : 60 * 60;
    response.setDateHeader("Expires", time + 1000 * delay);
    params.put("unreadCount", currentUser.getUnreadEvents());
    params.put("isMyNotifications", true);

    response.addHeader("Cache-Control", "no-cache");
    List<UserEvent> list = userEventService.getRepliesForUser(currentUser, true, topics, offset, eventFilter);
    List<PreparedUserEvent> prepared = userEventService.prepare(list, false, request.isSecure());

    if ("POST".equalsIgnoreCase(request.getMethod())) {
        userEventService.resetUnreadReplies(currentUser);
    } else {
        params.put("enableReset", true);
    }

    params.put("topicsList", prepared);
    params.put("hasMore", list.size() == topics);

    return new ModelAndView("show-replies", params);
}

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 ww .  j av  a 2s.co 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:com.skilrock.lms.web.scratchService.inventoryMgmt.common.AgentDispatchGameAction.java

/**
 * This method is called when the Add Book button is pressed
 * /*from   w  ww .  j  a  v  a 2 s  .  c  om*/
 * @return String
 */
public String addBook() {

    System.out.println("---------I am in ADD Book--------------");

    // reInitialize();

    HttpServletResponse response = getResponse();
    response.setHeader("Pragma", "no-cache"); // HTTP 1.0
    response.setHeader("Cache-Control", "no-cache"); // HTTP 1.1
    response.setDateHeader("Expires", 0); // prevents caching at the proxy
    // server
    response.setHeader("Cache-Control", "private"); // HTTP 1.1
    response.setHeader("Cache-Control", "no-store"); // HTTP 1.1
    response.setHeader("Cache-Control", "max-stale=0"); // HTTP 1.1

    // System.out.println("add bookkkkkkkkkkkkk::" +
    // request.getParameter("hidBookNbr"));

    // System.out.println("add bookkkkkkkkkkkkk::" + getHidBookNbr());

    HttpSession session = getRequest().getSession();
    List<BookBean> bookList = (List<BookBean>) session.getAttribute("AGT_BOOK_LIST");
    List<PackBean> packList = (List<PackBean>) session.getAttribute("AGT_PACK_LIST");

    BookBean bookBean = null;

    // copy values and add another book to the list
    if (bookList != null) {

        copyBookValues(bookList);
        bookBean = new BookBean();
        bookBean.setValid(true);
        bookList.add(bookBean);
        setBookList(bookList);
    }

    /*
     * try { PrintWriter out = getResponse().getWriter(); out.write("This is
     * Aman Chawla"); } catch (IOException e) { // TODO Auto-generated catch
     * block e.printStackTrace(); }
     */

    return SUCCESS;

}

From source file:com.pureinfo.tgirls.servlet.GetScriptServlet.java

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

    String scriptType = request.getParameter("scriptType");
    if (StringUtils.isEmpty(scriptType)) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST);
        return;// w  w w . j  a v  a2s.  c  o m
    }

    String location = null;
    String userId = null;
    String photoId = null;
    ScriptType st = null;//

    try {
        st = ScriptType.getScriptType(Integer.parseInt(scriptType));
    } catch (Exception e) {
    }

    switch (st) {
    case UserInfo:
        userId = request.getParameter("utid");
        location = ScriptManager.mapUserInfoScriptLocation(userId);
        break;
    case UserUpload:
        userId = request.getParameter("utid");
        location = ScriptManager.mapUserUploadScriptLocation(userId);
        break;
    case UserBuy:
        userId = request.getParameter("utid");
        location = ScriptManager.mapUserBuyScriptLocation(userId);
        break;
    case Pic:
        photoId = request.getParameter("picId");
        location = ScriptManager.mapPhotoScriptLocation(photoId);
        break;

    default:
        response.sendError(HttpServletResponse.SC_BAD_REQUEST);
        return;
    }

    if (StringUtils.isEmpty(location)) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST);
        return;
    }

    location += "?version=" + Math.random();
    logger.debug("return script:" + location);

    response.setHeader("Location", location);
    response.setHeader("Content-Encoding", "gzip");
    response.setStatus(HttpServletResponse.SC_SEE_OTHER);
    response.setHeader("Cache-Control", "no-cache"); //HTTP 1.1
    response.setHeader("Pragma", "no-cache"); //HTTP 1.0
    response.setDateHeader("Expires", -1);
    response.setDateHeader("max-age", 0);

    return;

}

From source file:at.gv.egiz.bku.online.webapp.ResultServlet.java

protected void doGet(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, java.io.IOException {

    BindingProcessorManager bindingProcessorManager = (BindingProcessorManager) getServletContext()
            .getAttribute("bindingProcessorManager");
    if (bindingProcessorManager == null) {
        String msg = "Configuration error: BindingProcessorManager missing!";
        log.error(msg);/*w w w . j ava2 s .c  om*/
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg);
        return;
    }

    Configuration conf = ((BindingProcessorManagerImpl) bindingProcessorManager).getConfiguration();
    if (conf == null)
        log.error("No configuration");
    else
        MoccaParameterBean.setP3PHeader(conf, resp);

    Id id = (Id) req.getAttribute("id");
    BindingProcessor bindingProcessor = null;
    if (id == null || !((bindingProcessor = bindingProcessorManager
            .getBindingProcessor(id)) instanceof HTTPBindingProcessor)) {
        resp.sendRedirect(expiredPageUrl);
        return;
    }

    HTTPBindingProcessor bp = (HTTPBindingProcessor) bindingProcessor;

    OutputStream outputStream = null;
    try {
        String redirectUrl = bp.getRedirectURL();
        if (redirectUrl != null && !redirectUrl.trim().isEmpty()) {
            log.info("Sending (deferred) redirect to {}.", redirectUrl);
            resp.sendRedirect(redirectUrl);
            // TODO Couldn't we simply discard the output?
            outputStream = new NullOutputStream();
        } else {
            log.debug("Setting HTTP status code {}.", bp.getResponseCode());
            resp.setStatus(bp.getResponseCode());
            resp.setHeader("Cache-Control", "no-store"); // HTTP 1.1
            resp.setHeader("Pragma", "no-cache"); // HTTP 1.0
            resp.setDateHeader("Expires", 0);
            Map<String, String> responseHeaders = bp.getResponseHeaders();
            for (Entry<String, String> header : responseHeaders.entrySet()) {
                String key = header.getKey();
                String value = header.getValue();
                log.debug("Setting response header {}: {}.", key, value);
                resp.setHeader(key, value);
            }
            resp.setContentType(bp.getResultContentType());
            log.info("Sending result.");
            outputStream = resp.getOutputStream();
        }
        bp.writeResultTo(outputStream, responseEncoding);
    } finally {
        if (outputStream != null)
            outputStream.close();
        bindingProcessorManager.removeBindingProcessor(id);
    }
}