com.monrai.cypher.lang.nl.registry.Pattern.java Source code

Java tutorial

Introduction

Here is the source code for com.monrai.cypher.lang.nl.registry.Pattern.java

Source

/* Pattern.java
 * Copyright 2000-2004 Monrai Technologies, Inc. All Rights Reserved.
 *
 * This software is the proprietary information of Monrai Technologies, Inc.
 * Use is subject to license terms.
 *
 */

package com.monrai.cypher.lang.nl.registry;

import java.io.Serializable;
import java.util.Date;
import java.util.Properties;
import java.util.Vector;

import javax.swing.tree.DefaultMutableTreeNode;

import org.joda.time.DateTime;
import org.joda.time.Interval;
import org.openrdf.model.Graph;
import org.openrdf.model.URI;
import org.openrdf.model.impl.GraphImpl;
import org.openrdf.model.vocabulary.RDF;
import org.openrdf.model.vocabulary.RDFS;

import com.monrai.cypher.beans.util.Pointer;
import com.monrai.cypher.crawler.TextCrawler;
import com.monrai.cypher.lang.nl.en.LeafNode;
import com.monrai.cypher.lang.nl.interfaces.Node;
import com.monrai.cypher.lang.nl.interfaces.Sense;
import com.monrai.cypher.lang.nl.interfaces.Token;
import com.monrai.cypher.lang.nl.interfaces.Word;
import com.monrai.cypher.lang.nl.registry.transcoder.CypherScriptUtilNotFoundException;
import com.monrai.cypher.lang.nl.registry.transcoder.Transcoder;
import com.monrai.cypher.listener.LexicalMatchListener;
import com.monrai.cypher.rdf.RDFRegistry;
import com.monrai.cypher.rdf.articulator.Articulator;
import com.monrai.cypher.start.Cypher;
import com.monrai.cypher.start.CypherHelper;
import com.monrai.cypher.util.Permutator;
import com.monrai.cypher.util.text.Substituter;
import com.monrai.util.text.NumberGenerator;

/**
 * Class Pattern represents a table in the <code>{@link com.monrai.cypher.lang.registry.PatternRegistry}</code>. This could have
 * been merged with the <code>TokenGroup</code> class, like <code>Consitituient</code> merges with <code>
 * Token</code> instances, however, we would have to then be mapped and stored somewhere, then retrieved
 * via a key, as opposed to just storing a pointer like it is now. By simply storing a table pointer,
 * we can just instanate a new <code>Pattern(pointer)</code>, and populate the <code>Pattern</code> on the fly,
 * instead of storing a key that maps to a stored <code>Pattern</code>, which would be more referent intensive.
 * 
 * Created on Aug 26, 2004 10:11:29 PM
 * @author Sherman
 *
 */

public class Pattern extends DefaultMutableTreeNode implements Constituent, Serializable {

    /**
     * Owned by the root pattern, this is a list of configuration properties passed from the 
     * user to the transcoders template process. E.g. targetDatabase=myAddressBook
     */
    Properties properties;

    private int index;

    private URI id;

    private String primary_key_field_value;
    String source_string_field_value;
    //   String context_field_value;
    URI function_field_value;
    String data_string_field_value;
    //   String rdf_resource_field_value;
    Pointer context_field_value;
    URI uri;

    Constituent[] cons;
    Word[] ambiguousTerms;
    URI partOfSpeech;

    Transcoder[] transcoders;

    boolean isImplicit = false;

    LeafNode metadata;

    Token initialToken;

    Date dateTime;
    int actors = 0, noise = 0, exceptions = 0;

    Pointer pointer;

    long duration;

    protected String paraphrase;

    //   DefaultMutableTreeNode tree;

    /**
     * 
     */
    //
    //   public Pattern(String table, int primary_key) {
    //      this(PatternRegistry.getPointer(table, primary_key));
    //   }

    public static String PROP_TARGET_REPOSITORY = "target";
    public static String PROP_LIMIT = "limit";
    public static String PROP_OFFSET = "offset";

    /**
     * @param pointer
     */
    public Pattern(Pointer pointer) {
        super();
        setId(createId());
        setPointer(pointer);
        ambiguousTerms = new Word[0];
        //      tree = new DefaultMutableTreeNode(this);

        Vector fieldNames = new Vector();
        Vector fieldValues = new Vector();
        //      Pointer p = new Pointer(pointer);
        CypherHelper.pattern_registry.getColumnValues(pointer, fieldNames, fieldValues);

        Vector store = new Vector();

        parseEachField: for (int i = 0; i < fieldNames.size(); i++) {
            String name = (String) fieldNames.elementAt(i);
            Object value = fieldValues.elementAt(i);
            Pointer value_pointer = (!(value instanceof String)) ? null : new Pointer((String) value);

            // no leaves bearing fields should have been sent, but check anyway
            if (RegistrySchema.isDataBearingColumn(name)) {
                if (name.endsWith(RegistrySchema.SUFFIX_SOURCE_STRING_COLUMN)) {
                    String s = (String) value;
                    s = Pattern.unprepareInput(s);
                    setStringValue(s);
                } else if (name.endsWith(RegistrySchema.SUFFIX_FUNCTION_COLUMN)) {
                    setFunction(RDFRegistry.getValueFactory().createURI((String) value));
                } else if (name.endsWith(RegistrySchema.SUFFIX_URI_COLUMN)) {
                    setUri(RDFRegistry.getValueFactory().createURI((String) value));
                } else if (name.endsWith(RegistrySchema.SUFFIX_DATA_STRING_COLUMN)) {
                    setDataString((String) value);
                } else if (name.endsWith(RegistrySchema.SUFFIX_CONTEXT_COLUMN)) {
                    setContext(new Pointer((String) value));
                } else if (name.endsWith(RegistrySchema.SUFFIX_TYPE_COLUMN)) {
                    setPartOfSpeech(RDFRegistry.getValueFactory().createURI((String) value));
                }
                //            else if(name.endsWith(MainRegistry.RDF_RESOURCE_FIELD_SUFFIX)){
                //               setRdfResource(value);
                //            }
                else if (name.equals(RegistrySchema.LIST_DELIMITER)) {
                    Vector fn = new Vector();
                    Vector fv = new Vector();
                    gatherContainerConstituents: for (i++; i < fieldNames.size(); i++) {
                        fn.add(fieldNames.elementAt(i));
                        fv.add(fieldValues.elementAt(i));
                        if (i + 1 < fieldNames.size()) {
                            if (((String) fieldNames.elementAt(i + 1)).equals(RegistrySchema.LIST_DELIMITER)) {
                                break gatherContainerConstituents;
                            }
                        }
                    }
                    //               System.out.println("Pattern.init() POINTER: " + pointer);
                    DisclosedPattern m = new DisclosedPattern(pointer, getPartOfSpeech(), fn, fv);
                    // the function for the container list is stored in the 
                    // value of the LIST_DELIMITER field that marks the 
                    // start of the macros list, see MainRegistry.getFields(String,Vector,Vector,boolean)
                    // set the function to the local name, without the TABLE_ prepended

                    // sometimes, the container can be empty, if it only has containers as childern
                    // the getFields() method does not return any container childern in the vector it returns,
                    // however, it will return the PK of every constituient it encounters, without regard for if
                    // the container has any non-container childern... 
                    // here, we interpret containers with only container childern as being empty, and no empty containers
                    // are allowed as a flesh and blood constituient
                    if (!m.isEmpty()) {
                        URI function = RegistrySchema.getId((String) value);
                        m.setFunction(function);
                        add(m);
                        store.add(m);
                        if (getInitialToken() == null)
                            setInitialToken(m.getInitialToken());
                        this.actors += m.getActors();
                        this.noise += m.getNoise();
                        this.exceptions += m.getExceptions();
                    }
                }
                continue parseEachField;
            } else if (name.endsWith(RegistrySchema.PRIMARY_KEY_FIELD_STRING)) {
                setPrimaryKey((String) value);
            } else if (value_pointer != null && value_pointer.isValid()) {
                Vector fn = new Vector();
                Vector fv = new Vector();
                Pattern p = new Pattern(value_pointer);
                p.setTimeStamp(new Date());
                store.add(p);
                add(p); // add to the tree

                if (getInitialToken() == null)
                    setInitialToken(p.getInitialToken());
                //            if(p.getType() != null && p.getType().indexOf("NOISE") >= 0) this.noise++;
                //            else if(p.getType() != null && p.getType().indexOf("EXCEPTION") >= 0) this.exceptions++;
                else
                    this.actors++;
            } else if (PatternRegistry.isToken((String) value)) {
                Token tk = PatternRegistry.getToken((String) value);

                // set the function to the local name, without the TABLE_ prepended
                URI function = RegistrySchema.getId(name);
                tk.setFunction(function);
                //            tk.setMetadata(CypherHelper.stx.getNode(function));
                tk.setContextType(getPartOfSpeech());
                tk.setContext(pointer);
                store.add(tk);
                add(new DefaultMutableTreeNode(tk));

                if (getInitialToken() == null)
                    setInitialToken(tk);

            }
        }

        try {
            this.cons = (Constituent[]) store.toArray(new Constituent[store.size()]);
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        // set up metadata
        metadata = CypherHelper.stx.getLeaves().getValueAt(getPartOfSpeech(), 0).copy();
        metadata.setOccuredAt(new Date());
        metadata.setPattern(this);

        setParaphrase("\"" + getStringValue() + "\"");
        setTimeStamp(new Date());
    }

    public Pattern copy() {
        return new Pattern(this.pointer);
    }

    public URI createId() {
        return RDFRegistry.getValueFactory()
                .createURI(RDFRegistry.mlo_ns.getPrefix() + "pattern/" + NumberGenerator.getUniqueNumber());
    }

    /**
     * @return
     */
    public Constituent[] getConstituents() {
        return cons;
    }

    public void addConstituients(Constituent[] cons) {
        for (int i = 0; i < cons.length; i++) {
            if (cons[i] == null) {
                continue;
            }
            addConstituient(cons[i]);
        }
    }

    public void addConstituient(Constituent con) {
        int len = cons.length;
        con.setFunction(con.getFunction());
        Constituent[] update = cons;
        cons = new Constituent[len + 1];
        System.arraycopy(update, 0, cons, 0, len);
        cons[len] = con;
    }

    public void insertConstituient(Constituent con, int pos) {
        int len = cons.length;
        con.setFunction(con.getFunction());
        Constituent[] update = cons;
        cons = new Constituent[len + 1];
        // the prefix of the src array is from 0 and copy partOfSpeech items
        // the suffix of the src array is from (partOfSpeech+1) and copy len-partOfSpeech items 
        int srcStart = 0;
        int tarStart = 0;
        int total = pos;
        System.arraycopy(update, srcStart, cons, tarStart, total);

        srcStart = pos; // begin where you left off
        tarStart = pos + 1; // skip a cubby
        total = update.length - srcStart;
        if (srcStart + total <= update.length)
            System.arraycopy(update, srcStart, cons, tarStart, total);
        cons[pos] = con;
    }

    /**
     * @param function   local name for the function of the constituients returned by this method
     */
    public void removeConstituients(URI function) {
        removeConstituients(function, false);
    }

    /**
     * @param function   local name for the function of the constituients returned by this method
     */
    public void removeConstituients(URI function, boolean discloseConstituents) {
        Vector store = new Vector();
        storeConstituent(store, cons, function, discloseConstituents, true);
        cons = (Constituent[]) store.toArray(new Constituent[store.size()]);
    }

    /**
     * @param function   local name for the function of the constituients returned by this method
     */
    public Constituent[] getConstituents(URI function) {
        return getConstituents(function, false);
    }

    public Constituent[] getConstituents(URI function, boolean discloseConstituents) {
        return getConstituents(function, discloseConstituents, false);
    }

    /**
     * @param function   local name for the function of the constituients returned by this method
     * @return
     */
    public Constituent[] getConstituents(URI function, boolean discloseConstituents, boolean excludeFilter) {
        //      function = function.toUpperCase();
        Vector store = new Vector();
        storeConstituent(store, cons, function, discloseConstituents, excludeFilter);
        return (Constituent[]) store.toArray(new Constituent[store.size()]);
    }

    public Vector storeConstituent(Vector store, Constituent[] cons, URI function, boolean discloseConstituents,
            boolean excludeFilter) {
        for (int i = 0; i < cons.length; i++) {
            Constituent con = cons[i];
            //         String fv = con.getFunctionGlobalName();
            boolean add = (excludeFilter) ? (!con.getFunction().equals(function))
                    : (con.getFunction().equals(function));
            //         if(add){
            if (discloseConstituents && con instanceof DisclosedPattern) {
                Constituent[] macros_cons = ((DisclosedPattern) cons[i]).getConstituents(function,
                        discloseConstituents, excludeFilter);
                storeConstituent(store, macros_cons, function, discloseConstituents, excludeFilter);
            } else if (add)
                store.add(con);
            //         }
        }
        return store;
    }

    /**
     * @param function   local name for the function of the constituients returned by this method
     * @return
     */
    public Constituent[] getConstituents(boolean discloseConstituents) {
        //      function = function.toUpperCase();
        Vector store = new Vector();
        storeUnfilteredConstituents(store, cons, discloseConstituents, false);
        return (Constituent[]) store.toArray(new Constituent[store.size()]);
    }

    public Vector storeUnfilteredConstituents(Vector store, Constituent[] cons, boolean discloseConstituents,
            boolean invert) {
        for (int i = 0; i < cons.length; i++) {
            Constituent con = cons[i];
            //         boolean add = (invert) ? (!con.getFunctionGlobalName().equalsIgnoreCase(getUse() + "_" + function)) : (con.getFunctionGlobalName().equalsIgnoreCase(getUse() + "_" + function));
            //         if(add){
            if (discloseConstituents && con instanceof DisclosedPattern) {
                Constituent[] macros_cons = ((DisclosedPattern) cons[i]).getConstituents(true);
                storeUnfilteredConstituents(store, macros_cons, discloseConstituents, invert);
            } else
                store.add(con);
            //         }
        }
        return store;
    }

    public Vector<URI> set(URI function, Constituent con, Vector<URI> exclude) {
        Vector<URI> dirty = new Vector<URI>();

        // had issue where caller wanted to swap a con within the pattern with another
        // constituient, so the|1 dog|2 ran|3 ==> the|1 ran|3 ran|3, now you can't distinguish
        // the last constituient if you wish to swap three
        // therefore, give each source constituient a new id
        Constituent source = con.copy();
        dirty.add(source.getId());
        for (int i = 0; i < cons.length; i++) {
            if (cons[i] instanceof DisclosedPattern) {
                ((DisclosedPattern) cons[i]).set(function, con, exclude);
            }
            if (!exclude.contains(cons[i].getId()) && cons[i].getFunction().equals(function)) {
                //            // be sure the target constituient keeps it's functional role
                //            source.setFunction(cons[i].getFunction());
                cons[i] = source;
            }
        }
        return dirty;
    }

    public String permutateConstituents() {
        //      String[] elements = {"a", "b", "c", "d", "e", "f", "g"};
        Constituent[] ca = cons;
        int[] indices;
        if (ca.length == 1 && ca[0] instanceof DisclosedPattern) {
            ca = ((DisclosedPattern) ca[0]).cons;
        }
        Permutator x = new Permutator(ca.length);
        StringBuffer combination = new StringBuffer();
        Constituent[] permed = new Constituent[this.cons.length];
        combination.append("<html>\n<head>\n\t<title>Results: " + this.getStringValue() + "</title>\n");
        combination.append("<style type=\"text/css\" media=\"screen\">@import \""
                + Cypher.getEngineProperties().getCSSBase() + "main.css\";</style>\n</head>\n<body>");
        combination.append("<div class=\"alterInput\">Alternatives for input: ");
        combination.append(this.getStringValue());
        combination.append("</div>\n");
        for (int j = 0; x.hasMore(); j++) {
            indices = x.getNext();
            for (int i = 0; i < indices.length; i++) {

                //         CypherHelper.stx. getMatchNodesForToken(0,0, )   ;        

                permed[i] = ca[indices[i]];

                //          combination.append ("\"");
                //          combination.append (ca[indices[i]].getStringValue());
                //          combination.append ("\" ");
            }

            this.cons = permed;
            combination.append("<div class=\"alterBlock\">\n");

            combination.append("<div class=\"alterNumber\">" + (j + 1) + "</div>\n");

            combination.append("<div class=\"alter\"><div class=\"alterLabel\">Permutation</div>\n");
            combination.append(this.buildHTMLString());
            combination.append("</div><!-- end alternative -->\n");
            // more methods
            Articulator a = new Articulator();
            combination.append("<div class=\"alter\"><div class=\"alterLabel\">Pluralize</div>\n");
            combination.append(a.pluralizeQuery(this, 3));
            combination.append("</div><!-- end alternative -->\n");

            combination.append("<div class=\"alter\"><div class=\"alterLabel\">Voice transform</div>\n");
            combination.append(a.transformVoice(this));
            combination.append("</div><!-- end alternative -->\n");

            combination.append("</div><!-- end alternative block -->\n");
            //combination.append("-------------------------------------------------------------------------------------------<br/>\n");
            //        System.out.println (combination.toString ());
        }

        combination.append("</body></html>");

        return combination.toString();
    }

    public String getDataString() {
        return data_string_field_value;
    }

    private void setDataString(String data_string_field_value) {
        this.data_string_field_value = data_string_field_value;
    }

    //   public URI getFunctionGlobalName() {
    //      return function_field_value;
    //   }
    public void setFunction(URI function_field_value) {
        this.function_field_value = function_field_value;
    }

    //   public String getFunctionLocalName() {
    //      String function  = function_field_value;
    //      if(function_field_value == null) return "";
    //      boolean has_context = (getContext() != null);
    //      if(has_context){
    //         String prefix = getContext().getUseName() + "_";
    //         if(function.startsWith(prefix)) function = function.substring(function.indexOf(prefix) + prefix.length());
    //      }
    //      return function;
    //   }
    public String getPrimaryKey() {
        return primary_key_field_value;
    }

    private void setPrimaryKey(String primary_key_field_value) {
        this.primary_key_field_value = primary_key_field_value;
    }

    public String getStringValue() {
        return source_string_field_value;
    }

    public void setStringValue(String value) {
        this.source_string_field_value = value;
    }

    public static String unprepareInput(String input) {
        //      unformatted_input = s;
        //      rule = s;
        String[] contractions = { "'S", "'T", "'LL", "'D", "'M", "'RE", "'s", "'t", "'ll", "'d", "'m", "'re" };

        // this is part of the rule, don't strip!!!!!
        input = Substituter.replace(" . ", ".", input);
        input = Substituter.replace(" ? ", "?", input);
        input = Substituter.replace(" ! ", "!", input);

        input = Substituter.replace(" , ", ",", input);
        input = Substituter.replace(" ; ", ";", input);
        input = Substituter.replace(" : ", ":", input);
        input = Substituter.replace(" \" ", "\"", input);
        input = Substituter.replace("'", "'", input);
        //rule = Substituter.replace("\'", " \' ", contractions, rule);
        input = Substituter.replace(" ( ", "(", input);
        input = Substituter.replace(" ) ", ")", input);
        input = Substituter.replace(" { ", "{", input);
        input = Substituter.replace(" } ", "}", input);
        input = Substituter.replace(" < ", "<", input);
        input = Substituter.replace(" > ", ">", input);
        input = Substituter.replace(" / ", "/", input);
        input = Substituter.replace(" \\ ", "\\", input);
        input = Substituter.replace(" - ", "-", input);
        input = Substituter.replace(" % ", "%", input);
        input = Substituter.replace(" & ", "&", input);
        input = Substituter.replace(" $ ", "$", input);
        input = Substituter.replace(" # ", "#", input);
        input = Substituter.replace(" @ ", "@", input);
        input = Substituter.replace(" + ", "+", input);
        input = Substituter.replace(" * ", "*", input);

        //      rule = Substituter.replace("0", " 0 ", rule);
        //      rule = Substituter.replace("1", " 1 ", rule);
        //      rule = Substituter.replace("2", " 2 ", rule);
        //      rule = Substituter.replace("3", " 3 ", rule);
        //      rule = Substituter.replace("4", " 4 ", rule);
        //      rule = Substituter.replace("5", " 5 ", rule);
        //      rule = Substituter.replace("6", " 6 ", rule);
        //      rule = Substituter.replace("7", " 7 ", rule);
        //      rule = Substituter.replace("8", " 8 ", rule);
        //      rule = Substituter.replace("9", " 9 ", rule);

        //rule = Substituter.replace("'S", " 'S ", rule);
        //      rule = Substituter.replace(" O'CLOCK", " O ' CLOCK ", rule);
        //      rule = Substituter.replace("AIN'T", " IS NOT ", rule);
        //      rule = Substituter.replace("WON'T", " WILL NOT ", rule);
        //      rule = Substituter.replace("N'T", " NOT ", rule);
        //      rule = Substituter.replace("'LL", " WILL ", rule);
        //      rule = Substituter.replace("'D", " WOULD ", rule);
        //      rule = Substituter.replace("'M", " AM ", rule);
        //      rule = Substituter.replace("'RE", " ARE ", rule);

        input = Substituter.replace("1 st", "1st", input);
        input = Substituter.replace("2 nd", "2nd", input);
        input = Substituter.replace("3 rd", "3rd", input);

        input = Substituter.replace("0 th", "0th", input); // >= 10th
        input = Substituter.replace("1 th", "1th", input); // >= 11th
        input = Substituter.replace("2 th", "2th", input); // >= 12th
        input = Substituter.replace("3 th", "3th", input); // >= 13th
        input = Substituter.replace("4 th", "4th", input);
        input = Substituter.replace("5 th", "5th", input);
        input = Substituter.replace("6 th", "6th", input);
        input = Substituter.replace("7 th", "7th", input);
        input = Substituter.replace("8 th", "8th", input);
        input = Substituter.replace("9 th", "9th", input);

        //rule = Substituter.replace("'s", " 's ", rule);
        //      rule = Substituter.replace("o ' clock", " o'clock ", rule);
        //      rule = Substituter.replace("ain't", " is not ", rule);
        //      rule = Substituter.replace("won't", " will not ", rule);
        //      rule = Substituter.replace("n't", " not ", rule);
        //      rule = Substituter.replace("'ll", " will ", rule);
        //      rule = Substituter.replace("'d", " would ", rule);
        //      rule = Substituter.replace("'m", " am ", rule);
        //      rule = Substituter.replace("'re", " are ", rule);

        return input;
    }

    public String toString() {
        return getStringValue() + "(" + getPartOfSpeech() + ")";
    }

    public Graph getGraph() {
        Graph g = new GraphImpl();

        g.add(getId(), RDFS.LABEL, RDFRegistry.getValueFactory().createLiteral(getStringValue(),
                Cypher.getEngineProperties().getLanguage()));
        g.add(getId(), RDF.TYPE, getPartOfSpeech());
        g.add(getId(), RDFRegistry.MLO_DURATION, RDFRegistry.getValueFactory().createLiteral(getDuration() + "",
                RDFRegistry.XSD_NONNEGATIVEINTEGER));

        //      Transcoder[] transcoders = (Transcoder[]) this.getTranscoders(TranscoderV2_RDF.class);
        //      for(int i = 0; i < transcoders.length; i++) {
        //         if(transcoders[i].getReferent() != null) {
        //            Value referent = (Value) transcoders[i].getReferent();
        //            if(referent != null) g.add(getId(), RDFRegistry.MLO_REFERENT, referent);
        //         }
        //      }

        if (getMetadata().getDescription() != null) {
            g.add(getId(), RDFRegistry.DC_DESCRIPTION, RDFRegistry.getValueFactory()
                    .createLiteral(getMetadata().getDescription() + "", RDFRegistry.XSD_NONNEGATIVEINTEGER));
            g.add(getId(), RDFS.COMMENT, RDFRegistry.getValueFactory()
                    .createLiteral(getMetadata().getDescription() + "", RDFRegistry.XSD_NONNEGATIVEINTEGER));
        }
        //      if(getFunctionGlobalName().equals("TOP LEVEL")) sb.append(" function=\"root\"");
        else {
            g.add(getId(), RDF.TYPE, getFunction());
        }
        Constituent[] cons = getConstituents(true);
        for (int i = 0; i < cons.length; i++) {
            Constituent con = cons[i];
            g.add(getId(), RDFRegistry.MLO_CONSTITUENT_PROPERTY, con.getId());
            g.addAll(con.getGraph());
        }
        //      g.add(getId(), RDFRegistry.MLO_CONTEXT, getContext().getId());
        return g;
    }

    public URI getFunction() {
        return this.function_field_value;
    }

    public Pattern getContext() {
        if (context_field_value == null)
            return null;
        return new Pattern(context_field_value);
    }

    public void setContext(Pointer context) {
        this.context_field_value = context;
    }

    /**
     * @return Returns the partOfSpeech.
     */
    public URI getPartOfSpeech() {
        return partOfSpeech;
    }

    /**
     * @param partOfSpeech The partOfSpeech to set.
     */
    public void setPartOfSpeech(URI type) {
        this.partOfSpeech = type;
    }

    //   public Pointer getPatternRegistryPointer(){
    //      return getPointer();
    //   }
    //
    /* (non-Javadoc)
     * @see com.monrai.cypher.lang.nl.registry.Constituent#isImplicit()
     */
    public boolean isImplicit() {
        return isImplicit;
    }

    /* (non-Javadoc)
     * @see com.monrai.cypher.lang.nl.registry.Constituent#setIsImplicit()
     */
    public void setIsImplicit(boolean isImplicit) {
        this.isImplicit = isImplicit;
    }
    //    /**
    //     * @return Returns the rdf_resource_field_value.
    //     */
    //    public String getRdfResource() {
    //        return rdf_resource_field_value;
    //    }
    //    /**
    //     * @param rdf_resource_field_value The rdf_resource_field_value to set.
    //     */
    //    public void setRdfResource(String rdf_resource_field_value) {
    //        this.rdf_resource_field_value = rdf_resource_field_value;
    //    }

    public Pattern refresh() {
        Pattern p = new Pattern(getPointer());
        return p;
    }

    /**
     * Transcoders are retrieved from the <code>Pattern</code> class via this method ONLY. For this reason,
     * the <code>Pattern.getTranscoder()</code> method may not be called from the transcoders class on its own pattern field,
     * otherwise an infinite loop will result.
     * 
     * @return Returns the transcoders.
     */

    public Transcoder[] getTranscoders(Class inclusionFilter) {
        return getTranscoders(inclusionFilter, new Vector<LexicalMatchListener>());
    }

    public Transcoder[] getTranscoders() {
        return getTranscoders(new Class[0], new Vector<LexicalMatchListener>());
    }

    public Transcoder[] getTranscoders(Vector<LexicalMatchListener> v) {
        return getTranscoders(new Class[0], v);
    }

    public Transcoder[] getTranscoders(Class inclusionFilter, Vector<LexicalMatchListener> v) {
        return getTranscoders(new Class[] { inclusionFilter }, v);
    }

    public Transcoder[] getTranscoders(Class[] inclusionFilter, Vector<LexicalMatchListener> v) {
        if (transcoders == null) {
            try {
                setTranscoders(PatternRegistry.createTranscoders(this, inclusionFilter, v));
            } catch (CypherScriptUtilNotFoundException e) {
                e.printStackTrace();
            }
        }
        return transcoders;
    }

    /**
     * @param transcoders The transcoders to set.
     */
    protected void setTranscoders(Transcoder[] transcoders) {
        this.transcoders = transcoders;
    }

    public void clearTranscoders() {
        setTranscoders(new Transcoder[0]);
    }
    //   
    //   
    //   public void refreshTranscoders(){
    //      getTranscoders();
    //   }

    //   public boolean validate(){
    //      return ClauseTranscoder_RDF.validateSentence(this);
    //   }

    void populateTree() {
        DefaultMutableTreeNode dsg = new DefaultMutableTreeNode();
    }

    //   /**
    //    * @return Returns the tree.
    //    */
    //   public DefaultMutableTreeNode getTree() {
    //      if(tree == null){
    //         populateTree();
    //      }
    //      return tree;
    //   }
    //   /**
    //    * @param tree The tree to set.
    //    */
    //   public void setTree(DefaultMutableTreeNode tree) {
    //      this.tree = tree;
    //   }
    /**
     * Retrieve all ambiguous <code>Word</code> constituients from this <code>Pattern</code> and its sub-patterns.
     * 
     * @return Returns the ambiguousTerms.
     */
    public Word[] getAmbiguousTerms() {
        if (ambiguousTerms.length > 0)
            return ambiguousTerms;
        Constituent[] cons = getConstituents();
        Vector at = new Vector();
        for (int i = 0; i < cons.length; i++) {
            if (cons[i] instanceof Word) {
                Sense[] senses = ((Word) cons[i]).getSenses();
                if (senses.length == 0)
                    at.add(cons[i]);
            } else if (cons[i] instanceof DisclosedPattern) {
                Word[] wa = ((DisclosedPattern) cons[i]).getAmbiguousTerms();
                if (wa.length > 0)
                    at.copyInto(wa);
            } else if (cons[i] instanceof Pattern) {
                Word[] wa = ((Pattern) cons[i]).getAmbiguousTerms();
                if (wa.length > 0)
                    at.copyInto(wa);
            }
        }
        ambiguousTerms = (Word[]) at.toArray(new Word[at.size()]);
        return ambiguousTerms;
    }

    /**
     * @param ambiguousTerms The ambiguousTerms to set.
     */
    public void setAmbiguousTerms(Word[] ambiguousTerms) {
        this.ambiguousTerms = ambiguousTerms;
    }

    /**
     * @return Returns the initialToken.
     */
    public Token getInitialToken() {
        return initialToken;
    }

    /**
     * @param initialToken The initialToken to set.
     */
    public void setInitialToken(Token initialToken) {
        this.initialToken = initialToken;
    }

    /**
     * @return Returns the dateTime.
     */
    public Date getTimeStamp() {
        return dateTime;
    }

    /**
     * @param dateTime The dateTime to set.
     */
    public void setTimeStamp(Date dateTime) {
        this.dateTime = dateTime;
    }

    /**
     * @return Returns the metadata.
     */
    public LeafNode getMetadata() {
        return metadata;
    }

    /**
     * @return Returns the actors.
     */
    public int getActors() {
        return actors;
    }

    /**
     * @param actors The actors to set.
     */
    public void setActors(int actors) {
        this.actors = actors;
    }

    /**
     * @return Returns the noise.
     */
    public int getNoise() {
        return noise;
    }

    /**
     * @param noise The noise to set.
     */
    public void setNoise(int noise) {
        this.noise = noise;
    }

    /**
     * @return Returns the exceptions.
     */
    public int getExceptions() {
        return exceptions;
    }

    /**
     * @param exceptions The exceptions to set.
     */
    public void setExceptions(int exceptions) {
        this.exceptions = exceptions;
    }

    public Pointer getPointer() {
        return pointer;
    }

    public void setPointer(Pointer pointer) {
        this.pointer = pointer;
    }

    StringBuffer stringValue;

    public String buildString() {
        return buildString(false);
    }

    public String buildString(boolean rebuild) {
        StringBuffer sb = new StringBuffer();
        Constituent[] cons = getConstituents();
        for (int i = 0; i < cons.length; i++) {
            Constituent con = cons[i];
            if (con instanceof Pattern) {
                sb.append(" " + ((Pattern) con).buildString(rebuild));
            } else if (con instanceof DisclosedPattern) {
                sb.append(" " + ((DisclosedPattern) con).buildString(rebuild));
            } else if (con instanceof Token) {
                sb.append(" " + ((Token) con).getStringValue());
            }
        }
        String str = sb.toString();
        if (rebuild)
            setStringValue(str);
        return str;
    }

    String htmlStringValue;

    public String buildHTMLString() {
        return buildHTMLString(false);
    }

    public String buildHTMLString(boolean rebuild) {
        StringBuffer sb = new StringBuffer();
        Constituent[] cons = getConstituents();
        for (int i = 0; i < cons.length; i++) {
            Constituent con = cons[i];
            if (con instanceof Pattern) {
                sb.append("<span class=\"phrase\">" + ((Pattern) con).buildHTMLString(rebuild)
                        + "<a href=\"\" title=\"" + RegistrySchema.getName(((Pattern) con).getFunction()) + " "
                        + ((Pattern) con).getId() + "\">*</a></span> ");
            } else if (con instanceof DisclosedPattern) {
                sb.append("<span class=\"phrase\">" + ((DisclosedPattern) con).buildHTMLString(rebuild)
                        + "<a href=\"\" title=\"" + RegistrySchema.getName(((DisclosedPattern) con).getFunction())
                        + " " + ((DisclosedPattern) con).getId() + "\">*</a></span> ");
            } else if (con instanceof Token) {
                sb.append("<span class=\"phrase\">" + ((Token) con).getStringValue() + "<a href=\"\" title=\""
                        + RegistrySchema.getName(((Token) con).getFunction()) + " " + ((Token) con).getId()
                        + "\">*</a></span> ");
            }
        }
        String str = sb.toString();
        if (rebuild)
            setHtmlStringValue(str);
        return str;
    }

    public URI getId() {
        return id;
    }

    public String getIdFrag() {
        String s = this.id.stringValue();
        if (s.indexOf("/") >= 0) {
            s = s.substring(s.lastIndexOf("/") + 1);
        }
        return s;
    }

    public void setId(URI id) {
        this.id = id;
    }

    public String getParaphrase() {
        return paraphrase;
    }

    public void setParaphrase(String paraphrase) {
        this.paraphrase = paraphrase;
    }

    public Properties getProperties() {
        return properties;
    }

    public void setProperties(Properties properties) {
        this.properties = properties;
    }

    public void setProperty(String key, String value) {
        this.properties.setProperty(key, value);
    }

    public String getProperty(String key) {
        return this.properties.getProperty(key);
    }

    public long getDuration() {
        return duration;
    }

    public void setDuration(long duration) {
        this.duration = duration;
    }

    public void setDuration(Date start) {
        this.setDuration(timeSpan(start, getTimeStamp()));
        Constituent[] cons = getConstituents();
        for (int i = 0; i < cons.length; i++) {
            Constituent con = cons[i];
            con.setDuration(start);
        }
    }

    public static long timeSpan(Date old, Date current) {
        if (old == null)
            return 0;
        DateTime dt = new DateTime(old.getTime());
        DateTime now = new DateTime(current.getTime());
        return new Interval(dt, now).toDurationMillis();
        //        Dim ts As TimeSpan = Date.Now.Subtract(lastTime);
        //        Return ts.TotalMilliseconds;
    }

    public URI getUri() {
        return uri;
    }

    public void setUri(URI uri) {
        this.uri = uri;
    }

    public void setMetadata(Node metadata) {
        this.metadata = (LeafNode) metadata;
    }

    public String getConstituientsList() {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < this.cons.length; i++) {
            sb.append(this.cons[i].getStringValue() + this.cons[i].getFunction().stringValue() + " ");
        }
        return sb.toString();
    }

    public int getIndex() {
        return index;
    }

    public void setIndex(int index) {
        this.index = index;
    }

    public String getHtmlStringValue() {
        return htmlStringValue;
    }

    public void setHtmlStringValue(String htmlStringValue) {
        this.htmlStringValue = htmlStringValue;
    }
}
// class Pattern