Example usage for javax.servlet.http HttpServletResponse SC_PRECONDITION_FAILED

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

Introduction

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

Prototype

int SC_PRECONDITION_FAILED

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

Click Source Link

Document

Status code (412) indicating that the precondition given in one or more of the request-header fields evaluated to false when it was tested on the server.

Usage

From source file:org.apache.sling.launchpad.webapp.integrationtest.servlets.post.PostServletMoveTest.java

public void testMoveNodeMultipleSourcePartial() throws IOException {
    final String testPath = TEST_BASE_PATH + "/mvmult/" + System.currentTimeMillis();
    final String testRoot = testClient.createNode(HTTP_BASE_URL + testPath, null);

    // create multiple source nodes
    Map<String, String> props = new HashMap<String, String>();
    props.put("text", "Hello");
    testClient.createNode(HTTP_BASE_URL + testPath + "/src1", props);
    testClient.createNode(HTTP_BASE_URL + testPath + "/src3", props);

    // move the src? nodes
    List<NameValuePair> nvPairs = new ArrayList<NameValuePair>();
    nvPairs.add(new NameValuePair(SlingPostConstants.RP_OPERATION, SlingPostConstants.OPERATION_MOVE));
    nvPairs.add(new NameValuePair(SlingPostConstants.RP_DEST, testPath + "/dest/"));
    nvPairs.add(new NameValuePair(SlingPostConstants.RP_APPLY_TO, testPath + "/src1"));
    nvPairs.add(new NameValuePair(SlingPostConstants.RP_APPLY_TO, testPath + "/src2"));
    nvPairs.add(new NameValuePair(SlingPostConstants.RP_APPLY_TO, testPath + "/src3"));
    nvPairs.add(new NameValuePair(SlingPostConstants.RP_APPLY_TO, testPath + "/src4"));
    assertPostStatus(testRoot, HttpServletResponse.SC_PRECONDITION_FAILED, nvPairs,
            "Expecting Move Failure: dest parent does not exist");

    // create destination parent
    testClient.createNode(HTTP_BASE_URL + testPath + "/dest", props);

    // now dest exists, so we expect success
    assertPostStatus(testRoot, HttpServletResponse.SC_OK, nvPairs, "Expecting Move Success");

    // assert partial existence of the src?/text properties
    assertHttpStatus(HTTP_BASE_URL + testPath + "/dest/src1/text", HttpServletResponse.SC_OK);
    assertHttpStatus(HTTP_BASE_URL + testPath + "/dest/src2/text", HttpServletResponse.SC_NOT_FOUND);
    assertHttpStatus(HTTP_BASE_URL + testPath + "/dest/src3/text", HttpServletResponse.SC_OK);
    assertHttpStatus(HTTP_BASE_URL + testPath + "/dest/src4/text", HttpServletResponse.SC_NOT_FOUND);

    // assert non-existence of src?
    assertHttpStatus(HTTP_BASE_URL + testPath + "/src1.html", HttpServletResponse.SC_NOT_FOUND);
    assertHttpStatus(HTTP_BASE_URL + testPath + "/src2.html", HttpServletResponse.SC_NOT_FOUND);
    assertHttpStatus(HTTP_BASE_URL + testPath + "/src3.html", HttpServletResponse.SC_NOT_FOUND);
    assertHttpStatus(HTTP_BASE_URL + testPath + "/src4.html", HttpServletResponse.SC_NOT_FOUND);

    testClient.delete(testRoot);/*from ww  w .  j  a  v a2 s.  co m*/
}

From source file:org.dspace.app.rest.utils.MultipartFileSenderTest.java

/**
 * If modified since given date then return 412
 *
 * @throws Exception//  ww w. ja  va  2s .  c  om
 */
@Test
public void testIfUnmodifiedSinceModifiedSince() throws Exception {
    Long time = new Date().getTime();
    MultipartFileSender multipartFileSender = MultipartFileSender.fromInputStream(is).with(requestWrapper)
            .withFileName(fileName).with(responseWrapper).withChecksum(checksum).withMimetype(mimeType)
            .withLength(length).withLastModified(time);

    when(request.getDateHeader(eq("If-Unmodified-Since"))).thenReturn(time - 100000);
    when(request.getDateHeader(eq("If-Modified-Since"))).thenReturn(-1L);

    multipartFileSender.isValid();

    assertEquals(HttpServletResponse.SC_PRECONDITION_FAILED, responseWrapper.getStatusCode());

}

From source file:info.magnolia.cms.filters.RangeSupportFilter.java

private HttpServletResponse wrapResponse(final HttpServletRequest request, final HttpServletResponse response) {
    return new HttpServletResponseWrapper(response) {

        /** default length is max. We hope that the underlying code will set proper content length as a header before we proceed serving some bytes. */
        private int length = Integer.MAX_VALUE;

        private final Map<String, Object> headers = new HashMap<String, Object>();

        private String eTag;

        private List<RangeInfo> ranges;

        private RangeInfo full;

        private ServletOutputStream stream;

        private PrintWriter writer;

        @Override//from ww w  .j  a  v a2s  .  c  o  m
        public void addDateHeader(String name, long date) {
            super.addDateHeader(name, date);
            this.headers.put(name, date);
            if ("Last-Modified".equalsIgnoreCase(name)) {
                lastModTime = date;
            }
        }

        @Override
        public void setDateHeader(String name, long date) {
            super.setDateHeader(name, date);
            this.headers.put(name, date);
            if ("Last-Modified".equalsIgnoreCase(name)) {
                lastModTime = date;
            }
        }

        @Override
        public void addHeader(String name, String value) {
            if ("Content-Disposition".equalsIgnoreCase(name) && log.isDebugEnabled()) {
                log.warn("content disposition enforced by underlying filter/servlet");
            }
            super.addHeader(name, value);
            this.headers.put(name, value);
        }

        @Override
        public void setHeader(String name, String value) {
            if ("Content-Disposition".equalsIgnoreCase(name) && log.isDebugEnabled()) {
                log.warn("content disposition enforced by underlying filter/servlet");
            }
            super.setHeader(name, value);
            this.headers.put(name, value);
        }

        @Override
        public void addIntHeader(String name, int value) {
            super.addIntHeader(name, value);
            this.headers.put(name, value);
        }

        @Override
        public void setIntHeader(String name, int value) {
            super.setIntHeader(name, value);
            this.headers.put(name, value);
        }

        @Override
        public void setContentLength(int len) {
            this.length = len;
            // do not propagate length up. We might not be able to change it once it is set. We will set it ourselves once we are ready to serve bytes.
        }

        @Override
        public ServletOutputStream getOutputStream() throws IOException {
            // make sure we set stream only once. Multiple calls to this method are allowed.
            if (this.stream == null) {
                ServletOutputStream stream = super.getOutputStream();
                // wrap the response to filter out everything except desired range
                this.stream = addRangeSupportWrapper(request, response, stream);

                if (!isServeContent || this.stream == null) {
                    // swallow output on head requests
                    this.stream = new ServletOutputStream() {

                        @Override
                        public void write(int b) throws IOException {
                            // do nothing, we do not write any output now
                        }
                    };
                }
            }
            return stream;
        }

        private ServletOutputStream addRangeSupportWrapper(final HttpServletRequest request,
                final HttpServletResponse response, ServletOutputStream stream) throws IOException {
            if (!processContent(request, response)) {
                // we might have to return null stream instead as the previous method already called res.sendError();
                return null;
            }

            if (headers.containsKey("Content-Range")) {
                // doesn't work for tomcat as it accesses underlying stream under our hands!!!
                log.debug("Range request was handled by underlying filter/servlet.");
                return stream;
            }
            if (ranges == null || ranges.isEmpty()) {
                // no op, serve all as usual
                log.debug("Didn't find any range to speak of. Serving all content as usual.");
                if (length != Integer.MAX_VALUE) {
                    // set real length when we know it
                    response.setContentLength(length);
                }
            } else if (ranges.size() == 1) {
                RangeInfo range = ranges.get(0);
                log.debug("Serving range [{}].", range);
                // setting 206 header is essential for some clients. The would abort if response is set to 200
                response.setStatus(SC_PARTIAL_CONTENT);
                stream = new RangedOutputStream(stream, range);
            } else {
                log.error("Requested multiple ranges [{}].", ranges.size());
                // TODO: add support for multiple ranges (sent as multipart request), for now just send error back
                response.setHeader("Content-Range", "bytes */" + length);
                response.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE);
                // again we might have to return null stream after calling sendError() as the original stream might no longer be valid
            }
            return stream;
        }

        @Override
        public PrintWriter getWriter() throws IOException {
            if (!wrapWriter) {
                return super.getWriter();
            }
            if (this.writer == null) {
                this.writer = new PrintWriter(new OutputStreamWriter(getOutputStream()));
            }
            return writer;
        }

        private boolean processContent(HttpServletRequest request, HttpServletResponse response)
                throws IOException {
            log.debug("Serving binary on uri {} was last modified at {}",
                    new Object[] { request.getRequestURI(), lastModTime });
            if (!isRequestValid(request, response)) {
                log.debug("Skipping request {} since it doesn't require body",
                        new Object[] { request.getRequestURI() });
                return false;
            }
            if (!processRange(request)) {
                log.debug("Could not process range of request {}", new Object[] { request.getRequestURI() });
                return false;
            }
            return true;
        }

        private boolean processRange(HttpServletRequest request) throws IOException {
            full = new RangeInfo(0, length - 1, length);
            ranges = new ArrayList<RangeInfo>();

            String range = request.getHeader("Range");

            // Valid range header format is "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);
                response.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE);
                return false;
            }

            // If-Range header must 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");
                    if (ifRangeTime != -1 && ifRangeTime + 1000 < lastModTime) {
                        ranges.add(full);
                    }
                } catch (IllegalArgumentException ignore) {
                    // happens when if-range contains something else then date
                    ranges.add(full);
                }
            }

            // in case there were no invalid If-Range headers, then look at requested byte ranges.
            if (ranges.isEmpty()) {
                for (String part : range.substring(6).split(",")) {
                    int start = intSubstring(StringUtils.substringBefore(part, "-"));
                    int end = intSubstring(StringUtils.substringAfter(part, "-"));

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

                    // Is range valid?
                    if (start > end) {
                        response.setHeader("Content-Range", "bytes */" + length); // Required in 416.
                        response.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE);
                        return false;
                    }

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

            response.setHeader("ETag", eTag);
            if (ranges.size() == 1) {
                RangeInfo r = ranges.get(0);
                response.setHeader("Accept-Ranges", "bytes");
                response.setHeader("Content-Range",
                        "bytes " + r.start + "-" + r.end + "/" + r.totalLengthOfServedBinary);
                length = r.lengthOfRange;
            }
            return true;
        }

        private int intSubstring(String value) {
            return value.length() > 0 ? Integer.parseInt(value) : -1;
        }

        @Override
        public void flushBuffer() throws IOException {
            if (writer != null) {
                writer.flush();
            }
            if (stream != null) {
                stream.flush();
            }

            super.flushBuffer();
        }

        private boolean isRequestValid(HttpServletRequest request, HttpServletResponse response)
                throws IOException {
            String fileName = StringUtils.substringAfterLast(request.getRequestURI(), "/");
            eTag = fileName + "_" + length + "_" + lastModTime;

            // If-None-Match header should contain "*" or ETag.
            String ifNoneMatch = request.getHeader("If-None-Match");
            if (ifNoneMatch != null && matches(ifNoneMatch, eTag)) {
                response.setHeader("ETag", eTag); // Required in 304.
                log.debug("Returning {} on header If-None-Match", HttpServletResponse.SC_NOT_MODIFIED);
                response.sendError(HttpServletResponse.SC_NOT_MODIFIED);
                return false;
            }

            // If-Modified-Since header must be greater than LastModified. ignore if If-None-Match header exists
            long ifModifiedSince = request.getDateHeader("If-Modified-Since");
            if (ifNoneMatch == null && ifModifiedSince != -1 && ifModifiedSince + 1000 > lastModTime) {
                response.setHeader("ETag", eTag); // Required in 304.
                // 304 response should contain Date header unless running on timeless server (see 304 response docu)
                response.addDateHeader("Date", lastModTime);
                log.debug("Returning {} on header If-Modified-Since", HttpServletResponse.SC_NOT_MODIFIED);
                response.sendError(HttpServletResponse.SC_NOT_MODIFIED);
                return false;
            }

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

            // If-Unmodified-Since header must be greater than LastModified.
            long ifUnmodifiedSince = request.getDateHeader("If-Unmodified-Since");
            if (ifUnmodifiedSince != -1 && ifUnmodifiedSince + 1000 <= lastModTime) {
                log.debug("Returning {} on header If-Unmodified-Since",
                        HttpServletResponse.SC_PRECONDITION_FAILED);
                response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
                return false;
            }

            log.debug("Passed all precondition checkes for request {}", request.getRequestURI());
            return true;
        }
    };
}

From source file:com.liferay.lms.servlet.SCORMFileServerServlet.java

/**
 * Procesa los metodos HTTP GET y POST.<br>
 * Busca en la ruta que se le ha pedido el comienzo del directorio
 * "contenidos" y sirve el fichero./*from  w  ww  .j  av a  2  s .  c  o  m*/
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response, boolean content)
        throws ServletException, java.io.IOException {
    String mime_type;
    String charset;
    String patharchivo;
    String uri;

    try {
        User user = PortalUtil.getUser(request);

        if (user == null) {
            String userId = null;
            String companyId = null;
            Cookie[] cookies = ((HttpServletRequest) request).getCookies();
            if (Validator.isNotNull(cookies)) {
                for (Cookie c : cookies) {
                    if ("COMPANY_ID".equals(c.getName())) {
                        companyId = c.getValue();
                    } else if ("ID".equals(c.getName())) {
                        userId = hexStringToStringByAscii(c.getValue());
                    }
                }
            }

            if (userId != null && companyId != null) {
                try {
                    Company company = CompanyLocalServiceUtil.getCompany(Long.parseLong(companyId));
                    Key key = company.getKeyObj();

                    String userIdPlain = Encryptor.decrypt(key, userId);

                    user = UserLocalServiceUtil.getUser(Long.valueOf(userIdPlain));

                    // Now you can set the liferayUser into a thread local
                    // for later use or
                    // something like that.

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

        String rutaDatos = SCORMContentLocalServiceUtil.getBaseDir();

        // Se comprueba que el usuario tiene permisos para acceder.
        // Damos acceso a todo el mundo al directorio "personalizacion",
        // para permitir mostrar a todos la pantalla de identificacion.
        uri = URLDecoder.decode(request.getRequestURI(), "UTF-8");
        uri = uri.substring(uri.indexOf("scorm/") + "scorm/".length());
        patharchivo = rutaDatos + "/" + uri;

        String[] params = uri.split("/");
        long groupId = GetterUtil.getLong(params[1]);
        String uuid = params[2];
        SCORMContent scormContent = SCORMContentLocalServiceUtil.getSCORMContentByUuidAndGroupId(uuid, groupId);

        boolean allowed = false;
        if (user == null) {
            user = UserLocalServiceUtil.getDefaultUser(PortalUtil.getDefaultCompanyId());
        }
        PermissionChecker pc = PermissionCheckerFactoryUtil.create(user);
        allowed = pc.hasPermission(groupId, SCORMContent.class.getName(), scormContent.getScormId(),
                ActionKeys.VIEW);
        if (!allowed) {
            AssetEntry scormAsset = AssetEntryLocalServiceUtil.getEntry(SCORMContent.class.getName(),
                    scormContent.getPrimaryKey());
            long scormAssetId = scormAsset.getEntryId();
            int typeId = new Long((new SCORMLearningActivityType()).getTypeId()).intValue();
            long[] groupIds = user.getGroupIds();
            for (long gId : groupIds) {
                List<LearningActivity> acts = LearningActivityLocalServiceUtil
                        .getLearningActivitiesOfGroupAndType(gId, typeId);
                for (LearningActivity act : acts) {
                    String entryId = LearningActivityLocalServiceUtil.getExtraContentValue(act.getActId(),
                            "assetEntry");
                    if (Validator.isNotNull(entryId) && Long.valueOf(entryId) == scormAssetId) {
                        allowed = pc.hasPermission(gId, LearningActivity.class.getName(), act.getActId(),
                                ActionKeys.VIEW);
                        if (allowed) {
                            break;
                        }
                    }
                }
                if (allowed) {
                    break;
                }
            }

        }
        if (allowed) {

            File archivo = new File(patharchivo);

            // Si el archivo existe y no es un directorio se sirve. Si no,
            // no se hace nada.
            if (archivo.exists() && archivo.isFile()) {

                // El content type siempre antes del printwriter
                mime_type = MimeTypesUtil.getContentType(archivo);
                charset = "";
                if (archivo.getName().toLowerCase().endsWith(".html")
                        || archivo.getName().toLowerCase().endsWith(".htm")) {
                    mime_type = "text/html";
                    if (isISO(FileUtils.readFileToString(archivo))) {
                        charset = "ISO-8859-1";
                    }
                }
                if (archivo.getName().toLowerCase().endsWith(".swf")) {
                    mime_type = "application/x-shockwave-flash";
                }
                if (archivo.getName().toLowerCase().endsWith(".mp4")) {
                    mime_type = "video/mp4";
                }
                if (archivo.getName().toLowerCase().endsWith(".flv")) {
                    mime_type = "video/x-flv";
                }
                response.setContentType(mime_type);
                if (Validator.isNotNull(charset)) {
                    response.setCharacterEncoding(charset);

                }
                response.addHeader("Content-Type",
                        mime_type + (Validator.isNotNull(charset) ? "; " + charset : ""));
                /*if (archivo.getName().toLowerCase().endsWith(".swf")
                      || archivo.getName().toLowerCase().endsWith(".flv")) {
                   response.addHeader("Content-Length",
                String.valueOf(archivo.length()));
                }
                */
                if (archivo.getName().toLowerCase().endsWith("imsmanifest.xml")) {
                    FileInputStream fis = new FileInputStream(patharchivo);

                    String sco = ParamUtil.get(request, "scoshow", "");
                    Document manifest = SAXReaderUtil.read(fis);
                    if (sco.length() > 0) {

                        Element organizatEl = manifest.getRootElement().element("organizations")
                                .element("organization");
                        Element selectedItem = selectItem(organizatEl, sco);
                        if (selectedItem != null) {
                            selectedItem.detach();
                            java.util.List<Element> items = organizatEl.elements("item");
                            for (Element item : items) {

                                organizatEl.remove(item);
                            }
                            organizatEl.add(selectedItem);
                        }
                    }
                    //clean unused resources.
                    Element resources = manifest.getRootElement().element("resources");
                    java.util.List<Element> theResources = resources.elements("resource");
                    Element organizatEl = manifest.getRootElement().element("organizations")
                            .element("organization");
                    java.util.List<String> identifiers = getIdentifierRefs(organizatEl);
                    for (Element resource : theResources) {
                        String identifier = resource.attributeValue("identifier");
                        if (!identifiers.contains(identifier)) {
                            resources.remove(resource);
                        }
                    }
                    response.getWriter().print(manifest.asXML());
                    fis.close();
                    return;

                }

                if (mime_type.startsWith("text") || mime_type.endsWith("javascript")
                        || mime_type.equals("application/xml")) {

                    java.io.OutputStream out = response.getOutputStream();
                    FileInputStream fis = new FileInputStream(patharchivo);

                    byte[] buffer = new byte[512];
                    int i = 0;

                    while (fis.available() > 0) {
                        i = fis.read(buffer);
                        if (i == 512)
                            out.write(buffer);
                        else
                            out.write(buffer, 0, i);

                    }

                    fis.close();
                    out.flush();
                    out.close();
                    return;
                }
                //If not manifest
                String fileName = archivo.getName();
                long length = archivo.length();
                long lastModified = archivo.lastModified();
                String eTag = fileName + "_" + length + "_" + lastModified;
                long expires = System.currentTimeMillis() + DEFAULT_EXPIRE_TIME;
                String ifNoneMatch = request.getHeader("If-None-Match");
                if (ifNoneMatch != null && matches(ifNoneMatch, eTag)) {
                    response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
                    response.setHeader("ETag", eTag); // Required in 304.
                    response.setDateHeader("Expires", expires); // Postpone cache with 1 week.
                    return;
                }
                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;
                }

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

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

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

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

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

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

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

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

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

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

                            // Add range.
                            ranges.add(new Range(start, end, length));
                        }
                    }
                }
                boolean acceptsGzip = false;
                String disposition = "inline";

                if (mime_type.startsWith("text")) {
                    //String acceptEncoding = request.getHeader("Accept-Encoding");
                    // acceptsGzip = acceptEncoding != null && accepts(acceptEncoding, "gzip");
                    // mime_type += ";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 (!mime_type.startsWith("image")) {
                    String accept = request.getHeader("Accept");
                    disposition = accept != null && accepts(accept, mime_type) ? "inline" : "attachment";
                }

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

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

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

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

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

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

                        if (content) {

                            // Content length is not directly predictable in case of GZIP.
                            // So only add it if there is no means of GZIP, else browser will hang.
                            response.setHeader("Content-Length", String.valueOf(r.length));

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

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

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

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

                    } else {

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

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

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

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

                            // End with multipart boundary.
                            sos.println();
                            sos.println("--" + MULTIPART_BOUNDARY + "--");
                        }
                    }
                } finally {
                    // Gently close streams.
                    close(output);
                    close(input);
                }
            } else {
                //java.io.OutputStream out = response.getOutputStream();
                response.sendError(404);
                //out.write(uri.getBytes());
            }
        } else {
            response.sendError(401);
        }
    } catch (Exception e) {
        System.out.println("Error en el processRequest() de ServidorArchivos: " + e.getMessage());
    }
}

From source file:org.alfresco.module.vti.handler.alfresco.AlfrescoMethodHandler.java

/**
 * @see org.alfresco.module.vti.handler.MethodHandler#putResource(HttpServletRequest, HttpServletResponse)
 *///from   w  w w  .j  a va  2s.com
public void putResource(HttpServletRequest request, HttpServletResponse response) {
    // Office 2008/2011 for Mac specific header
    final String lockTimeOut = request.getHeader(DAV_EXT_LOCK_TIMEOUT);

    if (request.getContentLength() == 0 && lockTimeOut == null) {
        return;
    }

    String decodedUrl = URLDecoder.decode(request.getRequestURI());
    if (decodedUrl.length() > getPathHelper().getAlfrescoContext().length()) {
        decodedUrl = decodedUrl.substring(getPathHelper().getAlfrescoContext().length() + 1);
    }

    FileInfo resourceFileInfo = getPathHelper().resolvePathFileInfo(decodedUrl);
    NodeRef resourceNodeRef = null;

    if (resourceFileInfo != null) {
        resourceNodeRef = resourceFileInfo.getNodeRef();
    }

    if (logger.isDebugEnabled()) {
        logger.debug("The request lock timeout from response is " + lockTimeOut);
        logger.debug("The resource nodeRef is " + resourceNodeRef);
    }

    // Does the file already exist (false), or has it been created by this request? 
    boolean newlyCreated = false;

    // Office 2008/2011 for Mac
    if (resourceNodeRef == null && lockTimeOut != null) {
        try {
            final Pair<String, String> parentChild = VtiPathHelper.splitPathParentChild(decodedUrl);
            final FileInfo parent = getPathHelper().resolvePathFileInfo(parentChild.getFirst());

            RetryingTransactionCallback<NodeRef> cb = new RetryingTransactionCallback<NodeRef>() {
                @Override
                public NodeRef execute() throws Throwable {
                    NodeRef result = getFileFolderService()
                            .create(parent.getNodeRef(), parentChild.getSecond(), ContentModel.TYPE_CONTENT)
                            .getNodeRef();

                    int timeout = Integer.parseInt(lockTimeOut.substring(WebDAV.SECOND.length()));
                    getLockService().lock(result, getUserName(), timeout);

                    return result;
                }
            };

            resourceNodeRef = getTransactionService().getRetryingTransactionHelper().doInTransaction(cb);

            if (resourceNodeRef != null) {
                newlyCreated = true;
            }

            if (logger.isDebugEnabled()) {
                logger.debug("Created new node " + resourceNodeRef);
            }

            response.setStatus(HttpServletResponse.SC_CREATED);
            response.setHeader(WebDAV.HEADER_LOCK_TOKEN, WebDAV.makeLockToken(resourceNodeRef, getUserName()));
            response.setHeader(DAV_EXT_LOCK_TIMEOUT, lockTimeOut);
        } catch (AccessDeniedException e) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return;
        }
    }

    // Check we managed to find the node one way or another
    if (resourceNodeRef == null) {
        if (logger.isInfoEnabled()) {
            logger.info("No node found for resource " + decodedUrl);
        }

        // TODO Is this the correct status code to return if they've
        //  tried to query for something that doesn't exist?
        // Or should we return something else, or even create it?
        response.setStatus(HttpServletResponse.SC_NOT_FOUND);
        return;
    }

    // Get the working copy of it
    final NodeRef workingCopyNodeRef = getCheckOutCheckInService().getWorkingCopy(resourceNodeRef);

    // ALF-15984
    if (!expectedETagForNode(request, resourceNodeRef)) {
        response.setStatus(HttpServletResponse.SC_PRECONDITION_FAILED);
        return;
    }

    // updates changes on the server

    final BufferedHttpServletRequest bufferedRequest = new BufferedHttpServletRequest(request, streamFactory);
    final NodeRef finalResourceNodeRef = resourceNodeRef;
    final String finalDecodedUrl = decodedUrl;
    final boolean finalNewlyCreated = newlyCreated;
    final String siteId = davHelper.determineSiteId(getPathHelper().getRootNodeRef(), finalDecodedUrl);
    RetryingTransactionCallback<Void> work = new RetryingTransactionCallback<Void>() {
        @SuppressWarnings("deprecation")
        @Override
        public Void execute() throws Throwable {
            ContentWriter writer;
            boolean newlyCreated = finalNewlyCreated;
            FileFolderService fileFolderService = getFileFolderService();
            if (workingCopyNodeRef != null) {
                if (logger.isDebugEnabled()) {
                    logger.debug("Writing to the workung copy " + workingCopyNodeRef);
                }
                if (fileFolderService.isHidden(workingCopyNodeRef)) {
                    fileFolderService.setHidden(workingCopyNodeRef, false);
                }

                // working copy writer
                writer = getContentService().getWriter(workingCopyNodeRef, ContentModel.PROP_CONTENT, true);
            } else {
                // ALF-17662, hidden node is the same as non-existed node for SPP
                if (fileFolderService.isHidden(finalResourceNodeRef)) {
                    // make it visible for client
                    fileFolderService.setHidden(finalResourceNodeRef, false);
                }
                if (logger.isDebugEnabled()) {
                    logger.debug("Writing to the node " + finalResourceNodeRef);
                }
                // original document writer
                writer = getContentService().getWriter(finalResourceNodeRef, ContentModel.PROP_CONTENT, true);

            }

            String documentName = getNodeService().getProperty(finalResourceNodeRef, ContentModel.PROP_NAME)
                    .toString();
            String mimetype = getMimetypeService().guessMimetype(documentName);
            writer.setMimetype(mimetype);
            writer.putContent(bufferedRequest.getInputStream());

            // If needed, mark the node as having now had its content supplied
            if (getNodeService().hasAspect(finalResourceNodeRef, ContentModel.ASPECT_WEBDAV_NO_CONTENT)) {
                // CLOUD-2209: newly created documents not shown in activity feed.
                newlyCreated = true;
                getNodeService().removeAspect(finalResourceNodeRef, ContentModel.ASPECT_WEBDAV_NO_CONTENT);
            }

            // If we actually have content, it's time to add the versionable aspect and save the current version
            ContentData contentData = writer.getContentData();
            if (workingCopyNodeRef == null
                    && !getNodeService().hasAspect(finalResourceNodeRef, ContentModel.ASPECT_VERSIONABLE)
                    && ContentData.hasContent(contentData) && contentData.getSize() > 0) {
                if (logger.isDebugEnabled()) {
                    logger.debug("Creating a new major version for " + finalResourceNodeRef);
                }
                getVersionService().createVersion(finalResourceNodeRef, Collections
                        .<String, Serializable>singletonMap(VersionModel.PROP_VERSION_TYPE, VersionType.MAJOR));
            }

            if (siteId != null) {
                String tenantDomain = davHelper.determineTenantDomain();
                long fileSize = contentData.getSize();
                reportUploadEvent(finalDecodedUrl, siteId, tenantDomain, newlyCreated, mimetype, fileSize);
            }

            return null;
        }
    };

    try {
        getTransactionService().getRetryingTransactionHelper().doInTransaction(work);
    } catch (Exception e) {
        if (logger.isDebugEnabled()) {
            logger.debug("An exception occurred during writing the content.", e);
        }
        response.setStatus(HttpServletResponse.SC_CONFLICT);
        return;
    } finally {
        if (bufferedRequest != null) {
            bufferedRequest.close();
        }
    }

    // original document properties
    Map<QName, Serializable> props = getNodeService().getProperties(resourceNodeRef);

    if (workingCopyNodeRef != null) {
        String workingCopyOwner = getNodeService()
                .getProperty(workingCopyNodeRef, ContentModel.PROP_WORKING_COPY_OWNER).toString();
        if (workingCopyOwner.equals(getAuthenticationService().getCurrentUserName())) {
            // working copy properties
            props = getNodeService().getProperties(workingCopyNodeRef);
        }
    }
    String guid = resourceNodeRef.getId().toUpperCase();
    Date lastModified = (Date) props.get(ContentModel.PROP_MODIFIED);
    response.setHeader("Repl-uid", VtiUtils.constructRid(guid));
    response.setHeader("ResourceTag", VtiUtils.constructResourceTag(guid, lastModified));
    response.setHeader("Last-Modified", VtiUtils.formatBrowserDate(lastModified));
    response.setHeader("ETag", VtiUtils.constructETag(guid, lastModified));

    ContentReader reader = getContentService().getReader(resourceNodeRef, ContentModel.PROP_CONTENT);
    String mimetype = reader == null ? null : reader.getMimetype();

    if (mimetype != null) {
        response.setContentType(mimetype);
    }
}

From source file:org.sakaiproject.nakamura.proxy.ProxyClientServiceImpl.java

/**
 * Executes a HTTP call using a path in the JCR to point to a template and a map of
 * properties to populate that template with. An example might be a SOAP call.
 *
 * <pre>//from w  w  w.j a va2  s . c  om
 * {http://www.w3.org/2001/12/soap-envelope}Envelope:{
 *  {http://www.w3.org/2001/12/soap-envelope}Body:{
 *   {http://www.example.org/stock}GetStockPriceResponse:{
 *    &gt;body:[       ]
 *    {http://www.example.org/stock}Price:{
 *     &gt;body:[34.5]
 *    }
 *   }
 *   &gt;body:[  ]
 *  }
 *  &gt;body:[   ]
 *  {http://www.w3.org/2001/12/soap-envelope}encodingStyle:[http://www.w3.org/2001/12/soap-encoding]
 * }
 *
 * </pre>
 *
 * @param resource
 *          the resource containing the proxy end point specification.
 * @param headers
 *          a map of headers to set int the request.
 * @param input
 *          a map of parameters for all templates (both url and body)
 * @param requestInputStream
 *          containing the request body (can be null if the call requires no body or the
 *          template will be used to generate the body)
 * @param requestContentLength
 *          if the requestImputStream is specified, the length specifies the lenght of
 *          the body.
 * @param requerstContentType
 *          the content type of the request, if null the node property
 *          sakai:proxy-request-content-type will be used.
 * @throws ProxyClientException
 */
public ProxyResponse executeCall(Node node, Map<String, String> headers, Map<String, Object> input,
        InputStream requestInputStream, long requestContentLength, String requestContentType)
        throws ProxyClientException {
    try {
        bindNode(node);

        if (node != null && node.hasProperty(SAKAI_REQUEST_PROXY_ENDPOINT)) {
            // setup the post request
            String endpointURL = JcrUtils.getMultiValueString(node.getProperty(SAKAI_REQUEST_PROXY_ENDPOINT));
            if (isUnsafeProxyDefinition(node)) {
                try {
                    URL u = new URL(endpointURL);
                    String host = u.getHost();
                    if (host.indexOf('$') >= 0) {
                        throw new ProxyClientException(
                                "Invalid Endpoint template, relies on request to resolve valid URL " + u);
                    }
                } catch (MalformedURLException e) {
                    throw new ProxyClientException(
                            "Invalid Endpoint template, relies on request to resolve valid URL", e);
                }
            }

            // Find all velocity replacement variable(s) in the endpointURL,
            // copy any equivalent keys from the input Map, to a new Map that
            // can be process by Velocity. In the new Map, the Map value field
            // has been changed from RequestParameter[] to String.

            Map<String, String> inputContext = new HashMap<String, String>();

            int startPosition = endpointURL.indexOf("${");
            while (startPosition > -1) {
                int endPosition = endpointURL.indexOf("}", startPosition);
                if (endPosition > -1) {
                    String key = endpointURL.substring(startPosition + 2, endPosition);
                    Object value = input.get(key);
                    if (value instanceof RequestParameter[]) {
                        // now change input value object from RequestParameter[] to String
                        // and add to inputContext Map.
                        RequestParameter[] requestParameters = (RequestParameter[]) value;
                        inputContext.put(key, requestParameters[0].getString());
                    } else {
                        // KERN-1346 regression; see KERN-1409
                        inputContext.put(key, String.valueOf(value));
                    }
                    // look for the next velocity replacement variable
                    startPosition = endpointURL.indexOf("${", endPosition);
                } else {
                    break;
                }
            }

            VelocityContext context = new VelocityContext(inputContext);

            // add in the config properties from the bundle overwriting everythign else.
            context.put("config", configProperties);

            endpointURL = processUrlTemplate(endpointURL, context);

            ProxyMethod proxyMethod = ProxyMethod.GET;
            if (node.hasProperty(SAKAI_REQUEST_PROXY_METHOD)) {
                try {
                    proxyMethod = ProxyMethod.valueOf(node.getProperty(SAKAI_REQUEST_PROXY_METHOD).getString());
                } catch (Exception e) {
                    logger.debug("The Proxy request specified by  " + node + " failed, cause follows:", e);
                }
            }
            HttpMethod method = null;
            switch (proxyMethod) {
            case GET:
                if (node.hasProperty(SAKAI_LIMIT_GET_SIZE)) {
                    long maxSize = node.getProperty(SAKAI_LIMIT_GET_SIZE).getLong();
                    method = new HeadMethod(endpointURL);
                    HttpMethodParams params = new HttpMethodParams(method.getParams());
                    // make certain we reject the body of a head
                    params.setBooleanParameter("http.protocol.reject-head-body", true);
                    method.setParams(params);
                    method.setFollowRedirects(true);
                    populateMethod(method, node, headers);
                    int result = httpClient.executeMethod(method);
                    if (externalAuthenticatingProxy && result == 407) {
                        method.releaseConnection();
                        method.setDoAuthentication(true);
                        result = httpClient.executeMethod(method);
                    }
                    if (result == 200) {
                        // Check if the content-length is smaller than the maximum (if any).
                        Header contentLengthHeader = method.getResponseHeader("Content-Length");
                        if (contentLengthHeader != null) {
                            long length = Long.parseLong(contentLengthHeader.getValue());
                            if (length > maxSize) {
                                return new ProxyResponseImpl(HttpServletResponse.SC_PRECONDITION_FAILED,
                                        "Response too large", method);
                            }
                        }
                    } else {
                        return new ProxyResponseImpl(result, method);
                    }
                }
                method = new GetMethod(endpointURL);
                // redirects work automatically for get, options and head, but not for put and
                // post
                method.setFollowRedirects(true);
                break;
            case HEAD:
                method = new HeadMethod(endpointURL);
                HttpMethodParams params = new HttpMethodParams(method.getParams());
                // make certain we reject the body of a head
                params.setBooleanParameter("http.protocol.reject-head-body", true);
                method.setParams(params);
                // redirects work automatically for get, options and head, but not for put and
                // post
                method.setFollowRedirects(true);
                break;
            case OPTIONS:
                method = new OptionsMethod(endpointURL);
                // redirects work automatically for get, options and head, but not for put and
                // post
                method.setFollowRedirects(true);
                break;
            case POST:
                method = new PostMethod(endpointURL);
                break;
            case PUT:
                method = new PutMethod(endpointURL);
                break;
            default:
                method = new GetMethod(endpointURL);
                // redirects work automatically for get, options and head, but not for put and
                // post
                method.setFollowRedirects(true);

            }

            populateMethod(method, node, headers);

            if (requestInputStream == null && !node.hasProperty(SAKAI_PROXY_REQUEST_TEMPLATE)) {
                if (method instanceof PostMethod) {
                    PostMethod postMethod = (PostMethod) method;
                    ArrayList<Part> parts = new ArrayList<Part>();
                    for (Entry<String, Object> param : input.entrySet()) {
                        String key = param.getKey();
                        Object value = param.getValue();
                        if (value instanceof RequestParameter[]) {
                            for (RequestParameter val : (RequestParameter[]) param.getValue()) {
                                Part part = null;
                                if (val.isFormField()) {
                                    part = new StringPart(param.getKey(), val.getString());
                                } else {
                                    ByteArrayPartSource source = new ByteArrayPartSource(key, val.get());
                                    part = new FilePart(key, source);
                                }
                                parts.add(part);
                            }
                        } else {
                            parts.add(new StringPart(key, value.toString()));
                        }
                        Part[] partsArray = parts.toArray(new Part[parts.size()]);
                        postMethod.setRequestEntity(new MultipartRequestEntity(partsArray, method.getParams()));
                    }
                }
            } else {

                if (method instanceof EntityEnclosingMethod) {
                    String contentType = requestContentType;
                    if (contentType == null && node.hasProperty(SAKAI_REQUEST_CONTENT_TYPE)) {
                        contentType = node.getProperty(SAKAI_REQUEST_CONTENT_TYPE).getString();

                    }
                    if (contentType == null) {
                        contentType = APPLICATION_OCTET_STREAM;
                    }
                    EntityEnclosingMethod eemethod = (EntityEnclosingMethod) method;
                    if (requestInputStream != null) {
                        eemethod.setRequestEntity(new InputStreamRequestEntity(requestInputStream,
                                requestContentLength, contentType));
                    } else {
                        // build the request
                        Template template = velocityEngine.getTemplate(node.getPath());
                        StringWriter body = new StringWriter();
                        template.merge(context, body);
                        byte[] soapBodyContent = body.toString().getBytes("UTF-8");
                        eemethod.setRequestEntity(new ByteArrayRequestEntity(soapBodyContent, contentType));

                    }
                }
            }

            int result = httpClient.executeMethod(method);
            if (externalAuthenticatingProxy && result == 407) {
                method.releaseConnection();
                method.setDoAuthentication(true);
                result = httpClient.executeMethod(method);
            }
            if (result == 302 && method instanceof EntityEnclosingMethod) {
                // handle redirects on post and put
                String url = method.getResponseHeader("Location").getValue();
                method = new GetMethod(url);
                method.setFollowRedirects(true);
                method.setDoAuthentication(false);
                result = httpClient.executeMethod(method);
                if (externalAuthenticatingProxy && result == 407) {
                    method.releaseConnection();
                    method.setDoAuthentication(true);
                    result = httpClient.executeMethod(method);
                }
            }

            return new ProxyResponseImpl(result, method);
        }

    } catch (ProxyClientException e) {
        throw e;
    } catch (Exception e) {
        throw new ProxyClientException("The Proxy request specified by  " + node + " failed, cause follows:",
                e);
    } finally {
        unbindNode();
    }
    throw new ProxyClientException(
            "The Proxy request specified by " + node + " does not contain a valid endpoint specification ");
}

From source file:org.apache.sling.launchpad.webapp.integrationtest.servlets.post.PostServletCopyTest.java

public void testCopyNodeMultipleSourceReplace() throws Exception {
    final String testPath = TEST_BASE_PATH + "/cpmult/" + System.currentTimeMillis();
    final String testRoot = testClient.createNode(HTTP_BASE_URL + testPath, null);

    // create multiple source nodes
    Map<String, String> props = new HashMap<String, String>();
    props.put("text", "Hello");
    testClient.createNode(HTTP_BASE_URL + testPath + "/src1", props);
    testClient.createNode(HTTP_BASE_URL + testPath + "/src2", props);

    // copy the src? nodes
    List<NameValuePair> nvPairs = new ArrayList<NameValuePair>();
    nvPairs.add(new NameValuePair(SlingPostConstants.RP_OPERATION, SlingPostConstants.OPERATION_COPY));
    nvPairs.add(new NameValuePair(SlingPostConstants.RP_DEST, testPath + "/dest/"));
    nvPairs.add(new NameValuePair(SlingPostConstants.RP_APPLY_TO, testPath + "/src1"));
    nvPairs.add(new NameValuePair(SlingPostConstants.RP_APPLY_TO, testPath + "/src2"));
    assertPostStatus(testRoot, HttpServletResponse.SC_PRECONDITION_FAILED, nvPairs,
            "Expecting Copy Failure: dest parent does not exist");

    // create destination parent
    testClient.createNode(HTTP_BASE_URL + testPath + "/dest", null);

    // now dest exists, so we expect success
    assertPostStatus(testRoot, HttpServletResponse.SC_OK, nvPairs, "Expecting Copy Success");

    // assert partial existence of the src?/text properties
    assertHttpStatus(HTTP_BASE_URL + testPath + "/dest/src1/text", HttpServletResponse.SC_OK);
    assertHttpStatus(HTTP_BASE_URL + testPath + "/dest/src2/text", HttpServletResponse.SC_OK);
    assertHttpStatus(HTTP_BASE_URL + testPath + "/dest/src3/text", HttpServletResponse.SC_NOT_FOUND);
    assertHttpStatus(HTTP_BASE_URL + testPath + "/dest/src4/text", HttpServletResponse.SC_NOT_FOUND);

    // assert content test
    String content = getContent(HTTP_BASE_URL + testPath + "/dest/src1.json", CONTENT_TYPE_JSON);
    JSONObject json = new JSONObject(content);
    assertEquals("Hello", json.get("text"));

    // modify src1 content
    nvPairs.clear();//w ww.  j a  v  a  2s .c o m
    nvPairs.add(new NameValuePair("text", "Modified Hello"));
    assertPostStatus(HTTP_BASE_URL + testPath + "/src1", HttpServletResponse.SC_OK, nvPairs,
            "Expect Content Update Success");

    // copy the src? nodes
    nvPairs.clear();
    nvPairs.add(new NameValuePair(SlingPostConstants.RP_OPERATION, SlingPostConstants.OPERATION_COPY));
    nvPairs.add(new NameValuePair(SlingPostConstants.RP_DEST, testPath + "/dest/"));
    nvPairs.add(new NameValuePair(SlingPostConstants.RP_APPLY_TO, testPath + "/src1"));
    nvPairs.add(new NameValuePair(SlingPostConstants.RP_APPLY_TO, testPath + "/src2"));
    assertPostStatus(testRoot, HttpServletResponse.SC_OK, nvPairs, "Expecting Copy Success");

    // assert content test
    String content2 = getContent(HTTP_BASE_URL + testPath + "/dest/src1.json", CONTENT_TYPE_JSON);
    JSONObject json2 = new JSONObject(content2);
    assertEquals("Modified Hello", json2.get("text"));

    // clean up
    testClient.delete(testRoot);
}

From source file:com.github.zhanhb.ckfinder.download.PathPartial.java

/**
 * Check if the if-none-match condition is satisfied.
 *
 * @param request The servlet request we are processing
 * @param etag ETag of the entity//  w ww  . j  a  v a  2 s.  c  om
 */
private void checkIfNoneMatch(HttpServletRequest request, String etag) {
    String headerValue = request.getHeader(HttpHeaders.IF_NONE_MATCH);
    if (headerValue != null && (headerValue.equals("*") || anyMatches(headerValue, etag))) {
        // For GET and HEAD, we should respond with
        // 304 Not Modified.
        // For every other method, 412 Precondition Failed is sent
        // back.
        String method = request.getMethod();
        if ("GET".equals(method) || "HEAD".equals(method)) {
            throw new UncheckException(HttpServletResponse.SC_NOT_MODIFIED);
        } else {
            throw new UncheckException(HttpServletResponse.SC_PRECONDITION_FAILED);
        }
    }
}

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

/**
 * Process the actual request.//from w ww.  j av  a2 s  .co m
 *
 * @param request The request to be processed.
 * @param response The response to be created.
 * @param content Whether the request body should be written (GET) or not
 * (HEAD).
 * @throws IOException If something fails at I/O level.
 */
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:org.apache.sling.launchpad.webapp.integrationtest.servlets.post.PostServletMoveTest.java

public void testMoveNodeMultipleSourceReplace() throws Exception {
    final String testPath = TEST_BASE_PATH + "/mvmult/" + System.currentTimeMillis();
    final String testRoot = testClient.createNode(HTTP_BASE_URL + testPath, null);

    // create multiple source nodes
    Map<String, String> props = new HashMap<String, String>();
    props.put("text", "Hello");
    testClient.createNode(HTTP_BASE_URL + testPath + "/src1", props);
    testClient.createNode(HTTP_BASE_URL + testPath + "/src2", props);

    // move the src? nodes
    List<NameValuePair> nvPairs = new ArrayList<NameValuePair>();
    nvPairs.add(new NameValuePair(SlingPostConstants.RP_OPERATION, SlingPostConstants.OPERATION_MOVE));
    nvPairs.add(new NameValuePair(SlingPostConstants.RP_DEST, testPath + "/dest/"));
    nvPairs.add(new NameValuePair(SlingPostConstants.RP_APPLY_TO, testPath + "/src1"));
    nvPairs.add(new NameValuePair(SlingPostConstants.RP_APPLY_TO, testPath + "/src2"));
    assertPostStatus(testRoot, HttpServletResponse.SC_PRECONDITION_FAILED, nvPairs,
            "Expecting Move Failure: dest parent does not exist");

    // create destination parent
    testClient.createNode(HTTP_BASE_URL + testPath + "/dest", null);

    // now dest exists, so we expect success
    assertPostStatus(testRoot, HttpServletResponse.SC_OK, nvPairs, "Expecting Move Success");

    // assert partial existence of the src?/text properties
    assertHttpStatus(HTTP_BASE_URL + testPath + "/dest/src1/text", HttpServletResponse.SC_OK);
    assertHttpStatus(HTTP_BASE_URL + testPath + "/dest/src2/text", HttpServletResponse.SC_OK);
    assertHttpStatus(HTTP_BASE_URL + testPath + "/dest/src3/text", HttpServletResponse.SC_NOT_FOUND);
    assertHttpStatus(HTTP_BASE_URL + testPath + "/dest/src4/text", HttpServletResponse.SC_NOT_FOUND);

    // assert content test
    String content = getContent(HTTP_BASE_URL + testPath + "/dest/src1.json", CONTENT_TYPE_JSON);
    JSONObject json = new JSONObject(content);
    assertEquals("Hello", json.get("text"));

    // modify src1 content
    nvPairs.clear();/*  w w  w. j a  va  2  s.  c  o m*/
    nvPairs.add(new NameValuePair("text", "Modified Hello"));
    assertPostStatus(HTTP_BASE_URL + testPath + "/src1", HttpServletResponse.SC_CREATED, nvPairs,
            "Expect Content Create Success");

    // move the src? nodes
    nvPairs.clear();
    nvPairs.add(new NameValuePair(SlingPostConstants.RP_OPERATION, SlingPostConstants.OPERATION_MOVE));
    nvPairs.add(new NameValuePair(SlingPostConstants.RP_DEST, testPath + "/dest/"));
    nvPairs.add(new NameValuePair(SlingPostConstants.RP_APPLY_TO, testPath + "/src1"));
    nvPairs.add(new NameValuePair(SlingPostConstants.RP_APPLY_TO, testPath + "/src2"));
    assertPostStatus(testRoot, HttpServletResponse.SC_OK, nvPairs, "Expecting Move Success");

    // assert content test
    String content2 = getContent(HTTP_BASE_URL + testPath + "/dest/src1.json", CONTENT_TYPE_JSON);
    JSONObject json2 = new JSONObject(content2);
    assertEquals("Modified Hello", json2.get("text"));

    // clean up
    testClient.delete(testRoot);
}