/** * * Copyright (c) 2003 University of Mancester. * @author Kevin Garwood (garwood@cs.man.ac.uk) */ package pedro.io; import java.io.File; import java.io.FileOutputStream; import java.io.BufferedOutputStream; import java.util.zip.ZipInputStream; import java.util.zip.ZipEntry; import java.io.FileInputStream; import java.io.PrintWriter; import java.io.IOException; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.ParserConfigurationException; import org.w3c.dom.Document; import org.xml.sax.SAXException; import org.w3c.dom.Node; import org.w3c.dom.Element; import org.w3c.dom.Text; import org.w3c.dom.NodeList; import java.util.ArrayList; import pedro.model.RecordModel; import pedro.model.RecordModelFactory; import pedro.view.NavigationTreeNode; import pedro.view.NavigationTree; import pedro.model.DataFieldModel; import pedro.util.ErrorDialog; import pedro.system.PedroException; import pedro.system.GlobalConstants; /** * @author Kevin Garwood * @date * @version 1.0 */ /* Code RoadMap: Section Constants Section Properties Section Construction Section Accessors Section Mutators Section Validation Section Errors Section Interfaces Section Overload */ public class ExperimentFileReader { // ========================================== // Section Constants // ========================================== private final int BUFFER_SIZE = 2048; // ========================================== // Section Properties // ========================================== private NavigationTreeNode rootNode; private NavigationTree navigationTree; private RecordModelFactory recordModelFactory; private boolean readTemplate; public int count; // ========================================== // Section Construction // ========================================== public ExperimentFileReader() { rootNode = null; recordModelFactory = RecordModelFactory.getRecordModelFactory(); count = 0; } public void setReadTemplate(boolean readTemplate) { this.readTemplate = readTemplate; } public void readFile(File zipFile, NavigationTree navigationTree) throws Exception { File nativeFormatFile = unzipNativeFormatFile(zipFile); parseNativeFormatFile(nativeFormatFile, navigationTree); nativeFormatFile.delete(); } private void parseNativeFormatFile(File file, NavigationTree navigationTree) throws Exception { this.navigationTree = navigationTree; DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); Document document = documentBuilder.parse(file); //the file will either start like: // // //... // //or // //... // //=============================================================================== //Part I: Obtain schema information and compare it to currently loaded data model //=============================================================================== Element topElement = null; String experimentSchemaName = null; if ( readTemplate == true) { //we should be expecting to read a template Element templateElement = PedroSchemaParser.getFirstChildElement(document); if ( templateElement.getTagName().equals("template") == false) { ErrorDialog.show("Template file is not formatted properly"); return; } //end if () experimentSchemaName = templateElement.getAttribute("xsi:schemaLocation"); topElement = PedroSchemaParser.getFirstChildElement(templateElement); if ( topElement == null) { ErrorDialog.show("Template is empty"); return; } //end if () } //end if () else { //file is a regular experiment file topElement = PedroSchemaParser.getFirstChildElement(document); //check that we haven't accidentally read a template anyway if ( topElement.getTagName().equals("template") == true) { StringBuffer message = new StringBuffer(); message.append("You're trying to open a template"); message.append(" as a normal file"); ErrorDialog.show(message.toString() ); return; } experimentSchemaName = topElement.getAttribute("xsi:schemaLocation"); } //end else if ( experimentSchemaName.equals(GlobalConstants.NO_ATTRIBUTE_VALUE) == true) { ErrorDialog.show("Experiment file doesn't specify schema information"); return; } //end if () RecordModelFactory recordModelFactory = RecordModelFactory.getRecordModelFactory(); String applicationSchemaName = GlobalConstants.getModelName(); if ( recordModelFactory.schemaMatchesCurrentDataModel(applicationSchemaName, experimentSchemaName) == false) { StringBuffer errorMessage = new StringBuffer(); errorMessage.append("Experiment file uses schema \""); errorMessage.append(experimentSchemaName); errorMessage.append("\" \n but the application is using schema \""); errorMessage.append(applicationSchemaName); errorMessage.append("\""); ErrorDialog.show(errorMessage.toString() ); return; } //end if () //=============================================================================== //Part II: read in the records //=============================================================================== navigationTree.enableUpdateUI(false); rootNode = visitRecordModel(topElement); if ( readTemplate == false) { //top level recordModel should match top level recordModel //created by schema parser RecordModel rootRecordModel = rootNode.getRecordModel(); String topLevelClass = recordModelFactory.getTopLevelRecordModelClass(); if ( rootRecordModel.getRecordClassName().equals(topLevelClass) == false) { StringBuffer message = new StringBuffer(); message.append("The top level element of your file does not "); message.append("start with a recordModel of type "); message.append(rootRecordModel.getRecordClassName() ); throw new PedroException(message.toString() ); } //end if () } //end if () navigationTree.enableUpdateUI(true); //out.close(); } public void fillEditField(RecordModel recordModel, Element element) throws Exception { String fieldName = element.getTagName(); Text text = (Text) element.getFirstChild(); String value = text.getData(); if ( value != null) { value = value.trim(); if ( ( value.equals("") == false) && (value.equals("null") == false) ) { try { recordModel.setValue(fieldName,value, false); } catch (Exception err) { //if we've encountered an error, we should check to //see if the problem has to do with the date DataFieldModel field = recordModel.getField(fieldName); if ( field != null) { int uiRenderingType = field.getUIRenderingType(); if ( uiRenderingType == GlobalConstants.DATE_FIELD) { throw new PedroException("Field " + fieldName+ " has an improperly formatted date."); } //end if () } //end if () else { throw err; } //end else } // end try-catch } //end if () } //end if () } public void fillListField(NavigationTreeNode parentNode, Element element) { String fieldName = element.getTagName(); RecordModel parentRecordModel = parentNode.getRecordModel(); Node currentChild = element.getFirstChild(); int ithChild = 1; while ( currentChild != null) { ithChild++; if ( currentChild.getNodeType() == Node.ELEMENT_NODE) { Element childElement = (Element) currentChild; String tagName = childElement.getTagName(); if ( recordModelFactory.recordClassRegistered(tagName) == true) { try { NavigationTreeNode currentNode = visitRecordModel(childElement); parentNode.add(currentNode); RecordModel currentRecordModel = currentNode.getRecordModel(); parentRecordModel.addChild(fieldName, currentRecordModel, false); } catch (Exception e) { System.out.println(e); } // end try-catch } //end if () } //end if () currentChild = currentChild.getNextSibling(); } //end while () } private NavigationTreeNode visitRecordModel(Element element) throws Exception { String recordModelType = element.getTagName(); RecordModel recordModel = recordModelFactory.createRecordModel(recordModelType); NavigationTreeNode node = new NavigationTreeNode(recordModel); //now scan for fields NodeList children = element.getChildNodes(); int numberOfChildren = children.getLength(); Element currentElement = null; String currentFieldValue = null; Node currentNode = element.getFirstChild(); while ( currentNode != null) { int nodeType = currentNode.getNodeType(); if ( nodeType == Node.ELEMENT_NODE) { currentElement = (Element) currentNode; String dataFieldTagName = currentElement.getTagName(); if ( recordModel.isEditField(dataFieldTagName) == true) { fillEditField(recordModel,currentElement); } //end else () else if (recordModel.isListField(dataFieldTagName) == true) { fillListField(node,currentElement); } //end if () } //end if () currentNode = currentNode.getNextSibling(); } // end for () recordModel.updateDisplayName(); recordModel.addChangeListener(navigationTree); return node; } /** * assumes that a file of format "x.pdz" is passed, * and that a file "x.pdr" can be extracted */ private File unzipNativeFormatFile(File file) throws Exception { String zipFileName = file.getName(); int dotPosition = zipFileName.lastIndexOf("."); String nativeFileName = zipFileName.substring(0,dotPosition); nativeFileName = nativeFileName + ".pdr"; BufferedOutputStream dest = null; FileInputStream zipFileInputStream = new FileInputStream(file); ZipInputStream zipIn = new ZipInputStream(zipFileInputStream); ZipEntry entry; boolean pdrFileFound = false; while((entry = zipIn.getNextEntry()) != null) { int count = 0; byte data[] = new byte[BUFFER_SIZE]; String currentFileName = entry.getName(); if ( currentFileName.equals(nativeFileName) == true) { pdrFileFound = true; } //end if () FileOutputStream nativeFileOutputStream = new FileOutputStream(currentFileName); dest = new BufferedOutputStream(nativeFileOutputStream, BUFFER_SIZE); while ((count = zipIn.read(data, 0, BUFFER_SIZE)) != -1) { dest.write(data, 0, count); } dest.flush(); dest.close(); } zipIn.close(); if ( pdrFileFound == false) { StringBuffer message = new StringBuffer(); message.append("Could not unzip \""); message.append(file.getName()); message.append("\" properly"); throw new PedroException(message.toString() ); } //end if () File nativeFile = new File(nativeFileName); return nativeFile; } // ========================================== // Section Accessors // ========================================== public NavigationTreeNode getRoot() { return rootNode; } // ========================================== // Section Mutators // ========================================== // ========================================== // Section Validation // ========================================== // ========================================== // Section Errors // ========================================== // ========================================== // Section Interfaces // ========================================== // ========================================== // Section Overload // ========================================== }