job #63 - remove calls to create and populate a model instance that is then never used.

.//=====================================================================
.//
.//  File:      $RCSfile: create_core_plugin_class.arc,v $
.//  Version:   $Revision: 1.64 $
.//  Modified:  $Date: 2013/05/10 13:26:39 $
.//
.// Copyright 2006-2013 by Mentor Graphics Corporation. All rights reserved.
.//
.//=====================================================================
.// This document contains information proprietary and confidential to
.// Mentor Graphics Corp. and is not for external distribution.
.//=====================================================================
.//
.invoke arc_env = GET_ENV_VAR( "PTC_MC_ARC_DIR" )
.assign mc_archetypes = arc_env.result
.if ( mc_archetypes == "" )
  .print "\nERROR: Environment variable PTC_MC_ARC_DIR not set."
  .exit 100
.end if
.//
.function create_core_plugin_class
  .param string path

  .assign default_image = "package_obj.gif"
package com.mentor.nucleus.bp.core;
//======================================================================
//
// File: ${path}/CorePlugin.java
//
// WARNING:      Do not edit this generated file
// Generated by: ${info.arch_file_name}
// Version:      $$Revision: 1.64 $$
//
// (c) Copyright 2006-2013 by Mentor Graphics Corp. All rights reserved.
//
//======================================================================
//
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
import java.util.Vector;

import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResourceChangeEvent;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.FileLocator;
import org.eclipse.core.runtime.IConfigurationElement;
import org.eclipse.core.runtime.IExtension;
import org.eclipse.core.runtime.IExtensionPoint;
import org.eclipse.core.runtime.IExtensionRegistry;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.MultiStatus;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.dialogs.ErrorDialog;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.MessageDialogWithToggle;
import org.eclipse.jface.preference.*;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.resource.ImageRegistry;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.swt.dnd.Clipboard;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.actions.ExportResourcesAction;
import org.eclipse.ui.actions.ImportResourcesAction;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.plugin.AbstractUIPlugin;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.service.prefs.Preferences;

import com.mentor.nucleus.bp.core.common.BridgePointPreferencesStore;
import com.mentor.nucleus.bp.core.common.ComponentResourceListener;
import com.mentor.nucleus.bp.core.common.IAllActivityModifier;
import com.mentor.nucleus.bp.core.common.NonRootModelElement;
import com.mentor.nucleus.bp.core.common.ModelRoot;
import com.mentor.nucleus.bp.core.common.IPasteListener;
import com.mentor.nucleus.bp.core.common.PersistenceChangeTracker;
import com.mentor.nucleus.bp.core.ui.AbstractModelExportFactory;
import com.mentor.nucleus.bp.core.ui.AbstractModelImportFactory;
import com.mentor.nucleus.bp.core.ui.AbstractStreamExportFactory;
import com.mentor.nucleus.bp.core.ui.AbstractStreamImportFactory;
import com.mentor.nucleus.bp.core.ui.DeleteAction;
import com.mentor.nucleus.bp.core.ui.IModelImport;
import com.mentor.nucleus.bp.core.ui.RenameAction;
import com.mentor.nucleus.bp.core.ui.marker.DelayedMarkerJob;
import com.mentor.nucleus.bp.core.ui.marker.ProblemModelChangeListener;
import com.mentor.nucleus.bp.core.ui.preferences.BridgePointProjectReferencesPreferenceNode;

/**
 * The main plugin class to be used in the desktop.
 */
public class CorePlugin extends AbstractUIPlugin {
	//The shared instance.
	private static CorePlugin plugin;
	//Resource bundle.
	private ResourceBundle resourceBundle;
	private static Clipboard clipboard;
	//Delete and rename actions;
	private static Action deleteAction;
	private static Vector renameActions = new Vector();

	private static ImageRegistry imageRegistry = null;
	private static final int FILE_FORMAT_ERROR = 1;
	public static final String MODEL_LOAD_ERROR = "Problem loading model";
	public static final String DUPLICATE_NAME_ERROR = "Name already exists.";
	public static final String INVALID_NAME_SPACES = "Spaces are not allowed in the name of an element of this type.";
	public static final String DANGLING_REFERENCE_DECORATOR_ID = "com.mentor.nucleus.bp.ui.explorer.decorators.danglingreferencedecorator"; //$$NON-NLS-1$$
	public static final Object UPGRADE_FAMILY = "UPGRADE_FAMILY"; //$$NON-NLS-1$$
    public static PrintStream out = System.out;

    public static PrintStream err = System.err;

    public static boolean loggingEnabled = true;

    private static ProblemModelChangeListener problemListener;

    private static NonRootModelElement[] loadedGlobals;

	/**
	 * The constructor.
	 */
	public CorePlugin() {
		super();
		plugin = this;
		try {
			resourceBundle = ResourceBundle.getBundle("com.mentor.nucleus.bp.core.CorePluginResources"); //$$NON-NLS-1$$
		} catch (MissingResourceException x) {
			resourceBundle = null;
		}
		IExtensionRegistry reg = Platform.getExtensionRegistry();
		IExtensionPoint extPt = reg.getExtensionPoint("com.mentor.nucleus.bp.core.editors"); //$$NON-NLS-1$$
		IExtension[] exts = extPt.getExtensions();
		for (int i = 0; i < exts.length; i++) {
			IConfigurationElement[] elems = exts[i].getConfigurationElements();
			for (int j = 0; j < elems.length; j++) {
				if (elems[j].getName().equals("editor")) { //$$NON-NLS-1$$
					String listenerClass = elems[j].getAttribute("listenerClass"); //$$NON-NLS-1$$
					if (listenerClass != null && !listenerClass.equals("")) {
						try {
							Runnable listener = (Runnable) elems[j].createExecutableExtension("listenerClass"); //$$NON-NLS-1$$
							listener.run();
						} catch (CoreException e) {
							logError( "Model Listener class "
									+ elems[j].getAttribute("listenerClass")//$$NON-NLS-1$$
									+ " not loaded.", e );
						}
					}
				}
			}
		}
		loadGlobals();
	}

	private void loadGlobals() {
		Bundle bpBundle = Platform.getBundle("com.mentor.nucleus.bp.pkg");
		Path globalsPath = new Path("globals/Globals.xtuml");
		URL fileURL = FileLocator.find(bpBundle, globalsPath, null);
		String fileName = null;
		try {
			fileURL = FileLocator.resolve(fileURL);
			fileName = fileURL.getFile();
		} catch (IOException e) {
			String msg = "Unable to locate: globals/Globals.xtuml.  ";
			if (bpBundle == null) {
				msg += "Unable to get bundle: com.mentor.nucleus.bp.pkg  ";
			}
			if (fileURL == null) {
				msg += "The file URL is null. ";
			} else {
				msg += "The file URL is: \n";
				msg += "\tProtocol: " + fileURL.getProtocol() + "\n";
				msg += "\tPort: " + fileURL.getPort() + "\n";
				msg += "\tHost: " + fileURL.getHost() + "\n";
				msg += "\tFile: " + fileURL.getFile() + "\n";
				msg += "\tExternalForm: " + fileURL.toExternalForm() + "\n";
			}
			logError( msg, e);  //$$NON-NLS-1$$
		}
		AbstractModelImportFactory mif = CorePlugin.getModelImportFactory();
		try {
		  IModelImport importer = mif.create(fileName,
                        Ooaofooa.getDefaultInstance(), null, false, true, true);
		  importer.run(new NullProgressMonitor());
		  loadedGlobals = importer.getLoadedInstances();
		}
		catch (FileNotFoundException fnf) {
			CorePlugin.logError(
			  "Internal error: Global element definition file not found.", fnf);
		} catch (InvocationTargetException e) {
			CorePlugin.logError("Internal error: Could not load global element definition file.", e);
		} catch (InterruptedException e) {
			CorePlugin.logError("Internal error: Could not load global element definition file.", e);
		}
	}

	public static NonRootModelElement[] getLoadedGlobals() {
		return loadedGlobals;
	}

	static private AbstractModelImportFactory modelImportFactory = null;
	static private AbstractModelImportFactory sqlImportFactory = null;
	static private AbstractStreamExportFactory streamExportFactory = null;
	static private AbstractStreamImportFactory streamImportFactory = null;

	public static AbstractModelImportFactory getSqlImportFactory(){
		if (sqlImportFactory == null) {
			sqlImportFactory = AbstractModelImportFactory.getInstance(
				"com.mentor.nucleus.bp.io.sql", //$$NON-NLS-1$$
				"ImportModelFactory"); //$$NON-NLS-1$$
      }
		return sqlImportFactory;
    }

	public static AbstractModelImportFactory getModelImportFactory(){
		if (modelImportFactory == null) {
			modelImportFactory = AbstractModelImportFactory.getInstance(
				"com.mentor.nucleus.bp.io.mdl", //$$NON-NLS-1$$
				"ImportModelFactory"); //$$NON-NLS-1$$
  }
		return modelImportFactory;
	}

	public static AbstractStreamExportFactory getStreamExportFactory() {
		if (streamExportFactory == null) {
			streamExportFactory = AbstractStreamExportFactory.getInstance(
					"com.mentor.nucleus.bp.io.mdl", //$$NON-NLS-1$$
					"ExportStreamFactory"); //$$NON-NLS-1$$
		}
		return streamExportFactory;
	}

	public static AbstractStreamImportFactory getStreamImportFactory() {
		if (streamImportFactory == null) {
			streamImportFactory = AbstractStreamImportFactory.getInstance(
					"com.mentor.nucleus.bp.io.mdl", //$$NON-NLS-1$$
					"ImportStreamFactory"); //$$NON-NLS-1$$
		}
		return streamImportFactory;
	}

	public String doLoadSql(SystemModel_c system, String rootId, File model,
		IProgressMonitor monitor, boolean parseAll, boolean isTemplate) {
		return executeImportFactory(getSqlImportFactory(), system, rootId, model, monitor, parseAll, isTemplate);
		}

	public String doLoad(SystemModel_c system, String rootId, InputStream model,
		IProgressMonitor monitor, boolean parseAll, boolean isTemplate) {
		return executeImportFactory(getModelImportFactory(), system, rootId, model, monitor, parseAll, isTemplate);
		}

	private String executeImportFactory(
		AbstractModelImportFactory importFactory,
		SystemModel_c system,
		String rootId,
		File model,
		IProgressMonitor monitor,
		boolean parseAll, boolean isTemplate) {
		try {
			IModelImport im = importFactory.create(
				model.getAbsolutePath(),
				Ooaofooa.getInstance(rootId, false),
				system,
				parseAll,
				true, isTemplate);
			int validate_result = im.countAndValidateInsertStatements();
			if (validate_result > 0) {
				im.run(monitor);
			}
			return im.getErrorMessage();
		} catch (FileNotFoundException fnf) {
			logError(MODEL_LOAD_ERROR, fnf);
		} catch (InterruptedException i) {
			logError(MODEL_LOAD_ERROR, i);
		} catch (InvocationTargetException it) {
			logError(MODEL_LOAD_ERROR, it);
		}
		return "Problem loading model, see error log";
	}
	private String executeImportFactory(
		AbstractModelImportFactory importFactory,
		SystemModel_c system,
		String rootId,
		InputStream model,
		IProgressMonitor monitor,
		boolean parseAll, boolean isTemplate) {
		try {
			IModelImport im = importFactory.create(model, Ooaofooa
				..getInstance(rootId, false), system, parseAll, true, true, isTemplate);
			int validate_result = im.countAndValidateInsertStatements();
			if (validate_result > 0) {
				im.run(monitor);
			}
			return im.getErrorMessage();
		} catch (IOException io) {
			logError(MODEL_LOAD_ERROR, io);
		} catch (InterruptedException i) {
			logError(MODEL_LOAD_ERROR, i);
		} catch (InvocationTargetException it) {
			logError(MODEL_LOAD_ERROR, it);
		}
		return "Problem loading model, see error log";
	}
	public static MultiStatus createImportErrorStatus(
		boolean isFileImport,
		String errorMessage) {

		final String headers[] = new String[] {
				"There was an error loading the model",
				"There was an error importing the file" };
		String name = getDefault().getBundle().getSymbolicName();
		MultiStatus errorStatus = new MultiStatus(
			name,
			FILE_FORMAT_ERROR,
			headers[isFileImport ? 1 : 0],
			null);
		String[] msg_lines = errorMessage.split("\n"); //$$NON-NLS-1$$
		for (int i = 0; i < msg_lines.length; ++i) {
			errorStatus.add(new Status(
				IStatus.ERROR,
				name,
				FILE_FORMAT_ERROR,
				msg_lines[i],
				null));
		}
		CorePlugin.getDefault().getLog().log(errorStatus);
		return errorStatus;
	}
	public static void showImportErrorMessage(
		boolean isFileImport,
		String errorMessage) {
		final String titles[] = new String[] { "Error loading model",
				"Invalid File" };
		MultiStatus errorStatus = createImportErrorStatus(
			isFileImport,
			errorMessage);
		ErrorDialog.openError(
			PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(),
			titles[isFileImport ? 1 : 0],
			null,
			errorStatus);
	}
	/**
	 * Returns the shared instance.
	 */
	public static CorePlugin getDefault() {
		return plugin;
	}
	/**
	 * Get the preferences store, force the BridgePoint preferences to be refreshed.
	 */
    public IPreferenceStore getPreferenceStore() {
    	IPreferenceStore store = super.getPreferenceStore();
    	return store;
    }
	/**
	 * Returns the workspace instance.
	 */
	public static IWorkspace getWorkspace() {
		return ResourcesPlugin.getWorkspace();
	}
	/**
	 * Returns the string from the plugin's resource bundle,
	 * or 'key' if not found.
	 */
	public static String getResourceString(String key) {
		ResourceBundle bundle = CorePlugin.getDefault().getResourceBundle();
		try {
			return bundle.getString(key);
		} catch (MissingResourceException e) {
			return key;
		}
	}
	/**
	 * Returns the plugin's resource bundle,
	 */
	public ResourceBundle getResourceBundle() {
		return resourceBundle;
	}
	/**
	 * Returns the ImageDescriptor instance identified by the passed
	 * string.
	 */
    public static ImageDescriptor getImageDescriptor(String name) {
        String iconPath = "icons/";
        try {
            CorePlugin plugin = getDefault();
            if (plugin == null) {
                RuntimeException rtException = new RuntimeException("Unable to acquire the CorePlugin therefore the icon " + iconPath + name + " can not be loaded.");
                throw rtException;
            }
            URL installURL = plugin.getBundle().getEntry("/");
            URL url = new URL(installURL, iconPath + name);

            InputStream check = null;
            try {
                check = url.openStream();
            } catch (IOException e1) {
                logError("Can not load the icon: " + iconPath + name, e1);
            } finally{
                if (check != null){
                    try {
                        check.close();
                    } catch (IOException e2) {

                    }
                }
            }

            ImageDescriptor imageDescriptor = getStaticImageRegistry().getDescriptor(name);
            if (imageDescriptor == null) {
                imageDescriptor = ImageDescriptor.createFromURL(url);
                if((!name.equals("InterfaceOperation_c")) && (!name.equals("InterfaceSignal_c")
                    && (!name.equals("ProvidedOperation_c")) && (!name.equals("ProvidedSignal_c"))
                    && (!name.equals("RequiredOperation_c")) && (!name.equals("RequiredSignal_c"))))
                 {
                    getStaticImageRegistry().put(name, imageDescriptor);
                 }
            }
            return imageDescriptor;
        } catch (RuntimeException e) {
            // this can happen if we fail to acquire a model builder license.
            return ImageDescriptor.getMissingImageDescriptor();
        } catch (MalformedURLException e) {
            // this can happen if we fail to acquire a model builder license.
            return ImageDescriptor.getMissingImageDescriptor();
        }
    }

    public static Image getImageFor(String imagePath) {
    	Image image = getStaticImageRegistry().get(imagePath);
    	if(image == null) {
        	ImageDescriptor descriptor = getImageDescriptor(imagePath);
    		image = descriptor.createImage();
    	}
    	return image;
    }

    public static Image getImageFor(Object object) {
    	return getImageFor(object, true);
    }

    public static Image getImageFor(Object object, boolean returnDefaultOnFail) {
        String type = object.getClass().getName();
        //Removing the packge name from the type string
        //We need to remove the full package path

        if (type.lastIndexOf('.') != -1)
            type = type.substring(type.lastIndexOf('.') + 1);

        return getImageFor(type, false,object, returnDefaultOnFail);
    }

    public static ImageDescriptor getImageDescriptorFor(String objectName, boolean stripName){
    	return getImageDescriptorFor(objectName, stripName, true);
    }
    public static ImageDescriptor getImageDescriptorFor(String objectName, boolean stripName, boolean returnDefaultOnFail){
      return getImageDescriptorFor(objectName, stripName, null, returnDefaultOnFail);

    }

    public static ImageDescriptor getImageDescriptorFor(String Name, boolean stripName, Object object, boolean returnDefaultOnFail) {
        String objectName;
        int direction;

        InterfaceOperation_c interfaceOperation;
        InterfaceSignal_c    interfaceSignal;
        ProvidedOperation_c providedOperation;
        ProvidedSignal_c providedSignal;
        RequiredOperation_c requiredOperation;
        RequiredSignal_c requiredSignal;

        if(object == null){
          objectName = Name;
          if (stripName){
            if (objectName.lastIndexOf('.') != -1) {
              objectName = objectName.substring(objectName.lastIndexOf('.') + 1);
            }
           }
        }else{

          objectName = object.getClass().getName();
          if (objectName.lastIndexOf('.') != -1) {
            objectName = objectName.substring(objectName.lastIndexOf('.') + 1);
          }
          objectName = extendNameIfNecessary(object, objectName);
        }

        ImageDescriptor descriptor = null;

  .select many tree_nodes from instances of T_TNS
  .for each node in tree_nodes
    .select any node_class from instances of O_OBJ where (selected.Key_Lett == node.Key_Lett)
    .invoke class_name = get_class_name(node_class)
    .if (class_name.body == "InterfaceOperation_c")
    else if (objectName.equals("InterfaceOperation_cClientServer")) {
      descriptor = getImageDescriptor("metadata/toProviderOperation.gif");
    } else if (objectName.equals("InterfaceOperation_cServerClient")) {
      descriptor = getImageDescriptor("metadata/fromProviderOperation.gif");
    }
    // else if(objectName.equals("InterfaceOperation_cBiDirectional")) {
    // descriptor = getImageDescriptor("metadata/bidirectionalOperation.gif");
    // }
    .elif (class_name.body == "InterfaceSignal_c")
    else if (objectName.equals("InterfaceSignal_cClientServer")) {
      descriptor = getImageDescriptor("metadata/toProviderSignal.gif");
    } else if (objectName.equals("InterfaceSignal_cServerClient")) {
      descriptor = getImageDescriptor("metadata/fromProviderSignal.gif");
    }
    // else if(objectName.equals("InterfaceSignal_cBiDirectional")) {
    // descriptor = getImageDescriptor("metadata/bidirectionalSignal.gif");
    // }
    .elif (class_name.body == "ProvidedOperation_c")
    else if (objectName.equals("ProvidedOperation_cClientServer")) {
      descriptor = getImageDescriptor("metadata/incomingOperation.gif");
    } else if (objectName.equals("ProvidedOperation_cServerClient")) {
      descriptor = getImageDescriptor("metadata/outgoingOperation.gif");
    }
    else if(objectName.equals("ProvidedOperation_c")) {
    	descriptor = getImageDescriptor("metadata/ProvidedOperation.gif");
    }
    // else if(objectName.equals("ProvidedOperation_cBiDirectional")) {
    // descriptor = getImageDescriptor("metadata/InOutOperation.gif");
    // }
    .elif (class_name.body == "ProvidedSignal_c")
    else if (objectName.equals("ProvidedSignal_cClientServer")) {
      descriptor = getImageDescriptor("metadata/incomingSignal.gif");
    } else if (objectName.equals("ProvidedSignal_cServerClient")) {
      descriptor = getImageDescriptor("metadata/outgoingSignal.gif");
    }
    else if(objectName.equals("ProvidedSignal_c")) {
    	descriptor = getImageDescriptor("metadata/ProvidedSignal.gif");
    }
    // else if(objectName.equals("ProvidedSignal_cBiDirectional")) {
    // descriptor = getImageDescriptor("metadata/InOutSignal.gif");
    // }
    .elif (class_name.body == "RequiredOperation_c")
    else if (objectName.equals("RequiredOperation_cClientServer")) {
      descriptor = getImageDescriptor("metadata/outgoingOperation.gif");
    } else if (objectName.equals("RequiredOperation_cServerClient")) {
      descriptor = getImageDescriptor("metadata/incomingOperation.gif");
    }
    else if(objectName.equals("RequiredOperation_c")) {
    	descriptor = getImageDescriptor("metadata/RequiredOperation.gif");
    }
    // else if(objectName.equals("RequiredOperation_cBiDirectional")) {
    // descriptor = getImageDescriptor("metadata/InOutOperation.gif");
    // }
    .elif (class_name.body == "RequiredSignal_c")
    else if (objectName.equals("RequiredSignal_cClientServer")) {
      descriptor = getImageDescriptor("metadata/outgoingSignal.gif");
    } else if (objectName.equals("RequiredSignal_cServerClient")) {
      descriptor = getImageDescriptor("metadata/incomingSignal.gif");
    }
    else if(objectName.equals("RequiredSignal_c")) {
    	descriptor = getImageDescriptor("metadata/RequiredSignal.gif");
    }
    // else if(objectName.equals("RequiredSignal_cBiDirectional")) {
    // descriptor = getImageDescriptor("metadata/InOutSignal.gif");
    // }
    .else
      .if (first tree_nodes)
            if (objectName.equals("${class_name.body}")) {
      .else
            else if (objectName.equals("${class_name.body}")) {
      .end if
.//
      .if (node.Icon != "")
            descriptor = getImageDescriptor("metadata/${node.Icon}");
      .else
                descriptor = getImageDescriptor("${default_image}");
      .end if
            }
    .end if
  .end for
            else if (objectName.equals("NewOperation")){
                String v_direction = Pref_c.Getstring("bridgepoint_prefs_message_direction");
                if ((v_direction.equals("from provider")))
                    descriptor = getImageDescriptor("metadata/fromProviderOperation.gif");
                else // To Provider
                    descriptor = getImageDescriptor("metadata/toProviderOperation.gif");
                //else  /* bidirectional */
                       //descriptor = getImageDescriptor("metadata/bidirectionalOperation.gif");
            }
            else if (objectName.equals("NewSignal")){
                String v_direction = Pref_c.Getstring("bridgepoint_prefs_message_direction");
                if ((v_direction.equals("from provider")))
                    descriptor = getImageDescriptor("metadata/fromProviderSignal.gif");
                else  // To Provider
                    descriptor = getImageDescriptor("metadata/toProviderSignal.gif");
                //else  /* bidirectional */
                       //descriptor = getImageDescriptor("metadata/bidirectionalSignal.gif");
            }
            else {
                if(returnDefaultOnFail) {
                	descriptor = getImageDescriptor("${default_image}");
                }
            }

        return descriptor;
    }

	public static Image getImageFor(String objectName, boolean stripName) {
		return getImageFor(objectName, stripName, true);
	}
    public static Image getImageFor(String objectName, boolean stripName, boolean returnDefaultOnFail) {

           return getImageFor(objectName, stripName,null, returnDefaultOnFail);
    }

    public static Image getImageFor(String objectName, boolean stripName,Object object, boolean returnDefaultOnFail) {

        if (stripName){
            if (objectName.lastIndexOf('.') != -1)
            objectName = objectName.substring(objectName.lastIndexOf('.') + 1);
        }
        objectName = extendNameIfNecessary(object, objectName);
        Image image = getStaticImageRegistry().get(objectName);
        if (image == null) {
            ImageDescriptor descriptor = getImageDescriptorFor(objectName, false ,object, returnDefaultOnFail);
            if (descriptor == null) {
                return null;
            } else {
                image = descriptor.createImage();
                getStaticImageRegistry().put(objectName, image);
            }
        }
        return image;
    }
    private static String extendNameIfNecessary(Object object, String name) {
      int dir = Ifdirectiontype_c.OOA_UNINITIALIZED_ENUM;
      if (object instanceof InterfaceOperation_c) {
        dir = ((InterfaceOperation_c)object).getDirection();
      }
      if (object instanceof InterfaceSignal_c) {
        dir = ((InterfaceSignal_c)object).getDirection();
      }
      if (object instanceof ProvidedOperation_c) {
        dir = ((ProvidedOperation_c) object).Getmessagedirection();
      }
      if (object instanceof ProvidedSignal_c) {
        dir = ((ProvidedSignal_c)object).Getmessagedirection();
      }
      if (object instanceof RequiredOperation_c) {
        dir = ((RequiredOperation_c)object).Getmessagedirection();
      }
      if (object instanceof RequiredSignal_c) {
        dir = ((RequiredSignal_c)object).Getmessagedirection();
      }
      if (dir == Ifdirectiontype_c.ClientServer) {
        name += "ClientServer";
      }
      if (dir == Ifdirectiontype_c.ServerClient) {
        name += "ServerClient";
      }
      //if (dir == Ifdirectiontype_c.BiDirectional) {
      //  name += "BiDirectional";
      //}
      return name;
    }
	/* (non-Javadoc)
	 * @see org.osgi.framework.BundleActivator#start(org.osgi.framework.BundleContext)
	 */
	public void start(BundleContext context) throws Exception {
		super.start(context);

        ComponentResourceListener synchronizer = ComponentResourceListener.getDefaultInstance();

		ResourcesPlugin.getWorkspace().addResourceChangeListener(synchronizer, IResourceChangeEvent.POST_CHANGE);

		problemListener = new ProblemModelChangeListener();
        Ooaofooa.addModelChangeListenerToAll(problemListener);
	}
	public void stop(BundleContext context) throws Exception {
		Ooaofooa.removeModelChangeListenerFromAll(problemListener);
		Ooaofooa.shutdown();
		DelayedMarkerJob.internal_cancel();
		super.stop(context);
	}
	/**
	 * Returns the plugin's delete action,
	 */
	public static Action getDeleteAction() {
		if (deleteAction == null) {
			deleteAction = new DeleteAction(getImageDescriptor("delete_edit.gif")); //$$NON-NLS-1$$
		}
		return deleteAction;
	}
	/**
	 * Returns the plugin's rename action,
	 */
	public static Action getRenameAction(TreeViewer viewer) {
		RenameAction renameAction = null;
		for (Iterator i = renameActions.iterator(); i.hasNext();) {
			renameAction = (RenameAction) i.next();
			if (renameAction.getTree().equals(viewer.getTree())) {
				return renameAction;
			}
		}
		// no existing action was found, create a new one
		renameAction = new RenameAction(viewer);
		renameActions.add(renameAction);
		return renameAction;
	}
	public static void logError(String msg, Throwable e) {
		CorePlugin cp = getDefault();
		// plugin is null when running unit tests
		if (cp != null) {
			Status status = new Status(IStatus.ERROR, getName(), IStatus.ERROR, msg, e);
			cp.getLog().log(status);
		} else {
			System.err.println(msg);
			if (e != null) {
				e.printStackTrace();
			}
		}
	}
	private static final boolean caseInsensitive = new File("a").compareTo(new File("A")) == 0; //$$NON-NLS-1$$ //$$NON-NLS-2$$
	public static boolean osIsCaseInsensitive() {
	  return caseInsensitive;
	}

    /**
     * Returns the name of this plug-in.  This method exists because this
     * plug-in's bundle, from which callers would normally obtain the name,
     * is not yet associated with this plug-in until partway through this
     * plug-in's initialization.
     */
    public static String getName()
    {
        // if this plug-in has an associated bundle
        CorePlugin plugin = getDefault();
        Bundle bundle = plugin.getBundle();
        if (bundle != null) {
            // return the name supplied by the bundle
            return bundle.getSymbolicName();
        }

        // otherwise, return a default name
        return "com.mentor.nucleus.bp.core"; //$$NON-NLS-1$$
    }

	public static void setOut(PrintStream out) {
		CorePlugin.out = out;
	}

	public static void setErr(PrintStream err) {
		CorePlugin.err = err;
	}

    /**
     * Determine if parse should be done.  The user may be prompted to
     * do the parse, so this method must be executed in the UI thread.
     *
     * @return true if parse should be done
     */
    public boolean getParseAllOnResourceChange() {
        IPreferenceStore store = getPreferenceStore();
        String option = store.getString(BridgePointPreferencesStore.PARSE_ALL_ON_RESOURCE_CHANGE);
        if (option.equals(MessageDialogWithToggle.ALWAYS)) {
            return true;
        } else if (option.equals(MessageDialogWithToggle.NEVER)) {
            return false;
        }

        MessageDialogWithToggle m = MessageDialogWithToggle.openYesNoQuestion(
            PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(),
            "Parse All Activities",
            "Import Complete, parse all action language?",
            "&Remember my decision",
            false,
            store,
            BridgePointPreferencesStore.PARSE_ALL_ON_RESOURCE_CHANGE);

        int result = m.getReturnCode();
        switch (result) {
            // yes, ok
            case IDialogConstants.YES_ID :
            case IDialogConstants.OK_ID :
                return true;
            // no
            case IDialogConstants.NO_ID :
                return false;
        }

        // default is to parse
        return true;
}

    /**
     * Sets 'parse all on resource change' to "Always"
     * Used by unit tests
     *
     */
    public static void enableParseAllOnResourceChange() {
        IPreferenceStore store = getDefault().getPreferenceStore();
        store.setValue(BridgePointPreferencesStore.PARSE_ALL_ON_RESOURCE_CHANGE, MessageDialogWithToggle.ALWAYS);
    }

    /**
     * Sets 'parse all on resource change' to "Never"
     * Used by unit tests
     *
     */
    public static void disableParseAllOnResourceChange() {
        IPreferenceStore store = getDefault().getPreferenceStore();
        store.setValue(BridgePointPreferencesStore.PARSE_ALL_ON_RESOURCE_CHANGE, MessageDialogWithToggle.NEVER);
    }

    /**
     * Parses all activities in domain using monitor
     * The method uses reflection to prevent an explicit circular dependency
     * on the com.mentor.nucleus.bp.ui.text package.
     */
    public static void parseAll(Domain_c domain, IProgressMonitor monitor) {
        try {
            Bundle ui_text = Platform.getBundle("com.mentor.nucleus.bp.ui.text");//$$NON-NLS-1$$
            Class factoryClass = ui_text.loadClass("com.mentor.nucleus.bp.ui.text.activity.AllActivityModifier"); //$$NON-NLS-1$$

            // find the constructor that takes domain and monitor as parameters
            Class [] arg_types = new Class[] { Domain_c.class, IProgressMonitor.class };
            Constructor ctor = factoryClass.getDeclaredConstructor(arg_types);

            // invoke the constructor to create an instance
            Object [] args = new Object[] { domain, monitor };
            IAllActivityModifier aam = (IAllActivityModifier)ctor.newInstance(args);

            aam.processAllActivities(IAllActivityModifier.PARSE);
        } catch (ClassNotFoundException cnf) {
            CorePlugin.logError("Problem loading activity parser ", cnf);
        } catch (IllegalAccessException i) {
            CorePlugin.logError("Problem loading activity parser ", i);
        } catch (InstantiationException i) {
            CorePlugin.logError("Problem loading activity parser ", i);
        } catch (InvocationTargetException e) {
            CorePlugin.logError("Problem running activity parser ", e);
        } catch (SecurityException e) {
            CorePlugin.logError("Problem running activity parser ", e);
        } catch (NoSuchMethodException e) {
            CorePlugin.logError("Problem running activity parser ", e);
        }
    }

    	/**
		 * Parses all given activities using monitor
		 * The method uses reflection to prevent an explicit circular dependency
		 * on the com.mentor.nucleus.bp.ui.text package.
		 */
		public static void parseAllActions(ModelRoot root, Object[] activities,
				IProgressMonitor monitor) {
			try {
				Bundle ui_text = Platform.getBundle("com.mentor.nucleus.bp.ui.text");//$$NON-NLS-1$$
				Class factoryClass = ui_text.loadClass("com.mentor.nucleus.bp.ui.text.activity.AllActivityModifier"); //$$NON-NLS-1$$

				// find the constructor that takes the element and monitor as parameters
				Class[] arg_types = new Class[] { ModelRoot.class, Object[].class,
						IProgressMonitor.class };
				Constructor ctor = factoryClass.getDeclaredConstructor(arg_types);

				// invoke the constructor to create an instance
				Object[] args = new Object[] { root, activities, monitor };
				IAllActivityModifier aam = (IAllActivityModifier) ctor.newInstance(args);

				aam.processAllActivities(IAllActivityModifier.PARSE);
			} catch (ClassNotFoundException cnf) {
				CorePlugin.logError("Problem loading activity parser ", cnf);
			} catch (IllegalAccessException i) {
				CorePlugin.logError("Problem loading activity parser ", i);
			} catch (InstantiationException i) {
				CorePlugin.logError("Problem loading activity parser ", i);
			} catch (InvocationTargetException e) {
				CorePlugin.logError("Problem running activity parser ", e);
			} catch (SecurityException e) {
				CorePlugin.logError("Problem running activity parser ", e);
			} catch (NoSuchMethodException e) {
				CorePlugin.logError("Problem running activity parser ", e);
			}
		}

	  /**
	 	 *  Returns the clipboard used throughout the execution
	   *  of BridgePoint
	 	 */
		public static Clipboard getSystemClipboard() {
				if(clipboard == null) {
						clipboard = new Clipboard(PlatformUI.getWorkbench().getDisplay());
				}
				return clipboard;
		}
  	private static Action importAction;
	  private static Action exportAction;

 		/**
		 * Returns the import action used across the workbench
		 *
		 */
		public static Action getResourceImportAction() {
			if(importAction == null) {
				importAction = new ImportResourcesAction(PlatformUI.getWorkbench().getActiveWorkbenchWindow());
			} return importAction;
		}

		/**
		 * Returns the export action used across the workbench
		 */
		public static Action getResourceExportAction() {
			if(exportAction == null) {
				exportAction = new ExportResourcesAction(PlatformUI.getWorkbench().getActiveWorkbenchWindow());
			} return exportAction;
		}

		/**
		 * Returns a filesystem path to the entry inside the core plugin
		 */
		public static String getEntryPath(String entry) throws IOException {
	        URL url = getDefault().getBundle().getEntry(entry);
	        URL resolvedURL = null;
	        try {
	            resolvedURL =  FileLocator.resolve(url);
	        } catch (IOException e) {
	            throw e;
	        }
	        return resolvedURL.getPath();
	    }

		// map used to store old instance keys that have changed during
		// an import or paste
		private static HashMap<NonRootModelElement, Object> fImportedElementKeyMap = new HashMap<NonRootModelElement, Object>();
		public static HashMap<NonRootModelElement, Object> getImportedElementKeyMap() {
			return fImportedElementKeyMap;
   		}

   		public static boolean decorationRequestsDisabled = false;
		public static void disableProblemMarkerDecorationRequests() {
			decorationRequestsDisabled = true;
		}

		public static void enableProblemMarkerDecorationRequests() {
			decorationRequestsDisabled = false;
		}

		public static boolean getProblemMarkerDecorationRequestsDisabled() {
			// there are currently no problem markers, therefore we do
			// not need decoration support
			return true;
		}

		private static List<IPasteListener> pasteListeners = new ArrayList<IPasteListener>();

		public static List<IPasteListener> getPasteListeners() {
			return pasteListeners;
		}

		public static void addPasteListener(IPasteListener listener) {
			pasteListeners.add(listener);
		}

		public static void removePasteListener(IPasteListener listener) {
			pasteListeners.remove(listener);
		}

		public static PreferenceManager getProjectPreferenceManager(Preferences projectNode) {
			PreferenceManager pm = new PreferenceManager();
			PreferenceNode pn = new BridgePointProjectReferencesPreferenceNode(projectNode);
			pm.addToRoot(pn);
			return pm;
        }

        /**
         * This routine intializes the static member imageRegistry if it has not been initialized.
         * This is done here instead of in a member initializer for plugin start-up purposes.
         * When called from the command-line there may not be a workbench.
         */
		private static ImageRegistry getStaticImageRegistry() {
			if (imageRegistry == null) {
				if (Display.getCurrent() != null) {
					imageRegistry = new ImageRegistry(Display.getCurrent());
				} else {
					imageRegistry = new ImageRegistry(PlatformUI.getWorkbench().getDisplay());
				}
			}
			return imageRegistry;
		}

		public static AbstractModelExportFactory getModelExportFactory() {
			return AbstractModelExportFactory.getInstance();
		}

		/**
		 * This method returns the current file persistence format version
		 * for the current tool version.
		 *
		 * @return
		 */
		public static String getPersistenceVersion() {
			return PersistenceChangeTracker.getCurrentVersion().getPersistenceVersion();
		}

		public static void addProjectForPEUpgrade(IProject project) {
			try {
				Bundle bundle = Platform.getBundle("com.mentor.nucleus.bp.io.mdl"); //$$NON-NLS-1$$
				Class<?> clazz = bundle.loadClass("com.mentor.nucleus.bp.io.mdl.upgrade.UpgradeUtil"); //$$NON-NLS-1$$
				Method method = clazz.getMethod("addProjectForPEUpgrade", new Class[] {IProject.class}); //$$NON-NLS-1$$
				method.invoke(clazz, new Object[] {project});
			} catch (ClassNotFoundException e) {
				CorePlugin.logError("Unable to perform model upgrade.", e);
			} catch (SecurityException e) {
				CorePlugin.logError("Unable to perform model upgrade.", e);
			} catch (NoSuchMethodException e) {
				CorePlugin.logError("Unable to perform model upgrade.", e);
			} catch (IllegalArgumentException e) {
				CorePlugin.logError("Unable to perform model upgrade.", e);
			} catch (IllegalAccessException e) {
				CorePlugin.logError("Unable to perform model upgrade.", e);
			} catch (InvocationTargetException e) {
				CorePlugin.logError("Unable to perform model upgrade.", e);
			}
		}

		public static void addProjectsForPEUpgrade(IProject[] projects) {
			try {
				Bundle bundle = Platform.getBundle("com.mentor.nucleus.bp.io.mdl"); //$$NON-NLS-1$$
				Class<?> clazz = bundle.loadClass("com.mentor.nucleus.bp.io.mdl.upgrade.UpgradeUtil"); //$$NON-NLS-1$$
				Method method = clazz.getMethod("addProjectsForPEUpgrade", new Class[] {IProject[].class}); //$$NON-NLS-1$$
				method.invoke(clazz, new Object[] {projects});
			} catch (ClassNotFoundException e) {
				CorePlugin.logError("Unable to perform model upgrade.", e);
			} catch (SecurityException e) {
				CorePlugin.logError("Unable to perform model upgrade.", e);
			} catch (NoSuchMethodException e) {
				CorePlugin.logError("Unable to perform model upgrade.", e);
			} catch (IllegalArgumentException e) {
				CorePlugin.logError("Unable to perform model upgrade.", e);
			} catch (IllegalAccessException e) {
				CorePlugin.logError("Unable to perform model upgrade.", e);
			} catch (InvocationTargetException e) {
				CorePlugin.logError("Unable to perform model upgrade.", e);
			}
		}
}
.end function
.include "${mc_archetypes}/arch_utils.inc"
.assign path = "src/com/mentor/nucleus/bp/core"

.invoke x = create_core_plugin_class( path )

${x.body}

.emit to file "${path}/CorePlugin.java"

.//=====================================================================
.//
.//  File:      $RCSfile: create_core_plugin_class.arc,v $
.//  Version:   $Revision: 1.64 $
.//  Modified:  $Date: 2013/05/10 13:26:39 $
.//
.// Copyright 2006-2013 by Mentor Graphics Corporation. All rights reserved.
.//
.//=====================================================================
.// This document contains information proprietary and confidential to
.// Mentor Graphics Corp. and is not for external distribution.
.//=====================================================================
.//
.invoke arc_env = GET_ENV_VAR( "PTC_MC_ARC_DIR" )
.assign mc_archetypes = arc_env.result
.if ( mc_archetypes == "" )
  .print "\nERROR: Environment variable PTC_MC_ARC_DIR not set."
  .exit 100
.end if
.//
.function create_core_plugin_class
  .param string path

  .assign default_image = "package_obj.gif"
package com.mentor.nucleus.bp.core;
//======================================================================
//
// File: ${path}/CorePlugin.java
//
// WARNING:      Do not edit this generated file
// Generated by: ${info.arch_file_name}
// Version:      $$Revision: 1.64 $$
//
// (c) Copyright 2006-2013 by Mentor Graphics Corp. All rights reserved.
//
//======================================================================
//
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
import java.util.Vector;

import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResourceChangeEvent;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.FileLocator;
import org.eclipse.core.runtime.IConfigurationElement;
import org.eclipse.core.runtime.IExtension;
import org.eclipse.core.runtime.IExtensionPoint;
import org.eclipse.core.runtime.IExtensionRegistry;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.MultiStatus;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.dialogs.ErrorDialog;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.MessageDialogWithToggle;
import org.eclipse.jface.preference.*;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.resource.ImageRegistry;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.swt.dnd.Clipboard;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.actions.ExportResourcesAction;
import org.eclipse.ui.actions.ImportResourcesAction;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.plugin.AbstractUIPlugin;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.service.prefs.Preferences;

import com.mentor.nucleus.bp.core.common.BridgePointPreferencesModel;
import com.mentor.nucleus.bp.core.common.BridgePointPreferencesStore;
import com.mentor.nucleus.bp.core.common.ComponentResourceListener;
import com.mentor.nucleus.bp.core.common.IAllActivityModifier;
import com.mentor.nucleus.bp.core.common.NonRootModelElement;
import com.mentor.nucleus.bp.core.common.ModelRoot;
import com.mentor.nucleus.bp.core.common.IPasteListener;
import com.mentor.nucleus.bp.core.common.PersistenceChangeTracker;
import com.mentor.nucleus.bp.core.ui.AbstractModelExportFactory;
import com.mentor.nucleus.bp.core.ui.AbstractModelImportFactory;
import com.mentor.nucleus.bp.core.ui.AbstractStreamExportFactory;
import com.mentor.nucleus.bp.core.ui.AbstractStreamImportFactory;
import com.mentor.nucleus.bp.core.ui.DeleteAction;
import com.mentor.nucleus.bp.core.ui.IModelImport;
import com.mentor.nucleus.bp.core.ui.RenameAction;
import com.mentor.nucleus.bp.core.ui.marker.DelayedMarkerJob;
import com.mentor.nucleus.bp.core.ui.marker.ProblemModelChangeListener;
import com.mentor.nucleus.bp.core.ui.preferences.BridgePointProjectReferencesPreferenceNode;

/**
 * The main plugin class to be used in the desktop.
 */
public class CorePlugin extends AbstractUIPlugin {
	//The shared instance.
	private static CorePlugin plugin;
	//Resource bundle.
	private ResourceBundle resourceBundle;
	private static Clipboard clipboard;
	//Delete and rename actions;
	private static Action deleteAction;
	private static Vector renameActions = new Vector();

	private static ImageRegistry imageRegistry = null;
	private static final int FILE_FORMAT_ERROR = 1;
	public static final String MODEL_LOAD_ERROR = "Problem loading model";
	public static final String DUPLICATE_NAME_ERROR = "Name already exists.";
	public static final String INVALID_NAME_SPACES = "Spaces are not allowed in the name of an element of this type.";
	public static final String DANGLING_REFERENCE_DECORATOR_ID = "com.mentor.nucleus.bp.ui.explorer.decorators.danglingreferencedecorator"; //$$NON-NLS-1$$
	public static final Object UPGRADE_FAMILY = "UPGRADE_FAMILY"; //$$NON-NLS-1$$
    public static PrintStream out = System.out;

    public static PrintStream err = System.err;

    public static boolean loggingEnabled = true;

    private static ProblemModelChangeListener problemListener;

    private static NonRootModelElement[] loadedGlobals;

	/**
	 * The constructor.
	 */
	public CorePlugin() {
		super();
		plugin = this;
		try {
			resourceBundle = ResourceBundle.getBundle("com.mentor.nucleus.bp.core.CorePluginResources"); //$$NON-NLS-1$$
		} catch (MissingResourceException x) {
			resourceBundle = null;
		}
		IExtensionRegistry reg = Platform.getExtensionRegistry();
		IExtensionPoint extPt = reg.getExtensionPoint("com.mentor.nucleus.bp.core.editors"); //$$NON-NLS-1$$
		IExtension[] exts = extPt.getExtensions();
		for (int i = 0; i < exts.length; i++) {
			IConfigurationElement[] elems = exts[i].getConfigurationElements();
			for (int j = 0; j < elems.length; j++) {
				if (elems[j].getName().equals("editor")) { //$$NON-NLS-1$$
					String listenerClass = elems[j].getAttribute("listenerClass"); //$$NON-NLS-1$$
					if (listenerClass != null && !listenerClass.equals("")) {
						try {
							Runnable listener = (Runnable) elems[j].createExecutableExtension("listenerClass"); //$$NON-NLS-1$$
							listener.run();
						} catch (CoreException e) {
							logError( "Model Listener class "
									+ elems[j].getAttribute("listenerClass")//$$NON-NLS-1$$
									+ " not loaded.", e );
						}
					}
				}
			}
		}
		loadGlobals();
	}

	private void loadGlobals() {
		Bundle bpBundle = Platform.getBundle("com.mentor.nucleus.bp.pkg");
		Path globalsPath = new Path("globals/Globals.xtuml");
		URL fileURL = FileLocator.find(bpBundle, globalsPath, null);
		String fileName = null;
		try {
			fileURL = FileLocator.resolve(fileURL);
			fileName = fileURL.getFile();
		} catch (IOException e) {
			String msg = "Unable to locate: globals/Globals.xtuml.  ";
			if (bpBundle == null) {
				msg += "Unable to get bundle: com.mentor.nucleus.bp.pkg  ";
			}
			if (fileURL == null) {
				msg += "The file URL is null. ";
			} else {
				msg += "The file URL is: \n";
				msg += "\tProtocol: " + fileURL.getProtocol() + "\n";
				msg += "\tPort: " + fileURL.getPort() + "\n";
				msg += "\tHost: " + fileURL.getHost() + "\n";
				msg += "\tFile: " + fileURL.getFile() + "\n";
				msg += "\tExternalForm: " + fileURL.toExternalForm() + "\n";
			}
			logError( msg, e);  //$$NON-NLS-1$$
		}
		AbstractModelImportFactory mif = CorePlugin.getModelImportFactory();
		try {
		  IModelImport importer = mif.create(fileName,
                        Ooaofooa.getDefaultInstance(), null, false, true, true);
		  importer.run(new NullProgressMonitor());
		  loadedGlobals = importer.getLoadedInstances();
		}
		catch (FileNotFoundException fnf) {
			CorePlugin.logError(
			  "Internal error: Global element definition file not found.", fnf);
		} catch (InvocationTargetException e) {
			CorePlugin.logError("Internal error: Could not load global element definition file.", e);
		} catch (InterruptedException e) {
			CorePlugin.logError("Internal error: Could not load global element definition file.", e);
		}
	}

	public static NonRootModelElement[] getLoadedGlobals() {
		return loadedGlobals;
	}

	static private AbstractModelImportFactory modelImportFactory = null;
	static private AbstractModelImportFactory sqlImportFactory = null;
	static private AbstractStreamExportFactory streamExportFactory = null;
	static private AbstractStreamImportFactory streamImportFactory = null;

	public static AbstractModelImportFactory getSqlImportFactory(){
		if (sqlImportFactory == null) {
			sqlImportFactory = AbstractModelImportFactory.getInstance(
				"com.mentor.nucleus.bp.io.sql", //$$NON-NLS-1$$
				"ImportModelFactory"); //$$NON-NLS-1$$
      }
		return sqlImportFactory;
    }

	public static AbstractModelImportFactory getModelImportFactory(){
		if (modelImportFactory == null) {
			modelImportFactory = AbstractModelImportFactory.getInstance(
				"com.mentor.nucleus.bp.io.mdl", //$$NON-NLS-1$$
				"ImportModelFactory"); //$$NON-NLS-1$$
  }
		return modelImportFactory;
	}

	public static AbstractStreamExportFactory getStreamExportFactory() {
		if (streamExportFactory == null) {
			streamExportFactory = AbstractStreamExportFactory.getInstance(
					"com.mentor.nucleus.bp.io.mdl", //$$NON-NLS-1$$
					"ExportStreamFactory"); //$$NON-NLS-1$$
		}
		return streamExportFactory;
	}

	public static AbstractStreamImportFactory getStreamImportFactory() {
		if (streamImportFactory == null) {
			streamImportFactory = AbstractStreamImportFactory.getInstance(
					"com.mentor.nucleus.bp.io.mdl", //$$NON-NLS-1$$
					"ImportStreamFactory"); //$$NON-NLS-1$$
		}
		return streamImportFactory;
	}

	public String doLoadSql(SystemModel_c system, String rootId, File model,
		IProgressMonitor monitor, boolean parseAll, boolean isTemplate) {
		return executeImportFactory(getSqlImportFactory(), system, rootId, model, monitor, parseAll, isTemplate);
		}

	public String doLoad(SystemModel_c system, String rootId, InputStream model,
		IProgressMonitor monitor, boolean parseAll, boolean isTemplate) {
		return executeImportFactory(getModelImportFactory(), system, rootId, model, monitor, parseAll, isTemplate);
		}

	private String executeImportFactory(
		AbstractModelImportFactory importFactory,
		SystemModel_c system,
		String rootId,
		File model,
		IProgressMonitor monitor,
		boolean parseAll, boolean isTemplate) {
		try {
			IModelImport im = importFactory.create(
				model.getAbsolutePath(),
				Ooaofooa.getInstance(rootId, false),
				system,
				parseAll,
				true, isTemplate);
			int validate_result = im.countAndValidateInsertStatements();
			if (validate_result > 0) {
				im.run(monitor);
			}
			return im.getErrorMessage();
		} catch (FileNotFoundException fnf) {
			logError(MODEL_LOAD_ERROR, fnf);
		} catch (InterruptedException i) {
			logError(MODEL_LOAD_ERROR, i);
		} catch (InvocationTargetException it) {
			logError(MODEL_LOAD_ERROR, it);
		}
		return "Problem loading model, see error log";
	}
	private String executeImportFactory(
		AbstractModelImportFactory importFactory,
		SystemModel_c system,
		String rootId,
		InputStream model,
		IProgressMonitor monitor,
		boolean parseAll, boolean isTemplate) {
		try {
			IModelImport im = importFactory.create(model, Ooaofooa
				..getInstance(rootId, false), system, parseAll, true, true, isTemplate);
			int validate_result = im.countAndValidateInsertStatements();
			if (validate_result > 0) {
				im.run(monitor);
			}
			return im.getErrorMessage();
		} catch (IOException io) {
			logError(MODEL_LOAD_ERROR, io);
		} catch (InterruptedException i) {
			logError(MODEL_LOAD_ERROR, i);
		} catch (InvocationTargetException it) {
			logError(MODEL_LOAD_ERROR, it);
		}
		return "Problem loading model, see error log";
	}
	public static MultiStatus createImportErrorStatus(
		boolean isFileImport,
		String errorMessage) {

		final String headers[] = new String[] {
				"There was an error loading the model",
				"There was an error importing the file" };
		String name = getDefault().getBundle().getSymbolicName();
		MultiStatus errorStatus = new MultiStatus(
			name,
			FILE_FORMAT_ERROR,
			headers[isFileImport ? 1 : 0],
			null);
		String[] msg_lines = errorMessage.split("\n"); //$$NON-NLS-1$$
		for (int i = 0; i < msg_lines.length; ++i) {
			errorStatus.add(new Status(
				IStatus.ERROR,
				name,
				FILE_FORMAT_ERROR,
				msg_lines[i],
				null));
		}
		CorePlugin.getDefault().getLog().log(errorStatus);
		return errorStatus;
	}
	public static void showImportErrorMessage(
		boolean isFileImport,
		String errorMessage) {
		final String titles[] = new String[] { "Error loading model",
				"Invalid File" };
		MultiStatus errorStatus = createImportErrorStatus(
			isFileImport,
			errorMessage);
		ErrorDialog.openError(
			PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(),
			titles[isFileImport ? 1 : 0],
			null,
			errorStatus);
	}
	/**
	 * Returns the shared instance.
	 */
	public static CorePlugin getDefault() {
		return plugin;
	}
	/**
	 * Get the preferences store, force the BridgePoint preferences to be refreshed.
	 */
    public IPreferenceStore getPreferenceStore() {
    	IPreferenceStore store = super.getPreferenceStore();
    	BridgePointPreferencesModel model = new BridgePointPreferencesModel();
    	model.getStore().loadModel(store, null, model);
    	return store;
    }
	/**
	 * Returns the workspace instance.
	 */
	public static IWorkspace getWorkspace() {
		return ResourcesPlugin.getWorkspace();
	}
	/**
	 * Returns the string from the plugin's resource bundle,
	 * or 'key' if not found.
	 */
	public static String getResourceString(String key) {
		ResourceBundle bundle = CorePlugin.getDefault().getResourceBundle();
		try {
			return bundle.getString(key);
		} catch (MissingResourceException e) {
			return key;
		}
	}
	/**
	 * Returns the plugin's resource bundle,
	 */
	public ResourceBundle getResourceBundle() {
		return resourceBundle;
	}
	/**
	 * Returns the ImageDescriptor instance identified by the passed
	 * string.
	 */
    public static ImageDescriptor getImageDescriptor(String name) {
        String iconPath = "icons/";
        try {
            CorePlugin plugin = getDefault();
            if (plugin == null) {
                RuntimeException rtException = new RuntimeException("Unable to acquire the CorePlugin therefore the icon " + iconPath + name + " can not be loaded.");
                throw rtException;
            }
            URL installURL = plugin.getBundle().getEntry("/");
            URL url = new URL(installURL, iconPath + name);

            InputStream check = null;
            try {
                check = url.openStream();
            } catch (IOException e1) {
                logError("Can not load the icon: " + iconPath + name, e1);
            } finally{
                if (check != null){
                    try {
                        check.close();
                    } catch (IOException e2) {

                    }
                }
            }

            ImageDescriptor imageDescriptor = getStaticImageRegistry().getDescriptor(name);
            if (imageDescriptor == null) {
                imageDescriptor = ImageDescriptor.createFromURL(url);
                if((!name.equals("InterfaceOperation_c")) && (!name.equals("InterfaceSignal_c")
                    && (!name.equals("ProvidedOperation_c")) && (!name.equals("ProvidedSignal_c"))
                    && (!name.equals("RequiredOperation_c")) && (!name.equals("RequiredSignal_c"))))
                 {
                    getStaticImageRegistry().put(name, imageDescriptor);
                 }
            }
            return imageDescriptor;
        } catch (RuntimeException e) {
            // this can happen if we fail to acquire a model builder license.
            return ImageDescriptor.getMissingImageDescriptor();
        } catch (MalformedURLException e) {
            // this can happen if we fail to acquire a model builder license.
            return ImageDescriptor.getMissingImageDescriptor();
        }
    }

    public static Image getImageFor(String imagePath) {
    	Image image = getStaticImageRegistry().get(imagePath);
    	if(image == null) {
        	ImageDescriptor descriptor = getImageDescriptor(imagePath);
    		image = descriptor.createImage();
    	}
    	return image;
    }

    public static Image getImageFor(Object object) {
    	return getImageFor(object, true);
    }

    public static Image getImageFor(Object object, boolean returnDefaultOnFail) {
        String type = object.getClass().getName();
        //Removing the packge name from the type string
        //We need to remove the full package path

        if (type.lastIndexOf('.') != -1)
            type = type.substring(type.lastIndexOf('.') + 1);

        return getImageFor(type, false,object, returnDefaultOnFail);
    }

    public static ImageDescriptor getImageDescriptorFor(String objectName, boolean stripName){
    	return getImageDescriptorFor(objectName, stripName, true);
    }
    public static ImageDescriptor getImageDescriptorFor(String objectName, boolean stripName, boolean returnDefaultOnFail){
      return getImageDescriptorFor(objectName, stripName, null, returnDefaultOnFail);

    }

    public static ImageDescriptor getImageDescriptorFor(String Name, boolean stripName, Object object, boolean returnDefaultOnFail) {
        String objectName;
        int direction;

        InterfaceOperation_c interfaceOperation;
        InterfaceSignal_c    interfaceSignal;
        ProvidedOperation_c providedOperation;
        ProvidedSignal_c providedSignal;
        RequiredOperation_c requiredOperation;
        RequiredSignal_c requiredSignal;

        if(object == null){
          objectName = Name;
          if (stripName){
            if (objectName.lastIndexOf('.') != -1) {
              objectName = objectName.substring(objectName.lastIndexOf('.') + 1);
            }
           }
        }else{

          objectName = object.getClass().getName();
          if (objectName.lastIndexOf('.') != -1) {
            objectName = objectName.substring(objectName.lastIndexOf('.') + 1);
          }
          objectName = extendNameIfNecessary(object, objectName);
        }

        ImageDescriptor descriptor = null;

  .select many tree_nodes from instances of T_TNS
  .for each node in tree_nodes
    .select any node_class from instances of O_OBJ where (selected.Key_Lett == node.Key_Lett)
    .invoke class_name = get_class_name(node_class)
    .if (class_name.body == "InterfaceOperation_c")
    else if (objectName.equals("InterfaceOperation_cClientServer")) {
      descriptor = getImageDescriptor("metadata/toProviderOperation.gif");
    } else if (objectName.equals("InterfaceOperation_cServerClient")) {
      descriptor = getImageDescriptor("metadata/fromProviderOperation.gif");
    }
    // else if(objectName.equals("InterfaceOperation_cBiDirectional")) {
    // descriptor = getImageDescriptor("metadata/bidirectionalOperation.gif");
    // }
    .elif (class_name.body == "InterfaceSignal_c")
    else if (objectName.equals("InterfaceSignal_cClientServer")) {
      descriptor = getImageDescriptor("metadata/toProviderSignal.gif");
    } else if (objectName.equals("InterfaceSignal_cServerClient")) {
      descriptor = getImageDescriptor("metadata/fromProviderSignal.gif");
    }
    // else if(objectName.equals("InterfaceSignal_cBiDirectional")) {
    // descriptor = getImageDescriptor("metadata/bidirectionalSignal.gif");
    // }
    .elif (class_name.body == "ProvidedOperation_c")
    else if (objectName.equals("ProvidedOperation_cClientServer")) {
      descriptor = getImageDescriptor("metadata/incomingOperation.gif");
    } else if (objectName.equals("ProvidedOperation_cServerClient")) {
      descriptor = getImageDescriptor("metadata/outgoingOperation.gif");
    }
    else if(objectName.equals("ProvidedOperation_c")) {
    	descriptor = getImageDescriptor("metadata/ProvidedOperation.gif");
    }
    // else if(objectName.equals("ProvidedOperation_cBiDirectional")) {
    // descriptor = getImageDescriptor("metadata/InOutOperation.gif");
    // }
    .elif (class_name.body == "ProvidedSignal_c")
    else if (objectName.equals("ProvidedSignal_cClientServer")) {
      descriptor = getImageDescriptor("metadata/incomingSignal.gif");
    } else if (objectName.equals("ProvidedSignal_cServerClient")) {
      descriptor = getImageDescriptor("metadata/outgoingSignal.gif");
    }
    else if(objectName.equals("ProvidedSignal_c")) {
    	descriptor = getImageDescriptor("metadata/ProvidedSignal.gif");
    }
    // else if(objectName.equals("ProvidedSignal_cBiDirectional")) {
    // descriptor = getImageDescriptor("metadata/InOutSignal.gif");
    // }
    .elif (class_name.body == "RequiredOperation_c")
    else if (objectName.equals("RequiredOperation_cClientServer")) {
      descriptor = getImageDescriptor("metadata/outgoingOperation.gif");
    } else if (objectName.equals("RequiredOperation_cServerClient")) {
      descriptor = getImageDescriptor("metadata/incomingOperation.gif");
    }
    else if(objectName.equals("RequiredOperation_c")) {
    	descriptor = getImageDescriptor("metadata/RequiredOperation.gif");
    }
    // else if(objectName.equals("RequiredOperation_cBiDirectional")) {
    // descriptor = getImageDescriptor("metadata/InOutOperation.gif");
    // }
    .elif (class_name.body == "RequiredSignal_c")
    else if (objectName.equals("RequiredSignal_cClientServer")) {
      descriptor = getImageDescriptor("metadata/outgoingSignal.gif");
    } else if (objectName.equals("RequiredSignal_cServerClient")) {
      descriptor = getImageDescriptor("metadata/incomingSignal.gif");
    }
    else if(objectName.equals("RequiredSignal_c")) {
    	descriptor = getImageDescriptor("metadata/RequiredSignal.gif");
    }
    // else if(objectName.equals("RequiredSignal_cBiDirectional")) {
    // descriptor = getImageDescriptor("metadata/InOutSignal.gif");
    // }
    .else
      .if (first tree_nodes)
            if (objectName.equals("${class_name.body}")) {
      .else
            else if (objectName.equals("${class_name.body}")) {
      .end if
.//
      .if (node.Icon != "")
            descriptor = getImageDescriptor("metadata/${node.Icon}");
      .else
                descriptor = getImageDescriptor("${default_image}");
      .end if
            }
    .end if
  .end for
            else if (objectName.equals("NewOperation")){
                String v_direction = Pref_c.Getstring("bridgepoint_prefs_message_direction");
                if ((v_direction.equals("from provider")))
                    descriptor = getImageDescriptor("metadata/fromProviderOperation.gif");
                else // To Provider
                    descriptor = getImageDescriptor("metadata/toProviderOperation.gif");
                //else  /* bidirectional */
                       //descriptor = getImageDescriptor("metadata/bidirectionalOperation.gif");
            }
            else if (objectName.equals("NewSignal")){
                String v_direction = Pref_c.Getstring("bridgepoint_prefs_message_direction");
                if ((v_direction.equals("from provider")))
                    descriptor = getImageDescriptor("metadata/fromProviderSignal.gif");
                else  // To Provider
                    descriptor = getImageDescriptor("metadata/toProviderSignal.gif");
                //else  /* bidirectional */
                       //descriptor = getImageDescriptor("metadata/bidirectionalSignal.gif");
            }
            else {
                if(returnDefaultOnFail) {
                	descriptor = getImageDescriptor("${default_image}");
                }
            }

        return descriptor;
    }

	public static Image getImageFor(String objectName, boolean stripName) {
		return getImageFor(objectName, stripName, true);
	}
    public static Image getImageFor(String objectName, boolean stripName, boolean returnDefaultOnFail) {

           return getImageFor(objectName, stripName,null, returnDefaultOnFail);
    }

    public static Image getImageFor(String objectName, boolean stripName,Object object, boolean returnDefaultOnFail) {

        if (stripName){
            if (objectName.lastIndexOf('.') != -1)
            objectName = objectName.substring(objectName.lastIndexOf('.') + 1);
        }
        objectName = extendNameIfNecessary(object, objectName);
        Image image = getStaticImageRegistry().get(objectName);
        if (image == null) {
            ImageDescriptor descriptor = getImageDescriptorFor(objectName, false ,object, returnDefaultOnFail);
            if (descriptor == null) {
                return null;
            } else {
                image = descriptor.createImage();
                getStaticImageRegistry().put(objectName, image);
            }
        }
        return image;
    }
    private static String extendNameIfNecessary(Object object, String name) {
      int dir = Ifdirectiontype_c.OOA_UNINITIALIZED_ENUM;
      if (object instanceof InterfaceOperation_c) {
        dir = ((InterfaceOperation_c)object).getDirection();
      }
      if (object instanceof InterfaceSignal_c) {
        dir = ((InterfaceSignal_c)object).getDirection();
      }
      if (object instanceof ProvidedOperation_c) {
        dir = ((ProvidedOperation_c) object).Getmessagedirection();
      }
      if (object instanceof ProvidedSignal_c) {
        dir = ((ProvidedSignal_c)object).Getmessagedirection();
      }
      if (object instanceof RequiredOperation_c) {
        dir = ((RequiredOperation_c)object).Getmessagedirection();
      }
      if (object instanceof RequiredSignal_c) {
        dir = ((RequiredSignal_c)object).Getmessagedirection();
      }
      if (dir == Ifdirectiontype_c.ClientServer) {
        name += "ClientServer";
      }
      if (dir == Ifdirectiontype_c.ServerClient) {
        name += "ServerClient";
      }
      //if (dir == Ifdirectiontype_c.BiDirectional) {
      //  name += "BiDirectional";
      //}
      return name;
    }
	/* (non-Javadoc)
	 * @see org.osgi.framework.BundleActivator#start(org.osgi.framework.BundleContext)
	 */
	public void start(BundleContext context) throws Exception {
		super.start(context);

        ComponentResourceListener synchronizer = ComponentResourceListener.getDefaultInstance();

		ResourcesPlugin.getWorkspace().addResourceChangeListener(synchronizer, IResourceChangeEvent.POST_CHANGE);

		problemListener = new ProblemModelChangeListener();
        Ooaofooa.addModelChangeListenerToAll(problemListener);
	}
	public void stop(BundleContext context) throws Exception {
		Ooaofooa.removeModelChangeListenerFromAll(problemListener);
		Ooaofooa.shutdown();
		DelayedMarkerJob.internal_cancel();
		super.stop(context);
	}
	/**
	 * Returns the plugin's delete action,
	 */
	public static Action getDeleteAction() {
		if (deleteAction == null) {
			deleteAction = new DeleteAction(getImageDescriptor("delete_edit.gif")); //$$NON-NLS-1$$
		}
		return deleteAction;
	}
	/**
	 * Returns the plugin's rename action,
	 */
	public static Action getRenameAction(TreeViewer viewer) {
		RenameAction renameAction = null;
		for (Iterator i = renameActions.iterator(); i.hasNext();) {
			renameAction = (RenameAction) i.next();
			if (renameAction.getTree().equals(viewer.getTree())) {
				return renameAction;
			}
		}
		// no existing action was found, create a new one
		renameAction = new RenameAction(viewer);
		renameActions.add(renameAction);
		return renameAction;
	}
	public static void logError(String msg, Throwable e) {
		CorePlugin cp = getDefault();
		// plugin is null when running unit tests
		if (cp != null) {
			Status status = new Status(IStatus.ERROR, getName(), IStatus.ERROR, msg, e);
			cp.getLog().log(status);
		} else {
			System.err.println(msg);
			if (e != null) {
				e.printStackTrace();
			}
		}
	}
	private static final boolean caseInsensitive = new File("a").compareTo(new File("A")) == 0; //$$NON-NLS-1$$ //$$NON-NLS-2$$
	public static boolean osIsCaseInsensitive() {
	  return caseInsensitive;
	}

    /**
     * Returns the name of this plug-in.  This method exists because this
     * plug-in's bundle, from which callers would normally obtain the name,
     * is not yet associated with this plug-in until partway through this
     * plug-in's initialization.
     */
    public static String getName()
    {
        // if this plug-in has an associated bundle
        CorePlugin plugin = getDefault();
        Bundle bundle = plugin.getBundle();
        if (bundle != null) {
            // return the name supplied by the bundle
            return bundle.getSymbolicName();
        }

        // otherwise, return a default name
        return "com.mentor.nucleus.bp.core"; //$$NON-NLS-1$$
    }

	public static void setOut(PrintStream out) {
		CorePlugin.out = out;
	}

	public static void setErr(PrintStream err) {
		CorePlugin.err = err;
	}

    /**
     * Determine if parse should be done.  The user may be prompted to
     * do the parse, so this method must be executed in the UI thread.
     *
     * @return true if parse should be done
     */
    public boolean getParseAllOnResourceChange() {
        IPreferenceStore store = getPreferenceStore();
        String option = store.getString(BridgePointPreferencesStore.PARSE_ALL_ON_RESOURCE_CHANGE);
        if (option.equals(MessageDialogWithToggle.ALWAYS)) {
            return true;
        } else if (option.equals(MessageDialogWithToggle.NEVER)) {
            return false;
        }

        MessageDialogWithToggle m = MessageDialogWithToggle.openYesNoQuestion(
            PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(),
            "Parse All Activities",
            "Import Complete, parse all action language?",
            "&Remember my decision",
            false,
            store,
            BridgePointPreferencesStore.PARSE_ALL_ON_RESOURCE_CHANGE);

        int result = m.getReturnCode();
        switch (result) {
            // yes, ok
            case IDialogConstants.YES_ID :
            case IDialogConstants.OK_ID :
                return true;
            // no
            case IDialogConstants.NO_ID :
                return false;
        }

        // default is to parse
        return true;
}

    /**
     * Sets 'parse all on resource change' to "Always"
     * Used by unit tests
     *
     */
    public static void enableParseAllOnResourceChange() {
        IPreferenceStore store = getDefault().getPreferenceStore();
        store.setValue(BridgePointPreferencesStore.PARSE_ALL_ON_RESOURCE_CHANGE, MessageDialogWithToggle.ALWAYS);
    }

    /**
     * Sets 'parse all on resource change' to "Never"
     * Used by unit tests
     *
     */
    public static void disableParseAllOnResourceChange() {
        IPreferenceStore store = getDefault().getPreferenceStore();
        store.setValue(BridgePointPreferencesStore.PARSE_ALL_ON_RESOURCE_CHANGE, MessageDialogWithToggle.NEVER);
    }

    /**
     * Parses all activities in domain using monitor
     * The method uses reflection to prevent an explicit circular dependency
     * on the com.mentor.nucleus.bp.ui.text package.
     */
    public static void parseAll(Domain_c domain, IProgressMonitor monitor) {
        try {
            Bundle ui_text = Platform.getBundle("com.mentor.nucleus.bp.ui.text");//$$NON-NLS-1$$
            Class factoryClass = ui_text.loadClass("com.mentor.nucleus.bp.ui.text.activity.AllActivityModifier"); //$$NON-NLS-1$$

            // find the constructor that takes domain and monitor as parameters
            Class [] arg_types = new Class[] { Domain_c.class, IProgressMonitor.class };
            Constructor ctor = factoryClass.getDeclaredConstructor(arg_types);

            // invoke the constructor to create an instance
            Object [] args = new Object[] { domain, monitor };
            IAllActivityModifier aam = (IAllActivityModifier)ctor.newInstance(args);

            aam.processAllActivities(IAllActivityModifier.PARSE);
        } catch (ClassNotFoundException cnf) {
            CorePlugin.logError("Problem loading activity parser ", cnf);
        } catch (IllegalAccessException i) {
            CorePlugin.logError("Problem loading activity parser ", i);
        } catch (InstantiationException i) {
            CorePlugin.logError("Problem loading activity parser ", i);
        } catch (InvocationTargetException e) {
            CorePlugin.logError("Problem running activity parser ", e);
        } catch (SecurityException e) {
            CorePlugin.logError("Problem running activity parser ", e);
        } catch (NoSuchMethodException e) {
            CorePlugin.logError("Problem running activity parser ", e);
        }
    }

    	/**
		 * Parses all given activities using monitor
		 * The method uses reflection to prevent an explicit circular dependency
		 * on the com.mentor.nucleus.bp.ui.text package.
		 */
		public static void parseAllActions(ModelRoot root, Object[] activities,
				IProgressMonitor monitor) {
			try {
				Bundle ui_text = Platform.getBundle("com.mentor.nucleus.bp.ui.text");//$$NON-NLS-1$$
				Class factoryClass = ui_text.loadClass("com.mentor.nucleus.bp.ui.text.activity.AllActivityModifier"); //$$NON-NLS-1$$

				// find the constructor that takes the element and monitor as parameters
				Class[] arg_types = new Class[] { ModelRoot.class, Object[].class,
						IProgressMonitor.class };
				Constructor ctor = factoryClass.getDeclaredConstructor(arg_types);

				// invoke the constructor to create an instance
				Object[] args = new Object[] { root, activities, monitor };
				IAllActivityModifier aam = (IAllActivityModifier) ctor.newInstance(args);

				aam.processAllActivities(IAllActivityModifier.PARSE);
			} catch (ClassNotFoundException cnf) {
				CorePlugin.logError("Problem loading activity parser ", cnf);
			} catch (IllegalAccessException i) {
				CorePlugin.logError("Problem loading activity parser ", i);
			} catch (InstantiationException i) {
				CorePlugin.logError("Problem loading activity parser ", i);
			} catch (InvocationTargetException e) {
				CorePlugin.logError("Problem running activity parser ", e);
			} catch (SecurityException e) {
				CorePlugin.logError("Problem running activity parser ", e);
			} catch (NoSuchMethodException e) {
				CorePlugin.logError("Problem running activity parser ", e);
			}
		}

	  /**
	 	 *  Returns the clipboard used throughout the execution
	   *  of BridgePoint
	 	 */
		public static Clipboard getSystemClipboard() {
				if(clipboard == null) {
						clipboard = new Clipboard(PlatformUI.getWorkbench().getDisplay());
				}
				return clipboard;
		}
  	private static Action importAction;
	  private static Action exportAction;

 		/**
		 * Returns the import action used across the workbench
		 *
		 */
		public static Action getResourceImportAction() {
			if(importAction == null) {
				importAction = new ImportResourcesAction(PlatformUI.getWorkbench().getActiveWorkbenchWindow());
			} return importAction;
		}

		/**
		 * Returns the export action used across the workbench
		 */
		public static Action getResourceExportAction() {
			if(exportAction == null) {
				exportAction = new ExportResourcesAction(PlatformUI.getWorkbench().getActiveWorkbenchWindow());
			} return exportAction;
		}

		/**
		 * Returns a filesystem path to the entry inside the core plugin
		 */
		public static String getEntryPath(String entry) throws IOException {
	        URL url = getDefault().getBundle().getEntry(entry);
	        URL resolvedURL = null;
	        try {
	            resolvedURL =  FileLocator.resolve(url);
	        } catch (IOException e) {
	            throw e;
	        }
	        return resolvedURL.getPath();
	    }

		// map used to store old instance keys that have changed during
		// an import or paste
		private static HashMap<NonRootModelElement, Object> fImportedElementKeyMap = new HashMap<NonRootModelElement, Object>();
		public static HashMap<NonRootModelElement, Object> getImportedElementKeyMap() {
			return fImportedElementKeyMap;
   		}

   		public static boolean decorationRequestsDisabled = false;
		public static void disableProblemMarkerDecorationRequests() {
			decorationRequestsDisabled = true;
		}

		public static void enableProblemMarkerDecorationRequests() {
			decorationRequestsDisabled = false;
		}

		public static boolean getProblemMarkerDecorationRequestsDisabled() {
			// there are currently no problem markers, therefore we do
			// not need decoration support
			return true;
		}

		private static List<IPasteListener> pasteListeners = new ArrayList<IPasteListener>();

		public static List<IPasteListener> getPasteListeners() {
			return pasteListeners;
		}

		public static void addPasteListener(IPasteListener listener) {
			pasteListeners.add(listener);
		}

		public static void removePasteListener(IPasteListener listener) {
			pasteListeners.remove(listener);
		}

		public static PreferenceManager getProjectPreferenceManager(Preferences projectNode) {
			PreferenceManager pm = new PreferenceManager();
			PreferenceNode pn = new BridgePointProjectReferencesPreferenceNode(projectNode);
			pm.addToRoot(pn);
			return pm;
        }

        /**
         * This routine intializes the static member imageRegistry if it has not been initialized.
         * This is done here instead of in a member initializer for plugin start-up purposes.
         * When called from the command-line there may not be a workbench.
         */
		private static ImageRegistry getStaticImageRegistry() {
			if (imageRegistry == null) {
				if (Display.getCurrent() != null) {
					imageRegistry = new ImageRegistry(Display.getCurrent());
				} else {
					imageRegistry = new ImageRegistry(PlatformUI.getWorkbench().getDisplay());
				}
			}
			return imageRegistry;
		}

		public static AbstractModelExportFactory getModelExportFactory() {
			return AbstractModelExportFactory.getInstance();
		}

		/**
		 * This method returns the current file persistence format version
		 * for the current tool version.
		 *
		 * @return
		 */
		public static String getPersistenceVersion() {
			return PersistenceChangeTracker.getCurrentVersion().getPersistenceVersion();
		}

		public static void addProjectForPEUpgrade(IProject project) {
			try {
				Bundle bundle = Platform.getBundle("com.mentor.nucleus.bp.io.mdl"); //$$NON-NLS-1$$
				Class<?> clazz = bundle.loadClass("com.mentor.nucleus.bp.io.mdl.upgrade.UpgradeUtil"); //$$NON-NLS-1$$
				Method method = clazz.getMethod("addProjectForPEUpgrade", new Class[] {IProject.class}); //$$NON-NLS-1$$
				method.invoke(clazz, new Object[] {project});
			} catch (ClassNotFoundException e) {
				CorePlugin.logError("Unable to perform model upgrade.", e);
			} catch (SecurityException e) {
				CorePlugin.logError("Unable to perform model upgrade.", e);
			} catch (NoSuchMethodException e) {
				CorePlugin.logError("Unable to perform model upgrade.", e);
			} catch (IllegalArgumentException e) {
				CorePlugin.logError("Unable to perform model upgrade.", e);
			} catch (IllegalAccessException e) {
				CorePlugin.logError("Unable to perform model upgrade.", e);
			} catch (InvocationTargetException e) {
				CorePlugin.logError("Unable to perform model upgrade.", e);
			}
		}

		public static void addProjectsForPEUpgrade(IProject[] projects) {
			try {
				Bundle bundle = Platform.getBundle("com.mentor.nucleus.bp.io.mdl"); //$$NON-NLS-1$$
				Class<?> clazz = bundle.loadClass("com.mentor.nucleus.bp.io.mdl.upgrade.UpgradeUtil"); //$$NON-NLS-1$$
				Method method = clazz.getMethod("addProjectsForPEUpgrade", new Class[] {IProject[].class}); //$$NON-NLS-1$$
				method.invoke(clazz, new Object[] {projects});
			} catch (ClassNotFoundException e) {
				CorePlugin.logError("Unable to perform model upgrade.", e);
			} catch (SecurityException e) {
				CorePlugin.logError("Unable to perform model upgrade.", e);
			} catch (NoSuchMethodException e) {
				CorePlugin.logError("Unable to perform model upgrade.", e);
			} catch (IllegalArgumentException e) {
				CorePlugin.logError("Unable to perform model upgrade.", e);
			} catch (IllegalAccessException e) {
				CorePlugin.logError("Unable to perform model upgrade.", e);
			} catch (InvocationTargetException e) {
				CorePlugin.logError("Unable to perform model upgrade.", e);
			}
		}
}
.end function
.include "${mc_archetypes}/arch_utils.inc"
.assign path = "src/com/mentor/nucleus/bp/core"

.invoke x = create_core_plugin_class( path )

${x.body}

.emit to file "${path}/CorePlugin.java"