001/* 002 * (C) Copyright 2006-20012 Nuxeo SAS (http://nuxeo.com/) and contributors. 003 * 004 * All rights reserved. This program and the accompanying materials 005 * are made available under the terms of the GNU Lesser General Public License 006 * (LGPL) version 2.1 which accompanies this distribution, and is available at 007 * http://www.gnu.org/licenses/lgpl.html 008 * 009 * This library is distributed in the hope that it will be useful, 010 * but WITHOUT ANY WARRANTY; without even the implied warranty of 011 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 012 * Lesser General Public License for more details. 013 * 014 * Contributors: 015 * Nuxeo - initial API and implementation 016 * 017 */ 018 019package org.nuxeo.template.samples.importer; 020 021import java.io.BufferedInputStream; 022import java.io.File; 023import java.io.FileInputStream; 024import java.io.IOException; 025 026import org.dom4j.Document; 027import org.dom4j.DocumentException; 028import org.dom4j.io.SAXReader; 029import org.nuxeo.common.utils.Path; 030import org.nuxeo.ecm.core.api.Blobs; 031import org.nuxeo.ecm.core.io.ExportConstants; 032import org.nuxeo.ecm.core.io.ExportedDocument; 033import org.nuxeo.ecm.core.io.impl.AbstractDocumentReader; 034import org.nuxeo.ecm.core.io.impl.ExportedDocumentImpl; 035 036/** 037 * CoreIO reader used to read a exploded XML archive. 038 * <p> 039 * This format is used here to make changes in the models easier 040 * 041 * @author <a href="mailto:tdelprat@nuxeo.com">Tiry</a> 042 */ 043public class XMLModelReader extends AbstractDocumentReader { 044 045 protected File source; 046 047 protected boolean done; 048 049 protected String modelName; 050 051 public XMLModelReader(File source, String modelName) { 052 this.source = source; 053 this.done = false; 054 this.modelName = modelName; 055 } 056 057 @Override 058 public void close() { 059 source = null; 060 } 061 062 @Override 063 public ExportedDocument read() throws IOException { 064 if (done) { 065 return null; 066 } 067 ExportedDocument xdoc = new ExportedDocumentImpl(); 068 for (File file : source.listFiles()) { 069 if (file.isFile()) { 070 String name = file.getName(); 071 if (ExportConstants.DOCUMENT_FILE.equals(name)) { 072 Document doc = loadXML(file); 073 xdoc.setDocument(doc); 074 xdoc.setPath(new Path(modelName)); 075 } else { // presume a blob 076 xdoc.putBlob(file.getName(), Blobs.createBlob(file)); 077 } 078 } 079 } 080 done = true; 081 return xdoc; 082 } 083 084 private static Document loadXML(File file) throws IOException { 085 BufferedInputStream in = null; 086 try { 087 in = new BufferedInputStream(new FileInputStream(file)); 088 return new SAXReader().read(in); 089 } catch (DocumentException e) { 090 IOException ioe = new IOException("Failed to read file document " + file + ": " + e.getMessage()); 091 ioe.setStackTrace(e.getStackTrace()); 092 throw ioe; 093 } finally { 094 if (in != null) { 095 in.close(); 096 } 097 } 098 } 099 100}