diff options
author | afinkbein | 2008-09-26 16:53:01 +0000 |
---|---|---|
committer | afinkbein | 2008-09-26 16:53:01 +0000 |
commit | 1f0c021dc1999bf2b76c51d268a3a24614a29d02 (patch) | |
tree | 61b7e79151bd077766a9ec88c55d9f7ecf239ecf | |
parent | 92ce907dd08771606e7fd6d4ff368ce9982f6d45 (diff) | |
download | org.eclipse.osee-1f0c021dc1999bf2b76c51d268a3a24614a29d02.tar.gz org.eclipse.osee-1f0c021dc1999bf2b76c51d268a3a24614a29d02.tar.xz org.eclipse.osee-1f0c021dc1999bf2b76c51d268a3a24614a29d02.zip |
87 files changed, 6339 insertions, 0 deletions
diff --git a/org.eclipse.osee.framework.ui.plugin/.classpath b/org.eclipse.osee.framework.ui.plugin/.classpath new file mode 100644 index 00000000000..02159672985 --- /dev/null +++ b/org.eclipse.osee.framework.ui.plugin/.classpath @@ -0,0 +1,7 @@ +<?xml version="1.0" encoding="UTF-8"?>
+<classpath>
+ <classpathentry kind="src" path="src"/>
+ <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
+ <classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/>
+ <classpathentry kind="output" path="bin"/>
+</classpath>
diff --git a/org.eclipse.osee.framework.ui.plugin/.project b/org.eclipse.osee.framework.ui.plugin/.project new file mode 100644 index 00000000000..0487983e96f --- /dev/null +++ b/org.eclipse.osee.framework.ui.plugin/.project @@ -0,0 +1,28 @@ +<?xml version="1.0" encoding="UTF-8"?> +<projectDescription> + <name>org.eclipse.osee.framework.ui.plugin</name> + <comment></comment> + <projects> + </projects> + <buildSpec> + <buildCommand> + <name>org.eclipse.jdt.core.javabuilder</name> + <arguments> + </arguments> + </buildCommand> + <buildCommand> + <name>org.eclipse.pde.ManifestBuilder</name> + <arguments> + </arguments> + </buildCommand> + <buildCommand> + <name>org.eclipse.pde.SchemaBuilder</name> + <arguments> + </arguments> + </buildCommand> + </buildSpec> + <natures> + <nature>org.eclipse.pde.PluginNature</nature> + <nature>org.eclipse.jdt.core.javanature</nature> + </natures> +</projectDescription> diff --git a/org.eclipse.osee.framework.ui.plugin/.settings/org.eclipse.jdt.core.prefs b/org.eclipse.osee.framework.ui.plugin/.settings/org.eclipse.jdt.core.prefs new file mode 100644 index 00000000000..a8020f2dc2e --- /dev/null +++ b/org.eclipse.osee.framework.ui.plugin/.settings/org.eclipse.jdt.core.prefs @@ -0,0 +1,12 @@ +#Fri Mar 28 14:00:57 GMT 2008
+eclipse.preferences.version=1
+org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
+org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6
+org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve
+org.eclipse.jdt.core.compiler.compliance=1.6
+org.eclipse.jdt.core.compiler.debug.lineNumber=generate
+org.eclipse.jdt.core.compiler.debug.localVariable=generate
+org.eclipse.jdt.core.compiler.debug.sourceFile=generate
+org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
+org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
+org.eclipse.jdt.core.compiler.source=1.6
diff --git a/org.eclipse.osee.framework.ui.plugin/META-INF/MANIFEST.MF b/org.eclipse.osee.framework.ui.plugin/META-INF/MANIFEST.MF new file mode 100644 index 00000000000..8ee0ceb2ef4 --- /dev/null +++ b/org.eclipse.osee.framework.ui.plugin/META-INF/MANIFEST.MF @@ -0,0 +1,32 @@ +Manifest-Version: 1.0 +Bundle-ManifestVersion: 2 +Bundle-Name: OSEE Framework Ui Plug-in (Incubation) +Bundle-SymbolicName: org.eclipse.osee.framework.ui.plugin;singleton:=true +Bundle-Version: 0.4.0.qualifier +Bundle-Activator: org.eclipse.osee.framework.ui.plugin.OseePluginUiActivator +Bundle-Vendor: Eclipse.org +Require-Bundle: org.apache.commons.lang, + org.eclipse.ui, + org.eclipse.core.runtime, + org.eclipse.osee.framework.jdk.core, + org.eclipse.osee.framework.ui.swt, + org.eclipse.core.resources, + org.eclipse.osee.framework.plugin.core, + org.eclipse.ui.ide, + org.eclipse.jdt.core, + org.eclipse.jdt.ui, + org.eclipse.ui.workbench.texteditor, + org.eclipse.jface.text, + org.eclipse.ui.editors, + org.eclipse.ui.console, + org.eclipse.ui.forms, + org.junit, + org.eclipse.osee.framework.db.connection +Bundle-ActivationPolicy: lazy +Export-Package: org.eclipse.osee.framework.ui.plugin, + org.eclipse.osee.framework.ui.plugin.event, + org.eclipse.osee.framework.ui.plugin.io, + org.eclipse.osee.framework.ui.plugin.security, + org.eclipse.osee.framework.ui.plugin.util +Import-Package: org.eclipse.osee.framework.logging +Bundle-RequiredExecutionEnvironment: JavaSE-1.6 diff --git a/org.eclipse.osee.framework.ui.plugin/build.properties b/org.eclipse.osee.framework.ui.plugin/build.properties new file mode 100644 index 00000000000..c40c94e6ec3 --- /dev/null +++ b/org.eclipse.osee.framework.ui.plugin/build.properties @@ -0,0 +1,8 @@ +bin.includes = META-INF/,\ + images/,\ + plugin.xml,\ + .,\ + schema/ +jars.compile.order = . +source.. = src/ +output.. = bin/ diff --git a/org.eclipse.osee.framework.ui.plugin/images/admin.gif b/org.eclipse.osee.framework.ui.plugin/images/admin.gif Binary files differnew file mode 100644 index 00000000000..11812dfd607 --- /dev/null +++ b/org.eclipse.osee.framework.ui.plugin/images/admin.gif diff --git a/org.eclipse.osee.framework.ui.plugin/images/browse.gif b/org.eclipse.osee.framework.ui.plugin/images/browse.gif Binary files differnew file mode 100644 index 00000000000..55ca8f3a9bf --- /dev/null +++ b/org.eclipse.osee.framework.ui.plugin/images/browse.gif diff --git a/org.eclipse.osee.framework.ui.plugin/images/bug.gif b/org.eclipse.osee.framework.ui.plugin/images/bug.gif Binary files differnew file mode 100644 index 00000000000..9a738e55054 --- /dev/null +++ b/org.eclipse.osee.framework.ui.plugin/images/bug.gif diff --git a/org.eclipse.osee.framework.ui.plugin/images/edit.gif b/org.eclipse.osee.framework.ui.plugin/images/edit.gif Binary files differnew file mode 100644 index 00000000000..22f0c4cba28 --- /dev/null +++ b/org.eclipse.osee.framework.ui.plugin/images/edit.gif diff --git a/org.eclipse.osee.framework.ui.plugin/images/errorSm.gif b/org.eclipse.osee.framework.ui.plugin/images/errorSm.gif Binary files differnew file mode 100644 index 00000000000..8612eaff599 --- /dev/null +++ b/org.eclipse.osee.framework.ui.plugin/images/errorSm.gif diff --git a/org.eclipse.osee.framework.ui.plugin/images/faq.gif b/org.eclipse.osee.framework.ui.plugin/images/faq.gif Binary files differnew file mode 100644 index 00000000000..520c1a8666a --- /dev/null +++ b/org.eclipse.osee.framework.ui.plugin/images/faq.gif diff --git a/org.eclipse.osee.framework.ui.plugin/images/filter.gif b/org.eclipse.osee.framework.ui.plugin/images/filter.gif Binary files differnew file mode 100644 index 00000000000..3d061d77cbe --- /dev/null +++ b/org.eclipse.osee.framework.ui.plugin/images/filter.gif diff --git a/org.eclipse.osee.framework.ui.plugin/images/lockkey.gif b/org.eclipse.osee.framework.ui.plugin/images/lockkey.gif Binary files differnew file mode 100644 index 00000000000..fca03252afd --- /dev/null +++ b/org.eclipse.osee.framework.ui.plugin/images/lockkey.gif diff --git a/org.eclipse.osee.framework.ui.plugin/images/needSave.gif b/org.eclipse.osee.framework.ui.plugin/images/needSave.gif Binary files differnew file mode 100644 index 00000000000..499dd0ca602 --- /dev/null +++ b/org.eclipse.osee.framework.ui.plugin/images/needSave.gif diff --git a/org.eclipse.osee.framework.ui.plugin/images/new.gif b/org.eclipse.osee.framework.ui.plugin/images/new.gif Binary files differnew file mode 100644 index 00000000000..9d050885be6 --- /dev/null +++ b/org.eclipse.osee.framework.ui.plugin/images/new.gif diff --git a/org.eclipse.osee.framework.ui.plugin/images/open.gif b/org.eclipse.osee.framework.ui.plugin/images/open.gif Binary files differnew file mode 100644 index 00000000000..51e703b1b9c --- /dev/null +++ b/org.eclipse.osee.framework.ui.plugin/images/open.gif diff --git a/org.eclipse.osee.framework.ui.plugin/images/permission.bmp b/org.eclipse.osee.framework.ui.plugin/images/permission.bmp Binary files differnew file mode 100644 index 00000000000..8a3e111c129 --- /dev/null +++ b/org.eclipse.osee.framework.ui.plugin/images/permission.bmp diff --git a/org.eclipse.osee.framework.ui.plugin/images/publish.gif b/org.eclipse.osee.framework.ui.plugin/images/publish.gif Binary files differnew file mode 100644 index 00000000000..a031b62c2d3 --- /dev/null +++ b/org.eclipse.osee.framework.ui.plugin/images/publish.gif diff --git a/org.eclipse.osee.framework.ui.plugin/images/refresh.gif b/org.eclipse.osee.framework.ui.plugin/images/refresh.gif Binary files differnew file mode 100644 index 00000000000..a063c230aca --- /dev/null +++ b/org.eclipse.osee.framework.ui.plugin/images/refresh.gif diff --git a/org.eclipse.osee.framework.ui.plugin/images/remove.gif b/org.eclipse.osee.framework.ui.plugin/images/remove.gif Binary files differnew file mode 100644 index 00000000000..2cd9c544436 --- /dev/null +++ b/org.eclipse.osee.framework.ui.plugin/images/remove.gif diff --git a/org.eclipse.osee.framework.ui.plugin/images/report.gif b/org.eclipse.osee.framework.ui.plugin/images/report.gif Binary files differnew file mode 100644 index 00000000000..e6bf9cf178e --- /dev/null +++ b/org.eclipse.osee.framework.ui.plugin/images/report.gif diff --git a/org.eclipse.osee.framework.ui.plugin/images/sample.gif b/org.eclipse.osee.framework.ui.plugin/images/sample.gif Binary files differnew file mode 100644 index 00000000000..34fb3c9d8cb --- /dev/null +++ b/org.eclipse.osee.framework.ui.plugin/images/sample.gif diff --git a/org.eclipse.osee.framework.ui.plugin/images/saved.gif b/org.eclipse.osee.framework.ui.plugin/images/saved.gif Binary files differnew file mode 100644 index 00000000000..ad505a9c23f --- /dev/null +++ b/org.eclipse.osee.framework.ui.plugin/images/saved.gif diff --git a/org.eclipse.osee.framework.ui.plugin/images/train.gif b/org.eclipse.osee.framework.ui.plugin/images/train.gif Binary files differnew file mode 100644 index 00000000000..222b48ad9d0 --- /dev/null +++ b/org.eclipse.osee.framework.ui.plugin/images/train.gif diff --git a/org.eclipse.osee.framework.ui.plugin/images/viewMenu.gif b/org.eclipse.osee.framework.ui.plugin/images/viewMenu.gif Binary files differnew file mode 100644 index 00000000000..a7c49189228 --- /dev/null +++ b/org.eclipse.osee.framework.ui.plugin/images/viewMenu.gif diff --git a/org.eclipse.osee.framework.ui.plugin/plugin.xml b/org.eclipse.osee.framework.ui.plugin/plugin.xml new file mode 100644 index 00000000000..489f440296c --- /dev/null +++ b/org.eclipse.osee.framework.ui.plugin/plugin.xml @@ -0,0 +1,14 @@ +<?xml version="1.0" encoding="UTF-8"?>
+<?eclipse version="3.2"?>
+<plugin>
+ <extension-point id="AuthenticationProvider" name="AuthenticationProvider" schema="schema/AuthenticationProvider.exsd"/>
+ <extension
+ id="DefaultAuthentication"
+ name="JvmAuthentication"
+ point="org.eclipse.osee.framework.ui.plugin.AuthenticationProvider">
+ <AuthenticationClass
+ classname="org.eclipse.osee.framework.ui.plugin.security.JvmAuthentication">
+ </AuthenticationClass>
+ </extension>
+
+</plugin>
diff --git a/org.eclipse.osee.framework.ui.plugin/schema/AuthenticationProvider.exsd b/org.eclipse.osee.framework.ui.plugin/schema/AuthenticationProvider.exsd new file mode 100644 index 00000000000..d72a2810948 --- /dev/null +++ b/org.eclipse.osee.framework.ui.plugin/schema/AuthenticationProvider.exsd @@ -0,0 +1,105 @@ +<?xml version='1.0' encoding='UTF-8'?>
+<!-- Schema file written by PDE -->
+<schema targetNamespace="org.eclipse.osee.framework.ui.plugin">
+<annotation>
+ <appInfo>
+ <meta.schema plugin="org.eclipse.osee.framework.ui.plugin" id="AuthenticationProvider" name="AuthenticationProvider"/>
+ </appInfo>
+ <documentation>
+ Contributions to this extension point provide logic to implement an authentication scheme.
+ </documentation>
+ </annotation>
+
+ <element name="extension">
+ <complexType>
+ <sequence>
+ <element ref="AuthenticationClass"/>
+ </sequence>
+ <attribute name="point" type="string" use="required">
+ <annotation>
+ <documentation>
+
+ </documentation>
+ </annotation>
+ </attribute>
+ <attribute name="id" type="string" use="required">
+ <annotation>
+ <documentation>
+
+ </documentation>
+ </annotation>
+ </attribute>
+ <attribute name="name" type="string">
+ <annotation>
+ <documentation>
+
+ </documentation>
+ <appInfo>
+ <meta.attribute translatable="true"/>
+ </appInfo>
+ </annotation>
+ </attribute>
+ </complexType>
+ </element>
+
+ <element name="AuthenticationClass">
+ <complexType>
+ <attribute name="classname" type="string" use="required">
+ <annotation>
+ <documentation>
+
+ </documentation>
+ <appInfo>
+ <meta.attribute kind="java" basedOn=":org.eclipse.osee.framework.ui.plugin.security.IAuthenticationStrategy"/>
+ </appInfo>
+ </annotation>
+ </attribute>
+ </complexType>
+ </element>
+
+ <annotation>
+ <appInfo>
+ <meta.section type="since"/>
+ </appInfo>
+ <documentation>
+ 0.1.0
+ </documentation>
+ </annotation>
+
+ <annotation>
+ <appInfo>
+ <meta.section type="examples"/>
+ </appInfo>
+ <documentation>
+ See org.eclipse.osee.framework.ui.plugin.security.GuestAuthentication for an example.
+ </documentation>
+ </annotation>
+
+ <annotation>
+ <appInfo>
+ <meta.section type="apiInfo"/>
+ </appInfo>
+ <documentation>
+ [Enter API information here.]
+ </documentation>
+ </annotation>
+
+ <annotation>
+ <appInfo>
+ <meta.section type="implementation"/>
+ </appInfo>
+ <documentation>
+ org.eclipse.osee.framework.ui.plugin.security.GuestAuthentication provides a default guest login.
+ </documentation>
+ </annotation>
+
+ <annotation>
+ <appInfo>
+ <meta.section type="copyright"/>
+ </appInfo>
+ <documentation>
+
+ </documentation>
+ </annotation>
+
+</schema>
diff --git a/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/EclipseErrorLogLogger.java b/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/EclipseErrorLogLogger.java new file mode 100644 index 00000000000..253b045d105 --- /dev/null +++ b/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/EclipseErrorLogLogger.java @@ -0,0 +1,38 @@ +package org.eclipse.osee.framework.ui.plugin;
+
+import java.util.logging.Level;
+import org.eclipse.core.runtime.Status;
+import org.eclipse.osee.framework.jdk.core.util.OseeProperties;
+import org.eclipse.osee.framework.logging.ILoggerFilter;
+import org.eclipse.osee.framework.logging.ILoggerListener;
+import org.eclipse.osee.framework.plugin.core.PluginCoreActivator;
+
+public class EclipseErrorLogLogger implements ILoggerListener {
+
+ private boolean isDeveloper = false;
+
+ public EclipseErrorLogLogger() {
+ isDeveloper = OseeProperties.isDeveloper();
+ }
+
+ public ILoggerFilter getFilter() {
+ return null;
+ }
+
+ public void log(String loggerName, String bundleId, Level level, String message, Throwable th) {
+ int statusLevel = 0;
+ if (level.intValue() >= Level.SEVERE.intValue()) {
+ statusLevel = Status.ERROR;
+ } else if (level.intValue() >= Level.WARNING.intValue()) {
+ statusLevel = Status.WARNING;
+ } else if (level.intValue() >= Level.INFO.intValue()) {
+ statusLevel = Status.INFO;
+ } else if (isDeveloper) {
+ statusLevel = Status.INFO;
+ } else {
+ return;
+ }
+ PluginCoreActivator.getInstance().getLog().log(new Status(statusLevel, bundleId, statusLevel, message, th));
+ }
+
+}
\ No newline at end of file diff --git a/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/OseeFormActivator.java b/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/OseeFormActivator.java new file mode 100644 index 00000000000..845befe4a4c --- /dev/null +++ b/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/OseeFormActivator.java @@ -0,0 +1,47 @@ +/******************************************************************************* + * Copyright (c) 2004, 2007 Boeing. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Boeing - initial API and implementation + *******************************************************************************/ +package org.eclipse.osee.framework.ui.plugin; + +import org.eclipse.swt.widgets.Display; +import org.eclipse.ui.forms.FormColors; +import org.osgi.framework.BundleContext; + +/** + * @author Ryan D. Brooks + */ +public abstract class OseeFormActivator extends OseeUiActivator { + private FormColors formColors; + + /** + * This method is called when the plug-in is stopped + */ + @Override + public void stop(BundleContext context) throws Exception { + super.stop(context); + if (formColors != null) { + formColors.dispose(); + formColors = null; + } + } + + /** + * returns a shared FormColors that can be passed to a FormToolkit constructor "Create one color manager (FormColors) + * per plug-in. When creating the toolkit, pass the color manager to the toolkit. The toolkit will know that the + * colors are shared and will not dispose them." + */ + public FormColors getSharedFormColors(Display display) { + if (formColors == null) { + formColors = new FormColors(display); + formColors.markShared(); + } + return formColors; + } +} diff --git a/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/OseePluginUiActivator.java b/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/OseePluginUiActivator.java new file mode 100644 index 00000000000..d0103f51508 --- /dev/null +++ b/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/OseePluginUiActivator.java @@ -0,0 +1,115 @@ +/******************************************************************************* + * Copyright (c) 2004, 2007 Boeing. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Boeing - initial API and implementation + *******************************************************************************/ +package org.eclipse.osee.framework.ui.plugin; + +import java.io.File; +import java.net.URL; +import java.util.logging.Logger; +import org.eclipse.core.runtime.FileLocator; +import org.eclipse.core.runtime.Platform; +import org.eclipse.osee.framework.db.connection.core.OseeInfo; +import org.eclipse.osee.framework.jdk.core.util.Lib; +import org.eclipse.osee.framework.logging.OseeLog; +import org.eclipse.osee.framework.plugin.core.config.ConfigUtil; +import org.eclipse.osgi.service.datalocation.Location; +import org.eclipse.ui.IWorkbench; +import org.eclipse.ui.IWorkbenchListener; +import org.eclipse.ui.PlatformUI; +import org.osgi.framework.BundleContext; + +/** + * The activator class controls the plug-in life cycle + */ +public class OseePluginUiActivator extends OseeUiActivator { + private static Logger logger = ConfigUtil.getConfigFactory().getLogger(OseePluginUiActivator.class); + + // The plug-in ID + public static final String PLUGIN_ID = "org.eclipse.osee.framework.ui.plugin"; + + // The shared instance + private static OseePluginUiActivator plugin; + + /** + * The constructor + */ + public OseePluginUiActivator() { + plugin = this; + } + + /* + * (non-Javadoc) + * @see org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext) + */ + public void start(BundleContext context) throws Exception { + super.start(context); + OseeLog.registerLoggerListener(new EclipseErrorLogLogger()); + + if (PlatformUI.isWorkbenchRunning()) { + IWorkbench workbench = PlatformUI.getWorkbench(); + workbench.addWorkbenchListener(new IWorkbenchListener() { + + @Override + public void postShutdown(IWorkbench workbench) { + } + + @Override + public boolean preShutdown(IWorkbench workbench, boolean forced) { + try { + if (Lib.isWindows()) { + String clearCache = OseeInfo.getValue("clear_cache"); + if (Boolean.parseBoolean(clearCache)) { + Location location = Platform.getInstallLocation(); + URL url = FileLocator.toFileURL(location.getURL()); + File file = new File(url.getFile()); + File cache = + new File(new File(new File(file, "p2"), "org.eclipse.equinox.p2.metadata.repository"), + "cache"); + File[] files = cache.listFiles(); + for (File toDelete : files) { + toDelete.delete(); + } + } + } + } catch (Throwable th) { + + } + return true; + } + + }); + } + } + + /* + * (non-Javadoc) + * @see org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext) + */ + public void stop(BundleContext context) throws Exception { + plugin = null; + super.stop(context); + } + + /** + * Returns the shared instance + * + * @return the shared instance + */ + public static OseePluginUiActivator getInstance() { + return plugin; + } + + /** + * @return the logger + */ + public static Logger getLogger() { + return logger; + } +}
\ No newline at end of file diff --git a/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/OseeUiActivator.java b/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/OseeUiActivator.java new file mode 100644 index 00000000000..443d1b1a78a --- /dev/null +++ b/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/OseeUiActivator.java @@ -0,0 +1,311 @@ +/******************************************************************************* + * Copyright (c) 2004, 2007 Boeing. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Boeing - initial API and implementation + *******************************************************************************/ +package org.eclipse.osee.framework.ui.plugin; + +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.net.URL; +import java.nio.CharBuffer; +import java.util.List; +import org.eclipse.core.resources.IWorkspace; +import org.eclipse.core.resources.IWorkspaceRoot; +import org.eclipse.core.resources.ResourcesPlugin; +import org.eclipse.core.runtime.IPath; +import org.eclipse.core.runtime.Platform; +import org.eclipse.core.runtime.Plugin; +import org.eclipse.core.runtime.Status; +import org.eclipse.jface.action.IAction; +import org.eclipse.jface.resource.ImageDescriptor; +import org.eclipse.jface.resource.ImageRegistry; +import org.eclipse.osee.framework.db.connection.ConnectionHandler; +import org.eclipse.osee.framework.db.connection.core.OseeApplicationServer; +import org.eclipse.osee.framework.jdk.core.util.Lib; +import org.eclipse.osee.framework.plugin.core.ActivatorHelper; +import org.eclipse.osee.framework.ui.plugin.util.Result; +import org.eclipse.swt.graphics.Image; +import org.eclipse.swt.program.Program; +import org.eclipse.swt.widgets.Control; +import org.eclipse.swt.widgets.Menu; +import org.eclipse.swt.widgets.MenuItem; +import org.eclipse.ui.PlatformUI; +import org.eclipse.ui.plugin.AbstractUIPlugin; +import org.osgi.framework.BundleContext; + +/** + * @author Ryan D. Brooks + */ +public abstract class OseeUiActivator extends AbstractUIPlugin { + private static final String imagePath = "images/"; + private ImageRegistry imageRegistry; + private OseeUiActivator parentPlugin; + private ActivatorHelper helper; + + /** + * The constructor. + */ + protected OseeUiActivator() { + super(); + } + + public Plugin getOseePlugin(String pluginId) { + return helper.getOseePlugin(pluginId); + } + + /** + * returns a File to from the default persistent storage area provided for the bundle by the Framework (.ie.) + * myworkspace/.metadata/.plugins/org.eclipse.pde.core/myPlugin/... + */ + public File getPluginStoreFile(String path) { + return helper.getPluginStoreFile(path); + } + + /** + * finds a resource in the plugin bundle and writes it out to the default persistent storage area as a regualar file + * + * @param path + * @return Return plugin file reference + * @throws IOException + */ + public File getPluginFile(String path) throws IOException { + return helper.getPluginFile(path); + } + + public InputStream getInputStream(String resource) throws IOException { + return helper.getInputStream(resource); + } + + public List<URL> getInputStreams(String directory, String pattern, boolean recurse) throws IOException { + return helper.getInputStreams(directory, pattern, recurse); + } + + /** + * This method is called upon plug-in activation + */ + public void start(BundleContext context) throws Exception { + super.start(context); + + parentPlugin = OseePluginUiActivator.getInstance(); + /* + * parentPlugin will be the CorePlugin except in the case of CorePlugin itself when + * parentPlugin will be null + */ + if (parentPlugin == this) parentPlugin = null; + + helper = new ActivatorHelper(context, this); + + } + + /** + * This method is called when the plug-in is stopped + */ + @Override + public void stop(BundleContext context) throws Exception { + super.stop(context); + if (imageRegistry != null) { + imageRegistry.dispose(); + } + } + + private Image getImageFromRegistry(String imageKey) { + /* + * initialize here rather than the constructor since some O.S.E.E. plug-ins don't use the image + * registry and because some plug-ins seem to load before it is safe to construct an image + * registry without getting a NullPointerException + */ + if (imageRegistry == null) { + imageRegistry = new ImageRegistry(); + } + return imageRegistry.get(imageKey); + } + + public void addImageToRegistry(String imageKey, ImageDescriptor descriptor) { + Image previousImage = getImageFromRegistry(imageKey); + if (previousImage == null) { + imageRegistry.put(imageKey, descriptor); + } else { + throw new IllegalArgumentException("The image registry already contains an image mapped to " + imageKey); + } + } + + public void addImageToRegistry(String imageKey, Image image) { + Image previousImage = getImageFromRegistry(imageKey); + if (previousImage == null) { + imageRegistry.put(imageKey, image); + } else { + throw new IllegalArgumentException("The image registry already contains an image mapped to " + imageKey); + } + } + + public Image getImageForProgram(String extenstion) { + Image image = getImageFromRegistry(extenstion); + + if (image == null && extenstion != null) { + Program program = Program.findProgram(extenstion); + if (program == null || program.getImageData() == null) { + // provide no image (i.e. leave null) + } else { + ImageDescriptor imageDescriptor = ImageDescriptor.createFromImageData(program.getImageData()); + imageRegistry.put(extenstion, imageDescriptor); + image = imageRegistry.get(extenstion); + } + } + return image; + } + + /** + * Returns the Image for the icon with the given path under images/ + * + * @return the Image object + */ + public Image getImage(String imageName) throws IllegalArgumentException { + Image image = getImageFromRegistry(imageName); + if (image == null) { // if image is not already cached + ImageDescriptor descriptor = getImageDescriptor(imageName); + + // if image not found in this plug-in, then look in parent plug-in (if parent exists) + if (descriptor == null && parentPlugin != null) { + Image ret = parentPlugin.getImage(imageName); + if (ret != null) { + return ret; + } + } + if (descriptor == null) { + throw new IllegalArgumentException(String.format("The image %s does not exist", imageName)); + } + + image = descriptor.createImage(false); + if (image != null) { // cache image only if successfully returned + imageRegistry.put(imageName, image); + } + } + return image; + } + + /** + * Returns the ImageDiscriptor from images/ with the given icon name + * + * @return the Image object + */ + public ImageDescriptor getImageDescriptor(String name) { + return imageDescriptorFromPlugin(getBundle().getSymbolicName(), imagePath + name); + } + + public InputStream getInputStreamForImage(String imageName) throws IOException { + return getInputStream(imagePath + imageName); + } + + public Object getBundleHeaderValue(String name) { + return getBundle().getHeaders().get(name); + } + + public void log(String message) { + getLog().log(new Status(0, toString(), 0, message, null)); + } + + public void log(String message, Exception ex) { + getLog().log(new Status(0, toString(), 0, message, ex)); + } + + public CharBuffer getCharBuffer(String resource) { + try { + return Lib.inputStreamToCharBuffer(getInputStream(resource)); + } catch (IOException ex) { + ex.printStackTrace(); + } + return null; + } + + public void setHelp(Control control, String name) { + PlatformUI.getWorkbench().getHelpSystem().setHelp(control, getPluginName() + "." + name); + } + + public void setHelp(IAction action, String name) { + PlatformUI.getWorkbench().getHelpSystem().setHelp(action, getPluginName() + "." + name); + } + + public void setHelp(Menu menu, String name) { + PlatformUI.getWorkbench().getHelpSystem().setHelp(menu, getPluginName() + "." + name); + } + + public void setHelp(MenuItem menuItem, String name) { + PlatformUI.getWorkbench().getHelpSystem().setHelp(menuItem, getPluginName() + "." + name); + } + + public void displayHelp(String name) { + PlatformUI.getWorkbench().getHelpSystem().displayHelp(getPluginName() + "." + name); + } + + protected String getPluginName() { + throw new UnsupportedOperationException(); + } + + public static File getBasePluginInstallDirectory() { + return new File(Platform.getInstallLocation().getURL().getFile() + File.separator + "plugins"); + } + + /** + * Returns the workspace instance. + * + * @return the workspace instance + */ + public static IWorkspace getWorkspace() { + return ResourcesPlugin.getWorkspace(); + } + + public static IPath getWorkspaceFile(IPath path) { + return getWorkspaceRoot().getLocation().append(path); + } + + public static IPath getWorkspaceFile(String path) { + return getWorkspaceRoot().getLocation().append(path); + } + + /** + * Returns Returns the root resource of this workspace + * + * @return the workspace root + */ + public static IWorkspaceRoot getWorkspaceRoot() { + return ResourcesPlugin.getWorkspace().getRoot(); + } + + public static String getStackMessages(Exception ex) { + Throwable exloop = ex; + String exceptionString = ""; + while (exloop != null) { + exceptionString += exloop.getClass().getName() + ":\n\t" + exloop.getMessage() + "\n"; + exloop = exloop.getCause(); + } + return exceptionString; + } + + /** + * Checks that OSEE is connected to all necessary application services + * + * @return Result.isFalse if not connected with getText() of problem + */ + public static Result areOSEEServicesAvailable() { + StringBuilder message = new StringBuilder(); + if (!ConnectionHandler.isConnected()) { + message.append("DB Connection Unavailable"); + } + if (!OseeApplicationServer.isApplicationServerAlive()) { + if (message.length() > 0) { + message.append("\n"); + } + message.append("OSEE Application Server Unavailable"); + } + + return message.length() > 0 ? new Result(message.toString()) : Result.TrueResult; + } + +}
\ No newline at end of file diff --git a/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/event/UnloadedArtifact.java b/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/event/UnloadedArtifact.java new file mode 100644 index 00000000000..a6ce6a68539 --- /dev/null +++ b/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/event/UnloadedArtifact.java @@ -0,0 +1,64 @@ +/*
+ * Created on Sep 13, 2008
+ *
+ * PLACE_YOUR_DISTRIBUTION_STATEMENT_RIGHT_HERE
+ */
+package org.eclipse.osee.framework.ui.plugin.event;
+
+/**
+ * @author Donald G. Dunne
+ */
+public class UnloadedArtifact {
+ private int artifactId;
+ private int branchId;
+ private int artifactTypeId;
+
+ public UnloadedArtifact(int branchId, int artifactId, int artifactTypeId) {
+ this.branchId = branchId;
+ this.artifactId = artifactId;
+ this.artifactTypeId = artifactTypeId;
+ }
+
+ /**
+ * @return the artifactId
+ */
+ public int getArtifactId() {
+ return artifactId;
+ }
+
+ /**
+ * @param artifactId the artifactId to set
+ */
+ public void setArtifactId(int artifactId) {
+ this.artifactId = artifactId;
+ }
+
+ /**
+ * @return the branchId
+ */
+ public int getBranchId() {
+ return branchId;
+ }
+
+ /**
+ * @param branchId the branchId to set
+ */
+ public void setBranchId(int branchId) {
+ this.branchId = branchId;
+ }
+
+ /**
+ * @return the artifactTypeId
+ */
+ public int getArtifactTypeId() {
+ return artifactTypeId;
+ }
+
+ /**
+ * @param artifactTypeId the artifactTypeId to set
+ */
+ public void setArtifactTypeId(int artifactTypeId) {
+ this.artifactTypeId = artifactTypeId;
+ }
+
+}
diff --git a/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/event/UnloadedRelation.java b/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/event/UnloadedRelation.java new file mode 100644 index 00000000000..a9714cae8de --- /dev/null +++ b/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/event/UnloadedRelation.java @@ -0,0 +1,76 @@ +/*
+ * Created on Sep 13, 2008
+ *
+ * PLACE_YOUR_DISTRIBUTION_STATEMENT_RIGHT_HERE
+ */
+package org.eclipse.osee.framework.ui.plugin.event;
+
+/**
+ * @author Donald G. Dunne
+ */
+public class UnloadedRelation {
+
+ private final int artifactAId;
+ private final int artifactATypeId;
+ private final int artifactBId;
+ private final int artifactBTypeId;
+ private final int relationTypeId;
+ private final int branchId;
+
+ public UnloadedRelation(int branchId, int artifactAId, int artifactATypeId, int artifactBId, int artifactBTypeId, int relationTypeId) {
+ this.branchId = branchId;
+ this.artifactAId = artifactAId;
+ this.artifactATypeId = artifactATypeId;
+ this.artifactBId = artifactBId;
+ this.artifactBTypeId = artifactBTypeId;
+ this.relationTypeId = relationTypeId;
+ }
+
+ @Override
+ public String toString() {
+ return "UnloadedRelation A: " + artifactAId + " AType: " + artifactATypeId + " B:" + artifactBId + " BType: " + artifactBTypeId + " RelType: " + relationTypeId + " Branch: " + branchId;
+ }
+
+ /**
+ * @return the artifactATypeId
+ */
+ public int getArtifactATypeId() {
+ return artifactATypeId;
+ }
+
+ /**
+ * @return the artifactBTypeId
+ */
+ public int getArtifactBTypeId() {
+ return artifactBTypeId;
+ }
+
+ /**
+ * @return the artifactAId
+ */
+ public int getArtifactAId() {
+ return artifactAId;
+ }
+
+ /**
+ * @return the artifactBId
+ */
+ public int getArtifactBId() {
+ return artifactBId;
+ }
+
+ /**
+ * @return the relationTypeId
+ */
+ public int getRelationTypeId() {
+ return relationTypeId;
+ }
+
+ /**
+ * @return the branchId
+ */
+ public int getBranchId() {
+ return branchId;
+ }
+
+}
diff --git a/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/io/FormattedTextOutputStream.java b/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/io/FormattedTextOutputStream.java new file mode 100644 index 00000000000..2674d2414a9 --- /dev/null +++ b/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/io/FormattedTextOutputStream.java @@ -0,0 +1,81 @@ +/******************************************************************************* + * Copyright (c) 2004, 2007 Boeing. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Boeing - initial API and implementation + *******************************************************************************/ +package org.eclipse.osee.framework.ui.plugin.io; + +import java.io.OutputStream; +import java.io.UnsupportedEncodingException; +import java.nio.charset.Charset; +import java.nio.charset.UnsupportedCharsetException; +import org.eclipse.osee.framework.ui.swt.FormattedText; +import org.eclipse.swt.SWT; +import org.eclipse.swt.custom.StyledText; + +/** + * @author Roberto E. Escobar + */ +public class FormattedTextOutputStream extends OutputStream { + + private FormattedText textArea; + private String charset; + private StyledText styledText; + private String type; + private int swtColor; + + public FormattedTextOutputStream(FormattedText textArea, String type) { + this.textArea = textArea; + this.styledText = textArea.getStyledText(); + this.charset = null; + this.type = type; + } + + public FormattedTextOutputStream(FormattedText ta, String charset, String type) throws UnsupportedCharsetException { + this(ta, type); + + Charset.forName(charset); + this.charset = charset; + } + + public void write(byte[] b) { + write(b, 0, b.length); + } + + private boolean isTextAreaAvailable() { + return (textArea != null && !textArea.getStyledText().isDisposed()); + } + + public void typeColor(int swtColor) { + this.swtColor = swtColor; + } + + public void write(byte[] b, int off, int len) { + String s; + try { + if (charset == null) + s = new String(b, off, len); + else + s = new String(b, off, len, charset); + } catch (UnsupportedEncodingException ex) { + throw new Error("encoding support was already verified", ex); + } + synchronized (textArea) { + if (isTextAreaAvailable()) { + textArea.addText("\t" + type + "> ", SWT.BOLD, swtColor); + textArea.addText(s + "\n"); + styledText.setSelection(styledText.getCharCount()); + } + } + } + + public void write(int b) { + byte[] tmp = {(byte) b}; + write(tmp); + } +} diff --git a/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/io/StreamToTextArea.java b/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/io/StreamToTextArea.java new file mode 100644 index 00000000000..e9c58b2db65 --- /dev/null +++ b/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/io/StreamToTextArea.java @@ -0,0 +1,71 @@ +/******************************************************************************* + * Copyright (c) 2004, 2007 Boeing. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Boeing - initial API and implementation + *******************************************************************************/ + +package org.eclipse.osee.framework.ui.plugin.io; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import org.eclipse.osee.framework.ui.swt.FormattedText; +import org.eclipse.swt.SWT; +import org.eclipse.swt.custom.StyledText; +import org.eclipse.swt.widgets.Display; + +/** + * @author Roberto E. Escobar + */ +public class StreamToTextArea extends Thread { + private InputStream is; + private String type; + private FormattedText textArea; + private StyledText styledText; + private int swtColor; + private boolean isStopped; + + public StreamToTextArea(InputStream is, String type, FormattedText textArea) { + this.is = is; + this.type = type; + this.textArea = textArea; + this.styledText = textArea.getStyledText(); + this.isStopped = false; + } + + public void typeColor(int swtColor) { + this.swtColor = swtColor; + } + + public void setStopped(boolean value) { + this.isStopped = value; + } + + public void run() { + try { + BufferedReader br = new BufferedReader(new InputStreamReader(is)); + String line = null; + while (true != isStopped && null != textArea && true != textArea.getStyledText().isDisposed() && null != (line = + br.readLine())) { + final String toDisplay = line; + Display.getDefault().asyncExec(new Runnable() { + public void run() { + if (textArea != null && !textArea.getStyledText().isDisposed()) { + textArea.addText("\t" + type + "> ", SWT.NORMAL, swtColor); + textArea.addText(toDisplay + "\n"); + styledText.setSelection(styledText.getCharCount()); + } + } + }); + } + } catch (IOException ioe) { + ioe.printStackTrace(); + } + } +} diff --git a/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/security/AbstractAuthentication.java b/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/security/AbstractAuthentication.java new file mode 100644 index 00000000000..d65f0a1d3a6 --- /dev/null +++ b/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/security/AbstractAuthentication.java @@ -0,0 +1,46 @@ +/******************************************************************************* + * Copyright (c) 2004, 2007 Boeing. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Boeing - initial API and implementation + *******************************************************************************/ +package org.eclipse.osee.framework.ui.plugin.security; + +import org.eclipse.osee.framework.ui.plugin.security.OseeAuthentication.AuthenticationStatus; + +/** + * @author Roberto E. Escobar + */ +public abstract class AbstractAuthentication implements IAuthentication { + + protected AuthenticationStatus authenticationStatus; + protected UserCredentials userCredentials; + + protected AbstractAuthentication() { + super(); + userCredentials = new UserCredentials(); + clear(); + } + + public AuthenticationStatus getAuthenticationStatus() { + return authenticationStatus; + } + + public UserCredentials getCredentials() { + return userCredentials; + } + + public void clear() { + authenticationStatus = AuthenticationStatus.NoResponse; + userCredentials.clear(); + } + + public boolean isAuthenticated() { + return authenticationStatus.equals(AuthenticationStatus.Success); + } + +} diff --git a/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/security/AuthenticationComposite.java b/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/security/AuthenticationComposite.java new file mode 100644 index 00000000000..98aed3aea6e --- /dev/null +++ b/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/security/AuthenticationComposite.java @@ -0,0 +1,376 @@ +/******************************************************************************* + * Copyright (c) 2004, 2007 Boeing. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Boeing - initial API and implementation + *******************************************************************************/ +package org.eclipse.osee.framework.ui.plugin.security; + +import java.util.HashMap; +import java.util.Map; +import org.eclipse.swt.SWT; +import org.eclipse.swt.custom.SashForm; +import org.eclipse.swt.events.ModifyEvent; +import org.eclipse.swt.events.ModifyListener; +import org.eclipse.swt.events.SelectionAdapter; +import org.eclipse.swt.events.SelectionEvent; +import org.eclipse.swt.events.SelectionListener; +import org.eclipse.swt.graphics.Image; +import org.eclipse.swt.layout.GridData; +import org.eclipse.swt.layout.GridLayout; +import org.eclipse.swt.widgets.Button; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Control; +import org.eclipse.swt.widgets.Group; +import org.eclipse.swt.widgets.Label; +import org.eclipse.swt.widgets.Text; +import org.eclipse.ui.ISharedImages; +import org.eclipse.ui.PlatformUI; + +/** + * @author Roberto E. Escobar + */ +public class AuthenticationComposite extends Composite { + + private static final String LABEL_KEY = "label"; + private static final String WARNING_MESSAGE = + "Saved passwords are stored in your computer in a file that is difficult, but not impossible, for an intruder to read."; + private static final Image errorImage = + PlatformUI.getWorkbench().getSharedImages().getImage(ISharedImages.IMG_OBJS_ERROR_TSK); + + private static final OseeAuthentication oseeAuthentication = OseeAuthentication.getInstance(); + + private enum LabelEnum { + UserId("Enter user name"), + Password(true, "Enter a valid password"), + Domain("Enter a valid domain [sw, nw, etc...]"), + Remember_My_Password(WARNING_MESSAGE); + + boolean isHidden; + String toolTipText; + + LabelEnum(boolean isHidden, String toolTipText) { + this.isHidden = isHidden; + this.toolTipText = toolTipText; + } + + LabelEnum(String toolTipText) { + this(false, toolTipText); + } + + public String getToolTipText() { + return toolTipText; + } + + public boolean isHidden() { + return isHidden; + } + } + + private Map<LabelEnum, Text> fieldMap; + private Map<LabelEnum, String> dataMap; + private Map<LabelEnum, Label> statusMap; + private boolean buildSubmitButton; + private SelectionListener listener; + private boolean allValid; + private Button memoButton; + private Button guestButton; + private Button userButton; + private Composite mainComposite; + private SashForm sash; + private boolean isGuestLogin; + + public AuthenticationComposite(Composite parent, int style, boolean buildSubmitButton) { + super(parent, style); + this.buildSubmitButton = buildSubmitButton; + fieldMap = new HashMap<LabelEnum, Text>(); + dataMap = new HashMap<LabelEnum, String>(); + statusMap = new HashMap<LabelEnum, Label>(); + createControl(); + } + + public AuthenticationComposite(Composite parent, int style) { + this(parent, style, true); + } + + private void createControl() { + this.setLayout(new GridLayout()); + this.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); + + sash = new SashForm(this, SWT.NONE); + sash.setLayout(new GridLayout()); + sash.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); + sash.setOrientation(SWT.VERTICAL); + + createLoginSelection(sash); + + mainComposite = new Group(sash, SWT.NONE); + mainComposite.setLayout(new GridLayout()); + mainComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); + + createFieldArea(mainComposite); + handleLoginTypeSelection(); + sash.setWeights(new int[] {3, 7}); + } + + private void createLoginSelection(Composite parent) { + Composite composite = new Composite(parent, SWT.NONE); + composite.setLayout(new GridLayout()); + composite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false)); + + guestButton = new Button(composite, SWT.RADIO); + guestButton.setText("Guest"); + guestButton.setSelection(isGuestLogin); + guestButton.setToolTipText("Allows users to log into the system with guest priviledges.\n"); + guestButton.addSelectionListener(new SelectionAdapter() { + + @Override + public void widgetSelected(SelectionEvent e) { + handleLoginTypeSelection(); + updateDefaultButtonStatus(); + } + + }); + + userButton = new Button(composite, SWT.RADIO); + userButton.setSelection(!isGuestLogin); + userButton.setText("User Login"); + userButton.setToolTipText("Enables User to login"); + userButton.addSelectionListener(new SelectionAdapter() { + + @Override + public void widgetSelected(SelectionEvent e) { + handleLoginTypeSelection(); + updateDefaultButtonStatus(); + } + }); + + } + + private void handleLoginTypeSelection() { + boolean allowUserLogin = false; + if (guestButton != null && !guestButton.isDisposed()) { + if (guestButton.getSelection()) { + allowUserLogin = false; + } + } + + if (userButton != null && !userButton.isDisposed()) { + if (userButton.getSelection()) { + allowUserLogin = true; + } + } + + isGuestLogin = !allowUserLogin; + if (mainComposite != null && !mainComposite.isDisposed()) { + setEnabledHelper(mainComposite, allowUserLogin); + } + } + + private void setEnabledHelper(Composite tempComposite, boolean setEnabled) { + for (Control control : tempComposite.getChildren()) { + if (control instanceof Composite) { + setEnabledHelper((Composite) control, setEnabled); + } else { + control.setEnabled(setEnabled); + } + } + } + + private void createFieldArea(Composite parent) { + Composite composite = new Composite(parent, SWT.NONE); + composite.setLayout(new GridLayout(3, false)); + composite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false)); + + for (LabelEnum labelEnum : LabelEnum.values()) { + if (labelEnum.equals(LabelEnum.Remember_My_Password)) { + createMementoButton(parent); + if (memoButton != null && !memoButton.isDisposed()) { + dataMap.put(labelEnum, Boolean.toString(memoButton.getSelection())); + } + } else { + Label label = new Label(composite, SWT.NONE); + label.setText(labelEnum.name() + ": "); + + int style = SWT.BORDER | SWT.SINGLE; + Text field = new Text(composite, (labelEnum.isHidden() ? style |= SWT.PASSWORD : style)); + field.setData(LABEL_KEY, labelEnum); + field.setToolTipText(labelEnum.getToolTipText()); + field.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false)); + + Label statusLabel = new Label(composite, SWT.NONE); + statusLabel.setImage(errorImage); + statusLabel.setVisible(true); + + field.addModifyListener(new ModifyListener() { + + public void modifyText(ModifyEvent e) { + Object object = e.getSource(); + if (object instanceof Text) { + Text field = (Text) object; + LabelEnum labelKey = (LabelEnum) field.getData(LABEL_KEY); + + dataMap.put(labelKey, field.getText()); + updateFieldStatus(labelKey, field); + updateDefaultButtonStatus(); + } + } + }); + fieldMap.put(labelEnum, field); + statusMap.put(labelEnum, statusLabel); + dataMap.put(labelEnum, field.getText()); + } + } + + if (buildSubmitButton) { + Composite buttonComposite = new Composite(parent, SWT.NONE); + buttonComposite.setLayout(new GridLayout()); + buttonComposite.setLayoutData(new GridData(SWT.END, SWT.END, true, false)); + + Button authenticate = new Button(buttonComposite, SWT.PUSH); + authenticate.setText("Submit"); + authenticate.setLayoutData(new GridData(SWT.END, SWT.END, false, false)); + authenticate.addSelectionListener(listener); + authenticate.setEnabled(allValid); + getShell().setDefaultButton(authenticate); + } + + listener = new SelectionAdapter() { + + @Override + public void widgetSelected(SelectionEvent e) { + String user = dataMap.get(LabelEnum.UserId); + String password = dataMap.get(LabelEnum.Password); + String domain = dataMap.get(LabelEnum.Domain); + String saveAllowed = dataMap.get(LabelEnum.Remember_My_Password); + + oseeAuthentication.setLogAsGuest(isGuestLogin()); + oseeAuthentication.authenticate(user, password, domain, + (saveAllowed != null ? Boolean.parseBoolean(saveAllowed) : false)); + + oseeAuthentication.setLogAsGuest(false); + } + }; + + } + + private void createMementoButton(Composite parent) { + Composite tempComposite = new Composite(parent, SWT.NONE); + tempComposite.setLayout(new GridLayout()); + tempComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false)); + + memoButton = new Button(tempComposite, SWT.CHECK); + memoButton.setText("Remember my password"); + memoButton.setLayoutData(new GridData(SWT.BEGINNING, SWT.BEGINNING, false, false)); + memoButton.setToolTipText(WARNING_MESSAGE); + memoButton.addSelectionListener(new SelectionAdapter() { + + @Override + public void widgetSelected(SelectionEvent e) { + dataMap.put(LabelEnum.Remember_My_Password, Boolean.toString(memoButton.getSelection())); + } + + }); + } + + public SelectionListener getAuthenticateListener() { + return listener; + } + + public void setUserName(String user) { + setAndStoreField(LabelEnum.UserId, user); + } + + public void setPassword(String password) { + setAndStoreField(LabelEnum.Password, password); + } + + public void setDomain(String domain) { + setAndStoreField(LabelEnum.Domain, domain); + } + + public void setStorageAllowed(boolean isStorageAllowed) { + setAndStoreField(LabelEnum.Remember_My_Password, Boolean.toString(isStorageAllowed)); + } + + private void setAndStoreField(LabelEnum fieldKey, String value) { + if (fieldKey.equals(LabelEnum.Remember_My_Password)) { + if (memoButton != null && !memoButton.isDisposed()) { + memoButton.setSelection(Boolean.valueOf(value)); + } + } else { + Text textField = fieldMap.get(fieldKey); + if (textField != null && !textField.isDisposed()) { + textField.setText(value); + updateFieldStatus(fieldKey, textField); + updateDefaultButtonStatus(); + } + } + dataMap.put(fieldKey, value); + } + + public String getUserName() { + return dataMap.get(LabelEnum.UserId); + } + + public String getPassword() { + return dataMap.get(LabelEnum.Password); + } + + public String getDomain() { + return dataMap.get(LabelEnum.Domain); + } + + public boolean isGuestLogin() { + return isGuestLogin; + } + + public void setGuestLogin(boolean isGuestLogin) { + this.isGuestLogin = isGuestLogin; + } + + public boolean isStorageAllowed() { + String value = dataMap.get(LabelEnum.Remember_My_Password); + return (value != null ? Boolean.parseBoolean(value) : false); + } + + public boolean isValid() { + return allValid; + } + + private void updateFieldStatus(LabelEnum labelKey, Text field) { + switch (labelKey) { + case UserId: + String temp = field.getText(); + statusMap.get(labelKey).setVisible(!(temp != null && temp.length() > 0)); + break; + case Remember_My_Password: + break; + default: + temp = field.getText(); + statusMap.get(labelKey).setVisible(!(temp != null && temp.length() > 0)); + break; + } + } + + private void updateDefaultButtonStatus() { + allValid = true; + + if (!isGuestLogin) { + for (LabelEnum key : LabelEnum.values()) { + Label label = statusMap.get(key); + if (label != null && !label.isDisposed()) { + allValid &= !label.isVisible(); + } + } + } + Button defaultButton = AuthenticationComposite.this.getShell().getDefaultButton(); + if (defaultButton != null) { + defaultButton.setEnabled(allValid); + } + } +} diff --git a/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/security/AuthenticationConsole.java b/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/security/AuthenticationConsole.java new file mode 100644 index 00000000000..adac47bff1e --- /dev/null +++ b/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/security/AuthenticationConsole.java @@ -0,0 +1,152 @@ +/******************************************************************************* + * Copyright (c) 2004, 2007 Boeing. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Boeing - initial API and implementation + *******************************************************************************/ +package org.eclipse.osee.framework.ui.plugin.security; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.OutputStream; +import java.io.PrintStream; +import java.util.HashMap; +import java.util.Map; +import org.eclipse.osee.framework.ui.plugin.security.OseeAuthentication.AuthenticationStatus; +import org.eclipse.osee.framework.ui.plugin.security.UserCredentials.UserCredentialEnum; + +/** + * @author Roberto E. Escobar + */ +public class AuthenticationConsole { + + private static final int MAX_RETRIES = 3; + private static final OseeAuthentication oseeAuthentication = OseeAuthentication.getInstance(); + + private enum PromptEnums { + USERNAME("Enter UserName: "), PASSWORD("Enter Password: "), DOMAIN("Enter Domain: "); + + private String prompt; + + PromptEnums(String prompt) { + this.prompt = prompt; + } + + public String getPrompt() { + return prompt; + } + } + + private OutputStream outWriter; + private OutputStream errorWriter; + private BufferedReader bufferedReader; + + public AuthenticationConsole() { + this(System.in, new PrintStream(System.out), new PrintStream(System.err)); + } + + public AuthenticationConsole(InputStream outStream, OutputStream outWriter, OutputStream errorWriter) { + this.bufferedReader = new BufferedReader(new InputStreamReader(System.in)); + this.outWriter = outWriter; + this.errorWriter = errorWriter; + } + + private String getDetailMessage(AuthenticationStatus status) { + String toReturn = ""; + switch (status) { + case UserNotFound: + toReturn = "User Id not found.\n" + "Enter your user id."; + break; + case InvalidPassword: + toReturn = "Invalid Password.\n" + "Make sure <CAPS LOCK> is not enabled.\n" + "Enter a valid password."; + break; + case NoResponse: + toReturn = "Please enter a valid user id and password."; + break; + default: + break; + } + return toReturn; + } + + private String waitForUserResponse(PromptEnums promptEnum) { + String line = ""; + try { + displayMessage(promptEnum.getPrompt() + "\n"); + line = bufferedReader.readLine(); + } catch (IOException ex) { + ex.printStackTrace(); + } + return line; + } + + public void run() { + String message = ""; + for (int numberOfTries = 0; numberOfTries < MAX_RETRIES; numberOfTries++) { + Map<PromptEnums, String> userInputs = getInputs(); + AuthenticationStatus status = authenticate(userInputs); + switch (status) { + case Success: + numberOfTries = MAX_RETRIES; + displayMessage(String.format("Authenticated. \nLogged in as: %s \n", + oseeAuthentication.getCredentials().getField(UserCredentialEnum.Name))); + break; + default: + if (numberOfTries >= MAX_RETRIES - 1) { + message = "Maximum number of Retries reached.\n"; + } else { + message = getDetailMessage(status); + } + displayError(String.format("Authentication Failed.\n%s\n\n\n", message)); + break; + } + } + } + + private void displayError(String value) { + try { + errorWriter.write(value.getBytes()); + errorWriter.flush(); + } catch (IOException ex) { + ex.printStackTrace(); + } + } + + private void displayMessage(String value) { + try { + outWriter.write(value.getBytes()); + outWriter.flush(); + } catch (IOException ex) { + ex.printStackTrace(); + } + } + + private Map<PromptEnums, String> getInputs() { + Map<PromptEnums, String> inputMap = new HashMap<PromptEnums, String>(); + for (PromptEnums promptEnum : PromptEnums.values()) { + String input = waitForUserResponse(promptEnum); + inputMap.put(promptEnum, ((input != null && input.length() > 0) ? input : "")); + } + return inputMap; + } + + private AuthenticationStatus authenticate(Map<PromptEnums, String> userInputs) { + String user = userInputs.get(PromptEnums.USERNAME); + String password = userInputs.get(PromptEnums.PASSWORD); + String domain = userInputs.get(PromptEnums.DOMAIN); + oseeAuthentication.authenticate(user, password, domain, true); + return oseeAuthentication.getAuthenticationStatus(); + } + + public static void main(String[] args) { + AuthenticationConsole authenticationConsole = new AuthenticationConsole(); + authenticationConsole.run(); + System.exit(0); + } +} diff --git a/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/security/AuthenticationDialog.java b/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/security/AuthenticationDialog.java new file mode 100644 index 00000000000..df6e4b8f604 --- /dev/null +++ b/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/security/AuthenticationDialog.java @@ -0,0 +1,218 @@ +/******************************************************************************* + * Copyright (c) 2004, 2007 Boeing. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Boeing - initial API and implementation + *******************************************************************************/ +package org.eclipse.osee.framework.ui.plugin.security; + +import org.eclipse.jface.dialogs.MessageDialog; +import org.eclipse.jface.window.Window; +import org.eclipse.osee.framework.ui.plugin.OseePluginUiActivator; +import org.eclipse.osee.framework.ui.plugin.security.OseeAuthentication.AuthenticationStatus; +import org.eclipse.osee.framework.ui.plugin.security.UserCredentials.UserCredentialEnum; +import org.eclipse.osee.framework.ui.swt.OseeMessageDialog; +import org.eclipse.swt.SWT; +import org.eclipse.swt.events.SelectionAdapter; +import org.eclipse.swt.events.SelectionEvent; +import org.eclipse.swt.graphics.Image; +import org.eclipse.swt.widgets.Button; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Control; +import org.eclipse.swt.widgets.Display; +import org.eclipse.swt.widgets.Shell; +import org.eclipse.ui.PlatformUI; + +/** + * @author Roberto E. Escobar + */ +public class AuthenticationDialog extends OseeMessageDialog { + + private Button okButton; + private Button cancelButton; + protected AuthenticationComposite authenticationComposite; + private boolean selectionOk; + private static final Image LOCK_AND_KEY = OseePluginUiActivator.getInstance().getImage("lockkey.gif"); + private static final int MAX_RETRIES = 3; + + public AuthenticationDialog(Shell parentShell) { + super(parentShell, "OSEE Authenticate", null, "Enter your user id (email address), password, and domain.", + LOCK_AND_KEY, new String[] {"Enter", "Cancel"}, 0); + + selectionOk = false; + authenticationComposite = new AuthenticationComposite(parentShell, SWT.NONE, false); + } + + @Override + protected Control createCustomArea(Composite parent) { + authenticationComposite.setParent(parent); + return authenticationComposite; + } + + @Override + protected Control createButtonBar(Composite parent) { + Control c = super.createButtonBar(parent); + okButton = getButton(0); + cancelButton = getButton(1); + + okButton.setEnabled(false); + okButton.addSelectionListener(authenticationComposite.getAuthenticateListener()); + okButton.addSelectionListener(new SelectionAdapter() { + + @Override + public void widgetSelected(SelectionEvent e) { + selectionOk = true; + } + }); + authenticationComposite.getShell().setDefaultButton(okButton); + + cancelButton.addSelectionListener(new SelectionAdapter() { + public void widgetSelected(SelectionEvent e) { + selectionOk = false; + } + }); + return c; + } + + public boolean isValid() { + return selectionOk; + } + + private void setUserName(String user) { + authenticationComposite.setUserName(user); + } + + private void setPassword(String password) { + authenticationComposite.setPassword(password); + } + + private void setDomain(String domain) { + authenticationComposite.setDomain(domain); + } + + private void setStorageAllowed(boolean isStorageAllowed) { + authenticationComposite.setStorageAllowed(isStorageAllowed); + } + + private void setGuestLogin(boolean isGuestLogin) { + authenticationComposite.setGuestLogin(isGuestLogin); + } + + private String getUserName() { + return authenticationComposite.getUserName(); + } + + private String getDomain() { + return authenticationComposite.getDomain(); + } + + private boolean isStorageAllowed() { + return authenticationComposite.isStorageAllowed(); + } + + private boolean isGuestLogin() { + return authenticationComposite.isGuestLogin(); + } + + public static void openDialog() { + Display.getDefault().syncExec(new Runnable() { + + private String getErrorMessage(AuthenticationStatus status) { + String toReturn = ""; + switch (status) { + case UserNotFound: + toReturn = "User Id not found.\n" + "Enter your user id."; + break; + case InvalidPassword: + toReturn = + "Invalid Password.\n" + "Make sure <CAPS LOCK> is not enabled.\n" + "Enter a valid password."; + break; + case NoResponse: + toReturn = "Please enter a valid user id and password."; + break; + default: + break; + } + return toReturn; + } + + public void run() { + String dialogTitle = "Authentication Failed"; + String endMsg = "Shutting down the workbench."; + String user = ""; + String domain = ""; + String message = ""; + boolean isStorageAllowed = false; + boolean isGuestLogin = false; + boolean shutdown = false; + Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(); + + OseeAuthentication oseeAuthentication = OseeAuthentication.getInstance(); + + for (int numberOfTries = 0; numberOfTries < MAX_RETRIES; numberOfTries++) { + AuthenticationDialog dialog = new AuthenticationDialog(shell); + if (numberOfTries != 0) { + dialog.setUserName(user); + dialog.setPassword(""); + dialog.setDomain(domain); + dialog.setStorageAllowed(isStorageAllowed); + dialog.setGuestLogin(isGuestLogin); + } + int result = dialog.open(); + + user = dialog.getUserName(); + domain = dialog.getDomain(); + isStorageAllowed = dialog.isStorageAllowed(); + isGuestLogin = dialog.isGuestLogin(); + + if (result == Window.CANCEL) { + // TODO This was added because ATS requires a user to be logged in + // Non-Authentication is not an option -- + if (numberOfTries >= MAX_RETRIES - 1) { + message = "Maximum number of Retries reached.\n" + endMsg; + shutdown = true; + } else { + message = + "Please log in as Guest or with your credentials.\n" + "A Log-in account is required to continue."; + } + + MessageDialog.openError(shell, "Authentication Cancelled", message); + } + // else if (result != Window.OK ) { + // numberOfTries = MAX_RETRIES; + // } + else { + if (dialog.isValid()) { + AuthenticationStatus status = oseeAuthentication.getAuthenticationStatus(); + switch (status) { + case Success: + numberOfTries = MAX_RETRIES; + MessageDialog.openInformation(shell, "Authenticated", + "Logged in as: " + oseeAuthentication.getCredentials().getField( + UserCredentialEnum.Name)); + break; + default: + if (numberOfTries >= MAX_RETRIES - 1) { + message = "Maximum number of Retries reached.\n" + endMsg; + shutdown = true; + } else { + message = getErrorMessage(status); + } + MessageDialog.openError(shell, dialogTitle, message); + break; + } + } + } + } + + if (shutdown) { + PlatformUI.getWorkbench().close(); + } + } + }); + } +} diff --git a/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/security/GuestAuthentication.java b/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/security/GuestAuthentication.java new file mode 100644 index 00000000000..1f53c7bab11 --- /dev/null +++ b/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/security/GuestAuthentication.java @@ -0,0 +1,69 @@ +/******************************************************************************* + * Copyright (c) 2004, 2007 Boeing. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Boeing - initial API and implementation + *******************************************************************************/ +package org.eclipse.osee.framework.ui.plugin.security; + +import org.eclipse.osee.framework.ui.plugin.security.OseeAuthentication.AuthenticationStatus; +import org.eclipse.osee.framework.ui.plugin.security.UserCredentials.UserCredentialEnum; + +/** + * @author Roberto E. Escobar + */ +public class GuestAuthentication extends AbstractAuthentication implements IAuthenticationStrategy { + + private static GuestAuthentication instance = null; + + public static final String DEFAULT_USER_NAME = "Guest"; + public static final String DEFAULT_USER_ID = "99999998"; + + private GuestAuthentication() { + super(); + } + + public static GuestAuthentication getInstance() { + if (instance == null) { + instance = new GuestAuthentication(); + } + return instance; + } + + /* + * (non-Javadoc) + * + * @see osee.plugin.core.security.IAuthentication#authenticate(java.lang.String, java.lang.String, + * java.lang.String) + */ + public boolean authenticate(String userName, String password, String domain) { + clear(); + userCredentials.setFieldAndValidity(UserCredentialEnum.Id, true, DEFAULT_USER_ID); + userCredentials.setFieldAndValidity(UserCredentialEnum.Name, true, DEFAULT_USER_NAME); + authenticationStatus = AuthenticationStatus.Success; + return true; + } + + /* + * (non-Javadoc) + * + * @see osee.plugin.core.security.IAuthentication#isNetworked() + */ + public boolean isNetworked() { + return false; + } + + /* + * (non-Javadoc) + * + * @see osee.plugin.core.security.IAuthentication#isLoginAllowed() + */ + public boolean isLoginAllowed() { + return true; + } + +} diff --git a/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/security/IAuthentication.java b/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/security/IAuthentication.java new file mode 100644 index 00000000000..6a273de7da6 --- /dev/null +++ b/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/security/IAuthentication.java @@ -0,0 +1,29 @@ +/******************************************************************************* + * Copyright (c) 2004, 2007 Boeing. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Boeing - initial API and implementation + *******************************************************************************/ +package org.eclipse.osee.framework.ui.plugin.security; + +import org.eclipse.osee.framework.ui.plugin.security.OseeAuthentication.AuthenticationStatus; + +/** + * @author Roberto E. Escobar + */ +public interface IAuthentication { + + UserCredentials getCredentials(); + + boolean isAuthenticated(); + + AuthenticationStatus getAuthenticationStatus(); + + void clear(); + + boolean isLoginAllowed(); +} diff --git a/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/security/IAuthenticationStrategy.java b/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/security/IAuthenticationStrategy.java new file mode 100644 index 00000000000..fc2d9b322bc --- /dev/null +++ b/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/security/IAuthenticationStrategy.java @@ -0,0 +1,18 @@ +/******************************************************************************* + * Copyright (c) 2004, 2007 Boeing. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Boeing - initial API and implementation + *******************************************************************************/ +package org.eclipse.osee.framework.ui.plugin.security; + +/** + * @author Roberto E. Escobar + */ +public interface IAuthenticationStrategy extends IAuthentication { + boolean authenticate(String userName, String password, String domain); +} diff --git a/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/security/INetworkRequired.java b/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/security/INetworkRequired.java new file mode 100644 index 00000000000..6d0f6418daf --- /dev/null +++ b/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/security/INetworkRequired.java @@ -0,0 +1,18 @@ +/******************************************************************************* + * Copyright (c) 2004, 2007 Boeing. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Boeing - initial API and implementation + *******************************************************************************/ +package org.eclipse.osee.framework.ui.plugin.security; + +/** + * @author Roberto E. Escobar + */ +public interface INetworkRequired { + +} diff --git a/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/security/JvmAuthentication.java b/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/security/JvmAuthentication.java new file mode 100644 index 00000000000..0134375ec5c --- /dev/null +++ b/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/security/JvmAuthentication.java @@ -0,0 +1,65 @@ +/******************************************************************************* + * Copyright (c) 2004, 2007 Boeing. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Boeing - initial API and implementation + *******************************************************************************/ +package org.eclipse.osee.framework.ui.plugin.security; + +import org.eclipse.osee.framework.ui.plugin.security.OseeAuthentication.AuthenticationStatus; +import org.eclipse.osee.framework.ui.plugin.security.UserCredentials.UserCredentialEnum; + +/** + * @author Roberto E. Escobar + */ +public class JvmAuthentication extends AbstractAuthentication implements IAuthenticationStrategy { + private static final JvmAuthentication instance = new JvmAuthentication(); + + protected JvmAuthentication() { + super(); + } + + public static JvmAuthentication getInstance() { + return instance; + } + + protected String getUserNameProperty() { + return java.lang.System.getProperty("user.name"); + } + + /* + * (non-Javadoc) + * + * @see osee.plugin.core.security.IAuthentication#authenticate(java.lang.String, java.lang.String, + * java.lang.String) + */ + public boolean authenticate(String userName, String password, String domain) { + clear(); + String jvmUserName = getUserNameProperty(); + userCredentials.setFieldAndValidity(UserCredentialEnum.Id, true, jvmUserName); + userCredentials.setFieldAndValidity(UserCredentialEnum.Name, true, jvmUserName); + authenticationStatus = AuthenticationStatus.Success; + return true; + } + + /* + * (non-Javadoc) + * + * @see osee.plugin.core.security.IAuthentication#isNetworked() + */ + public boolean isNetworked() { + return false; + } + + /* (non-Javadoc) + * @see osee.plugin.core.security.IAuthentication#isLoginAllowed() + */ + public boolean isLoginAllowed() { + return false; + } + +} diff --git a/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/security/OseeAuthentication.java b/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/security/OseeAuthentication.java new file mode 100644 index 00000000000..a2e754b7467 --- /dev/null +++ b/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/security/OseeAuthentication.java @@ -0,0 +1,142 @@ +/******************************************************************************* + * Copyright (c) 2004, 2007 Boeing. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Boeing - initial API and implementation + *******************************************************************************/ + +package org.eclipse.osee.framework.ui.plugin.security; + +import java.net.MalformedURLException; +import java.net.URL; +import java.util.HashMap; +import java.util.Map; +import java.util.logging.Level; +import java.util.logging.Logger; +import org.eclipse.core.runtime.CoreException; +import org.eclipse.core.runtime.Platform; +import org.eclipse.osee.framework.plugin.core.config.ConfigUtil; +import org.eclipse.osee.framework.plugin.core.util.ExtensionDefinedObjects; +import org.eclipse.osee.framework.ui.plugin.security.UserCredentials.UserCredentialEnum; + +/** + * @author Roberto E. Escobar + */ +public class OseeAuthentication extends AbstractAuthentication { + private static final Logger logger = ConfigUtil.getConfigFactory().getLogger(OseeAuthentication.class); + private static final String EXTENSION_ID = "org.eclipse.osee.framework.ui.plugin.AuthenticationProvider"; + private static final String ELEMENT_NAME = "AuthenticationClass"; + private static OseeAuthentication instance = null; + private static URL DEFAULT_URL; + private boolean logAsGuest = false; + + static { + try { + DEFAULT_URL = new URL("http://osee.authentication/"); + } catch (MalformedURLException e) { + } + } + + public enum AuthenticationStatus { + Success, UserNotFound, InvalidPassword, NoResponse; + } + + private IAuthenticationStrategy authenticationProvider; + private ExtensionDefinedObjects<IAuthenticationStrategy> authenticationStrategies; + + private OseeAuthentication() { + super(); + authenticationProvider = null; + authenticationStrategies = + new ExtensionDefinedObjects<IAuthenticationStrategy>(EXTENSION_ID, ELEMENT_NAME, "classname"); + authenticateFromStorage(); + } + + public static OseeAuthentication getInstance() { + if (instance == null) { + instance = new OseeAuthentication(); + } + return instance; + } + + public AuthenticationStatus authenticate(String userName, String password, String domain, boolean isStorageAllowed) { + IAuthenticationStrategy authenticationStrategy = getAuthenticationStrategy(); + authenticationStrategy.authenticate(userName, password, domain); + authenticationStatus = authenticationStrategy.getAuthenticationStatus(); + userCredentials = authenticationStrategy.getCredentials(); + + if (authenticationStatus.equals(AuthenticationStatus.Success) && isStorageAllowed) { + storeCredentials(userCredentials, userName, password); + } + return authenticationStatus; + } + + public IAuthenticationStrategy getAuthenticationStrategy() { + IAuthenticationStrategy toReturn = null; + + // Load the authentication provider if we don't have one yet + if (authenticationProvider == null) { + String providerId = ConfigUtil.getConfigFactory().getOseeConfig().getAuthenticationProviderId(); + try { + authenticationProvider = authenticationStrategies.getObjectById(providerId); + if (authenticationProvider == null) { + throw new IllegalStateException(); + } + } catch (Exception ex) { + logger.log(Level.SEVERE, String.format("Authentication Provider [ %s ] not found defaulting to guest. ", + providerId)); + logAsGuest = true; + } + } + + if (false != logAsGuest) { + toReturn = GuestAuthentication.getInstance(); + } else { + toReturn = authenticationProvider; + } + return toReturn; + } + + @SuppressWarnings("unchecked") + private void authenticateFromStorage() { + Map info = Platform.getAuthorizationInfo(DEFAULT_URL, "", ""); + + if (info != null) { + userCredentials = UserCredentials.toCredentials(new HashMap(info)); + authenticate(userCredentials.getField(UserCredentialEnum.UserName), + userCredentials.getField(UserCredentialEnum.Password), + userCredentials.getField(UserCredentialEnum.Domain), false); + } + } + + private void storeCredentials(UserCredentials userCredentials, String userName, String password) { + try { + userCredentials.setFieldAndValidity(UserCredentialEnum.UserName, true, userName); + userCredentials.setFieldAndValidity(UserCredentialEnum.Password, true, password); + Platform.addAuthorizationInfo(DEFAULT_URL, "", "", userCredentials.toMap()); + } catch (CoreException e) { + } + } + + /* + * (non-Javadoc) + * + * @see osee.plugin.core.security.IAuthentication#isLoginAllowed() + */ + public boolean isLoginAllowed() { + return getAuthenticationStrategy().isLoginAllowed(); + } + + public void setLogAsGuest(boolean logAsGuest) { + this.logAsGuest = logAsGuest; + } + + public void logOff() { + super.clear(); + storeCredentials(userCredentials, "", ""); + } +} diff --git a/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/security/UserCredentials.java b/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/security/UserCredentials.java new file mode 100644 index 00000000000..233cb482614 --- /dev/null +++ b/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/security/UserCredentials.java @@ -0,0 +1,108 @@ +/******************************************************************************* + * Copyright (c) 2004, 2007 Boeing. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Boeing - initial API and implementation + *******************************************************************************/ +package org.eclipse.osee.framework.ui.plugin.security; + +import java.io.Serializable; +import java.util.HashMap; +import java.util.Map; +import java.util.Set; +import org.eclipse.osee.framework.jdk.core.type.Pair; + +/** + * @author Roberto E. Escobar + */ +public class UserCredentials { + + public enum UserCredentialEnum implements Serializable { + Name, Email, Id, Domain, UserName, Password; + } + + private Map<UserCredentialEnum, Pair<Boolean, String>> credentialsMap; + + public UserCredentials() { + super(); + credentialsMap = new HashMap<UserCredentialEnum, Pair<Boolean, String>>(); + } + + public boolean isValid(UserCredentialEnum field) { + Pair<Boolean, String> pair = credentialsMap.get(field); + if (pair != null) { + return pair.getKey().booleanValue(); + } + return false; + } + + public String getField(UserCredentialEnum field) { + Pair<Boolean, String> pair = credentialsMap.get(field); + if (pair != null) { + return pair.getValue(); + } + return ""; + } + + public void setFieldAndValidity(UserCredentialEnum field, boolean isValid, String value) { + Pair<Boolean, String> pair = credentialsMap.get(field); + if (pair != null) { + pair.setKey(new Boolean(isValid)); + pair.setValue(value); + } else { + credentialsMap.put(field, new Pair<Boolean, String>(new Boolean(isValid), value)); + } + } + + public void setValid(UserCredentialEnum field, boolean isValid) { + Pair<Boolean, String> pair = credentialsMap.get(field); + if (pair != null) { + pair.setKey(new Boolean(isValid)); + } else { + credentialsMap.put(field, new Pair<Boolean, String>(new Boolean(isValid), "")); + } + } + + public void setField(UserCredentialEnum field, String value) { + Pair<Boolean, String> pair = credentialsMap.get(field); + if (pair != null) { + pair.setValue(value); + } else { + credentialsMap.put(field, new Pair<Boolean, String>(new Boolean(false), value)); + } + } + + protected static UserCredentials toCredentials(Map<String, String> info) { + UserCredentials toReturn = new UserCredentials(); + for (UserCredentialEnum credentialEnum : UserCredentialEnum.values()) { + String value = (String) info.get(credentialEnum.toString()); + if (value != null) { + toReturn.setFieldAndValidity(credentialEnum, true, value); + } + } + return toReturn; + } + + public Map<String, String> toMap() { + Map<String, String> infoMap = new HashMap<String, String>(); + Set<UserCredentialEnum> keys = credentialsMap.keySet(); + for (UserCredentialEnum credentialEnum : keys) { + String key = credentialEnum.toString(); + String value = getField(credentialEnum); + infoMap.put(key, value); + } + return infoMap; + } + + public void clear() { + credentialsMap.clear(); + } + + public String toString() { + return String.format("%s", credentialsMap.toString()); + } +} diff --git a/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/util/AEditor.java b/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/util/AEditor.java new file mode 100644 index 00000000000..1e414fdd6ff --- /dev/null +++ b/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/util/AEditor.java @@ -0,0 +1,149 @@ +/******************************************************************************* + * Copyright (c) 2004, 2007 Boeing. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Boeing - initial API and implementation + *******************************************************************************/ +package org.eclipse.osee.framework.ui.plugin.util; + +import org.eclipse.core.resources.IFile; +import org.eclipse.jface.text.IDocument; +import org.eclipse.jface.text.IRegion; +import org.eclipse.jface.text.ITextSelection; +import org.eclipse.jface.viewers.ISelection; +import org.eclipse.jface.viewers.ISelectionProvider; +import org.eclipse.ui.IEditorInput; +import org.eclipse.ui.IEditorPart; +import org.eclipse.ui.IEditorReference; +import org.eclipse.ui.IEditorSite; +import org.eclipse.ui.IFileEditorInput; +import org.eclipse.ui.IWorkbenchPage; +import org.eclipse.ui.IWorkbenchWindow; +import org.eclipse.ui.PartInitException; +import org.eclipse.ui.PlatformUI; +import org.eclipse.ui.ide.IDE; +import org.eclipse.ui.texteditor.AbstractDecoratedTextEditor; +import org.eclipse.ui.texteditor.ITextEditor; + +/** + * TODO It appears that this class is not being used. + * + * @author Donald G. Dunne + */ +public class AEditor { + + /** + * Jump to line number of an iFile + */ + public static void goToLine(IFile targetIFile, int lineNumber) { + if (targetIFile == null || targetIFile.equals("")) { + return; + } + lineNumber = (lineNumber >= 0) ? --lineNumber : -1; + final IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage(); + + IEditorPart editor = page.getActiveEditor(); + if (editor != null) { + IEditorInput input = editor.getEditorInput(); + if (input instanceof IFileEditorInput) { + IFile file = ((IFileEditorInput) input).getFile(); + if (targetIFile.equals(file)) { + page.activate(editor); + } + } + } + + try { + // if jarIFile is java file, + String editorId = IDE.getEditorDescriptor(targetIFile).getId(); + editor = IDE.openEditor(page, targetIFile, editorId); + IEditorInput editorInput = editor.getEditorInput(); + if (editor instanceof AbstractDecoratedTextEditor) { + ITextEditor textEditor = (ITextEditor) editor; + IDocument document = textEditor.getDocumentProvider().getDocument(editorInput); + IRegion lineInformation = document.getLineInformation(lineNumber); + textEditor.selectAndReveal(lineInformation.getOffset(), 0); + } + } catch (Exception e) { + e.printStackTrace(); + } + } + + public static boolean openEditor(String filename) { + IFile iFile = AWorkspace.getIFile(filename); + return openEditor(iFile); + } + + public static boolean openEditor(IFile iFile) { + IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage(); + try { + IDE.openEditor(page, iFile, true); + } catch (PartInitException e) { + e.printStackTrace(); + return false; + } + return true; + } + + public static IFile getActiveEditorIFile() { + IWorkbenchWindow workbenchWindow = PlatformUI.getWorkbench().getActiveWorkbenchWindow(); + if (workbenchWindow != null) { + IWorkbenchPage workbenchPage = workbenchWindow.getActivePage(); + if (workbenchPage != null) { + IEditorPart editorPart = workbenchPage.getActiveEditor(); + if (editorPart != null) { + IEditorInput editorInput = editorPart.getEditorInput(); + if (editorInput != null) { + if (editorInput instanceof IFileEditorInput) return ((IFileEditorInput) editorInput).getFile(); + } + } + } + } + return null; + } + + public static IEditorReference[] getEditorReferences() { + IWorkbenchWindow workbenchWindow = PlatformUI.getWorkbench().getActiveWorkbenchWindow(); + if (workbenchWindow != null) { + IWorkbenchPage workbenchPage = workbenchWindow.getActivePage(); + if (workbenchPage != null) { + return workbenchPage.getEditorReferences(); + } + } + return null; + } + + /** + * @return line number of selected text in active editor + */ + public static ITextSelection getSelectedText() { + IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow(); + if (window != null) { + IWorkbenchPage page = window.getActivePage(); + IEditorPart activeEditorPart = page.getActiveEditor(); + if (activeEditorPart != null) { + IEditorSite editorSite = page.getActiveEditor().getEditorSite(); + ISelectionProvider selectionProvider = editorSite.getSelectionProvider(); + if (selectionProvider != null) { + ISelection selection = selectionProvider.getSelection(); + if (selection instanceof ITextSelection) { + return (ITextSelection) selection; + } + } + } + } + return null; + } + + /** + * @return line number of selected text in active editor + */ + public static int getLineNumber() { + return getSelectedText().getStartLine() + 1; + } + +} diff --git a/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/util/AIFile.java b/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/util/AIFile.java new file mode 100644 index 00000000000..574b7fabeab --- /dev/null +++ b/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/util/AIFile.java @@ -0,0 +1,48 @@ +/******************************************************************************* + * Copyright (c) 2004, 2007 Boeing. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Boeing - initial API and implementation + *******************************************************************************/ +package org.eclipse.osee.framework.ui.plugin.util; + +import java.io.IOException; +import java.io.InputStream; +import org.eclipse.core.resources.IFile; +import org.eclipse.core.resources.IWorkspaceRoot; +import org.eclipse.core.resources.ResourcesPlugin; +import org.eclipse.core.runtime.CoreException; +import org.eclipse.core.runtime.NullProgressMonitor; +import org.eclipse.core.runtime.Path; +import org.eclipse.osee.framework.jdk.core.util.io.Streams; + +/** + * @author Ryan D. Brooks + */ +public class AIFile { + + public static void writeToFile(IFile file, InputStream in) throws CoreException, IOException { + if (file.exists()) { + file.setCharset("UTF-8", new NullProgressMonitor()); + file.setContents(in, true, false, null); // steam will be closed before return + } else { + file.create(in, true, null); + in.close(); + } + } + + public static void writeToFile(IFile file, String string) throws CoreException, IOException { + writeToFile(file, Streams.convertStringToInputStream(string, "UTF-8")); + } + + public static IFile constructIFile(String fullPath) { + IWorkspaceRoot workspaceRoot = ResourcesPlugin.getWorkspace().getRoot(); + IFile[] files = workspaceRoot.findFilesForLocation(Path.fromOSString(fullPath)); + if (files == null || files.length == 0) return null; + return workspaceRoot.findFilesForLocation(Path.fromOSString(fullPath))[0]; + } +}
\ No newline at end of file diff --git a/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/util/AIFolder.java b/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/util/AIFolder.java new file mode 100644 index 00000000000..dd8158d95c9 --- /dev/null +++ b/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/util/AIFolder.java @@ -0,0 +1,27 @@ +/******************************************************************************* + * Copyright (c) 2004, 2007 Boeing. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Boeing - initial API and implementation + *******************************************************************************/ +package org.eclipse.osee.framework.ui.plugin.util; + +import org.eclipse.core.resources.IFolder; +import org.eclipse.core.resources.IProject; +import org.eclipse.core.runtime.CoreException; + +public class AIFolder { + + public static IFolder getFolder(IProject containingProject, String name) throws CoreException { + IFolder folder = containingProject.getFolder(name); + + if (!folder.exists()) { + folder.create(true, true, null); + } + return folder; + } +} diff --git a/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/util/AJavaProject.java b/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/util/AJavaProject.java new file mode 100644 index 00000000000..2e19f7778cd --- /dev/null +++ b/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/util/AJavaProject.java @@ -0,0 +1,234 @@ +/******************************************************************************* + * Copyright (c) 2004, 2007 Boeing. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Boeing - initial API and implementation + *******************************************************************************/ +package org.eclipse.osee.framework.ui.plugin.util; + +import java.io.File; +import java.io.IOException; +import java.net.MalformedURLException; +import java.net.URL; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Map; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import org.eclipse.core.resources.IFile; +import org.eclipse.core.runtime.IPath; +import org.eclipse.jdt.core.IClasspathEntry; +import org.eclipse.jdt.core.IJavaProject; +import org.eclipse.jdt.core.JavaCore; +import org.eclipse.jdt.core.JavaModelException; +import org.eclipse.osee.framework.jdk.core.util.Lib; + +/** + * @author Donald G. Dunne + */ +public class AJavaProject { + + private static Map<IJavaProject, IClasspathEntry[]> cachedPath = new HashMap<IJavaProject, IClasspathEntry[]>(); + + + private static IClasspathEntry[] localGetResolvedClasspath(IJavaProject javaProject) throws JavaModelException { + IClasspathEntry[] paths = cachedPath.get(javaProject); + if(paths == null){ + paths = javaProject.getResolvedClasspath(true); + cachedPath.put(javaProject, paths); + } + return paths; + } +// public static URL[] getClasspathAsURLArray(IJavaProject javaProject) { + // if (javaProject == null) + // return null; + // Set visited = new HashSet(); + // ArrayList urls = new ArrayList(70); + // return myClasspath(javaProject).; + // // collectClasspathURLs(javaProject, urls, visited, true); + // // URL[] result = new URL[urls.size()]; + // // urls.toArray(result); + // // return result; + // } + + public static IJavaProject getJavaProject(File file) { + IFile ifile = AWorkspace.fileToIFile(file); + return JavaCore.create(ifile.getProject()); + } + + public static ArrayList<URL> getAllJavaProjectDependancies(IJavaProject javaProject) { + ArrayList<URL> urls = new ArrayList<URL>(); + ArrayList<File> files = getJavaProjectProjectDependancies(javaProject); + for (int i = 0; i < files.size(); i++) { + try { + urls.add(files.get(i).toURL()); + } catch (MalformedURLException ex) { + ex.printStackTrace(); + } + } + return urls; + } + + public static String getClassFilePath(String file) { + String classFile = null; + IJavaProject javaProject = getJavaProject(new File(file)); + //ArrayList<File> urls = new ArrayList<File>(); + try { + + IClasspathEntry[] paths = localGetResolvedClasspath(javaProject); + + for (int i = 0; i < paths.length; i++) { + if (paths[i].getEntryKind() == IClasspathEntry.CPE_SOURCE) { + File projectlocation = javaProject.getProject().getLocation().toFile(); + File projecttricky = javaProject.getProject().getFullPath().toFile(); + IPath output = paths[i].getOutputLocation(); + File fileLocation; + if (output == null) { + fileLocation = new File(paths[i].getPath().toFile().getPath().replace("src", "bin")); + } else { + fileLocation = paths[i].getOutputLocation().toFile(); + } + File javaFileLocation = paths[i].getPath().toFile(); + String realClassLocation = + fileLocation.toString().replace(projecttricky.toString(), projectlocation.toString()); + String realJavaLocation = + javaFileLocation.toString().replace(projecttricky.toString(), projectlocation.toString()); + String packagePath = file.replace(realJavaLocation, ""); + packagePath = packagePath.replace(".java", ".class"); + File theclassfile = new File(realClassLocation, packagePath); + if (theclassfile.exists()) { + classFile = theclassfile.getAbsolutePath(); + break; + } + } + } + + } catch (JavaModelException ex) { + ex.printStackTrace(); + } + if (classFile == null) { + try { + String packageName = ""; + File java = new File(file); + packageName = getJavaPackage(java); + packageName = packageName.replace(".", File.separator); + packageName += File.separator + java.getName(); + classFile = file.replace(packageName, ""); + } catch (IOException e) { + e.printStackTrace(); + } + } + return classFile; + } + + public static String getClassName(String file) { + String classname = null; + IJavaProject javaProject = getJavaProject(new File(file)); + //ArrayList<File> urls = new ArrayList<File>(); + try { + IClasspathEntry[] paths = localGetResolvedClasspath(javaProject); + for (int i = 0; i < paths.length; i++) { + if (paths[i].getEntryKind() == IClasspathEntry.CPE_SOURCE) { + File projectlocation = javaProject.getProject().getLocation().toFile(); + File projecttricky = javaProject.getProject().getFullPath().toFile(); + IPath output = paths[i].getOutputLocation(); + File fileLocation; + if (output == null) { + fileLocation = new File(paths[i].getPath().toFile().getPath().replace("src", "bin")); + } else { + fileLocation = paths[i].getOutputLocation().toFile(); + } + File javaFileLocation = paths[i].getPath().toFile(); + String realClassLocation = + fileLocation.toString().replace(projecttricky.toString(), projectlocation.toString()); + String realJavaLocation = + javaFileLocation.toString().replace(projecttricky.toString(), projectlocation.toString()); + String packagePath = file.replace(realJavaLocation, ""); + packagePath = packagePath.replace(".java", ".class"); + File theclassfile = new File(realClassLocation, packagePath); + if (theclassfile.exists()) { + packagePath = packagePath.replace(".class", ""); + classname = packagePath.replaceAll("^\\\\", "");//windows + classname = classname.replaceAll("^/", "");//linux + classname = classname.replace("\\", ".");//windows + classname = classname.replace("/", ".");//linux + break; + } + } + } + + } catch (JavaModelException ex) { + ex.printStackTrace(); + } + if (classname == null) { + try { + String packageName = ""; + File java = new File(file); + packageName = getJavaPackage(java); + if (packageName.length() > 0) { + packageName += "."; + } + packageName += java.getName().replace(".java", ""); + classname = packageName; + } catch (IOException e) { + e.printStackTrace(); + } + } + return classname; + } + + public static String getJavaPackage(File javaFile) throws IOException { + String packageName = ""; + String javaFileContent = Lib.fileToString(javaFile); + Pattern pattern = Pattern.compile(".*package\\s*(.*?);.*", Pattern.DOTALL); + Matcher match = pattern.matcher(javaFileContent); + if (match.matches()) { + packageName = match.group(1); + } + return packageName; + } + + public static ArrayList<File> getJavaProjectProjectDependancies(IJavaProject javaProject) { + ArrayList<File> urls = new ArrayList<File>(); + try { + IClasspathEntry[] paths = localGetResolvedClasspath(javaProject); + for (int i = 0; i < paths.length; i++) { + if (paths[i].getEntryKind() == IClasspathEntry.CPE_LIBRARY) { + if (paths[i].getPath().toFile().exists()) { + // urls.add(paths[i].getPath().toFile()); + } else { + File f = null; + f = new File(AWorkspace.getWorkspacePath().concat(paths[i].getPath().toOSString())); + if (f != null && f.exists()) { + urls.add(f); + } + } + } else if (paths[i].getEntryKind() == IClasspathEntry.CPE_PROJECT) { + urls.add(new File(AWorkspace.getWorkspacePath().concat( + paths[i].getPath().toFile().getPath().concat(File.separator + "bin" + File.separator)))); + } else if (paths[i].getEntryKind() == IClasspathEntry.CPE_SOURCE) { + File projectlocation = javaProject.getProject().getLocation().toFile(); + File projecttricky = javaProject.getProject().getFullPath().toFile(); + IPath output = paths[i].getOutputLocation(); + File fileLocation; + if (output == null) { + fileLocation = new File(paths[i].getPath().toFile().getPath().replace("src", "bin")); + } else { + fileLocation = paths[i].getOutputLocation().toFile(); + } + String realLocation = + fileLocation.toString().replace(projecttricky.toString(), projectlocation.toString()); + urls.add(new File(realLocation)); + } + } + + } catch (JavaModelException ex) { + ex.printStackTrace(); + } + return urls; + } +}
\ No newline at end of file diff --git a/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/util/AWorkbench.java b/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/util/AWorkbench.java new file mode 100644 index 00000000000..2c7413de5c1 --- /dev/null +++ b/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/util/AWorkbench.java @@ -0,0 +1,67 @@ +/******************************************************************************* + * Copyright (c) 2004, 2007 Boeing. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Boeing - initial API and implementation + *******************************************************************************/ +package org.eclipse.osee.framework.ui.plugin.util; + +import java.util.logging.Level; +import org.eclipse.jface.dialogs.MessageDialog; +import org.eclipse.osee.framework.logging.OseeLog; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.ui.IViewPart; +import org.eclipse.ui.IWorkbenchPage; +import org.eclipse.ui.IWorkbenchWindow; +import org.eclipse.ui.PlatformUI; + +/** + * @author Donald G. Dunne + */ +public class AWorkbench { + + /** + * Popup a workbench viewer eg: AWorkbench.popupView(IPageLayout.ID_PROBLEM_VIEW); + * + * @param iPageLayoutView + * @return success + */ + public static boolean popupView(String iPageLayoutView) { + IViewPart p = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().findView(iPageLayoutView); + if (p != null) { + PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().activate(p); + return true; + } + return false; + } + + public static IViewPart getView(String viewId) { + return PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().findView(viewId); + } + + public static void popup(final String title, final String message) { + if (!PlatformUI.isWorkbenchRunning()) { + OseeLog.log(AWorkbench.class, Level.SEVERE, message); + } else { + Displays.ensureInDisplayThread(new Runnable() { + public void run() { + MessageDialog.openInformation(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), title, + message); + } + }); + } + } + + public static void popup(Composite comp, String title, String message) { + MessageDialog.openInformation(comp.getShell(), title, message); + } + + public static IWorkbenchPage getActivePage() { + IWorkbenchWindow workbenchWindow = PlatformUI.getWorkbench().getActiveWorkbenchWindow(); + return workbenchWindow != null ? workbenchWindow.getActivePage() : null; + } +}
\ No newline at end of file diff --git a/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/util/AWorkspace.java b/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/util/AWorkspace.java new file mode 100644 index 00000000000..7c86013af6f --- /dev/null +++ b/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/util/AWorkspace.java @@ -0,0 +1,585 @@ +/******************************************************************************* + * Copyright (c) 2004, 2007 Boeing. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Boeing - initial API and implementation + *******************************************************************************/ +package org.eclipse.osee.framework.ui.plugin.util; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.logging.Level; +import java.util.logging.Logger; +import java.util.regex.Pattern; +import org.eclipse.core.resources.IContainer; +import org.eclipse.core.resources.IFile; +import org.eclipse.core.resources.IProject; +import org.eclipse.core.resources.IResource; +import org.eclipse.core.resources.IResourceChangeEvent; +import org.eclipse.core.resources.IResourceChangeListener; +import org.eclipse.core.resources.IResourceDelta; +import org.eclipse.core.resources.IWorkspace; +import org.eclipse.core.resources.ResourcesPlugin; +import org.eclipse.core.runtime.CoreException; +import org.eclipse.core.runtime.IPath; +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.core.runtime.IStatus; +import org.eclipse.core.runtime.Path; +import org.eclipse.core.runtime.Status; +import org.eclipse.core.runtime.jobs.Job; +import org.eclipse.jdt.ui.IPackagesViewPart; +import org.eclipse.jface.dialogs.MessageDialog; +import org.eclipse.jface.viewers.StructuredSelection; +import org.eclipse.osee.framework.jdk.core.util.Lib; +import org.eclipse.osee.framework.plugin.core.config.ConfigUtil; +import org.eclipse.swt.widgets.Display; +import org.eclipse.ui.IViewPart; +import org.eclipse.ui.IViewReference; +import org.eclipse.ui.IWindowListener; +import org.eclipse.ui.IWorkbenchPage; +import org.eclipse.ui.IWorkbenchPart; +import org.eclipse.ui.IWorkbenchWindow; +import org.eclipse.ui.PartInitException; +import org.eclipse.ui.PlatformUI; +import org.eclipse.ui.ide.IDE; +import org.eclipse.ui.views.navigator.IResourceNavigator; +import org.eclipse.ui.views.navigator.ResourceNavigator; + +/** + * @author Donald G. Dunne + */ +public class AWorkspace { + + private static final Logger logger = ConfigUtil.getConfigFactory().getLogger(AWorkspace.class); + + private static HashMap<String, File> fileFindMap = new HashMap<String, File>(); + + private static boolean initializedWorkspaceSearch = false; + private static HashMap<String, List<File>> fileSearch = new HashMap<String, List<File>>(); + private static IWindowListener windowListener; + private static IResourceChangeListener changeListener; + + static { + logger.setLevel(Level.WARNING); + } + + public static void init(final Object objectToNotify) { + Job initJob = new WorkspaceSearchInit(objectToNotify); + initJob.setPriority(Job.LONG); + initJob.schedule(); + } + + public static void reinit() { + Job initJob = new Job("Initializing Workspace Search") { + protected IStatus run(IProgressMonitor monitor) { + initializedWorkspaceSearch = false; + File savefile = OseeData.getFile("serializedFileFinder"); + savefile.delete(); + + File mapfile = OseeData.getFile("fileFindMap"); + mapfile.delete(); + + fileSearch.clear(); + fileFindMap.clear(); + initWorkspaceSearch(); + return Status.OK_STATUS; + } + }; + initJob.setPriority(Job.LONG); + initJob.schedule(); + } + + @SuppressWarnings("unchecked") + public static void initWorkspaceSearch() { + if (!initializedWorkspaceSearch) { + initializedWorkspaceSearch = true; + File savefile = OseeData.getFile("serializedFileFinder"); + File mapfile = OseeData.getFile("fileFindMap"); + if (savefile.exists() && mapfile.exists()) { + ObjectInputStream ois; + try { + logger.log(Level.INFO, "starting init"); + long time = System.currentTimeMillis(); + ois = new ObjectInputStream(new FileInputStream(savefile)); + fileSearch = (HashMap<String, List<File>>) ois.readObject(); + logger.log(Level.INFO, "ending init " + (System.currentTimeMillis() - time) / 1000 + " secs"); + + logger.log(Level.INFO, "starting init"); + time = System.currentTimeMillis(); + ois = new ObjectInputStream(new FileInputStream(mapfile)); + fileFindMap = (HashMap<String, File>) ois.readObject(); + logger.log(Level.INFO, "ending init " + (System.currentTimeMillis() - time) / 1000 + " secs"); + + } catch (FileNotFoundException ex) { + ex.printStackTrace(); + } catch (IOException ex) { + ex.printStackTrace(); + } catch (ClassNotFoundException ex) { + ex.printStackTrace(); + } + } else { + logger.log(Level.INFO, "starting init"); + long time = System.currentTimeMillis(); + List files = Lib.recursivelyListFiles(new File(getWorkspacePath()), Pattern.compile(".*")); + for (Object obj : files) { + File file = (File) obj; + addFile(file); + } + logger.log(Level.INFO, "ending init " + (System.currentTimeMillis() - time) / 1000 + " secs"); + } + + if (changeListener == null) { + changeListener = new IResourceChangeListener() { + + public void resourceChanged(IResourceChangeEvent event) { + if (IResourceChangeEvent.POST_CHANGE == event.getType()) { + recDeltaInfo(event.getDelta()); + } + } + + private void recDeltaInfo(IResourceDelta delta) { + File file = delta.getResource().getLocation().toFile(); + if ((delta.getKind() & IResourceDelta.ADDED) > 0) { + addFile(file); + } else if ((delta.getKind() & IResourceDelta.REMOVED) > 0) { + removeFile(file); + } + IResourceDelta[] deltas = + delta.getAffectedChildren(IResourceDelta.ADDED | IResourceDelta.REMOVED | IResourceDelta.CHANGED); + for (IResourceDelta d : deltas) { + recDeltaInfo(d); + } + } + }; + OseeData.getProject().getWorkspace().addResourceChangeListener(changeListener); + } + if (windowListener == null) { + windowListener = new IWindowListener() { + + public void windowActivated(IWorkbenchWindow window) { + } + + public void windowClosed(IWorkbenchWindow window) { + logger.log(Level.INFO, "closed window"); + logger.log(Level.INFO, "saving..."); + + try { + ObjectOutputStream oos = + new ObjectOutputStream(new FileOutputStream(OseeData.getFile("serializedFileFinder"))); + oos.writeObject(fileSearch); + + oos = new ObjectOutputStream(new FileOutputStream(OseeData.getFile("fileFindMap"))); + oos.writeObject(fileFindMap); + } catch (FileNotFoundException ex) { + ex.printStackTrace(); + } catch (IOException ex) { + ex.printStackTrace(); + } + + } + + public void windowDeactivated(IWorkbenchWindow window) { + } + + public void windowOpened(IWorkbenchWindow window) { + } + + }; + PlatformUI.getWorkbench().addWindowListener(windowListener); + } + + } + } + + /** + * @param file + */ + protected static void removeFile(File file) { + List<File> files = fileSearch.get(file.getName()); + Iterator<File> it = files.iterator(); + while (it.hasNext()) { + File f = it.next(); + if (f.equals(file)) { + it.remove(); + } + } + if (files.size() == 0) { + fileSearch.remove(file.getName()); + } + } + + /** + * @param file + */ + protected static void addFile(File file) { + if (file.isFile()) { + List<File> fileSearchResults = fileSearch.get(file.getName()); + if (fileSearchResults == null) { + fileSearchResults = new ArrayList<File>(); + fileSearch.put(file.getName(), fileSearchResults); + } + if (!fileSearchResults.contains(file)) { + fileSearchResults.add(file); + } + } + } + + public static File getProjectFile(File fileFile) { + // If file is an artifact, go up one level to create tree + File parentFile = fileFile.getParentFile(); + while (!parentFile.getParentFile().getName().equals("workspace") && !parentFile.getParentFile().getName().equals( + "runtime-workbench-workspace")) { + parentFile = parentFile.getParentFile(); + } + return parentFile; + } + + public static String getWorkspacePath() { + return ResourcesPlugin.getWorkspace().getRoot().getLocation().toOSString(); + } + + public static File iFileToFile(IFile iFile) { + return new File(iFile.getLocation().toString()); + } + + public static IFile fileToIFile(File file) { + String p = file.getAbsolutePath(); + IPath path = new Path(p); + IFile iFile = ResourcesPlugin.getWorkspace().getRoot().getFile(path); + if (iFile.exists()) return iFile; + p = p.replace('\\', '/'); + // System.err.println("p *" + p + "*"); + // Run through projects to see if any contain this file + IProject projs[] = getProjects(); + for (int i = 0; i < projs.length; i++) { + IProject proj = projs[i]; + String projLoc = proj.getLocation().toString(); + // System.err.println("proj *" + projLoc + "*"); + if (p.equals(projLoc)) { + return null; + } else if (p.startsWith(projLoc)) { + // System.out.println("found it"); + p = p.replaceFirst(projLoc, ""); + p = "/" + proj.getName() + p; + // System.err.println("new pLoc*" + p + "*"); + path = new Path(p); + iFile = ResourcesPlugin.getWorkspace().getRoot().getFile(path); + if (iFile.exists()) { + return iFile; + } else { + // System.err.println("iFile DOESN'T exist *" + + // iFile.getRawLocation()+ "*"); + } + } + // System.out.println("proj"); + } + return null; + } + + public static IProject fileToIProject(File file) { + String p = file.getAbsolutePath(); + p = p.replace('\\', '/'); + System.err.println("p *" + p + "*"); + // Run through projects to see if any contain this file + IProject projs[] = getProjects(); + for (int i = 0; i < projs.length; i++) { + IProject proj = projs[i]; + String projLoc = proj.getLocation().toString(); + System.err.println("proj *" + projLoc + "*"); + if (p.equals(projLoc)) { + return proj; + } + } + return null; + } + + public static IFile getIFile(String filename) { + return fileToIFile(new File(filename)); + } + + public static IProject[] getProjects() { + IWorkspace workspace = ResourcesPlugin.getWorkspace(); + return workspace.getRoot().getProjects(); + } + + public static boolean showInResourceNavigator(IFile file) { + if (file == null) { + return false; + } + IWorkbenchPage page = AWorkbench.getActivePage(); + try { + IViewPart viewPart = + page.showView("org.eclipse.ui.views.ResourceNavigator", null, IWorkbenchPage.VIEW_ACTIVATE); + + if (viewPart != null && viewPart instanceof ResourceNavigator) { + ResourceNavigator resourceNavigator = (ResourceNavigator) viewPart; + StructuredSelection ss = new StructuredSelection(file); + resourceNavigator.selectReveal(ss); + return true; + } + } catch (PartInitException ex) { + ex.printStackTrace(); + } + + return false; + } + + public static boolean openEditor(String filename) { + IFile iFile = AWorkspace.getIFile(filename); + return openEditor(iFile); + } + + public static boolean openEditor(IFile iFile) { + IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage(); + try { + IDE.openEditor(page, iFile, true); + } catch (PartInitException e) { + e.printStackTrace(); + return false; + } + return true; + } + + public static boolean showInPackageExplorer(IFile file) { + if (file == null) return false; + IViewPart p = + PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().findView( + "org.eclipse.jdt.ui.PackageExplorer"); + if (p != null && p instanceof IPackagesViewPart) { + StructuredSelection ss = new StructuredSelection(file); + IPackagesViewPart rn = (IPackagesViewPart) p; + rn.selectAndReveal(ss); + } + return true; + } + + public static void refreshResource(IResource resource) { + IResource parentResource = resource.getParent(); + try { + parentResource.refreshLocal(IResource.DEPTH_INFINITE, null); + } catch (org.eclipse.core.runtime.CoreException ex) { + MessageDialog.openInformation(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), + "Refresh Navigator", "Can't refresh \"" + resource.getName() + "\"\n\nYou must refresh Manually"); + return; + } + + } + + public static StructuredSelection getSelection() { + IViewReference[] parts = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getViewReferences(); + for (int i = 0; i < parts.length; i++) { + StructuredSelection sel = getSelection(parts[i].getPart(false)); + if (sel != null) return sel; + } + return null; + } + + public static StructuredSelection getSelection(IWorkbenchPart targetPart) { + if (targetPart instanceof IResourceNavigator) { + IResourceNavigator navigator = (IResourceNavigator) targetPart; + return (StructuredSelection) navigator.getViewer().getSelection(); + } else if (targetPart instanceof IPackagesViewPart) { + IPackagesViewPart navigator = (IPackagesViewPart) targetPart; + return (StructuredSelection) navigator.getTreeViewer().getSelection(); + } + return null; + } + + /** + * @return IResource arraylist + */ + public static ArrayList<IResource> getSelectedResources() { + ArrayList<IResource> l = new ArrayList<IResource>(); + StructuredSelection sel = getSelection(); + Iterator<?> i = sel.iterator(); + while (i.hasNext()) { + IResource resource = (IResource) i.next(); + l.add(resource); + } + return l; + } + + // public static File findWorkspaceFile(String fileName, String filePathHint) throws IOException + // { + // File file = fileFindMap.get(fileName); + // if(file == null || !file.exists()){ + // File workspace = new File(AWorkspace.getWorkspacePath()); + // List files = Lib.recursivelyListFiles(workspace, Pattern.compile(fileName)); + // if(files.size() == 0){ + // throw new IOException("we didn't find the file in the workspace"); + // } else if (files.size() > 1){ + // + // DialogSelectionHelper selection = new DialogSelectionHelper(files.toArray()); + // + // Display.getDefault().syncExec(selection); + // + // if(selection.getSelectionIndex() == -1){ + // String message = "we found multiple matches"; + // for(int i = 0; i < files.size(); i++){ + // message += "\n" + files.get(i); + // } + // throw new IOException(message); + // } else { + // if(selection.isSaveSelection()){ + // fileFindMap.put(fileName, (File)files.get(selection.getSelectionIndex())); + // } + // return (File)files.get(selection.getSelectionIndex()); + // } + // } else { + // file = (File)files.get(0); + // fileFindMap.put(fileName, file); + // } + // } + // return file; + // } + /** + * Return workspace file give workspace relative path and file. eg ".metadata/.log" + */ + public static File getWorkspaceFile(String wsPathFileName) throws IOException { + return new File(getWorkspacePath() + "\\" + wsPathFileName); + } + + public static File findWorkspaceFileNew(final String fileName) throws IOException { + File file = fileFindMap.get(fileName); + if (file != null) { + return file; + } + List<File> files = fileSearch.get(fileName); + if (files != null) { + if (files.size() == 1) { + return files.get(0); + } else if (files.size() > 0) { + DialogSelectionHelper selection = new DialogSelectionHelper(files.toArray()); + + Display.getDefault().syncExec(selection); + + if (selection.getSelectionIndex() == -1) { + String message = "we found multiple matches"; + for (int i = 0; i < files.size(); i++) { + message += "\n" + files.get(i); + } + throw new IOException(message); + } else { + if (selection.isSaveSelection()) { + fileFindMap.put(fileName, (File) files.get(selection.getSelectionIndex())); + } + return (File) files.get(selection.getSelectionIndex()); + } + } + } + // Display.getDefault().asyncExec(new Runnable() { + // public void run() { + // if + // (MessageDialog.openQuestion(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), + // "Open Error", "Can't find \"" + fileName + // + "\" in workspace. Would you like to re-initialize the search structure, it will be + // performed in the background and could take several minutes?")) { + // reinit(); + // } + // } + // }); + return null; + } + + public static File findWorkspaceFile(String fileName, String filePathHint) throws IOException { + File file = fileFindMap.get(fileName); + if (file == null || !file.exists()) { + List<File> files = null; + if (filePathHint != null) { + files = Lib.recursivelyListFiles(new File(filePathHint), Pattern.compile(fileName)); + } + if (files == null || files.size() == 0) { + files = Lib.recursivelyListFiles(new File(AWorkspace.getWorkspacePath()), Pattern.compile(fileName)); + } + if (files.size() == 0) { + throw new IOException("we didn't find the file [" + fileName + "] in the workspace"); + } else if (files.size() > 1) { + + DialogSelectionHelper selection = new DialogSelectionHelper(files.toArray()); + + Display.getDefault().syncExec(selection); + + if (selection.getSelectionIndex() == -1) { + String message = "we found multiple matches"; + for (int i = 0; i < files.size(); i++) { + message += "\n" + files.get(i); + } + throw new IOException(message); + } else { + if (selection.isSaveSelection()) { + fileFindMap.put(fileName, (File) files.get(selection.getSelectionIndex())); + } + return (File) files.get(selection.getSelectionIndex()); + } + } else { + file = (File) files.get(0); + fileFindMap.put(fileName, file); + } + } + return file; + } + + public static IResource findWorkspaceFile(String fileName) throws IOException { + IContainer ws = ResourcesPlugin.getWorkspace().getRoot(); + List<IResource> resources = new ArrayList<IResource>(); + recursiveFileFind(fileName, ws, resources); + for (IResource resource : resources) { + System.out.println("found a file " + resource.getName()); + } + if (resources.size() > 0) { + return resources.get(0); + } + return null; + } + + public static void recursiveFileFind(String fileName, IResource resource, List<IResource> matches) { + if (resource.getName().equalsIgnoreCase(fileName)) { + matches.add(resource); + } + if (resource instanceof IContainer) { + try { + for (IResource res : ((IContainer) resource).members()) { + recursiveFileFind(fileName, res, matches); + } + } catch (CoreException ex) { + } + } + } + + public static List<IResource> findWorkspaceFileMatch(String regex) throws IOException { + IContainer ws = ResourcesPlugin.getWorkspace().getRoot(); + List<IResource> resources = new ArrayList<IResource>(); + recursiveFileFindMatch(regex, ws, resources); + return resources; + } + + public static void recursiveFileFindMatch(String regex, IResource resource, List<IResource> matches) { + if (IResource.FILE == resource.getType() && resource.getName().length() > 0) { + if (resource.getName().matches(regex)) { + matches.add(resource); + } + } + if (resource instanceof IContainer) { + try { + for (IResource res : ((IContainer) resource).members()) { + recursiveFileFindMatch(regex, res, matches); + } + } catch (CoreException ex) { + } + } + } + +}
\ No newline at end of file diff --git a/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/util/AbstractSelectionEnabledHandler.java b/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/util/AbstractSelectionEnabledHandler.java new file mode 100644 index 00000000000..6ea36bfb056 --- /dev/null +++ b/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/util/AbstractSelectionEnabledHandler.java @@ -0,0 +1,37 @@ +/******************************************************************************* + * Copyright (c) 2004, 2007 Boeing. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Boeing - initial API and implementation + *******************************************************************************/ +package org.eclipse.osee.framework.ui.plugin.util; + +import org.eclipse.core.commands.AbstractHandler; +import org.eclipse.core.commands.HandlerEvent; +import org.eclipse.jface.action.MenuManager; +import org.eclipse.swt.events.MenuEvent; +import org.eclipse.swt.events.MenuListener; + +/** + * A Handler that will fire an enabled changed event each time the menu is shown. + * + * @author Robert A. Fisher + */ +public abstract class AbstractSelectionEnabledHandler extends AbstractHandler implements MenuListener { + private final HandlerEvent enabledChangedEvent = new HandlerEvent(this, true, false); + + public AbstractSelectionEnabledHandler(MenuManager menuManager) { + menuManager.getMenu().addMenuListener(this); + } + + public final void menuHidden(MenuEvent e) { + } + + public final void menuShown(MenuEvent e) { + fireHandlerChanged(enabledChangedEvent); + } +} diff --git a/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/util/ArrayTreeContentProvider.java b/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/util/ArrayTreeContentProvider.java new file mode 100644 index 00000000000..266765a2931 --- /dev/null +++ b/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/util/ArrayTreeContentProvider.java @@ -0,0 +1,84 @@ +/******************************************************************************* + * Copyright (c) 2004, 2007 Boeing. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Boeing - initial API and implementation + *******************************************************************************/ +package org.eclipse.osee.framework.ui.plugin.util; + +import java.util.Collection; +import org.eclipse.jface.viewers.ITreeContentProvider; +import org.eclipse.jface.viewers.Viewer; + +/** + * @author Donald G. Dunne + */ +public class ArrayTreeContentProvider implements ITreeContentProvider { + + /** + * + */ + public ArrayTreeContentProvider() { + super(); + } + + /* + * (non-Javadoc) + * + * @see org.eclipse.jface.viewers.ITreeContentProvider#getChildren(java.lang.Object) + */ + @SuppressWarnings("unchecked") + public Object[] getChildren(Object parentElement) { + if (parentElement instanceof Collection) return ((Collection) parentElement).toArray(); + return new Object[] {}; + } + + /* + * (non-Javadoc) + * + * @see org.eclipse.jface.viewers.ITreeContentProvider#getParent(java.lang.Object) + */ + public Object getParent(Object element) { + return null; + } + + /* + * (non-Javadoc) + * + * @see org.eclipse.jface.viewers.ITreeContentProvider#hasChildren(java.lang.Object) + */ + public boolean hasChildren(Object element) { + return false; + } + + /* + * (non-Javadoc) + * + * @see org.eclipse.jface.viewers.IStructuredContentProvider#getElements(java.lang.Object) + */ + public Object[] getElements(Object inputElement) { + return getChildren(inputElement); + } + + /* + * (non-Javadoc) + * + * @see org.eclipse.jface.viewers.IContentProvider#dispose() + */ + public void dispose() { + } + + /* + * (non-Javadoc) + * + * @see org.eclipse.jface.viewers.IContentProvider#inputChanged(org.eclipse.jface.viewers.Viewer, + * java.lang.Object, java.lang.Object) + */ + public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { + } + +} diff --git a/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/util/CancelWatcher.java b/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/util/CancelWatcher.java new file mode 100644 index 00000000000..04fa3790af8 --- /dev/null +++ b/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/util/CancelWatcher.java @@ -0,0 +1,67 @@ +/******************************************************************************* + * Copyright (c) 2004, 2007 Boeing. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Boeing - initial API and implementation + *******************************************************************************/ +package org.eclipse.osee.framework.ui.plugin.util; + +import org.eclipse.core.runtime.IProgressMonitor; + +/** + * @author Robert A. Fisher + */ +public class CancelWatcher extends Thread { + private final Thread thread; + private final IProgressMonitor monitor; + private boolean done; + private boolean cancelled; + + /** + * @param thread + * @param monitor + */ + public CancelWatcher(Thread thread, IProgressMonitor monitor) { + super(); + this.thread = thread; + this.monitor = monitor; + this.done = false; + this.cancelled = false; + + setDaemon(true); + } + + /* (non-Javadoc) + * @see java.lang.Thread#run() + */ + @Override + public void run() { + while (!done) { + try { + sleep(500); + } catch (InterruptedException e) { + done = true; + } + if (monitor.isCanceled()) { + cancelled = true; + done = true; + thread.interrupt(); + } + } + } + + public void done() { + done = true; + } + + /** + * @return Returns the cancelled. + */ + public boolean isCancelled() { + return cancelled; + } +} diff --git a/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/util/Commands.java b/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/util/Commands.java new file mode 100644 index 00000000000..8958d9e1b59 --- /dev/null +++ b/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/util/Commands.java @@ -0,0 +1,91 @@ +/*******************************************************************************
+ * Copyright (c) 2004, 2007 Boeing.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Boeing - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.osee.framework.ui.plugin.util;
+
+import java.util.Map;
+import org.eclipse.core.commands.Category;
+import org.eclipse.core.commands.Command;
+import org.eclipse.core.commands.CommandManager;
+import org.eclipse.core.commands.IParameter;
+import org.eclipse.jface.resource.ImageDescriptor;
+import org.eclipse.ui.IWorkbenchPartSite;
+import org.eclipse.ui.IWorkbenchSite;
+import org.eclipse.ui.commands.ICommandService;
+import org.eclipse.ui.menus.CommandContributionItem;
+import org.eclipse.ui.services.IServiceLocator;
+
+/**
+ * @author Robert A. Fisher
+ */
+public final class Commands {
+
+ // This is a utility class and should not ever be instantiated
+ private Commands() {
+ }
+
+ /**
+ * Sets up a local command with no id and uses that to retrieve a CommandContributionItem.
+ *
+ * @param site may not be null
+ * @param shortCommandId may not be null
+ * @param name may not be null
+ * @param parameterDefs may be null
+ * @param parameters may be null
+ * @param image may be null
+ * @param mnemonic may be null
+ * @param tooltip may be null
+ * @param helpContextId may be null
+ * @return
+ */
+ public static CommandContributionItem getLocalCommandContribution(IWorkbenchPartSite site, String shortCommandId, String name, IParameter[] parameterDefs, Map<String, String> parameters, ImageDescriptor image, String mnemonic, String tooltip, String helpContextId) {
+ return createCommandContributionItem(site, site.getId(), shortCommandId, name, parameterDefs, parameters, image,
+ mnemonic, tooltip, helpContextId);
+ }
+
+ /**
+ * Sets up a local command with no id and uses that to retrieve a CommandContributionItem.
+ *
+ * @param site may not be null
+ * @param id may not be null
+ * @param shortCommandId may not be null
+ * @param name may not be null
+ * @param parameterDefs may be null
+ * @param parameters may be null
+ * @param image may be null
+ * @param mnemonic may be null
+ * @param tooltip may be null
+ * @param helpContextId may be null
+ * @return
+ */
+ public static CommandContributionItem getLocalCommandContribution(String id, IWorkbenchSite site, String shortCommandId, String name, IParameter[] parameterDefs, Map<String, String> parameters, ImageDescriptor image, String mnemonic, String tooltip, String helpContextId) {
+ return createCommandContributionItem(site, id, shortCommandId, name, parameterDefs, parameters, image, mnemonic,
+ tooltip, helpContextId);
+ }
+
+ private static CommandContributionItem createCommandContributionItem(IServiceLocator site, String id, String shortCommandId, String name, IParameter[] parameterDefs, Map<String, String> parameters, ImageDescriptor image, String mnemonic, String tooltip, String helpContextId) {
+ ICommandService commandService = (ICommandService) site.getService(ICommandService.class);
+ String commandId = id;
+
+ if (shortCommandId != null) {
+ commandId = commandId + "." + shortCommandId;
+ }
+
+ Command command = commandService.getCommand(commandId);
+ if (!command.isDefined()) {
+ Category category = commandService.getCategory(CommandManager.AUTOGENERATED_CATEGORY_ID);
+ command.define(name, null, category, parameterDefs, null, helpContextId);
+ }
+
+ // Use the commandId as the id so calling code can get to the commandId
+ return new CommandContributionItem(site, command.getId(), command.getId(), parameters, image, null, null, name,
+ mnemonic, tooltip, CommandContributionItem.STYLE_PUSH);
+ }
+}
diff --git a/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/util/CoreDebug.java b/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/util/CoreDebug.java new file mode 100644 index 00000000000..ac83b3acde9 --- /dev/null +++ b/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/util/CoreDebug.java @@ -0,0 +1,43 @@ +/******************************************************************************* + * Copyright (c) 2004, 2007 Boeing. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Boeing - initial API and implementation + *******************************************************************************/ +package org.eclipse.osee.framework.ui.plugin.util; + +/** + * @author Donald G. Dunne + */ +public class CoreDebug extends Debug { + + /* (non-Javadoc) + * @see org.eclipse.osee.framework.ui.plugin.util.Debug#getPluginName() + */ + @Override + protected String getPluginName() { + return "org.eclipse.osee.framework.ui.plugin"; + } + + /** + * @param debugOn + * @param timeStampOn + * @param nameSpace + */ + public CoreDebug(boolean debugOn, boolean timeStampOn, String nameSpace) { + super(debugOn, timeStampOn, nameSpace); + } + + /** + * @param debugOn + * @param nameSpace + */ + public CoreDebug(boolean debugOn, String nameSpace) { + super(debugOn, nameSpace); + } + +} diff --git a/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/util/Debug.java b/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/util/Debug.java new file mode 100644 index 00000000000..f0c989de41b --- /dev/null +++ b/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/util/Debug.java @@ -0,0 +1,265 @@ +/******************************************************************************* + * Copyright (c) 2004, 2007 Boeing. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Boeing - initial API and implementation + *******************************************************************************/ +package org.eclipse.osee.framework.ui.plugin.util; + +import java.io.IOException; +import java.io.OutputStream; +import java.io.PrintStream; +import java.io.RandomAccessFile; +import java.text.SimpleDateFormat; +import java.util.Calendar; +import java.util.Date; +import java.util.HashMap; +import java.util.Map; +import org.eclipse.osee.framework.jdk.core.util.Lib; +import org.eclipse.swt.SWT; +import org.eclipse.swt.widgets.Display; + +/** + * Debug abstract class allows each plugin to subclass off a Debug class for the use by its own classes. Each plugin can + * (and should) have an easter-egg way to turn on global debugging from the UI. This class allows each plugin to have + * it's own Console window show only it's debug statments. Once subclassed in a plugin (standard is to simply use the + * subclass "Debug" in the plugin), each class can instantiate a debug object to send debug to standard out normally or + * to the Console if activate through the UI. + * + * @author Donald G. Dunne + */ +public abstract class Debug { + + // True = debug everything for this instance of debug + // False = don't debug unless globalDebug is set + boolean debugOn = false; + // Show timestamp with debug statement (eg: 12:12 This is debug) + boolean timeStampOn = false; + // Show (x) instance tag with statment (eg: StrView(4) This is) + boolean displayInstanceTag = true; + private static Map<String, Integer> instanceNumHash = new HashMap<String, Integer>(); // pluginName, + // int + private int thisInstanceNum = 0; + // Namespace to give debug instance (eg: <namespace> this is) + private String nameSpace = ""; + // True = everything debugs + // False = only Debug(true, ..) debugs + private static Map<String, Boolean> globalDebugHash = new HashMap<String, Boolean>(); // pluginName, + // boolean + private static Map<String, OseeConsole> oseeConsoleHash = new HashMap<String, OseeConsole>(); // pluginName, + // OseeConsole + private PrintStream out; + // Color of debug in console window + private int currentColor = SWT.COLOR_GREEN; + + // Return the plugin name to use in the console debug window + protected abstract String getPluginName(); + + protected int getNextInstanceNum() { + if (!instanceNumHash.containsKey(getPluginName())) { + setInstanceNum(1); + return 1; + } + return instanceNumHash.get(getPluginName()).intValue(); + } + + protected void setInstanceNum(int num) { + instanceNumHash.put(getPluginName(), new Integer(num)); + } + + /** + * @return true if globalDebug flag is on for this plugin + */ + protected boolean isGlobalDebug() { + if (!globalDebugHash.containsKey(getPluginName())) { + return false; + } + return globalDebugHash.get(getPluginName()).booleanValue(); + } + + protected OseeConsole getConsole() { + if (!oseeConsoleHash.containsKey(getPluginName())) { + return null; + } + return oseeConsoleHash.get(getPluginName()); + } + + protected void setConsole(OseeConsole console) { + oseeConsoleHash.put(getPluginName(), console); + } + + /** + * Call to turn global debug on/off. Successive calls switch the state. + */ + public void setGlobalDebug() { + // All this to simply change from false to true or visa versa + globalDebugHash.put(getPluginName(), new Boolean(!isGlobalDebug())); + String debugOnStr = "Debug == " + ((isGlobalDebug()) ? "On" : "Off"); + System.out.println(debugOnStr); + if (getConsole() == null) { + setConsole(new OseeConsole(getPluginName() + " Debug Console")); + } + if (getConsole() != null) { + OseeConsole console = (OseeConsole) getConsole(); + console.writeError(debugOnStr); + } + } + + public Debug(boolean debugOn, boolean timeStampOn, String nameSpace) { + this(debugOn, nameSpace); + this.timeStampOn = timeStampOn; + } + + public Debug(boolean debugOn, String nameSpace) { + thisInstanceNum = getNextInstanceNum(); + this.debugOn = debugOn; + this.nameSpace = nameSpace; + globalDebugHash.put(getPluginName(), false); + } + + /** + * Display (x) where x is # of instantiation of debug + * + * @param set + */ + public void setInstanceTag(boolean set) { + displayInstanceTag = set; + } + + /** + * Report debug + * + * @param str = string to display + */ + public void report(String str) { + report(str, currentColor); + } + + public void report(String str, Throwable ex) { + report(str + "\nException: " + Lib.exceptionToString(ex), currentColor); + } + + public void report(String str, boolean showTimestamp) { + if (showTimestamp) + report(str + " " + (new SimpleDateFormat("hh:mm:ss")).format(new Date())); + else + report(str); + + } + + /** + * Report debug in SWT.COLOR + * + * @param str + * @param color + */ + public void report(String str, int color) { + if (!debugOn && !isGlobalDebug()) return; + String timeStr = "", nameStr = ""; + if (timeStampOn) { + Calendar cal = Calendar.getInstance(); + cal.setTime(new Date()); + timeStr = + "(" + cal.get(Calendar.HOUR) + ":" + cal.get(Calendar.MINUTE) + ":" + cal.get(Calendar.SECOND) + ") "; + } + if (!nameSpace.equals("")) { + String instStr = ""; + if (displayInstanceTag) { + instStr = "(" + thisInstanceNum + ")"; + } + nameStr = nameSpace + instStr + " => "; + } + String dispStr = timeStr + nameStr + str; + + if (isGlobalDebug() && getConsole() != null) { + Display.getCurrent().getSystemColor(color); + ((OseeConsole) getConsole()).write(dispStr); + } else + System.out.println(dispStr); + if (out != null) out.println(dispStr); + } + + /** + * Set debug on for this instance of Debug + * + * @param debug + */ + public void setDebug(boolean debug) { + this.debugOn = debug; + } + + /** + * Is debug on for this instance of Debug + * + * @return boolean + */ + public boolean isDebug() { + return debugOn; + } + + /** + * @param timeStampOn The timeStampOn to set. + */ + public void setTimeStampOn(boolean timeStampOn) { + this.timeStampOn = timeStampOn; + } + + /** + * @return Returns the nameSpace. + */ + public String getNameSpace() { + return nameSpace; + } + + /** + * @param nameSpace The nameSpace to set. When print debug, will be namespace => <debug string> + */ + public void setNameSpace(String nameSpace) { + this.nameSpace = nameSpace; + } + + /** + * @param swtColor + */ + public void setColor(int swtColor) { + currentColor = swtColor; + } + + public void setFileOutput(String filename) { + try { + out = new PrintStream(new AppendFileStream(filename)); + report("Output being sent to file " + filename); + } catch (IOException ex) { + ex.printStackTrace(); + } + } + + class AppendFileStream extends OutputStream { + RandomAccessFile fd; + + public AppendFileStream(String file) throws IOException { + fd = new RandomAccessFile(file, "rw"); + fd.seek(fd.length()); + } + + public void close() throws IOException { + fd.close(); + } + + public void write(byte[] b) throws IOException { + fd.write(b); + } + + public void write(byte[] b, int off, int len) throws IOException { + fd.write(b, off, len); + } + + public void write(int b) throws IOException { + fd.write(b); + } + } +}
\ No newline at end of file diff --git a/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/util/DialogSelectionHelper.java b/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/util/DialogSelectionHelper.java new file mode 100644 index 00000000000..f72bd955455 --- /dev/null +++ b/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/util/DialogSelectionHelper.java @@ -0,0 +1,49 @@ +/******************************************************************************* + * Copyright (c) 2004, 2007 Boeing. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Boeing - initial API and implementation + *******************************************************************************/ +package org.eclipse.osee.framework.ui.plugin.util; + +public class DialogSelectionHelper implements Runnable { + + private int selection = -1; + private boolean saveSelection; + private Object[] availableSelections; + + public DialogSelectionHelper(Object[] availableSelections) { + this.availableSelections = availableSelections; + } + + public DialogSelectionHelper(Object[] availableSelections, String msg) { + this.availableSelections = availableSelections; + } + + public void run() { + ListSelectionDialog dlg = + new ListSelectionDialog(availableSelections, null, "File Selection", null, "String dialogMessage", 3, + new String[] {"OK", "Cancel"}, 0); + + int result = dlg.open(); + if (result == 0) { + selection = dlg.getSelection(); + saveSelection = dlg.saveSelection(); + } + } + + public int getSelectionIndex() { + return selection; + } + + /** + * @return Returns the saveSelection. + */ + public boolean isSaveSelection() { + return saveSelection; + } +} diff --git a/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/util/DirectoryOrFileSelector.java b/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/util/DirectoryOrFileSelector.java new file mode 100644 index 00000000000..871fc755b2a --- /dev/null +++ b/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/util/DirectoryOrFileSelector.java @@ -0,0 +1,181 @@ +/******************************************************************************* + * Copyright (c) 2004, 2007 Boeing. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Boeing - initial API and implementation + *******************************************************************************/ +package org.eclipse.osee.framework.ui.plugin.util; + +import java.io.File; +import org.eclipse.swt.SWT; +import org.eclipse.swt.events.SelectionAdapter; +import org.eclipse.swt.events.SelectionEvent; +import org.eclipse.swt.layout.GridData; +import org.eclipse.swt.layout.GridLayout; +import org.eclipse.swt.widgets.Button; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.DirectoryDialog; +import org.eclipse.swt.widgets.Event; +import org.eclipse.swt.widgets.FileDialog; +import org.eclipse.swt.widgets.Group; +import org.eclipse.swt.widgets.Listener; +import org.eclipse.swt.widgets.Text; +import org.eclipse.ui.dialogs.WizardDataTransferPage; + +/** + * @author Robert A. Fisher + */ +public class DirectoryOrFileSelector extends Composite implements Listener { + + private Button radDirectory; + private Button radSingleFile; + private Text txtDirectory; + private Text txtSingleFile; + private Button btnDirectory; + private Button btnSingleFile; + + /** + * @param parent + * @param style + */ + public DirectoryOrFileSelector(Composite parent, int style, String name, Listener listener) { + super(parent, style); + setLayout(new GridLayout()); + setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); + + Group composite = new Group(this, style); + composite.setText("Import Source"); + GridLayout gd = new GridLayout(); + gd.numColumns = 3; + composite.setLayout(gd); + composite.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); + + radDirectory = new Button(composite, SWT.RADIO); + radDirectory.setText("Directory:"); + radDirectory.addListener(SWT.Selection, this); + radDirectory.addListener(SWT.Selection, listener); + txtDirectory = new Text(composite, SWT.SINGLE | SWT.BORDER); + txtDirectory.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); + txtDirectory.addListener(SWT.Modify, this); + txtDirectory.addListener(SWT.Modify, listener); + btnDirectory = new Button(composite, SWT.PUSH); + btnDirectory.setText("&Browse..."); + btnDirectory.addSelectionListener(new SelectionAdapter() { + + /* (non-Javadoc) + * @see org.eclipse.swt.events.SelectionAdapter#widgetSelected(org.eclipse.swt.events.SelectionEvent) + */ + @Override + public void widgetSelected(SelectionEvent e) { + File directory = selectDirectory(); + if (directory != null && directory.isDirectory()) txtDirectory.setText(directory.getPath()); + } + + }); + + radSingleFile = new Button(composite, SWT.RADIO); + radSingleFile.setText("File:"); + radSingleFile.addListener(SWT.Selection, this); + radSingleFile.addListener(SWT.Selection, listener); + txtSingleFile = new Text(composite, SWT.SINGLE | SWT.BORDER); + txtSingleFile.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); + txtSingleFile.addListener(SWT.Modify, this); + txtSingleFile.addListener(SWT.Modify, listener); + btnSingleFile = new Button(composite, SWT.PUSH); + btnSingleFile.setText("&Browse..."); + btnSingleFile.addSelectionListener(new SelectionAdapter() { + + /* (non-Javadoc) + * @see org.eclipse.swt.events.SelectionAdapter#widgetSelected(org.eclipse.swt.events.SelectionEvent) + */ + @Override + public void widgetSelected(SelectionEvent e) { + File file = selectFile(); + if (file != null && file.isFile()) txtSingleFile.setText(file.getPath()); + } + + }); + } + + private void updateWidgetEnablements() { + boolean directorySelected = radDirectory.getSelection(); + + txtDirectory.setEnabled(directorySelected); + btnDirectory.setEnabled(directorySelected); + + txtSingleFile.setEnabled(!directorySelected); + btnSingleFile.setEnabled(!directorySelected); + } + + public File getFile() { + File file; + if (isDirectorySelected()) { + file = new File(txtDirectory.getText()); + } else { + file = new File(txtSingleFile.getText()); + } + + return file; + } + + public String getText() { + return (isDirectorySelected() ? txtDirectory : txtSingleFile).getText(); + } + + public boolean isDirectorySelected() { + return radDirectory.getSelection(); + } + + public void setDirectorySelected(boolean selected) { + radDirectory.setSelection(selected); + radSingleFile.setSelection(!selected); + + updateWidgetEnablements(); + } + + public void setText(String text) { + (isDirectorySelected() ? txtDirectory : txtSingleFile).setText(text); + } + + public boolean validate(WizardDataTransferPage wizardPage) { + if ((isDirectorySelected() && getFile().isDirectory()) || (!isDirectorySelected() && getFile().isFile())) return true; + + wizardPage.setErrorMessage(getText() + " is not a " + (isDirectorySelected() ? "directory" : "file")); + return false; + } + + private File selectFile() { + FileDialog dialog = new FileDialog(getShell(), SWT.OPEN | SWT.SINGLE); + dialog.setFilterExtensions(new String[] {"*.xml"}); + dialog.setFilterPath(AWorkspace.getWorkspacePath()); + + String path = dialog.open(); + + if (path != null) { + return new File(path); + } else { + return null; + } + } + + private File selectDirectory() { + DirectoryDialog dialog = new DirectoryDialog(getShell(), SWT.OPEN); + dialog.setFilterPath(AWorkspace.getWorkspacePath()); + + String path = dialog.open(); + + if (path != null) { + return new File(path); + } else { + return null; + } + } + + public void handleEvent(Event event) { + updateWidgetEnablements(); + } +} diff --git a/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/util/Displays.java b/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/util/Displays.java new file mode 100644 index 00000000000..e3a52745e73 --- /dev/null +++ b/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/util/Displays.java @@ -0,0 +1,42 @@ +/******************************************************************************* + * Copyright (c) 2004, 2007 Boeing. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Boeing - initial API and implementation + *******************************************************************************/ +package org.eclipse.osee.framework.ui.plugin.util; + +import org.eclipse.swt.widgets.Display; + +/** + * @author Robert A. Fisher + */ +public class Displays { + + public static void ensureInDisplayThread(Runnable runnable) { + ensureInDisplayThread(runnable, false); + } + + public static void ensureInDisplayThread(Runnable runnable, boolean forcePend) { + if (isDisplayThread()) { + // No need to check for force since this will always pend + runnable.run(); + } else { + if (forcePend) { + Display.getDefault().syncExec(runnable); + } else { + Display.getDefault().asyncExec(runnable); + } + } + } + + public static boolean isDisplayThread() { + if (Display.getCurrent() == null) return false; + + return Display.getCurrent().getThread() == Thread.currentThread(); + } +} diff --git a/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/util/EnumStringMultiSelectionDialog.java b/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/util/EnumStringMultiSelectionDialog.java new file mode 100644 index 00000000000..7c9d2d53138 --- /dev/null +++ b/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/util/EnumStringMultiSelectionDialog.java @@ -0,0 +1,113 @@ +/******************************************************************************* + * Copyright (c) 2004, 2007 Boeing. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Boeing - initial API and implementation + *******************************************************************************/ +package org.eclipse.osee.framework.ui.plugin.util; + +import java.util.Collection; +import org.eclipse.swt.SWT; +import org.eclipse.swt.events.SelectionAdapter; +import org.eclipse.swt.events.SelectionEvent; +import org.eclipse.swt.layout.GridLayout; +import org.eclipse.swt.widgets.Button; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Control; +import org.eclipse.swt.widgets.Display; +import org.eclipse.swt.widgets.Label; +import org.eclipse.ui.dialogs.CheckedTreeSelectionDialog; + +/** + * @author Donald G. Dunne + */ +public class EnumStringMultiSelectionDialog extends CheckedTreeSelectionDialog { + + private Button addSelectedRadioButton; + private Button replaceAllRadioButton; + private Button deleteSelectedRadioButton; + public static enum Selection { + AddSelection, ReplaceAll, DeleteSelected + }; + private Selection selected = Selection.AddSelection; + + /** + * @param parent + * @param artifacts + */ + public EnumStringMultiSelectionDialog(String displayName, Collection<String> enums, Collection<String> selEnums) { + super(Display.getCurrent().getActiveShell(), new StringLabelProvider(), new ArrayTreeContentProvider()); + setTitle("Select " + displayName); + setMessage("Select " + displayName + " to add, delete or replace."); + setInput(enums); + setComparator(new StringViewerSorter()); + setInitialSelections(selEnums.toArray()); + } + + @Override + protected Control createDialogArea(Composite container) { + Control c = super.createDialogArea(container); + + Composite comp = new Composite(container, SWT.NONE); + comp.setLayout(new GridLayout(2, false)); + + (new Label(comp, SWT.None)).setText("Add selected item(s) to existing if not already chosen."); + + addSelectedRadioButton = new Button(comp, SWT.CHECK); + addSelectedRadioButton.setSelection(true); + addSelectedRadioButton.addSelectionListener(new SelectionAdapter() { + /* + * (non-Javadoc) + * + * @see org.eclipse.swt.events.SelectionAdapter#widgetSelected(org.eclipse.swt.events.SelectionEvent) + */ + @Override + public void widgetSelected(SelectionEvent e) { + super.widgetSelected(e); + if (addSelectedRadioButton.getSelection()) selected = Selection.AddSelection; + } + }); + + (new Label(comp, SWT.None)).setText("Replace all existing with selected item(s)."); + + replaceAllRadioButton = new Button(comp, SWT.CHECK); + replaceAllRadioButton.addSelectionListener(new SelectionAdapter() { + /* + * (non-Javadoc) + * + * @see org.eclipse.swt.events.SelectionAdapter#widgetSelected(org.eclipse.swt.events.SelectionEvent) + */ + @Override + public void widgetSelected(SelectionEvent e) { + super.widgetSelected(e); + if (replaceAllRadioButton.getSelection()) selected = Selection.ReplaceAll; + } + }); + + (new Label(comp, SWT.None)).setText("Remove selected item(s) if already chosen."); + + deleteSelectedRadioButton = new Button(comp, SWT.CHECK); + deleteSelectedRadioButton.addSelectionListener(new SelectionAdapter() { + /* + * (non-Javadoc) + * + * @see org.eclipse.swt.events.SelectionAdapter#widgetSelected(org.eclipse.swt.events.SelectionEvent) + */ + @Override + public void widgetSelected(SelectionEvent e) { + super.widgetSelected(e); + if (deleteSelectedRadioButton.getSelection()) selected = Selection.DeleteSelected; + } + }); + return c; + } + + public Selection getSelected() { + return selected; + } + +} diff --git a/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/util/EnumStringSingleSelectionDialog.java b/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/util/EnumStringSingleSelectionDialog.java new file mode 100644 index 00000000000..d98aa435fc4 --- /dev/null +++ b/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/util/EnumStringSingleSelectionDialog.java @@ -0,0 +1,41 @@ +/******************************************************************************* + * Copyright (c) 2004, 2007 Boeing. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Boeing - initial API and implementation + *******************************************************************************/ +package org.eclipse.osee.framework.ui.plugin.util; + +import java.util.Collection; +import org.eclipse.jface.viewers.ArrayContentProvider; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Control; +import org.eclipse.swt.widgets.Display; + +/** + * @author Donald G. Dunne + */ +public class EnumStringSingleSelectionDialog extends org.eclipse.ui.dialogs.ListDialog { + + public EnumStringSingleSelectionDialog(String title, String message, Collection<String> options, String currSelected) { + super(Display.getCurrent().getActiveShell()); + this.setTitle(title); + this.setMessage(message); + this.setContentProvider(new ArrayContentProvider()); + setLabelProvider(new StringLabelProvider()); + setInput(options); + if (currSelected != null) setInitialSelections(new Object[] {currSelected}); + } + + @Override + protected Control createDialogArea(Composite container) { + Control c = super.createDialogArea(container); + getTableViewer().setSorter(new StringViewerSorter()); + return c; + } + +} diff --git a/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/util/FileSelector.java b/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/util/FileSelector.java new file mode 100644 index 00000000000..eba951a6d5d --- /dev/null +++ b/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/util/FileSelector.java @@ -0,0 +1,108 @@ +/******************************************************************************* + * Copyright (c) 2004, 2007 Boeing. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Boeing - initial API and implementation + *******************************************************************************/ +package org.eclipse.osee.framework.ui.plugin.util; + +import java.io.File; +import org.eclipse.swt.SWT; +import org.eclipse.swt.events.SelectionAdapter; +import org.eclipse.swt.events.SelectionEvent; +import org.eclipse.swt.layout.GridData; +import org.eclipse.swt.layout.GridLayout; +import org.eclipse.swt.widgets.Button; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.FileDialog; +import org.eclipse.swt.widgets.Group; +import org.eclipse.swt.widgets.Label; +import org.eclipse.swt.widgets.Listener; +import org.eclipse.swt.widgets.Text; +import org.eclipse.ui.dialogs.WizardDataTransferPage; + +/** + * @author Robert A. Fisher + */ +public class FileSelector extends Composite { + + private Label radSingleFile; + private Text txtSingleFile; + private Button btnSingleFile; + + /** + * @param parent + * @param style + */ + public FileSelector(Composite parent, int style, String name, Listener listener) { + super(parent, style); + setLayout(new GridLayout()); + setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); + + Group composite = new Group(this, style); + composite.setText(name); + GridLayout gd = new GridLayout(); + gd.numColumns = 3; + composite.setLayout(gd); + composite.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); + + radSingleFile = new Label(composite, SWT.NONE); + radSingleFile.setText("File:"); + txtSingleFile = new Text(composite, SWT.SINGLE | SWT.BORDER); + txtSingleFile.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); + txtSingleFile.addListener(SWT.Modify, listener); + btnSingleFile = new Button(composite, SWT.PUSH); + btnSingleFile.setText("&Browse..."); + btnSingleFile.addSelectionListener(new SelectionAdapter() { + + /* (non-Javadoc) + * @see org.eclipse.swt.events.SelectionAdapter#widgetSelected(org.eclipse.swt.events.SelectionEvent) + */ + @Override + public void widgetSelected(SelectionEvent e) { + File file = selectFile(); + if (file != null && file.isFile()) txtSingleFile.setText(file.getPath()); + } + + }); + } + + public File getFile() { + File file = new File(txtSingleFile.getText()); + return file; + } + + public String getText() { + return txtSingleFile.getText(); + } + + public void setText(String text) { + txtSingleFile.setText(text); + } + + public boolean validate(WizardDataTransferPage wizardPage) { + if (getText().endsWith(".xml") && getFile().isFile()) return true; + + wizardPage.setErrorMessage("File is not a valid xml file"); + return false; + } + + private File selectFile() { + FileDialog dialog = new FileDialog(getShell(), SWT.OPEN | SWT.SINGLE); + dialog.setFilterExtensions(new String[] {"*.xml"}); + dialog.setFilterPath(AWorkspace.getWorkspacePath()); + + String path = dialog.open(); + + if (path != null) { + return new File(path); + } else { + return null; + } + } + +} diff --git a/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/util/Files.java b/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/util/Files.java new file mode 100644 index 00000000000..3ba7b943976 --- /dev/null +++ b/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/util/Files.java @@ -0,0 +1,36 @@ +/******************************************************************************* + * Copyright (c) 2004, 2007 Boeing. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Boeing - initial API and implementation + *******************************************************************************/ +package org.eclipse.osee.framework.ui.plugin.util; + +import java.io.File; +import org.eclipse.swt.SWT; +import org.eclipse.swt.widgets.FileDialog; +import org.eclipse.swt.widgets.Shell; + +/** + * @author Robert A. Fisher + */ +public class Files { + + public static File selectFile(Shell shell, int swtType, String... extensions) { + FileDialog dialog = new FileDialog(shell, swtType | SWT.SINGLE); + dialog.setFilterExtensions(extensions); + dialog.setFilterPath(AWorkspace.getWorkspacePath()); + + String path = dialog.open(); + + if (path != null) { + return new File(path); + } else { + return null; + } + } +} diff --git a/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/util/GetChildrenJob.java b/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/util/GetChildrenJob.java new file mode 100644 index 00000000000..ad2e0ed5b6a --- /dev/null +++ b/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/util/GetChildrenJob.java @@ -0,0 +1,78 @@ +/******************************************************************************* + * Copyright (c) 2004, 2007 Boeing. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Boeing - initial API and implementation + *******************************************************************************/ +package org.eclipse.osee.framework.ui.plugin.util; + +import java.util.logging.Level; +import java.util.logging.Logger; +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.core.runtime.IStatus; +import org.eclipse.core.runtime.Status; +import org.eclipse.core.runtime.jobs.Job; +import org.eclipse.jface.viewers.Viewer; +import org.eclipse.osee.framework.plugin.core.config.ConfigUtil; +import org.eclipse.osee.framework.ui.swt.IContentProviderRunnable; + +/** + * @author Robert A. Fisher + */ +public class GetChildrenJob extends Job { + private static final Logger logger = ConfigUtil.getConfigFactory().getLogger(GetChildrenJob.class); + + private final Viewer viewer; + private final JobbedNode parent; + private final IContentProviderRunnable runnable; + + /** + * @param name + * @param viewer + * @param parent + * @param runnable + */ + public GetChildrenJob(String name, Viewer viewer, JobbedNode parent, IContentProviderRunnable runnable) { + super("Fetching children" + (name == null ? "" : " for " + name)); + if (viewer == null) throw new IllegalArgumentException("view can not be null"); + if (parent == null) throw new IllegalArgumentException("parent can not be null."); + if (runnable == null) throw new IllegalArgumentException("runnable can not be null."); + + this.viewer = viewer; + this.parent = parent; + this.runnable = runnable; + } + + @Override + protected final IStatus run(IProgressMonitor monitor) { + CancelWatcher watcher = new CancelWatcher(getThread(), monitor); + watcher.start(); + try { + Object[] children = runnable.run(parent.getBackingData()); + + if (!monitor.isCanceled()) { + parent.setChildren(children); + + Displays.ensureInDisplayThread(new Runnable() { + public void run() { + viewer.refresh(); + } + }); + } else { + parent.cancelled(); + } + } catch (Exception ex) { + logger.log(Level.SEVERE, ex.toString(), ex); + parent.cancelled(ex); + } finally { + watcher.done(); + monitor.done(); + } + + return Status.OK_STATUS; + } +} diff --git a/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/util/IExceptionableRunnable.java b/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/util/IExceptionableRunnable.java new file mode 100644 index 00000000000..005bd65d245 --- /dev/null +++ b/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/util/IExceptionableRunnable.java @@ -0,0 +1,22 @@ +/******************************************************************************* + * Copyright (c) 2004, 2007 Boeing. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Boeing - initial API and implementation + *******************************************************************************/ +package org.eclipse.osee.framework.ui.plugin.util; + +import org.eclipse.core.runtime.IProgressMonitor; + +/** + * @author Ryan D. Brooks + * @author Robert A. Fisher + */ +public interface IExceptionableRunnable { + + public void run(IProgressMonitor monitor) throws Exception; +} diff --git a/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/util/IShellCloseEvent.java b/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/util/IShellCloseEvent.java new file mode 100644 index 00000000000..ae472132b78 --- /dev/null +++ b/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/util/IShellCloseEvent.java @@ -0,0 +1,18 @@ +/******************************************************************************* + * Copyright (c) 2004, 2007 Boeing. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Boeing - initial API and implementation + *******************************************************************************/ +package org.eclipse.osee.framework.ui.plugin.util; + +/** + * @author Andrew M. Finkbeiner + */ +public interface IShellCloseEvent { + void onClose(); +} diff --git a/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/util/InputStreamImageDescriptor.java b/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/util/InputStreamImageDescriptor.java new file mode 100644 index 00000000000..68d42248905 --- /dev/null +++ b/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/util/InputStreamImageDescriptor.java @@ -0,0 +1,76 @@ +/******************************************************************************* + * Copyright (c) 2004, 2007 Boeing. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Boeing - initial API and implementation + *******************************************************************************/ +package org.eclipse.osee.framework.ui.plugin.util; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.InputStream; +import java.io.Serializable; +import java.util.logging.Level; +import java.util.logging.Logger; +import org.eclipse.jface.resource.ImageDescriptor; +import org.eclipse.osee.framework.jdk.core.util.io.Streams; +import org.eclipse.osee.framework.plugin.core.config.ConfigUtil; +import org.eclipse.swt.SWT; +import org.eclipse.swt.SWTException; +import org.eclipse.swt.graphics.Image; +import org.eclipse.swt.graphics.ImageData; +import org.eclipse.swt.graphics.ImageLoader; + +/** + * ImageDescriptor concrete class that can be fed data from any storage medium, such as a database, and can then produce + * images without having to write the image back to disk. + * + * @author Robert A. Fisher + */ +public class InputStreamImageDescriptor extends ImageDescriptor implements Serializable { + private static final Logger logger = ConfigUtil.getConfigFactory().getLogger(InputStreamImageDescriptor.class); + private static final long serialVersionUID = -1671707512486351173L; + private final byte[] data; + private ImageData imageData; + + public InputStreamImageDescriptor(InputStream input) { + this.data = input == null ? null : Streams.getByteArray(input); + } + + public InputStreamImageDescriptor(Image image) { + ImageLoader loader = new ImageLoader(); + loader.data = new ImageData[] {image.getImageData()}; + ByteArrayOutputStream imageStream = new ByteArrayOutputStream(); + loader.save(imageStream, SWT.IMAGE_GIF); + + this.data = imageStream.toByteArray(); + } + + /** + * @param data The data to be used for producing the image. The byte[] should match the format that would be acquired + * from reading an image file. + */ + public InputStreamImageDescriptor(byte[] data) { + this.data = data; + } + + @Override + public ImageData getImageData() { + try { + if (data != null && data.length > 0) { + imageData = new ImageData(new ByteArrayInputStream(data)); + } + } catch (SWTException ex) { + logger.log(Level.WARNING, ex.getLocalizedMessage(), ex); + } + return imageData; + } + + public byte[] getData() { + return data; + } +} diff --git a/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/util/JobbedNode.java b/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/util/JobbedNode.java new file mode 100644 index 00000000000..05728ef906c --- /dev/null +++ b/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/util/JobbedNode.java @@ -0,0 +1,116 @@ +/******************************************************************************* + * Copyright (c) 2004, 2007 Boeing. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Boeing - initial API and implementation + *******************************************************************************/ +package org.eclipse.osee.framework.ui.plugin.util; + +import org.eclipse.jface.viewers.TreeViewer; +import org.eclipse.jface.viewers.Viewer; +import org.eclipse.osee.framework.ui.swt.IContentProviderRunnable; +import org.eclipse.osee.framework.ui.swt.ITreeNode; +import org.eclipse.osee.framework.ui.swt.TreeNode; + +/** + * @author Robert A. Fisher + */ +public class JobbedNode extends TreeNode { + private static final long serialVersionUID = 2285210369260889786L; + private static final JobbedNode LOADING_NODE = new JobbedNode("Loading..."); + private static final JobbedNode CANCELLED_NODE = new JobbedNode("Cancelled"); + private static final Object[] LOADING = new Object[] {LOADING_NODE}; + private static final Object[] CANCELLED = new Object[] {CANCELLED_NODE}; + private final Viewer viewer; + private final IContentProviderRunnable providerRunnable; + private boolean expand = false; + + private JobbedNode(String title) { + super(null, null, title); + this.viewer = null; + this.providerRunnable = null; + } + + public JobbedNode(Object backingData, Viewer viewer, IContentProviderRunnable providerRunnable) { + this(backingData, viewer, providerRunnable, null); + } + + public JobbedNode(Object backingData, Viewer viewer, IContentProviderRunnable providerRunnable, JobbedNode parent) { + super(parent, null, backingData); + this.viewer = viewer; + this.providerRunnable = providerRunnable; + } + + /* + * (non-Javadoc) + * + * @see org.eclipse.osee.framework.jdk.core.swt.ITreeNode#getChildren() + */ + @Override + public Object[] getChildren() { + if (children == null && providerRunnable != null) { + children = LOADING; + Jobs.startJob(new GetChildrenJob(null, viewer, this, providerRunnable)); + } + return children; + } + + public void cancelled() { + cancelled(CANCELLED); + } + + public void cancelled(Exception ex) { + cancelled(new Object[] {ex}); + } + + private void cancelled(Object[] children) { + this.children = children; + Displays.ensureInDisplayThread(new Runnable() { + public void run() { + viewer.refresh(); + } + }); + } + + @Override + public void setChildren(Object[] objChildren) { + super.setChildren(objChildren); + + if (expand) { + if (viewer instanceof TreeViewer) { + final TreeViewer treeViewer = (TreeViewer) viewer; + + Displays.ensureInDisplayThread(new Runnable() { + + public void run() { + treeViewer.refresh(); + treeViewer.expandToLevel(2); + } + }); + } + } + } + + public void refresh() { + refresh(false); + } + + public void refresh(boolean expand) { + this.expand = expand; + + if (children != null) for (Object obj : children) + if (obj instanceof JobbedNode) ((JobbedNode) obj).refresh(true); + + children = null; + } + + @Override + protected ITreeNode getChild(Object backingData) { + return new JobbedNode(backingData, viewer, providerRunnable, this); + } + +} diff --git a/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/util/Jobs.java b/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/util/Jobs.java new file mode 100644 index 00000000000..17c2027023f --- /dev/null +++ b/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/util/Jobs.java @@ -0,0 +1,91 @@ +/******************************************************************************* + * Copyright (c) 2004, 2007 Boeing. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Boeing - initial API and implementation + *******************************************************************************/ +package org.eclipse.osee.framework.ui.plugin.util; + +import java.util.logging.Level; +import java.util.logging.Logger; +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.core.runtime.IStatus; +import org.eclipse.core.runtime.Status; +import org.eclipse.core.runtime.jobs.IJobChangeListener; +import org.eclipse.core.runtime.jobs.Job; + +/** + * @author Ryan D. Brooks + */ +public final class Jobs { + + private Jobs() { + }; + + public static Job startJob(Job job, IJobChangeListener jobChangeListener) { + return startJob(job, true, jobChangeListener); + } + + public static Job startJob(Job job) { + return startJob(job, true, null); + } + + public static Job startJob(Job job, boolean user) { + return startJob(job, user, null); + } + + public static Job startJob(Job job, boolean user, IJobChangeListener jobChangeListener) { + job.setUser(user); + job.setPriority(Job.LONG); + if (jobChangeListener != null) { + job.addJobChangeListener(jobChangeListener); + } + job.schedule(); + return job; + } + + public static void run(String name, IExceptionableRunnable runnable, Logger logger, String pluginId) { + run(name, runnable, logger, pluginId, true); + } + + public static void run(String name, IExceptionableRunnable runnable, Logger logger, String pluginId, boolean user) { + startJob(new CatchAndReleaseJob(name, runnable, logger, pluginId), user); + } + + public static class CatchAndReleaseJob extends Job { + private final IExceptionableRunnable runnable; + private final Logger logger; + private final String pluginId; + + /** + * @param name + * @param runnable + * @param logger + * @param pluginId + */ + public CatchAndReleaseJob(String name, IExceptionableRunnable runnable, Logger logger, String pluginId) { + super(name); + this.runnable = runnable; + this.logger = logger; + this.pluginId = pluginId; + } + + @Override + protected IStatus run(IProgressMonitor monitor) { + + try { + runnable.run(monitor); + } catch (Exception ex) { + logger.log(Level.SEVERE, ex.getLocalizedMessage(), ex); + String message = ex.getLocalizedMessage() == null ? ex.toString() : ex.getLocalizedMessage(); + return new Status(Status.ERROR, pluginId, Status.OK, message, ex); + } + + return Status.OK_STATUS; + } + } +}
\ No newline at end of file diff --git a/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/util/ListSelectionDialog.java b/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/util/ListSelectionDialog.java new file mode 100644 index 00000000000..ca63e893cbf --- /dev/null +++ b/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/util/ListSelectionDialog.java @@ -0,0 +1,118 @@ +/******************************************************************************* + * Copyright (c) 2004, 2007 Boeing. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Boeing - initial API and implementation + *******************************************************************************/ +package org.eclipse.osee.framework.ui.plugin.util; + +import org.eclipse.jface.dialogs.MessageDialog; +import org.eclipse.swt.SWT; +import org.eclipse.swt.events.SelectionEvent; +import org.eclipse.swt.events.SelectionListener; +import org.eclipse.swt.graphics.Image; +import org.eclipse.swt.widgets.Button; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Control; +import org.eclipse.swt.widgets.List; +import org.eclipse.swt.widgets.Shell; + +public class ListSelectionDialog extends MessageDialog { + + private Button okButton; + private Button cancelButton; + private List selections; + private int selectionIndex; + private Object[] choose; + private Button saveSelection; + private boolean isChecked = true; + + /** + * @return Returns the isChecked. + */ + public boolean saveSelection() { + return isChecked; + } + + public ListSelectionDialog(Object[] choose, Shell parentShell, String dialogTitle, Image dialogTitleImage, String dialogMessage, int dialogImageType, String[] dialogButtonLabels, int defaultIndex) { + super(parentShell, dialogTitle, dialogTitleImage, dialogMessage, dialogImageType, dialogButtonLabels, + defaultIndex); + this.choose = choose; + } + + @Override + protected Control createCustomArea(Composite parent) { + selections = new List(parent, SWT.SINGLE); + saveSelection = new Button(parent, SWT.CHECK);//.setText("Checkbox 1"); + saveSelection.setText("Remember Selection"); + saveSelection.setSelection(true); + + saveSelection.addSelectionListener(new SelectionListener() { + + public void widgetSelected(SelectionEvent e) { + isChecked = saveSelection.getSelection(); + } + + public void widgetDefaultSelected(SelectionEvent e) { + } + + }); + for (int i = 0; i < choose.length; i++) { + selections.add(choose[i].toString()); + } + + selections.addSelectionListener(new SelectionListener() { + + public void widgetSelected(SelectionEvent e) { + selectionIndex = selections.getSelectionIndex(); + System.out.println("selected index " + selectionIndex); + } + + public void widgetDefaultSelected(SelectionEvent e) { + } + + }); + + selections.select(0); + + return parent; + } + + @Override + protected Control createButtonBar(Composite parent) { + Control c = super.createButtonBar(parent); + okButton = getButton(0); + cancelButton = getButton(1); + + okButton.addSelectionListener(new SelectionListener() { + + public void widgetSelected(SelectionEvent e) { + + } + + public void widgetDefaultSelected(SelectionEvent e) { + } + }); + + cancelButton.addSelectionListener(new SelectionListener() { + + public void widgetSelected(SelectionEvent e) { + + } + + public void widgetDefaultSelected(SelectionEvent e) { + } + + }); + + return c; + } + + public int getSelection() { + return selectionIndex; + } +} diff --git a/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/util/ModeChecker.java b/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/util/ModeChecker.java new file mode 100644 index 00000000000..cc4b815fa77 --- /dev/null +++ b/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/util/ModeChecker.java @@ -0,0 +1,40 @@ +/******************************************************************************* + * Copyright (c) 2004, 2007 Boeing. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Boeing - initial API and implementation + *******************************************************************************/ +package org.eclipse.osee.framework.ui.plugin.util; + +import org.eclipse.osee.framework.plugin.core.config.ConfigUtil; +import org.eclipse.osee.framework.plugin.core.config.OseeRunMode; +import org.eclipse.swt.SWT; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Display; + +/** + * Checks mode based on OSEESiteConfig file + * + * @author Jeff C. Phillips + */ +public class ModeChecker { + + public ModeChecker() { + super(); + } + + /** + * Changes composite's color if running development mode. + * + * @param parent + */ + public static void check(Composite parent) { + + if (ConfigUtil.getConfigFactory().getOseeConfig().getRunMode().equals(OseeRunMode.Development)) parent.setBackground(Display.getDefault().getSystemColor( + SWT.COLOR_BLUE)); + } +} diff --git a/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/util/ModelessDialog.java b/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/util/ModelessDialog.java new file mode 100644 index 00000000000..81b21163965 --- /dev/null +++ b/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/util/ModelessDialog.java @@ -0,0 +1,60 @@ +/******************************************************************************* + * Copyright (c) 2004, 2007 Boeing. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Boeing - initial API and implementation + *******************************************************************************/ +package org.eclipse.osee.framework.ui.plugin.util; + +import java.util.ArrayList; +import java.util.List; +import org.eclipse.jface.dialogs.MessageDialog; +import org.eclipse.swt.SWT; +import org.eclipse.swt.events.SelectionListener; +import org.eclipse.swt.graphics.Image; +import org.eclipse.swt.widgets.Button; +import org.eclipse.swt.widgets.Shell; + +public class ModelessDialog extends MessageDialog { + private List<IShellCloseEvent> closeEventListeners = new ArrayList<IShellCloseEvent>(); + + public ModelessDialog(Shell parentShell, String dialogTitle, Image dialogTitleImage, String dialogMessage, int dialogImageType, String[] dialogButtonLabels, int defaultIndex) { + super(parentShell, dialogTitle, dialogTitleImage, dialogMessage, dialogImageType, dialogButtonLabels, + defaultIndex); + } + + /** + * Calling will enable dialog to loose focus + */ + public void setModeless() { + setShellStyle(SWT.DIALOG_TRIM | SWT.MODELESS); + setBlockOnOpen(false); + } + + public void setSelectionListener(SelectionListener listener) { + for (int i = 0; i < getButtonLabels().length; i++) { + Button button = getButton(i); + button.addSelectionListener(listener); + } + } + + /* (non-Javadoc) + * @see org.eclipse.jface.dialogs.MessageDialog#handleShellCloseEvent() + */ + @Override + protected void handleShellCloseEvent() { + super.handleShellCloseEvent(); + for (IShellCloseEvent event : closeEventListeners) { + event.onClose(); + } + } + + public void addShellCloseEventListeners(IShellCloseEvent event) { + closeEventListeners.add(event); + } + +} diff --git a/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/util/ObjectList.java b/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/util/ObjectList.java new file mode 100644 index 00000000000..40c48a14cbc --- /dev/null +++ b/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/util/ObjectList.java @@ -0,0 +1,130 @@ +/******************************************************************************* + * Copyright (c) 2004, 2007 Boeing. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Boeing - initial API and implementation + *******************************************************************************/ +package org.eclipse.osee.framework.ui.plugin.util; + +import java.util.ArrayList; +import java.util.Collection; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.List; + +/** + * @author Robert A. Fisher + */ +public class ObjectList<A> extends List { + private java.util.List<A> items; + + public ObjectList(Composite parent, int style) { + super(parent, style); + items = new ArrayList<A>(); + } + + /* (non-Javadoc) + * @see org.eclipse.swt.widgets.List#add(java.lang.String, int) + */ + @Override + @Deprecated + public void add(String string, int index) { + throw new UnsupportedOperationException(); + } + + /* (non-Javadoc) + * @see org.eclipse.swt.widgets.List#add(java.lang.String) + */ + @Override + @Deprecated + public void add(String string) { + throw new UnsupportedOperationException(); + } + + public void add(A item, String description) { + items.add(item); + super.add(description); + } + + public void add(A item, String description, int index) { + items.add(index, item); + super.add(description, index); + } + + public A getItemAt(int index) { + return items.get(index); + } + + public A getSelectedItem() { + if (this.getSelectionCount() > 1) throw new IllegalStateException("There is more than one item selected"); + + int index = this.getSelectionIndex(); + if (index < 0) + return null; + else + return getItemAt(this.getSelectionIndex()); + } + + public Collection<A> getSelectedItems() { + int[] selected = super.getSelectionIndices(); + ArrayList<A> selectedItems = new ArrayList<A>(selected.length); + for (int i : selected) + selectedItems.add(items.get(i)); + + return selectedItems; + } + + /* (non-Javadoc) + * @see org.eclipse.swt.widgets.List#remove(int, int) + */ + @Override + public void remove(int start, int end) { + for (int i = 0; i <= (end - start); i++) + items.remove(start); + super.remove(start, end); + } + + /* (non-Javadoc) + * @see org.eclipse.swt.widgets.List#remove(int) + */ + @Override + public void remove(int index) { + items.remove(index); + super.remove(index); + } + + /* (non-Javadoc) + * @see org.eclipse.swt.widgets.List#remove(int[]) + */ + @Override + @Deprecated + public void remove(int[] indices) { + throw new UnsupportedOperationException(); + } + + /* (non-Javadoc) + * @see org.eclipse.swt.widgets.List#remove(java.lang.String) + */ + @Override + @Deprecated + public void remove(String string) { + throw new UnsupportedOperationException(); + } + + /* (non-Javadoc) + * @see org.eclipse.swt.widgets.List#removeAll() + */ + @Override + public void removeAll() { + items.clear(); + super.removeAll(); + } + + // Stop SWT from disallowing our simple class extension + @Override + protected void checkSubclass() { + } +} diff --git a/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/util/OseeConsole.java b/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/util/OseeConsole.java new file mode 100644 index 00000000000..3760526ba39 --- /dev/null +++ b/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/util/OseeConsole.java @@ -0,0 +1,254 @@ +/*******************************************************************************
+ * Copyright (c) 2004, 2007 Boeing.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Boeing - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.osee.framework.ui.plugin.util;
+
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.InputStreamReader;
+import java.io.PrintStream;
+import java.util.Calendar;
+import java.util.Date;
+import java.util.concurrent.CopyOnWriteArrayList;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+import org.eclipse.osee.framework.jdk.core.util.IConsoleInputListener;
+import org.eclipse.osee.framework.jdk.core.util.Lib;
+import org.eclipse.osee.framework.plugin.core.config.ConfigUtil;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.widgets.Display;
+import org.eclipse.ui.PlatformUI;
+import org.eclipse.ui.console.ConsolePlugin;
+import org.eclipse.ui.console.IConsole;
+import org.eclipse.ui.console.IOConsole;
+import org.eclipse.ui.console.IOConsoleOutputStream;
+
+/**
+ * Creates an Eclipse Console instance and allows writing output, errors and prompt messages There should be at one
+ * instance of a ConsoleWriter per plugin that needs to output messages and errors. *
+ *
+ * @author Donald G. Dunne
+ */
+public class OseeConsole {
+
+ private static Logger logger = ConfigUtil.getConfigFactory().getLogger(
+ OseeConsole.class);
+
+ private IOConsoleOutputStream streamOut = null;
+
+ private IOConsoleOutputStream streamErr = null;
+
+ private IOConsoleOutputStream streamPrompt = null;
+
+ private final IOConsole console;
+
+ private final HandleInput inputHandler;
+
+ private boolean time;
+
+ private final Thread thread;
+
+ public OseeConsole(String title) {
+ this(title, true);
+ }
+
+ public OseeConsole(String title, boolean time) {
+ console = new IOConsole(title, null);
+ this.time = time;
+ this.inputHandler = new HandleInput();
+
+ thread = new Thread(inputHandler);
+ thread.setName("Osee console input handler");
+ ConsolePlugin.getDefault().getConsoleManager().addConsoles(
+ new IConsole[] { console });
+ PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {
+ public void run() {
+ streamOut = console.newOutputStream();// newMessageStream();
+ streamOut.setColor(Display.getDefault().getSystemColor(
+ SWT.COLOR_BLACK));
+ streamErr = console.newOutputStream();
+ streamErr.setColor(Display.getDefault().getSystemColor(
+ SWT.COLOR_RED));
+ streamPrompt = console.newOutputStream();
+ streamPrompt.setColor(Display.getDefault().getSystemColor(
+ SWT.COLOR_BLUE));
+ }
+ });
+ thread.start();
+ }
+
+ public PrintStream getPrintStream() {
+ return new PrintStream(streamOut);
+ }
+
+ public void shutdown() {
+ thread.interrupt();
+ ConsolePlugin.getDefault().getConsoleManager().removeConsoles(
+ new IConsole[] { console });
+ }
+
+ public static final int CONSOLE_ERROR = 0;
+
+ public static final int CONSOLE_OUT = 1;
+
+ public static final int CONSOLE_PROMPT = 2;
+
+ /**
+ * Writes string to console without popping console forward
+ *
+ * @param str
+ */
+ public void write(String str) {
+ write(str, false);
+ }
+
+ /**
+ * Writes string to console without popping console forward
+ *
+ * @param str
+ */
+ public void writeError(String str) {
+ write(str, CONSOLE_ERROR, true);
+ }
+
+ /**
+ * Writes string to console
+ *
+ * @param str
+ * @param popup
+ * bring console window forward
+ */
+ public void write(String str, boolean popup) {
+ write(str, CONSOLE_OUT, true);
+ }
+
+ /**
+ * Write string to console
+ *
+ * @param str
+ * @param type
+ * CONSOLE_ERROR, CONSOLE_OUT, CONSOLE_PROMPT
+ */
+ public void write(String str, int type) {
+ write(str, type, false);
+ }
+
+ /**
+ * Write string to console
+ *
+ * @param str
+ * @param type
+ * CONSOLE_ERROR, CONSOLE_OUT, CONSOLE_PROMPT
+ * @param popup
+ * bring console window forward
+ */
+ public void write(String str, int type, boolean popup) {
+ String time = "";
+ if (this.time) {
+ Calendar cal = Calendar.getInstance();
+ cal.setTime(new Date());
+
+ if (cal.get(Calendar.HOUR) == 0)
+ time = "12";
+ else
+ time = "" + cal.get(Calendar.HOUR);
+ time = Lib.padLeading(time, '0', 2);
+ String minute = "" + cal.get(Calendar.MINUTE);
+ minute = Lib.padLeading(minute, '0', 2);
+ time += ":" + minute + " => ";
+ }
+ try {
+ sendToStreams(type, time);
+ if (str.length() > 100000) {
+ int i = 0;
+
+ while (i < str.length()) {
+ int endIndex = i + 100000;
+ endIndex = endIndex > str.length() ? str.length()
+ : endIndex;
+ String chunk = str.substring(i, endIndex);
+ sendToStreams(type, chunk);
+ i = endIndex;
+ }
+ } else {
+ sendToStreams(type, str);
+ }
+
+ sendToStreams(type, "\n");
+ if (popup)
+ popup();
+ } catch (IOException ex) {
+ ex.printStackTrace();
+ }
+ }
+
+ public void prompt(String str) throws IOException {
+ sendToStreams(CONSOLE_PROMPT, str);
+ }
+
+ private void sendToStreams(int type, String str) throws IOException {
+ if (type == CONSOLE_ERROR && streamErr != null) {
+ streamErr.write(str);
+ }
+ if (type == CONSOLE_PROMPT && streamPrompt != null) {
+ streamPrompt.write(str);
+ }
+ if (type == CONSOLE_OUT && streamOut != null) {
+ streamOut.write(str);
+ }
+ }
+
+ public void popup() {
+ ConsolePlugin.getDefault().getConsoleManager().showConsoleView(console);
+ }
+
+ public void addInputListener(IConsoleInputListener listener) {
+ inputHandler.addListener(listener);
+ }
+
+ public void removeInputListener(IConsoleInputListener listener) {
+ inputHandler.removeListener(listener);
+ }
+
+ private class HandleInput implements Runnable {
+
+ private final CopyOnWriteArrayList<IConsoleInputListener> listeners;
+
+ public HandleInput() {
+ listeners = new CopyOnWriteArrayList<IConsoleInputListener>();
+ }
+
+ public void addListener(IConsoleInputListener listener) {
+ listeners.add(listener);
+ }
+
+ public void removeListener(IConsoleInputListener listener) {
+ listeners.remove(listener);
+ }
+
+
+ public void run() {
+ BufferedReader input = new BufferedReader(new InputStreamReader(
+ console.getInputStream()));
+ try {
+ String line = null;
+ while ((line = input.readLine()) != null) {
+ for (IConsoleInputListener listener : listeners) {
+ listener.lineRead(line);
+ }
+ }
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+ logger.log(Level.INFO, "done with the handling of input");
+ }
+
+ }
+}
\ No newline at end of file diff --git a/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/util/OseeData.java b/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/util/OseeData.java new file mode 100644 index 00000000000..e42a2706a07 --- /dev/null +++ b/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/util/OseeData.java @@ -0,0 +1,191 @@ +/******************************************************************************* + * Copyright (c) 2004, 2007 Boeing. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Boeing - initial API and implementation + *******************************************************************************/ +package org.eclipse.osee.framework.ui.plugin.util; + +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.io.PipedInputStream; +import java.io.PipedOutputStream; +import java.io.PrintStream; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.logging.Level; +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.transform.TransformerException; +import org.eclipse.core.resources.IFile; +import org.eclipse.core.resources.IFolder; +import org.eclipse.core.resources.IProject; +import org.eclipse.core.resources.IWorkspaceRoot; +import org.eclipse.core.resources.ResourcesPlugin; +import org.eclipse.core.runtime.CoreException; +import org.eclipse.core.runtime.IPath; +import org.eclipse.osee.framework.jdk.core.util.xml.Jaxp; +import org.eclipse.osee.framework.ui.plugin.OseePluginUiActivator; +import org.eclipse.osee.framework.ui.plugin.OseeUiActivator; +import org.w3c.dom.Document; +import org.w3c.dom.Element; + +/** + * This class provides a front end to writing files to a common osee.data directory in the workspace. This dir is + * invisible to Eclipse Navigator and Package Explorer. It is provided as a common repository for files that need to be + * created and retained by any plugin, but don't need to be visible to the user. This class does nothing more than + * ensure the directory is created and provide a way to get the path for other plugins to use. + * + * @author Donald G. Dunne + */ +public class OseeData { + private static final IPath workspacePath = ResourcesPlugin.getWorkspace().getRoot().getLocation(); + private static String oseeDataPathName = ".osee.data"; + private static final IPath oseeDataPath = workspacePath.append(oseeDataPathName); + private static final File oseeDir = oseeDataPath.toFile(); + private static final String dataStoreName = "OseeDataStore"; + private static IProject project; + private static Map<String, String> keyValue; + + static { + if (!oseeDir.exists()) { + if (!oseeDir.mkdir()) { + System.err.println("Can't create " + oseeDataPathName + " dir."); + } + } + + createProject(); + initKeyValueDataStore(); + } + + public static IPath getPath() { + return oseeDataPath; + } + + private static void initKeyValueDataStore() { + keyValue = new HashMap<String, String>(); + loadFromFile(); + } + + public static File getFile(String filename) { + return new File(oseeDir, filename); + } + + public static IFile getIFile(String fileName) { + return project.getFile(fileName); + } + + public static IFile getIFile(String fileName, InputStream in) throws CoreException, IOException { + return getIFile(fileName, in, false); + } + + public static IFile getIFile(String fileName, InputStream in, boolean overwrite) throws CoreException, IOException { + IFile iFile = project.getFile(fileName); + if (!iFile.exists() || overwrite) { + AIFile.writeToFile(iFile, in); + } + return iFile; + } + + private static boolean createProject() { + IWorkspaceRoot root = OseeUiActivator.getWorkspaceRoot(); + project = root.getProject(oseeDataPathName); + if (!project.exists()) { + try { + project.create(null); + } catch (CoreException ex) { + ex.printStackTrace(); + return false; + } + } + try { + project.open(null); + } catch (CoreException e) { + e.printStackTrace(); + return false; + } + return true; + } + + public static String getValue(String key) { + return keyValue.get(key); + } + + public static void setValue(String key, String value) { + keyValue.put(key, value); + try { + saveToFile(); + } catch (Exception ex) { + ex.printStackTrace(); + } + } + + private static void loadFromFile() { + keyValue.clear(); + + try { + Document doc = Jaxp.readXmlDocument(getFile()); + + Element root = doc.getDocumentElement(); + List<Element> pairs = Jaxp.getChildDirects(root, "Pair"); + + for (Element pair : pairs) { + String key = Jaxp.getChildText(pair, "Key"); + String value = Jaxp.getChildText(pair, "Value"); + if (key != null && value != null && !key.equals("") && !value.equals("")) keyValue.put(key, value); + } + } catch (Exception ex) { + OseePluginUiActivator.getLogger().log(Level.SEVERE, ex.getLocalizedMessage(), ex); + } + } + + private static void saveToFile() throws ParserConfigurationException, TransformerException, IOException, CoreException { + Document doc = Jaxp.newDocument(); + Element root = doc.createElement(dataStoreName); + doc.appendChild(root); + + Set<Map.Entry<String, String>> keySet = keyValue.entrySet(); + for (Map.Entry<String, String> entry : keySet) { + String key = entry.getKey(); + String value = entry.getValue(); + if (!key.equals("") && !value.equals("")) { + Element pair = doc.createElement("Pair"); + pair.appendChild(Jaxp.createElement(doc, "Key", key)); + pair.appendChild(Jaxp.createElement(doc, "Value", value)); + } + + } + Jaxp.writeXmlDocument(doc, getFile()); + } + + private static File getFile() throws IOException, CoreException { + PipedOutputStream pos = new PipedOutputStream(); + PrintStream ps = new PrintStream(pos); + InputStream in = new PipedInputStream(pos); + ps.println("<" + dataStoreName + "></" + dataStoreName + ">"); + ps.close(); + return getIFile(OseeData.class.getCanonicalName() + "." + dataStoreName + ".xml", in).getLocation().toFile(); + } + + /** + * @return Returns the project. + */ + public static IProject getProject() { + return project; + } + + public static IFolder getFolder(String name) throws CoreException { + IFolder folder = project.getFolder(name); + + if (!folder.exists()) { + folder.create(true, true, null); + } + return folder; + } +}
\ No newline at end of file diff --git a/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/util/OverlayImage.java b/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/util/OverlayImage.java new file mode 100644 index 00000000000..d8a5ae276b2 --- /dev/null +++ b/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/util/OverlayImage.java @@ -0,0 +1,117 @@ +/******************************************************************************* + * Copyright (c) 2004, 2007 Boeing. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Boeing - initial API and implementation + *******************************************************************************/ +package org.eclipse.osee.framework.ui.plugin.util; + +import java.util.ArrayList; +import java.util.Collection; +import org.eclipse.jface.resource.CompositeImageDescriptor; +import org.eclipse.jface.resource.ImageDescriptor; +import org.eclipse.swt.graphics.Image; +import org.eclipse.swt.graphics.Point; + +public class OverlayImage extends CompositeImageDescriptor { + + private Image baseImage; + private ImageDescriptor overlayImageDescriptor; + private int xValue = 0; + private int yValue = 0; + private Collection<ImageInfo> imageInfo; + + public static enum Location { + TOP_LEFT, TOP_RIGHT, BOT_LEFT, BOT_RIGHT + }; + + public static class ImageInfo { + public ImageDescriptor descriptor; + public Location location; + + public ImageInfo(ImageDescriptor descriptor, Location location) { + this.descriptor = descriptor; + this.location = location; + } + } + + public OverlayImage(Image baseImage, Collection<ImageInfo> imageInfo) { + this.baseImage = baseImage; + this.imageInfo = imageInfo; + } + + public OverlayImage(Image baseImage, ImageDescriptor overlayImageDescriptor, Location location) { + this.baseImage = baseImage; + this.overlayImageDescriptor = overlayImageDescriptor; + this.imageInfo = new ArrayList<ImageInfo>(2); + imageInfo.add(new ImageInfo(overlayImageDescriptor, location)); + } + + public OverlayImage(Image baseImage, ImageDescriptor overlayImageDescriptor) { + this(baseImage, overlayImageDescriptor, 0, 0); + } + + public OverlayImage(Image baseImage, ImageDescriptor overlayImageDescriptor, int xValue, int yValue) { + if (baseImage == null) throw new IllegalArgumentException("baseImage can not be null"); + if (overlayImageDescriptor == null) throw new IllegalArgumentException("overlayImageDescriptor can not be null"); + + this.baseImage = baseImage; + this.overlayImageDescriptor = overlayImageDescriptor; + this.xValue = xValue; + this.yValue = yValue; + } + + /** + * Set x,y pixel to draw the overlay image eg: 8,8 for bottom right of a 16x16 image 0,0 for top left + * + * @param xValue + * @param yValue + */ + public void setXY(int xValue, int yValue) { + this.xValue = xValue; + this.yValue = yValue; + } + + protected void drawCompositeImage(int width, int height) { + // To draw a composite image, the base image should be + // drawn first (first layer) and then the overlay image + // (second layer) + // Draw the base image using the base image's image data + drawImage(baseImage.getImageData(), 0, 0); + + if (imageInfo == null) { + // Overlaying the icon in the top left corner i.e. x and y + // coordinates are both zero + drawImage(overlayImageDescriptor.getImageData(), xValue, yValue); + } else { + for (ImageInfo info : imageInfo) { + if (info.location == Location.TOP_LEFT) + drawImage(info.descriptor.getImageData(), 0, 0); + else if (info.location == Location.BOT_LEFT) + drawImage(info.descriptor.getImageData(), 0, 8); + else if (info.location == Location.TOP_RIGHT) + drawImage(info.descriptor.getImageData(), 8, 0); + else if (info.location == Location.BOT_RIGHT) drawImage(info.descriptor.getImageData(), 8, 8); + } + } + } + + protected Point getSize() { + // System.err.println("Width = " + baseImage.getBounds().width); + // System.err.println("Height = " + baseImage.getBounds().height); + int baseWidth = baseImage.getBounds().width; + int baseHeight = baseImage.getBounds().height; + + Image overImg = overlayImageDescriptor.createImage(); + int overWidth = overImg.getBounds().width; + int overHeight = overImg.getBounds().height; + overlayImageDescriptor.destroyResource(overImg); + + return new Point(baseWidth > overWidth ? baseWidth : overWidth, baseHeight > overHeight ? baseHeight : overHeight); + } + +}
\ No newline at end of file diff --git a/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/util/Result.java b/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/util/Result.java new file mode 100644 index 00000000000..a49b7a0a422 --- /dev/null +++ b/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/util/Result.java @@ -0,0 +1,73 @@ +/******************************************************************************* + * Copyright (c) 2004, 2007 Boeing. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Boeing - initial API and implementation + *******************************************************************************/ + +package org.eclipse.osee.framework.ui.plugin.util; + +public class Result { + + public static Result TrueResult = new Result(true); + public static Result FalseResult = new Result(false); + private boolean isTrue = false; + private String text = ""; + + public Result(boolean valid, String text) { + this.isTrue = valid; + this.text = text; + } + + public Result(String text) { + this.isTrue = false; + this.text = text; + } + + public Result(boolean isTrue) { + this.isTrue = isTrue; + } + + public Result() { + this.isTrue = true; + } + + public boolean isTrue() { + return isTrue; + } + + public boolean isFalse() { + return !isTrue; + } + + public String getText() { + return text; + } + + public String toString() { + return String.valueOf(isTrue()) + (getText().equals("") ? "" : " - \"" + getText() + "\""); + } + + public void popup() { + popup(false); + } + + public void popup(final boolean success) { + Displays.ensureInDisplayThread(new Runnable() { + public void run() { + AWorkbench.popup( + (success ? "Success" : "ERROR"), + text != null && !text.equals("") ? text : success ? "Success" : "Error Encountered. See Error Log View"); + }; + }); + } + + public void setText(String text) { + this.text = text; + } + +} diff --git a/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/util/ResultRunnable.java b/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/util/ResultRunnable.java new file mode 100644 index 00000000000..362ebc6e15e --- /dev/null +++ b/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/util/ResultRunnable.java @@ -0,0 +1,33 @@ +/******************************************************************************* + * Copyright (c) 2004, 2007 Boeing. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Boeing - initial API and implementation + *******************************************************************************/ +package org.eclipse.osee.framework.ui.plugin.util; + +/** + * @author Donald G. Dunne + */ +public class ResultRunnable implements Runnable { + + protected Result runnableResult = Result.TrueResult; + + /* (non-Javadoc) + * @see java.lang.Runnable#run() + */ + public void run() { + } + + /** + * @return the result + */ + public Result getResult() { + return runnableResult; + } + +} diff --git a/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/util/SelectionCountChangeListener.java b/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/util/SelectionCountChangeListener.java new file mode 100644 index 00000000000..065bea1a76d --- /dev/null +++ b/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/util/SelectionCountChangeListener.java @@ -0,0 +1,48 @@ +/******************************************************************************* + * Copyright (c) 2004, 2007 Boeing. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Boeing - initial API and implementation + *******************************************************************************/ +package org.eclipse.osee.framework.ui.plugin.util; + +import org.eclipse.jface.action.IStatusLineManager; +import org.eclipse.jface.viewers.ISelectionChangedListener; +import org.eclipse.jface.viewers.IStructuredSelection; +import org.eclipse.jface.viewers.SelectionChangedEvent; +import org.eclipse.ui.IViewSite; + +/** + * @author Robert A. Fisher + */ +public class SelectionCountChangeListener implements ISelectionChangedListener { + private IStatusLineManager statusLineManager; + + /** + * @param viewSite + */ + public SelectionCountChangeListener(IViewSite viewSite) { + this.statusLineManager = viewSite.getActionBars().getStatusLineManager(); + } + + /** + * @param statusLineManager + */ + public SelectionCountChangeListener(IStatusLineManager statusLineManager) { + this.statusLineManager = statusLineManager; + } + + public void selectionChanged(SelectionChangedEvent event) { + IStructuredSelection selection = (IStructuredSelection) event.getSelection(); + + IStatusLineManager lineManager = statusLineManager; + if (selection.size() > 1) + lineManager.setMessage(selection.size() + " items selected"); + else + lineManager.setMessage(""); + } +} diff --git a/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/util/StringLabelProvider.java b/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/util/StringLabelProvider.java new file mode 100644 index 00000000000..8cfc94b1727 --- /dev/null +++ b/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/util/StringLabelProvider.java @@ -0,0 +1,45 @@ +/******************************************************************************* + * Copyright (c) 2004, 2007 Boeing. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Boeing - initial API and implementation + *******************************************************************************/ +package org.eclipse.osee.framework.ui.plugin.util; + +import org.eclipse.jface.viewers.ILabelProvider; +import org.eclipse.jface.viewers.ILabelProviderListener; +import org.eclipse.swt.graphics.Image; + +/** + * Generic Artifact Label Provider showing Descriptive Name as text + * + * @author Donald G. Dunne + */ +public class StringLabelProvider implements ILabelProvider { + + public Image getImage(Object arg0) { + return null; + } + + public String getText(Object arg0) { + return ((String) arg0); + } + + public void addListener(ILabelProviderListener arg0) { + } + + public void dispose() { + } + + public boolean isLabelProperty(Object arg0, String arg1) { + return false; + } + + public void removeListener(ILabelProviderListener arg0) { + } + +} diff --git a/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/util/StringViewerSorter.java b/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/util/StringViewerSorter.java new file mode 100644 index 00000000000..a831fc7041a --- /dev/null +++ b/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/util/StringViewerSorter.java @@ -0,0 +1,40 @@ +/******************************************************************************* + * Copyright (c) 2004, 2007 Boeing. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Boeing - initial API and implementation + *******************************************************************************/ +package org.eclipse.osee.framework.ui.plugin.util; + +import java.text.Collator; +import org.eclipse.jface.viewers.Viewer; +import org.eclipse.jface.viewers.ViewerSorter; + +/** + * @author Donald G. Dunne + */ +public class StringViewerSorter extends ViewerSorter { + + /** + * + */ + public StringViewerSorter() { + } + + /** + * @param collator + */ + public StringViewerSorter(Collator collator) { + super(collator); + } + + @SuppressWarnings("unchecked") + @Override + public int compare(Viewer viewer, Object e1, Object e2) { + return getComparator().compare((String) e1, (String) e2); + } +} diff --git a/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/util/ViewPartUtil.java b/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/util/ViewPartUtil.java new file mode 100644 index 00000000000..c091eb141a4 --- /dev/null +++ b/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/util/ViewPartUtil.java @@ -0,0 +1,90 @@ +/******************************************************************************* + * Copyright (c) 2004, 2007 Boeing. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Boeing - initial API and implementation + *******************************************************************************/ +package org.eclipse.osee.framework.ui.plugin.util; + +import java.util.Iterator; +import java.util.SortedSet; +import java.util.TreeSet; +import org.eclipse.jface.dialogs.MessageDialog; +import org.eclipse.ui.IViewPart; +import org.eclipse.ui.IViewReference; +import org.eclipse.ui.IWorkbenchPage; +import org.eclipse.ui.PartInitException; +import org.eclipse.ui.PlatformUI; + +public class ViewPartUtil { + + /** + * Attempts to start up the ViewPart using an integer as the unique identifier for the secondary ID. This secondary + * ID will be the smallest integer not currently being used as a secondary ID for this view type, beginning with 1. + * + * @param viewID The Canonical name to the ViewPart class to be started. + * @return the integer used as the secondary ID + */ + public static int startMultiView(String viewID) { + /* + * ViewParts have a primary ID (which identifies the type of the View) and a secondary ID + * (which allows us to have multiple Views of the same type running concurrently. Since the + * secondary ID must be unique, we need to find an ID that isn't being used currently. Also, + * its nice to display this to the user so they can keep the views straight. So, we've opted + * to simply use an integer number for this purpose. Therefore, to startup another instnace of + * this view, we want to find a number which isn't currently being used, and use that. The + * lower numbers are preferable from a useability standpoint, and we'll start counting at 1. + * If a view is closed, we should first re-use its number before going on to higher numbers. + * For example, if views with secondary IDs 1, and 3 are currently running, the next instance + * of the view should be 2. + */ + + SortedSet<Integer> set = new TreeSet<Integer>(); + IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage(); + IViewReference[] viewRefs = page.getViewReferences(); + for (IViewReference viewRef : viewRefs) { + if (viewRef.getId().equals(viewID)) { + try { + set.add(new Integer(viewRef.getSecondaryId())); + } catch (NumberFormatException ex) { + ex.printStackTrace(); + } + } + } + + // Find the next available integer number + Iterator<Integer> iter = set.iterator(); + boolean found = false; + int secondaryId = 1; + while (iter.hasNext() && !found) { + if (iter.next().intValue() != secondaryId) + found = true; + else + secondaryId++; + } + try { + page.showView(viewID, Integer.toString(secondaryId), IWorkbenchPage.VIEW_ACTIVATE); + } catch (PartInitException ex) { + System.err.println("COULD NOT FIND " + viewID + ", with ID # = " + secondaryId); + ex.printStackTrace(); + } + + return secondaryId; + } + + public static IViewPart openOrShowView(String viewId) { + IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage(); + try { + return page.showView(viewId); + } catch (PartInitException e1) { + MessageDialog.openInformation(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), "Launch Error", + "Couldn't Launch " + viewId + "\n\n" + e1.getMessage()); + } + return null; + } + +} diff --git a/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/util/WindowLocal.java b/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/util/WindowLocal.java new file mode 100644 index 00000000000..fb421a558ba --- /dev/null +++ b/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/util/WindowLocal.java @@ -0,0 +1,96 @@ +/******************************************************************************* + * Copyright (c) 2004, 2007 Boeing. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Boeing - initial API and implementation + *******************************************************************************/ +package org.eclipse.osee.framework.ui.plugin.util; + +import java.util.HashMap; +import java.util.Map; +import org.eclipse.ui.PlatformUI; + +/** + * An Eclipse window-local variable. This will provide variables that appear to be scoped based on the active window + * that accesses the variable. All access to the variable from a non-window is considered from the same scope. + * + * @author Robert A. Fisher + */ +public class WindowLocal<T> { + private static final Object NON_WINDOW = new Object(); + private Map<Object, T> valueMap; + private WindowKey windowKey; + + public WindowLocal() { + this.valueMap = new HashMap<Object, T>(); + windowKey = new WindowKey(); + } + + /** + * Provide the initial value to be used when accessed from a scope for the first time. This should be overriden by + * the application in most cases. The default implementation returns a null.<br/><br/> This method is not called + * when the first access to the variable in a scope is a set call. + */ + protected T initialValue() { + return null; + } + + /** + * Get the value of the variable for the current scope. + */ + public T get() { + Object key = getWindowLocalKey(); + T value = valueMap.get(key); + + if (value == null) { + value = initialValue(); + set(value); + } + + return value; + } + + /** + * Assign the value of the variable for the current scope. + */ + public void set(T value) { + valueMap.put(getWindowLocalKey(), value); + } + + /** + * Remove the variable from the current scope. This will cause the next access from this scope to appear as the + * first. + */ + public void remove() { + valueMap.remove(getWindowLocalKey()); + } + + private Object getWindowLocalKey() { + Object key; + + if (PlatformUI.isWorkbenchRunning()) { + Displays.ensureInDisplayThread(windowKey); + key = windowKey.getKey(); + } else { + key = NON_WINDOW; + } + + return key; + } + + private class WindowKey implements Runnable { + private Object key; + + public void run() { + key = PlatformUI.getWorkbench().getActiveWorkbenchWindow(); + } + + public Object getKey() { + return key; + } + } +} diff --git a/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/util/Wizards.java b/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/util/Wizards.java new file mode 100644 index 00000000000..b122885d080 --- /dev/null +++ b/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/util/Wizards.java @@ -0,0 +1,48 @@ +/******************************************************************************* + * Copyright (c) 2004, 2007 Boeing. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Boeing - initial API and implementation + *******************************************************************************/ +package org.eclipse.osee.framework.ui.plugin.util; + +import org.eclipse.jface.viewers.ISelection; +import org.eclipse.jface.viewers.IStructuredSelection; +import org.eclipse.jface.viewers.StructuredSelection; +import org.eclipse.jface.wizard.WizardDialog; +import org.eclipse.swt.widgets.Shell; +import org.eclipse.ui.IViewPart; +import org.eclipse.ui.IWorkbenchWindow; +import org.eclipse.ui.IWorkbenchWizard; + +/** + * @author Robert A. Fisher + */ +public final class Wizards { + public static final void initAndOpen(IWorkbenchWizard wizard, IViewPart viewPart) { + initAndOpen(wizard, viewPart.getViewSite().getWorkbenchWindow()); + } + + public static final void initAndOpen(IWorkbenchWizard wizard, IWorkbenchWindow workbenchWindow) { + + IStructuredSelection selectionToPass; + // get the current workbench selection + ISelection workbenchSelection = workbenchWindow.getSelectionService().getSelection(); + if (workbenchSelection instanceof IStructuredSelection) { + selectionToPass = (IStructuredSelection) workbenchSelection; + } else { + selectionToPass = StructuredSelection.EMPTY; + } + + wizard.init(workbenchWindow.getWorkbench(), selectionToPass); + + Shell parent = workbenchWindow.getShell(); + WizardDialog dialog = new WizardDialog(parent, wizard); + dialog.create(); + dialog.open(); + } +} diff --git a/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/util/WorkspaceSearchInit.java b/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/util/WorkspaceSearchInit.java new file mode 100644 index 00000000000..ac1afc886f7 --- /dev/null +++ b/org.eclipse.osee.framework.ui.plugin/src/org/eclipse/osee/framework/ui/plugin/util/WorkspaceSearchInit.java @@ -0,0 +1,38 @@ +/******************************************************************************* + * Copyright (c) 2004, 2007 Boeing. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Boeing - initial API and implementation + *******************************************************************************/ +package org.eclipse.osee.framework.ui.plugin.util; + +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.core.runtime.IStatus; +import org.eclipse.core.runtime.Status; +import org.eclipse.core.runtime.jobs.Job; + +/** + * @author Andrew M. Finkbeiner + */ +public class WorkspaceSearchInit extends Job { + private Object obj; + + public WorkspaceSearchInit(Object obj) { + super("Initializing Workspace Search"); + this.obj = obj; + } + + /* (non-Javadoc) + * @see org.eclipse.core.runtime.jobs.Job#run(org.eclipse.core.runtime.IProgressMonitor) + */ + @Override + protected IStatus run(IProgressMonitor monitor) { + AWorkspace.initWorkspaceSearch(); + obj.notify(); + return Status.OK_STATUS; + } +} |