Package tool.model

Source Code of tool.model.ToolClass$ClassProperty

package tool.model;

import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.antlr.runtime.CommonTokenStream;
import org.antlr.runtime.RecognitionException;
import org.antlr.runtime.Token;
import org.antlr.runtime.tree.CommonTree;
import org.antlr.runtime.tree.CommonTreeAdaptor;
import org.antlr.runtime.tree.CommonTreeNodeStream;
import org.antlr.stringtemplate.StringTemplate;
import org.antlr.stringtemplate.StringTemplateGroup;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.FileLocator;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.content.IContentDescriber;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.Region;
import org.eclipse.ui.console.MessageConsole;
import org.eclipse.ui.console.MessageConsoleStream;
import org.eclipse.ui.editors.text.TextFileDocumentProvider;
import org.eclipse.ui.texteditor.IDocumentProvider;

import tool.ToolModelActivator;
import tool.ToolProjectSupport;
import tool.model.describer.ClassContentDescriber;
import tool.model.grammar.ErrorReporter;
import tool.model.grammar.ForteAST;
import tool.model.grammar.ForteCDFTree;
import tool.model.grammar.ForteParser.classFile_return;
import tool.model.grammar.IErrorReporter;


public class ToolClass extends ToolType implements IProjectComponent, PropertyChangeListener{
  protected Map<String, ToolAttribute> attributes;
  protected Map<String, ToolMethod> methods;
  protected Map<String, ToolWindowAttribute> windowAttributes;
  protected Map<String, ToolConstant> constants;
  protected Map<String, ToolEventHandler> eventHandlers;
  protected Map<String, ToolVirtualAttribute> virtualAttributes;
  protected Map<String, ToolEvent> events;
  protected Set<String> implementations;
  protected IFile windowFile;
  protected String superClass;
  protected boolean mapped = false;
  protected boolean parsed;
  protected List<ClassProperty> properties = new ArrayList<ClassProperty>();
  private IErrorReporter plan;
  public String source;
 
  protected static Map<String, String> specialNames = new HashMap<String, String>();
 
  static {
    specialNames.put("qqsp_Heap", "Array");
    specialNames.put("qqsp_Binary", "BinaryData");
    specialNames.put("qqsp_NullBinary", "BinaryNullable");
    specialNames.put("qqsp_Boolean", "BooleanData");
    specialNames.put("qqsp_NullBoolean", "BooleanNullable");
    specialNames.put("qqsp_Data", "DataValue");
    specialNames.put("qqsp_DateTime", "DateTimeData");
    specialNames.put("qqsp_NullDateTime", "DateTimeNullable");
    specialNames.put("qqsp_Decimal", "DecimalData");
    specialNames.put("qqsp_NullDecimal", "DecimalNullable");
    specialNames.put("qqsp_4GLHeap", "Array");
    specialNames.put("qqsp_4GLBinary", "BinaryData");
    specialNames.put("qqsp_4GLNullBinary", "BinaryNullable");
    specialNames.put("qqsp_4GLBoolean", "BooleanData");
    specialNames.put("qqsp_4GLNullBoolean", "BooleanNullable");
    specialNames.put("qqsp_4GLData", "DataValue");
    specialNames.put("qqsp_4GLDateTime", "DateTimeData");
    specialNames.put("qqsp_4GLNullDateTime", "DateTimeNullable");
    specialNames.put("qqsp_4GLDecimal", "DecimalData");
    specialNames.put("qqsp_4GLNullDecimal", "DecimalNullable");
    specialNames.put("qqlo_ObjectManager", "DistObjectMgr");
    specialNames.put("qqsp_Real", "DoubleData");
    specialNames.put("qqsp_NullReal", "DoubleNullable");
    specialNames.put("qqsp_4GLReal", "DoubleData");
    specialNames.put("qqsp_4GLNullReal", "DoubleNullable");
    specialNames.put("qqsp_ErrorDescriptor", "ErrorDesc");
    specialNames.put("qqlo_EventInstance", "EventHandle");
    specialNames.put("qqlo_EventHandlerInfo", "EventRegistration");
    specialNames.put("qqsp_Float", "FloatData");
    specialNames.put("qqsp_Array", "GenericArray");
    specialNames.put("qqsp_Exception", "GenericException");
    specialNames.put("qqsp_HashTable", "GenericHashTable");
    specialNames.put("qqlo_Map", "GenericMap");
    specialNames.put("qqsp_HashOvrChain", "HashTable");
    specialNames.put("qqsp_ImageData", "ImageData");
    specialNames.put("qqsp_Integer", "IntegerData");
    specialNames.put("qqsp_NullInteger", "IntegerNullable");
    specialNames.put("qqsp_Interval", "IntervalData");
    specialNames.put("qqsp_NullInterval", "IntervalNullable");
    specialNames.put("qqsp_4GLImageData", "ImageData");
    specialNames.put("qqsp_4GLNullImageData", "ImageNullable");
    specialNames.put("qqsp_4GLInteger", "IntegerData");
    specialNames.put("qqsp_4GLNullInteger", "IntegerNullable");
    specialNames.put("qqsp_4GLInterval", "IntervalData");
    specialNames.put("qqsp_4GLNullInterval", "IntervalNullable");
    specialNames.put("qqsp_4GLHashFuncs", "HashFuncs");
    specialNames.put("qqlo_Scope", "Library");
    specialNames.put("qqsp_Logger", "LogMgr");
    specialNames.put("qqlo_MappedObject", "MappedAttribute");
    specialNames.put("qqsp_Numeric", "NumericData");
    specialNames.put("qqlo_Ols", "ObjectLocationMgr");
    specialNames.put("qqlos_OpEnv", "OperatingEnvironment");
    specialNames.put("qqcm_IORendezvous", "Rendezvous");
    specialNames.put("qqsp_Short", "ShortData");
    specialNames.put("qqsh_Synchronization", "Synchronizer");
    specialNames.put("qqsh_TaskId", "TaskDesc");
    specialNames.put("qqsh_Task", "TaskHandle");
    specialNames.put("qqsp_String", "TextData");
    specialNames.put("qqsp_$GLString", "TextData");
    specialNames.put("qqsp_StringNoConversion", "TextDataNoConvert");
    specialNames.put("qqsp_StringFormat", "TextFormat");
    specialNames.put("qqsp_NullString", "TextNullable");
    specialNames.put("qqsp_4GLNullString", "TextNullable");
    specialNames.put("qqsp_UserTimer", "Timer");
    specialNames.put("qqsh_XactId", "TrahsactionDesc");
    specialNames.put("qqsh_XactHandle", "TrahsactionHandle");
    specialNames.put("qqlo_4GLObject", "Object");
    specialNames.put("qqlo_4GLClassType", "ClassType");
    specialNames.put("qqsh_4GLAttributeDesc", "AttributeDesc");
    specialNames.put("qqds_4GLDisplayNode", "DisplayNode");
    specialNames.put("qqds_4GLUserWindow", "UserWindow");
   
   
  }
 
 
 
  //public static final String CLASS_REGEX ="^class\\s+";
  public static final String CLASS_REGEX ="class\\s+([A-Za-z0-9_]+)\\s+.*inherits from\\s+([A-Za-z0-9_\\.]+)";
  public static final String WHOLE_CLASS_REGEX ="class\\s+(?s).+?\\s+end class;";
  public static final String PROPERTIES_REGEX ="^has property\\s+([\\s\\S]+;)";
  public static final String ID_PROPERTIES_REGEX ="^has property(?s).+?(?-s)id = (\\d)+; proxyId = (\\d)+;";
  public static final String SINGLE_PROP_REGEX ="(shared|monitored|transactional|distributed)=\\(allow=(on|off), override=(on|off)(, default=(on|off)|)\\);";
  public static final String IMPLEMENTATIONS ="implements\\s+([a-zA-Z0-9\\.]+);";
  public static final Pattern pattern = Pattern.compile(CLASS_REGEX);
  public static final Pattern whole_pattern = Pattern.compile(WHOLE_CLASS_REGEX, Pattern.MULTILINE);
  public static final Pattern propertiesPattern = Pattern.compile(PROPERTIES_REGEX, Pattern.MULTILINE);
  public static final Pattern idPropertiesPattern = Pattern.compile(ID_PROPERTIES_REGEX, Pattern.MULTILINE);
  public static final Pattern singlePropPattern = Pattern.compile(SINGLE_PROP_REGEX);
  public static final Pattern implementationsPattern = Pattern.compile(IMPLEMENTATIONS);
  private static ClassContentDescriber describer = new ClassContentDescriber(true);
 
  private static File toolTemplateFile;
  public static File toolTemplate(){
    if (ToolClass.toolTemplateFile == null){
      try {
        URL url = Platform.getBundle(ToolModelActivator.PLUGIN_ID).getEntry("StringTemplates/Tool/CDF.stg");
        toolTemplateFile = new File(FileLocator.toFileURL(url).toURI());
      } catch (URISyntaxException e) {
        ToolModelActivator.showError("Cannot locate Class Template file", e);
      } catch (IOException e) {
        ToolModelActivator.showError("Cannot locate Class Template file", e);
      }
    }
    return toolTemplateFile;
  }

  private IDocumentProvider provider;
  private int id;
  private int proxyId;
  private static String planName;
 
  public static ToolType fetch(IProject project, String fullClassName) {
    String[] nameParts = fullClassName.split("\\.");
    return fetch(project, nameParts[0].trim(), nameParts[1].trim());
  }
 
  public synchronized static ToolClass fetch(IProject project, String planName, String className){
    if (project == null)
      return (ToolClass) getForteTypeCache().get((planName + "." + className).toUpperCase());
    ToolClass model = (ToolClass) getTypeCache(project).get((planName + "." + className).toUpperCase());
    if (model == null)
      model = (ToolClass) getForteTypeCache().get((planName + "." + className).toUpperCase());
    if (model == null){
      /*
       * if its not in the cashe we look for it in the resource tree.
       * if it is there we parse it which adds it to the cache
       *
       * first we check in the user classes
       */
      List<IFolder> sourceFolders = ToolProjectSupport.getSourceFolders(project);
      for (IFolder projectsFolder : sourceFolders){
        IFolder planFolder = (IFolder)projectsFolder.findMember(planName);
        if (planFolder != null){
          try {
            planFolder.refreshLocal(IResource.DEPTH_ONE, null);
            IResource clsResource = planFolder.findMember(className + ".cdf");
            if (clsResource != null){
              ToolClass cls = fetch((IFile)clsResource);
              if (cls!= null)
                return cls;
            }
          } catch (CoreException e) {
            ToolModelActivator.showError("Error searching for class", e);
          }
        }
      }
      /*
       * then we check on the forte libraries
       */
      IFolder libFolder = (IFolder)project.findMember(ToolProjectSupport.UDS_LIBRARY_FOLDER_NAME);
      IResource resource = libFolder.findMember(planName + ".pex");
      if (resource != null){
        ToolPlan plan = ToolPlan.getInstance(resource);
        if (plan != null){
          ToolClass cls = plan.findClass(className);
          if (cls!= null)
            return cls;
        }
      }
      /*
       * finally we check in the user libraries
       */
      libFolder = (IFolder)project.findMember(ToolProjectSupport.LIBRARY_FOLDER_NAME);
      resource = libFolder.findMember(planName + ".pex");
      if (resource != null){
        ToolPlan plan = ToolPlan.getInstance(resource);
        if (plan != null){
          ToolClass cls = plan.findClass(className);
          if (cls!= null)
            return cls;
        }
      }
    }
    return model;
  }
 

  public synchronized static List<ToolClass> find(IProject project, String className){
    List<ToolClass> result = new ArrayList<ToolClass>();
    /*
     * if the name is fully qualified, just look it up in the cache
     */
    if (className.contains(".")){
      String[] parts = className.split("\\.");
      ToolClass found = ToolClass.fetch(project, parts[0].trim(), parts[1].trim());
      if (found != null){
        result.add(found);
      }
    } else {
      /*
       * if not do a search
       */
      try {
        IFolder projectsFolder = (IFolder)project.findMember(ToolProjectSupport.PROJECT_FOLDER_NAME);
        IResource[] members = projectsFolder.members();
        for (IResource resource : members){
          if (resource instanceof IFolder){
            IFolder planFolder = (IFolder)resource;

            try {
              IResource[] planMembers = planFolder.members();
              for(IResource member : planMembers){
                if (member.getName().equalsIgnoreCase(className + ".cdf")){
                  ToolClass cls = fetch((IFile)member);
                  if (cls!= null)
                    result.add(cls);
                }
              }
            } catch (CoreException e) {
              ToolModelActivator.showError("Cannot find class: " + className, e);
             
            }
            //          IResource clsResource = planFolder.findMember(className + ".cdf");
            //          if (clsResource != null){
            //            ToolClass cls = fetch((IFile)clsResource);
            //            if (cls!= null)
            //              result.add(cls);
            //          }
          }
        }
        IFolder libFolder = (IFolder)project.findMember(ToolProjectSupport.LIBRARY_FOLDER_NAME);
        members = libFolder.members();
        for (IResource resource : members){
          ToolPlan plan = ToolPlan.getInstance(resource);
          if (plan != null){
            ToolClass cls = plan.findClass(className);
            if (cls!= null)
              result.add(cls);
          }
        }
        libFolder = (IFolder)project.findMember(ToolProjectSupport.UDS_LIBRARY_FOLDER_NAME);
        members = libFolder.members();
        for (IResource resource : members){
          ToolPlan plan = ToolPlan.getInstance(resource);
          if (plan != null){
            ToolClass cls = plan.findClass(className);
            if (cls!= null)
              result.add(cls);
          }
        }
      } catch (CoreException e) {
        ToolModelActivator.showError("Error finding Tool class", e);
      } finally {

      }
    }
    return result;
  }
  public synchronized static ToolClass fetch(IFile modelFile){
    IProject project = modelFile.getProject();
    planName = modelFile.getParent().getName();
    String className = modelFile.getName().substring(0, modelFile.getName().lastIndexOf("."));
    if (className.startsWith("qq")){
      className = className.substring(5);// remove the qq**_
    }
    String keyString = (planName + "." + className).toUpperCase();
    ToolClass model = (ToolClass) getTypeCache(project).get(keyString);
    if (model == null){
      try {
        if (!(describer.describe(modelFile.getContents(), null) == IContentDescriber.VALID))
          return null;
       
        model = new ToolClass();
        model.setFile(modelFile);
        model.setPlanName(planName);
        model.provider = new TextFileDocumentProvider();
        model.provider.connect(modelFile);
        model.document = model.provider.getDocument(modelFile);
       
        model.parse(model.document);
        getTypeCache(model.getProject()).put(keyString, model);

      } catch (CoreException e) {
        ToolModelActivator.log(IStatus.ERROR,"Error updating Class Model.", e);
      } catch (IOException e) {
        ToolModelActivator.log(IStatus.ERROR,"Error updating Class Model.", e);
      }
    }
    return model;
  }
 
  public synchronized static ToolClass createFromSource(ToolPlan plan, String classSource){
    ToolClass model = new ToolClass();
    //model.setParent(plan);
    model.setFile(null);
    model.setPlanName(plan.getToolName());
    model.parse(classSource);
    String keyString = (plan.getToolName() + "." + model.getLabelText()).toUpperCase();
    if (plan.isFortePlan()){
      getForteTypeCache().put(keyString, model);
    } else {
      getTypeCache(plan.getProject()).put(keyString, model);
    }
    return model;
  }
 
 

  private ToolClass(){
    super();
  }
  public ToolClass(String newClassName) {
    this();
    setToolName(newClassName);
  }

  /**
   * create a new, empty class in the supplied plan
   * @param plan
   */
  public ToolClass(ToolPlan plan, boolean isWindowClass) {
    this();
    this.setPlanName(plan.getToolName());
    if (isWindowClass){
      this.setSuperClass("DisplayProject.UserWindow");
      this.setMapped(true);
    } else {
      this.setSuperClass("Framework.Object");
    }
    this.setDirty(true);
  }
 
  public static ToolClass parseUsingGrammar(IFile file){
    try {
      TextFileDocumentProvider provider = new TextFileDocumentProvider();
      provider.connect(file);
      IDocument document = provider.getDocument(file);   
      String source = document.get();
      CommonTokenStream tokens = createTokenStream(source);
      ToolClass toolClass =  parseSource(tokens, file);
      if (toolClass != null){
        toolClass.document = document;
      }
      return toolClass;
    } catch (CoreException e) {
      ToolModelActivator.showError("Cannot parse file "  + file.getName(), e);
    } catch (RecognitionException e) {
      ToolModelActivator.showError("Cannot parse file "  + file.getName(), e);
    }
    return null;
  }
  public static ToolClass parseUsingGrammar(File file){
    try {
      TextFileDocumentProvider provider = new TextFileDocumentProvider();
      provider.connect(file);
      IDocument document = provider.getDocument(file);   
      String source = document.get();
      CommonTokenStream tokens = createTokenStream(source);
      ToolClass toolClass =  parseSource(tokens, null);
      if (toolClass != null){
        toolClass.document = document;
      }
      return toolClass;
    } catch (CoreException e) {
      ToolModelActivator.showError("Cannot parse file "  + file.getName(), e);
    } catch (RecognitionException e) {
      ToolModelActivator.showError("Cannot parse file "  + file.getName(), e);
    }
    return null;
  }
  public static ToolClass parseSource(CommonTokenStream tokens, IFile file) throws RecognitionException{
      ErrorReporter parseErrors = new ErrorReporter();
      CommonTree tree = null;
      parser.setTokenStream(tokens);
      parser.setErrorReporter(parseErrors);
      parser.setTreeAdaptor(new CommonTreeAdaptor(){
        public Object create(Token payload){
          return new CommonTree(payload);
        }
      });
      classFile_return result = parser.classFile();
      if (parser.getNumberOfSyntaxErrors() > 0){
        MessageConsole console = ToolModelActivator.findConsole(ToolModelActivator.TOOL_PARSER_OUTPUT);
        MessageConsoleStream msgStream = console.newMessageStream();
        msgStream.println(parser.getNumberOfSyntaxErrors() + " Syntax error(s) in class " + file.getName() + "\n"
            + parseErrors.toString());
      }

      tree = (CommonTree) result.getTree();
      System.out.println(tree.toStringTree());
      CommonTreeNodeStream nodes = new CommonTreeNodeStream(tree);
      nodes.setTokenStream(tokens);
      ForteCDFTree walker = new ForteCDFTree(file, nodes);
      ToolClass toolClass = walker.classDeclaration().toolClass;
      return toolClass;
  }

  public void parse(IDocument doc){
    virtualAttributes = new HashMap<String, ToolVirtualAttribute>();
    attributes = new HashMap<String, ToolAttribute>();
    windowAttributes = new HashMap<String, ToolWindowAttribute>();
    constants = new HashMap<String, ToolConstant>();
    methods = new HashMap<String, ToolMethod>();
    eventHandlers = new HashMap<String, ToolEventHandler>();
    implementations = new HashSet<String>();
    this.document = doc;
    String fileName = this.file.getName();
    this.setToolName( fileName.substring(0, fileName.lastIndexOf('.')));
   
    IFolder folder = ((IFolder)this.file.getParent());
    String name = this.file.getName();
    // Method File
    String cexName = name.substring(0, name.lastIndexOf('.')) + ".cex";
    IResource cexResource = folder.findMember(cexName);
    if (cexResource != null){
      this.implementationFile = (IFile)cexResource;
      /*
       * if we are working with a whole class file then
       * we set the method file to the class file
       */
    } else if (this.file.getFileExtension().equalsIgnoreCase("cex")){
      this.implementationFile = this.file;
    }

    // Window file
    String fswName = name.substring(0, name.lastIndexOf('.')) + ".fsw";
    IResource fswResource = folder.findMember(fswName);
    if (fswResource != null){
      this.windowFile = (IFile)fswResource;
    }
    String source = document.get();
    parse(source);
    this.setDirty(false);
  }
  public void parse(String source){
    this.parsed = false;
    parseClass(source);
    parseAttributes(source);
    parseWindowAttributes(source);
    parseVirtualAttributes(source);
    parseConstants(source);
    parseMethods(source);
    parseEvents(source);
    parseEventHandlers(source);
    parseClassProperties(source);
    parseImplements(source);
   
  }
  private void parseImplements(String source) {
    //Implementations
    Matcher matcher = implementationsPattern.matcher(source);
    while (matcher.find()){
      String wholeMatch = matcher.group(0);
      String imp = matcher.group(1);
      if (implementations == null)
        implementations = new HashSet<String>();
      implementations.add(imp);
    }
   
  }


  private void parseVirtualAttributes(String source) {
    //Virtual Attributes
    Matcher matcher = ToolVirtualAttribute.pattern.matcher(source);
    while (matcher.find()){
      String wholeMatch = matcher.group(0);
      ToolVirtualAttribute att = new ToolVirtualAttribute(this, wholeMatch);
      add(att);
      att.setDirty(false);
    }
  }
  public void add(ToolVirtualAttribute att){
    if (virtualAttributes == null)
      virtualAttributes = new HashMap<String, ToolVirtualAttribute>();
    virtualAttributes.put(att.getName(), att);
  }

  private void parseClassProperties(String source){
    Matcher props = ToolClass.propertiesPattern.matcher(source);
    if (props.find()){
      this.properties.clear();
      String wholeMatch = props.group(0);
      Matcher prop = ToolClass.singlePropPattern.matcher(wholeMatch);
      while (prop.find()){
        String propName = prop.group(1);
        boolean allow = prop.group(2).equals("on");
        boolean override = prop.group(3).equals("on");
        boolean def = (prop.group(5)==null) ? false : prop.group(5).equals("on");
        this.properties.add(new ClassProperty(propName, allow, override, def));
       
      }
     
    }
    props = ToolClass.idPropertiesPattern.matcher(source);
    if (props.find()){
      String wholeMatch = props.group(0);
      this.id = Integer.parseInt(props.group(1));
      this.proxyId = Integer.parseInt(props.group(2));
     
    }
    this.parsed = true;
  }
  private void parseClass(String source){
    Matcher cls = ToolClass.pattern.matcher(source);
    if (cls.find()){
      String wholeMatch = cls.group(0);
      setToolName(xlateName(cls.group(1)));
      superClass = cls.group(2);
      mapped = wholeMatch.contains("is mapped");
    }
  }
  private void parseEvents(String source) {
    //Events
    Matcher sig = ToolEvent.pattern.matcher(source);
   
    while (sig.find()){
      String wholeMatch = sig.group(0);
      ToolEvent eh = new ToolEvent(this, wholeMatch);
      eh.setRegion(new Region(sig.start(0), sig.end(0)));
      add(eh);
      eh.setDirty(false);
     
    }
  } 
  public void add(ToolEvent ev){
    if (events == null)
      events = new HashMap<String, ToolEvent>();
    events.put(ev.getLabelText(), ev);
  }

  private void parseEventHandlers(String source) {
    //Event Handlers
    Matcher sig = ToolEventHandler.pattern.matcher(source);
   
    while (sig.find()){
      //process signature
      String wholeMatch = sig.group(0);
      ToolEventHandler eh = new ToolEventHandler(this, wholeMatch);
      eh.setRegion(new Region(sig.start(0), sig.end(0)));
      eh.setFile(this.implementationFile);
      add(eh);
      eh.setDirty(false);
     
    }
  }
  public void add(ToolEventHandler eh){
    if (eventHandlers == null)
      eventHandlers = new HashMap<String, ToolEventHandler>();
    eventHandlers.put(eh.getLabelText(), eh);
  }

  private void parseMethods(String source) {
    //Methods
    Matcher sig = ToolMethod.declarationPattern.matcher(source);
   
    while (sig.find()){
      //process method signature
      String wholeMatch = sig.group(0);
      ToolMethod method = new ToolMethod(this, wholeMatch);
      method.setRegion(new Region(sig.start(0), sig.end(0)));
      method.setFile(this.implementationFile);
      if (methods == null)
        methods = new HashMap<String, ToolMethod>();
      methods.put(method.getLabelText(), method);
     
      method.setDirty(false);
     
    }
  }
  public void add(ToolMethod method){
    if (methods == null)
      methods = new HashMap<String, ToolMethod>();
    methods.put(method.getLabelText(), method);
  }

  public void parseConstants(String source){
    //Constants
    Matcher matcher = ToolConstant.pattern.matcher(source);
    while (matcher.find()){
      String wholeMatch = matcher.group(0);
      ToolConstant con = new ToolConstant(this, wholeMatch);
      con.setRegion(new Region(matcher.start(0), matcher.end(0)));
      if (constants == null)
        constants = new HashMap<String, ToolConstant>();
      constants.put(con.getName(), con);
      con.setDirty(false);
    }
  }

  public void parseAttributes(String source){
    //Attributes
    Matcher matcher = ToolAttribute.pattern.matcher(source);
    while (matcher.find()){
      String wholeMatch = matcher.group(0);
      ToolAttribute att = new ToolAttribute(this, wholeMatch);
      att.setRegion(new Region(matcher.start(0), matcher.end(0)));
      add(att);
      att.setDirty(false);
    }
  }
  public void add(ToolAttribute att){
    if (attributes == null)
      attributes = new HashMap<String, ToolAttribute>();
    attributes.put(att.getName(), att);
  }
 
  public void parseWindowAttributes(String source){
    //Window Attributes
    Matcher matcher = ToolWindowAttribute.pattern.matcher(source);
    while (matcher.find()){
      String wholeMatch = matcher.group(0);
      ToolWindowAttribute att = new ToolWindowAttribute(this, wholeMatch);
      att.setRegion(new Region(matcher.start(0), matcher.end(0)));
      if (windowAttributes == null)
        windowAttributes = new HashMap<String, ToolWindowAttribute>();
      windowAttributes.put(att.getName(), att);
      att.setDirty(false);
    }
  }

  public IClassComponent[] getComponents(){
    int kidsSize = ((attributes!= null) ? attributes.size() : 0) +
        ((windowAttributes!= null) ? windowAttributes.size() : 0) +
        ((eventHandlers!= null) ? eventHandlers.size() : 0)+
        ((events!= null) ? events.size() : 0)+
        ((methods!= null) ? methods.size() : 0) +
        ((constants!= null) ? constants.size() : 0) +
        ((virtualAttributes!= null) ? virtualAttributes.size() : 0);
    IClassComponent[] allKids = new IClassComponent[kidsSize];
    int j = 0;
    //Constants
    if (constants != null){
      Object[] consts = constants.values().toArray();
      for (int i = 0; i < constants.size(); i++, j++){
        allKids[j] = (IClassComponent) consts[i];
      }
    }
    //Attributes
    if (attributes != null){
      Object[] atts = attributes.values().toArray();
      for (int i = 0; i < attributes.size(); i++, j++){
        allKids[j] = (IClassComponent) atts[i];
      }
    }
    //Window Attributes
    if (windowAttributes != null){
      Object[]  atts = windowAttributes.values().toArray();
      for (int i = 0; i < windowAttributes.size(); i++, j++){
        allKids[j] = (IClassComponent) atts[i];
      }
    }
    //Methods
    if (methods != null){
      Object[]  meths = methods.values().toArray();
      for (int i = 0; i < methods.size(); i++, j++){
        allKids[j] = (IClassComponent) meths[i];
      }
    }
    //Event Handlers
    if (eventHandlers != null){
      Object[]  ehs = eventHandlers.values().toArray();
      for (int i = 0; i < eventHandlers.size(); i++, j++){
        allKids[j] = (IClassComponent) ehs[i];
      }
    }
    //Event
    if (events != null){
      Object[]  ehs = events.values().toArray();
      for (int i = 0; i < events.size(); i++, j++){
        allKids[j] = (IClassComponent) ehs[i];
      }
    }
    //Virtual Attributes
    if (virtualAttributes != null){
      Object[]  ehs = virtualAttributes.values().toArray();
      for (int i = 0; i < virtualAttributes.size(); i++, j++){
        allKids[j] = (IClassComponent) ehs[i];
      }
    }
    return allKids;
  }
 
  @Override
  public boolean hasChildren() {
    return (attributes!= null)||
      (windowAttributes!= null) ||
      (constants != null) ||
      (methods != null) ||
      (eventHandlers != null) ||
      (events != null);
  }
 
  public boolean isMapped(){
    return mapped;
  }
  public String getSuperClass() {
    return superClass;
  }
  public void setSuperClass(String superClass) {
    propertyChangeSupport.firePropertyChange("superClass", this.superClass,
        this.superClass = superClass);
    setDirty(true);
  }
  public void setMapped(boolean mapped) {
    propertyChangeSupport.firePropertyChange("mapped", this.mapped,
        this.mapped = mapped);
    setDirty(true);
  }

 
 
  public IFile getWindowFile() {
    return windowFile;
  }

  public List<ClassProperty> getClassProperties() {
    return properties;
  }



  public class ClassProperty{
    public boolean allow;
    public boolean override;
    public boolean def;
    public String name;
    public ClassProperty(String name, boolean allow, boolean override, boolean def){
      this.allow = allow;
      this.override = override;
      this.def = def;
      this.name = name;
    }
   
    public String isAllow() {
      return onOff(allow);
    }

    public String isOverride() {
      return onOff(override);
    }

    public String isDef() {
      return onOff(def);
    }

    public String getName() {
      return name;
    }

    public String toSource(){
      StringBuilder sb = new StringBuilder();
      sb.append(name);
      sb.append("=(allow=");
      sb.append(onOff(allow));
      sb.append(", override=");
      sb.append(onOff(override));
      sb.append(", default=");
      sb.append(onOff(def));
      sb.append(");");
      return sb.toString();
    }
   
    private String onOff(boolean value){
      return (value) ? "on" : "off";
    }
  }



  @Override
  public IFile getProjectFile() {
    return getFile();
  }
  @Override
  public void setProjectFile(IFile file) {
    setFile(file);
   
  }
  @Override
  public String getLabelText() {
    String name = getToolName();
    if (name.startsWith("qq")){
      String target = xlateName(name);
      if (target.startsWith("qq"))
        name = name.substring(5);
      else
        name = target;
    }
    return name;
  }
  @Override
  public String getLabelText(int options) {
    if ((options & LabelProvider.FULL_PATH) == LabelProvider.FULL_PATH){
      return getPlanName() + "." + getLabelText();
    }
    return getLabelText();
  }
 
  public String xlateName(String source){
    String target = specialNames.get(source);
    if (target!=null)
      return target;
    else {
      if (source.startsWith("qq")){
        return source.substring(5);
      }
    }
    return source;
  }
  @Override
  public String getIconString() {
    if (isMapped())
      return "icons/window_class.gif";
    else
      return "icons/class.gif";
  }
 
  public ToolClass getToolSuperClass(){
    String[] parts = getSuperClass().split("\\.");
    String projectName = parts[0].trim();
    String className = parts[1].trim();
    ToolClass superClass = ToolClass.fetch(getProject(), projectName, className);
    /*
     * this will not work if the superclass is a in a Library
     */
    if (superClass == null){
      IProject project = this.getFile().getProject();
      List<IFolder> sourceFolders = ToolProjectSupport.getSourceFolders(project);
      for (IFolder sourceFolder : sourceFolders){
        IFolder projectFolder = (IFolder)sourceFolder.findMember(projectName);
        if (projectFolder != null){
          IFile superCDF = (IFile)projectFolder.findMember(className + ".cdf");
          superClass = ToolClass.fetch(superCDF);
        }
      }
    }
    return superClass;
  }
 
  public synchronized void remove(){
    ToolPlan plan = getPlan();
    plan.removeComponent(this);
    ToolClass.getTypeCache(this.getProject()).remove(getFullName().toUpperCase());
   
  }
 
  public synchronized void move(String newPlanName){
    ToolPlan plan = ToolPlan.fetch(getProject(), newPlanName);
    if (plan == null)
      return;
    remove();
    ToolClass.getTypeCache(this.getProject()).put(getFullName().toUpperCase(), this);
   
  }

//  @SuppressWarnings("unchecked")
//  public static Map<String, ToolClass> getClassCache(IProject project){
//    Map<String, ToolClass> cache = null;
//    try {
//      cache = (Map<String, ToolClass>)project.getSessionProperty(new QualifiedName(ToolProjectSupport.PROJECT_QUALIFIED_NAME, ToolProjectSupport.CLASS_CACHE));
//      if (cache == null){
//        cache = new HashMap<String, ToolClass>();
//        project.setSessionProperty(new QualifiedName(ToolProjectSupport.PROJECT_QUALIFIED_NAME, ToolProjectSupport.CLASS_CACHE), cache);
//      }
//    } catch (CoreException e) {
//      ToolModelActivator.showError("Error getting class cache", e);
//    }
//    return cache;
//  }

  public boolean isParsed() {
    return parsed;
  }


  public void setParsed(boolean parsed) {
    propertyChangeSupport.firePropertyChange("parsed", this.parsed,
        this.parsed = parsed);
  }


  public Set<String> getImplementations() {
    if (this.implementations != null)
      return this.implementations;
    else
      return new HashSet<String>();
  }





  public void setImplementationFile(IFile implementationFile) {
    propertyChangeSupport.firePropertyChange("implementationFile", this.implementationFile,
        this.implementationFile = implementationFile);
  }


  public String getFullName() {
    return getPlanName() + "." + getToolName();
  }

  @Override
  public Object getParent() {
    return getPlan();
  }

  public String toSource(){
    FileReader reader;
    String output = "";
    try {
      reader = new FileReader(toolTemplate());
      StringTemplateGroup templates = new StringTemplateGroup(reader);
      StringTemplate cdfTemplate = templates.lookupTemplate("cdfFile");
      cdfTemplate.setAttribute("cls", this);
      output = cdfTemplate.toString();
    } catch (FileNotFoundException e) {
      ToolModelActivator.showError("Error generating Tool source", e);
    }
    return output;

//    StringBuilder sb = new StringBuilder();
//    sb.append("begin CLASS;\n\nclass ");
//    sb.append(getToolName());
//    if (isMapped()){
//      sb.append(" is mapped");
//    }
//    sb.append(" inherits from ");
//    sb.append(getSuperClass());
//    sb.append("\n\n");
//   
//    if (this.windowAttributes != null){
//      for (ToolWindowAttribute wa : this.windowAttributes.values()){
//        sb.append(wa.toSource());
//        sb.append("\n");
//      }
//      sb.append("\n");
//    }
//   
//    if (this.attributes != null){
//      for (ToolAttribute att : this.attributes.values()){
//        sb.append(att.toSource());
//        sb.append("\n");
//      }
//      sb.append("\n");
//    }
//   
//    if (this.methods != null){
//      for (ToolMethod meth: this.methods.values()){
//        sb.append(meth.toSource());
//        sb.append("\n");
//      }
//      sb.append("\n");
//    }
//
//    sb.append("has property\n");
//    for (ClassProperty cp : this.properties){
//      sb.append("\t");
//      sb.append(cp.toSource());
//      sb.append("\n");
//    }
//   
//    sb.append("\tid = ").append(this.id).append("; proxyId = ").append(this.proxyId).append(";\n");
//   
//    windowFile(sb);
//   
//    sb.append("\nend class;\nend CLASS;");
//    return sb.toString();
  }

  protected void windowFile(StringBuilder sb) {
    if (isMapped()){
      sb.append("\nhas file '");
      sb.append(this.windowFile.getLocation().toOSString());
      sb.append("';\n");
    }
  }

  @Override
  public void propertyChange(PropertyChangeEvent evt) {
    if (evt.getPropertyName().equals("dirty")){
      if ((Boolean)evt.getNewValue())
        setDirty(true);
    }
   
  }
 
  public void doSave(IProgressMonitor monitor){
    try {
      String source = toSource();
      if (this.document != null && this.provider != null){
        this.document.set(source);
        this.provider.saveDocument(monitor, this.file, this.document, true);
      }
    } catch (CoreException e) {
      ToolModelActivator.showError("Cannot save class", e);
    }
  }
 
  public List<ToolComponent> getElementsByPartialName(String partialKey, boolean includePrivate){
    String partialKeyLowerCase = partialKey.toLowerCase();
    List<ToolComponent> result = new ArrayList<ToolComponent>();
    //This class
   
    // attributes
    for (ToolAttribute att : this.attributes.values()){
      if (att.getToolName().toLowerCase().startsWith(partialKeyLowerCase))
        result.add(att);
    }
   
    // methods
    for (ToolMethod meth: this.methods.values()){
      if (meth.getToolName().toLowerCase().startsWith(partialKeyLowerCase))
        result.add(meth);
    }
    // events
    for (ToolEvent event : this.events.values()){
      if (event.getToolName().toLowerCase().startsWith(partialKeyLowerCase))
        result.add(event);
    }
    // event handlers
    for (ToolEventHandler eventHandler : this.eventHandlers.values()){
      if (eventHandler.getToolName().toLowerCase().startsWith(partialKeyLowerCase))
        result.add(eventHandler);
    }
    // Super Class elements
    ToolClass superClass = (ToolClass) ToolClass.fetch(getProject(), getSuperClass());
    result.addAll(superClass.getElementsByPartialName(partialKey, false));
    Collections.sort(result, ToolComponent.comparator);
    //TODO traverse the whole chain
    return result;
  }
 
  public ToolMethod findMethod(String fullSignature){
    return this.methods.get(fullSignature);
  }

  public List<ToolAttribute> getAttributes() {
    List<ToolAttribute> list = new ArrayList<ToolAttribute>(attributes.values());
    return list; 
  }

  public List<ToolMethod> getMethods() {
    List<ToolMethod> list = new ArrayList<ToolMethod>(methods.values());
    return list; 
  }

  public List<ToolWindowAttribute> getWindowAttributes() {
    List<ToolWindowAttribute> list = new ArrayList<ToolWindowAttribute>(windowAttributes.values());
    return list; 
  }

  public List<ToolConstant> getConstants() {
    List<ToolConstant> list = new ArrayList<ToolConstant>(constants.values());
    return list; 
  }

  public List<ToolEventHandler> getEventHandlers() {
    List<ToolEventHandler> list = new ArrayList<ToolEventHandler>(eventHandlers.values());
    return list; 
  }

  public List<ToolVirtualAttribute> getVirtualAttributes() {
    List<ToolVirtualAttribute> list = new ArrayList<ToolVirtualAttribute>(virtualAttributes.values());
    return list;
  }

  public List<ToolEvent> getEvents() {
    List<ToolEvent> list = new ArrayList<ToolEvent>(events.values());
    return list;
  }
 
 
}
TOP

Related Classes of tool.model.ToolClass$ClassProperty

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.