public interface Configuration {
    
    void addPreferenceChangeListener(PreferenceChangeListener listener);
    
    public int getUiPreferenceChangeCount();
    public void decreaseUiPreferenceChangeCount();
    
    public int getTextAreaFontSize();
    public void setTextAreaFontSize(int newSize);

    public int getUIFontSize();
    public void setUIFontSize(int newSize);

    public boolean getLinkFontSizes();
    public void setLinkFontSizes(boolean linkFontSizes);

    public String getLookAndFeel();
    public void setLookAndFeel(String lafClassName);

    public RuleMLFormat getRuleMLFormat();
    public void setSelectedRuleMLFormat(RuleMLFormat rmlFormat);
    
    public int getHttpConnectionTimeout();
    public void setHttpConnectionTimeout(int timeoutInMilliseconds);

    public Level getLogLevel();
    public void setLogLevel(Level logLevel);
}
 public interface Reasoner {
    public void clearClauses();
    public void loadClauses(Iterator iterator);
}
 public enum SyntaxFormat {
	RDFS,
	RULEML,
	POSL
} public class POSLParser {
    Vector clauses = new Vector();

    public POSLParser() {
    }

    /**
     * Returns an interator over the clauses that are stored in the parsers
     * internal buffer; the buffer is not automatically cleared after a call
     * to iterator(). To clear the buffer a call to reset() must be invoked.
     * @return Iterator
     */
    public Iterator iterator() {
        return clauses.iterator();
    }

    /**
     * Clears the parsers internal clause buffer.
     */
    public void reset() {
        clauses = new Vector();
    }

    /**
     * This method is used to parse a single definite clause, stored in a
     * String. The DefiniteClause object that represents the parsed clause is
     * returned directly to the user and not added to the internal clause
     * buffer.
     *
     * @param clause String A string containing the clause to be parsed. If the
     * string contains multiple clauses only the first clause will be parsed.
     *
     * @return DefiniteClause The DefiniteClause object that represents the
     * parsed clause.
     *
     * @throws RecognitionException
     * @throws TokenStreamException
     */
    public DefiniteClause parseDefiniteClause(String clause) throws RecognitionException, TokenStreamException{
        StringReader sr = new StringReader(clause);
        POSLLexer lex = new POSLLexer(sr);
        org.ruleml.oojdrew.parsing.generated.POSLParser pp = new org.ruleml.oojdrew.parsing.generated.POSLParser(lex);
        return pp.clause(true);
    }

    /**
     * This method is used to parse a query - stored in a String. The
     * DefiniteClause object that represents the parsed query is returned
     * directly to the user and not added to the internal clause buffer.
     *
     * @param query String A string containing the query to be parsed. If the
     * string contains multiple queries only the first query will be parsed.
     *
     * @return DefiniteClause The DefiniteClause object that represents the
     * parsed query.
     *
     * @throws RecognitionException
     * @throws TokenStreamException
     */
    public DefiniteClause parseQueryString(String query) throws RecognitionException, TokenStreamException{
        return parseDefiniteClause("$top():-" + query + ".");
    }
	//used for parsing a Type Query String
 	public DefiniteClause parseQueryStringT(String query) throws RecognitionException, TokenStreamException{
        return parseDefiniteClause(query + ".");
    }

    /**
     * This method is used to parse a group of clauses, stored in a String. The
     * parsed clauses (DefiniteClause objects) are added to the internal clause
     * buffer and not returned directly to the caller. The an iterator over the
     * clauses can be retrieved by invoking the iterator() method.
     *
     * @param clauses String A string containing one or more clauses.
     *
     * @throws RecognitionException
     * @throws TokenStreamException
     */
    public void parseDefiniteClauses(String clauses) throws RecognitionException, TokenStreamException{
        StringReader sr = new StringReader(clauses);
        parseReader(sr);
    }

    /**
     * This method is used to parse a group of clauses stored in a local file.
     * The full path to the filename should be used. A FileReader object is
     * created using the filename as the path; then the reader is passed to
     * the parseReader(Reader) method.
     *
     * @param filename String A string containing the complete path to the file.
     *
     * @throws FileNotFoundException
     * @throws RecognitionException
     * @throws TokenStreamException
     */
    public void parseDCFile(String filename) throws FileNotFoundException, RecognitionException, TokenStreamException{
        FileReader fr = new FileReader(filename);
        parseReader(fr);
    }

    /**
     * This method is used to parse a group of clauses read from an InputStream
     * (keyboard, socket, etc.). A InputStreamReader is created using the
     * InputStream and passed to the parseReader(Reader) method. Clauses are
     * parsed until a End of File (EOF) character is reached (Typically CTRL-D
     * on Unix-like systems and CTRL-Z on Windows).
     *
     * @param is InputStream The input stream to read clauses from.
     *
     * @throws RecognitionException
     * @throws TokenStreamException
     */
    public void parseInputStream(InputStream is) throws RecognitionException, TokenStreamException {
        InputStreamReader isr = new InputStreamReader(is);
        parseReader(isr);
    }

    /**
     * This method is used by parseInputStream(), parseDCFile() and
     * parseDefiniteClauses() to perform the parsing, using the reader that is
     * created in each of those methods.
     *
     * This method creates a POSLLexer (Lexcographical Analyzer) object on the
     * Reader. Once this is done a org.ruleml.oojdrew.util.parsing.POSLParser object
     * created on the lexer and the rulebase(Vector) method is invoked to parse
     * the rulebase that is read from the reader.
     *
     * @param r Reader The reader to read the input from.
     *
     * @throws RecognitionException
     * @throws TokenStreamException
     */
    private void parseReader(Reader r) throws RecognitionException, TokenStreamException {
        POSLLexer lex = new POSLLexer(r);
        org.ruleml.oojdrew.parsing.generated.POSLParser pp = new org.ruleml.oojdrew.parsing.generated.POSLParser(lex);
        pp.rulebase(this.clauses);
    }
}
 public class RDFSParser {
    private static String rdfsuri;
    private static String rdfuri;

    private static final String RDF = "rdf";
    private static final String RDFS = "rdfs";
    private static final String RDFSCLASS = "rdfs:Class";
    private static final String RDFDESCRIPTION = "rdf:Description";
    private static final String RDFID = "rdf:ID";
    private static final String RDFABOUT = "rdf:about";
    private static final String RDFRESOURCE = "rdf:resource";
    private static final String RDFSSUBCLASSOF = "rdfs:subClassOf";
    private static final String RDFTYPE = "rdf:type";

    private static final String CLASS = "Class";
    private static final String DESCRIPTION = "Description";
    private static final String ID = "ID";
    private static final String ABOUT = "about";
    private static final String RESOURCE = "resource";
    private static final String SUBCLASSOF = "subClassOf";
    private static final String TYPE = "type";

    private static final String CLASSRES =
            "http://www.w3.org/2000/01/rdf-schema#Class";

   // private static Logger logger = Logger.getLogger("jdrew.oo.util.RDFSParser");

    /**
     * Method to parse an RDFS file and load the type information in the RDFS
     * into the engines type sorts.
     *
     * This method parses the file into a XOM tree and passes the XOM
     * Document object to the parseDocument(Document doc) method.
     *
     * @param filename String A string containing the complete path to the RDFS
     * file.
     *
     * @throws ParsingException Thrown if there is an error in the RDFS file
     * that causes parsing to fail.
     *
     * @throws ValidityException Thrown if the XML document is not wellformed
     * or does not conform to the RDFS DTD.
     *
     * @throws IOException Thrown if there is an error reading the file from
     * disk.
     */
    public static void parseRDFS(String filename) throws ParsingException,
        ValidityException, IOException {
        Builder b = new Builder();
        File f = new File(filename);
        Document doc = b.build(f);
        parseDocument(doc);
    }

    public static void parseRDFSFile(File f) throws ParsingException, ValidityException, IOException {
    	Builder b = new Builder();	
    	Document doc = b.build(f);
    	parseDocument(doc);
    }

    /**
     * Method that parses an RDFS document contained in a string and load the
     * type information in the RDFS into the engines type sorts.
     *
     * This method parses the string to an XOM document and passes the Document
     * object to the parseDocument(Document doc) method.
     *
     * @param contents String
     *
     * @throws ParseException Thrown if there is an error in the RDFS document
     * that causes parsing to fail.
     *
     * @throws ParsingException Thrown if there is an error parsing at an XML
     * level.
     *
     * @throws ValidityException Thrown if the XML document is not wellformed
     * or does not conform to the RDFS DTD.
     *
     * @throws IOException Thrown if there is an error reading the string -
     * this should not occur.
     */
    public static void parseRDFSString(String contents) throws ParseException,
            ParsingException, ValidityException, IOException {
        Builder bl = new Builder();

        StringReader sr = new StringReader(contents);
        Document doc = bl.build(sr);
        
        //System.out.println(doc.toXML());
        parseDocument(doc);
    }

    /**
     * Parses the XOM document object that should represent an RDFS document;
     * containing types that will be added to the type sorts.
     *
     * @param doc Document The XOM document object to parse.
     */
    private static void parseDocument(Document doc) {
        Element root = doc.getRootElement();
        rdfsuri = root.getNamespaceURI("rdfs");
        rdfuri = root.getNamespaceURI("rdf");

        //logger.debug("RDFS Uri: " + rdfsuri);
        //logger.debug("RDF Uri: " + rdfuri);

        Elements els = root.getChildElements();
        for (int i = 0; i < els.size(); i++) {
            Element el = els.get(i);
            //logger.debug("Parsing element: " + el.getQualifiedName());
            if (el.getQualifiedName().equals(RDFSCLASS)) {
                parseClass(el);
            } else if (el.getQualifiedName().equals(RDFDESCRIPTION)) {
                parseDescription(el);
            } else {
                //logger.debug(
                //        "Unrecognized element in RDFS file. Element being ignored.");
            }
            
        }
// should put new type parser here
        Types.makeTypes();
        
    }

    /**
     * This method parses a rdfs:Class element and loads the information
     * contained into the Type system.
     *
     * @param cls Element The XOM element that contains the rdfs:Class object.
     */
    private static void parseClass(Element cls) {
        String typename = cls.getAttributeValue(ID, rdfuri);
        if (typename == null) {
          //  logger.debug(
           //         "rdfs:Class element does not have rdf:ID attribute - trying rdf:about");
            typename = cls.getAttributeValue(ABOUT, rdfuri);
            if (typename == null) {
                //logger.warn("rdfs:Class element does not have and rdf:about or rdf:ID attribute - no typename - type creation failure.");
                return;
            }
        }

        if (typename.indexOf("#") > 0) {
            typename = typename.substring(typename.indexOf("#") + 1);
        }

        Vector v = new Vector();
        Elements els = cls.getChildElements();
        for (int i = 0; i < els.size(); i++) {
            Element el = els.get(i);
            if (el.getQualifiedName().equals(RDFSSUBCLASSOF)) {
                String parentname = el.getAttributeValue(RESOURCE, rdfuri);
                if (parentname.indexOf("#") >= 0) {
                    parentname = parentname.substring(parentname.indexOf("#") +
                            1);
                }
                v.add(parentname);
            }
        }

        String[] parents = new String[v.size()];
        String parentstr = "";
        for (int i = 0; i < parents.length; i++) {
            parents[i] = v.get(i).toString();
            parentstr += v.get(i).toString() + " ";
        }

        //logger.info("Creating Type: " + typename + " parents: " + parentstr);
       // System.out.println("Dies before createType");
        
        Types.storeTempTypes(typename, parents);
       // Types.createDAGNode(typename);
       // Types.createDAGEdges(typename, parents);



}

    /**
     * Parses a rdf:description element and loads the type information into the
     * type sorts.
     *
     * @param desc Element The XOM element object representing the
     * rdf:description element.
     */
    private static void parseDescription(Element desc) {
        String typename = desc.getAttributeValue(ID, rdfuri);
        if (typename == null) {
           // logger.debug(
           //         "rdf:Description element does not have rdf:ID attribute - trying rdf:about");
            typename = desc.getAttributeValue(ABOUT, rdfuri);
            if (typename == null) {
               // logger.warn("rdf:Description element does not have an rdf:about or rdf:ID attribute - no typename - type creation failure.");
                return;
            }
        }

        if (typename.indexOf("#") > 0) {
            typename = typename.substring(typename.indexOf("#") + 1);
        }

        Element type = desc.getFirstChildElement(TYPE, rdfuri);
        if (type == null ||
            !type.getAttributeValue(RESOURCE, rdfuri).equals(CLASSRES)) {
           // logger.warn(
           //         "rdf:Description element has not rdf:type child element, or is not of type " +
            //        CLASSRES + " - ignoring rdf:Description element.");
            return;
        }

        if (typename.indexOf("#") >= 0) {
            typename = typename.substring(typename.indexOf("#") + 1);
        }

        Vector v = new Vector();
        Elements els = desc.getChildElements();
        for (int i = 0; i < els.size(); i++) {
            Element el = els.get(i);
            if (el.getQualifiedName().equals(RDFSSUBCLASSOF)) {
                String parentname = el.getAttributeValue(RESOURCE, rdfuri);
                if (parentname.indexOf("#") >= 0) {
                    parentname = parentname.substring(parentname.indexOf("#") +
                            1);
                }
                v.add(parentname);
            }
        }

        String[] parents = new String[v.size()];
        String parentstr = "";
        for (int i = 0; i < parents.length; i++) {
            parents[i] = v.get(i).toString();
            parentstr += v.get(i).toString() + " ";
        }

        //logger.info("Creating Type: " + typename + " parents: " + parentstr);

        //Types.createType(typename, parents);
        
        Types.storeTempTypes(typename, parents);
        
       // Types.createDAGNode(typename);
       // Types.createDAGEdges(typename, parents);
    }


}
 public enum RuleMLFormat {
    RuleML88("RuleML 0.88"), RuleML91("RuleML 0.91"), RuleML100(
            "RuleML 1.0");

    private String versionName;

    RuleMLFormat(String versionName) {
        this.versionName = versionName;
    }

    public String getVersionName() {
        return this.versionName;
    }

    public static RuleMLFormat fromString(String versionName) {
        if (versionName != null) {
            for (RuleMLFormat rmlFormat : RuleMLFormat.values()) {
                if (versionName.equalsIgnoreCase(rmlFormat.versionName)) {
                    return rmlFormat;
                }
            }
        }
        return null;
    }

    public static String[] getVersionNames() {
        String[] versionNames = new String[values().length];
        int i = 0;
        for (RuleMLFormat rmlFormat : values()) {
            versionNames[i] = rmlFormat.versionName;
            i++;
        }
        return versionNames;
    }
}
 public class RuleMLParser implements PreferenceChangeListener {

    /**
     * A buffer that stores clauses that have already been parsed.
     */
    private Vector<DefiniteClause> clauses;
    private Configuration config;
    
    private RuleMLFormat rmlFormat;

    private Level logLevel;

    /**
     * Constructs a new parser object.
     * 
     * @param config
     *            The configuration instance which should be used
     */
    public RuleMLParser(Configuration config) {
        clauses = new Vector<DefiniteClause>();
        this.config = config;
        config.addPreferenceChangeListener(this);
        preferenceChange(null);
    }

    /**
     * Gets an iterator over all clauses that are stored in the internal clause
     * buffer. This method does not automatically clear items from the buffer.
     * 
     * @return Iterator An iterator over all clauses in the buffer.
     */
    public Iterator<DefiniteClause> iterator() {
        return clauses.iterator();
    }

    /**
     * Clears the internal buffer; and forces a garbage collection cycle. This
     * allows the easy reuse of a parser object.
     */
    public void clear() {
        clauses = new Vector<DefiniteClause>();
        System.gc();
    }

    /**
     * @see jdrew.oo.parsing.RuleMLParser#parseDocument
     */
    public void parseFile(String filename) throws ParseException, ParsingException, IOException {
        File file = new File(filename);
        parseFile(file);
    }

    /**
     * @see jdrew.oo.parsing.RuleMLParser#parseDocument
     */
    public void parseFile(File file) throws ParseException, ParsingException, IOException {
        Builder bl = new Builder();
        Document doc = bl.build(file);
        parseDocument(doc);
    }

    /**
     * @see jdrew.oo.parsing.RuleMLParser#parseDocument
     */
    public void parseRuleMLString(String contents) throws ParseException, ParsingException, IOException {
        Builder bl = new Builder();
        StringReader sr = new StringReader(contents);
        Document doc = bl.build(sr);
        parseDocument(doc);
    }

    /**
     * Parses a document containing a knowledge base that is in the indicated
     * format. If additional backed parsers are created then additional formats
     * will be added.
     * 
     * NOTE: It may be a good idea to add format auto detection based upon the
     * XSD and/or DTD that is referenced by the document.
     * 
     * @param format
     *            RuleMLVersion The RuleML version for the back-end parser
     * 
     * @param doc
     *            The document which should be parsed
     * 
     * @throws ParseException
     *             A ParseException is thrown if there is an error in the
     *             document that causes parsing to fail.
     * 
     * @throws ParsingException
     *             A ParsingException is thrown if there is an error in parsing
     *             the document at an XML level or a ValidityException
     *             (subclass) is thrown if the XML document is not well * formed
     *             or does not conform to the DTD specified.
     */
    public void parseDocument(Document doc) throws ParseException, ParsingException {
        RuleMLDocumentParser parser = new RuleMLDocumentParser(rmlFormat, clauses);
        parser.setLogLevel(logLevel);

        parser.parseRuleMLDocument(doc);
    }

    /**
     * Parses a RuleML query
     * 
     * @param contents
     *            The document content
     * 
     * @return A DefiniteClause containing the parsed document
     * 
     * @throws ParseException
     * @throws ParsingException
     * @throws IOException
     */
    public DefiniteClause parseRuleMLQuery(String contents)
            throws ParseException, ParsingException, IOException {

        contents = ensureQueryTag(contents);
        contents = buildFakeImplication(contents);

        parseRuleMLString(contents);

        return (DefiniteClause) clauses.lastElement();
    }

    /**
     * Builds a fake implication which is needed to satisfy the reasoning
     * engine.
     * 
     * @param query
     *            An input query
     * 
     * @return Input query as a RuleML implication
     */
    private String buildFakeImplication(String query) {
        Builder builder = new Builder();
        StringReader stringReader = new StringReader(query);
        Document document;

        try {
            document = builder.build(stringReader);
        } catch (Exception e) {
            // Cannot happen
            e.printStackTrace();
            return "";
        }

        Element queryElement = document.getRootElement();

        RuleMLTagNames rmlTags = new RuleMLTagNames(rmlFormat);

        Element rel = new Element(rmlTags.REL);
        rel.insertChild("$top", 0);

        Element topAtom = new Element(rmlTags.ATOM);
        topAtom.appendChild(rel);

        Nodes atoms = queryElement.removeChildren();

        Element implies = new Element(rmlTags.IMPLIES);

        for (int i = 0; i < atoms.size(); ++i) {
            implies.appendChild(atoms.get(i));
        }

        implies.appendChild(topAtom);

        queryElement.appendChild(implies);

        return document.toXML();
    }

    /**
     * Manually add <Query> wrapper if not exists
     * 
     * @param query
     *            An input query
     * 
     * @return Input query encapsulated with a <Query> tag
     */
    private String ensureQueryTag(String query) {
        // Evil hack: encapsulate the query contents in a pair of <Query> tags
        RuleMLTagNames rmlTags = new RuleMLTagNames(rmlFormat);
        query = query.trim();
        String queryTagOpen = String.format("<%s>", rmlTags.QUERY);
        String queryTagClose = String.format("</%s>", rmlTags.QUERY);

        if (!query.contains(queryTagOpen)) {
            query = String.format("%s%s%s", queryTagOpen, query, queryTagClose);
        }

        return query;
    }

    /**
     * Updates parser configuration when preferences have changed
     */
    public void preferenceChange(PreferenceChangeEvent evt) {
        rmlFormat = config.getRuleMLFormat();
        logLevel = config.getLogLevel();
    }
}
 public class SubsumesParser {
	
	String parseString;
	/** A Vector of the subsumes Objects in the system after parsing. */
	Vector subsumeObjects = new Vector();
	
	/** A Vector of Strings that contain all the classes in the type system after parsing. */
	Vector allClasses = new Vector();
	
	/** A Vector of RDFObjects in the type system after parsing. */
	Vector RDFObjects = new Vector();
	String finalRDFSString = "";
	/** 
	 * This is the constructor for the subsumes parser.  All it needs is a string to be
	 * parsed.
	 *   
	 * @param String - parseString this is the POSL representation of the type system to be
	 * parsed
	 */
	public SubsumesParser(String parseString){
		
		this.parseString = parseString;
	}
	
	public SubsumesParser()
	{
		this.parseString = "";
	}
	
	/**
	 * This method will parse the given String when the SubsumesParser was created. 
	 *
	 * @throws SubsumesException - a Exception that could occur depending on invalid formatting
	 * @throws IOException 
	 * @throws ParsingException 
	 * @throws ParseException 
	 * @throws ValidityException 
	 */
	
	public void parseSubsumes() throws SubsumesException, ValidityException, ParseException, ParsingException, IOException{
		this.buildSubsumeObjects();
		this.buildRDFObjects();
		RDFSParser.parseRDFSString(finalRDFSString);
		//this.buildTypes();
	}
	
	public void parseSubsumes(String parseString) throws SubsumesException, ValidityException, ParseException, ParsingException, IOException
	{
		this.parseString = parseString;
		parseSubsumes();
	}
	
	/**
	 * This method will parse through all the given subsumes relations and create
	 * objects for them.  The objects contain a 2 strings one for the super class and one 
	 * for the sub class.
	 * 
	 * @throws SubsumesException a Exception that could occur depending on invalid formatting
	 */
	public void buildSubsumeObjects() throws SubsumesException{
		
		 Vector rdfsObjects = new Vector();
	 	 //Parsing the POSL String given
		 POSLParser pp = new POSLParser();
		 try{
		 pp.parseDefiniteClauses(parseString);
		 }catch(Exception e){
			 throw new SubsumesException("Incorrect POSL syntax");
		 }
		 //Obtaining the Parsed subsume objects	 
		 Iterator it = pp.iterator();
		 
		 //Iterating through all of the clauses to make sure they are of valid syntax
		 //Once they have been validated then a subsumes Object is created to 
		 //store the parameters of the subsumes objects
		 while (it.hasNext()) {
		    DefiniteClause dc = (DefiniteClause) it.next();
		    
		    Term[] atoms = dc.atoms;
	    	if(atoms.length != 1){
	    		throw new SubsumesException("Types cannot contain a rule.");
	       	}
	    	Term t1 = atoms[0];
	    	String predicate = t1.getSymbolString();
	    	if(!predicate.equals("subsumes")){
	    		throw new SubsumesException("Only subsumes facts can be in type definition.");	
	    	}
	    	Term[] terms = t1.getSubTerms();
	    	
    		if(terms.length != 3){
    			throw new SubsumesException("Subsumes facts can only have 2 arguments.");
    		}
    		String[] varnames = dc.variableNames;
    		String term1 = terms[1].toPOSLString(varnames,true);
    		String term2 = terms[2].toPOSLString(varnames,true);
    		//System.out.println(term1 + " " + term2);
    	    boolean t1Var = false;
    	    boolean t2Var = false;
    		
    	    String term1Sub = term1.substring(0,1);
    	    String term2Sub = term2.substring(0,1);
    	    
    	    if(term1Sub.equals("?")){
    	    	throw new SubsumesException("Subsumes facts cannot contain variables in type definitions");
    	    	
    	    }
    	    if(term2Sub.equals("?")){
    	    	throw new SubsumesException("Subsumes facts cannot contain variables in type definitions");
    	    	
    	    }
    	    
    	    SubsumesObject so = new SubsumesObject(term1,term2);
    	    
    	    subsumeObjects.add(so);	 
		 }
		 
	}
	/**
	 * Iterating through all of the subsume objects to create RDF Objects
	 * RDF objects contain the the parent class and all of its sub classes.
	 */
	public void buildRDFObjects(){
		String allRDFSObjects = "";
		
		Iterator it = subsumeObjects.iterator();
		String superClass;
		String subClass;
		String compare;
		boolean firstPass = true;
		boolean superDuplicate = false;
		boolean subDuplicate = false;
		
		//Looping through the subsume Objects to determine all of the classes in the
		//Type System duplicates must be removed.
		
		while(it.hasNext()){
			superDuplicate = false;
			subDuplicate = false;
			
			Object b = it.next();
			SubsumesObject so = (SubsumesObject) b;
			
			superClass = so.getSuperClass();
			subClass = so.getSubClass() ;

			if(firstPass){
				//System.out.println("First pass");
				firstPass = false;
				allClasses.add(superClass);
			}
			int classSize = allClasses.size();
			
			Iterator allClassIt = allClasses.iterator();
			//checking for duplicates
			while(allClassIt.hasNext()){
				
				Object comp = allClassIt.next();
				compare = comp.toString();
				
				if(superClass.equals(compare)){
					//System.out.println("Found duplicate super");
					superDuplicate = true;
				}
				
				if(subClass.equals(compare)){
					//System.out.println("Found duplicate sub");
					subDuplicate = true;
				}
			}	
			if(!superDuplicate){
				allClasses.add(superClass);
			}
			if(!subDuplicate){
				allClasses.add(subClass);			
			}
		}
						
		
		Iterator secondPass = allClasses.iterator();
		//make all RDF objects for each class
		//This iteration will create all of the RDF Objects needed
		//We need to find all of the subClasses of every class collected in the
		//allClasses Vector.
		while(secondPass.hasNext()){

			Object sup = secondPass.next();
			String mainClass = sup.toString();
			
			Iterator subObjects = subsumeObjects.iterator();
			//find all parents of each rdf object
			Vector allParents = new Vector();
			while(subObjects.hasNext()){	
				Object subObject = subObjects.next();
				SubsumesObject so = (SubsumesObject)subObject;
				String superC = so.getSuperClass();
				String subC   = so.getSubClass();
				
				if(mainClass.equals(subC)){
					allParents.add(superC);
				}
			
			}
			int size = allParents.size();
			String[] parents = new String[size];
			
			for(int i = 0 ; i < size; i++){
				Object parOb = allParents.elementAt(i);
				parents[i] = parOb.toString();
			}

			RDFObject ro = new RDFObject(mainClass,parents);	
			
			String rdfStringSingle = "<rdf:Description rdf:ID=\""+ro.getName()+"\">" +"\n" + 
			"<rdf:type rdf:resource=\"http://www.w3.org/2000/01/rdf-schema#Class\"/>\n";
			
			String[] parentz = ro.getParents();
			
			for(int i = 0; i <parentz.length; i++){
				rdfStringSingle = rdfStringSingle + "<rdfs:subClassOf rdf:resource=\"#" + parentz[i]+ "\"/>\n";			
			}
			rdfStringSingle = "\n" + rdfStringSingle + "</rdf:Description>\n";
			allRDFSObjects = allRDFSObjects + rdfStringSingle;		
			RDFObjects.add(ro);
		}	

		
		  finalRDFSString =
		  "<rdf:RDF\n" + 	 
		  "xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"\n" +
		  "xmlns:rdfs=\"http://www.w3.org/2000/01/rdf-schema#\"\n" + 
		  "xml:base=\"http://example.org/schemas/vehicles\">\n" +
		  allRDFSObjects + "\n" +
		  "</rdf:RDF>";

	}
	/**
	 * This method will create the RDFS Types.  Once the RDF Objects have been created
	 * all that is left to do is define them in the Type Graph.
	 */
	public void buildTypes(){
		
		Iterator it = RDFObjects.iterator();
		
		while(it.hasNext()){
			
			Object ob = it.next();
			RDFObject rdfsOb = (RDFObject)ob;
			
			String name = rdfsOb.getName();
			String[] parents = rdfsOb.getParents();

			Types.createType(name, parents);
			
		}
	}
	
}//SubsumesParser Class
 public class Types {
	
		public static void main(String[] args){
			
			System.out.println("hi");
			Types.reset();
		}
	
        /**
         * The integer code for the base type of the type system (Thing) - this
         * value should not be used; ITHING should be used instead. This is kept
         * for compatability purposes.
         */
        public static final int IOBJECT = 0;

        /**
         * The integer code for the base type of the type system (Thing).
         */
        public static final int ITHING = 0;

        /**
         * The type name for the base type of the type system (Thing).
         */
        public static final String OBJECT = "Thing";

        /**
         * The integer code for the bottom of the type lattice (Nothing). This
         * type inherits from all other types in the system.
         */
        public static final int INOTHING = -1;

        /**
         * The name for the bottom of the type lattice (Nothing).
         */
        public static final String NOTHING = "Nothing";

        /**
         * The name for the base type for all numeric types in the type lattice.
         */
        public static final String NUMERIC = "Numeric";

        /**
         * The name for the integer type in the type lattice.
         */
        public static final String INTEGER = "Integer";

        /**
         * The name for the floating point number type in the type lattice.
         */
        public static final String FLOAT = "Real";

        /**
         * The name for the string type in the type lattice.
         */
        public static final String STRING = "String";

        /**
         * The integer code for the integer type.
         */
        public static int IINTEGER;

        /**
         * The integer code for the floating point number type.
         */
        public static int IFLOAT;

        /**
         * The integer code for the numeric base type.
         */
        public static int INUMERIC;

        /**
         * The integer code for the String base type.
         */
        public static int ISTRING;

        /**
         * A vector that contains all of the type names. The index of a type
         * in this vector is the integer code that is used for that type.
         */
        public static Vector types = new Vector();
        
        /**
         * A vector that contains all types yet to be created. The index of a type
         * in this vector is the integer code that is used for that type.
         */
        public static Vector tempTypes = new Vector();
        

        /**
         * A dag that represents the types and their inheritance pathways.
         * This is used to efficiently determine the type relationships.
         */
        public static DirectedAcyclicGraph dag = new DirectedAcyclicGraph();
		
				
        static Logger log = Logger.getLogger("jdrew.oo.util.Types");

    /**
     * The static initialization of the base types in the type system.
     */
    static {
        types.add(OBJECT);
        dag.addNodeWeight(0);
        
        
        INUMERIC = createType(NUMERIC, new String[] {OBJECT});
        IINTEGER = createType(INTEGER, new String[] {NUMERIC});
        IFLOAT = createType(FLOAT, new String[] {NUMERIC});
        ISTRING = createType(STRING, new String[] {OBJECT});
    }	

    /**
     * A method to reset the type system. Any clause related data structres that
     * were created before a call to reset() cannot be used after the reset as
     * the integer codes may no longer be valid.
     */
    public static void reset() {
        dag = new DirectedAcyclicGraph();
        types = new Vector();
        types.add(OBJECT);
        dag.addNodeWeight(0);
        INUMERIC = createType(NUMERIC, new String[] {OBJECT});
        IINTEGER = createType(INTEGER, new String[] {NUMERIC});
        IFLOAT = createType(FLOAT, new String[] {NUMERIC});
        ISTRING = createType(STRING, new String[] {OBJECT});
    }

    /**
     * Greg's Working on this
     *
     * @param name String The name of the new type to be defined.
     *
     * @param parents String[] An array containing the name of all direct
     * superclasses of the type.
     *
     * @return int The integer code for the type, this is what is stored in a
     * Term objects type instance variable.
     */
    public static int createDAGNode(String name) {
    	
                if (types.contains(name)) {
            log.warn("Type " + name +
                     " already exists, cannot create type definition.");
            throw new EngineException("Type " + name +
                    " already exists, cannot create type definition.");
        }

      

        int id = types.size();
        types.add(name);

        Integer iID = id;
        dag.addNodeWeight(iID);

        return id;
    }

    /**
     * Define a new type in the type system. The user must specify the name of
     * the type and the names of all direct superclasses.
     *
     * @param name String The name of the new type to be defined.
     *
     * @param parents String[] An array containing the name of all direct
     * superclasses of the type.
     *
     * @return int The integer code for the type, this is what is stored in a
     * Term objects type instance variable.
     */
    public static int createType(String name, String[] parents) {
        Integer[] parentids;

        if (types.contains(name)) {
            log.warn("Type " + name +
                     " already exists, cannot create type definition.");
            throw new EngineException("Type " + name +
                    " already exists, cannot create type definition.");
        }

        if (parents.length > 0) {
            parentids = new Integer[parents.length];

            for (int i = 0; i < parents.length; i++) {
                int id = types.indexOf(parents[i]);
                if (id == -1) {
                    log.warn("Type " + parents[i] +
                             " not defined, cannot create sub-type.");
                    throw new EngineException("Type " + parents[i] +
                            " not defined, cannot create sub-type.");
                }
                parentids[i] = id;
            }
        } else {
            parentids = new Integer[1];
            parentids[0] = IOBJECT;
        }

        int id = types.size();
        types.add(name);

        Integer iID = id;
        dag.addNodeWeight(iID);

        for (int i = 0; i < parentids.length; i++) {
            dag.addEdge(iID, parentids[i]);
        }

        return id;
    }

    
    
    
    
    
    /**
     * Store uncreated types temporarily
     * 
     * 
     * 
     */
    
    public static void storeTempTypes(String name, String[] parents){
	
    	Object[] obj = new Object[2];
	
    	obj[0] = name;
    	obj[1] = parents;
	
    	tempTypes.add(obj);
	
}    
    
    
/**
 * Retrieves and creates uncreated types temporarily
 * 
 * 
 * 
 */

    public static void makeTypes(){

    	Vector temp = new Vector();
    	while(!tempTypes.isEmpty()){	
    			Object obj[] = (Object[])tempTypes.remove(0);

    			String name = obj[0].toString();

    			Types.createDAGNode(name);
    			System.out.println(name);
    			temp.add(obj);
    	}

    	while(!temp.isEmpty()){
	
    		Object obj[] = (Object[])temp.remove(0);
    		String name = obj[0].toString();	
    		String[] parents = (String[])obj[1];
    		Types.createDAGEdges(name, parents);
	}

}       
    
    /**
     * Define a new type in the type system. The user must specify the name of
     * the type and the names of all direct superclasses.
     *
     * @param name String The name of the new type to be defined.
     *
     * @param parents String[] An array containing the name of all direct
     * superclasses of the type.
     *
     * @return int The integer code for the type, this is what is stored in a
     * Term objects type instance variable.
     */
    public static int createDAGEdges(String name, String[] parents) {
        Integer[] parentids;

        if (types.contains(name)) {
            log.warn("Type " + name +
                     " already exists, creating DAG edges.");
            }

        if (parents.length > 0) {
            parentids = new Integer[parents.length];

            for (int i = 0; i < parents.length; i++) {
                int id = types.indexOf(parents[i]);
                if (id == -1) {
                    log.warn("Type " + parents[i] +
                             " not defined, cannot create sub-type.");
                    throw new EngineException("Type " + parents[i] +
                            " not defined, cannot create sub-type.");
                }
                parentids[i] = id;
            }
        } else {
            parentids = new Integer[1];
            parentids[0] = IOBJECT;
        }

        Integer iID = types.indexOf(name);
        //dag.addNodeWeight(iID);

        for (int i = 0; i < parentids.length; i++) {
            dag.addEdge(iID, parentids[i]);
        }

        return 1;
    }
    
    
    /**
     * Get the type name for a specified type identification number.
     *
     * @param id int The integer typy identification number of the type.
     *
     * @return String The name of the type defined by that
     */
    public static String typeName(int id) {
        if (id < -1 || id >= types.size()) {
            throw new EngineException("No type has been defined with code " +
                                      id + ".");
        } else if (id == -1) {
            return "NOTHING";
        } else {
            return (String) types.get(id);
        }
    }

    /**
     * Get the type identification integer associated with a type name.
     *
     * @param name String The name of the type to get the identification number
     * for.
     *
     * @return int The identification integer associated with the type.
     */
    public static int typeID(String name) {

        if (name.equals(NOTHING)) {
            return -1;
        }
        if (types.contains(name)) {
            return types.indexOf(name);
        } else {
            throw new EngineException("There is no type " + name + " defined.");
        }
    }

    /**
     * Check to see if a type is defined for the identification integer passed.
     *
     * @param id int The type identification integer.
     *
     * @return boolean true if there is a type with an identification integer
     * equal to id, false otherwise.
     */
    public static boolean isTypeDefined(int id) {
        if (id < -1 || id >= types.size()) {
            return false;
        } else {
            return true;
        }
    }

    /**
     * Check to see if there is a type with a specified name already defined.
     *
     * @param name String The type name to check.
     *
     * @return boolean true if there is a type defined with with a name equal to
     * the passed name, false otherwise.
     */
    public static boolean isTypeDefined(String name) {
        if (name.equals(NOTHING)) {
            return true;
        } else {
            return types.contains(name);
        }
    }

    /**
     * This method is a synonyom for the
     * isSubClass(int subClass, int superClass) method.
     *
     * @param subClass int The integer identification number of the sub-type to
     * test.
     *
     * @param superClass int The integer identification number of the super-type
     * to test.
     *
     * @return boolean true if the type identified by subClass is a sub-type of
     * the type identified by superClass, for if subClass and superClass are the
     * same types, false otherwise.
     */
    public static boolean isa(int subClass, int superClass) {
        return isSubClass(subClass, superClass);

    }

    /**
     * Check to see if the type identified by subClass is is a subclass of the
     * type identified by superClass. (Transitive Closure)
     *
     * @param subClass int The integer identification number of the sub-type to
     * test.
     *
     * @param superClass int The integer identification number of the super-type
     * to test.
     *
     * @return boolean true if the type identified by subClass is a sub-type of
     * the type identified by superClass, for if subClass and superClass are the
     * same types, false otherwise.
     */
    public static boolean isSubClass(int subClass, int superClass) {

        int glb = greatestLowerBound(superClass, subClass);
        if (glb == subClass) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * Check to see if type subClass is a sub-type of type superClass. (Transitive Closure)
     *
     * @param subClass String The sub-type to check.
     *
     * @param superClass String The super-type to check.
     *
     * @return boolean true if subClass is a sub-type of superClass, or if they
     * are the same type, false otherwise.
     */
    public static boolean isSubClass(String subClass, String superClass) {
        int idsub = typeID(subClass);
        int idsuper = typeID(superClass);

        return isSubClass(idsub, idsuper);
    }

    /**
     * Check to see if one type is the super-type of another. (Transitive Closure)
     *
     * @param superClass int The integer identification of the super-type.
     *
     * @param subClass int The integer identification of the sub-type
     *
     * @return boolean true if the type identified by superClass is a super-type
     * of the type identified by subClass, or if they are the same type, false
     * otherwise.
     */
    public static boolean isSuperClass(int superClass, int subClass) {
        return isSubClass(subClass, superClass);
    }

    /**
     * Check to see if one type is the super-type of another type. (Transitive Closure)
     *
     * @param superClass String The super-type to check.
     *
     * @param subClass String The sub-type to check.
     *
     * @return boolean true if superClass is a super-type of subClass, of if
     * they are the same type, false otherwise.
     */
    public static boolean isSuperClass(String superClass, String subClass) {
        int idsub = typeID(subClass);
        int idsuper = typeID(superClass);

        return isSubClass(idsub, idsuper);
    }

    /**
     * Find the greatest lower bound of two types. Identified by integer codes.
     *
     * @param class1 int The integer code for type 1.
     *
     * @param class2 int The integer code for type 2.
     *
     * @return int The integer code of the greatest lower bound of the two types.
     * If this is negative one (-1) then they have no real greatest lower bound,
     * only the artificial lower bound of 'Nothing'.
     */
    public static int greatestLowerBound(int class1, int class2) {
        if (class1 == -1 || class2 == -1) {
            return -1;
        }
        Integer glb = ((Integer) dag.greatestLowerBound(class1,
        		class2));
        if (glb == null) {
            return -1;
        } else {
            return glb.intValue();
        }
    }

    /**
     * Find the greatest lower bound of typed types.
     *
     * @param class1 String The first type.
     *
     * @param class2 String The second type.
     *
     * @return String The name of the type that is the greatest lower bound of
     * the two types. If this is "Nothing" then they have no real greatest lower
     * bound, just the artificial lower bound of 'Nothing'.
     */
    public static String greatestLowerBound(String class1, String class2) {
        int classid1 = typeID(class1);
        int classid2 = typeID(class2);
        int glb = greatestLowerBound(classid1, classid2);

        if (glb == -1) {
            return NOTHING;
        } else {
            return Types.typeName(glb);
        }
    }

    /**
     * Find the greatest lower bound of a list of types, identified by integer
     * codes.
     *
     * @param classes int[] An array containing the integer codes of the types
     * to find the greatest lower bound for.
     *
     * @return int The integer code for the type that is the greatest lower
     * bound of the passed types. If this is negative one (-1) then the passed
     * types have no real lower bound, just the artificial lower bound
     * 'Nothing'.
     */
    public static int greatestLowerBound(int[] classes) {
        Object[] classesobj = new Object[classes.length];
        for (int i = 0; i < classes.length; i++) {
            if (classes[i] == -1) {
                return -1;
            }
            classesobj[i] = classes[i];
        }
        Integer glb = (Integer) dag.greatestLowerBound(classesobj);

        if (glb == null) {
            return -1;
        } else {
            return glb.intValue();
        }
    }

    /**
     * Find the greater lower bound for a group of types.
     *
     * @param classes String[] An array containing the types to find the
     * greatest lower bound of.
     *
     * @return String The name of the type that is the greatest lower bound of
     * the types that are passed. If this is "Nothing" then the passed types
     * have no real lower bound, only the artificial lower bound of 'Nothing'.
     */
    public static String greatestLowerBound(String[] classes) {
        Object[] classesobj = new Object[classes.length];
        for (int i = 0; i < classes.length; i++) {
            int type = Types.typeID(classes[i]);
            if (type == -1) {
                return NOTHING;
            }
            classesobj[i] = type;
        }
        Integer glb = (Integer) dag.greatestLowerBound(classesobj);
        
        if (glb == null) {
            return NOTHING;
        } else {
            return Types.typeName(glb.intValue());
        }
    }

    /**
     * This method is used to test for a direct sub class or a direct super class
     * 
     * @param superClass - the super class to be tested for
     * @param subClass - the sub class to be tested for
     * @return boolean - true if a edge exist from the superClass to the subClass
     */
    
	public static boolean edgeExist(String superClass, String subClass){
		
		int classid1 = typeID(superClass);
		int classid2 = typeID(subClass);
		
		Object b = classid1;
		Object c = classid2;
		
		boolean hasEdge =  dag.edgeExists(c,b);
					 
		return hasEdge;
		
	}

    /**
     * Find the greatest lower bound of two types. Identified by integer codes.
     *
     * @param class1 int The integer code for type 1.
     *
     * @param class2 int The integer code for type 2.
     *
     * @return int The integer code of the greatest lower bound of the two types.
     * If this is negative one (-1) then they have no real greatest lower bound,
     * only the artificial lower bound of 'Nothing'.
     */
    public static int leastUpperBound(int class1, int class2) {
        if (class1 == -1 || class2 == -1) {
            return -1;
        }
        Integer lub = ((Integer) dag.leastUpperBound(class1,
        		class2));
        if (lub == null) {
            return -1;
        } else {
            return lub.intValue();
        }
    }

    /**
     * Find the greatest lower bound of type types.
     *
     * @param class1 String The first type.
     *
     * @param class2 String The second type.
     *
     * @return String The name of the type that is the greatest lower bound of
     * the two types. If this is "Nothing" then they have no real greatest lower
     * bound, just the artificial lower bound of 'Nothing'.
     */
    public static String leastUpperBound(String class1, String class2) {
        int classid1 = typeID(class1);
        int classid2 = typeID(class2);
        int lub = leastUpperBound(classid1, classid2);

        if (lub == -1) {
            return NOTHING;
        } else {
            return Types.typeName(lub);
        }
    }

    /**
     * Find the greatest lower bound of a list of types, identified by integer
     * codes.
     *
     * @param classes int[] An array containing the integer codes of the types
     * to find the greatest lower bound for.
     *
     * @return int The integer code for the type that is the greatest lower
     * bound of the passed types. If this is negative one (-1) then the passed
     * types have no real lower bound, just the artificial lower bound
     * 'Nothing'.
     */
    public static int leastUpperBound(int[] classes) {
        Object[] classesobj = new Object[classes.length];
        for (int i = 0; i < classes.length; i++) {
            if (classes[i] == -1) {
                return -1;
            }
            classesobj[i] = classes[i];
        }
        Integer lub = (Integer) dag.leastUpperBound(classesobj);

        if (lub == null) {
            return -1;
        } else {
            return lub.intValue();
        }
    }

    /**
     * Find the lower bound of a group of type.
     *
     * @param classes String[] An array containing the types to find the
     * greatest lower bound of.
     *
     * @return String The name of the type that is the greatest lower bound of
     * the types that are passed. If this is "Nothing" then the passed types
     * have no real lower bound, only the artificial lower bound of 'Nothing'.
     */
    public static String leastUpperBound(String[] classes) {
        Object[] classesobj = new Object[classes.length];
        for (int i = 0; i < classes.length; i++) {
            int type = Types.typeID(classes[i]);
            if (type == -1) {
                return NOTHING;
            }
            classesobj[i] = type;
        }
        Integer lub = (Integer) dag.leastUpperBound(classesobj);

        if (lub == null) {
            return NOTHING;
        } else {
            return Types.typeName(lub.intValue());
        }
    }

}
 public class Util {

    /**
     * Line separator (new line) specified by the operating system
     */
    public static final String NEWLINE = System.getProperty("line.separator");

    /**
     * Read content from a given web address (URI)
     * 
     * @param uri
     *            Address to read content from
     * 
     * @return Content at the given address as a string
     * 
     * @throws IOException
     *             Throws an IOException when web address is not accessible or
     *             when an error occurred during the read process
     */
    public static String readFromURIWithTimeout(String uri, int connectionTimeoutMillis)
            throws IOException {
        // Create new HTTP connection with given timeout
        URL url = new URL(uri);
        URLConnection urlConnection = url.openConnection();

        // Set connection timeout [ms] for HTTP connection
        urlConnection.setConnectTimeout(connectionTimeoutMillis);

        // Open input stream for reading
        InputStream inputStream = urlConnection.getInputStream();

        String result = readStream(new InputStreamReader(inputStream));
        return result;
    }

    /**
     * Show dialog for selecting a file and read file content
     * 
     * @param parent
     *            Reference to parent component (can be null)
     * 
     * @return File content as a string or null if action was cancelled
     * 
     * @throws IOException
     *             Throws an IOException when file is not accessible or when an
     *             error occurred during the read process
     */
    public static String selectAndReadFile(Component parent) throws IOException {
        // Create a file open dialog
        JFileChooser fileOpenDialog = new JFileChooser();
        int dialogResult = fileOpenDialog.showOpenDialog(parent);

        // Show file open dialog and read content from file
        String result = null;
        if (dialogResult == JFileChooser.APPROVE_OPTION) {
            File file = fileOpenDialog.getSelectedFile();

            // Open file for reading and read content
            result = readFile(file);
        }
        return result;
    }

    /**
     * Show dialog for selecting a file and write file content to file
     * 
     * @param content
     *            Content which should be written to a file
     * 
     * @param parent
     *            Reference to parent component (can be null)
     * 
     * @throws IOException
     *             Throws an IOException when file is not accessible or when an
     *             error occurred during the write process
     */
    public static void selectAndSaveToFile(String content, Component parent) throws IOException {
        // Create file save dialog
        @SuppressWarnings("serial")
        JFileChooser fileSaveDialog = new JFileChooser() {
            @Override
            public void approveSelection() {
                File f = getSelectedFile();
                if (f.exists() && getDialogType() == SAVE_DIALOG) {
                    int result = JOptionPane.showConfirmDialog(this,
                            "File already exists, overwrite?", "Existing file",
                            JOptionPane.YES_NO_OPTION);
                    switch (result) {
                    case JOptionPane.YES_OPTION:
                        super.approveSelection();
                        return;
                    case JOptionPane.NO_OPTION:
                        return;
                    }
                }
                super.approveSelection();
            }
        };
        fileSaveDialog.setFileSelectionMode(JFileChooser.FILES_ONLY);

        // Show file save dialog and write content to file
        int dialogResult = fileSaveDialog.showSaveDialog(parent);
        if (dialogResult == JFileChooser.APPROVE_OPTION) {
            File file = fileSaveDialog.getSelectedFile();

            // Open file for writing and write content
            writeToFile(new FileWriter(file), content);
        }
    }

    /**
     * Read a given file and return its content as a string
     * 
     * @param file
     *            The file to read content from
     * 
     * @see Util#readStream(Reader)
     */
    public static String readFile(File file) throws FileNotFoundException, IOException {
        FileInputStream fileInputStream = new FileInputStream(file);
        BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream);
        
        // Detect character set for Unicode handling
        CharsetDetector charsetDetector = new CharsetDetector();
        charsetDetector.setText(bufferedInputStream);
        CharsetMatch charsetMatch = charsetDetector.detect();
        
        if (charsetMatch == null) {
            throw new IOException("Character set is not supported.");
        }
        
        Reader reader = charsetMatch.getReader();
        return readStream(reader);
    }

    /**
     * Directly read content from a given reader object
     * 
     * @param reader
     *            A reader object
     * 
     * @return Content which has been read from the reader
     * 
     * @throws IOException
     *             Throws an IOException when an error occurred during the read
     *             process
     */
    private static String readStream(Reader reader) throws IOException {
        BufferedReader bufferedReader = new BufferedReader(reader);

        // Read content to buffer
        StringBuilder buffer = new StringBuilder();
        String currentLine;
        while ((currentLine = bufferedReader.readLine()) != null) {
            buffer.append(currentLine);
            buffer.append(NEWLINE);
        }

        // Close stream and return file content
        bufferedReader.close();
        return buffer.toString();
    }

    /**
     * Directly writes content to a given writer object
     * 
     * @param writer
     *            A writer object
     * 
     * @param content
     *            Content which should be written
     * 
     * @throws IOException
     *             Throws an IOException when an error occurred during the write
     *             process
     */
    private static void writeToFile(Writer writer, String content) throws IOException {
        BufferedWriter bufferedWriter = new BufferedWriter(writer);

        // Write content and close steam
        bufferedWriter.write(content);
        bufferedWriter.close();
    }
    
    public static int getTypeForInference(String inputstring){
    	int type = -1;
		try {
			Integer.parseInt(inputstring);
			type = 2;
		} catch (NumberFormatException e) {
			//Symbol is no int. Try parsing to double.
			try{
				Double.parseDouble(inputstring);
				type = 3;
			} catch(NumberFormatException e2){
				//Symbol is no double. We assign the String type
				type = 4;
			}
		}
		return type;
    }
}
 public class RuleMLNormalizer {

    /**
     * Supported XSL versions (1.x and 2.0)
     */
    public enum XSLVersion {
        XSL1X, XSL20
    }

    // System property string which specifies the XML transformer factory to use
    private final String TransformerFactoryProperty = "javax.xml.transform.TransformerFactory";
    
    // SAXON XML transformer (http://saxon.sourceforge.net/)
    private final String SaxonTransformer = "net.sf.saxon.TransformerFactoryImpl";
    // XALAN (default) XML transformer
    private final String XalanTransformer = "org.apache.xalan.processor.TransformerFactoryImpl";

    /**
     * Initializes a RuleML normalizer which uses XSL either in version 1.x or
     * in version 2.0
     * 
     * @param xslVersion
     *            The XSL version to use (XSL 1.x or XSL 2.0)
     */
    public RuleMLNormalizer(XSLVersion xslVersion) {
        if (xslVersion == XSLVersion.XSL20) {
            System.setProperty(TransformerFactoryProperty, SaxonTransformer);
        } else {
            // Use XALAN (default) for XML transforming
            System.setProperty(TransformerFactoryProperty, XalanTransformer);
        }
    }
    
    /**
     * Initializes a RuleML normalizer which uses XSL in version 1.x
     */
    public RuleMLNormalizer() {
        this(XSLVersion.XSL1X);
    }

    /**
     * Normalizes a given RuleML string with the given format.
     * 
     * @param input
     *            The input which should be normalized
     * 
     * @param rmlFormat
     *            The RuleML format (e.g. RuleML 1.0)
     * 
     * @return The normalized RuleML string
     * 
     * @throws TransformerFactoryConfigurationError
     * @throws TransformerException
     * @throws IOException 
     * @throws ParsingException 
     * @throws UnsupportedEncodingException 
     */
    public String normalize(String input, RuleMLFormat rmlFormat)
            throws TransformerFactoryConfigurationError, TransformerException, ParsingException, UnsupportedEncodingException {
        String normalizerXSLT = getXSLTNormalizer(rmlFormat);
        InputStream xsltStream = RuleMLNormalizer.class.getResourceAsStream(normalizerXSLT);
        StreamSource xsltStreamSource = new StreamSource(xsltStream);

        ByteArrayInputStream xmlStream = new ByteArrayInputStream(input.getBytes());
        StreamSource xmlSource = new StreamSource(xmlStream);

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        StreamResult outputTarget = new StreamResult(outputStream);

        TransformerFactory transformerFactory = TransformerFactory.newInstance();        
        Transformer xmlTransformer = transformerFactory.newTransformer(xsltStreamSource);

        xmlTransformer.transform(xmlSource, outputTarget);
        String result = outputTarget.getOutputStream().toString();
        
        // Format normalized document
        try {
            result = XmlUtils.formatDocument(result);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
    
    /**
     * Get the XSLT for the given RuleML format. By now, RuleML 1.0 and
     * RuleML 0.91 are supported.
     * 
     * @param rmlFormat
     *            The RuleML format (e.g. RuleML 1.0)
     * 
     * @return The XSLT corresponding to the RuleML format
     * 
     * @throws UnsupportedEncodingException
     *             If the RuleML format is not supported
     */
    private String getXSLTNormalizer(RuleMLFormat rmlFormat) throws UnsupportedEncodingException {
        switch (rmlFormat) {
        case RuleML100:
            return "100_normalizer.quarantine.xslt";
        case RuleML91:
            return "091_normalizer.xslt";
        default:
            String msg = String.format("RuleML format is not supported (%s).", rmlFormat.getVersionName());
            throw new UnsupportedEncodingException(msg);
        }
    }
}
 public class RuleMLValidator {
    
    private final String SAX_PARSER = "org.apache.xerces.parsers.SAXParser";
    
    public void validateRuleMLDocument(String rmlContent) throws Exception {
        XMLReader xmlReader;
        try {
            xmlReader = XMLReaderFactory.createXMLReader(SAX_PARSER);
            xmlReader.setFeature("http://apache.org/xml/features/validation/schema", true);
        } catch (SAXException e) {
            throw new Exception("Unable to create XML validator");
        }

        Builder builder = new Builder(xmlReader, true);
        StringReader stringReader = new StringReader(rmlContent);
        try {
            builder.build(stringReader);
        } catch (ValidityException e) {
            throw new ValidityException("Document does not validate against the specified XSD.");
        } catch (Exception e) {
            throw new Exception("Error occurred during document validation.");
        }
    }
}

import java.awt.Component;
import java.io.IOException;
import java.util.prefs.PreferenceChangeEvent;
import java.util.prefs.PreferenceChangeListener;
import javax.swing.JOptionPane;
import org.apache.log4j.Logger;
import org.apache.log4j.PatternLayout;
import org.ruleml.oojdrew.Configuration;
import org.ruleml.oojdrew.Reasoner;
import org.ruleml.oojdrew.SyntaxFormat;
import org.ruleml.oojdrew.parsing.POSLParser;
import org.ruleml.oojdrew.parsing.RDFSParser;
import org.ruleml.oojdrew.parsing.RuleMLFormat;
import org.ruleml.oojdrew.parsing.RuleMLParser;
import org.ruleml.oojdrew.parsing.SubsumesParser;
import org.ruleml.oojdrew.util.Types;
import org.ruleml.oojdrew.util.Util;
import org.ruleml.oojdrew.xml.RuleMLNormalizer;
import org.ruleml.oojdrew.xml.RuleMLValidator;

        this.rmlParser = rmlParser;
        this.subsumesParser = subsumesParser;
        this.reasoner = reasoner;
        
        TextPaneAppender tpa = new TextPaneAppender(new PatternLayout("%-5p %d [%t]:  %m%n"), "Debug");
        tpa.setTextPane(debugConsole.getTextPane());
        logger.addAppender(tpa);

        ui.setController(this);
        preferenceDialogUI.setSettingsController(this);
        config.addPreferenceChangeListener(this);
        preferenceChange(null);
    }

    public void syncUIWithSettings() {
        preferenceDialogUI.setSpinnerTextAreaFontSizeValue(config.getTextAreaFontSize());
        preferenceDialogUI.setSpinnerUIFontSizeValue(config.getUIFontSize());
        preferenceDialogUI.setLinkFontSizes(config.getLinkFontSizes());
        preferenceDialogUI.setLookAndFeel(config.getLookAndFeel());
        preferenceDialogUI.setRuleMLFormat(config.getRuleMLFormat());
        preferenceDialogUI.setLoggingLevel(config.getLogLevel());
    }

    public void applySettingsFromUI() {
        config.setTextAreaFontSize(preferenceDialogUI.getSpinnerTextAreaFontSizeValue());
        config.setUIFontSize(preferenceDialogUI.getSpinnerUIFontSizeValue());
        config.setLinkFontSizes(preferenceDialogUI.getLinkFontSizes());
        config.setLookAndFeel(preferenceDialogUI.getSelectedLookAndFeel());
        config.setSelectedRuleMLFormat(preferenceDialogUI.getRuleMLFormat());
        config.setLogLevel(preferenceDialogUI.getLoggingLevel());
    }

    public void showDebugConsole() {
        debugConsole.setVisible(true);
    }

    public void showPreferenceDialog() {
        preferenceDialogUI.setVisible(true);
    }

    public void preferenceChange(PreferenceChangeEvent evt) {
        int uiPreferenceChanges = config.getUiPreferenceChangeCount();
        if (uiPreferenceChanges > 0) {
            if (uiPreferenceChanges == 1) {
                preferenceDialogUI.updateUI();
                ui.updateUI();
                debugConsole.updateUI();
            }
            config.decreaseUiPreferenceChangeCount();
        } else {
            logger.setLevel(config.getLogLevel());
        }
    }

    private boolean showOpenForAppendDialog() {
        return 0 == JOptionPane.showConfirmDialog(ui.getFrmOoJdrew(), "Append content?",
                "Append or replace?", JOptionPane.YES_NO_OPTION);
    }

    private void setTextOfCurrentEditingTab(String text, boolean append) {
        if (text == null) {
            return;
        }

        if (append) {
            ui.appendToCurrentEditingTab(text);
        } else {
            ui.setTextForCurrentEditingTab(text);
        }
    }

    /**
     * Shows open URI dialog and reads from URL to editing tab
     */
    public void openURI() {
        boolean append = showOpenForAppendDialog();
        String uri = JOptionPane.showInputDialog("Please enter an URI");

        if (uri != null) {
            int httpConnectionTimeout = config.getHttpConnectionTimeout();
            String pageContent;
            try {
                pageContent = Util.readFromURIWithTimeout(uri, httpConnectionTimeout);
            } catch (IOException e) {
                defaultExceptionHandler(e);
                return;
            }

            setTextOfCurrentEditingTab(pageContent, append);
        }
    }

    public void openFile() {
        boolean append = showOpenForAppendDialog();
        Component parent = ui.getFrmOoJdrew();

        String fileContent;
        try {
            fileContent = Util.selectAndReadFile(parent);
        } catch (IOException e) {
            defaultExceptionHandler(e);
            return;
        }

        setTextOfCurrentEditingTab(fileContent, append);
    }

    public void saveFileAs() {
        String content = ui.getTextForCurrentEditingTab();
        Component parent = ui.getFrmOoJdrew();

        try {
            Util.selectAndSaveToFile(content, parent);
        } catch (IOException e) {
            defaultExceptionHandler(e);
        }
    }

    public void parseTypeInformation() {
        String typeInformation = ui.getTypeDefinitionTextAreaText();

        SyntaxFormat format = ui.getTypeInformationInputFormat();
