Package tool.model

Source Code of tool.model.ToolPlan

package tool.model;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileFilter;
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.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.antlr.runtime.CommonTokenStream;
import org.antlr.runtime.RecognitionException;
import org.antlr.runtime.tree.CommonTree;
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.IStatus;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.QualifiedName;
import org.eclipse.core.runtime.content.IContentDescriber;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.Region;
import org.eclipse.ui.editors.text.TextFileDocumentProvider;
import org.eclipse.ui.texteditor.IDocumentProvider;

import tool.ToolPlugin;
import tool.ToolProjectSupport;
import tool.model.grammar.FortePRXTree;
import tool.model.grammar.ForteParser.project_return;
import tool.model.grammar.IErrorReporter;
import tool.navigator.cdf.InterfaceContentDescriber;

public class ToolPlan extends ToolComponent implements IErrorReporter{

  protected static final String CONSTANT_SEGMENTS = "__constant_segments";
  private IDocument document = null;
  private ArrayList<IModelListener> modelListeners;
  protected String type;
  protected Set<String> supplierPlans;
  protected boolean library = false;
  protected Map<String, ToolClass> classes;
  protected Map<String, ToolInterface> interfaces;
  protected List<ToolConstant> constants;
  protected Set<ToolCType> cTypes;
  protected int compatibilityLevel = 0;
  protected String projectType;
  protected boolean Restricted = false;
  protected boolean MultiThreaded = true;
  protected boolean Internal = false;
  protected String libraryName;
  protected java.util.UUID UUID;
  protected List<ToolCursor> cursors;
  protected String startClass;
  protected String startMethod;
  protected Map<String, ToolServiceObject> serviceObjects;
  protected Set<String> supplierTo;
  protected IDocumentProvider provider;
  protected Map<String, ToolForwardDeclaration> forwardDeclarations = new HashMap<String, ToolForwardDeclaration>();


  private static Map<String, ToolPlan> forteLibraryCache;

  static {
    forteLibraryCache = new HashMap<String, ToolPlan>();
  }

  public static final String REGEX ="begin\\s+(TOOL|C)\\s+([A-Za-z0-9_]+)\\s*(from library|);";
  //public static final String PROPERTIES_REGEX ="HAS PROPERTY\\s+(.+);";
  public static final String PROPERTIES_REGEX = "(?s)CompatibilityLevel = (\\d+);\\s+" +
      "ProjectType = (APPLICATION|LIBRARY|SERVER);\\s+" +
      "Restricted = (TRUE|FALSE);\\s+" +
      "MultiThreaded = (TRUE|FALSE);\\s+" +
      "Internal = (TRUE|FALSE);\\s+" +
      "LibraryName = '([a-zA-Z0-9_]+)';(\\s+" +
      "StartingMethod = \\(class = ([a-zA-Z0-9_]+), method = ([a-zA-Z0-9_]+)\\);|)(?-s)";
  public static final String SUPPLIER_REGEX = "includes\\s+([A-Za-z0-9_]+);";
  public static final String LIBRARY_REGEX ="HAS\\s+PROPERTY\\s+IsLibrary\\s+=\\s+(TRUE|FALSE)\\s*;";

  public static final Pattern pattern = Pattern.compile(REGEX);
  public static final Pattern propertiesPattern = Pattern.compile(PROPERTIES_REGEX, Pattern.MULTILINE);
  public static final Pattern supplierPattern = Pattern.compile(SUPPLIER_REGEX);
  public static final Pattern libraryPattern = Pattern.compile(LIBRARY_REGEX);


  public static ToolPlan fetch(IProject project, String name){
    if (project == null) //Assume its a system Library
      return getForteLibraryCache().get(name.toUpperCase());
    ToolPlan model = getPlanCache(project).get(name.toUpperCase());
    if (model == null)
      model = getForteLibraryCache().get(name.toUpperCase());
    if (model == null){

      // look in source folders
      List<IFolder> sourceFolders = ToolProjectSupport.getSourceFolders(project);
      for (IFolder folder : sourceFolders){
        try {
          folder.refreshLocal(IResource.DEPTH_INFINITE, null);

          IFolder planFolder = (IFolder) folder.findMember(name);
          if (planFolder == null)
            break;
          IResource resource = planFolder.findMember(name + ".prx");
          if (resource == null)
            break;
          model = getInstance(resource);
          if (model != null){
            return model;
          }
        } catch (CoreException e) {
          ToolPlugin.showError("Error geting plan: " + name, e);
        }
      }


      List<IFolder> libFolders = new ArrayList<IFolder>();
      libFolders.add(ToolProjectSupport.getLibraryFolder(project));

      for (IFolder folder : libFolders){
        IResource resource = folder.findMember(name + ".pex");
        if (resource == null)
          continue;
        model = getInstance(resource);
        if (model != null){
          return model;
        }
      }
    }
    return model;
  }
  public static void removeInstance(IResource resource) {
    IProject project = resource.getProject();
    String planName = resource.getName();
    if (planName.contains("."))
      planName = planName.substring(0, planName.indexOf('.'));
    Map<String, ToolPlan> cache = getPlanCache(project);
    cache.remove(planName.toUpperCase());
    IFolder planFolder = (IFolder)resource.getParent();
    try {
      ToolProjectSupport.removePlanFromFolder(planFolder);
    } catch (CoreException e) {
      ToolPlugin.showError("Error removing plan instance: " + resource.getName(), e);
    }
  }
  public static ToolPlan getInstance(IResource resource){
    IProject project = resource.getProject();
    String planName = resource.getName();
    if (planName.contains("."))
      planName = planName.substring(0, planName.indexOf('.'));

    ToolPlan prx = getPlanCache(project).get(planName.toUpperCase());

    if (prx == null){
      IFile modelFile = null;
      if (resource instanceof IFolder){
        modelFile = (IFile)((IFolder)resource).findMember(resource.getName() + ".prx");
      } else {
        modelFile = (IFile)resource;
      }
      prx = createPlanFromFile(modelFile);
      getPlanCache(project).put(planName.toUpperCase(), prx);
    }
    return prx;
  }

  protected static ToolPlan createPlanFromFile(IFile modelFile){
    ToolPlan prx = null;
    try {
      prx = new ToolPlan();
      prx.setFile(modelFile);
      prx.provider = new TextFileDocumentProvider();
      prx.provider.connect(modelFile);
      IDocument document = prx.provider.getDocument(modelFile);   
      prx.document = document;
      String source = document.get();
      boolean isPEX = modelFile.getFileExtension().equalsIgnoreCase("pex");
      prx.parse(source, isPEX);
      /*
       * special case for Framework
       */
      createFrameworkScalarTypes(prx);

    } catch (CoreException e) {
      ToolPlugin.log(IStatus.ERROR,"Error initializing ToolPlan.", e);
    }
    return prx;
  }
  protected static ToolPlan createPlanFromFile(File modelFile){
    ToolPlan prx = null;
    try {
      prx = new ToolPlan();
      StringBuffer contents = new StringBuffer();
      BufferedReader reader = new BufferedReader(new FileReader(modelFile));

      String text = null;
      // repeat until all lines is read
      while ((text = reader.readLine()) != null) {
        contents.append(text).append(System.getProperty("line.separator"));
      }
      String source = contents.toString();
      prx.parse(source, true);
      /*
       * special case for Framework
       */
      createFrameworkScalarTypes(prx);

    } catch (FileNotFoundException e) {
      ToolPlugin.log(IStatus.ERROR,"Error initializing ToolPlan.", e);
    } catch (IOException e) {
      ToolPlugin.log(IStatus.ERROR,"Error initializing ToolPlan.", e);
    }
    return prx;
  }

  private static void createFrameworkScalarTypes(ToolPlan prx){
    /*
     * special case for Framework
     */
    if (prx.isFortePlan() && prx.getToolName().equalsIgnoreCase("Framework")){
      ToolCType scalar = ToolCType.createScalar(prx, "integer");
      prx.cTypes.add(scalar);
      scalar = ToolCType.createScalar(prx, "string");
      prx.cTypes.add(scalar);
      scalar = ToolCType.createScalar(prx, "int");
      prx.cTypes.add(scalar);
      scalar = ToolCType.createScalar(prx, "i1");
      prx.cTypes.add(scalar);
      scalar = ToolCType.createScalar(prx, "i2");
      prx.cTypes.add(scalar);
      scalar = ToolCType.createScalar(prx, "i4");
      prx.cTypes.add(scalar);
      scalar = ToolCType.createScalar(prx, "ui1");
      prx.cTypes.add(scalar);
      scalar = ToolCType.createScalar(prx, "ui2");
      prx.cTypes.add(scalar);
      scalar = ToolCType.createScalar(prx, "pointer");
      prx.cTypes.add(scalar);
      scalar = ToolCType.createScalar(prx, "boolean");
      prx.cTypes.add(scalar);
      scalar = ToolCType.createScalar(prx, "short");
      prx.cTypes.add(scalar);
      scalar = ToolCType.createScalar(prx, "long");
      prx.cTypes.add(scalar);
      scalar = ToolCType.createScalar(prx, "char");
      prx.cTypes.add(scalar);
    }

  }
  /**
   * computes supplier to graph
   * @param project
   */
  public static void computeSupplierTo(IProject project){
    Set<ToolPlan> plans = ToolProjectSupport.getAllPlansForProject(project);
    for (ToolPlan plan : plans){
      String planName = plan.getToolName();
      for (String name : plan.getSupplierPlansAsList()){
        ToolPlan.fetch(project, name).addSupplierTo(planName);
      }

    }

  }
  private ToolPlan(){
    this.compatibilityLevel = 0;
    this.Restricted = false;
    this.MultiThreaded = true;
    this.UUID = java.util.UUID.randomUUID();
    this.projectType = "APPLICATION";
    this.Internal = false;
    addSupplierPlan("Framework");
  }
  public ToolPlan(String newPlanName) {
    this();
    setToolName(newPlanName);
  }

  @Override
  public void setToolName(String name) {
    super.setToolName(name);
    if (name.length() <= 8)
      setLibraryName(name.toLowerCase());
    else
      setLibraryName(name.substring(0, 8).toLowerCase());

  }
  public void parse(String source, boolean isPEX) {
    if (ToolPlugin.useParser() && !isPEX){
      parseUsingGrammar(source);
    } else {
      parsePlan(source);
      parseLibrary(source);
      parseSuppliers(source);
      parseConstants(source);
      parseProperties(source);
      if (isPEX){
        setReadWrite(false);
        /*
         * this is a library export, so process the whole thing
         */
        parseClasses(source);
        parseServiceObjects(source);
        parseCursors(source);
        parseInterfaces(source);
        parseStructs(source);
      }
    }
  }

  @SuppressWarnings("static-access")
  private void parseUsingGrammar(String source){

    try {
      CommonTree tree = null;
      CommonTokenStream tokens = createTokenStream(source);
      parser.setTokenStream(tokens);
      parser.setErrorReporter(this);
      parser.setTreeAdaptor(adaptor);
      project_return result = parser.project();
      if (parser.getNumberOfSyntaxErrors() > 0){
        ToolPlugin.showError(parser.getNumberOfSyntaxErrors() + " Syntax error in project " + getFile().getName() + "\n"
            + this.parseErrors.toString(), null);
      } else {
        tree = (CommonTree) result.getTree();
        CommonTreeNodeStream nodes = new CommonTreeNodeStream(tree);
        nodes.setTokenStream(tokens);
        FortePRXTree walker = new FortePRXTree(this, nodes);
        walker.project();
      }
    } catch (RecognitionException e) {
      ToolPlugin.showError("Cannot parse project "  + getFile().getName(), e);
    }

  }


  private void parseInterfaces(String source) {
    Matcher interfaceMatcher = ToolInterface.whole_pattern.matcher(source);
    while (interfaceMatcher.find()){
      String wholeMatch = interfaceMatcher.group(0);
      ToolInterface cls = ToolInterface.createFromSource(this, wholeMatch);
      if (cls != null){
        cls.setPlanName(this.getToolName());
        cls.setReadWrite(isReadWrite());
        addInterface(cls);
      }
    }
  }
  private void addInterface(ToolInterface cls) {
    if (this.interfaces == null)
      this.interfaces = new HashMap<String, ToolInterface>();
    this.interfaces.put(cls.getToolName().toUpperCase(), cls);

  }
  private void parseCursors(String source) {
    // TODO Auto-generated method stub

  }
  private void parseServiceObjects(String source) {
    // TODO Auto-generated method stub

  }
  private void parseClasses(String source) {
    Matcher classMatcher = ToolClass.whole_pattern.matcher(source);
    while (classMatcher.find()){
      String wholeMatch = classMatcher.group(0);
      ToolClass cls = ToolClass.createFromSource(this, wholeMatch);
      cls.setPlanName(this.getToolName());
      cls.setReadWrite(isReadWrite());
      addClass(cls);
    }
  }
  private void parseStructs(String source) {
    Matcher structMatcher = ToolCType.whole_pattern.matcher(source);
    while (structMatcher.find()){
      String wholeMatch = structMatcher.group(0);
      ToolCType cls = ToolCType.createFromSource(this, wholeMatch);
      cls.setReadWrite(isReadWrite());
      addCType(cls);
    }
  }
  private void parsePlan(String source){
    Matcher plan = ToolPlan.pattern.matcher(source);
    if (plan.find()){
      String wholeMatch = plan.group(0);
      setToolName(plan.group(2));
    } else {
      System.out.println("Plan: error parsing plan:\n" + source);
    }
  }
  private void parseSuppliers(String source){
    Matcher sups = ToolPlan.supplierPattern.matcher(source);
    while (sups.find()){
      String wholeMatch = sups.group(0);
      String name = sups.group(1);
      addSupplierPlan(name);
    }
  }
  private void parseProperties(String source){
    Matcher props = ToolPlan.propertiesPattern.matcher(source);
    if (props.find()){
      String wholeMatch = props.group(0);
      this.compatibilityLevel = Integer.parseInt(props.group(1));
      this.projectType = props.group(2);
      this.Restricted = Boolean.parseBoolean(props.group(3));
      this.MultiThreaded = Boolean.parseBoolean(props.group(4));
      this.Internal = Boolean.parseBoolean(props.group(5));
      this.libraryName =props.group(6);
      this.startClass = props.group(8);
      this.startMethod = props.group(9);

    } else {
      System.out.println("Plan: error parsing properties:\n" + source);
    }
  }
  private void parseLibrary(String source){
    Matcher lib = ToolPlan.libraryPattern.matcher(source);
    if (lib.find()){
      String wholeMatch = lib.group(0);
      setLibrary(lib.group(1).equalsIgnoreCase("TRUE"));
    } else {
      System.out.println("Plan: error parsing library:\n" + source);
    }
  }
  public void parseConstants(String source){
    //Constants
    Matcher matcher = ToolConstant.planPattern.matcher(source);
    while (matcher.find()){
      String wholeMatch = matcher.group(0);
      ToolConstant con = new ToolConstant(this, wholeMatch, true);
      con.setRegion(new Region(matcher.start(0), matcher.end(0)));
      if (constants == null)
        constants = new ArrayList<ToolConstant>();
      constants.add(con);
    }
  }

  public ToolClass findClass(String className) {
    if (classes != null){
      return classes.get(className.toUpperCase());
    }
    return null;
  }
  public ToolServiceObject findSO(String soName) {
    if (serviceObjects != null){
      return serviceObjects.get(soName.toUpperCase());
    }
    return null;
  }

  public void addServiceObject(ToolServiceObject newSO){
    ToolServiceObject.addToCache(this.getProject(), newSO);
    serviceObjects.put(newSO.getToolName().toUpperCase(), newSO);
  }

  @Override
  public boolean hasChildren() {
    return /*(supplierPlans!= null)||*/
        (constants != null)||
        (cTypes != null)||
        (classes != null);
  }

  public IProjectComponent[] getComponents(){
    int kidsSize = /*((supplierPlans!= null) ? supplierPlans.size() : 0) +*/
        ((constants!= null) ? constants.size() : 0)+
        ((cTypes!= null) ? cTypes.size() : 0)+
        ((interfaces!= null) ? interfaces.size() : 0)+
        ((classes!= null) ? classes.size() : 0);
    IProjectComponent[] allKids = new IProjectComponent[kidsSize];
    int j = 0;
    //Constants
    if (constants != null){
      IProjectComponent[] consts = getProjectConstants();
      for (int i = 0; i < constants.size(); i++, j++){
        allKids[j] = consts[i];
      }
    }
    //classes
    if (classes != null){
      Collection<ToolClass> clses = classes.values();
      for (ToolComponent cls : clses){
        allKids[j] = (IProjectComponent) cls;
        j++;
      }
    }
    //interfaces
    if (interfaces != null){
      Collection<ToolInterface> clses = interfaces.values();
      for (ToolComponent cls : clses){
        allKids[j] = (IProjectComponent) cls;
        j++;
      }
    }
    //ctypes
    if (cTypes != null){
      for (ToolComponent cls : cTypes){
        allKids[j] = (IProjectComponent) cls;
        j++;
      }
    }
    return allKids;
  }


  public IProjectComponent[] getProjectConstants() {
    int kidsSize = ((constants!= null) ? constants.size() : 0);
    IProjectComponent[] allKids = new IProjectComponent[kidsSize];
    int j = 0;
    if (constants != null){
      Object[] consts = constants.toArray();
      for (int i = 0; i < constants.size(); i++, j++){
        allKids[j] = (IProjectComponent) consts[i];
      }
    }
    return allKids;
  }

  public Set<String> getSupplierPlans() {
    return this.supplierPlans;
  }

  public List<String> getSupplierPlansAsList() {
    List<String> list = new ArrayList<String>();
    for (String name : this.supplierPlans){
      list.add(name);
    }
    return list;
  }

  public Set<ToolPlan> getSupplierPlansAsToolPlans(){
    Set<ToolPlan> list = new TreeSet<ToolPlan>(new NameComparator());
    IProject project = getProject();
    for (String name : this.supplierPlans){
      list.add(ToolPlan.fetch(project, name));
    }
    return list;
  }

  public void addModelListener(IModelListener listener) {
    if (!modelListeners.contains(listener))
      modelListeners.add(listener);
  }

  public void removeModelListener(IModelListener listener) {
    modelListeners.remove(listener);
  }

  public void fireModelChanged(Object[] objects, String type, String property) {
    for (int i = 0; i < modelListeners.size(); i++) {
      ((IModelListener) modelListeners.get(i)).modelChanged(objects,
          type, property);
    }
  }

  public void setDocument(IDocument document) {
    this.document = document;
  }

  public IDocument getDocument() {
    return document;
  }
  public String getStartClass() {
    return startClass;
  }
  public void setStartClass(String startClass) {
    propertyChangeSupport.firePropertyChange("startClass", this.startClass,
        this.startClass = startClass);
  }
  public String getStartMethod() {
    return startMethod;
  }
  public void setStartMethod(String startMethod) {
    propertyChangeSupport.firePropertyChange("startMethod", this.startMethod,
        this.startMethod = startMethod);
  }

  public String getType() {
    return type;
  }
  public void setType(String type) {
    propertyChangeSupport.firePropertyChange("type", this.type,
        this.type = type);
  }
  public String getProjectType() {
    return projectType;
  }
  public void setProjectType(String projectType) {
    propertyChangeSupport.firePropertyChange("projectType", this.projectType,
        this.projectType = projectType);
  }
  public boolean isLibrary() {
    return library;
  }
  public void setLibrary(boolean library) {
    propertyChangeSupport.firePropertyChange("library", this.library,
        this.library = library);
  }
  public boolean isRestricted() {
    return Restricted;
  }
  public void setRestricted(boolean restricted) {
    propertyChangeSupport.firePropertyChange("restricted", this.Restricted,
        this.Restricted = restricted);
  }
  public boolean isMultiThreaded() {
    return MultiThreaded;
  }
  public void setMultiThreaded(boolean multiThreaded) {
    propertyChangeSupport.firePropertyChange("multiThreaded", this.MultiThreaded,
        this.MultiThreaded = multiThreaded);
  }
  public boolean isInternal() {
    return Internal;
  }
  public void setInternal(boolean internal) {
    propertyChangeSupport.firePropertyChange("internal", this.Internal,
        this.Internal = internal);
  }
  public String getLibraryName() {
    return libraryName;
  }
  public void setLibraryName(String libraryName) {
    propertyChangeSupport.firePropertyChange("libraryName", this.libraryName,
        this.libraryName = libraryName);
  }
  public java.util.UUID getUUID() {
    return UUID;
  }
  public void setUUID(java.util.UUID uuid) {
    propertyChangeSupport.firePropertyChange("UUID", this.UUID,
        this.UUID = uuid);
  }

  public int getCompatibilityLevel() {
    return compatibilityLevel;
  }
  public void setCompatibilityLevel(int compatibilityLevel) {
    propertyChangeSupport.firePropertyChange("compatibilityLevel",
        this.compatibilityLevel,
        this.compatibilityLevel = compatibilityLevel);
  }
  public IProject getProject(){
    if ( this.file == null)
      return null;
    return this.file.getProject();
  }
  public static Map<String, ToolPlan> getPlanCache(IProject project){
    Map<String, ToolPlan> cache = null;
    try {
      cache = (Map<String, ToolPlan>)project.getSessionProperty(new QualifiedName(ToolProjectSupport.PROJECT_QUALIFIED_NAME, ToolProjectSupport.PLAN_CACHE));
      if (cache == null){
        cache = new HashMap<String, ToolPlan>();
        project.setSessionProperty(new QualifiedName(ToolProjectSupport.PROJECT_QUALIFIED_NAME, ToolProjectSupport.PLAN_CACHE), cache);
      }
    } catch (CoreException e) {
      ToolPlugin.showError("Error getting Plan cache", e);
    }
    return cache;
  }
  public static Map<String, ToolPlan> getForteLibraryCache(){
    /*
     * if the cache is empty, load it
     */
    if (forteLibraryCache.isEmpty()){
      try {
        URL url = Platform.getBundle(ToolPlugin.PLUGIN_ID).getEntry("UDSLibraries");
        File udsLibraries;
        udsLibraries = new File(FileLocator.toFileURL(url).toURI());
        File[] files = udsLibraries.listFiles(new FileFilter() {

          @Override
          public boolean accept(File pathname) {
            if (pathname.getName().endsWith(".pex"))
              return true;
            return false;
          }
        });
        if (files != null){
          for (File fOrig : files){
            ToolPlan plan = createPlanFromFile(fOrig);
            forteLibraryCache.put(plan.getToolName().toUpperCase(), plan);
          }
        }

      } catch (URISyntaxException e) {
        ToolPlugin.showError("Error creating Tool library cache", e);
      } catch (IOException e) {
        ToolPlugin.showError("Error creating Tool library cache", e);
      }
    }
    return forteLibraryCache;
  }
  public static ToolPlan newPlan(IFolder sourceFolder, String newPlanName, boolean display, boolean dataBase) {
    ToolPlan newToolPlan = new ToolPlan(newPlanName);
    if (display)
      newToolPlan.addSupplierPlan("DisplayProject");
    if (dataBase)
      newToolPlan.addSupplierPlan("GenericDBMS");
    IFile prxFile = sourceFolder.getFile(newPlanName +".prx");
    newToolPlan.setFile(prxFile);
    newToolPlan.writePrxFile();

    getPlanCache(sourceFolder.getProject()).put(newPlanName, newToolPlan);
    return newToolPlan;
  }
  public void addSupplierPlan(String supplierPlanName) {
    if (supplierPlans == null){
      supplierPlans = new HashSet<String>();
    }
    if (supplierPlans.contains(supplierPlanName))
      return;
    supplierPlans.add(supplierPlanName);
    setDirty(true);
  }

  public void addConstant(ToolConstant constant){
    if (constants == null)
      constants = new ArrayList<ToolConstant>();
    constants.add(constant);
  }

  public void addClass(ToolClass newCass){
    if (classes == null)
      classes = new HashMap<String, ToolClass>();
    classes.put(newCass.getLabelText().toUpperCase(), newCass);
    setDirty(true);
  }
  public void addCType(ToolCType newType){
    if (cTypes == null)
      cTypes = new HashSet<ToolCType>();
    cTypes.add(newType);
    setDirty(true);
  }
 
  public IFile writePrxFile(){
   
    try {
      URL url = Platform.getBundle(ToolPlugin.PLUGIN_ID).getEntry("StringTemplates/Tool/PRX.stg");
      File lemplateFile = new File(FileLocator.toFileURL(url).toURI());
      writePrxFile(lemplateFile.toString());
    } catch (IOException e) {
      ToolPlugin.showError("Error writing project file", e);
    } catch (URISyntaxException e) {
      ToolPlugin.showError("Error writing project file", e);
    } catch (CoreException e) {
      ToolPlugin.showError("Error writing project file", e);
    }
    return getFile();
   
  }

  public void writePrxFile(String templateFileName) throws IOException, CoreException{
    FileReader reader = new FileReader(templateFileName);
    StringTemplateGroup templates = new StringTemplateGroup(reader);
    StringTemplate prxTemplate = templates.lookupTemplate("prxFile");
    prxTemplate.setAttribute("plan", this);
    String output = prxTemplate.toString();
    if (this.document != null && this.provider != null){
      this.document.set(output);
      this.provider.saveDocument(new NullProgressMonitor(), this.file, this.document, true);
    }

  }

  public void removeComponent(ToolComponent toolClass) {
    this.classes.remove(toolClass.getToolName());
  }

  public void addSupplierTo(String name){
    if (this.supplierTo == null)
      this.supplierTo = new HashSet<String>();
    this.supplierTo.add(name);

  }

  @Override
  public String toString() {
    return "Project: " + getProject().getName() + " Plan: " + getToolName();
  }
  @Override
  public String getLabelText() {
    return getToolName();
  }
  @Override
  public String getLabelText(int options) {
    return getLabelText();
  }
  public List<ToolCursor> getCursors() {
    if (this.cursors == null){
      this.cursors = new ArrayList<ToolCursor>();
    }
   
    if (isLibrary() || isFortePlan()){
      return this.cursors;
    } else {
      IFolder folder = (IFolder)getFile().getParent();
      List<ToolCursor> cursors = new ArrayList<ToolCursor>();
      try {
        for (IResource file : folder.members()){
          if (!file.getFileExtension().equalsIgnoreCase("cur"))
            continue;
          ToolCursor cls = ToolCursor.fetch((IFile)file);
          if (cls != null)
            cursors.add(cls);
        }
       
      } catch (CoreException e) {
        ToolPlugin.showError("Error finding cursors for plan", e);
      }
      return cursors;
    }
  }

  public List<ToolClass> getClasses(){
    List<ToolClass> classes = new ArrayList<ToolClass>();
    if (isLibrary() || isFortePlan()){
      /*
       * the classes are parsed from the PEX files
       * so they are stored as children in this class
       */
      if (this.classes != null){
        for (Object cls : this.classes.values()){
          classes.add((ToolClass)cls);
        }
      }
    } else {
      /*
       * get the class resources from the IFolder
       */
      IFolder folder = (IFolder)getFile().getParent();
      try {
        for (IResource file : folder.members()){
          if (!file.getFileExtension().equalsIgnoreCase("cdf"))
            continue;
          ToolClass cls = ToolClass.fetch((IFile)file);
          if (cls != null)
            classes.add(cls);
        }
      } catch (CoreException e) {
        ToolPlugin.showError("Error finding classes for plan", e);
      }
    }
    return classes;
  }

  public List<ToolServiceObject> getServiceObjects() {
    List<ToolServiceObject> soList = new ArrayList<ToolServiceObject>();
    if (isLibrary() || isFortePlan()){
      /*
       * the service objects are parsed from the PEX files
       * so they are stored as children in this class
       */
      if (this.serviceObjects != null){
        for (Object so : this.serviceObjects.values()){
          soList.add((ToolServiceObject)so);
        }
      }
    } else {
      /*
       * get the class resources from the IFolder
       */
      IFolder folder = (IFolder)getFile().getParent();
      try {
        for (IResource file : folder.members()){
          if (!file.getFileExtension().equalsIgnoreCase("so"))
            continue;
          ToolServiceObject cls = ToolServiceObject.fetch((IFile)file);
          if (cls != null)
            soList.add(cls);
        }
      } catch (CoreException e) {
        ToolPlugin.showError("Error finding service objects for plan", e);
      }
    }
    return soList;
  }


  public List<ToolInterface> getInterfaces(){
    List<ToolInterface> interfaces = new ArrayList<ToolInterface>();
    if (isLibrary() || isFortePlan()){
      /*
       * the classes are parsed from the PEX files
       * so they are stored as children in this class
       */
      if (this.interfaces != null){
        for (Object inter : this.interfaces.values()){
          interfaces.add((ToolInterface)inter);
        }
      }
    } else {
      /*
       * get the class resources from the IFolder
       */
      IFolder folder = (IFolder)getFile().getParent();

      try {
        InterfaceContentDescriber icd = new InterfaceContentDescriber();
        for (IResource file : folder.members()){
          if (!file.getFileExtension().equalsIgnoreCase("cdf"))
            continue;
          if (icd.describe(((IFile)file).getContents(), null) != IContentDescriber.VALID)
            continue;
          ToolInterface inter = ToolInterface.fetch(file.getProject(), (IFile)file);
          if (inter != null)
            interfaces.add(inter);
        }
      } catch (CoreException e) {
        ToolPlugin.showError("Error finding interfaces for plan", e);
      } catch (IOException e) {
        ToolPlugin.showError("Error finding interfaces for plan", e);
      }
    }
    return interfaces;
  }
  public List<ToolConstant> getConstants() {
    return constants;
  }

  public List<ToolCType> getCTypes(){
    List<ToolCType> cTypes = new ArrayList<ToolCType>();
    if (isLibrary() || isFortePlan()){
      /*
       * the cTypes are parsed from the PEX files
       * so they are stored as children in this class
       */
      if (this.cTypes != null){
        for (Object ct : this.cTypes){
          cTypes.add((ToolCType)ct);
        }
      }
    }
    return cTypes;
  }

  public boolean isFortePlan(){
    return ToolProjectSupport.forteLibrariesSet.contains(this.getToolName());
  }

  public void clearSuppliers(){
    this.supplierPlans = null;
  }
  @Override
  public void reportError(String error) {
    this.parseErrors.append(error + "\n");

  }

  public void addForwardDeclaration(String name, ToolForwardDeclaration.Kind kind){
    ToolForwardDeclaration forward = new ToolForwardDeclaration(name, kind);
    this.forwardDeclarations.put(name, forward);
  }
 
  public Map<String,ToolForwardDeclaration> getForwardDeclarations(){
    return this.forwardDeclarations;
  }
  public List<ToolForwardDeclaration> listForwardDeclarations(){
    return new ArrayList<ToolForwardDeclaration>(this.forwardDeclarations.values());
  }
}
TOP

Related Classes of tool.model.ToolPlan

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.