001/*
002 * Copyright (c) 2006-2011 Nuxeo SA (http://nuxeo.com/) and others.
003 *
004 * All rights reserved. This program and the accompanying materials
005 * are made available under the terms of the Eclipse Public License v1.0
006 * which accompanies this distribution, and is available at
007 * http://www.eclipse.org/legal/epl-v10.html
008 *
009 * Contributors:
010 *     Nuxeo - initial API and implementation
011 *
012 * $Id: DocumentTreeReader.java 29029 2008-01-14 18:38:14Z ldoguin $
013 */
014
015package org.nuxeo.ecm.core.io.impl.plugins;
016
017import java.io.IOException;
018
019import org.nuxeo.ecm.core.api.CoreSession;
020import org.nuxeo.ecm.core.api.DocumentModel;
021import org.nuxeo.ecm.core.api.DocumentRef;
022import org.nuxeo.ecm.core.api.DocumentTreeIterator;
023import org.nuxeo.ecm.core.io.ExportedDocument;
024import org.nuxeo.ecm.core.io.impl.ExportedDocumentImpl;
025
026/**
027 * @author <a href="mailto:bs@nuxeo.com">Bogdan Stefanescu</a>
028 */
029public class DocumentTreeReader extends DocumentModelReader {
030
031    protected DocumentTreeIterator iterator;
032
033    protected int pathSegmentsToRemove = 0;
034
035    public DocumentTreeReader(CoreSession session, DocumentModel root, boolean excludeRoot) {
036        super(session);
037        iterator = new DocumentTreeIterator(session, root, excludeRoot);
038        pathSegmentsToRemove = root.getPath().segmentCount() - (excludeRoot ? 0 : 1);
039    }
040
041    public DocumentTreeReader(CoreSession session, DocumentRef root) {
042        this(session, session.getDocument(root));
043    }
044
045    public DocumentTreeReader(CoreSession session, DocumentModel root) {
046        this(session, root, false);
047    }
048
049    @Override
050    public void close() {
051        super.close();
052        iterator.reset();
053        iterator = null;
054    }
055
056    @Override
057    public ExportedDocument read() throws IOException {
058        if (iterator.hasNext()) {
059            DocumentModel docModel = iterator.next();
060            if (pathSegmentsToRemove > 0) {
061                // remove unwanted leading segments
062                return new ExportedDocumentImpl(docModel, docModel.getPath().removeFirstSegments(pathSegmentsToRemove),
063                        inlineBlobs);
064            } else {
065                return new ExportedDocumentImpl(docModel, inlineBlobs);
066            }
067        }
068        return null;
069    }
070
071}