Package tool.model

Source Code of tool.model.ToolPlan

package tool.model;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
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.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.IContainer;
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.resources.IResourceProxy;
import org.eclipse.core.resources.IResourceProxyVisitor;
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.Path;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.QualifiedName;
import org.eclipse.core.runtime.content.IContentDescriber;
import org.eclipse.core.runtime.jobs.Job;
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.InterfaceContentDescriber;
import tool.model.grammar.ErrorReporter;
import tool.model.grammar.ForteAST;
import tool.model.grammar.ForteParser.project_return;
import tool.model.jobs.LoadPlanCacheJob;

public class ToolPlan extends ToolComponent{

  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>();



  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 final String[] forteLibrariesList = new String[] {
    "APPC",
    "Configuration",
    "Corba",
    "CosNaming",
    "DB2",
    "DCE",
    "DDEProject",
    "DisplayProject",
    "EnvManagement",
    "ForeignObjMgr",
    "Framework",
    "GenericDBMS",
    "GenericRepository",
    "HTTP",
    "HTTPSupport",
    "Informix",
    "Ingres",
    "LDAP",
    "ODBC",
    "OLE",
    "OLE2",
    "Oracle",
    "Oracle7",
    "Rdb",
    "Sybase",
    "SybaseCTLib",
    "SystemMonitor",
    "TOOLCompiler",
    "TOOLInterpreter",
    "XMLDOM2",
    "XMLParser",
    "XMLSAX2",
    "XMLSvr",
    "XSLT"
  };
  public static Set<String> forteLibrariesSet = new HashSet<String>();
  public static Set<SupplierPlan> forteLibrariesSupplierPlanSet = new HashSet<SupplierPlan>();
  static {
    for (String libName : forteLibrariesList){
      forteLibrariesSet.add(libName);
      forteLibrariesSupplierPlanSet.add(new SupplierPlan(libName, true, true));
    }
  }

  public static ToolPlan fetch(IProject project, final String name){
    if ((project == null) ||(forteLibrariesSet.contains(name))) {
      ToolPlan fortePlan = getPlanCache(project).get(name.toUpperCase());
      if (fortePlan == null) {
        IFolder udsFolder = project.getFolder(ToolProjectSupport.UDS_LIBRARY_FOLDER_NAME);
        if (!udsFolder.exists()){
          ToolProjectSupport.copyForteLibraries(project);
        }
        IFile udsPlanFile = udsFolder.getFile(name + ".pex");
        if (udsPlanFile.exists()){
          fortePlan = parseUsingGrammar(udsPlanFile);
          getPlanCache(project).put(name.toUpperCase(), fortePlan);
        }
      }
      return fortePlan;
    } else {
      ToolPlan model = getPlanCache(project).get(name.toUpperCase());

      if (model == null){

        try {
          final List<IFolder> planFolderList = new ArrayList<IFolder>();
          project.accept(new IResourceProxyVisitor() {

            @Override
            public boolean visit(IResourceProxy proxy) throws CoreException {
              if ((proxy.getType() == IResource.FOLDER  &&
                  proxy.getName().equalsIgnoreCase(name))){
                planFolderList.add((IFolder) proxy.requestResource());
                return false;
              }
              return true;
            }
          }, IResource.DEPTH_INFINITE);
          if (planFolderList.size() > 0)
            model = fetch(planFolderList.get(0));
        } catch (CoreException e) {
          ToolModelActivator.showError("Error searching for folder: " + name, e);
        }
      }
      return model;
    }
  }
  public static ToolPlan fetch(IFolder planFolder){
    ToolPlan model = getPlanCache(planFolder.getProject()).get(planFolder.getName().toUpperCase());
    if (model == null){
      IFile file = ((IFolder)planFolder.getParent()).getFile(planFolder.getName() + ".pex");
      if (file.exists()){
        model = ToolPlan.createPlanFromFile(file);
        getPlanCache(planFolder.getProject()).put(model.getToolName().toUpperCase(), 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) {
      ToolModelActivator.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;
  }

  public static ToolPlan createPlanFromFile(IFile modelFile){
    ToolPlan prx = null;
     
      prx = parseUsingGrammar(modelFile);
      /*
       * special case for Framework
       */
      createFrameworkScalarTypes(prx);

    return prx;
  }
  protected static ToolPlan createPlanFromFile(File modelFile, IProject project){
    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();
//  TODO    prx.parse(source, project);
      /*
       * special case for Framework
       */
      createFrameworkScalarTypes(prx);

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

  private static void createFrameworkScalarTypes(ToolPlan prx){
    if (prx == null)
      return;
    /*
     * 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.getSupplierPlans()){
        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(IFile file) {
      parseUsingGrammar(file);
  }

  @SuppressWarnings("static-access")
  public static ToolPlan parseUsingGrammar(IFile file){
    try {
    TextFileDocumentProvider provider = new TextFileDocumentProvider();
    provider.connect(file);
    IDocument document = provider.getDocument(file);   
    String source = document.get();
    ErrorReporter parseErrors = new ErrorReporter();
      CommonTree tree = null;
      CommonTokenStream tokens = createTokenStream(source);
      parser.setTokenStream(tokens);
      parser.setErrorReporter(parseErrors);
      parser.setTreeAdaptor(new CommonTreeAdaptor(){
        public Object create(Token payload){
          return new CommonTree(payload);
        }
      });
      project_return result = parser.project();
      if (parser.getNumberOfSyntaxErrors() > 0){
        MessageConsole console = ToolModelActivator.findConsole(ToolModelActivator.TOOL_PARSER_OUTPUT);
        MessageConsoleStream msgStream = console.newMessageStream();
        msgStream.println(parser.getNumberOfSyntaxErrors() + " Syntax error in project " + file.getName() + "\n"
            + parseErrors.toString());
      } else {
        tree = (CommonTree) result.getTree();
        CommonTreeNodeStream nodes = new CommonTreeNodeStream(tree);
        nodes.setTokenStream(tokens);
        ForteAST walker = new ForteAST(file, nodes);
        ToolPlan plan = walker.project();
        plan.document = document;
        if (forteLibrariesSet.contains(plan.getToolName())){
          plan.setLibrary(true);
       
        }
        return plan;
      }
    } catch (RecognitionException e) {
      ToolModelActivator.showError("Cannot parse project "  + file.getName(), e);
    } catch (CoreException e) {
      ToolModelActivator.showError("Cannot parse project "  + file.getName(), e);
    }
    return null;
  }


  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<SupplierPlan> getSupplierPlansAsList() {
    List<SupplierPlan> list = new ArrayList<SupplierPlan>();
    IProject project = getProject();
    for (String name : this.supplierPlans){
      ToolPlan plan = ToolPlan.fetch(project, name);
      SupplierPlan supPlan;
      if (plan == null)
        supPlan = new SupplierPlan(name, true, true);
      else
        supPlan = new SupplierPlan(name, plan.isLibrary(), plan.isFortePlan());
      list.add(supPlan);
    }
    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>();
        LoadPlanCacheJob runner = new LoadPlanCacheJob(project, cache);
        runner.setPriority(Job.INTERACTIVE);
//        runner.schedule();
//        runner.join();
        project.setSessionProperty(new QualifiedName(ToolProjectSupport.PROJECT_QUALIFIED_NAME, ToolProjectSupport.PLAN_CACHE), cache);
      }
    } catch (CoreException e) {
      ToolModelActivator.showError("Error getting Plan cache", e);
//    } catch (InterruptedException e) {
//      ToolModelActivator.showError("Error getting Plan cache", e);
    }
    return cache;
  }
//  public static Map<String, ToolPlan> getForteLibraryCache(IProject project){
//    /*
//     * if the cache is empty, load it
//     */
//    Map<String, ToolPlan> forteLibraryCache =  null;
//    try {
//
//      forteLibraryCache  = (Map<String, ToolPlan>)project.getSessionProperty(new QualifiedName(ToolProjectSupport.PROJECT_QUALIFIED_NAME, ToolProjectSupport.FORTE_LIBRARY_CACHE));   
//
//      if (forteLibraryCache == null){
//        final Map<String, ToolPlan> newCache = new HashMap<String, ToolPlan>();
//        project.setSessionProperty(new QualifiedName(ToolProjectSupport.PROJECT_QUALIFIED_NAME, ToolProjectSupport.PLAN_CACHE), newCache);
//        ToolProjectSupport.copyForteLibraries(project);
////        IFolder udsFolder = project.getFolder(ToolProjectSupport.UDS_LIBRARY_FOLDER_NAME);
////        udsFolder.accept(new IResourceProxyVisitor() {
////          public boolean visit(IResourceProxy proxy) throws CoreException {
////            if (proxy.getType() == IResource.FILE) {
////              IFile file = (IFile) proxy.requestResource();
////                    if (file.getLocation().getFileExtension() != null
////                        && file.getLocation().getFileExtension().matches("pex")) {
////                     
////                      ToolPlan plan = ToolPlan.createPlanFromFile(file);
////                      if (plan != null)
////                        newCache.put(plan.getToolName().toUpperCase(), plan);
////                    }
////                 }
////                 return true;
////          }
////        }, IResource.DEPTH_INFINITE);
//
//        forteLibraryCache = newCache;
//      }
//    } catch (IOException e) {
//      ToolModelActivator.showError("Error creating Tool library cache", e);
//    } catch (CoreException e) {
//      ToolModelActivator.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);
    try {
      IFolder folder = getPlanFolderFromPEX(this.file);
      IFile conFile = folder.getFile(constant.toolName + ".CON");
      if (!conFile.exists()){
        InputStream source = new ByteArrayInputStream(constant.toSource().getBytes());
        conFile.create(source, false, null);
        conFile.refreshLocal(IResource.DEPTH_ZERO, null);
      }
    } catch (CoreException e) {
      ToolModelActivator.log(IStatus.ERROR, "Cannot create constant file", e);
    }
  }

  public void addClass(ToolClass newCass){
//    if (classes == null)
//      classes = new HashMap<String, ToolClass>();
//    classes.put(newCass.getLabelText().toUpperCase(), newCass);
//    setDirty(true);
    System.out.println("Adding class: " + newCass.getToolName());
    try {
      IFolder folder = getPlanFolderFromPEX(this.file);
      IFile conFile = folder.getFile(newCass.toolName + ((newCass.isMapped())? ".WCL" : ".CLA"));
      if (!conFile.exists() && newCass.source != null){
        InputStream source = new ByteArrayInputStream(newCass.source.getBytes());
        conFile.create(source, false, null);
        conFile.getParent().refreshLocal(IResource.DEPTH_ZERO, null);
      }
    } catch (CoreException e) {
      ToolModelActivator.log(IStatus.ERROR, "Cannot create class file", e);
    }
  }
  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(ToolModelActivator.PLUGIN_ID).getEntry("StringTemplates/Tool/PRX.stg");
      File lemplateFile = new File(FileLocator.toFileURL(url).toURI());
      writePrxFile(lemplateFile.toString());
    } catch (IOException e) {
      ToolModelActivator.showError("Error writing project file", e);
    } catch (URISyntaxException e) {
      ToolModelActivator.showError("Error writing project file", e);
    } catch (CoreException e) {
      ToolModelActivator.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) {
        ToolModelActivator.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) {
        ToolModelActivator.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) {
        ToolModelActivator.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) {
        ToolModelActivator.showError("Error finding interfaces for plan", e);
      } catch (IOException e) {
        ToolModelActivator.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;
  }

  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());
  }
 
  public static IFolder getPlanFolderFromPEX(IFile pexFile){
    IContainer parent = pexFile.getParent();
    String planName = pexFile.getName().substring(0, pexFile.getName().lastIndexOf('.'));
    IFolder folder = (IFolder) parent.getFolder(new Path(planName));
    if (!folder.exists()){
      try {
        folder.create(true, true, null);
        folder.getParent().refreshLocal(IResource.DEPTH_ZERO, null);
      } catch (CoreException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
     
    }
    return folder;
  }
}
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.