Example usage for javax.servlet.http HttpServletResponse SC_REQUEST_ENTITY_TOO_LARGE

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

Introduction

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

Prototype

int SC_REQUEST_ENTITY_TOO_LARGE

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

Click Source Link

Document

Status code (413) indicating that the server is refusing to process the request because the request entity is larger than the server is willing or able to process.

Usage

From source file:org.gss_project.gss.server.rest.FilesHandler.java

/**
 * A method for handling multipart POST requests for uploading
 * files from browser-based JavaScript clients.
 *
 * @param request the HTTP request/*  www.  ja v  a2  s  . com*/
 * @param response the HTTP response
 * @param path the resource path
 * @throws IOException in case an error occurs writing to the
 *       response stream
 */
private void handleMultipart(HttpServletRequest request, HttpServletResponse response, String path)
        throws IOException {
    if (logger.isDebugEnabled())
        logger.debug("Multipart POST for resource: " + path);

    User owner = getOwner(request);
    boolean exists = true;
    Object resource = null;
    FileHeader file = null;
    try {
        resource = getService().getResourceAtPath(owner.getId(), path, false);
    } catch (ObjectNotFoundException e) {
        exists = false;
    } catch (RpcException e) {
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, path);
        return;
    }

    if (exists)
        if (resource instanceof FileHeader) {
            file = (FileHeader) resource;
            if (file.isDeleted()) {
                response.sendError(HttpServletResponse.SC_CONFLICT, file.getName() + " is in the trash");
                return;
            }
        } else {
            response.sendError(HttpServletResponse.SC_CONFLICT, path + " is a folder");
            return;
        }

    Object parent;
    String parentPath = null;
    try {
        parentPath = getParentPath(path);
        parent = getService().getResourceAtPath(owner.getId(), parentPath, true);
    } catch (ObjectNotFoundException e) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND, parentPath);
        return;
    } catch (RpcException e) {
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, path);
        return;
    }
    if (!(parent instanceof Folder)) {
        response.sendError(HttpServletResponse.SC_CONFLICT);
        return;
    }
    final Folder folderLocal = (Folder) parent;
    final String fileName = getLastElement(path);

    if (!isValidResourceName(fileName)) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST);
        return;
    }

    FileItemIterator iter;
    File uploadedFile = null;
    try {
        // Create a new file upload handler.
        ServletFileUpload upload = new ServletFileUpload();
        StatusProgressListener progressListener = new StatusProgressListener(getService());
        upload.setProgressListener(progressListener);
        iter = upload.getItemIterator(request);
        String dateParam = null;
        String auth = null;
        while (iter.hasNext()) {
            FileItemStream item = iter.next();
            String name = item.getFieldName();
            InputStream stream = item.openStream();
            if (item.isFormField()) {
                final String value = Streams.asString(stream);
                if (name.equals(DATE_PARAMETER))
                    dateParam = value;
                else if (name.equals(AUTHORIZATION_PARAMETER))
                    auth = value;

                if (logger.isDebugEnabled())
                    logger.debug(name + ":" + value);
            } else {
                // Fetch the timestamp used to guard against replay attacks.
                if (dateParam == null) {
                    response.sendError(HttpServletResponse.SC_FORBIDDEN, "No Date parameter");
                    return;
                }

                long timestamp;
                try {
                    timestamp = DateUtil.parseDate(dateParam).getTime();
                } catch (DateParseException e) {
                    response.sendError(HttpServletResponse.SC_FORBIDDEN, e.getMessage());
                    return;
                }

                // Fetch the Authorization parameter and find the user specified in it.
                if (auth == null) {
                    response.sendError(HttpServletResponse.SC_FORBIDDEN, "No Authorization parameter");
                    return;
                }
                String[] authParts = auth.split(" ");
                if (authParts.length != 2) {
                    response.sendError(HttpServletResponse.SC_FORBIDDEN);
                    return;
                }
                String username = authParts[0];
                String signature = authParts[1];
                User user = null;
                try {
                    user = getService().findUser(username);
                } catch (RpcException e) {
                    response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, path);
                    return;
                }
                if (user == null) {
                    response.sendError(HttpServletResponse.SC_FORBIDDEN);
                    return;
                }
                request.setAttribute(USER_ATTRIBUTE, user);

                // Remove the servlet path from the request URI.
                String p = request.getRequestURI();
                String servletPath = request.getContextPath() + request.getServletPath();
                p = p.substring(servletPath.length());
                // Validate the signature in the Authorization parameter.
                String data = request.getMethod() + dateParam + p;
                if (!isSignatureValid(signature, user, data)) {
                    response.sendError(HttpServletResponse.SC_FORBIDDEN);
                    return;
                }

                progressListener.setUserId(user.getId());
                progressListener.setFilename(fileName);
                final String contentType = item.getContentType();

                try {
                    uploadedFile = getService().uploadFile(stream, user.getId());
                } catch (IOException ex) {
                    throw new GSSIOException(ex, false);
                }
                FileHeader fileLocal = null;
                final File upf = uploadedFile;
                final FileHeader f = file;
                final User u = user;
                if (file == null)
                    fileLocal = new TransactionHelper<FileHeader>().tryExecute(new Callable<FileHeader>() {
                        @Override
                        public FileHeader call() throws Exception {
                            return getService().createFile(u.getId(), folderLocal.getId(), fileName,
                                    contentType, upf.getCanonicalFile().length(), upf.getAbsolutePath());
                        }
                    });
                else
                    fileLocal = new TransactionHelper<FileHeader>().tryExecute(new Callable<FileHeader>() {
                        @Override
                        public FileHeader call() throws Exception {
                            return getService().updateFileContents(u.getId(), f.getId(), contentType,
                                    upf.getCanonicalFile().length(), upf.getAbsolutePath());
                        }
                    });
                updateAccounting(owner, new Date(), fileLocal.getCurrentBody().getFileSize());
                getService().removeFileUploadProgress(user.getId(), fileName);
            }
        }
        // We can't return 204 here since GWT's onSubmitComplete won't fire.
        response.setContentType("text/html");
        response.getWriter().print("<pre></pre>");
    } catch (FileUploadException e) {
        String error = "Error while uploading file";
        logger.error(error, e);
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, error);
    } catch (GSSIOException e) {
        if (uploadedFile != null && uploadedFile.exists())
            uploadedFile.delete();
        String error = "Error while uploading file";
        if (e.logAsError())
            logger.error(error, e);
        else
            logger.debug(error, e);
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, error);
    } catch (DuplicateNameException e) {
        if (uploadedFile != null && uploadedFile.exists())
            uploadedFile.delete();
        String error = "The specified file name already exists in this folder";
        logger.error(error, e);
        response.sendError(HttpServletResponse.SC_CONFLICT, error);

    } catch (InsufficientPermissionsException e) {
        if (uploadedFile != null && uploadedFile.exists())
            uploadedFile.delete();
        String error = "You don't have the necessary permissions";
        logger.error(error, e);
        response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, error);

    } catch (QuotaExceededException e) {
        if (uploadedFile != null && uploadedFile.exists())
            uploadedFile.delete();
        String error = "Not enough free space available";
        if (logger.isDebugEnabled())
            logger.debug(error, e);
        response.sendError(HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE, error);

    } catch (ObjectNotFoundException e) {
        if (uploadedFile != null && uploadedFile.exists())
            uploadedFile.delete();
        String error = "A specified object was not found";
        logger.error(error, e);
        response.sendError(HttpServletResponse.SC_NOT_FOUND, error);
    } catch (RpcException e) {
        if (uploadedFile != null && uploadedFile.exists())
            uploadedFile.delete();
        String error = "An error occurred while communicating with the service";
        logger.error(error, e);
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, error);
    } catch (Exception e) {
        if (uploadedFile != null && uploadedFile.exists())
            uploadedFile.delete();
        String error = "An internal server error occurred";
        logger.error(error, e);
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, error);
    }
}

From source file:org.gss_project.gss.server.rest.FilesHandler.java

/**
 * Move the resource in the specified path to the specified destination.
 *
 * @param req the HTTP request/*www  .j  a v  a  2  s  .  co  m*/
 * @param resp the HTTP response
 * @param path the path of the resource
 * @param moveTo the destination of the move procedure
 * @throws IOException if an input/output error occurs
 */
private void moveResource(HttpServletRequest req, HttpServletResponse resp, String path, String moveTo)
        throws IOException {
    final User user = getUser(req);
    User owner = getOwner(req);
    Object resource = null;
    try {
        resource = getService().getResourceAtPath(owner.getId(), path, true);
    } catch (ObjectNotFoundException e) {
        resp.sendError(HttpServletResponse.SC_NOT_FOUND, path);
        return;
    } catch (RpcException e) {
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, path);
        return;
    }

    String destination = null;
    User destOwner = null;
    boolean exists = true;
    try {
        destination = getDestinationPath(req, encodePath(moveTo));
        destination = URLDecoder.decode(destination, "UTF-8");
        destOwner = getDestinationOwner(req);
        getService().getResourceAtPath(destOwner.getId(), destination, true);
    } catch (ObjectNotFoundException e) {
        exists = false;
    } catch (URISyntaxException e) {
        resp.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getMessage());
        return;
    } catch (RpcException e) {
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, destination);
        return;
    }
    if (exists) {
        resp.sendError(HttpServletResponse.SC_CONFLICT, destination + " already exists");
        return;
    }

    try {
        final User dOwner = destOwner;
        final String dest = destination;
        if (resource instanceof Folder) {
            final Folder folderLocal = (Folder) resource;
            new TransactionHelper<Void>().tryExecute(new Callable<Void>() {
                @Override
                public Void call() throws Exception {
                    getService().moveFolderToPath(user.getId(), dOwner.getId(), folderLocal.getId(), dest);
                    return null;
                }
            });
        } else {
            final FileHeader fileLocal = (FileHeader) resource;
            new TransactionHelper<Void>().tryExecute(new Callable<Void>() {
                @Override
                public Void call() throws Exception {
                    getService().moveFileToPath(user.getId(), dOwner.getId(), fileLocal.getId(), dest);
                    return null;
                }
            });

        }
    } catch (InsufficientPermissionsException e) {
        resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
    } catch (ObjectNotFoundException e) {
        resp.sendError(HttpServletResponse.SC_NOT_FOUND, e.getMessage());
    } catch (RpcException e) {
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, destination);
    } catch (DuplicateNameException e) {
        resp.sendError(HttpServletResponse.SC_CONFLICT, e.getMessage());
    } catch (GSSIOException e) {
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
    } catch (QuotaExceededException e) {
        resp.sendError(HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE, e.getMessage());
    } catch (Exception e) {
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, destination);
    }
}

From source file:org.gss_project.gss.server.rest.FilesHandler.java

/**
 * Copy the resource in the specified path to the specified destination.
 *
 * @param req the HTTP request//from  w  ww . j av  a  2s  .  c o m
 * @param resp the HTTP response
 * @param path the path of the resource
 * @param copyTo the destination of the copy procedure
 * @throws IOException if an input/output error occurs
 */
private void copyResource(HttpServletRequest req, HttpServletResponse resp, String path, String copyTo)
        throws IOException {
    final User user = getUser(req);
    User owner = getOwner(req);
    Object resource = null;
    try {
        resource = getService().getResourceAtPath(owner.getId(), path, true);
    } catch (ObjectNotFoundException e) {
        resp.sendError(HttpServletResponse.SC_NOT_FOUND, path);
        return;
    } catch (RpcException e) {
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, path);
        return;
    }

    String destination = null;
    User destOwner = null;
    boolean exists = true;
    try {
        String destinationEncoded = getDestinationPath(req, encodePath(copyTo));
        destination = URLDecoder.decode(destinationEncoded, "UTF-8");
        destOwner = getDestinationOwner(req);
        getService().getResourceAtPath(destOwner.getId(), destinationEncoded, true);
    } catch (ObjectNotFoundException e) {
        exists = false;
    } catch (URISyntaxException e) {
        resp.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getMessage());
        return;
    } catch (RpcException e) {
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, destination);
        return;
    }
    if (exists) {
        resp.sendError(HttpServletResponse.SC_CONFLICT, destination + " already exists");
        return;
    }

    try {
        final User dOwner = destOwner;
        final String dest = destination;
        if (resource instanceof Folder) {
            final Folder folderLocal = (Folder) resource;
            new TransactionHelper<Void>().tryExecute(new Callable<Void>() {
                @Override
                public Void call() throws Exception {
                    getService().copyFolderStructureToPath(user.getId(), dOwner.getId(), folderLocal.getId(),
                            dest);
                    return null;
                }
            });
        } else {
            final FileHeader fileLocal = (FileHeader) resource;
            new TransactionHelper<Void>().tryExecute(new Callable<Void>() {
                @Override
                public Void call() throws Exception {
                    getService().copyFileToPath(user.getId(), dOwner.getId(), fileLocal.getId(), dest);
                    return null;
                }
            });
        }
    } catch (InsufficientPermissionsException e) {
        resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
    } catch (ObjectNotFoundException e) {
        resp.sendError(HttpServletResponse.SC_NOT_FOUND, e.getMessage());
    } catch (RpcException e) {
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, destination);
    } catch (DuplicateNameException e) {
        resp.sendError(HttpServletResponse.SC_CONFLICT, e.getMessage());
    } catch (GSSIOException e) {
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
    } catch (QuotaExceededException e) {
        resp.sendError(HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE, e.getMessage());
    } catch (Exception e) {
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, destination);
    }
}

From source file:org.sakaiproject.dav.DavServlet.java

/**
 * PROPFIND Method.//from  www  .  j a  v  a 2s  .c om
 */
protected void doPropfind(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {

    String path = getRelativePathSAKAI(req);

    if (path.endsWith("/"))
        path = path.substring(0, path.length() - 1);

    if ((path.toUpperCase().startsWith("/WEB-INF")) || (path.toUpperCase().startsWith("/META-INF"))
            || prohibited(path)) {
        resp.sendError(SakaidavStatus.SC_FORBIDDEN);
        return;
    }

    // Properties which are to be displayed.
    Vector<String> properties = null;
    // Propfind depth
    int depth = INFINITY;
    // Propfind type
    int type = FIND_ALL_PROP;

    String depthStr = req.getHeader("Depth");

    if (depthStr == null) {
        depth = INFINITY;
    } else {
        if (depthStr.equals("0")) {
            depth = 0;
        } else if (depthStr.equals("1")) {
            depth = 1;
        } else if (depthStr.equals("infinity")) {
            depth = INFINITY;
        }
    }

    Node propNode = null;

    DocumentBuilder documentBuilder = getDocumentBuilder();

    // be careful how we get content, as we've had hangs in mod_jk
    // Rather than passing the XML parser a stream on the network
    // input, we read it into a buffer and pass them a stream
    // on the buffer. This is an experiment to see if it fixes
    // the hangs.

    // Note that getContentLength can return -1. As everyone seems
    // to use the content-length header, ignore that case for now
    // It is strongly discouraged by the spec.

    int contentLength = req.getContentLength();

    if (contentLength > MAX_XML_STREAM_LENGTH) {
        resp.sendError(HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE);
        return;
    } else if (contentLength > 0) {

        byte[] byteContent = new byte[contentLength];
        InputStream inputStream = req.getInputStream();

        int lenRead = 0;

        try {
            while (lenRead < contentLength) {
                int read = inputStream.read(byteContent, lenRead, contentLength - lenRead);
                if (read <= 0)
                    break;
                lenRead += read;
            }
        } catch (Exception ignore) {
        }
        // if anything goes wrong, we treat it as find all props

        // Parse the input XML to see what they really want
        if (lenRead > 0)
            try {
                InputStream is = new ByteArrayInputStream(byteContent, 0, lenRead);
                // System.out.println("have bytes");
                Document document = documentBuilder.parse(new InputSource(is));

                // Get the root element of the document
                Element rootElement = document.getDocumentElement();
                NodeList childList = rootElement.getChildNodes();
                // System.out.println("have nodes " + childList.getLength());

                for (int i = 0; i < childList.getLength(); i++) {
                    Node currentNode = childList.item(i);
                    // System.out.println("looking at node " + currentNode.getNodeName());
                    switch (currentNode.getNodeType()) {
                    case Node.TEXT_NODE:
                        break;
                    case Node.ELEMENT_NODE:
                        if (currentNode.getNodeName().endsWith("prop")) {
                            type = FIND_BY_PROPERTY;
                            propNode = currentNode;
                        }
                        if (currentNode.getNodeName().endsWith("propname")) {
                            type = FIND_PROPERTY_NAMES;
                        }
                        if (currentNode.getNodeName().endsWith("allprop")) {
                            type = FIND_ALL_PROP;
                        }
                        break;
                    }
                }
            } catch (SAXParseException se) {
                resp.sendError(HttpServletResponse.SC_BAD_REQUEST);
                return;
            } catch (Exception e) {
                M_log.warn("Exception parsing DAV request", e);
            }
        // again, in case of exception, we'll have the default
        // FIND_ALL_PROP
    }

    // System.out.println("Find type " + type);

    if (type == FIND_BY_PROPERTY) {
        properties = new Vector<String>();
        NodeList childList = propNode.getChildNodes();

        for (int i = 0; i < childList.getLength(); i++) {
            Node currentNode = childList.item(i);
            switch (currentNode.getNodeType()) {
            case Node.TEXT_NODE:
                break;
            case Node.ELEMENT_NODE:
                String nodeName = currentNode.getNodeName();
                String propertyName = null;
                if (nodeName.indexOf(':') != -1) {
                    propertyName = nodeName.substring(nodeName.indexOf(':') + 1);
                } else {
                    propertyName = nodeName;
                }
                // href is a live property which is handled differently
                properties.addElement(propertyName);
                break;
            }
        }

    }

    // Retrieve the resources
    DirContextSAKAI resources = getResourcesSAKAI();

    if (resources == null) {
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        return;
    }

    // Point the resource object at a particular path and catch the error if necessary.

    boolean exists = true;
    try {
        resources.lookup(path);
    } catch (NamingException e) {
        exists = false;
        int slash = path.lastIndexOf('/');
        if (slash != -1) {
            String parentPath = path.substring(0, slash);
            Vector<String> currentLockNullResources = lockNullResources.get(parentPath);
            if (currentLockNullResources != null) {
                Enumeration<String> lockNullResourcesList = currentLockNullResources.elements();
                while (lockNullResourcesList.hasMoreElements()) {
                    String lockNullPath = lockNullResourcesList.nextElement();
                    if (lockNullPath.equals(path)) {
                        resp.setStatus(SakaidavStatus.SC_MULTI_STATUS);
                        resp.setContentType("text/xml; charset=UTF-8");
                        // Create multistatus object
                        XMLWriter generatedXML = new XMLWriter(resp.getWriter());
                        generatedXML.writeXMLHeader();
                        generatedXML.writeElement("D", "multistatus" + generateNamespaceDeclarations(),
                                XMLWriter.OPENING);
                        parseLockNullProperties(req, generatedXML, lockNullPath, type, properties);
                        generatedXML.writeElement("D", "multistatus", XMLWriter.CLOSING);
                        generatedXML.sendData();
                        return;
                    }
                }
            }
        }
    }

    if (!exists) {
        resp.sendError(HttpServletResponse.SC_NOT_FOUND, "/dav" + path);
        return;
    }

    resp.setStatus(SakaidavStatus.SC_MULTI_STATUS);

    resp.setContentType("text/xml; charset=UTF-8");

    // Create multistatus object
    XMLWriter generatedXML = new XMLWriter(resp.getWriter());
    generatedXML.writeXMLHeader();

    generatedXML.writeElement("D", "multistatus" + generateNamespaceDeclarations(), XMLWriter.OPENING);

    if (depth == 0) {
        parseProperties(req, resources, generatedXML, path, type, properties);
    } else {
        // The stack always contains the object of the current level
        Stack<String> stack = new Stack<String>();
        stack.push(path);

        // Stack of the objects one level below
        Stack<String> stackBelow = new Stack<String>();

        while ((!stack.isEmpty()) && (depth >= 0)) {

            String currentPath = (String) stack.pop();

            try {
                // if (M_log.isDebugEnabled()) M_log.debug("Lookup currentPath="+currentPath);
                resources.lookup(currentPath);
            } catch (NamingException e) {
                continue;
            }

            parseProperties(req, resources, generatedXML, currentPath, type, properties);

            if ((resources.isCollection) && (depth > 0)) {

                Iterator<ContentEntity> it = resources.list(currentPath);
                while (it.hasNext()) {
                    Entity mbr = it.next();
                    String resourceName = getResourceNameSAKAI(mbr);

                    String newPath = currentPath;
                    if (!(newPath.endsWith("/")))
                        newPath += "/";
                    newPath += resourceName;
                    if (!(newPath.toLowerCase().indexOf("/protected") >= 0
                            && !contentHostingService.allowAddCollection(newPath)))
                        stackBelow.push(newPath);
                    // if (M_log.isDebugEnabled()) M_log.debug("SAKAI found resource " + newPath);
                }

                // Displaying the lock-null resources present in that
                // collection
                String lockPath = currentPath;
                if (lockPath.endsWith("/"))
                    lockPath = lockPath.substring(0, lockPath.length() - 1);
                Vector<String> currentLockNullResources = lockNullResources.get(lockPath);
                if (currentLockNullResources != null) {
                    Enumeration<String> lockNullResourcesList = currentLockNullResources.elements();
                    while (lockNullResourcesList.hasMoreElements()) {
                        String lockNullPath = (String) lockNullResourcesList.nextElement();

                        parseLockNullProperties(req, generatedXML, lockNullPath, type, properties);
                    }
                }

            }

            if (stack.isEmpty()) {
                depth--;
                stack = stackBelow;

                stackBelow = new Stack<String>();
            }
            // if (M_log.isDebugEnabled()) M_log.debug("SAKAIDAV.propfind() " + generatedXML.toString());
            generatedXML.sendData();
        }
    }

    generatedXML.writeElement("D", "multistatus", XMLWriter.CLOSING);
    // if (M_log.isDebugEnabled()) M_log.debug("SAKAIDAV.propfind() at end:" + generatedXML.toString());
    generatedXML.sendData();

}

From source file:org.gss_project.gss.server.rest.FilesHandler.java

/**
 * @param req/*from   w w  w  . ja v  a2  s . c om*/
 * @param resp
 * @throws IOException
 * @throws FileNotFoundException
 */
void putResource(HttpServletRequest req, HttpServletResponse resp) throws IOException, FileNotFoundException {
    String path = getInnerPath(req, PATH_FILES);
    try {
        path = URLDecoder.decode(path, "UTF-8");
    } catch (IllegalArgumentException e) {
        resp.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getMessage());
        return;
    }
    if (logger.isDebugEnabled())
        logger.debug("Updating resource: " + path);

    final User user = getUser(req);
    User owner = getOwner(req);
    boolean exists = true;
    Object resource = null;
    FileHeader fileLocal = null;
    try {
        resource = getService().getResourceAtPath(owner.getId(), path, false);
    } catch (ObjectNotFoundException e) {
        exists = false;
    } catch (RpcException e) {
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, path);
        return;
    }

    if (exists)
        if (resource instanceof FileHeader)
            fileLocal = (FileHeader) resource;
        else {
            resp.sendError(HttpServletResponse.SC_CONFLICT, path + " is a folder");
            return;
        }
    boolean result = true;

    // Temporary content file used to support partial PUT.
    File contentFile = null;

    Range range = parseContentRange(req, resp);

    InputStream resourceInputStream = null;

    // Append data specified in ranges to existing content for this
    // resource - create a temporary file on the local filesystem to
    // perform this operation.
    // Assume just one range is specified for now
    if (range != null) {
        try {
            contentFile = executePartialPut(req, range, path);
        } catch (RpcException e) {
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, path);
            return;
        } catch (ObjectNotFoundException e) {
            resp.sendError(HttpServletResponse.SC_CONFLICT);
            return;
        } catch (InsufficientPermissionsException e) {
            resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
            return;
        }
        resourceInputStream = new FileInputStream(contentFile);
    } else
        resourceInputStream = req.getInputStream();

    try {
        Folder folderLocal = null;
        Object parent = getService().getResourceAtPath(owner.getId(), getParentPath(path), true);
        if (!(parent instanceof Folder)) {
            resp.sendError(HttpServletResponse.SC_CONFLICT);
            return;
        }
        folderLocal = (Folder) parent;
        final String name = getLastElement(path);
        final String mimeType = context.getMimeType(name);
        File uploadedFile = null;
        try {
            uploadedFile = getService().uploadFile(resourceInputStream, user.getId());
        } catch (IOException ex) {
            throw new GSSIOException(ex, false);
        }
        FileHeader fileTemp = null;
        final File uploadedf = uploadedFile;
        final Folder parentf = folderLocal;
        final FileHeader f = fileLocal;
        if (exists)
            fileTemp = new TransactionHelper<FileHeader>().tryExecute(new Callable<FileHeader>() {
                @Override
                public FileHeader call() throws Exception {
                    return getService().updateFileContents(user.getId(), f.getId(), mimeType,
                            uploadedf.getCanonicalFile().length(), uploadedf.getAbsolutePath());
                }
            });
        else
            fileTemp = new TransactionHelper<FileHeader>().tryExecute(new Callable<FileHeader>() {
                @Override
                public FileHeader call() throws Exception {
                    return getService().createFile(user.getId(), parentf.getId(), name, mimeType,
                            uploadedf.getCanonicalFile().length(), uploadedf.getAbsolutePath());
                }

            });
        updateAccounting(owner, new Date(), fileTemp.getCurrentBody().getFileSize());
        getService().removeFileUploadProgress(user.getId(), fileTemp.getName());
    } catch (ObjectNotFoundException e) {
        result = false;
    } catch (RpcException e) {
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, path);
        return;
    } catch (IOException e) {
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, path);
        return;
    } catch (GSSIOException e) {
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, path);
        return;
    } catch (DuplicateNameException e) {
        resp.sendError(HttpServletResponse.SC_CONFLICT);
        return;
    } catch (InsufficientPermissionsException e) {
        resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
        return;
    } catch (QuotaExceededException e) {
        resp.sendError(HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE, e.getMessage());
        return;
    } catch (Exception e) {
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, path);
        return;
    }

    if (result) {
        if (exists)
            resp.setStatus(HttpServletResponse.SC_NO_CONTENT);
        else
            resp.setStatus(HttpServletResponse.SC_CREATED);
    } else
        resp.sendError(HttpServletResponse.SC_CONFLICT);
}

From source file:org.sakaiproject.dav.DavServlet.java

/**
 * PROPPATCH Method.//from w w w. j a v  a 2  s. c  o m
 */
@SuppressWarnings("deprecation")
protected void doProppatch(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {
    // Check that the resource is not locked
    if (isLocked(req)) {
        resp.sendError(SakaidavStatus.SC_LOCKED);
    }

    // we can't actually do this, but MS requires us to. Say we did.
    // I'm trying to be as close to valid here, so I generate an OK
    // for all the properties they tried to set. This is really hairy because
    // it gets into name spaces. But if we ever try to implement this for real,
    // we'll have to do this. So might as well start now.
    //    During testing I found by mistake that it's actually OK to send
    // an empty multistatus return, so I don't actually  need all of this stuff.
    //    The big problem is that the properties are typically not in the dav namespace
    // we build a hash table of namespaces, with the prefix we're going to use
    // since D: is used for dav, we start with E:, actually D+1

    DocumentBuilder documentBuilder = null;
    try {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(true);
        factory.setFeature("http://xml.org/sax/features/external-general-entities", false);
        factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);

        documentBuilder = factory.newDocumentBuilder();
    } catch (Exception e) {
        resp.sendError(SakaidavStatus.SC_METHOD_FAILURE);
        return;
    }

    int contentLength = req.getContentLength();

    // a list of the properties with the new prefix
    List<String> props = new ArrayList<String>();
    // hash of namespace, prefix
    Hashtable<String, String> spaces = new Hashtable<String, String>();

    // read the xml document
    if (contentLength > MAX_XML_STREAM_LENGTH) {
        resp.sendError(HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE);
        return;
    } else if (contentLength > 0) {

        byte[] byteContent = new byte[contentLength];
        InputStream inputStream = req.getInputStream();

        int lenRead = 0;

        try {
            while (lenRead < contentLength) {
                int read = inputStream.read(byteContent, lenRead, contentLength - lenRead);
                if (read <= 0)
                    break;
                lenRead += read;
            }
        } catch (Exception ignore) {
        }

        // Parse the input XML to see what they really want
        if (lenRead > 0)
            try {
                // if we got here, "is" is the xml document
                InputStream is = new ByteArrayInputStream(byteContent, 0, lenRead);
                Document document = documentBuilder.parse(new InputSource(is));

                // Get the root element of the document
                Element rootElement = document.getDocumentElement();
                // find all the property nodes
                NodeList childList = rootElement.getElementsByTagNameNS("DAV:", "prop");

                int nextChar = 1;

                for (int i = 0; i < childList.getLength(); i++) {

                    // this should be a prop node
                    Node currentNode = childList.item(i);
                    // this should be the actual property
                    NodeList names = currentNode.getChildNodes();
                    // this should be the name
                    for (int j = 0; j < names.getLength(); j++) {
                        String namespace = names.item(j).getNamespaceURI();
                        String prefix = spaces.get(namespace);
                        // see if we know about this namespace. If not add it and
                        // generate a prefix
                        if (prefix == null) {
                            prefix = "" + Character.toChars('D' + nextChar)[0];
                            spaces.put(namespace, prefix);
                        }
                        props.add(prefix + ":" + names.item(j).getLocalName());
                    }
                }
            } catch (Exception ignore) {
            }
    }

    resp.setStatus(SakaidavStatus.SC_MULTI_STATUS);
    resp.setContentType("text/xml; charset=UTF-8");

    Writer writer = resp.getWriter();

    writer.write("<D:multistatus xmlns:D=\"DAV:\"");
    // dump all the name spaces and their prefix
    for (String namespace : spaces.keySet())
        writer.write(" xmlns:" + spaces.get(namespace) + "=\"" + namespace + "\"");
    writer.write("><D:response><D:href>" + javax.servlet.http.HttpUtils.getRequestURL(req) + "</D:href>");
    // now output properties, claiming we did it
    for (String pname : props) {
        writer.write("<D:propstat><D:prop><" + pname
                + "/></D:prop><D:status>HTTP/1.1 201 OK</D:status></D:propstat>");
    }
    writer.write("</D:response></D:multistatus>");
    writer.close();

}

From source file:com.zimbra.client.ZMailbox.java

/**
 * Uploads HTTP post parts to <tt>FileUploadServlet</tt>.
 * @return the attachment id//from w w  w .j a v  a  2 s. c  o  m
 */
public String uploadAttachments(Part[] parts, int msTimeout) throws ServiceException {
    String aid = null;

    URI uri = getUploadURI();
    HttpClient client = getHttpClient(uri);

    // make the post
    PostMethod post = new PostMethod(uri.toString());
    post.getParams().setSoTimeout(msTimeout);

    int statusCode;
    try {
        if (mCsrfToken != null) {
            post.setRequestHeader(Constants.CSRF_TOKEN, mCsrfToken);
        }
        post.setRequestEntity(new MultipartRequestEntity(parts, post.getParams()));
        statusCode = HttpClientUtil.executeMethod(client, post);

        // parse the response
        if (statusCode == HttpServletResponse.SC_OK) {
            String response = post.getResponseBodyAsString();
            aid = getAttachmentId(response);
        } else if (statusCode == HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE) {
            throw ZClientException.UPLOAD_SIZE_LIMIT_EXCEEDED("upload size limit exceeded", null);
        } else {
            throw ZClientException.UPLOAD_FAILED("Attachment post failed, status=" + statusCode, null);
        }
    } catch (IOException e) {
        throw ZClientException.IO_ERROR(e.getMessage(), e);
    } finally {
        post.releaseConnection();
    }
    return aid;
}

From source file:com.zimbra.client.ZMailbox.java

public String uploadContentAsStream(String name, InputStream in, String contentType, long contentLength,
        int msTimeout, boolean limitByFileUploadMaxSize) throws ServiceException {
    String aid = null;// ww w.j a  v  a2 s .  co  m
    if (name != null) {
        contentType += "; name=" + name;
    }

    URI uri = getUploadURI(limitByFileUploadMaxSize);
    HttpClient client = getHttpClient(uri);

    // make the post
    PostMethod post = new PostMethod(uri.toString());
    post.getParams().setSoTimeout(msTimeout);

    int statusCode;
    try {
        post = HttpClientUtil.addInputStreamToHttpMethod(post, in, contentLength, contentType);
        if (mCsrfToken != null) {
            post.addRequestHeader(Constants.CSRF_TOKEN, this.mCsrfToken);
        }
        statusCode = HttpClientUtil.executeMethod(client, post);

        // parse the response
        if (statusCode == HttpServletResponse.SC_OK) {
            String response = post.getResponseBodyAsString();
            aid = getAttachmentId(response);
        } else if (statusCode == HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE) {
            throw ZClientException.UPLOAD_SIZE_LIMIT_EXCEEDED("upload size limit exceeded", null);
        } else {
            throw ZClientException.UPLOAD_FAILED("Attachment post failed, status=" + statusCode, null);
        }
    } catch (IOException e) {
        throw ZClientException.IO_ERROR(e.getMessage(), e);
    } finally {
        post.releaseConnection();
    }
    return aid;
}

From source file:com.zimbra.client.ZMailbox.java

public static String getAttachmentId(String result) throws ZClientException {
    if (result.startsWith(HttpServletResponse.SC_OK + "")) {
        Matcher m = sAttachmentId.matcher(result);
        return m.find() ? m.group(1) : null;
    } else if (result.startsWith(HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE + "")) {
        throw ZClientException.UPLOAD_SIZE_LIMIT_EXCEEDED("upload size limit exceeded", null);
    }/*from  w  ww . j  a va 2  s . c om*/
    throw ZClientException.UPLOAD_FAILED("upload failed, response: " + result, null);
}