/gicl/projs6/uvzaychi/code-link/cvs-testing/CUP/working/FileManager.java

import java.net.*;
import javax.swing.JApplet;
import java.io.*;
import java.util.Vector;
//xml stuff
import java.io.File;
import javax.vecmath.*;
import org.w3c.dom.*;
Message
import com.sun.xml.parser.Resolver;
import com.sun.xml.tree.XmlDocument;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
/**************************************************
 *			     CLASS :: FILE MANAGER
 **************************************************/
public class FileManager{
  public static final int XML=0;
  public static final int VRML=1;
  static String configFile="cup.cfg";
Message Message
  CUPworld parent;
  File currFile;
  public FileManager(CUPworld parent){
    this.parent=parent;
    init();
  }
  public void init() {
    Vector configuration = getConfig(FileManager.configFile);    
    TagInfo.setConfig(configuration);
  }
  public Vector getConfig (String file) {
    String config="";
    String nextLine="";
    
    try{
      currFile = new File(file);
	BufferedReader fin=new BufferedReader(new FileReader(currFile));
        boolean EOF=false;
        
        while(!EOF){
	    nextLine=fin.readLine();
	    nextLine=nextLine.trim();
	    if(nextLine != null){
	      if (nextLine.startsWith("/*")){
	        boolean comment=true;
	        while(comment){
		    nextLine=fin.readLine();
		    nextLine.trim();
		    if(nextLine.startsWith("*/")) comment=false;
	        }
	      }
	      else if (!(nextLine.startsWith("//") || nextLine.equals(""))){
	        if(nextLine.startsWith("EOF")) 
	          EOF=true;
	        else
	          config+=nextLine;
	      }
	    }
	    else
	      EOF=true;
        }
    } catch(FileNotFoundException fnfe){
    	System.err.println("File not found");
    } catch(IOException ioe){
      System.err.println("IO Exception");
    }
    
    if(file.endsWith(".cfg"))
      return StringParser.parseToVector("tag", config);
    else if(file.endsWith(".wrl"))
      return StringParser.parseToVector("vrml", config);
    else return null;
  }
  
  public boolean parseFile(String filename){
    InputSource  input;
    XmlDocument  doc;
    try {
      // turn the filename into an input source
      input = Resolver.createInputSource (new File (filename));
	// turn it into an in-memory object
	// ... the "false" flag says not to validate
	doc = XmlDocument.createXmlDocument (input, true);
	
	// normalize text representation
	doc.getDocumentElement ().normalize ();
	
	Element root = doc.getDocumentElement();
	parseShapes(root.getElementsByTagName("Shape"));
	parseGroups(root.getElementsByTagName("Group"));
	parseLinks(root.getElementsByTagName("Link"));
	
    } catch (SAXParseException err) {
	System.out.println ("** Parsing error" 
	  + ", line " + err.getLineNumber ()
	  + ", uri " + err.getSystemId ());
	System.out.println("   " + err.getMessage ());
	// print stack trace as below
	return false;
    } catch (SAXException e) {
	Exception  x = e.getException ();
      ((x == null) ? e : x).printStackTrace ();
      return false;
    } catch (Throwable t) {
      t.printStackTrace ();
      return false;
    }
    return true;
  }
  
  private void parseTagInfo(Node t){
    TagInfo tag = ((CUPShape)parent.getSelectedGroup()).tag;
    NamedNodeMap attributes;    
    Node attribute;
    NodeList children;
    Node child;
    
    children=t.getChildNodes();
    for(int i=0; i
      child=children.item(i);
      if(child.getNodeName().equals("StructureList")){
        NodeList list = child.getChildNodes();
        for(int j=0; j
          Node structure=list.item(j);
          attributes=structure.getAttributes();
          attribute=attributes.getNamedItem("value");
          tag.addStructure(attribute.getNodeValue());
        }
      } else if(child.getNodeName().equals("FunctionList")){
        NodeList list = child.getChildNodes();
        for(int j=0; j
          Node function=list.item(j);
          attributes=function.getAttributes();
          attribute=attributes.getNamedItem("value");
          tag.addFunction(attribute.getNodeValue());
        }
      } else if(child.getNodeName().equals("BehaviorList")){
        NodeList list = child.getChildNodes();
        for(int j=0; j
          Node behavior=list.item(j);
          attributes=behavior.getAttributes();
          attribute=attributes.getNamedItem("value");
          tag.addFunction(attribute.getNodeValue());
        }
      } else if(child.getNodeName().equals("FlowList")){
        NodeList list = child.getChildNodes();
        Flow flow;
        for(int j=0; j
          Node flowItem=list.item(j);
          attributes=flowItem.getAttributes();
          attribute=attributes.getNamedItem("value");
          flow=new Flow(attribute.getNodeValue());
          attribute=attributes.getNamedItem("source");
          flow.source=attribute.getNodeValue();
          attribute=attributes.getNamedItem("destination");
          flow.destination=attribute.getNodeValue();
          tag.addFlow(flow);
        }
      } else if(child.getNodeName().equals("Protection")){
        attributes=child.getAttributes();
        attribute=attributes.getNamedItem("value");
        tag.setProtection(attribute.getNodeValue());
      } else if(child.getNodeName().equals("View")){
        attributes=child.getAttributes();
        attribute=attributes.getNamedItem("value");
        tag.setView(attribute.getNodeValue());
      }
    }
  }
  
  private void parseColorInfo(Node c){
    CUPShape s=(CUPShape)parent.getSelectedGroup();
    ColorInfo ci=s.coloring;
    NamedNodeMap attributes;    
    Node attribute;
    NodeList children;
    Node child;
    children=c.getChildNodes();
    for(int i=0; i
      child=children.item(i);
      attributes=child.getAttributes();
      if(child.getNodeName().equals("Transparency")){
        attribute=attributes.getNamedItem("value");
        ci.setTransparency(Float.parseFloat(attribute.getNodeValue()));
      } else if(child.getNodeName().equals("Color")){
        attribute=attributes.getNamedItem("red");
        ci.r=Float.parseFloat(attribute.getNodeValue());
        attribute=attributes.getNamedItem("green");
        ci.g=Float.parseFloat(attribute.getNodeValue());
        attribute=attributes.getNamedItem("blue");
        ci.b=Float.parseFloat(attribute.getNodeValue());
      }
    }
    
    s.setColorInfo(ci);
  }
  
  private void parseTransform(Node t){
    NamedNodeMap attributes;    
    Node attribute;
    NodeList children;
    Node child;
    children=t.getChildNodes();
    for(int i=0; i
      child=children.item(i);
      String childName=child.getNodeName();
      attributes=child.getAttributes();
      if(childName.equals("Translation") || childName.equals("Scale")){
        Vector3d v3d = new Vector3d();
        attribute=attributes.getNamedItem("x");
        v3d.x=Double.parseDouble(attribute.getNodeValue());
        attribute=attributes.getNamedItem("y");
        v3d.y=Double.parseDouble(attribute.getNodeValue());
        attribute=attributes.getNamedItem("z");
        v3d.z=Double.parseDouble(attribute.getNodeValue());
        if(childName.equals("Translation"))
          parent.setTranslation(v3d);
        else
          parent.setScale(v3d);
      } else if(child.getNodeName().equals("Rotation")){
        Matrix3f m3f = new Matrix3f();
        attribute=attributes.getNamedItem("m00");
        m3f.m00=Float.parseFloat(attribute.getNodeValue());
        attribute=attributes.getNamedItem("m01");
        m3f.m01=Float.parseFloat(attribute.getNodeValue());
        attribute=attributes.getNamedItem("m02");
        m3f.m02=Float.parseFloat(attribute.getNodeValue());
        attribute=attributes.getNamedItem("m10");
        m3f.m10=Float.parseFloat(attribute.getNodeValue());
        attribute=attributes.getNamedItem("m11");
        m3f.m11=Float.parseFloat(attribute.getNodeValue());
        attribute=attributes.getNamedItem("m12");
        m3f.m12=Float.parseFloat(attribute.getNodeValue());
        attribute=attributes.getNamedItem("m20");
        m3f.m20=Float.parseFloat(attribute.getNodeValue());
        attribute=attributes.getNamedItem("m21");
        m3f.m21=Float.parseFloat(attribute.getNodeValue());
        attribute=attributes.getNamedItem("m22");
        m3f.m22=Float.parseFloat(attribute.getNodeValue());
        parent.setRotation(m3f);
      }      
    }
  }
  
  private void parseShapes(NodeList shapes){
    CUPShape shape;
    NodeList children;
    Node shapeNode;
    NamedNodeMap attributes;
    Node attribute;
    Node node;
    
    for(int i=0; i
      shape=null; children=null; shapeNode=null; attributes=null; attribute=null; node=null;
      
      shapeNode=shapes.item(i);
      attributes=shapeNode.getAttributes();
      
      attribute=attributes.getNamedItem("type");
      String type=attribute.getNodeValue();
      if(type.toUpperCase().equals("BOX"))
        shape=(CUPShape)parent.createObj(CUPShape.BOX);
      else if(type.toUpperCase().equals("SPHERE"))
        shape=(CUPShape)parent.createObj(CUPShape.SPHERE);
      else if(type.toUpperCase().equals("CONE"))
        shape=(CUPShape)parent.createObj(CUPShape.CONE);
      else if(type.toUpperCase().equals("CYLINDER"))
        shape=(CUPShape)parent.createObj(CUPShape.CYLINDER);
        
      if(shape!=null){
        parent.objTransRoot.addChild(shape);
        parent.setSelectedGroup(shape);
        
        attribute=attributes.getNamedItem("name");
        shape.tag.setTagName(attribute.getNodeValue());
        
        children=shapeNode.getChildNodes();
        for(int j=0; j
          node=children.item(j);
          
          if(node.getNodeName().equals("TagInfo"))
            parseTagInfo(node);
          else if(node.getNodeName().equals("ColorInfo"))
            parseColorInfo(node);
          else if(node.getNodeName().equals("Transform"))
            parseTransform(node);
        }
        
      }
    }  
  }
  
  private void parseGroups(NodeList groups){
  
  }
  
  private void parseLinks(NodeList links){
  
  }
    
  public boolean saveFile(String filename, Vector fileContent){
    boolean successful = true;
    if(fileContent==null) return false;
    try{
      PrintWriter out=new PrintWriter(new BufferedWriter(new FileWriter(filename)), true);
      
      out.println("");
      out.println("");
      
      int tab = 0;
      for(int i=0; i
        String str = ((String)fileContent.elementAt(i)).trim();
        if(str.equals("}") || str.equals("]") 
          || str.startsWith("
          tab-=2;
        for(int j=0; j
          out.print(' ');
        out.println(str);
        if(!str.startsWith("<")&&str.endsWith(">"))
          tab-=2;
        if(str.equals("{") || str.equals("[") || str.endsWith("{") || str.endsWith("[")
          || (str.startsWith("<")&&!str.startsWith("")))
          tab+=2;
      }
      out.close();
    } catch(IOException ioe){
      successful=false;
      System.err.println("IO ERROR");
    }
    
    return successful;
  }
}