diff options
author | afinkbein | 2008-12-01 16:59:08 +0000 |
---|---|---|
committer | afinkbein | 2008-12-01 16:59:08 +0000 |
commit | 15bb30199fbab6fcfb4570318788094e90f294d2 (patch) | |
tree | 280f439cc668cfbd37c821acb881a104aeee2575 | |
parent | dee6b96cf046fc710dd6cff74ae1a8cf41708184 (diff) | |
download | org.eclipse.osee-15bb30199fbab6fcfb4570318788094e90f294d2.tar.gz org.eclipse.osee-15bb30199fbab6fcfb4570318788094e90f294d2.tar.xz org.eclipse.osee-15bb30199fbab6fcfb4570318788094e90f294d2.zip |
60 files changed, 6947 insertions, 0 deletions
diff --git a/org.eclipse.osee.framework.database/.classpath b/org.eclipse.osee.framework.database/.classpath new file mode 100644 index 00000000000..64ed6b3795d --- /dev/null +++ b/org.eclipse.osee.framework.database/.classpath @@ -0,0 +1,7 @@ +<?xml version="1.0" encoding="UTF-8"?>
+<classpath>
+ <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
+ <classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/>
+ <classpathentry kind="src" path="src"/>
+ <classpathentry kind="output" path="bin"/>
+</classpath>
diff --git a/org.eclipse.osee.framework.database/.project b/org.eclipse.osee.framework.database/.project new file mode 100644 index 00000000000..c6fe077dcdf --- /dev/null +++ b/org.eclipse.osee.framework.database/.project @@ -0,0 +1,29 @@ +<?xml version="1.0" encoding="UTF-8"?>
+<projectDescription>
+ <name>org.eclipse.osee.framework.database</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>
+ <nature>org.apache.derby.ui.derbyEngine</nature>
+ </natures>
+</projectDescription>
diff --git a/org.eclipse.osee.framework.database/META-INF/MANIFEST.MF b/org.eclipse.osee.framework.database/META-INF/MANIFEST.MF new file mode 100644 index 00000000000..77eb2093f45 --- /dev/null +++ b/org.eclipse.osee.framework.database/META-INF/MANIFEST.MF @@ -0,0 +1,35 @@ +Manifest-Version: 1.0 +Bundle-ManifestVersion: 2 +Bundle-Name: Database Plug-in (Incubation) +Bundle-SymbolicName: org.eclipse.osee.framework.database;singleton:=true +Bundle-Version: 0.4.0.qualifier +Bundle-Activator: org.eclipse.osee.framework.database.DatabaseActivator +Export-Package: org.eclipse.osee.framework.database, + org.eclipse.osee.framework.database.config, + org.eclipse.osee.framework.database.core, + org.eclipse.osee.framework.database.data, + org.eclipse.osee.framework.database.initialize, + org.eclipse.osee.framework.database.initialize.tasks, + org.eclipse.osee.framework.database.initialize.tasks.relational, + org.eclipse.osee.framework.database.sql, + org.eclipse.osee.framework.database.sql.datatype, + org.eclipse.osee.framework.database.utility +Require-Bundle: + org.eclipse.core.runtime, + org.eclipse.core.resources, + org.apache.commons.lang, + org.eclipse.osee.framework.jdk.core, + org.eclipse.osee.framework.plugin.core, + org.eclipse.osee.framework.ui.plugin, + org.eclipse.osee.framework.core, + org.eclipse.osee.framework.core.client +Bundle-ActivationPolicy: lazy +Bundle-Vendor: Eclipse.org +Import-Package: org.eclipse.osee.framework.core.client, + org.eclipse.osee.framework.db.connection, + org.eclipse.osee.framework.db.connection.core, + org.eclipse.osee.framework.db.connection.core.schema, + org.eclipse.osee.framework.db.connection.exception, + org.eclipse.osee.framework.db.connection.info, + org.eclipse.osee.framework.logging +Bundle-RequiredExecutionEnvironment: JavaSE-1.6 diff --git a/org.eclipse.osee.framework.database/build.properties b/org.eclipse.osee.framework.database/build.properties new file mode 100644 index 00000000000..b44f0f8392a --- /dev/null +++ b/org.eclipse.osee.framework.database/build.properties @@ -0,0 +1,9 @@ +bin.includes = plugin.xml,\
+ META-INF/,\
+ support/,\
+ src/,\
+ .
+jars.compile.order = .
+source.. = src/
+output.. = bin/
+
diff --git a/org.eclipse.osee.framework.database/plugin.xml b/org.eclipse.osee.framework.database/plugin.xml new file mode 100644 index 00000000000..87b288c5af4 --- /dev/null +++ b/org.eclipse.osee.framework.database/plugin.xml @@ -0,0 +1,50 @@ +<?xml version="1.0" encoding="UTF-8"?>
+<?eclipse version="3.0"?>
+<plugin>
+ <extension-point id="IDbInitializationTask" name="DbInitializationTask" schema="schema/IDbInitializationTask.exsd"/>
+ <extension-point id="AddDbInitChoice" name="Add Database Initialization Choice" schema="schema/AddDbInitChoice.exsd"/>
+ <extension
+ id="configClient"
+ point="org.eclipse.core.runtime.applications">
+ <application>
+ <run class="org.eclipse.osee.framework.database.ConfigDatabase"/>
+ </application>
+ </extension>
+
+<extension
+ id="BackupTableData"
+ point="org.eclipse.osee.framework.database.IDbInitializationTask">
+ <DatabaseTask
+ classname="org.eclipse.osee.framework.database.initialize.tasks.relational.BackupTableData"/>
+</extension>
+<extension
+ id="RestoreTableData"
+ point="org.eclipse.osee.framework.database.IDbInitializationTask">
+ <DatabaseTask
+ classname="org.eclipse.osee.framework.database.initialize.tasks.relational.RestoreTableData"/>
+</extension>
+<extension
+ id="ImportDataFromDbService"
+ point="org.eclipse.osee.framework.database.IDbInitializationTask">
+ <DatabaseTask
+ classname="org.eclipse.osee.framework.database.initialize.tasks.ImportDataFromDbService"/>
+</extension>
+<extension
+ id="availableDbTasks"
+ name="availableDbTasks"
+ point="org.eclipse.core.runtime.applications">
+ <application>
+ <run class="org.eclipse.osee.framework.database.PlatformRunnableAvailableInitTasks"/>
+ </application>
+</extension>
+<extension
+ id="PostDbInitializationProcess"
+ name="PostDbInitializationProcess"
+ point="org.eclipse.osee.framework.database.IDbInitializationTask">
+ <DatabaseTask
+ classname="org.eclipse.osee.framework.database.initialize.tasks.PostDatabaseInitialization">
+ </DatabaseTask>
+</extension>
+
+
+</plugin>
diff --git a/org.eclipse.osee.framework.database/schema/AddDbInitChoice.exsd b/org.eclipse.osee.framework.database/schema/AddDbInitChoice.exsd new file mode 100644 index 00000000000..17670ac4781 --- /dev/null +++ b/org.eclipse.osee.framework.database/schema/AddDbInitChoice.exsd @@ -0,0 +1,105 @@ +<?xml version='1.0' encoding='UTF-8'?>
+<!-- Schema file written by PDE -->
+<schema targetNamespace="org.eclipse.osee.framework.database">
+<annotation>
+ <appInfo>
+ <meta.schema plugin="org.eclipse.osee.framework.database" id="AddDbInitChoice" name="Add Database Initialization Choice"/>
+ </appInfo>
+ <documentation>
+ [Enter description of this extension point.]
+ </documentation>
+ </annotation>
+
+ <element name="extension">
+ <complexType>
+ <sequence>
+ <element ref="dbInitChoice"/>
+ </sequence>
+ <attribute name="point" type="string" use="required">
+ <annotation>
+ <documentation>
+
+ </documentation>
+ </annotation>
+ </attribute>
+ <attribute name="id" type="string">
+ <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="dbInitChoice">
+ <complexType>
+ <attribute name="classname" type="string" use="required">
+ <annotation>
+ <documentation>
+
+ </documentation>
+ <appInfo>
+ <meta.attribute kind="java" basedOn=":org.eclipse.osee.framework.database.utility.IAddDbInitChoice"/>
+ </appInfo>
+ </annotation>
+ </attribute>
+ </complexType>
+ </element>
+
+ <annotation>
+ <appInfo>
+ <meta.section type="since"/>
+ </appInfo>
+ <documentation>
+ [Enter the first release in which this extension point appears.]
+ </documentation>
+ </annotation>
+
+ <annotation>
+ <appInfo>
+ <meta.section type="examples"/>
+ </appInfo>
+ <documentation>
+ [Enter extension point usage example here.]
+ </documentation>
+ </annotation>
+
+ <annotation>
+ <appInfo>
+ <meta.section type="apiInfo"/>
+ </appInfo>
+ <documentation>
+ [Enter API information here.]
+ </documentation>
+ </annotation>
+
+ <annotation>
+ <appInfo>
+ <meta.section type="implementation"/>
+ </appInfo>
+ <documentation>
+ [Enter information about supplied implementation of this extension point.]
+ </documentation>
+ </annotation>
+
+ <annotation>
+ <appInfo>
+ <meta.section type="copyright"/>
+ </appInfo>
+ <documentation>
+
+ </documentation>
+ </annotation>
+
+</schema>
diff --git a/org.eclipse.osee.framework.database/schema/IDbInitializationTask.exsd b/org.eclipse.osee.framework.database/schema/IDbInitializationTask.exsd new file mode 100644 index 00000000000..14b791e28c4 --- /dev/null +++ b/org.eclipse.osee.framework.database/schema/IDbInitializationTask.exsd @@ -0,0 +1,114 @@ +<?xml version='1.0' encoding='UTF-8'?>
+<!-- Schema file written by PDE -->
+<schema targetNamespace="org.eclipse.osee.framework.database" xmlns="http://www.w3.org/2001/XMLSchema">
+<annotation>
+ <appinfo>
+ <meta.schema plugin="org.eclipse.osee.framework.database" id="IDbInitializationTask" name="DbInitializationTask"/>
+ </appinfo>
+ <documentation>
+ [Enter description of this extension point.]
+ </documentation>
+ </annotation>
+
+ <element name="extension">
+ <annotation>
+ <appinfo>
+ <meta.element />
+ </appinfo>
+ </annotation>
+ <complexType>
+ <sequence>
+ <element ref="DatabaseTask"/>
+ </sequence>
+ <attribute name="point" type="string" use="required">
+ <annotation>
+ <documentation>
+
+ </documentation>
+ </annotation>
+ </attribute>
+ <attribute name="id" type="string">
+ <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="DatabaseTask">
+ <complexType>
+ <sequence>
+ </sequence>
+ <attribute name="classname" type="string" use="required">
+ <annotation>
+ <documentation>
+
+ </documentation>
+ <appinfo>
+ <meta.attribute kind="java" basedOn=":org.eclipse.osee.framework.database.IDbInitializationTask"/>
+ </appinfo>
+ </annotation>
+ </attribute>
+ <attribute name="DbInitRule" type="string">
+ <annotation>
+ <documentation>
+
+ </documentation>
+ <appinfo>
+ <meta.attribute kind="java" basedOn=":org.eclipse.osee.framework.database.IDbInitRule"/>
+ </appinfo>
+ </annotation>
+ </attribute>
+ </complexType>
+ </element>
+
+ <annotation>
+ <appinfo>
+ <meta.section type="since"/>
+ </appinfo>
+ <documentation>
+ [Enter the first release in which this extension point appears.]
+ </documentation>
+ </annotation>
+
+ <annotation>
+ <appinfo>
+ <meta.section type="examples"/>
+ </appinfo>
+ <documentation>
+ [Enter extension point usage example here.]
+ </documentation>
+ </annotation>
+
+ <annotation>
+ <appinfo>
+ <meta.section type="apiInfo"/>
+ </appinfo>
+ <documentation>
+ [Enter API information here.]
+ </documentation>
+ </annotation>
+
+ <annotation>
+ <appinfo>
+ <meta.section type="implementation"/>
+ </appinfo>
+ <documentation>
+ [Enter information about supplied implementation of this extension point.]
+ </documentation>
+ </annotation>
+
+
+</schema>
diff --git a/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/ConfigDatabase.java b/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/ConfigDatabase.java new file mode 100644 index 00000000000..d209e113db4 --- /dev/null +++ b/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/ConfigDatabase.java @@ -0,0 +1,44 @@ +/******************************************************************************* + * 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.database; + +import org.eclipse.core.runtime.Platform; +import org.eclipse.equinox.app.IApplication; +import org.eclipse.equinox.app.IApplicationContext; +import org.eclipse.osee.framework.database.initialize.DatabaseInitializationOperation; + +public class ConfigDatabase implements IApplication { + + private static String[] bundlesToStart = + new String[] {"org.eclipse.osee.framework.db.connection", "org.eclipse.equinox.ds"}; + + /* + * (non-Javadoc) + * + * @see org.eclipse.equinox.app.IApplication#start(org.eclipse.equinox.app.IApplicationContext) + */ + public Object start(IApplicationContext context) throws Exception { + for (String symbolicName : bundlesToStart) { + Platform.getBundle(symbolicName).start(); + } + DatabaseInitializationOperation.executeConfigureFromJvmProperties(); + return EXIT_OK; + } + + /* + * (non-Javadoc) + * + * @see org.eclipse.equinox.app.IApplication#stop() + */ + public void stop() { + } + +} diff --git a/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/DatabaseActivator.java b/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/DatabaseActivator.java new file mode 100644 index 00000000000..438edac1981 --- /dev/null +++ b/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/DatabaseActivator.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.database; + +import org.eclipse.osee.framework.plugin.core.OseeActivator; + +/** + * The main plug-in class to be used in the desktop. + * + * @author Ryan D. Brooks + */ +public class DatabaseActivator extends OseeActivator { + + // The shared instance. + private static DatabaseActivator plugin; + + /** + * The constructor. + */ + public DatabaseActivator() { + plugin = this; + } + + /** + * Returns the shared instance. + */ + public static DatabaseActivator getInstance() { + return plugin; + } +}
\ No newline at end of file diff --git a/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/IDbInitializationRule.java b/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/IDbInitializationRule.java new file mode 100644 index 00000000000..f409d573d97 --- /dev/null +++ b/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/IDbInitializationRule.java @@ -0,0 +1,21 @@ +/*******************************************************************************
+ * 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.database;
+
+import org.eclipse.osee.framework.db.connection.exception.OseeCoreException;
+
+/**
+ * @author Roberto E. Escobar
+ */
+public interface IDbInitializationRule {
+
+ public boolean isAllowed() throws OseeCoreException;
+}
diff --git a/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/IDbInitializationTask.java b/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/IDbInitializationTask.java new file mode 100644 index 00000000000..05aef3c3a20 --- /dev/null +++ b/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/IDbInitializationTask.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.database; + +import org.eclipse.osee.framework.db.connection.OseeConnection; +import org.eclipse.osee.framework.db.connection.exception.OseeCoreException; + +public interface IDbInitializationTask { + public abstract void run(OseeConnection connection) throws OseeCoreException; +} diff --git a/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/MySqlLaunch.java b/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/MySqlLaunch.java new file mode 100644 index 00000000000..01808496137 --- /dev/null +++ b/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/MySqlLaunch.java @@ -0,0 +1,56 @@ +/******************************************************************************* + * 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.database; + +import java.io.File; +import java.io.IOException; +import java.sql.Connection; +import org.eclipse.osee.framework.db.connection.IDatabaseInfo; +import org.eclipse.osee.framework.db.connection.OseeDbConnection; +import org.eclipse.osee.framework.db.connection.exception.OseeDataStoreException; + +/** + * @author Andrew M. Finkbeiner + */ +public class MySqlLaunch { + private static final int NUMBER_OF_TRIES = 10; + private static final long SLEEP_TIME = 2000; + private String installLocation; + private IDatabaseInfo dbInfo; + + public MySqlLaunch(IDatabaseInfo dbInfo, String installLocation) { + this.installLocation = installLocation; + this.dbInfo = dbInfo; + } + + private void startMySql() throws IOException { + if (installLocation == null) { + System.out.println("install location null"); + throw new IllegalArgumentException( + "A `MySqlInfo` element in the oseeSiteConfig.xml file does not exist or has not specified a `InstallLocation` attribute."); + } + File exe = new File(installLocation, "bin/mysqld.exe"); + Runtime.getRuntime().exec(exe.getAbsolutePath()); + } + + public Connection getLocalMysqlConnection() throws IOException, InterruptedException { + startMySql(); + Connection connection = null; + for (int i = 0; i < NUMBER_OF_TRIES && connection == null; i++) { + Thread.sleep(SLEEP_TIME); + try { + connection = OseeDbConnection.getConnection(dbInfo); + } catch (OseeDataStoreException ex) { + } + } + return connection; + } +} diff --git a/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/NotOnProductionDbInitializationRule.java b/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/NotOnProductionDbInitializationRule.java new file mode 100644 index 00000000000..51d42a70e68 --- /dev/null +++ b/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/NotOnProductionDbInitializationRule.java @@ -0,0 +1,28 @@ +/*******************************************************************************
+ * 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.database;
+
+import org.eclipse.osee.framework.db.connection.DatabaseInfoManager;
+import org.eclipse.osee.framework.db.connection.exception.OseeCoreException;
+
+/**
+ * @author Roberto E. Escobar
+ */
+public class NotOnProductionDbInitializationRule implements IDbInitializationRule {
+
+ /* (non-Javadoc)
+ * @see org.eclipse.osee.framework.database.IDbInitializationRule#isAllowed()
+ */
+ @Override
+ public boolean isAllowed() throws OseeCoreException {
+ return !DatabaseInfoManager.getDefault().isProduction();
+ }
+}
diff --git a/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/PlatformRunnableAvailableInitTasks.java b/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/PlatformRunnableAvailableInitTasks.java new file mode 100644 index 00000000000..7ef6208013a --- /dev/null +++ b/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/PlatformRunnableAvailableInitTasks.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.database; + +import org.eclipse.core.runtime.IExtension; +import org.eclipse.core.runtime.IExtensionPoint; +import org.eclipse.core.runtime.Platform; +import org.eclipse.equinox.app.IApplication; +import org.eclipse.equinox.app.IApplicationContext; + +public class PlatformRunnableAvailableInitTasks implements IApplication { + + private void printExtensionPoints(String pointId) { + System.out.println("Point [" + pointId + "] search results:"); + IExtensionPoint point = Platform.getExtensionRegistry().getExtensionPoint(pointId); + if (point != null) { + for (IExtension ex : point.getExtensions()) { + System.out.println(" " + ex.getNamespaceIdentifier() + "/" + ex.getUniqueIdentifier()); + } + } + } + + /* + * (non-Javadoc) + * + * @see org.eclipse.equinox.app.IApplication#start(org.eclipse.equinox.app.IApplicationContext) + */ + public Object start(IApplicationContext context) throws Exception { + printExtensionPoints("org.eclipse.osee.framework.database.IDbInitializationTask"); + printExtensionPoints("org.eclipse.osee.framework.database.SkynetDbTypes"); + return null; + } + + /* + * (non-Javadoc) + * + * @see org.eclipse.equinox.app.IApplication#stop() + */ + public void stop() { + } +} diff --git a/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/SkynetTypesEnumGenerator.java b/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/SkynetTypesEnumGenerator.java new file mode 100644 index 00000000000..16e598845a4 --- /dev/null +++ b/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/SkynetTypesEnumGenerator.java @@ -0,0 +1,292 @@ +/******************************************************************************* + * 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.database; + +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileWriter; +import java.io.IOException; +import java.util.Arrays; +import java.util.Iterator; +import java.util.TreeSet; +import java.util.logging.Level; +import java.util.regex.Pattern; +import org.eclipse.osee.framework.jdk.core.util.io.xml.ExcelSaxHandler; +import org.eclipse.osee.framework.jdk.core.util.io.xml.RowProcessor; +import org.eclipse.osee.framework.logging.OseeLog; +import org.xml.sax.InputSource; +import org.xml.sax.SAXException; +import org.xml.sax.XMLReader; +import org.xml.sax.helpers.XMLReaderFactory; + +public class SkynetTypesEnumGenerator implements RowProcessor { + private static final Pattern nonJavaCharP = Pattern.compile("[^a-zA-Z_0-9]"); + + private static final String relationImports = + "import java.sql.SQLException;\n" + "import org.eclipse.osee.framework.skynet.core.artifact.Branch;\n" + "import org.eclipse.osee.framework.skynet.core.relation.IRelationEnumeration;\n" + "import org.eclipse.osee.framework.skynet.core.relation.RelationLink;\n" + "import org.eclipse.osee.framework.skynet.core.relation.RelationPersistenceManager;\n" + "import org.eclipse.osee.framework.skynet.core.relation.RelationSide;\n" + "import org.eclipse.osee.framework.skynet.core.relation.RelationType;\n" + "import org.eclipse.osee.framework.skynet.core.relation.RelationTypeManager;\n\n"; + + private static final String relationEnumCode = + " private boolean sideA;\n" + "\n" + " private String typeName;\n" + "\n" + " private CLASSNAME_PLACEHOLDER(boolean sideA, String typeName) {\n" + " this.sideA = sideA;\n" + " this.typeName = typeName;\n" + " RelationPersistenceManager.sideHash.put(typeName, sideA, this);\n" + " }\n" + " \n" + " public static IRelationEnumeration getRelationSide(String relationType, String relationSide, Branch branch) throws SQLException {\n" + " RelationType desc = RelationTypeManager.getType(relationType);\n" + " boolean isSideA = (desc.getSideAName().equals(relationSide));\n" + " return RelationPersistenceManager.sideHash.get(relationType, isSideA);\n" + " }\n" + "\n" + " /**\n" + " * @return Returns the sideName.\n" + " */\n" + " public boolean isSideA() {\n" + " return sideA;\n" + " }\n" + "\n" + " public String getSideName(Branch branch) throws SQLException {\n" + " if (isSideA())\n" + " return getRelationType().getSideAName();\n" + " else\n" + " return getRelationType().getSideBName();\n" + " }\n" + "\n" + " /**\n" + " * @return Returns the typeName.\n" + " */\n" + " public String getTypeName() {\n" + " return typeName;\n" + " }\n" + "\n" + " public RelationType getRelationType() throws SQLException {\n" + " return RelationTypeManager.getType(typeName);\n" + " }\n" + " \n" + " public boolean isThisType(RelationLink link) {\n" + " return link.getRelationType().getTypeName().equals(typeName);\n}\n\n" + " public RelationSide getSide() { \n" + " return sideA ? RelationSide.SIDE_A : RelationSide.SIDE_B;\n" + "}\n\n" + " public String getSideName() throws SQLException {\n" + " if (isSideA()) {\n" + " return getRelationType().getSideAName();\n" + " } else {\n" + " return getRelationType().getSideBName();\n}\n}\n"; + + private enum Table { + ARTIFACT_TYPE_TABLE, ATTRIBUTE_TYPE_TABLE, ATTRIBUTE_MAP_TABLE, RELATION_TYPE_TABLE, RELATION_SIDE_TABLE + } + + private static final String description = "Setup artifact, attribute, and relation type data"; + + private final ExcelSaxHandler excelHandler; + + private Table currentTable; + + private Iterator<Table> tableIterator; + + private boolean done; + + private final XMLReader xmlReader; + + private TreeSet<String> artifacts; + + private TreeSet<String> attributes; + + private TreeSet<String> relations; + + private String sheetName; + + private File destinationDir; + + private static final String skynetTypeCode = + " private String name;\n private CLASSNAME_PLACEHOLDER(String name){ this.name = name; }\n public String getName(){ return this.name;}\n"; + + /** + * @throws SAXException + */ + public SkynetTypesEnumGenerator() throws SAXException { + + excelHandler = new ExcelSaxHandler(this, true, true); + + xmlReader = XMLReaderFactory.createXMLReader(); + xmlReader.setContentHandler(excelHandler); + + artifacts = new TreeSet<String>(); + attributes = new TreeSet<String>(); + relations = new TreeSet<String>(); + } + + public void extractTypesFromSheet(File importFile, File destinationDir) throws IOException, SAXException { + done = false; + tableIterator = Arrays.asList(Table.values()).iterator(); + xmlReader.parse(new InputSource(new FileInputStream(importFile))); + + this.destinationDir = + (destinationDir != null && destinationDir.isDirectory()) ? destinationDir : importFile.getParentFile(); + } + + public void finish() throws IOException { + BufferedWriter out; + //relation enum gen + String relClassName = this.sheetName + "_RELATIONS"; + out = new BufferedWriter(new FileWriter(new File(destinationDir, relClassName + ".java"))); + out.append("\n\n"); + out.append(relationImports); + out.append("public enum "); + out.append(relClassName); + out.append(" implements IRelationEnumeration {\n"); + Iterator<String> it = relations.iterator(); + while (it.hasNext()) { + out.append(" "); + out.append(it.next()); + if (it.hasNext()) out.append(",\n"); + } + out.append(";\n"); + out.append(relationEnumCode.replace("CLASSNAME_PLACEHOLDER", relClassName)); + out.append("}"); + out.close(); + //attribute enum gen + String attrClassName = this.sheetName + "_ATTRIBUTES"; + out = new BufferedWriter(new FileWriter(new File(destinationDir, attrClassName + ".java"))); + out.append("\n\nimport org.eclipse.osee.framework.skynet.core.ISkynetType;\n\npublic enum "); + out.append(attrClassName); + out.append(" implements ISkynetType {\n"); + it = attributes.iterator(); + while (it.hasNext()) { + out.append(" "); + out.append(it.next()); + if (it.hasNext()) out.append(",\n"); + } + out.append(";\n\n"); + out.append(skynetTypeCode.replace("CLASSNAME_PLACEHOLDER", attrClassName)); + out.append("}"); + out.close(); + //artifact enum gen + String artClassName = this.sheetName + "_ARTIFACTS"; + out = new BufferedWriter(new FileWriter(new File(destinationDir, artClassName + ".java"))); + out.append("\n\nimport org.eclipse.osee.framework.skynet.core.ISkynetType;\n\npublic enum "); + out.append(artClassName); + out.append(" implements ISkynetType {\n"); + it = artifacts.iterator(); + while (it.hasNext()) { + out.append(" "); + out.append(it.next()); + if (it.hasNext()) out.append(",\n"); + } + out.append(";\n\n"); + out.append(skynetTypeCode.replace("CLASSNAME_PLACEHOLDER", artClassName)); + out.append("}"); + out.close(); + } + + public static String getDescription() { + return description; + } + + /* + * (non-Javadoc) + * + * @see osee.define.artifact.Import.RowProcessor#processHeaderRow(java.lang.String[]) + */ + public void processHeaderRow(String[] headerRow) { + if (done) return; + if (tableIterator.hasNext()) { + currentTable = tableIterator.next(); + } else { + throw new IllegalArgumentException( + "Encountered row past end of last expected table: " + Arrays.deepToString(headerRow)); + } + } + + /** + * import Artifacts + * + * @param row + */ + public void processRow(String[] row) { + if (done) return; + try { + switch (currentTable) { + case ARTIFACT_TYPE_TABLE: + addArtifactType(row); + break; + case ATTRIBUTE_TYPE_TABLE: + addAttributeType(row); + break; + case RELATION_TYPE_TABLE: + addRelationType(row); + break; + default: + break; + } + } catch (Exception ex) { + OseeLog.log(DatabaseActivator.class, Level.SEVERE, ex.toString(), ex); + } + } + + /** + * @param row + * @throws ClassNotFoundException + */ + private void addAttributeType(String[] row) throws ClassNotFoundException { + // String attrBaseType = row[0]; + // String attrProviderType = row[1]; + String attributeName = row[2]; + int index = attributeName.lastIndexOf("."); + if (index != -1 && index + 1 < attributeName.length()) { + attributeName = attributeName.substring(index + 1, attributeName.length()); + } + // String fileTypeExtension = row[3]; + // String defaultValue = row[4]; + // String validityXml = row[5]; + // int minOccurrence = getQuantity(row[6]); + // int maxOccurrence = getQuantity(row[7]); + // String tipText = row[8]; + + // if (fileTypeExtension == null) { + // fileTypeExtension = ""; + // } + + attributes.add(nonJavaCharP.matcher(attributeName).replaceAll("_").toUpperCase() + "(\"" + attributeName + "\")"); + } + + /** + * @param row + */ + private void addRelationType(String[] row) { + + String relationTypeName = row[0]; + String sideAName = row[1]; + // String A2BPhrase = row[2]; + String sideBName = row[3]; + // String B2APhrase = row[4]; + // String shortName = row[5]; + generateRelationSideEnum(relationTypeName, sideAName, sideBName); + } + + private void generateRelationSideEnum(String relationTypeName, String sideAName, String sideBName) { + sideAName = nonJavaCharP.matcher(sideAName).replaceAll("_").toUpperCase(); + sideBName = nonJavaCharP.matcher(sideBName).replaceAll("_").toUpperCase(); + String enumPrefix = nonJavaCharP.matcher(relationTypeName).replaceAll("_").toUpperCase(); + relations.add(String.format("%s__%s(true, \"%s\"),\n %s__%s(false, \"%s\")", enumPrefix, sideAName, + relationTypeName, enumPrefix, sideBName, relationTypeName)); + } + + /** + * @param row + */ + private void addArtifactType(String[] row) { + // String factoryClassName = row[0]; + String artifactTypeName = row[1]; + // String superTypeName = row[2]; + + artifacts.add(nonJavaCharP.matcher(artifactTypeName).replaceAll("_").toUpperCase() + "(\"" + artifactTypeName + "\")"); + } + + /* + * (non-Javadoc) + * + * @see osee.define.artifact.Import.RowProcessor#processEmptyRow(java.lang.String[]) + */ + public void processEmptyRow() { + } + + /* + * (non-Javadoc) + * + * @see osee.define.artifact.Import.RowProcessor#processCommentRow(java.lang.String[]) + */ + public void processCommentRow(String[] row) { + } + + /* + * (non-Javadoc) + * + * @see osee.define.artifact.Import.RowProcessor#reachedEndOfWorksheet() + */ + public void reachedEndOfWorksheet() { + done = true; + } + + /* + * (non-Javadoc) + * + * @see osee.define.artifact.Import.RowProcessor#detectedTotalRowCount(int) + */ + public void detectedRowAndColumnCounts(int rowCount, int columnCount) { + } + + /* + * (non-Javadoc) + * + * @see osee.define.artifact.Import.RowProcessor#foundStartOfWorksheet(java.lang.String) + */ + public void foundStartOfWorksheet(String sheetName) { + this.sheetName = nonJavaCharP.matcher(sheetName).replaceAll("_").toUpperCase(); + } +} diff --git a/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/config/SchemaConfigUtility.java b/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/config/SchemaConfigUtility.java new file mode 100644 index 00000000000..96d1e46d5cf --- /dev/null +++ b/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/config/SchemaConfigUtility.java @@ -0,0 +1,55 @@ +/******************************************************************************* + * 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.database.config; + +import java.io.IOException; +import java.net.URL; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import org.eclipse.osee.framework.database.data.SchemaData; +import org.eclipse.osee.framework.database.data.TableElement; + +/** + * @author Roberto E. Escobar + */ +public class SchemaConfigUtility { + + /** + * Reads files containing Schema Table information and groups tables by schema. + */ + public static Map<String, SchemaData> getUserDefinedConfig(List<URL> files) { + Map<String, SchemaData> userSpecifiedConfig = new HashMap<String, SchemaData>(); + + for (URL file : files) { + SchemaData schemaData; + try { + schemaData = TableConfigUtility.getInstance().getTableConfigData(file.openStream()); + List<TableElement> tables = schemaData.getTablesOrderedByDependency(); + for (TableElement table : tables) { + String schemaAddress = table.getSchema(); + + SchemaData schema = null; + if (!userSpecifiedConfig.containsKey(schemaAddress)) { + schema = new SchemaData(); + userSpecifiedConfig.put(schemaAddress, schema); + } else { + schema = userSpecifiedConfig.get(schemaAddress); + } + schema.addTableDefinition(table); + } + } catch (IOException e) { + e.printStackTrace(); + } + } + return userSpecifiedConfig; + } +} diff --git a/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/config/TableConfigUtility.java b/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/config/TableConfigUtility.java new file mode 100644 index 00000000000..e2eb8dba2c3 --- /dev/null +++ b/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/config/TableConfigUtility.java @@ -0,0 +1,235 @@ +/******************************************************************************* + * 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.database.config; + +import java.io.IOException; +import java.io.InputStream; +import java.util.List; +import java.util.logging.Level; +import javax.xml.parsers.ParserConfigurationException; +import org.eclipse.osee.framework.database.DatabaseActivator; +import org.eclipse.osee.framework.database.data.AppliesToClause; +import org.eclipse.osee.framework.database.data.ColumnMetadata; +import org.eclipse.osee.framework.database.data.ConstraintElement; +import org.eclipse.osee.framework.database.data.ConstraintFactory; +import org.eclipse.osee.framework.database.data.ConstraintTypes; +import org.eclipse.osee.framework.database.data.ForeignKey; +import org.eclipse.osee.framework.database.data.IndexElement; +import org.eclipse.osee.framework.database.data.ReferenceClause; +import org.eclipse.osee.framework.database.data.SchemaData; +import org.eclipse.osee.framework.database.data.TableElement; +import org.eclipse.osee.framework.database.data.AppliesToClause.AppliesToEntries; +import org.eclipse.osee.framework.database.data.AppliesToClause.OrderType; +import org.eclipse.osee.framework.database.data.ConstraintElement.ConstraintFields; +import org.eclipse.osee.framework.database.data.IndexElement.IndexFields; +import org.eclipse.osee.framework.database.data.ReferenceClause.OnDeleteEnum; +import org.eclipse.osee.framework.database.data.ReferenceClause.OnUpdateEnum; +import org.eclipse.osee.framework.database.data.ReferenceClause.ReferencesFields; +import org.eclipse.osee.framework.database.data.TableElement.ColumnFields; +import org.eclipse.osee.framework.database.data.TableElement.TableDescriptionFields; +import org.eclipse.osee.framework.database.data.TableElement.TableSections; +import org.eclipse.osee.framework.database.data.TableElement.TableTags; +import org.eclipse.osee.framework.jdk.core.util.xml.Jaxp; +import org.eclipse.osee.framework.logging.OseeLog; +import org.w3c.dom.Attr; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.NamedNodeMap; +import org.xml.sax.SAXException; + +/** + * @author Roberto E. Escobar + */ +public class TableConfigUtility { + + private static TableConfigUtility instance = null; + + private SchemaData parsedData; + private Document document; + + private TableConfigUtility() { + } + + public static TableConfigUtility getInstance() { + if (instance == null) instance = new TableConfigUtility(); + return instance; + } + + public SchemaData getTableConfigData(InputStream configFile) { + this.document = xmlFileToDocument(configFile); + this.parsedData = parseTableConfigData(); + return parsedData; + } + + public static Document xmlFileToDocument(InputStream configFile) { + Document document = null; + try { + document = Jaxp.readXmlDocument(configFile); + } catch (ParserConfigurationException ex) { + OseeLog.log(DatabaseActivator.class, Level.SEVERE, ex.toString(), ex); + } catch (SAXException ex) { + OseeLog.log(DatabaseActivator.class, Level.SEVERE, ex.toString(), ex); + } catch (IOException ex) { + OseeLog.log(DatabaseActivator.class, Level.SEVERE, ex.toString(), ex); + } + return document; + } + + private void parseTableDescription(Element element, TableElement tableEntry) { + NamedNodeMap attributes = element.getAttributes(); + for (int i = 0; i < attributes.getLength(); i++) { + Attr attribute = (Attr) attributes.item(i); + TableDescriptionFields tableField = TableDescriptionFields.valueOf(attribute.getName()); + tableEntry.addTableDescription(tableField, attribute.getValue()); + } + } + + private void parseColumnEntries(Element element, TableElement tableEntry) { + List<Element> columns = Jaxp.getChildDirects(element, TableSections.Column.name()); + for (Element column : columns) { + NamedNodeMap attributes = column.getAttributes(); + ColumnMetadata columnMetadata = new ColumnMetadata(""); + for (int i = 0; i < attributes.getLength(); i++) { + Attr attribute = (Attr) attributes.item(i); + ColumnFields columnField = ColumnFields.valueOf(attribute.getName()); + columnMetadata.addColumnField(columnField, attribute.getValue().toUpperCase()); + } + tableEntry.addColumn(columnMetadata); + } + } + + private void parseConstraintEntries(Element element, TableElement tableEntry) { + List<Element> constraints = Jaxp.getChildDirects(element, TableSections.Constraint.name()); + for (Element constraint : constraints) { + Attr type = constraint.getAttributeNode(ConstraintFields.type.name()); + Attr id = constraint.getAttributeNode(ConstraintFields.id.name()); + String schema = constraint.getAttribute(ConstraintFields.schema.name()); + String deferrable = constraint.getAttribute(ConstraintFields.deferrable.name()); + if (type != null && id != null) { + + ConstraintElement constraintElement = + ConstraintFactory.getConstraint(ConstraintTypes.textToType(type.getValue().toUpperCase()), + schema.toUpperCase(), id.getValue().toUpperCase(), + deferrable.equalsIgnoreCase(Boolean.toString(true))); + + Attr appliesTo = constraint.getAttributeNode(ConstraintFields.appliesTo.name()); + if (appliesTo != null) { + String[] columns = appliesTo.getValue().split(","); + for (String column : columns) { + constraintElement.addColumn(column.toUpperCase()); + } + } + + if (constraintElement instanceof ForeignKey) { + Element reference = Jaxp.getChildDirect(constraint, ReferenceClause.REFERENCES_TAG); + if (reference != null) { + Attr table = reference.getAttributeNode(ReferencesFields.table.name()); + Attr refColumn = reference.getAttributeNode(ReferencesFields.column.name()); + Attr onUpdate = reference.getAttributeNode(ReferencesFields.onUpdate.name()); + Attr onDelete = reference.getAttributeNode(ReferencesFields.onDelete.name()); + String refSchema = reference.getAttribute(ReferencesFields.schema.name()); + + if (table != null) { + + ReferenceClause references = + new ReferenceClause(refSchema.toUpperCase(), table.getValue().toUpperCase()); + if (refColumn != null) { + String[] columns = refColumn.getValue().split(","); + for (String column : columns) { + references.addColumn(column.toUpperCase()); + } + } + if (onUpdate != null) { + OnUpdateEnum[] values = OnUpdateEnum.values(); + for (OnUpdateEnum value : values) { + if (value.toString().equals(onUpdate.getValue().toUpperCase())) { + references.setOnUpdateAction(value); + } + } + } + if (onDelete != null) { + OnDeleteEnum[] values = OnDeleteEnum.values(); + for (OnDeleteEnum value : values) { + if (value.toString().equals(onDelete.getValue().toUpperCase())) { + references.setOnDeleteAction(value); + } + } + } + ((ForeignKey) constraintElement).addReference(references); + } + } + } + tableEntry.addConstraint(constraintElement); + } + } + } + + private void parseIndexDataEntries(Element element, TableElement tableEntry) { + List<Element> indexDataList = Jaxp.getChildDirects(element, TableSections.Index.name()); + for (Element indexDataEntry : indexDataList) { + String id = indexDataEntry.getAttribute(IndexFields.id.name()); + String ignore = indexDataEntry.getAttribute(IndexFields.mySqlIgnore.name()); + Attr indexType = indexDataEntry.getAttributeNode(IndexFields.type.name()); + String tablespace = indexDataEntry.getAttribute(IndexFields.tablespace.name()); + if (id.length() > 0) { + IndexElement indexData = new IndexElement(id); + if (Boolean.parseBoolean(ignore)) { + indexData.setMySqlIgnore(true); + } + if (indexType != null) { + indexData.setIndexType(indexType.getValue()); + } + if (tablespace != null) { + indexData.setTablespace(tablespace); + } + parseAppliesToClause(indexDataEntry, indexData); + tableEntry.addIndexData(indexData); + } + } + } + + public void parseAppliesToClause(Element element, IndexElement indexData) { + List<Element> appliesToList = Jaxp.getChildDirects(element, AppliesToClause.APPLIES_TO_TAG); + for (Element appliesToElement : appliesToList) { + String idString = appliesToElement.getAttribute(AppliesToEntries.id.name()); + String sortString = appliesToElement.getAttribute(AppliesToEntries.sort.name()); + if (idString.length() > 0) { + OrderType orderType = OrderType.Undefined; + if (sortString.equalsIgnoreCase("Ascending")) { + orderType = OrderType.Ascending; + } else if (sortString.equalsIgnoreCase("Descending")) { + orderType = OrderType.Descending; + } + indexData.addAppliesTo(idString, orderType); + } + } + } + + private SchemaData parseTableConfigData() { + if (document == null) { + return null; + } + SchemaData tableData = new SchemaData(); + List<Element> elements = Jaxp.getChildDirects(document.getDocumentElement(), TableTags.Table.name()); + for (Element element : elements) { + + TableElement tableEntry = new TableElement(); + + parseTableDescription(element, tableEntry); + parseColumnEntries(element, tableEntry); + parseConstraintEntries(element, tableEntry); + parseIndexDataEntries(element, tableEntry); + + tableData.addTableDefinition(tableEntry); + } + return tableData; + } +} diff --git a/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/core/IConfigClient.java b/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/core/IConfigClient.java new file mode 100644 index 00000000000..4824908fe0e --- /dev/null +++ b/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/core/IConfigClient.java @@ -0,0 +1,20 @@ +/******************************************************************************* + * 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.database.core; + +/** + * @author Roberto E. Escobar + */ +public interface IConfigClient { + + public abstract void startConfigClient(); + +} diff --git a/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/data/AppliesToClause.java b/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/data/AppliesToClause.java new file mode 100644 index 00000000000..a35368b7a64 --- /dev/null +++ b/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/data/AppliesToClause.java @@ -0,0 +1,94 @@ +/******************************************************************************* + * 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.database.data; + +import org.apache.commons.lang.builder.EqualsBuilder; +import org.apache.commons.lang.builder.HashCodeBuilder; +import org.eclipse.osee.framework.jdk.core.persistence.Xmlizable; +import org.w3c.dom.Document; +import org.w3c.dom.Element; + +/** + * @author Roberto E. Escobar + */ +public class AppliesToClause implements Xmlizable { + public static final String APPLIES_TO_TAG = "AppliesTo"; + + public enum OrderType { + Undefined, Ascending, Descending; + } + + public enum AppliesToEntries { + id, sort; + } + + private String columnName; + private OrderType orderType; + + public AppliesToClause(String columnName, OrderType orderType) { + this.columnName = columnName; + this.orderType = orderType; + } + + public String getColumnName() { + return columnName; + } + + public void setColumnName(String columnName) { + this.columnName = columnName; + } + + public OrderType getOrderType() { + return orderType; + } + + public void setOrderType(OrderType orderType) { + this.orderType = orderType; + } + + public String toString() { + return String.format("%s:[%s]\t%s:[%s]", AppliesToEntries.id.name(), columnName, AppliesToEntries.sort.name(), + orderType); + } + + @Override + public boolean equals(Object otherObject) { + if (otherObject instanceof AppliesToClause == false) { + return false; + } + if (this == otherObject) { + return true; + } + AppliesToClause that = (AppliesToClause) otherObject; + return new EqualsBuilder().appendSuper(super.equals(otherObject)).append(this.columnName, that.getColumnName()).append( + this.orderType, that.getOrderType()).isEquals(); + } + + @Override + public int hashCode() { + return new HashCodeBuilder(23, 37).append(columnName).append(orderType).toHashCode(); + } + + /* + * (non-Javadoc) + * + * @see org.eclipse.osee.framework.jdk.core.persistence.Xmlizable#toXml() + */ + public Element toXml(Document doc) { + Element element = doc.createElement(APPLIES_TO_TAG); + element.setAttribute(AppliesToEntries.id.name(), columnName); + if (!orderType.equals(OrderType.Undefined)) { + element.setAttribute(AppliesToEntries.sort.name(), orderType.name()); + } + return element; + } +} diff --git a/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/data/ColumnDbData.java b/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/data/ColumnDbData.java new file mode 100644 index 00000000000..94583df7eef --- /dev/null +++ b/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/data/ColumnDbData.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.database.data; + +/** + * @author Roberto E. Escobar + */ +public class ColumnDbData { + private String columnName; + private String columnValue; + + public ColumnDbData(String columnName, String columnValue) { + this.columnName = columnName; + this.columnValue = columnValue; + } + + public String getColumnName() { + return columnName; + } + + public String getColumnValue() { + return columnValue; + } + + public String toString() { + return "[" + columnName + ", " + columnValue + "]"; + } +} diff --git a/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/data/ColumnMetadata.java b/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/data/ColumnMetadata.java new file mode 100644 index 00000000000..efcd24e8dfb --- /dev/null +++ b/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/data/ColumnMetadata.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.database.data; + +import java.util.HashMap; +import java.util.Map; +import java.util.Set; +import org.apache.commons.lang.builder.EqualsBuilder; +import org.apache.commons.lang.builder.HashCodeBuilder; +import org.eclipse.osee.framework.database.data.TableElement.ColumnFields; +import org.eclipse.osee.framework.database.data.TableElement.TableSections; +import org.eclipse.osee.framework.jdk.core.persistence.Xmlizable; +import org.w3c.dom.Document; +import org.w3c.dom.Element; + +/** + * @author Roberto E. Escobar + */ +public class ColumnMetadata implements Xmlizable { + private Map<ColumnFields, String> columnFields; + + public ColumnMetadata(String columnId) { + columnFields = new HashMap<ColumnFields, String>(); + columnFields.put(ColumnFields.id, columnId); + } + + public String getId() { + return getColumnField(ColumnFields.id); + } + + public Map<ColumnFields, String> getColumnFields() { + return columnFields; + } + + public void addColumnField(ColumnFields field, String value) { + columnFields.put(field, value); + } + + public String getColumnField(ColumnFields field) { + if (columnFields.containsKey(field)) { + return columnFields.get(field); + } + return ""; + } + + @Override + public boolean equals(Object otherObject) { + if (otherObject instanceof ColumnMetadata == false) { + return false; + } + if (this == otherObject) { + return true; + } + ColumnMetadata that = (ColumnMetadata) otherObject; + return new EqualsBuilder().appendSuper(super.equals(otherObject)).append(this.columnFields, + that.getColumnFields()).isEquals(); + } + + @Override + public int hashCode() { + return new HashCodeBuilder(101, 83).append(columnFields).toHashCode(); + } + + public String toString() { + String toReturn = TableSections.Column + ": "; + Set<ColumnFields> keys = columnFields.keySet(); + for (ColumnFields field : keys) { + String value = columnFields.get(field); + toReturn += "\t" + field + "[" + value + "]"; + } + return toReturn; + } + + public Element toXml(Document doc) { + Element columnElement = doc.createElement(TableSections.Column.toString()); + for (ColumnFields key : columnFields.keySet()) { + columnElement.setAttribute(key.toString(), columnFields.get(key)); + } + return columnElement; + } +} diff --git a/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/data/ConstraintElement.java b/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/data/ConstraintElement.java new file mode 100644 index 00000000000..7d5ef6566fa --- /dev/null +++ b/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/data/ConstraintElement.java @@ -0,0 +1,141 @@ +/******************************************************************************* + * 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.database.data; + +import java.util.ArrayList; +import java.util.List; +import org.apache.commons.lang.builder.EqualsBuilder; +import org.apache.commons.lang.builder.HashCodeBuilder; +import org.eclipse.osee.framework.database.data.TableElement.TableSections; +import org.eclipse.osee.framework.jdk.core.persistence.Xmlizable; +import org.eclipse.osee.framework.jdk.core.util.StringFormat; +import org.w3c.dom.Document; +import org.w3c.dom.Element; + +/** + * @author Roberto E. Escobar + */ +public class ConstraintElement implements Xmlizable { + + public enum ConstraintFields { + id, schema, type, appliesTo, deferrable + }; + + private ConstraintTypes constraintType; + private boolean deferrable; + private String schema; + private String id; + private List<String> columns; + + public ConstraintElement(ConstraintTypes constraintType, String schema, String id, boolean deferrable) { + this.schema = schema.toUpperCase(); + this.schema = this.schema.trim(); + this.id = id.toUpperCase(); + this.id = this.id.trim(); + this.deferrable = deferrable; + this.constraintType = constraintType; + this.columns = new ArrayList<String>(); + } + + public List<String> getColumns() { + return columns; + } + + public String getId() { + return id; + } + + public String getSchema() { + return schema; + } + + public void addColumn(String columnName) { + columnName = columnName.toUpperCase(); + columnName = columnName.trim(); + this.columns.add(columnName); + } + + public void setId(String id) { + id = id.toUpperCase(); + id = id.trim(); + this.id = id; + } + + public void setSchema(String schema) { + schema = schema.toUpperCase(); + schema = schema.trim(); + this.schema = schema; + } + + public String getFullyQualifiedId() { + if (schema != null && !schema.equals("")) { + return schema + "." + id; + } else { + return id; + } + } + + /** + * @return Returns the deferrable. + */ + public boolean isDeferrable() { + return deferrable; + } + + public ConstraintTypes getConstraintType() { + return constraintType; + } + + public String getCommaSeparatedColumnsList() { + return StringFormat.listToCommaSeparatedString(columns); + } + + public String toString() { + String toReturn = TableSections.Constraint + ": "; + toReturn += "\t" + ConstraintFields.schema + "[" + schema + "]"; + toReturn += "\t" + ConstraintFields.id + "[" + id + "]"; + toReturn += "\t" + ConstraintFields.type + "[" + constraintType.toString() + "]"; + toReturn += "\t" + ConstraintFields.appliesTo + "[" + getCommaSeparatedColumnsList() + "]"; + toReturn += "\t" + ConstraintFields.deferrable + "[" + Boolean.toString(deferrable) + "]"; + return toReturn; + } + + public Element toXml(Document doc) { + Element constraintElement = doc.createElement(TableSections.Constraint.toString()); + constraintElement.setAttribute(ConstraintFields.schema.name(), schema); + constraintElement.setAttribute(ConstraintFields.id.name(), id); + constraintElement.setAttribute(ConstraintFields.type.name(), constraintType.toString()); + constraintElement.setAttribute(ConstraintFields.appliesTo.name(), getCommaSeparatedColumnsList()); + constraintElement.setAttribute(ConstraintFields.deferrable.name(), Boolean.toString(deferrable)); + return constraintElement; + } + + @Override + public boolean equals(Object otherObject) { + if (otherObject instanceof ConstraintElement == false) { + return false; + } + if (this == otherObject) { + return true; + } + ConstraintElement that = (ConstraintElement) otherObject; + return new EqualsBuilder().appendSuper(super.equals(otherObject)).append(this.constraintType, + that.getConstraintType()).append(this.schema, that.getSchema()).append(this.id, that.getId()).append( + this.columns, that.getColumns()).append(this.deferrable, that.deferrable).isEquals(); + } + + @Override + public int hashCode() { + return new HashCodeBuilder(37, 11).append(constraintType).append(schema).append(id).append(columns).append( + deferrable).toHashCode(); + } +} diff --git a/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/data/ConstraintFactory.java b/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/data/ConstraintFactory.java new file mode 100644 index 00000000000..652f102be48 --- /dev/null +++ b/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/data/ConstraintFactory.java @@ -0,0 +1,35 @@ +/******************************************************************************* + * 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.database.data; + +/** + * @author Roberto E. Escobar + */ +public class ConstraintFactory { + + public static ConstraintElement getConstraint(ConstraintTypes constraintType, String schema, String id, boolean deferrable) { + ConstraintElement element = null; + if (constraintType != null) { + switch (constraintType) { + case FOREIGN_KEY: + element = new ForeignKey(constraintType, schema, id, deferrable); + break; + case PRIMARY_KEY: + case UNIQUE: + case CHECK: + default: + element = new ConstraintElement(constraintType, schema, id, deferrable); + break; + } + } + return element; + } +} diff --git a/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/data/ConstraintTypes.java b/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/data/ConstraintTypes.java new file mode 100644 index 00000000000..65193668a94 --- /dev/null +++ b/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/data/ConstraintTypes.java @@ -0,0 +1,34 @@ +/******************************************************************************* + * 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.database.data; + +/** + * @author Roberto E. Escobar + */ +public enum ConstraintTypes { + PRIMARY_KEY, FOREIGN_KEY, UNIQUE, CHECK; + + public String toString() { + String toReturn = super.toString(); + toReturn = toReturn.replaceAll("_", " "); + return toReturn; + } + + public static ConstraintTypes textToType(String text) { + ConstraintTypes[] typesArray = ConstraintTypes.values(); + for (ConstraintTypes type : typesArray) { + if (type.toString().equals(text.toUpperCase())) { + return type; + } + } + return null; + } +} diff --git a/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/data/ForeignKey.java b/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/data/ForeignKey.java new file mode 100644 index 00000000000..c3acad999b5 --- /dev/null +++ b/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/data/ForeignKey.java @@ -0,0 +1,66 @@ +/******************************************************************************* + * 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.database.data; + +import java.util.ArrayList; +import java.util.List; +import java.util.Set; +import java.util.TreeSet; +import org.eclipse.osee.framework.jdk.core.persistence.Xmlizable; +import org.w3c.dom.Document; +import org.w3c.dom.Element; + +/** + * @author Roberto E. Escobar + */ +public class ForeignKey extends ConstraintElement implements Xmlizable { + + List<ReferenceClause> references; + + public ForeignKey(ConstraintTypes constraintType, String schema, String id, boolean deferrable) { + super(constraintType, schema, id, deferrable); + references = new ArrayList<ReferenceClause>(); + } + + public void addReference(ReferenceClause reference) { + references.add(reference); + } + + public List<ReferenceClause> getReferences() { + return references; + } + + public Set<String> getReferencedTables() { + Set<String> refTables = new TreeSet<String>(); + for (ReferenceClause ref : references) { + refTables.add(ref.getFullyQualifiedTableName()); + } + return refTables; + } + + @Override + public String toString() { + String toReturn = super.toString(); + for (ReferenceClause reference : references) { + toReturn += "\n\t\t" + reference.toString(); + } + return toReturn; + } + + @Override + public Element toXml(Document doc) { + Element parent = super.toXml(doc); + for (ReferenceClause reference : references) { + parent.appendChild(reference.toXml(doc)); + } + return parent; + } +} diff --git a/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/data/IndexElement.java b/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/data/IndexElement.java new file mode 100644 index 00000000000..9195bdf782d --- /dev/null +++ b/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/data/IndexElement.java @@ -0,0 +1,134 @@ +/******************************************************************************* + * 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.database.data; + +import java.util.ArrayList; +import java.util.List; +import org.apache.commons.lang.builder.EqualsBuilder; +import org.apache.commons.lang.builder.HashCodeBuilder; +import org.eclipse.osee.framework.database.data.AppliesToClause.OrderType; +import org.eclipse.osee.framework.jdk.core.persistence.Xmlizable; +import org.eclipse.osee.framework.jdk.core.util.Strings; +import org.w3c.dom.Document; +import org.w3c.dom.Element; + +/** + * @author Roberto E. Escobar + */ +public class IndexElement implements Xmlizable { + + public enum IndexFields { + id, mySqlIgnore, type, tablespace; + } + + private String id; + private String indexType; + private List<AppliesToClause> appliesToList; + private boolean ignoreMySql = false; + private String tablespace; + + public IndexElement(String id) { + this.id = id; + this.appliesToList = new ArrayList<AppliesToClause>(); + this.indexType = ""; + this.tablespace = ""; + } + + public void setId(String id) { + this.id = id; + } + + public String getId() { + return id; + } + + public void addAppliesTo(String name, OrderType type) { + appliesToList.add(new AppliesToClause(name, type)); + } + + public List<AppliesToClause> getAppliesToList() { + return appliesToList; + } + + public String toString() { + StringBuilder toReturn = new StringBuilder(); + toReturn.append(" Index: " + id); + toReturn.append(getAppliesToAsString()); + return toReturn.toString(); + } + + /* + * (non-Javadoc) + * + * @see org.eclipse.osee.framework.jdk.core.persistence.Xmlizable#toXml() + */ + public Element toXml(Document doc) { + Element element = doc.createElement(TableElement.TableSections.Index.name()); + element.setAttribute(IndexFields.id.name(), id); + for (AppliesToClause clause : appliesToList) { + element.appendChild(clause.toXml(doc)); + } + return element; + } + + public String getAppliesToAsString() { + StringBuilder toReturn = new StringBuilder(); + for (int index = 0; index < appliesToList.size(); index++) { + toReturn.append("\n\t\tApplies to " + appliesToList.get(index)); + } + return toReturn.toString(); + } + + @Override + public boolean equals(Object otherObject) { + if (otherObject instanceof IndexElement == false) { + return false; + } + if (this == otherObject) { + return true; + } + IndexElement that = (IndexElement) otherObject; + return new EqualsBuilder().appendSuper(super.equals(otherObject)).append(this.appliesToList, + that.getAppliesToList()).append(this.id, that.getId()).isEquals(); + } + + @Override + public int hashCode() { + return new HashCodeBuilder(113, 67).append(id).append(appliesToList).toHashCode(); + } + + public void setMySqlIgnore(boolean b) { + this.ignoreMySql = b; + } + + public void setIndexType(String indexType) { + if (indexType != null) { + this.indexType = indexType; + } + } + + public String getIndexType() { + return indexType; + } + + public boolean ignoreMySql() { + return this.ignoreMySql; + } + + public String getTablespace() { + return Strings.isValid(tablespace) ? tablespace : ""; + } + + public void setTablespace(String tablespace) { + this.tablespace = tablespace; + } +}
\ No newline at end of file diff --git a/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/data/ReferenceClause.java b/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/data/ReferenceClause.java new file mode 100644 index 00000000000..4a8521e5d7e --- /dev/null +++ b/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/data/ReferenceClause.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.database.data; + +import java.util.ArrayList; +import java.util.List; +import org.apache.commons.lang.builder.EqualsBuilder; +import org.apache.commons.lang.builder.HashCodeBuilder; +import org.eclipse.osee.framework.jdk.core.persistence.Xmlizable; +import org.eclipse.osee.framework.jdk.core.util.StringFormat; +import org.w3c.dom.Document; +import org.w3c.dom.Element; + +/** + * @author Roberto E. Escobar + */ +public class ReferenceClause implements Xmlizable { + public static final String REFERENCES_TAG = "References"; + + public enum ReferencesFields { + schema, table, column, onUpdate, onDelete; + } + + public enum OnDeleteEnum { + NO_ACTION, RESTRICT, CASCADE, SET_NULL, UNSPECIFIED; + + public String toString() { + String toReturn = super.toString(); + toReturn = toReturn.replaceAll("_", " "); + return toReturn; + } + } + + public enum OnUpdateEnum { + NO_ACTION, RESTRICT, UNSPECIFIED; + + public String toString() { + String toReturn = super.toString(); + toReturn = toReturn.replaceAll("_", " "); + return toReturn; + } + } + + private String schema; + private String table; + List<String> columns; + OnDeleteEnum onDeleteAction; + OnUpdateEnum onUpdateAction; + + public ReferenceClause(String schema, String table) { + this.schema = schema.toUpperCase(); + this.schema = this.schema.trim(); + this.table = table.toUpperCase(); + this.table = this.table.trim(); + this.columns = new ArrayList<String>(); + this.onDeleteAction = OnDeleteEnum.UNSPECIFIED; + this.onUpdateAction = OnUpdateEnum.UNSPECIFIED; + } + + public void setSchema(String schema) { + this.schema = schema; + } + + public OnDeleteEnum getOnDeleteAction() { + return onDeleteAction; + } + + public OnUpdateEnum getOnUpdateAction() { + return onUpdateAction; + } + + public void setOnDeleteAction(OnDeleteEnum onDeleteAction) { + this.onDeleteAction = onDeleteAction; + } + + public void setOnUpdateAction(OnUpdateEnum onUpdateAction) { + this.onUpdateAction = onUpdateAction; + } + + public void addColumn(String column) { + column = column.toUpperCase(); + column = column.trim(); + columns.add(column); + } + + public String getFullyQualifiedTableName() { + return schema + "." + table; + } + + public List<String> getColumns() { + return columns; + } + + public String getCommaSeparatedColumnsList() { + return StringFormat.listToCommaSeparatedString(columns); + } + + public String toString() { + String toReturn = REFERENCES_TAG + ": " + getFullyQualifiedTableName(); + toReturn += "\t["; + for (String column : columns) { + toReturn += column + " "; + } + toReturn += "]"; + return toReturn; + } + + public Element toXml(Document doc) { + Element refElement = doc.createElement(REFERENCES_TAG); + refElement.setAttribute(ReferencesFields.schema.name(), schema); + refElement.setAttribute(ReferencesFields.table.name(), table); + refElement.setAttribute(ReferencesFields.column.name(), getCommaSeparatedColumnsList()); + + if (!onDeleteAction.equals(OnDeleteEnum.UNSPECIFIED)) { + refElement.setAttribute(ReferencesFields.onDelete.name(), onDeleteAction.toString()); + } + + if (!onUpdateAction.equals(OnUpdateEnum.UNSPECIFIED)) { + refElement.setAttribute(ReferencesFields.onUpdate.name(), onUpdateAction.toString()); + } + return refElement; + } + + @Override + public boolean equals(Object otherObject) { + if (otherObject instanceof ReferenceClause == false) { + return false; + } + if (this == otherObject) { + return true; + } + ReferenceClause that = (ReferenceClause) otherObject; + return new EqualsBuilder().appendSuper(super.equals(otherObject)).append(this.getFullyQualifiedTableName(), + that.getFullyQualifiedTableName()).append(this.columns, that.getColumns()).append(this.onDeleteAction, + that.getOnDeleteAction()).append(this.onUpdateAction, that.getOnUpdateAction()).isEquals(); + } + + @Override + public int hashCode() { + return new HashCodeBuilder(113, 67).append(schema).append(table).append(columns).append(onDeleteAction).append( + onUpdateAction).toHashCode(); + } +} diff --git a/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/data/SchemaData.java b/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/data/SchemaData.java new file mode 100644 index 00000000000..075f1508804 --- /dev/null +++ b/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/data/SchemaData.java @@ -0,0 +1,262 @@ +/******************************************************************************* + * 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.database.data; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.TreeSet; +import javax.xml.parsers.ParserConfigurationException; +import org.apache.commons.lang.builder.EqualsBuilder; +import org.apache.commons.lang.builder.HashCodeBuilder; +import org.eclipse.osee.framework.database.data.TableElement.ColumnFields; +import org.eclipse.osee.framework.jdk.core.persistence.Xmlizable; +import org.eclipse.osee.framework.jdk.core.util.xml.Jaxp; +import org.w3c.dom.Document; +import org.w3c.dom.Element; + +/** + * @author Roberto E. Escobar + */ +public class SchemaData implements Xmlizable { + + public static final String ROOT_TAG = "TableConfig"; + private List<TableElement> tableDefinitions; + private SchemaDataLookup schemaLookup; + + private boolean isSorted; + + public SchemaData() { + this.tableDefinitions = new ArrayList<TableElement>(); + this.isSorted = false; + this.schemaLookup = new SchemaDataLookup(this); + } + + public SchemaDataLookup getLookUpStrategy() { + return schemaLookup; + } + + public List<TableElement> getTablesOrderedByDependency() { + sortTablesForConstraints(); + markIdentityColumns(); + return tableDefinitions; + } + + public Set<String> getTablesToBackup() { + Set<String> backupTables = new TreeSet<String>(); + for (TableElement table : tableDefinitions) { + if (table.isBackupDataSet()) { + backupTables.add(table.getFullyQualifiedTableName()); + } + } + return backupTables; + } + + public Map<String, Set<String>> getTablesToImport() { + Map<String, Set<String>> importTables = new HashMap<String, Set<String>>(); + for (TableElement table : tableDefinitions) { + if (table.isImportDataSet()) { + String importFrom = table.getImportFrom(); + Set<String> tableSet; + if (importTables.containsKey(importFrom)) { + tableSet = importTables.get(importFrom); + } else { + tableSet = new TreeSet<String>(); + } + tableSet.add(table.getFullyQualifiedTableName()); + importTables.put(importFrom, tableSet); + } + } + return importTables; + } + + public void addTableDefinition(TableElement table) { + tableDefinitions.add(table); + } + + public String toString() { + String toReturn = ""; + for (TableElement table : tableDefinitions) { + toReturn += table.toString(); + } + return toReturn; + } + + public Document getXmlDocument() throws ParserConfigurationException { + Document doc = Jaxp.newDocument(); + Element root = doc.createElement(ROOT_TAG); + doc.appendChild(root); + for (TableElement table : tableDefinitions) { + root.appendChild(table.toXml(doc)); + } + return doc; + } + + public Element toXml(Document doc) { + return null; + } + + private void sortTablesForConstraints() { + this.tableDefinitions = sortTablesForConstraints(this.tableDefinitions); + } + + private boolean canCreate(TableElement table, Set<String> canCreate) { + Set<String> dependencies = table.getTableDependency(); + if (canCreate.containsAll(dependencies)) { + return true; + } + return false; + } + + private void markIdentityColumns() { + for (TableElement aTable : tableDefinitions) { + determineIdentityColumns(aTable); + } + } + + private void determineIdentityColumns(TableElement tableDef) { + List<String> primaryKeys = new ArrayList<String>(); + + // first get all of the vars used for the primary key + List<ConstraintElement> constraints = tableDef.getConstraints(); + for (ConstraintElement constraint : constraints) { + if (constraint.getConstraintType().equals(ConstraintTypes.PRIMARY_KEY)) { + List<String> columns = constraint.getColumns(); + for (String column : columns) { + primaryKeys.add(column); + } + } + } + + // now go through and remove any of the primary key vars that are foreign keys + List<ForeignKey> foreignKeys = tableDef.getForeignKeyConstraints(); + for (ForeignKey fkConstraint : foreignKeys) { + List<String> columns = fkConstraint.getColumns(); + for (String column : columns) { + primaryKeys.remove(column); + } + } + + // now we should only be left with those primary keys that are identities. + // we set them by setting their corresponding identity column to true, a little hokey but that + // way we don't have to create special data structures for the column + Map<String, ColumnMetadata> columns = tableDef.getColumns(); + Set<String> columnKeys = columns.keySet(); + for (String key : columnKeys) { + ColumnMetadata column = columns.get(key); + if (primaryKeys.contains(column.getId())) { + column.addColumnField(ColumnFields.identity, Boolean.TRUE.toString()); + } + } + } + + private List<TableElement> sortTablesForConstraints(List<TableElement> tables) { + List<TableElement> sorted = new ArrayList<TableElement>(); + Set<String> canCreate = new HashSet<String>(); + + Map<TableElement, Boolean> toSort = new HashMap<TableElement, Boolean>(); + + for (TableElement aTable : tables) { + if (aTable.hasForeignKey()) { + toSort.put(aTable, false); + } else { + sorted.add(aTable); + canCreate.add(aTable.getFullyQualifiedTableName()); + } + } + + // Prevent for endless loops caused by + // foreign/primary key discrepancies + int guard = toSort.size() * 2; + int count = 0; + while (toSort.containsValue(false) && (count < guard)) { + Set<TableElement> elements = toSort.keySet(); + + for (TableElement aTable : elements) { + + if (!toSort.get(aTable)) { + if (canCreate(aTable, canCreate)) { + canCreate.add(aTable.getFullyQualifiedTableName()); + sorted.add(aTable); + toSort.put(aTable, true); + } + } + } + count++; + } + + // If we were stuck in an endless loop copy all unsortable tables + // to the end of the sorted array and return + if (toSort.containsValue(false)) { + Set<TableElement> elements = toSort.keySet(); + for (TableElement aTable : elements) { + if (!toSort.get(aTable)) { + canCreate.add(aTable.getFullyQualifiedTableName()); + sorted.add(aTable); + toSort.put(aTable, true); + } + } + } + + return sorted; + } + + @Override + public boolean equals(Object otherObject) { + if (otherObject instanceof SchemaData == false) { + return false; + } + if (this == otherObject) { + return true; + } + SchemaData that = (SchemaData) otherObject; + return hasEqualState(that); + } + + @Override + public int hashCode() { + return new HashCodeBuilder(37, 11).append(tableDefinitions).append(isSorted).append(schemaLookup).toHashCode(); + } + + public Map<String, TableElement> getTableMap() { + Map<String, TableElement> tableMap = new HashMap<String, TableElement>(); + for (TableElement table : tableDefinitions) { + tableMap.put(table.getFullyQualifiedTableName(), table); + } + return tableMap; + } + + public boolean hasEqualState(SchemaData that) { + EqualsBuilder equalsBuilder = new EqualsBuilder(); + equalsBuilder.appendSuper(super.equals(that)); + + Map<String, TableElement> thisTableMap = this.getTableMap(); + Map<String, TableElement> thatTableMap = that.getTableMap(); + + Set<String> thisKey1 = thisTableMap.keySet(); + Set<String> thatKey2 = thatTableMap.keySet(); + + boolean toReturn = true; + if (thisKey1.equals(thatKey2)) { + for (String key : thisKey1) { + equalsBuilder.append(thisTableMap.get(key), thatTableMap.get(key)); + } + toReturn &= equalsBuilder.isEquals(); + } else { + toReturn = false; + } + return toReturn; + } +} diff --git a/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/data/SchemaDataLookup.java b/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/data/SchemaDataLookup.java new file mode 100644 index 00000000000..5c2ba88f1f9 --- /dev/null +++ b/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/data/SchemaDataLookup.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.database.data; + +import java.util.List; +import java.util.Map; + +/** + * @author Roberto E. Escobar + */ +public class SchemaDataLookup { + + private SchemaData schemaData; + + public SchemaDataLookup(SchemaData schemaData) { + this.schemaData = schemaData; + } + + public ColumnMetadata getColumnDefinition(TableElement table, String columnId) { + Map<String, ColumnMetadata> columns = table.getColumns(); + return getColumnDefinition(columns, columnId); + } + + public static ColumnMetadata getColumnDefinition(Map<String, ColumnMetadata> columns, String columnId) { + if (columns.containsKey(columnId)) { + return columns.get(columnId); + } + return null; + } + + public TableElement getTableDefinition(String tableName) { + List<TableElement> list = schemaData.getTablesOrderedByDependency(); + for (TableElement table : list) { + return table; + } + return null; + } +} diff --git a/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/data/TableElement.java b/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/data/TableElement.java new file mode 100644 index 00000000000..8a5090eae86 --- /dev/null +++ b/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/data/TableElement.java @@ -0,0 +1,238 @@ +/******************************************************************************* + * 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.database.data; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.TreeSet; +import org.apache.commons.lang.builder.EqualsBuilder; +import org.apache.commons.lang.builder.HashCodeBuilder; +import org.eclipse.osee.framework.core.client.OseeClientProperties; +import org.eclipse.osee.framework.jdk.core.persistence.Xmlizable; +import org.eclipse.osee.framework.jdk.core.util.Strings; +import org.w3c.dom.Document; +import org.w3c.dom.Element; + + +/** + * @author Roberto E. Escobar + */ +public class TableElement implements Xmlizable { + + public enum TableTags{ + Table, ColumnInfo, Row; + } + + public enum TableSections { + Column, Constraint, Index; + }; + + public enum TableDescriptionFields { + name, schema, backupData, importData, importFrom, tablespace; + }; + + public enum ColumnFields { + id, type, limits, identity, defaultValue;; + }; + + private Map<TableDescriptionFields, String> tableDescription; + private Map<String, ColumnMetadata> columns; + private List<ConstraintElement> constraints; + private List<ForeignKey> foreignKeys; + private List<IndexElement> indeces; + + public TableElement() { + this.tableDescription = new HashMap<TableDescriptionFields, String>(); + this.columns = new HashMap<String, ColumnMetadata>(); + this.constraints = new ArrayList<ConstraintElement>(); + this.foreignKeys = new ArrayList<ForeignKey>(); + this.indeces = new ArrayList<IndexElement>(); + } + + public void addColumn(ColumnMetadata column) { + this.columns.put(column.getId(), column); + } + + public void addConstraint(ConstraintElement constraint) { + if(constraint instanceof ForeignKey){ + foreignKeys.add((ForeignKey)constraint); + } else { + constraints.add(constraint); + } + } + + public void addIndexData(IndexElement indexData){ + indeces.add(indexData); + } + + public String getSchema() { + return this.tableDescription.get(TableDescriptionFields.schema); + } + + public String getName() { + return this.tableDescription.get(TableDescriptionFields.name); + } + + public boolean isBackupDataSet(){ + if(this.tableDescription.containsKey(TableDescriptionFields.backupData)){ + return Boolean.parseBoolean(this.tableDescription.get(TableDescriptionFields.backupData)); + } + return false; + } + + public boolean isImportDataSet(){ + if(this.tableDescription.containsKey(TableDescriptionFields.importData)){ + return Boolean.parseBoolean(this.tableDescription.get(TableDescriptionFields.importData)); + } + return false; + } + + public String getImportFrom(){ + if(this.tableDescription.containsKey(TableDescriptionFields.importFrom)){ + return this.tableDescription.get(TableDescriptionFields.importFrom); + } + return OseeClientProperties.getTableImportSource(); + } + + public void addTableDescription(TableDescriptionFields field, String value){ + if(!field.equals(TableDescriptionFields.importFrom)){ + value = value.toUpperCase(); + } + value = value.trim(); + this.tableDescription.put(field, value); + } + + public Map<String, ColumnMetadata> getColumns(){ + return this.columns; + } + + public Map<TableDescriptionFields, String> getDescription(){ + return this.tableDescription; + } + + public boolean hasForeignKey(){ + return foreignKeys.size() > 0; + } + + public String getFullyQualifiedTableName(){ + if(getSchema()==null) + return getName(); + else + return getSchema() + "." + getName(); + } + + public List<ConstraintElement> getConstraints(){ + return constraints; + } + + public List<ForeignKey> getForeignKeyConstraints(){ + return foreignKeys; + } + + public List<IndexElement> getIndexData(){ + return indeces; + } + + public String toString(){ + StringBuilder toReturn = new StringBuilder(); + toReturn.append(" Table : \n"); + Set<TableDescriptionFields> keys = tableDescription.keySet(); + for(TableDescriptionFields key : keys){ + toReturn.append(" \t" + key.toString() + ": " + tableDescription.get(key)); + } + toReturn.append("\n"); + int count = 0; + Set<String> columnKeys = columns.keySet(); + for(String key : columnKeys){ + toReturn.append("\t[" + ++count + "] " + columns.get(key).toString() + "\n"); + } + count = 0; + for(ConstraintElement constraint : constraints){ + toReturn.append("\t[" + ++count + "] " + constraint.toString() + "\n"); + } + for(ForeignKey fkeys : foreignKeys){ + toReturn.append("\t[" + ++count + "] " + fkeys.toString() + "\n"); + } + count = 0; + for(IndexElement iData : indeces){ + toReturn.append("\t[" + ++count + "] " + iData.toString() + "\n"); + } + return toReturn.toString(); + } + + /** + * @param doc The XML document we're creating the XML for + * @return The XML Element corresponding to this + */ + public Element toXml(Document doc) { + Element tableElement = doc.createElement(TableTags.Table.name()); + for(TableDescriptionFields key : tableDescription.keySet()){ + tableElement.setAttribute(key.toString(), tableDescription.get(key)); + } + for(String key : columns.keySet()) { + tableElement.appendChild(columns.get(key).toXml(doc)); + } + for(ConstraintElement constraint : constraints){ + tableElement.appendChild(constraint.toXml(doc)); + } + for(ForeignKey constraint : foreignKeys){ + tableElement.appendChild(constraint.toXml(doc)); + } + for(IndexElement iData : indeces){ + tableElement.appendChild(iData.toXml(doc)); + } + return tableElement; + } + + public Set<String> getTableDependency(){ + Set<String> dependency = new TreeSet<String>(); + for(ForeignKey fk : foreignKeys){ + Set<String> refTables = fk.getReferencedTables(); + for(String tableName : refTables){ + dependency.add(tableName); + } + } + return dependency; + } + + + @Override + public boolean equals(Object otherObject) { + if (otherObject instanceof TableElement == false) { + return false; + } + if (this == otherObject) { + return true; + } + TableElement that = (TableElement) otherObject; + return new EqualsBuilder().appendSuper(super.equals(otherObject)) + .append(this.tableDescription, that.getDescription()) + .append(this.columns, that.getColumns()) + .append(this.constraints, that.getConstraints()) + .append(this.foreignKeys, that.getForeignKeyConstraints()) + .append(this.indeces, that.getIndexData()) + .isEquals(); + } + + @Override + public int hashCode() { + return new HashCodeBuilder(79, 17).append(tableDescription).append(columns) + .append(constraints).append(foreignKeys).append(indeces).toHashCode(); + } + + public String getTablespace() { + String toReturn = getDescription().get(TableDescriptionFields.tablespace); + return Strings.isValid(toReturn) ? toReturn : ""; + } +} diff --git a/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/initialize/DatabaseInitializationOperation.java b/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/initialize/DatabaseInitializationOperation.java new file mode 100644 index 00000000000..ff01d04042c --- /dev/null +++ b/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/initialize/DatabaseInitializationOperation.java @@ -0,0 +1,288 @@ +/******************************************************************************* + * 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.database.initialize; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.net.URL; +import java.net.URLConnection; +import java.util.List; +import java.util.logging.Level; +import org.apache.commons.lang.time.StopWatch; +import org.eclipse.core.runtime.IConfigurationElement; +import org.eclipse.core.runtime.IExtension; +import org.eclipse.core.runtime.InvalidRegistryObjectException; +import org.eclipse.core.runtime.Platform; +import org.eclipse.osee.framework.core.client.OseeClientProperties; +import org.eclipse.osee.framework.database.DatabaseActivator; +import org.eclipse.osee.framework.database.IDbInitializationRule; +import org.eclipse.osee.framework.database.IDbInitializationTask; +import org.eclipse.osee.framework.database.utility.GroupSelection; +import org.eclipse.osee.framework.db.connection.DatabaseInfoManager; +import org.eclipse.osee.framework.db.connection.IDatabaseInfo; +import org.eclipse.osee.framework.db.connection.OseeConnection; +import org.eclipse.osee.framework.db.connection.OseeDbConnection; +import org.eclipse.osee.framework.db.connection.exception.OseeCoreException; +import org.eclipse.osee.framework.db.connection.exception.OseeDataStoreException; +import org.eclipse.osee.framework.jdk.core.util.Strings; +import org.eclipse.osee.framework.logging.OseeLog; +import org.osgi.framework.Bundle; + +/** + * @author Roberto E. Escobar + */ +public class DatabaseInitializationOperation { + private static final String dbInitExtensionPointId = "org.eclipse.osee.framework.database.IDbInitializationTask"; + private static BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in)); + + private final String preSelectedChoice; + private final boolean isPromptEnabled; + + private DatabaseInitializationOperation(String preSelectedChoice, boolean isPromptEnabled) { + this.preSelectedChoice = preSelectedChoice; + this.isPromptEnabled = isPromptEnabled; + } + + private boolean isPromptingAllowed() { + return isPromptEnabled; + } + + private String getPreSelectedChoice() { + return preSelectedChoice; + } + + private void execute() throws OseeCoreException { + boolean isConfigured = false; + if (checkPreconditions()) { + IDatabaseInfo dbInfo = DatabaseInfoManager.getDefault(); + String dbName = dbInfo.getDatabaseName(); + String userName = dbInfo.getDatabaseLoginName(); + + String line = null; + if (isPromptEnabled) { + System.out.println("\nAre you sure you want to configure: " + dbName + ":" + userName); + line = waitForUserResponse(); + } else { + line = "Y"; + } + if (line.equalsIgnoreCase("Y")) { + isConfigured = true; + OseeLog.log(DatabaseActivator.class, Level.INFO, "Configuring Database..."); + StopWatch stopWatch = new StopWatch(); + stopWatch.start(); + + OseeConnection connection = OseeDbConnection.getConnection(dbInfo); + try { + processTask(connection); + } catch (Throwable ex) { + OseeLog.log(DatabaseActivator.class, Level.SEVERE, ex); + } finally { + connection.close(); + stopWatch.stop(); + System.out.println(String.format("Database Configurationg completed in [%s] ms", stopWatch)); + } + } + } + + if (isConfigured != true) { + System.out.println("Database will not be configured. "); + } + } + + private void processTask(OseeConnection connection) throws InvalidRegistryObjectException { + OseeLog.log(DatabaseInitializationOperation.class, Level.INFO, "Begin Database Initialization..."); + + for (String pointId : getDbInitTasks()) { + IExtension extension = Platform.getExtensionRegistry().getExtension(pointId); + if (extension == null) { + OseeLog.log(DatabaseActivator.class, Level.SEVERE, "Unable to locate extension [" + pointId + "]"); + } else { + String extsionPointId = extension.getExtensionPointUniqueIdentifier(); + if (dbInitExtensionPointId.equals(extsionPointId)) { + try { + runDbInitTasks(extension, connection); + } catch (Throwable th) { + OseeLog.log(DatabaseActivator.class, Level.SEVERE, th); + } + } else { + OseeLog.log(DatabaseInitializationOperation.class, Level.SEVERE, + "Unknown extension id [" + extsionPointId + "] from extension [" + pointId + "]"); + } + } + } + OseeLog.log(DatabaseActivator.class, Level.INFO, "Database Initialization Complete."); + } + + /** + * Call to get DB initialization Tasks from choice made by User + * + * @return initialization task list + */ + private List<String> getDbInitTasks() { + String selectedChoice = null; + GroupSelection selector = GroupSelection.getInstance(); + List<String> choices = selector.getChoices(); + if (choices.size() == 1) { + selectedChoice = choices.get(0); + } else { + int selection = -1; + if (Strings.isValid(getPreSelectedChoice())) { + selection = choices.indexOf(getPreSelectedChoice()); + } + if (selection <= -1) { + selectedChoice = getInitChoiceFromUser("Select Init Group To Run.", choices); + } + } + OseeLog.log(DatabaseActivator.class, Level.INFO, String.format("DB Config Choice Selected: [%s]", selectedChoice)); + return selector.getDbInitTasksByChoiceEntry(selectedChoice); + } + + private static String getInitChoiceFromUser(String message, List<String> choices) { + int selection = -1; + BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in)); + while (selection == -1) { + try { + System.out.println(message); + for (int i = 0; i < choices.size(); i++) { + System.out.println(" " + i + ") " + choices.get(i)); + } + System.out.println("Enter: 0 - " + (choices.size() - 1)); + String line = stdin.readLine(); + selection = Integer.parseInt(line); + if (selection < 0 || selection >= choices.size()) { + System.out.println("Invalid selection: Index [" + selection + "] is out of range."); + selection = -1; + } + } catch (Exception ex) { + System.out.println("Invalid selection: Index [" + selection + "] is out of range."); + ex.printStackTrace(); + } + } + return choices.get(selection); + } + + /** + * @param skynetDbTypesExtensions + * @param extensionIds + * @throws OseeCoreException + * @throws ClassNotFoundException + * @throws IllegalAccessException + * @throws InstantiationException + */ + private static void runDbInitTasks(IExtension extension, OseeConnection connection) throws OseeCoreException, InstantiationException, IllegalAccessException, ClassNotFoundException { + IConfigurationElement[] elements = extension.getConfigurationElements(); + String classname = null; + String bundleName = null; + String initRuleClassName = null; + for (IConfigurationElement el : elements) { + if (el.getName().equals("DatabaseTask")) { + classname = el.getAttribute("classname"); + bundleName = el.getContributor().getName(); + initRuleClassName = el.getAttribute("DbInitRule"); + } + } + if (classname != null && bundleName != null) { + Bundle bundle = Platform.getBundle(bundleName); + boolean isExecutionAllowed = true; + if (Strings.isValid(initRuleClassName)) { + isExecutionAllowed = false; + Class<?> taskClass = bundle.loadClass(initRuleClassName); + IDbInitializationRule rule = (IDbInitializationRule) taskClass.newInstance(); + isExecutionAllowed = rule.isAllowed(); + } + + OseeLog.log(DatabaseActivator.class, isExecutionAllowed ? Level.INFO : Level.WARNING, String.format( + "%s [%s] execution rule [%s]", isExecutionAllowed ? "Starting" : "Skipping", + extension.getUniqueIdentifier(), Strings.isValid(initRuleClassName) ? initRuleClassName : "Default")); + if (isExecutionAllowed) { + IDbInitializationTask task = (IDbInitializationTask) bundle.loadClass(classname).newInstance(); + task.run(connection); + } + } + } + + private String waitForUserResponse() { + System.out.println("Enter: [Y|N]\n"); + String line = "N"; + + if (!isPromptingAllowed()) { + line = "Y"; + } else { + try { + line = stdin.readLine(); + } catch (IOException ex) { + OseeLog.log(DatabaseActivator.class, Level.SEVERE, ex); + } + } + return line; + } + + private boolean isApplicationServerAlive(String applicationServerUrl) { + boolean canConnection = false; + try { + URL url = new URL(applicationServerUrl); + URLConnection connection = url.openConnection(); + connection.connect(); + canConnection = true; + } catch (Exception ex) { + + } + return canConnection; + } + + private boolean checkPreconditions() throws OseeCoreException { + IDatabaseInfo dbInfo = DatabaseInfoManager.getDefault(); + + String serverUrl = OseeClientProperties.getOseeApplicationServer(); + if (Strings.isValid(serverUrl) != true) { + throw new OseeDataStoreException( + String.format( + "Invalid resource server address [%s]. Database initialization requires an application server to be set by default. ", + serverUrl)); + } + + if (dbInfo.isProduction()) { + System.err.println(String.format( + "You are not allowed to run config client against production: [%s].\nExiting.", dbInfo.getDatabaseName())); + return true; + } + + boolean serverOk = isApplicationServerAlive(serverUrl); + System.out.println(String.format("OSEE Application Server Validation [%s]", serverOk ? "PASSED" : "FAILED")); + if (serverOk != true) { + System.err.println(String.format( + "Error connecting to application server [%s].\n" + "Please ensure server is running and try again.", + serverUrl)); + return false; + } + + return true; + } + + public static void executeWithoutPrompting(String choice) throws OseeCoreException { + new DatabaseInitializationOperation(choice, false).execute(); + } + + public static void executeWithPromptsAndChoice(String choice) throws OseeCoreException { + new DatabaseInitializationOperation(choice, false).execute(); + } + + public static void executeWithPrompts() throws OseeCoreException { + new DatabaseInitializationOperation(null, true).execute(); + } + + public static void executeConfigureFromJvmProperties() throws OseeCoreException { + boolean arePromptsAllowed = OseeClientProperties.promptOnDbInit(); + String predefinedChoice = OseeClientProperties.getChoiceOnDbInit(); + new DatabaseInitializationOperation(predefinedChoice, arePromptsAllowed).execute(); + } +} diff --git a/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/initialize/DbFactory.java b/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/initialize/DbFactory.java new file mode 100644 index 00000000000..6bccf278465 --- /dev/null +++ b/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/initialize/DbFactory.java @@ -0,0 +1,63 @@ +/******************************************************************************* + * 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.database.initialize; + +import java.sql.Connection; +import java.util.List; +import org.eclipse.osee.framework.database.data.SchemaData; +import org.eclipse.osee.framework.database.data.TableElement; +import org.eclipse.osee.framework.database.sql.SqlFactory; +import org.eclipse.osee.framework.database.sql.SqlManager; +import org.eclipse.osee.framework.db.connection.exception.OseeDataStoreException; +import org.eclipse.osee.framework.db.connection.info.SupportedDatabase; + +/** + * @author Roberto E. Escobar + */ +public class DbFactory { + + private SchemaData schemaData; + protected SqlManager sqlManager; + protected Connection connection; + + public DbFactory(Connection connection, SupportedDatabase databaseType, SchemaData schemaData) { + this.schemaData = schemaData; + this.connection = connection; + this.sqlManager = SqlFactory.getSqlManager(databaseType); + } + + public void createTables() throws OseeDataStoreException { + List<TableElement> tableDefs = schemaData.getTablesOrderedByDependency(); + for (TableElement tableDef : tableDefs) { + sqlManager.createTable(connection, tableDef); + } + } + + public void dropTables() throws OseeDataStoreException { + List<TableElement> tableDefs = schemaData.getTablesOrderedByDependency(); + for (int index = (tableDefs.size() - 1); index >= 0; index--) { + TableElement tableDef = tableDefs.get(index); + sqlManager.dropTable(connection, tableDef); + } + } + + public void createIndeces() throws OseeDataStoreException { + for (TableElement tableDef : schemaData.getTableMap().values()) { + sqlManager.createIndex(connection, tableDef); + } + } + + public void dropIndeces() throws OseeDataStoreException { + for (TableElement tableDef : schemaData.getTableMap().values()) { + sqlManager.dropIndex(connection, tableDef); + } + } +} diff --git a/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/initialize/tasks/ImportDataFromDbService.java b/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/initialize/tasks/ImportDataFromDbService.java new file mode 100644 index 00000000000..5b6894e6819 --- /dev/null +++ b/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/initialize/tasks/ImportDataFromDbService.java @@ -0,0 +1,230 @@ +/******************************************************************************* + * 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.database.initialize.tasks; + +import java.io.File; +import java.sql.Connection; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.TreeSet; +import org.eclipse.osee.framework.core.client.OseeClientProperties; +import org.eclipse.osee.framework.database.IDbInitializationTask; +import org.eclipse.osee.framework.database.data.SchemaData; +import org.eclipse.osee.framework.database.data.TableElement; +import org.eclipse.osee.framework.database.utility.DatabaseDataExtractor; +import org.eclipse.osee.framework.database.utility.DatabaseSchemaExtractor; +import org.eclipse.osee.framework.database.utility.FileUtility; +import org.eclipse.osee.framework.db.connection.DatabaseInfoManager; +import org.eclipse.osee.framework.db.connection.IDatabaseInfo; +import org.eclipse.osee.framework.db.connection.OseeConnection; +import org.eclipse.osee.framework.db.connection.OseeDbConnection; +import org.eclipse.osee.framework.db.connection.exception.OseeCoreException; +import org.eclipse.osee.framework.db.connection.exception.OseeDataStoreException; +import org.eclipse.osee.framework.jdk.core.util.Strings; + +public class ImportDataFromDbService implements IDbInitializationTask { + private final Map<String, SchemaData> userSpecifiedConfig; + private static final File backupDirectory = new File("BackupDirectory"); + + public ImportDataFromDbService(Map<String, SchemaData> userSpecifiedConfig) { + this.userSpecifiedConfig = userSpecifiedConfig; + } + + public void run(OseeConnection connection) throws OseeCoreException { + Set<String> importConnections = getImportConnections(); + for (String importFromDbService : importConnections) { + System.out.println("Import Table Data from Db: " + importFromDbService); + + IDatabaseInfo dbInfo = DatabaseInfoManager.getDataStoreById(importFromDbService); + OseeConnection importConnection = OseeDbConnection.getConnection(dbInfo); + if (importConnection != null) { + try { + System.out.println("Gathering information from ..." + importFromDbService); + + String userName = dbInfo.getDatabaseLoginName(); + if (userName != null && !userName.equals("")) { + + Set<String> schemasToGet = new TreeSet<String>(); + schemasToGet.add(userName.toUpperCase()); + + Map<String, Set<String>> dataToImport = + getTablesToImport(importConnection, userName.toUpperCase(), schemasToGet); + if (dataToImport.size() > 0) { + System.out.println(dataToImport.toString().replaceAll(", ", "\n")); + makeBackupDirectoryIfItDoesntExist(); + + System.out.println("Backing up Files to: " + backupDirectory.getAbsolutePath()); + DatabaseDataExtractor dbDataExtractor = + new DatabaseDataExtractor(importConnection, schemasToGet, backupDirectory); + + Set<String> tablesToImport; + if (importFromDbService.equals(determineDefaultConnection())) { + tablesToImport = dataToImport.get(OseeClientProperties.getTableImportSource()); + } else { + tablesToImport = dataToImport.get(importFromDbService); + } + + for (String importTable : tablesToImport) { + dbDataExtractor.addTableNameToExtract(importTable); + } + dbDataExtractor.extract(); + dbDataExtractor.waitForWorkerThreads(); + + prepareFilesForImport(); + } + + } + } finally { + importConnection.close(); + } + } + } + } + + private void prepareFilesForImport() { + Set<String> keys = userSpecifiedConfig.keySet(); + if (keys.size() == 1) { + String userName = ""; + for (String temp : keys) { + userName = temp; + } + List<File> files = FileUtility.getDBDataFileList(backupDirectory); + for (File fileName : files) { + String filename = fileName.getAbsolutePath().toString(); + filename = filename.substring(filename.lastIndexOf(File.separator) + 1, filename.length()); + filename = filename.substring(filename.indexOf(".") + 1, filename.length()); + fileName.renameTo(new File(backupDirectory + File.separator + userName + "." + filename)); + } + } + } + + private String determineDefaultConnection() { + String importFromDbService = System.getProperty(OseeClientProperties.getTableImportSource()); + if (!Strings.isValid(importFromDbService)) { + importFromDbService = "oracle"; + } + return importFromDbService; + } + + private Set<String> getImportConnections() { + String defaultConnection = determineDefaultConnection(); + Set<String> userSchemas = userSpecifiedConfig.keySet(); + Set<String> connectionsNeeded = new TreeSet<String>(); + for (String key : userSchemas) { + SchemaData schemaDataInUserConfig = userSpecifiedConfig.get(key); + Map<String, Set<String>> tableNamesToImport = schemaDataInUserConfig.getTablesToImport(); + Set<String> keys = tableNamesToImport.keySet(); + for (String connectionString : keys) { + if (connectionString.equals(OseeClientProperties.getTableImportSource())) { + connectionsNeeded.add(defaultConnection); + } else { + connectionsNeeded.add(connectionString); + } + } + } + return connectionsNeeded; + } + + public boolean canRun() { + return true; + } + + private Map<String, SchemaData> getAvailableSchemasFromImportDb(Connection importConnection, Set<String> schemas) throws OseeDataStoreException { + DatabaseSchemaExtractor schemaExtractor = new DatabaseSchemaExtractor(importConnection, schemas); + schemaExtractor.extractSchemaData(); + return schemaExtractor.getSchemas(); + } + + private Map<String, Set<String>> getTablesToImport(Connection importConnection, String userName, Set<String> schemasToGet) throws OseeDataStoreException { + Map<String, SchemaData> currentDbSchemas = getAvailableSchemasFromImportDb(importConnection, schemasToGet); + Set<String> userSchemas = userSpecifiedConfig.keySet(); + + SchemaData schemaData = currentDbSchemas.get(userName); + Map<String, TableElement> tableMap = schemaData.getTableMap(); + + Map<String, Set<String>> importTables = new HashMap<String, Set<String>>(); + for (String key : userSchemas) { + SchemaData schemaDataInUserConfig = userSpecifiedConfig.get(key); + Map<String, Set<String>> tableNamesToImport = schemaDataInUserConfig.getTablesToImport(); + + Set<String> keys = tableNamesToImport.keySet(); + for (String importKey : keys) { + Set<String> namesToImport = tableNamesToImport.get(importKey); + + for (String tableName : namesToImport) { + tableName = tableName.replaceAll(key + "\\.", userName + "."); + + if (tableMap.containsKey(tableName)) { + Set<String> tableSet; + if (importTables.containsKey(importKey)) { + tableSet = importTables.get(importKey); + } else { + tableSet = new TreeSet<String>(); + } + tableSet.add(tableName); + importTables.put(importKey, tableSet); + } + } + } + } + return importTables; + } + + private void makeBackupDirectoryIfItDoesntExist() { + if (backupDirectory != null && backupDirectory.exists() && backupDirectory.canWrite()) { + return; + } else { + backupDirectory.mkdirs(); + } + } + + /* (non-Javadoc) + * @see org.eclipse.osee.framework.database.initialize.tasks.IDbInitializationTask#setDependancies(java.util.List) + */ + public void setDependancies(List<String> bundles) { + } + + /* (non-Javadoc) + * @see org.eclipse.osee.framework.database.initialize.tasks.IDbInitializationTask#getBundle() + */ + public String getBundle() { + return null; + } + + /* (non-Javadoc) + * @see org.eclipse.osee.framework.database.initialize.tasks.IDbInitializationTask#getDependancies() + */ + public List<String> getDependancies() { + return null; + } + + /* (non-Javadoc) + * @see org.eclipse.osee.framework.database.initialize.tasks.IDbInitializationTask#setBundle(java.lang.String) + */ + public void setBundle(String bundle) { + } + + /* (non-Javadoc) + * @see java.lang.Comparable#compareTo(java.lang.Object) + */ + public int compareTo(IDbInitializationTask o) { + return 0; + } + + /* (non-Javadoc) + * @see java.lang.Comparable#compareTo(java.lang.Object) + */ + public int compareTo(Object o) { + return 0; + } +}
\ No newline at end of file diff --git a/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/initialize/tasks/PostDatabaseInitialization.java b/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/initialize/tasks/PostDatabaseInitialization.java new file mode 100644 index 00000000000..da0c391811f --- /dev/null +++ b/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/initialize/tasks/PostDatabaseInitialization.java @@ -0,0 +1,46 @@ +/*
+ * Created on Aug 12, 2008
+ *
+ * PLACE_YOUR_DISTRIBUTION_STATEMENT_RIGHT_HERE
+ */
+package org.eclipse.osee.framework.database.initialize.tasks;
+
+import java.util.logging.Level;
+import org.eclipse.osee.framework.database.IDbInitializationTask;
+import org.eclipse.osee.framework.db.connection.ConnectionHandler;
+import org.eclipse.osee.framework.db.connection.OseeConnection;
+import org.eclipse.osee.framework.db.connection.exception.OseeCoreException;
+import org.eclipse.osee.framework.db.connection.info.SupportedDatabase;
+import org.eclipse.osee.framework.logging.OseeLog;
+
+/**
+ * @author Roberto E. Escobar
+ */
+public class PostDatabaseInitialization implements IDbInitializationTask {
+
+ private static final String POSTGRESQL_VACUUM_AND_STATS = "VACUUM FULL VERBOSE ANALYZE";
+ private static final String ORACLE_GATHER_STATS =
+ "begin DBMS_STATS.GATHER_SCHEMA_STATS (ownname => '', estimate_percent => 99," + " granularity => 'ALL', degree => NULL , cascade => TRUE); end;";
+
+ /* (non-Javadoc)
+ * @see org.eclipse.osee.framework.database.initialize.tasks.IDbInitializationTask#run(java.sql.Connection)
+ */
+ @Override
+ public void run(OseeConnection connection) throws OseeCoreException {
+ OseeLog.log(PostDatabaseInitialization.class, Level.INFO, "Running Post-Initialization Process...");
+ SupportedDatabase supportedDb = SupportedDatabase.getDatabaseType(connection);
+ switch (supportedDb) {
+ case postgresql:
+ OseeLog.log(PostDatabaseInitialization.class, Level.INFO, "Vacuumiing PostgreSQL");
+ ConnectionHandler.runPreparedUpdate(POSTGRESQL_VACUUM_AND_STATS);
+ break;
+ case oracle:
+ OseeLog.log(PostDatabaseInitialization.class, Level.INFO, "Gathering Oracle Statistics");
+ ConnectionHandler.runPreparedUpdate(ORACLE_GATHER_STATS);
+ break;
+ default:
+ OseeLog.log(PostDatabaseInitialization.class, Level.INFO, "No - postdbinit process to run");
+ break;
+ }
+ }
+}
diff --git a/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/initialize/tasks/PrintTables.java b/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/initialize/tasks/PrintTables.java new file mode 100644 index 00000000000..29d0e8a9a72 --- /dev/null +++ b/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/initialize/tasks/PrintTables.java @@ -0,0 +1,94 @@ +/******************************************************************************* + * 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.database.initialize.tasks; + +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.ResultSetMetaData; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.Map; +import java.util.Set; +import org.eclipse.osee.framework.database.IDbInitializationTask; +import org.eclipse.osee.framework.database.data.SchemaData; +import org.eclipse.osee.framework.db.connection.OseeConnection; +import org.eclipse.osee.framework.db.connection.exception.OseeCoreException; + +public class PrintTables implements IDbInitializationTask { + + private Map<String, SchemaData> userConfig; + + public PrintTables(Map<String, SchemaData> userConfig) { + super(); + this.userConfig = userConfig; + } + + public void run(OseeConnection connection) throws OseeCoreException { + Set<String> keys = userConfig.keySet(); + for (String key : keys) { + SchemaData schemaData = userConfig.get(key); + Set<String> tables = schemaData.getTableMap().keySet(); + for (String tableName : tables) { + printTable(connection, tableName); + } + } + } + + private void printTable(Connection connection, String tableName) { + Statement statement = null; + ResultSet resultSet = null; + try { + statement = connection.createStatement(); + resultSet = statement.executeQuery("select * from " + tableName); + ResultSetMetaData resultSetMetaData = resultSet.getMetaData(); + int numberOfColumns = resultSetMetaData.getColumnCount(); + String header = "\nTable:\t" + tableName + "\n"; + header += "Columns:\t"; + for (int index = 1; index <= numberOfColumns; index++) { + header += resultSetMetaData.getColumnLabel(index); + if (index + 1 <= numberOfColumns) { + header += ", "; + } + } + header += "\n"; + + System.out.print(header); + + String results = ""; + while (resultSet.next()) { + results = "Data:\t"; + for (int index = 1; index <= numberOfColumns; index++) { + results += resultSet.getObject(index).toString(); + if (index + 1 <= numberOfColumns) { + results += ", "; + } + } + results += "\n"; + System.out.print(results); + } + } catch (SQLException ex) { + ex.printStackTrace(); + } finally { + try { + if (resultSet != null) { + resultSet.close(); + } + } catch (Exception ex) { + } + try { + if (statement != null) { + statement.close(); + } + } catch (Exception ex) { + } + } + } +} diff --git a/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/initialize/tasks/relational/BackupTableData.java b/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/initialize/tasks/relational/BackupTableData.java new file mode 100644 index 00000000000..12e7799c3aa --- /dev/null +++ b/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/initialize/tasks/relational/BackupTableData.java @@ -0,0 +1,128 @@ +/******************************************************************************* + * 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.database.initialize.tasks.relational; + +import java.io.File; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.TreeSet; +import org.eclipse.osee.framework.database.IDbInitializationTask; +import org.eclipse.osee.framework.database.data.SchemaData; +import org.eclipse.osee.framework.database.data.TableElement; +import org.eclipse.osee.framework.database.utility.DatabaseDataExtractor; +import org.eclipse.osee.framework.db.connection.OseeConnection; +import org.eclipse.osee.framework.db.connection.exception.OseeCoreException; + +public class BackupTableData implements IDbInitializationTask { + private Set<String> schemas; + private Map<String, SchemaData> userSpecifiedConfig; + private Map<String, SchemaData> currentDatabaseConfig; + private static final File backupDirectory = new File("BackupDirectory"); + + public BackupTableData(Set<String> schemas, Map<String, SchemaData> userSpecifiedConfig, Map<String, SchemaData> currentDatabaseConfig) { + this.schemas = schemas; + this.userSpecifiedConfig = userSpecifiedConfig; + this.currentDatabaseConfig = currentDatabaseConfig; + } + + public void run(OseeConnection connection) throws OseeCoreException { + System.out.println("BackupTableData: "); + Set<String> dataToBackup = getTablesToBackup(); + if (dataToBackup.size() > 0) { + System.out.println(dataToBackup.toString().replaceAll(", ", "\n")); + clearBackupDirectory(); + DatabaseDataExtractor dbDataExtractor = new DatabaseDataExtractor(connection, schemas, backupDirectory); + Set<String> backupTables = dataToBackup; + for (String backupTable : backupTables) { + dbDataExtractor.addTableNameToExtract(backupTable); + } + dbDataExtractor.extract(); + dbDataExtractor.waitForWorkerThreads(); + } + } + + public boolean canRun() { + return true; + } + + private Set<String> getTablesToBackup() { + Set<String> backupTables = new TreeSet<String>(); + Set<String> userSchemas = userSpecifiedConfig.keySet(); + for (String key : userSchemas) { + // Backup data only if data exists in the current database + if (currentDatabaseConfig.containsKey(key)) { + SchemaData schemaDataInDb = currentDatabaseConfig.get(key); + Map<String, TableElement> currentDbTableMap = schemaDataInDb.getTableMap(); + Set<String> currentDbTableNames = currentDbTableMap.keySet(); + + SchemaData schemaData = userSpecifiedConfig.get(key); + Set<String> tableNamesToBackup = schemaData.getTablesToBackup(); + for (String tableName : tableNamesToBackup) { + // Check that table we want to backup exists in the database + // before we add it to the list + if (currentDbTableNames.contains(tableName)) { + backupTables.add(tableName); + } else { + System.out.println("Table doesn't exist in Db. Unable to backup [" + tableName + "]"); + } + } + } else { + System.out.println("Schema doesn't exist in Db. Unable to backup tables from schema [" + key + "]"); + } + } + return backupTables; + } + + private void clearBackupDirectory() { + if (backupDirectory != null && backupDirectory.exists() && backupDirectory.canWrite()) { + File[] fileList = backupDirectory.listFiles(); + for (File fileToDelete : fileList) { + fileToDelete.delete(); + } + backupDirectory.delete(); + backupDirectory.mkdirs(); + } + } + + /* (non-Javadoc) + * @see org.eclipse.osee.framework.database.initialize.tasks.IDbInitializationTask#getBundle() + */ + public String getBundle() { + return null; + } + + /* (non-Javadoc) + * @see org.eclipse.osee.framework.database.initialize.tasks.IDbInitializationTask#getDependancies() + */ + public List<String> getDependancies() { + return null; + } + + /* (non-Javadoc) + * @see org.eclipse.osee.framework.database.initialize.tasks.IDbInitializationTask#setBundle(java.lang.String) + */ + public void setBundle(String bundle) { + } + + /* (non-Javadoc) + * @see org.eclipse.osee.framework.database.initialize.tasks.IDbInitializationTask#setDependancies(java.util.List) + */ + public void setDependancies(List<String> bundles) { + } + + /* (non-Javadoc) + * @see java.lang.Comparable#compareTo(java.lang.Object) + */ + public int compareTo(Object o) { + return 0; + } +}
\ No newline at end of file diff --git a/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/initialize/tasks/relational/RestoreTableData.java b/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/initialize/tasks/relational/RestoreTableData.java new file mode 100644 index 00000000000..8b8b3492210 --- /dev/null +++ b/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/initialize/tasks/relational/RestoreTableData.java @@ -0,0 +1,133 @@ +/******************************************************************************* + * 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.database.initialize.tasks.relational; + +import java.io.File; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Set; +import org.eclipse.osee.framework.database.IDbInitializationTask; +import org.eclipse.osee.framework.database.data.SchemaData; +import org.eclipse.osee.framework.database.data.TableElement; +import org.eclipse.osee.framework.database.sql.SqlFactory; +import org.eclipse.osee.framework.database.sql.SqlManager; +import org.eclipse.osee.framework.database.utility.DatabaseDataImporter; +import org.eclipse.osee.framework.db.connection.OseeConnection; +import org.eclipse.osee.framework.db.connection.exception.OseeCoreException; +import org.eclipse.osee.framework.db.connection.info.SupportedDatabase; + +public class RestoreTableData implements IDbInitializationTask { + private Set<String> schemas; + private Map<String, SchemaData> userSpecifiedConfig; + private SupportedDatabase databaseType; + private static final File backupDirectory = new File("backupDirectory"); + + public RestoreTableData(Set<String> schemas, Map<String, SchemaData> userSpecifiedConfig, SupportedDatabase databaseType) { + this.schemas = schemas; + this.userSpecifiedConfig = userSpecifiedConfig; + this.databaseType = databaseType; + } + + public void run(OseeConnection connection) throws OseeCoreException { + System.out.println("RestoreTables"); + System.out.flush(); + SqlManager sqlManager = SqlFactory.getSqlManager(databaseType); + + for (String schemaKey : schemas) { + if (userSpecifiedConfig.containsKey(schemaKey)) { + DatabaseDataImporter importer = new DatabaseDataImporter(connection, backupDirectory, sqlManager); + SchemaData schemaData = userSpecifiedConfig.get(schemaKey); + + setImportOrder(importer, schemaData); + setTablesToImport(importer, schemaData); + importer.setSchemaToImportTo(schemaKey); + + importer.importDataIntoDatabase(); + } + } + + clearBackupDirectory(); + } + + private void setImportOrder(DatabaseDataImporter importer, SchemaData schemaData) { + List<String> importOrder = new ArrayList<String>(); + + List<TableElement> tables = schemaData.getTablesOrderedByDependency(); + for (TableElement table : tables) { + importOrder.add(table.getFullyQualifiedTableName()); + } + importer.setImportOrder(importOrder); + } + + private void setTablesToImport(DatabaseDataImporter importer, SchemaData schemaData) { + importer.clearTableFilter(); + Set<String> selectedTables = schemaData.getTablesToBackup(); + for (String tableName : selectedTables) { + importer.addToTableFilter(tableName); + } + Map<String, Set<String>> importedTables = schemaData.getTablesToImport(); + Set<String> keys = importedTables.keySet(); + for (String key : keys) { + Set<String> tables = importedTables.get(key); + for (String tableName : tables) { + importer.addToTableFilter(tableName); + } + } + } + + public boolean canRun() { + return true; + } + + private void clearBackupDirectory() { + if (backupDirectory != null && backupDirectory.exists() && backupDirectory.canWrite()) { + File[] fileList = backupDirectory.listFiles(); + for (File fileToDelete : fileList) { + fileToDelete.delete(); + } + backupDirectory.delete(); + } + } + + /* (non-Javadoc) + * @see org.eclipse.osee.framework.database.initialize.tasks.IDbInitializationTask#getBundle() + */ + public String getBundle() { + return null; + } + + /* (non-Javadoc) + * @see org.eclipse.osee.framework.database.initialize.tasks.IDbInitializationTask#getDependancies() + */ + public List<String> getDependancies() { + return null; + } + + /* (non-Javadoc) + * @see org.eclipse.osee.framework.database.initialize.tasks.IDbInitializationTask#setBundle(java.lang.String) + */ + public void setBundle(String bundle) { + } + + /* (non-Javadoc) + * @see org.eclipse.osee.framework.database.initialize.tasks.IDbInitializationTask#setDependancies(java.util.List) + */ + public void setDependancies(List<String> bundles) { + } + + /* (non-Javadoc) + * @see java.lang.Comparable#compareTo(java.lang.Object) + */ + public int compareTo(Object o) { + return 0; + } +} diff --git a/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/sql/DerbySqlManager.java b/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/sql/DerbySqlManager.java new file mode 100644 index 00000000000..2605a96de1b --- /dev/null +++ b/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/sql/DerbySqlManager.java @@ -0,0 +1,124 @@ +/*******************************************************************************
+ * 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.database.sql;
+
+import java.util.List;
+import java.util.Map;
+import java.util.logging.Level;
+import org.eclipse.osee.framework.database.DatabaseActivator;
+import org.eclipse.osee.framework.database.data.ConstraintElement;
+import org.eclipse.osee.framework.database.data.ForeignKey;
+import org.eclipse.osee.framework.database.data.ReferenceClause;
+import org.eclipse.osee.framework.database.data.ReferenceClause.OnDeleteEnum;
+import org.eclipse.osee.framework.database.data.ReferenceClause.OnUpdateEnum;
+import org.eclipse.osee.framework.database.data.TableElement.ColumnFields;
+import org.eclipse.osee.framework.database.sql.datatype.SqlDataType;
+import org.eclipse.osee.framework.db.connection.info.SQL3DataType;
+import org.eclipse.osee.framework.logging.OseeLog;
+
+/**
+ * @author Roberto E. Escobar
+ */
+public class DerbySqlManager extends SqlManagerImpl {
+
+ /**
+ * @param logger
+ * @param sqlDataType
+ */
+ public DerbySqlManager(SqlDataType sqlDataType) {
+ super(sqlDataType);
+ }
+
+ /* (non-Javadoc)
+ * @see org.eclipse.osee.framework.database.sql.SqlManager#constraintDataToSQL(org.eclipse.osee.framework.database.data.ConstraintElement, java.lang.String)
+ */
+ @Override
+ public String constraintDataToSQL(ConstraintElement constraint, String tableID) {
+ StringBuilder toReturn = new StringBuilder();
+ String id = formatQuotedString(constraint.getId(), "\\.");
+ String type = constraint.getConstraintType().toString();
+ String appliesTo = formatQuotedString(constraint.getCommaSeparatedColumnsList(), ",");
+
+ if (id != null && !id.equals("") && appliesTo != null && !appliesTo.equals("")) {
+ toReturn.append("CONSTRAINT " + id + " " + type + " (" + appliesTo + ")");
+
+ if (constraint instanceof ForeignKey) {
+ ForeignKey fk = (ForeignKey) constraint;
+ List<ReferenceClause> refs = fk.getReferences();
+
+ for (ReferenceClause ref : refs) {
+ String refTable = formatQuotedString(ref.getFullyQualifiedTableName(), "\\.");
+ String refColumns = formatQuotedString(ref.getCommaSeparatedColumnsList(), ",");
+
+ String onUpdate = "";
+ if (!ref.getOnUpdateAction().equals(OnUpdateEnum.UNSPECIFIED)) {
+ onUpdate = "ON UPDATE " + ref.getOnUpdateAction().toString();
+ }
+
+ String onDelete = "";
+ if (!ref.getOnDeleteAction().equals(OnDeleteEnum.UNSPECIFIED)) {
+ onDelete = "ON DELETE " + ref.getOnDeleteAction().toString();
+ }
+
+ if (refTable != null && refColumns != null && !refTable.equals("") && !refColumns.equals("")) {
+ toReturn.append(" REFERENCES " + refTable + " (" + refColumns + ")");
+ if (!onUpdate.equals("")) {
+ toReturn.append(" " + onUpdate);
+ }
+
+ if (!onDelete.equals("")) {
+ toReturn.append(" " + onDelete);
+ }
+
+ // Not Supported in Derby ?
+ // if (constraint.isDeferrable()) {
+ // toReturn.append(" DEFERRABLE");
+ // }
+ }
+
+ else {
+ OseeLog.log(DatabaseActivator.class, Level.WARNING,
+ "Skipping CONSTRAINT at Table: " + tableID + "\n\t " + fk.toString());
+ }
+
+ }
+ }
+ } else {
+ OseeLog.log(DatabaseActivator.class, Level.WARNING,
+ "Skipping CONSTRAINT at Table: " + tableID + "\n\t " + constraint.toString());
+ }
+ return toReturn.toString();
+ }
+
+ public String columnDataToSQL(Map<ColumnFields, String> column) {
+ StringBuilder toReturn = new StringBuilder();
+
+ String columnLimits = column.get(ColumnFields.limits);
+ String defaultValue = column.get(ColumnFields.defaultValue);
+
+ SQL3DataType dataType = SQL3DataType.valueOf(column.get(ColumnFields.type));
+ columnLimits = sqlDataType.getLimit(dataType, columnLimits);
+ toReturn.append("\"");
+ toReturn.append(column.get(ColumnFields.id));
+ toReturn.append("\"");
+ toReturn.append(" ");
+ toReturn.append(sqlDataType.getType(dataType));
+
+ if (columnLimits != null && !columnLimits.equals("")) {
+ toReturn.append(" (" + columnLimits + ")");
+ }
+ if (defaultValue != null && !defaultValue.equals("")) {
+ toReturn.append(" " + defaultValue);
+ }
+ return toReturn.toString();
+ }
+}
diff --git a/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/sql/MysqlSqlManager.java b/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/sql/MysqlSqlManager.java new file mode 100644 index 00000000000..acb20db11f7 --- /dev/null +++ b/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/sql/MysqlSqlManager.java @@ -0,0 +1,159 @@ +/******************************************************************************* + * 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.database.sql; + +import java.sql.Connection; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.logging.Level; +import org.eclipse.osee.framework.database.DatabaseActivator; +import org.eclipse.osee.framework.database.data.ColumnMetadata; +import org.eclipse.osee.framework.database.data.ConstraintElement; +import org.eclipse.osee.framework.database.data.ForeignKey; +import org.eclipse.osee.framework.database.data.IndexElement; +import org.eclipse.osee.framework.database.data.ReferenceClause; +import org.eclipse.osee.framework.database.data.TableElement; +import org.eclipse.osee.framework.database.data.ReferenceClause.OnDeleteEnum; +import org.eclipse.osee.framework.database.data.ReferenceClause.OnUpdateEnum; +import org.eclipse.osee.framework.database.data.TableElement.ColumnFields; +import org.eclipse.osee.framework.database.sql.datatype.SqlDataType; +import org.eclipse.osee.framework.db.connection.ConnectionHandler; +import org.eclipse.osee.framework.db.connection.exception.OseeDataStoreException; +import org.eclipse.osee.framework.jdk.core.util.StringFormat; +import org.eclipse.osee.framework.logging.OseeLog; + +/** + * @author Andrew M. Finkbeiner + */ +public class MysqlSqlManager extends SqlManagerImpl { + + /** + * @param sqlDataType + */ + public MysqlSqlManager(SqlDataType sqlDataType) { + super(sqlDataType); + } + + private String handleColumnCreationSection(Connection connection, Map<String, ColumnMetadata> columns) { + List<String> lines = new ArrayList<String>(); + Set<String> keys = columns.keySet(); + for (String key : keys) { + Map<ColumnFields, String> column = columns.get(key).getColumnFields(); + lines.add(columnDataToSQL(column)); + } + String toExecute = StringFormat.listToValueSeparatedString(lines, ",\n"); + return toExecute; + } + + public void createTable(Connection connection, TableElement tableDef) throws OseeDataStoreException { + String toExecute = "CREATE TABLE " + tableDef.getFullyQualifiedTableName() + " ( \n"; + toExecute += handleColumnCreationSection(connection, tableDef.getColumns()); + toExecute += handleConstraintCreationSection(tableDef.getConstraints(), tableDef.getFullyQualifiedTableName()); + toExecute += + handleConstraintCreationSection(tableDef.getForeignKeyConstraints(), tableDef.getFullyQualifiedTableName()); + toExecute += " \n)\n"; + OseeLog.log(DatabaseActivator.class, Level.INFO, + "Creating Table: [ " + tableDef.getFullyQualifiedTableName() + "]"); + ConnectionHandler.runPreparedUpdate(connection, toExecute); + } + + @Override + public void dropTable(Connection connection, TableElement tableDef) throws OseeDataStoreException { + String toExecute = "DROP TABLE " + formatQuotedString(tableDef.getFullyQualifiedTableName(), "\\."); + OseeLog.log(DatabaseActivator.class, Level.INFO, + "Dropping Table: [ " + tableDef.getFullyQualifiedTableName() + "]"); + ConnectionHandler.runPreparedUpdate(connection, toExecute); + } + + protected String formatQuotedString(String value, String splitAt) { + String[] array = value.split(splitAt); + for (int index = 0; index < array.length; index++) { + array[index] = array[index]; + } + // return value; + return StringFormat.separateWith(array, splitAt.replaceAll("\\\\", "")); + } + + public void dropIndex(Connection connection, TableElement tableDef) throws OseeDataStoreException { + List<IndexElement> tableIndeces = tableDef.getIndexData(); + String tableName = tableDef.getFullyQualifiedTableName(); + for (IndexElement iData : tableIndeces) { + if (iData.ignoreMySql()) continue; + OseeLog.log(DatabaseActivator.class, Level.INFO, String.format("Dropping Index: [%s] FROM [%s]", + iData.getId(), tableName)); + if (iData.getId().equals("PRIMARY")) { + ConnectionHandler.runPreparedUpdate(connection, + "ALTER TABLE " + tableDef.getFullyQualifiedTableName() + " DROP PRIMARY KEY"); + } else { + ConnectionHandler.runPreparedUpdate(connection, + "ALTER TABLE " + tableDef.getFullyQualifiedTableName() + " DROP INDEX " + iData.getId()); + } + } + } + + public String constraintDataToSQL(ConstraintElement constraint, String tableID) { + StringBuilder toReturn = new StringBuilder(); + String id = formatQuotedString(constraint.getId(), "\\."); + String type = constraint.getConstraintType().toString(); + String appliesTo = formatQuotedString(constraint.getCommaSeparatedColumnsList(), ","); + + if (id != null && !id.equals("") && appliesTo != null && !appliesTo.equals("")) { + toReturn.append("CONSTRAINT " + id + " " + type + " (" + appliesTo + ")"); + + if (constraint instanceof ForeignKey) { + ForeignKey fk = (ForeignKey) constraint; + List<ReferenceClause> refs = fk.getReferences(); + + for (ReferenceClause ref : refs) { + String refTable = formatQuotedString(ref.getFullyQualifiedTableName(), "\\."); + String refColumns = formatQuotedString(ref.getCommaSeparatedColumnsList(), ","); + + String onUpdate = ""; + if (!ref.getOnUpdateAction().equals(OnUpdateEnum.UNSPECIFIED)) { + onUpdate = "ON UPDATE " + ref.getOnUpdateAction().toString(); + } + + String onDelete = ""; + if (!ref.getOnDeleteAction().equals(OnDeleteEnum.UNSPECIFIED)) { + onDelete = "ON DELETE " + ref.getOnDeleteAction().toString(); + } + + if (refTable != null && refColumns != null && !refTable.equals("") && !refColumns.equals("")) { + toReturn.append(" REFERENCES " + refTable + " (" + refColumns + ")"); + if (!onUpdate.equals("")) { + toReturn.append(" " + onUpdate); + } + + if (!onDelete.equals("")) { + toReturn.append(" " + onDelete); + } + + // if (constraint.isDeferrable()) { + // toReturn.append(" DEFERRABLE"); + // } + } + + else { + OseeLog.log(DatabaseActivator.class, Level.WARNING, + "Skipping CONSTRAINT at Table: " + tableID + "\n\t " + fk.toString()); + } + + } + } + } else { + OseeLog.log(DatabaseActivator.class, Level.WARNING, + "Skipping CONSTRAINT at Table: " + tableID + "\n\t " + constraint.toString()); + } + return toReturn.toString(); + } +} diff --git a/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/sql/OracleSqlManager.java b/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/sql/OracleSqlManager.java new file mode 100644 index 00000000000..6ef0d15505f --- /dev/null +++ b/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/sql/OracleSqlManager.java @@ -0,0 +1,87 @@ +/******************************************************************************* + * 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.database.sql; + +import java.sql.Connection; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.logging.Level; +import org.eclipse.osee.framework.database.DatabaseActivator; +import org.eclipse.osee.framework.database.data.ColumnMetadata; +import org.eclipse.osee.framework.database.data.IndexElement; +import org.eclipse.osee.framework.database.data.TableElement; +import org.eclipse.osee.framework.database.data.TableElement.ColumnFields; +import org.eclipse.osee.framework.database.sql.datatype.SqlDataType; +import org.eclipse.osee.framework.db.connection.ConnectionHandler; +import org.eclipse.osee.framework.db.connection.exception.OseeDataStoreException; +import org.eclipse.osee.framework.jdk.core.util.StringFormat; +import org.eclipse.osee.framework.logging.OseeLog; + +/** + * @author Roberto E. Escobar + */ +public class OracleSqlManager extends SqlManager { + + public OracleSqlManager(SqlDataType sqlDataType) { + super(sqlDataType); + } + + protected String handleColumnCreationSection(Connection connection, Map<String, ColumnMetadata> columns) { + List<String> lines = new ArrayList<String>(); + Set<String> keys = columns.keySet(); + for (String key : keys) { + Map<ColumnFields, String> column = columns.get(key).getColumnFields(); + lines.add(columnDataToSQL(column)); + } + String toExecute = StringFormat.listToValueSeparatedString(lines, ",\n"); + return toExecute; + } + + public void createTable(Connection connection, TableElement tableDef) throws OseeDataStoreException { + StringBuilder toExecute = new StringBuilder(); + toExecute.append(SqlManager.CREATE_STRING + " TABLE " + formatQuotedString(tableDef.getFullyQualifiedTableName(), + "\\.") + " ( \n"); + toExecute.append(handleColumnCreationSection(connection, tableDef.getColumns())); + toExecute.append(handleConstraintCreationSection(tableDef.getConstraints(), tableDef.getFullyQualifiedTableName())); + toExecute.append(handleConstraintCreationSection(tableDef.getForeignKeyConstraints(), + tableDef.getFullyQualifiedTableName())); + toExecute.append(" \n)"); + toExecute.append(" tablespace "); + toExecute.append(tableDef.getTablespace()); + toExecute.append("\n"); + OseeLog.log(DatabaseActivator.class, Level.INFO, + "Creating Table: [ " + tableDef.getFullyQualifiedTableName() + "]"); + ConnectionHandler.runPreparedUpdate(connection, toExecute.toString()); + } + + /* (non-Javadoc) + * @see org.eclipse.osee.framework.database.sql.SqlManager#createIndexPostProcess(java.lang.String) + */ + @Override + protected String createIndexPostProcess(IndexElement indexElement, String original) { + StringBuilder buffer = new StringBuilder(original); + buffer.append(" tablespace "); + buffer.append(indexElement.getTablespace()); + return buffer.toString(); + } + + @Override + public void dropTable(Connection connection, TableElement tableDef) throws OseeDataStoreException { + StringBuilder toExecute = new StringBuilder(); + toExecute.append(SqlManager.DROP_STRING + " TABLE " + formatQuotedString(tableDef.getFullyQualifiedTableName(), + "\\.") + " cascade constraints purge"); + OseeLog.log(DatabaseActivator.class, Level.INFO, + "Dropping Table: [ " + tableDef.getFullyQualifiedTableName() + "]"); + ConnectionHandler.runPreparedUpdate(connection, toExecute.toString()); + } +} diff --git a/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/sql/PostgreSqlManager.java b/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/sql/PostgreSqlManager.java new file mode 100644 index 00000000000..a57b0ce1812 --- /dev/null +++ b/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/sql/PostgreSqlManager.java @@ -0,0 +1,197 @@ +/******************************************************************************* + * 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.database.sql; + +import java.sql.Connection; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.logging.Level; +import org.eclipse.osee.framework.database.DatabaseActivator; +import org.eclipse.osee.framework.database.data.AppliesToClause; +import org.eclipse.osee.framework.database.data.ColumnMetadata; +import org.eclipse.osee.framework.database.data.ConstraintElement; +import org.eclipse.osee.framework.database.data.ForeignKey; +import org.eclipse.osee.framework.database.data.IndexElement; +import org.eclipse.osee.framework.database.data.ReferenceClause; +import org.eclipse.osee.framework.database.data.TableElement; +import org.eclipse.osee.framework.database.data.ReferenceClause.OnDeleteEnum; +import org.eclipse.osee.framework.database.data.ReferenceClause.OnUpdateEnum; +import org.eclipse.osee.framework.database.data.TableElement.ColumnFields; +import org.eclipse.osee.framework.database.sql.datatype.SqlDataType; +import org.eclipse.osee.framework.db.connection.ConnectionHandler; +import org.eclipse.osee.framework.db.connection.exception.OseeDataStoreException; +import org.eclipse.osee.framework.jdk.core.util.StringFormat; +import org.eclipse.osee.framework.logging.OseeLog; + +/** + * @author Andrew M. Finkbeiner + */ +public class PostgreSqlManager extends SqlManagerImpl { + /** + * @param sqlDataType + */ + public PostgreSqlManager(SqlDataType sqlDataType) { + super(sqlDataType); + } + + private String handleColumnCreationSection(Connection connection, Map<String, ColumnMetadata> columns) { + List<String> lines = new ArrayList<String>(); + Set<String> keys = columns.keySet(); + for (String key : keys) { + Map<ColumnFields, String> column = columns.get(key).getColumnFields(); + lines.add(columnDataToSQL(column)); + } + String toExecute = StringFormat.listToValueSeparatedString(lines, ",\n"); + return toExecute; + } + + public void createTable(Connection connection, TableElement tableDef) throws OseeDataStoreException { + String toExecute = "CREATE TABLE " + tableDef.getFullyQualifiedTableName() + " ( \n"; + toExecute += handleColumnCreationSection(connection, tableDef.getColumns()); + toExecute += handleConstraintCreationSection(tableDef.getConstraints(), tableDef.getFullyQualifiedTableName()); + toExecute += + handleConstraintCreationSection(tableDef.getForeignKeyConstraints(), tableDef.getFullyQualifiedTableName()); + toExecute += " \n)\n"; + OseeLog.log(DatabaseActivator.class, Level.INFO, + "Creating Table: [ " + tableDef.getFullyQualifiedTableName() + "]"); + ConnectionHandler.runPreparedUpdate(connection, toExecute); + } + + @Override + public void dropTable(Connection connection, TableElement tableDef) throws OseeDataStoreException { + String toExecute = "DROP TABLE " + formatQuotedString(tableDef.getFullyQualifiedTableName(), "\\.") + " CASCADE"; + OseeLog.log(DatabaseActivator.class, Level.INFO, + "Dropping Table: [ " + tableDef.getFullyQualifiedTableName() + "]"); + ConnectionHandler.runPreparedUpdate(connection, toExecute); + } + + protected String formatQuotedString(String value, String splitAt) { + String[] array = value.split(splitAt); + for (int index = 0; index < array.length; index++) { + array[index] = array[index]; + } + // return value; + return StringFormat.separateWith(array, splitAt.replaceAll("\\\\", "")); + } + + public void dropIndex(Connection connection, TableElement tableDef) throws OseeDataStoreException { + List<IndexElement> tableIndeces = tableDef.getIndexData(); + String tableName = tableDef.getFullyQualifiedTableName(); + for (IndexElement iData : tableIndeces) { + if (iData.ignoreMySql()) continue; + OseeLog.log(DatabaseActivator.class, Level.INFO, String.format("Dropping Index: [%s] FROM [%s]\n", + iData.getId(), tableName)); + if (iData.getId().equals("PRIMARY")) { + ConnectionHandler.runPreparedUpdate(connection, + "ALTER TABLE " + tableDef.getFullyQualifiedTableName() + " DROP PRIMARY KEY"); + } else { + ConnectionHandler.runPreparedUpdate(connection, + "ALTER TABLE " + tableDef.getFullyQualifiedTableName() + " DROP INDEX " + iData.getId()); + } + } + } + + public String constraintDataToSQL(ConstraintElement constraint, String tableID) { + StringBuilder toReturn = new StringBuilder(); + String id = formatQuotedString(constraint.getId(), "\\."); + String type = constraint.getConstraintType().toString(); + String appliesTo = formatQuotedString(constraint.getCommaSeparatedColumnsList(), ","); + + if (id != null && !id.equals("") && appliesTo != null && !appliesTo.equals("")) { + toReturn.append("CONSTRAINT " + id + " " + type + " (" + appliesTo + ")"); + + if (constraint instanceof ForeignKey) { + ForeignKey fk = (ForeignKey) constraint; + List<ReferenceClause> refs = fk.getReferences(); + + for (ReferenceClause ref : refs) { + String refTable = formatQuotedString(ref.getFullyQualifiedTableName(), "\\."); + String refColumns = formatQuotedString(ref.getCommaSeparatedColumnsList(), ","); + + String onUpdate = ""; + if (!ref.getOnUpdateAction().equals(OnUpdateEnum.UNSPECIFIED)) { + onUpdate = "ON UPDATE " + ref.getOnUpdateAction().toString(); + } + + String onDelete = ""; + if (!ref.getOnDeleteAction().equals(OnDeleteEnum.UNSPECIFIED)) { + onDelete = "ON DELETE " + ref.getOnDeleteAction().toString(); + } + + if (refTable != null && refColumns != null && !refTable.equals("") && !refColumns.equals("")) { + toReturn.append(" REFERENCES " + refTable + " (" + refColumns + ")"); + if (!onUpdate.equals("")) { + toReturn.append(" " + onUpdate); + } + + if (!onDelete.equals("")) { + toReturn.append(" " + onDelete); + } + + if (constraint.isDeferrable()) { + toReturn.append(" DEFERRABLE"); + } + } + + else { + OseeLog.log(DatabaseActivator.class, Level.WARNING, + "Skipping CONSTRAINT at Table: " + tableID + "\n\t " + fk.toString()); + } + + } + } + } else { + OseeLog.log(DatabaseActivator.class, Level.WARNING, + "Skipping CONSTRAINT at Table: " + tableID + "\n\t " + constraint.toString()); + } + return toReturn.toString(); + } + + public void createIndex(Connection connection, TableElement tableDef) throws OseeDataStoreException { + List<IndexElement> tableIndeces = tableDef.getIndexData(); + String indexId = null; + StringBuilder appliesTo = new StringBuilder(); + String tableName = formatQuotedString(tableDef.getFullyQualifiedTableName(), "\\."); + for (IndexElement iData : tableIndeces) { + if (iData.ignoreMySql()) continue; + indexId = iData.getId(); + appliesTo.delete(0, appliesTo.length()); + + List<AppliesToClause> appliesToList = iData.getAppliesToList(); + for (int index = 0; index < appliesToList.size(); index++) { + AppliesToClause record = appliesToList.get(index); + appliesTo.append(record.getColumnName()); + + // switch (record.getOrderType()) { + // case Ascending: + // appliesTo.append(" ASC"); + // break; + // case Descending: + // appliesTo.append(" DESC"); + // break; + // default: + // break; + // } + if (index + 1 < appliesToList.size()) { + appliesTo.append(", "); + } + } + String toExecute = + String.format(CREATE_STRING + " " + iData.getIndexType() + " INDEX %s ON %s (%s)", indexId, tableName, + appliesTo); + OseeLog.log(DatabaseActivator.class, Level.INFO, toExecute); + ConnectionHandler.runPreparedUpdate(connection, toExecute); + } + } + +} diff --git a/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/sql/SqlFactory.java b/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/sql/SqlFactory.java new file mode 100644 index 00000000000..aa4c7882528 --- /dev/null +++ b/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/sql/SqlFactory.java @@ -0,0 +1,53 @@ +/******************************************************************************* + * 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.database.sql; + +import org.eclipse.osee.framework.database.sql.datatype.DerbySqlDataType; +import org.eclipse.osee.framework.database.sql.datatype.FoxProDataType; +import org.eclipse.osee.framework.database.sql.datatype.MySqlDataType; +import org.eclipse.osee.framework.database.sql.datatype.OracleSqlDataType; +import org.eclipse.osee.framework.database.sql.datatype.PostgresqlDataType; +import org.eclipse.osee.framework.db.connection.info.SupportedDatabase; + +/** + * @author Roberto E. Escobar + */ +public class SqlFactory { + + private SqlFactory() { + super(); + } + + public static SqlManager getSqlManager(SupportedDatabase db) { + SqlManager instance = null; + switch (db) { + case oracle: + instance = new OracleSqlManager(new OracleSqlDataType()); + break; + case derby: + instance = new DerbySqlManager(new DerbySqlDataType()); + break; + case foxpro: + instance = new SqlManagerImpl(new FoxProDataType()); + break; + case mysql: + instance = new MysqlSqlManager(new MySqlDataType()); + break; + case postgresql: + instance = new PostgreSqlManager(new PostgresqlDataType()); + break; + default: + instance = null; + break; + } + return instance; + } +} diff --git a/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/sql/SqlManager.java b/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/sql/SqlManager.java new file mode 100644 index 00000000000..41bc9612b65 --- /dev/null +++ b/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/sql/SqlManager.java @@ -0,0 +1,313 @@ +/******************************************************************************* + * 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.database.sql; + +import java.io.BufferedInputStream; +import java.io.ByteArrayInputStream; +import java.math.BigDecimal; +import java.sql.Connection; +import java.sql.Date; +import java.sql.Time; +import java.sql.Timestamp; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.logging.Level; +import org.eclipse.osee.framework.database.DatabaseActivator; +import org.eclipse.osee.framework.database.data.AppliesToClause; +import org.eclipse.osee.framework.database.data.ColumnDbData; +import org.eclipse.osee.framework.database.data.ColumnMetadata; +import org.eclipse.osee.framework.database.data.ConstraintElement; +import org.eclipse.osee.framework.database.data.ForeignKey; +import org.eclipse.osee.framework.database.data.IndexElement; +import org.eclipse.osee.framework.database.data.ReferenceClause; +import org.eclipse.osee.framework.database.data.SchemaDataLookup; +import org.eclipse.osee.framework.database.data.TableElement; +import org.eclipse.osee.framework.database.data.ReferenceClause.OnDeleteEnum; +import org.eclipse.osee.framework.database.data.ReferenceClause.OnUpdateEnum; +import org.eclipse.osee.framework.database.data.TableElement.ColumnFields; +import org.eclipse.osee.framework.database.sql.datatype.SqlDataType; +import org.eclipse.osee.framework.db.connection.ConnectionHandler; +import org.eclipse.osee.framework.db.connection.exception.OseeDataStoreException; +import org.eclipse.osee.framework.db.connection.info.SQL3DataType; +import org.eclipse.osee.framework.jdk.core.util.StringFormat; +import org.eclipse.osee.framework.jdk.core.util.time.GlobalTime; +import org.eclipse.osee.framework.logging.OseeLog; + +/** + * @author Roberto E. Escobar + */ +public abstract class SqlManager { + protected SqlDataType sqlDataType; + public static final String CREATE_STRING = "CREATE"; + public static final String DROP_STRING = "DROP"; + + public SqlManager(SqlDataType sqlDataType) { + this.sqlDataType = sqlDataType; + } + + public abstract void createTable(Connection connection, TableElement tableDef) throws OseeDataStoreException; + + public abstract void dropTable(Connection connection, TableElement tableDef) throws OseeDataStoreException; + + public void insertData(Connection connection, List<ColumnDbData> rowData, TableElement tableMetadata) throws OseeDataStoreException { + List<String> columnNames = new ArrayList<String>(); + List<String> placeHolders = new ArrayList<String>(); + List<String> columnValues = new ArrayList<String>(); + List<SQL3DataType> columnTypes = new ArrayList<SQL3DataType>(); + + for (ColumnDbData dbData : rowData) { + String columnId = dbData.getColumnName(); + String columnValue = dbData.getColumnValue(); + + ColumnMetadata columnMetadata = SchemaDataLookup.getColumnDefinition(tableMetadata.getColumns(), columnId); + SQL3DataType type = SQL3DataType.valueOf(columnMetadata.getColumnField(ColumnFields.type)); + + columnNames.add("\"" + columnId + "\""); + placeHolders.add("?"); + columnValues.add(columnValue); + columnTypes.add(type); + } + + String toExecute = + "INSERT INTO " + formatQuotedString(tableMetadata.getFullyQualifiedTableName(), "\\.") + " (\n"; + toExecute += StringFormat.listToCommaSeparatedString(columnNames); + toExecute += "\n) VALUES (\n"; + toExecute += StringFormat.listToCommaSeparatedString(placeHolders); + toExecute += ")\n"; + + Object[] data = new Object[columnNames.size()]; + for (int index = 0; index < columnNames.size(); index++) { + data[index] = preparedStatementHelper(columnTypes.get(index), columnValues.get(index)); + } + ConnectionHandler.runPreparedUpdate(connection, toExecute, data); + } + + public Object preparedStatementHelper(SQL3DataType columnType, String value) throws OseeDataStoreException { + switch (columnType) { + case BINARY: + case BIT: + return value != null && !value.equals("") ? Byte.parseByte(value) : 0; + case TINYINT: + case SMALLINT: + return value != null && !value.equals("") ? Short.valueOf(value) : 0; + case INTEGER: + return value != null && !value.equals("") ? Integer.valueOf(value) : 0; + case BIGINT: + return value != null && !value.equals("") ? BigDecimal.valueOf(Double.valueOf(value)) : new BigDecimal(0); + case FLOAT: + return value != null && !value.equals("") ? Float.valueOf(value) : 0.0f; + case NUMERIC: + case DECIMAL: + case REAL: + case DOUBLE: + return value != null && !value.equals("") ? Double.valueOf(value) : 0.0; + case CHAR: + case VARCHAR: + case LONGVARCHAR: + return value; + case DATE: + return value == null || value.equals("") ? SQL3DataType.DATE : Date.valueOf(value); + case TIMESTAMP: + return value != null && !value.equals("") ? Timestamp.valueOf(value) : GlobalTime.GreenwichMeanTimestamp(); + case TIME: + return value == null || value.equals("") ? SQL3DataType.TIME : Time.valueOf(value); + case VARBINARY: + case LONGVARBINARY: + return value.getBytes(); + case BLOB: + return new BufferedInputStream(new ByteArrayInputStream(value.getBytes())); + case CLOB: + return new BufferedInputStream(new ByteArrayInputStream(value.getBytes())); + case BOOLEAN: + return value == null || value.equals("") ? false : Boolean.parseBoolean(value); + default: + throw new OseeDataStoreException("unexpected column type: " + columnType); + } + } + + public String getType(SQL3DataType dataType) { + return sqlDataType.getType(dataType); + } + + public String columnDataToSQL(Map<ColumnFields, String> column) { + StringBuilder toReturn = new StringBuilder(); + + String columnLimits = column.get(ColumnFields.limits); + String defaultValue = column.get(ColumnFields.defaultValue); + + SQL3DataType dataType = SQL3DataType.valueOf(column.get(ColumnFields.type)); + columnLimits = sqlDataType.getLimit(dataType, columnLimits); + toReturn.append(column.get(ColumnFields.id)); + toReturn.append(" "); + toReturn.append(sqlDataType.getType(dataType)); + + if (columnLimits != null && !columnLimits.equals("")) { + toReturn.append(" (" + columnLimits + ")"); + } + if (defaultValue != null && !defaultValue.equals("")) { + toReturn.append(" " + defaultValue); + } + return toReturn.toString(); + } + + @SuppressWarnings("unchecked") + protected String handleConstraintCreationSection(List constraints, String tableId) { + List<String> constraintStatements = new ArrayList<String>(); + for (Object object : constraints) { + ConstraintElement constraint = (ConstraintElement) object; + constraintStatements.add(constraintDataToSQL(constraint, tableId)); + } + StringBuilder toExecute = new StringBuilder(); + toExecute.append((constraintStatements.size() != 0 ? ",\n" : "")); + toExecute.append(StringFormat.listToValueSeparatedString(constraintStatements, ",\n")); + return toExecute.toString(); + } + + protected String formatQuotedString(String value, String splitAt) { + String[] array = value.split(splitAt); + for (int index = 0; index < array.length; index++) { + array[index] = "\"" + array[index] + "\""; + } + // return value; + return StringFormat.separateWith(array, splitAt.replaceAll("\\\\", "")); + } + + public String constraintDataToSQL(ConstraintElement constraint, String tableID) { + StringBuilder toReturn = new StringBuilder(); + String id = formatQuotedString(constraint.getId(), "\\."); + String type = constraint.getConstraintType().toString(); + String appliesTo = formatQuotedString(constraint.getCommaSeparatedColumnsList(), ","); + + if (id != null && !id.equals("") && appliesTo != null && !appliesTo.equals("")) { + toReturn.append("CONSTRAINT " + id + " " + type + " (" + appliesTo + ")"); + + if (constraint instanceof ForeignKey) { + ForeignKey fk = (ForeignKey) constraint; + List<ReferenceClause> refs = fk.getReferences(); + + for (ReferenceClause ref : refs) { + String refTable = formatQuotedString(ref.getFullyQualifiedTableName(), "\\."); + String refColumns = formatQuotedString(ref.getCommaSeparatedColumnsList(), ","); + + String onUpdate = ""; + if (!ref.getOnUpdateAction().equals(OnUpdateEnum.UNSPECIFIED)) { + onUpdate = "ON UPDATE " + ref.getOnUpdateAction().toString(); + } + + String onDelete = ""; + if (!ref.getOnDeleteAction().equals(OnDeleteEnum.UNSPECIFIED)) { + onDelete = "ON DELETE " + ref.getOnDeleteAction().toString(); + } + + if (refTable != null && refColumns != null && !refTable.equals("") && !refColumns.equals("")) { + toReturn.append(" REFERENCES " + refTable + " (" + refColumns + ")"); + if (!onUpdate.equals("")) { + toReturn.append(" " + onUpdate); + } + + if (!onDelete.equals("")) { + toReturn.append(" " + onDelete); + } + + if (constraint.isDeferrable()) { + toReturn.append(" DEFERRABLE"); + } + } + + else { + OseeLog.log(DatabaseActivator.class, Level.WARNING, + "Skipping CONSTRAINT at Table: " + tableID + "\n\t " + fk.toString()); + } + + } + } + } else { + OseeLog.log(DatabaseActivator.class, Level.WARNING, + "Skipping CONSTRAINT at Table: " + tableID + "\n\t " + constraint.toString()); + } + return toReturn.toString(); + } + + public void createSchema(Connection connection, String schema) throws OseeDataStoreException { + StringBuilder toExecute = new StringBuilder(); + toExecute.append(CREATE_STRING + " SCHEMA \"" + schema + "\""); + ConnectionHandler.runPreparedUpdate(connection, toExecute.toString()); + } + + public void dropSchema(Connection connection, String schema) throws OseeDataStoreException { + StringBuilder toExecute = new StringBuilder(); + toExecute.append(DROP_STRING + " SCHEMA \"" + schema + "\" CASCADE"); + ConnectionHandler.runPreparedUpdate(connection, toExecute.toString()); + } + + protected String insertDataToSQL(String fullyQualifiedTableName, List<String> columns, List<String> columnData) { + StringBuilder toExecute = new StringBuilder(); + toExecute.append("INSERT INTO " + formatQuotedString(fullyQualifiedTableName, "\\.") + " (\n"); + toExecute.append(StringFormat.listToCommaSeparatedString(columns)); + toExecute.append("\n) VALUES (\n"); + toExecute.append(StringFormat.listToCommaSeparatedString(columnData)); + toExecute.append(")\n"); + return toExecute.toString(); + } + + public void createIndex(Connection connection, TableElement tableDef) throws OseeDataStoreException { + List<IndexElement> tableIndeces = tableDef.getIndexData(); + String indexId = null; + StringBuilder appliesTo = new StringBuilder(); + String tableName = formatQuotedString(tableDef.getFullyQualifiedTableName(), "\\."); + for (IndexElement iData : tableIndeces) { + if (iData.ignoreMySql()) continue; + indexId = iData.getId(); + appliesTo.delete(0, appliesTo.length()); + + List<AppliesToClause> appliesToList = iData.getAppliesToList(); + for (int index = 0; index < appliesToList.size(); index++) { + AppliesToClause record = appliesToList.get(index); + appliesTo.append(record.getColumnName()); + + switch (record.getOrderType()) { + case Ascending: + appliesTo.append(" ASC"); + break; + case Descending: + appliesTo.append(" DESC"); + break; + default: + break; + } + if (index + 1 < appliesToList.size()) { + appliesTo.append(", "); + } + } + String toExecute = + String.format("%s %s INDEX %s ON %s (%s)", CREATE_STRING, iData.getIndexType(), indexId, tableName, + appliesTo); + toExecute = createIndexPostProcess(iData, toExecute); + OseeLog.log(DatabaseActivator.class, Level.INFO, toExecute + "\n"); + ConnectionHandler.runPreparedUpdate(connection, toExecute); + } + } + + protected String createIndexPostProcess(IndexElement indexElement, String original) { + return original; + } + + public void dropIndex(Connection connection, TableElement tableDef) throws OseeDataStoreException { + List<IndexElement> tableIndeces = tableDef.getIndexData(); + String tableName = tableDef.getFullyQualifiedTableName(); + for (IndexElement iData : tableIndeces) { + OseeLog.log(DatabaseActivator.class, Level.INFO, String.format("Dropping Index: [%s] FROM [%s]\n", + iData.getId(), tableName)); + ConnectionHandler.runPreparedUpdate(connection, DROP_STRING + " INDEX " + iData.getId()); + } + } +} diff --git a/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/sql/SqlManagerImpl.java b/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/sql/SqlManagerImpl.java new file mode 100644 index 00000000000..094eccc23eb --- /dev/null +++ b/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/sql/SqlManagerImpl.java @@ -0,0 +1,72 @@ +/******************************************************************************* + * 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.database.sql; + +import java.sql.Connection; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.logging.Level; +import org.eclipse.osee.framework.database.DatabaseActivator; +import org.eclipse.osee.framework.database.data.ColumnMetadata; +import org.eclipse.osee.framework.database.data.TableElement; +import org.eclipse.osee.framework.database.data.TableElement.ColumnFields; +import org.eclipse.osee.framework.database.sql.datatype.SqlDataType; +import org.eclipse.osee.framework.db.connection.ConnectionHandler; +import org.eclipse.osee.framework.db.connection.exception.OseeDataStoreException; +import org.eclipse.osee.framework.jdk.core.util.StringFormat; +import org.eclipse.osee.framework.logging.OseeLog; + +/** + * @author Roberto E. Escobar + */ +public class SqlManagerImpl extends SqlManager { + + public SqlManagerImpl(SqlDataType sqlDataType) { + super(sqlDataType); + } + + private String handleColumnCreationSection(Connection connection, Map<String, ColumnMetadata> columns) { + List<String> lines = new ArrayList<String>(); + Set<String> keys = columns.keySet(); + for (String key : keys) { + Map<ColumnFields, String> column = columns.get(key).getColumnFields(); + lines.add(columnDataToSQL(column)); + } + String toExecute = StringFormat.listToValueSeparatedString(lines, ",\n"); + return toExecute; + } + + public void createTable(Connection connection, TableElement tableDef) throws OseeDataStoreException { + StringBuilder toExecute = new StringBuilder(); + toExecute.append(SqlManager.CREATE_STRING + " TABLE " + formatQuotedString(tableDef.getFullyQualifiedTableName(), + "\\.") + " ( \n"); + toExecute.append(handleColumnCreationSection(connection, tableDef.getColumns())); + toExecute.append(handleConstraintCreationSection(tableDef.getConstraints(), tableDef.getFullyQualifiedTableName())); + toExecute.append(handleConstraintCreationSection(tableDef.getForeignKeyConstraints(), + tableDef.getFullyQualifiedTableName())); + toExecute.append(" \n)\n"); + OseeLog.log(DatabaseActivator.class, Level.INFO, + "Creating Table: [ " + tableDef.getFullyQualifiedTableName() + "]"); + ConnectionHandler.runPreparedUpdate(connection, toExecute.toString()); + } + + @Override + public void dropTable(Connection connection, TableElement tableDef) throws OseeDataStoreException { + StringBuilder toExecute = new StringBuilder(); + toExecute.append(SqlManager.DROP_STRING + " TABLE " + formatQuotedString(tableDef.getFullyQualifiedTableName(), + "\\.")); + OseeLog.log(DatabaseActivator.class, Level.INFO, + "Dropping Table: [ " + tableDef.getFullyQualifiedTableName() + "]"); + ConnectionHandler.runPreparedUpdate(connection, toExecute.toString()); + } +} diff --git a/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/sql/datatype/DerbySqlDataType.java b/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/sql/datatype/DerbySqlDataType.java new file mode 100644 index 00000000000..a043250da9f --- /dev/null +++ b/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/sql/datatype/DerbySqlDataType.java @@ -0,0 +1,102 @@ +/******************************************************************************* + * 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.database.sql.datatype; + +/** + * @author Roberto E. Escobar + */ +public class DerbySqlDataType extends SqlDataType { + + public DerbySqlDataType() { + super(); + } + + public String getBooleanType() { + return "boolean"; + } + + public String getBitType() { + return "smallint"; + } + + public String getIntegerType() { + return "integer"; + } + + public String getDecimalType() { + return "decimal"; + } + + public String getFloatType() { + return "float"; + } + + public String getRealType() { + return "real"; + } + + public String getDoubleType() { + return getRealType(); + } + + public String getDateType() { + return "date"; + } + + public String getCharType() { + return "char"; + } + + public String getVarCharType() { + return "varchar"; + } + + @Override + public String getSmallIntType() { + return "smallint"; + } + + @Override + protected String getClobType() { + return "clob"; + } + + @Override + protected String getTimestamp() { + return "timestamp"; + } + + @Override + protected String getTime() { + return "time"; + } + + @Override + protected String getBlobType() { + return "blob"; + } + + @Override + protected String getBigInt() { + return "bigint"; + } + + @Override + protected String getLongVarCharType() { + return "long varchar"; + } + + @Override + protected String getNumericType() { + return "numeric"; + } + +} diff --git a/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/sql/datatype/FoxProDataType.java b/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/sql/datatype/FoxProDataType.java new file mode 100644 index 00000000000..06ead6d4156 --- /dev/null +++ b/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/sql/datatype/FoxProDataType.java @@ -0,0 +1,101 @@ +/******************************************************************************* + * 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.database.sql.datatype; + +/** + * @author Roberto E. Escobar + */ +public class FoxProDataType extends SqlDataType { + + public FoxProDataType() { + super(); + } + + public String getBooleanType() { + return "number"; + } + + public String getBitType() { + return "number"; + } + + public String getIntegerType() { + return "integer"; + } + + public String getDecimalType() { + return "number"; + } + + public String getFloatType() { + return "float"; + } + + public String getDoubleType() { + return "number"; + } + + public String getRealType() { + return "real"; + } + + public String getDateType() { + return "date"; + } + + public String getCharType() { + return "char"; + } + + public String getVarCharType() { + return "varchar"; + } + + @Override + public String getSmallIntType() { + return "smallint"; + } + + @Override + protected String getClobType() { + return "clob"; + } + + @Override + protected String getTimestamp() { + return "timestamp"; + } + + @Override + protected String getTime() { + return "time"; + } + + @Override + protected String getBlobType() { + return "blob"; + } + + @Override + protected String getBigInt() { + return "number"; + } + + @Override + protected String getLongVarCharType() { + return "long varchar"; + } + + @Override + protected String getNumericType() { + return "number"; + } +} diff --git a/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/sql/datatype/MySqlDataType.java b/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/sql/datatype/MySqlDataType.java new file mode 100644 index 00000000000..77327864b27 --- /dev/null +++ b/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/sql/datatype/MySqlDataType.java @@ -0,0 +1,102 @@ +/******************************************************************************* + * 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.database.sql.datatype; + +/** + * @author Roberto E. Escobar + */ +public class MySqlDataType extends SqlDataType { + + public MySqlDataType() { + super(); + } + + public String getBooleanType() { + return "boolean"; + } + + public String getBitType() { + return "smallint"; + } + + public String getIntegerType() { + return "integer"; + } + + public String getDecimalType() { + return "decimal"; + } + + public String getFloatType() { + return "float"; + } + + public String getRealType() { + return "real"; + } + + public String getDoubleType() { + return getRealType(); + } + + public String getDateType() { + return "date"; + } + + public String getCharType() { + return "char"; + } + + public String getVarCharType() { + return "varchar"; + } + + @Override + public String getSmallIntType() { + return "smallint"; + } + + @Override + protected String getClobType() { + return "blob"; + } + + @Override + protected String getTimestamp() { + return "timestamp"; + } + + @Override + protected String getTime() { + return "time"; + } + + @Override + protected String getBlobType() { + return "blob"; + } + + @Override + protected String getBigInt() { + return "bigint"; + } + + @Override + protected String getLongVarCharType() { + return "long varchar"; + } + + @Override + protected String getNumericType() { + return "numeric"; + } + +} diff --git a/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/sql/datatype/OracleSqlDataType.java b/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/sql/datatype/OracleSqlDataType.java new file mode 100644 index 00000000000..e403e6e53ad --- /dev/null +++ b/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/sql/datatype/OracleSqlDataType.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.database.sql.datatype; + +import org.eclipse.osee.framework.db.connection.info.SQL3DataType; + +/** + * @author Roberto E. Escobar + */ +public class OracleSqlDataType extends SqlDataType { + + public OracleSqlDataType() { + super(); + } + + @Override + public String getLimit(SQL3DataType dataType, String limit) { + if (dataType == SQL3DataType.VARCHAR && limit != null && !limit.equals("")) { + return limit + " CHAR"; + } else { + return super.getLimit(dataType, limit); + } + } + + public String getBooleanType() { + return "number"; + } + + public String getBitType() { + return "number"; + } + + public String getIntegerType() { + return "integer"; + } + + public String getDecimalType() { + return "number"; + } + + public String getFloatType() { + return "float"; + } + + public String getRealType() { + return "real"; + } + + public String getDoubleType() { + return "number"; + } + + public String getDateType() { + return "date"; + } + + public String getCharType() { + return "char"; + } + + public String getVarCharType() { + return "varchar2"; + } + + @Override + public String getSmallIntType() { + return "smallint"; + } + + @Override + protected String getClobType() { + return "clob"; + } + + @Override + protected String getTimestamp() { + return "timestamp"; + } + + @Override + protected String getTime() { + return "time"; + } + + @Override + protected String getBlobType() { + return "blob"; + } + + @Override + protected String getBigInt() { + return "number"; + } + + @Override + protected String getLongVarCharType() { + return "varchar2"; + } + + @Override + protected String getNumericType() { + return "number"; + } + +} diff --git a/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/sql/datatype/PostgresqlDataType.java b/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/sql/datatype/PostgresqlDataType.java new file mode 100644 index 00000000000..9c431f1756e --- /dev/null +++ b/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/sql/datatype/PostgresqlDataType.java @@ -0,0 +1,102 @@ +/******************************************************************************* + * 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.database.sql.datatype; + +/** + * @author Roberto E. Escobar + */ +public class PostgresqlDataType extends SqlDataType { + + public PostgresqlDataType() { + super(); + } + + public String getBooleanType() { + return "bool"; + } + + public String getBitType() { + return "number"; + } + + public String getIntegerType() { + return "integer"; + } + + public String getDecimalType() { + return "decimal"; + } + + public String getFloatType() { + return "float"; + } + + public String getRealType() { + return "float8"; + } + + public String getDoubleType() { + return "numeric"; + } + + public String getDateType() { + return "date"; + } + + public String getCharType() { + return "char"; + } + + public String getVarCharType() { + return "varchar"; + } + + @Override + public String getSmallIntType() { + return "smallint"; + } + + @Override + protected String getClobType() { + return "bytea"; + } + + @Override + protected String getTimestamp() { + return "timestamp"; + } + + @Override + protected String getTime() { + return "time"; + } + + @Override + protected String getBlobType() { + return "bytea"; + } + + @Override + protected String getBigInt() { + return "numeric"; + } + + @Override + protected String getLongVarCharType() { + return "varchar"; + } + + @Override + protected String getNumericType() { + return "numeric"; + } + +} diff --git a/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/sql/datatype/SqlDataType.java b/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/sql/datatype/SqlDataType.java new file mode 100644 index 00000000000..35e17ce4a5e --- /dev/null +++ b/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/sql/datatype/SqlDataType.java @@ -0,0 +1,192 @@ +/******************************************************************************* + * 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.database.sql.datatype; + +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import org.eclipse.osee.framework.db.connection.info.SQL3DataType; + +/** + * @author Roberto E. Escobar + */ +public abstract class SqlDataType { + + public SqlDataType() { + super(); + } + + protected abstract String getBooleanType(); + + protected abstract String getBitType(); + + protected abstract String getSmallIntType(); + + protected abstract String getIntegerType(); + + protected abstract String getDecimalType(); + + protected abstract String getFloatType(); + + protected abstract String getDoubleType(); + + protected abstract String getRealType(); + + protected abstract String getDateType(); + + protected abstract String getCharType(); + + protected abstract String getVarCharType(); + + protected abstract String getClobType(); + + protected abstract String getBlobType(); + + protected abstract String getTimestamp(); + + protected abstract String getTime(); + + protected abstract String getBigInt(); + + protected abstract String getLongVarCharType(); + + protected abstract String getNumericType(); + + public String getLimit(SQL3DataType dataType, String limit) { + return limit; + } + + public String getType(SQL3DataType dataType) { + String toReturn = ""; + + switch (dataType) { + case BOOLEAN: + toReturn = this.getBooleanType(); + break; + case BIT: + toReturn = this.getBitType(); + break; + case SMALLINT: + toReturn = this.getSmallIntType(); + break; + case INTEGER: + toReturn = this.getIntegerType(); + break; + case REAL: + toReturn = this.getRealType(); + break; + case DECIMAL: + toReturn = this.getDecimalType(); + break; + case FLOAT: + toReturn = this.getFloatType(); + break; + case DOUBLE: + toReturn = this.getDoubleType(); + break; + case DATE: + toReturn = this.getDateType(); + break; + case CHAR: + toReturn = this.getCharType(); + break; + case VARCHAR: + toReturn = this.getVarCharType(); + break; + case CLOB: + toReturn = this.getClobType(); + break; + case TIMESTAMP: + toReturn = this.getTimestamp(); + break; + case TIME: + toReturn = this.getTime(); + break; + case BLOB: + toReturn = this.getBlobType(); + break; + case BIGINT: + toReturn = this.getBigInt(); + break; + case LONGVARCHAR: + toReturn = this.getLongVarCharType(); + break; + case NUMERIC: + toReturn = this.getNumericType(); + break; + default: + toReturn = "ADDTHISTYPE:" + dataType.name(); + break; + } + return toReturn; + } + + public String formatDataValueforDataType(String columnValue, SQL3DataType columnType) { + String toReturn = ""; + switch (columnType) { + case BIGINT: + case BIT: + case BOOLEAN: + case DECIMAL: + case DOUBLE: + case FLOAT: + case INTEGER: + case REAL: + case NUMERIC: + case SMALLINT: + case TINYINT: + toReturn = ((columnValue != null && !columnValue.equals("")) ? columnValue : "0"); + break; + case DATE: + toReturn = "{d '" + formatDate(columnValue) + "'}"; + break; + case TIMESTAMP: + toReturn = "{ts '" + formatDate(columnValue) + "'}"; + break; + case TIME: + toReturn = "{t '" + columnValue + "'}"; + break; + default: + toReturn = "'" + columnValue + "'"; + break; + } + return toReturn; + } + + private String formatDate(String input) { + String[] sets = input.split(" "); + String date = sets[0]; + String time = ""; + if (sets.length > 1) { + time += " "; + for (int i = 1; i < sets.length; i++) { + time += sets[i]; + } + } + if (!date.contains("/") && !date.contains("-") && !date.contains(":")) { + Pattern pattern = Pattern.compile("([0-9][0-9][0-9][0-9])([0-9][0-9])([0-9][0-9])"); + Matcher matcher = pattern.matcher(date); + + if (matcher.find()) { + if (matcher.groupCount() == 3) { + String year = matcher.group(1); + String month = matcher.group(2); + String day = matcher.group(3); + + date = year + "-" + month + "-" + day; + } + } + } else { + date = date.replaceAll("/", "-"); + date = date.replaceAll(":", "-"); + } + return date + time; + } +} diff --git a/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/utility/DatabaseConfigurationData.java b/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/utility/DatabaseConfigurationData.java new file mode 100644 index 00000000000..1fab05dd81d --- /dev/null +++ b/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/utility/DatabaseConfigurationData.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.database.utility; + +import java.net.URL; +import java.sql.Connection; +import java.sql.DatabaseMetaData; +import java.sql.SQLException; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import org.eclipse.osee.framework.core.client.OseeClientProperties; +import org.eclipse.osee.framework.database.config.SchemaConfigUtility; +import org.eclipse.osee.framework.database.data.ColumnMetadata; +import org.eclipse.osee.framework.database.data.ConstraintElement; +import org.eclipse.osee.framework.database.data.ForeignKey; +import org.eclipse.osee.framework.database.data.IndexElement; +import org.eclipse.osee.framework.database.data.ReferenceClause; +import org.eclipse.osee.framework.database.data.SchemaData; +import org.eclipse.osee.framework.database.data.TableElement; +import org.eclipse.osee.framework.database.data.TableElement.TableDescriptionFields; + +public class DatabaseConfigurationData { + + private List<URL> filesToProcess; + private Connection connection; + + public DatabaseConfigurationData(Connection connection, List<URL> filesToProcess) { + this.filesToProcess = filesToProcess; + this.connection = connection; + } + + public List<URL> getUserSchemaFilesToProcess() { + return filesToProcess; + } + + public Map<String, SchemaData> getUserSpecifiedSchemas() { + Map<String, SchemaData> schemasFromUserFiles = + SchemaConfigUtility.getUserDefinedConfig(getUserSchemaFilesToProcess()); + if (!useFileSpecifiedSchemas()) { + try { + DatabaseMetaData meta = connection.getMetaData(); + if (meta != null) { + String userName = meta.getUserName(); + if (userName != null && !userName.equals("")) { + int index = userName.indexOf('@'); + if (index > 1) { + userName = userName.substring(0, index); + } + schemasFromUserFiles = useUserNameAsSchema(userName.toUpperCase(), schemasFromUserFiles); + } + } + } catch (SQLException ex) { + ex.printStackTrace(); + } + } + return schemasFromUserFiles; + } + + private boolean useFileSpecifiedSchemas() { + return OseeClientProperties.useSchemasSpecifiedInDbConfigFiles(); + } + + private Map<String, SchemaData> useUserNameAsSchema(String userName, Map<String, SchemaData> userSchemas) { + Map<String, SchemaData> newData = new HashMap<String, SchemaData>(); + SchemaData newSchemaData = new SchemaData(); + Set<String> keys = userSchemas.keySet(); + for (String key : keys) { + SchemaData schemaData = userSchemas.get(key); + List<TableElement> tables = schemaData.getTablesOrderedByDependency(); + for (TableElement table : tables) { + TableElement newTable = useUserNameAsSchemaForTable(userName, table); + newSchemaData.addTableDefinition(newTable); + } + } + newData.put(userName, newSchemaData); + return newData; + } + + private TableElement useUserNameAsSchemaForTable(String userName, TableElement table) { + TableElement newTable = new TableElement(); + + Map<TableDescriptionFields, String> tableDescription = table.getDescription(); + Map<String, ColumnMetadata> columns = table.getColumns(); + List<ConstraintElement> constraints = table.getConstraints(); + List<ForeignKey> foreignKeys = table.getForeignKeyConstraints(); + List<IndexElement> indexElements = table.getIndexData(); + + TableDescriptionFields[] descriptors = TableDescriptionFields.values(); + for (TableDescriptionFields field : descriptors) { + String value = tableDescription.get(field); + if (field.equals(TableDescriptionFields.schema)) { + value = userName; + } + if (value != null && !value.equals("")) { + newTable.addTableDescription(field, value); + } + } + + Set<String> columnKeys = columns.keySet(); + for (String key : columnKeys) { + newTable.addColumn(columns.get(key)); + } + for (ConstraintElement constraint : constraints) { + constraint.setSchema(userName); + newTable.addConstraint(constraint); + } + for (ForeignKey constraint : foreignKeys) { + constraint.setSchema(userName); + List<ReferenceClause> references = constraint.getReferences(); + for (ReferenceClause clause : references) { + clause.setSchema(userName); + } + newTable.addConstraint(constraint); + } + for (IndexElement indexElement : indexElements) { + newTable.addIndexData(indexElement); + } + return newTable; + } +} diff --git a/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/utility/DatabaseDataExtractor.java b/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/utility/DatabaseDataExtractor.java new file mode 100644 index 00000000000..c5f2b9e0087 --- /dev/null +++ b/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/utility/DatabaseDataExtractor.java @@ -0,0 +1,270 @@ +/******************************************************************************* + * 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.database.utility; + +import java.io.BufferedOutputStream; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.OutputStream; +import java.io.OutputStreamWriter; +import java.math.BigDecimal; +import java.sql.Connection; +import java.sql.Date; +import java.sql.Time; +import java.sql.Timestamp; +import java.sql.Types; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.TreeSet; +import java.util.logging.Level; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import org.eclipse.osee.framework.database.DatabaseActivator; +import org.eclipse.osee.framework.database.data.SchemaData; +import org.eclipse.osee.framework.database.data.TableElement; +import org.eclipse.osee.framework.database.data.TableElement.ColumnFields; +import org.eclipse.osee.framework.database.data.TableElement.TableDescriptionFields; +import org.eclipse.osee.framework.database.data.TableElement.TableTags; +import org.eclipse.osee.framework.db.connection.ConnectionHandlerStatement; +import org.eclipse.osee.framework.db.connection.exception.OseeDataStoreException; +import org.eclipse.osee.framework.db.connection.info.SQL3DataType; +import org.eclipse.osee.framework.db.connection.info.SupportedDatabase; +import org.eclipse.osee.framework.jdk.core.db.DbConfigFileInformation; +import org.eclipse.osee.framework.logging.OseeLog; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import com.sun.org.apache.xerces.internal.dom.DocumentImpl; +import com.sun.org.apache.xml.internal.serialize.OutputFormat; +import com.sun.org.apache.xml.internal.serialize.XMLSerializer; + +/** + * @author Roberto E. Escobar + */ +public class DatabaseDataExtractor { + + private static final String SQL_WILD_QUERY = "SELECT * FROM "; + private Connection connection; + private DatabaseSchemaExtractor databaseInfo; + private Set<String> schemas; + private File directory; + private List<Thread> workerThreads; + private Set<String> extractTables; + private SupportedDatabase dbType; + + private class ColumnInfo { + String name; + SQL3DataType type; + } + + public DatabaseDataExtractor(Connection connection, Set<String> schemas, File directory) throws OseeDataStoreException { + this.connection = connection; + this.schemas = schemas; + this.directory = directory; + this.workerThreads = new ArrayList<Thread>(); + this.extractTables = new TreeSet<String>(); + this.dbType = SupportedDatabase.getDatabaseType(connection); + } + + public void addTableNameToExtract(String fullyQualifiedTableName) { + this.extractTables.add(fullyQualifiedTableName); + } + + public void clearFilter() { + this.extractTables.clear(); + } + + public void extract() throws OseeDataStoreException { + FileUtility.setupDirectoryForWrite(directory); + extractData(); + } + + private class DataExtractorThread extends Thread { + private TableElement table; + + public DataExtractorThread(TableElement table) { + this.table = table; + setName(table.getName() + " Extractor"); + } + + public void run() { + ConnectionHandlerStatement chStmt = new ConnectionHandlerStatement(connection); + try { + try { + chStmt.runPreparedQuery(SQL_WILD_QUERY + table.getFullyQualifiedTableName()); + } catch (OseeDataStoreException ex) { + chStmt.runPreparedQuery(SQL_WILD_QUERY + table.getName()); + } + + Document document = buildXml(chStmt, table); + if (document != null) { + writeDocumentToFile(document, table.getFullyQualifiedTableName()); + } + } catch (Exception ex) { + OseeLog.log(DatabaseActivator.class, Level.SEVERE, + "Error Processing Table [ " + table.getSchema() + "." + table.getName() + " ] Data ", ex); + } finally { + chStmt.close(); + } + } + } + + public void waitForWorkerThreads() { + for (Thread worker : workerThreads) { + try { + worker.join(); + } catch (InterruptedException ex) { + OseeLog.log(DatabaseActivator.class, Level.SEVERE, "Thread [" + worker.getName() + "] was Interrupted. ", + ex); + } + } + } + + private void extractData() throws OseeDataStoreException { + databaseInfo = new DatabaseSchemaExtractor(connection, schemas); + databaseInfo.extractSchemaData(); + Map<String, SchemaData> schemaDataMap = databaseInfo.getSchemas(); + Set<String> schemaKeys = schemaDataMap.keySet(); + for (String schema : schemaKeys) { + SchemaData schemaData = schemaDataMap.get(schema); + + List<TableElement> tables = schemaData.getTablesOrderedByDependency(); + for (TableElement table : tables) { + + boolean extract = true; + // only extract items in filter since filter was set with data + if (this.extractTables != null && this.extractTables.size() > 0) { + extract = extractTables.contains(table.getFullyQualifiedTableName()); + } + + if (extract) { + DataExtractorThread workerThread = new DataExtractorThread(table); + workerThreads.add(workerThread); + workerThread.start(); + } + } + } + } + + private Document buildXml(ConnectionHandlerStatement chStmt, TableElement table) throws OseeDataStoreException { + ArrayList<ColumnInfo> columns = new ArrayList<ColumnInfo>(); + int numberOfColumns = chStmt.getColumnCount(); + for (int index = 1; index <= numberOfColumns; index++) { + ColumnInfo columnInfo = new ColumnInfo(); + columnInfo.name = chStmt.getColumnName(index); + columnInfo.name = columnInfo.name.toUpperCase(); + + int dataType = chStmt.getColumnType(index); + if (dbType.equals(SupportedDatabase.foxpro)) { + if (dataType == Types.CHAR) { + dataType = Types.VARCHAR; + } + } + columnInfo.type = SQL3DataType.get(dataType); + columns.add(columnInfo); + } + + Document xmlDoc = new DocumentImpl(); + Element rootElement = xmlDoc.createElement(TableTags.Table.name()); + xmlDoc.appendChild(rootElement); + rootElement.setAttribute(TableDescriptionFields.schema.name(), table.getSchema()); + rootElement.setAttribute(TableDescriptionFields.name.name(), table.getName()); + + for (ColumnInfo info : columns) { + Element columnInfo = xmlDoc.createElement(TableTags.ColumnInfo.name()); + rootElement.appendChild(columnInfo); + columnInfo.setAttribute(ColumnFields.id.name(), info.name); + columnInfo.setAttribute(ColumnFields.type.name(), info.type.name()); + } + + while (chStmt.next()) { + Element columnElement = xmlDoc.createElement(TableTags.Row.name()); + for (ColumnInfo column : columns) { + String columnValue; + switch (column.type) { + case BIGINT: + BigDecimal bigD = chStmt.getBigDecimal(column.name); + columnValue = (bigD != null ? bigD.toString() : ""); + break; + case DATE: + Date date = chStmt.getDate(column.name); + columnValue = (date != null ? date.toString() : ""); + break; + case TIME: + Time time = chStmt.getTime(column.name); + columnValue = (time != null ? time.toString() : ""); + break; + case TIMESTAMP: + Timestamp timestamp = chStmt.getTimestamp(column.name); + columnValue = (timestamp != null ? timestamp.toString() : ""); + break; + default: + columnValue = chStmt.getString(column.name); + columnValue = handleSpecialCharacters(columnValue); + break; + } + columnElement.setAttribute(column.name, (columnValue != null ? columnValue : "")); + } + rootElement.appendChild(columnElement); + } + return xmlDoc; + } + + private String handleSpecialCharacters(String value) { + // \0 An ASCII 0 (NUL) character. + // '' A single quote (�'�) character. + // \b A backspace character. + // \n A newline (linefeed) character. + // \r A carriage return character. + // \t A tab character. + // \Z ASCII 26 (Control-Z). See note following the table. + + if (value != null) { + + value = value.replaceAll("\0", ""); + value = value.replaceAll("'", "''"); + // value = value.replaceAll("\"", "\\\\\""); No need to do this. + Pattern pattern = + Pattern.compile("[^" + "a-zA-Z0-9" + "!@#$%\\^&*\\(\\)" + "+ _.-=" + "\'\"<>{}\\[\\]|:;,\n\r\t\b?/`~\\\\]+"); + Matcher matcher = pattern.matcher(value); + + while (matcher.find()) { + // System.out.println("Matcher: [" + matcher.group() + "]"); + value = value.replace(matcher.group(), ""); + } + } + return value; + } + + private void writeDocumentToFile(Document doc, String tableName) throws IOException { + String fileString = directory + File.separator + tableName + DbConfigFileInformation.getDbDataFileExtension(); + OutputFormat outputFormat; + OutputStreamWriter out = null; + try { + OutputStream bout = new BufferedOutputStream(new FileOutputStream(fileString)); + out = new OutputStreamWriter(bout); + + outputFormat = new OutputFormat("XML", "UTF-8", true); + XMLSerializer xmlSerializer = new XMLSerializer(out, outputFormat); + xmlSerializer.serialize(doc.getDocumentElement()); + } catch (FileNotFoundException ex) { + OseeLog.log(DatabaseActivator.class, Level.SEVERE, "File error [" + fileString + "] ", ex); + } catch (IOException ex) { + OseeLog.log(DatabaseActivator.class, Level.SEVERE, "Error writing to File [" + fileString + "] ", ex); + } finally { + out.flush(); + out.close(); + } + } +}
\ No newline at end of file diff --git a/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/utility/DatabaseDataImporter.java b/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/utility/DatabaseDataImporter.java new file mode 100644 index 00000000000..9cc06dd2d2e --- /dev/null +++ b/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/utility/DatabaseDataImporter.java @@ -0,0 +1,256 @@ +/******************************************************************************* + * 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.database.utility; + +import java.io.File; +import java.sql.Connection; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.TreeSet; +import java.util.logging.Level; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; +import org.eclipse.osee.framework.database.DatabaseActivator; +import org.eclipse.osee.framework.database.data.ColumnDbData; +import org.eclipse.osee.framework.database.data.ColumnMetadata; +import org.eclipse.osee.framework.database.data.TableElement; +import org.eclipse.osee.framework.database.data.TableElement.ColumnFields; +import org.eclipse.osee.framework.database.data.TableElement.TableDescriptionFields; +import org.eclipse.osee.framework.database.data.TableElement.TableTags; +import org.eclipse.osee.framework.database.sql.SqlManager; +import org.eclipse.osee.framework.db.connection.exception.OseeDataStoreException; +import org.eclipse.osee.framework.jdk.core.db.DbConfigFileInformation; +import org.eclipse.osee.framework.logging.OseeLog; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.NamedNodeMap; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; + +/** + * @author Roberto E. Escobar + */ +public class DatabaseDataImporter { + private Connection connection; + private File directory; + private SqlManager sqlManager; + private List<String> tableOrder; + private String schemaToImportTo; + private Set<String> tableFilter; + + private class TableData extends TableElement { + private List<List<ColumnDbData>> rowData; + + public TableData() { + rowData = new ArrayList<List<ColumnDbData>>(); + } + + public void addRow(List<ColumnDbData> row) { + rowData.add(row); + } + + public List<List<ColumnDbData>> getRows() { + return rowData; + } + } + + public DatabaseDataImporter(Connection connection, File directory, SqlManager sqlManager) { + this.connection = connection; + this.directory = directory; + this.sqlManager = sqlManager; + this.tableFilter = new TreeSet<String>(); + } + + public void setImportOrder(List<String> tableOrder) { + this.tableOrder = tableOrder; + } + + public void setSchemaToImportTo(String schema) { + this.schemaToImportTo = schema; + } + + public void addToTableFilter(String fullyQualifiedTableName) { + this.tableFilter.add(fullyQualifiedTableName); + } + + public void clearTableFilter() { + this.tableFilter.clear(); + } + + public List<File> orderFilesByImportOrder(Map<String, File> toOrder) { + List<File> orderedSet = new ArrayList<File>(); + if (tableOrder != null && tableOrder.size() != 0) { + for (String tableName : tableOrder) { + if (toOrder.containsKey(tableName + DbConfigFileInformation.getDbDataFileExtension())) { + orderedSet.add(toOrder.get(tableName + DbConfigFileInformation.getDbDataFileExtension())); + } + } + } else { + Set<String> keys = toOrder.keySet(); + for (String key : keys) { + orderedSet.add(toOrder.get(key)); + } + } + return orderedSet; + } + + public Map<String, File> filterDataToImport(Map<String, File> toProcess) { + Map<String, File> filteredList = new HashMap<String, File>(); + if (tableFilter != null && tableFilter.size() != 0) { + for (String tableName : tableFilter) { + if (toProcess.containsKey(tableName + DbConfigFileInformation.getDbDataFileExtension())) { + filteredList.put(tableName + DbConfigFileInformation.getDbDataFileExtension(), + toProcess.get(tableName + DbConfigFileInformation.getDbDataFileExtension())); + } + } + } else { + return toProcess; + } + return filteredList; + } + + public void importDataIntoDatabase() { + if (FileUtility.isValidDirectory(directory)) { + Map<String, File> filesToProcess = getFilesToProcess(); + Map<String, File> filteredFiles = filterDataToImport(filesToProcess); + List<File> files = orderFilesByImportOrder(filteredFiles); + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + DocumentBuilder builder; + Document document; + for (File file : files) { + try { + builder = factory.newDocumentBuilder(); + document = builder.parse(file); + processData(parseXMLDbDataFile(document)); + } catch (ParserConfigurationException ex) { + OseeLog.log(DatabaseActivator.class, Level.SEVERE, "Unable to Parse File. ", ex); + } catch (Exception ex) { + OseeLog.log(DatabaseActivator.class, Level.SEVERE, "Exception: \n", ex); + } + } + } + } + + private Map<String, File> getFilesToProcess() { + Map<String, File> toReturn = new HashMap<String, File>(); + List<File> files = FileUtility.getDBDataFileList(directory); + for (File fileName : files) { + toReturn.put(fileName.getName(), new File(directory + File.separator + fileName.getName())); + } + return toReturn; + } + + private void processData(List<TableData> tables) throws OseeDataStoreException { + if (tables.size() != 0) { + for (TableData tableData : tables) { + OseeLog.log(DatabaseActivator.class, Level.INFO, + "Populating: [ " + tableData.getFullyQualifiedTableName() + "]\n"); + List<List<ColumnDbData>> rows = tableData.getRows(); + if (!rows.isEmpty()) { + for (List<ColumnDbData> rowData : rows) { + sqlManager.insertData(connection, rowData, tableData); + } + } + } + } + } + + private void parseColumnMetadata(Element tableElement, TableData tableData) { + NodeList columnElements = tableElement.getElementsByTagName(TableTags.ColumnInfo.name()); + if (columnElements != null) { + for (int index = 0; index < columnElements.getLength(); index++) { + Element columnElement = (Element) columnElements.item(index); + if (columnElement != null) { + + NamedNodeMap attributeMap = columnElement.getAttributes(); + if (attributeMap != null && attributeMap.getLength() != 0) { + ColumnMetadata columnMetaData = new ColumnMetadata(""); + for (int attributeIndex = 0; attributeIndex < attributeMap.getLength(); attributeIndex++) { + Node node = attributeMap.item(attributeIndex); + String nodeName = node.getNodeName(); + String nodeValue = node.getTextContent(); + if (nodeName != null && !nodeName.equals("")) { + columnMetaData.addColumnField(ColumnFields.valueOf(nodeName), + (nodeValue != null ? nodeValue : "")); + } + } + tableData.addColumn(columnMetaData); + } + } + } + } + } + + private void parseRowInformation(Element tableElement, TableData tableData) { + NodeList rowElements = tableElement.getElementsByTagName(TableTags.Row.name()); + if (rowElements != null) { + for (int rowIndex = 0; rowIndex < rowElements.getLength(); rowIndex++) { + Element row = (Element) rowElements.item(rowIndex); + if (row != null) { + NamedNodeMap attributeMap = row.getAttributes(); + if (attributeMap != null && attributeMap.getLength() != 0) { + List<ColumnDbData> rowData = new ArrayList<ColumnDbData>(); + tableData.addRow(rowData); + for (int attributeIndex = 0; attributeIndex < attributeMap.getLength(); attributeIndex++) { + Node node = attributeMap.item(attributeIndex); + String nodeName = node.getNodeName(); + String nodeValue = node.getTextContent(); + if (nodeName != null && !nodeName.equals("")) { + rowData.add(new ColumnDbData(nodeName, (nodeValue != null ? nodeValue : ""))); + } + } + } + } + } + } + } + + private List<TableData> parseXMLDbDataFile(Document document) { + NodeList tableElements = document.getElementsByTagName(TableTags.Table.name()); + List<TableData> tables = new ArrayList<TableData>(); + for (int index = 0; index < tableElements.getLength(); index++) { + Element tableXmlElement = (Element) tableElements.item(index); + if (tableXmlElement != null) { + NamedNodeMap map = tableXmlElement.getAttributes(); + if (map != null && map.getLength() != 0) { + Node tableName = map.getNamedItem(TableDescriptionFields.name.name()); + Node tableAddress = map.getNamedItem(TableDescriptionFields.schema.name()); + String tableNameString = ""; + String tableAddressString = ""; + if (tableName != null) { + tableNameString = tableName.getTextContent(); + } + if (tableAddress != null) { + tableAddressString = tableAddress.getTextContent(); + } + + if (tableNameString != null && !tableNameString.equals("") && tableAddressString != null && !tableAddressString.equals("")) { + TableData tableData = new TableData(); + tableData.addTableDescription(TableDescriptionFields.name, tableNameString); + if (this.schemaToImportTo != null && !this.schemaToImportTo.equals("")) { + tableData.addTableDescription(TableDescriptionFields.schema, schemaToImportTo); + } else { + tableData.addTableDescription(TableDescriptionFields.schema, tableAddressString); + } + parseRowInformation(tableXmlElement, tableData); + parseColumnMetadata(tableXmlElement, tableData); + tables.add(tableData); + } + } + } + } + return tables; + } +} diff --git a/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/utility/DatabaseSchemaExtractor.java b/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/utility/DatabaseSchemaExtractor.java new file mode 100644 index 00000000000..4823dc29e13 --- /dev/null +++ b/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/utility/DatabaseSchemaExtractor.java @@ -0,0 +1,502 @@ +/******************************************************************************* + * 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.database.utility; + +import java.io.File; +import java.io.IOException; +import java.sql.Connection; +import java.sql.DatabaseMetaData; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Types; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.TreeSet; +import java.util.logging.Level; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.transform.TransformerException; +import org.eclipse.osee.framework.database.DatabaseActivator; +import org.eclipse.osee.framework.database.data.AppliesToClause; +import org.eclipse.osee.framework.database.data.ColumnMetadata; +import org.eclipse.osee.framework.database.data.ConstraintElement; +import org.eclipse.osee.framework.database.data.ConstraintFactory; +import org.eclipse.osee.framework.database.data.ConstraintTypes; +import org.eclipse.osee.framework.database.data.ForeignKey; +import org.eclipse.osee.framework.database.data.IndexElement; +import org.eclipse.osee.framework.database.data.ReferenceClause; +import org.eclipse.osee.framework.database.data.SchemaData; +import org.eclipse.osee.framework.database.data.TableElement; +import org.eclipse.osee.framework.database.data.AppliesToClause.OrderType; +import org.eclipse.osee.framework.database.data.ReferenceClause.OnDeleteEnum; +import org.eclipse.osee.framework.database.data.ReferenceClause.OnUpdateEnum; +import org.eclipse.osee.framework.database.data.TableElement.ColumnFields; +import org.eclipse.osee.framework.database.data.TableElement.TableDescriptionFields; +import org.eclipse.osee.framework.db.connection.exception.OseeDataStoreException; +import org.eclipse.osee.framework.db.connection.info.SQL3DataType; +import org.eclipse.osee.framework.db.connection.info.SupportedDatabase; +import org.eclipse.osee.framework.jdk.core.db.DbConfigFileInformation; +import org.eclipse.osee.framework.jdk.core.util.xml.Jaxp; +import org.eclipse.osee.framework.logging.OseeLog; + +/** + * @author Roberto E. Escobar + */ +public class DatabaseSchemaExtractor { + + private DatabaseMetaData dbData; + private String dbName; + private String dbVersion; + private Map<String, SchemaData> database; + private List<String> filter; + private Set<String> tablesToExtract; + private Set<String> schemas; + private SupportedDatabase dbType; + + private static final String DEFAULT_FILTER = "BIN.*"; + + public DatabaseSchemaExtractor(Connection connection, Set<String> schemas) throws OseeDataStoreException { + try { + this.dbData = connection.getMetaData(); + this.dbName = dbData.getDatabaseProductName(); + this.dbVersion = dbData.getDatabaseProductVersion(); + this.dbType = SupportedDatabase.getDatabaseType(connection); + this.filter = new ArrayList<String>(); + filter.add(DEFAULT_FILTER); + this.tablesToExtract = new TreeSet<String>(); + this.schemas = schemas; + } catch (SQLException ex) { + throw new OseeDataStoreException(ex); + } + } + + public void addToFilter(String value) { + filter.add(value); + } + + public String getDBName() { + return dbName; + } + + public String getDBVersion() { + return dbVersion; + } + + public Map<String, SchemaData> getSchemas() { + return database; + } + + public void extractSchemaData() throws OseeDataStoreException { + database = new HashMap<String, SchemaData>(); + for (String schema : schemas) { + SchemaData dbTables = getTableInformation(schema); + database.put(schema, dbTables); + } + } + + public Set<String> getAllSchemas() throws SQLException { + ResultSet schemaResults = dbData.getSchemas(); + Set<String> schemaSet = new TreeSet<String>(); + + while (schemaResults.next()) { + String schema = schemaResults.getString("TABLE_SCHEM"); + if (schema != null && !schema.equals("")) { + schemaSet.add(schema); + } + } + schemaResults.close(); + return schemaSet; + } + + /** + * Writes the XML files in the directory specified. + * + * @param directory The directory tow write the XML files. + * @throws IOException + */ + public void writeToFile(File directory) throws IOException { + FileUtility.setupDirectoryForWrite(directory); + Set<String> keys = database.keySet(); + for (String schema : keys) { + SchemaData tableData = database.get(schema); + File xmlFile = + new File( + directory.getAbsolutePath() + File.separator + schema + DbConfigFileInformation.getSchemaFileExtension()); + try { + Jaxp.writeXmlDocument(tableData.getXmlDocument(), xmlFile); + } catch (TransformerException ex) { + OseeLog.log(DatabaseActivator.class, Level.SEVERE, ex.toString(), ex); + } catch (ParserConfigurationException ex) { + OseeLog.log(DatabaseActivator.class, Level.SEVERE, ex.toString(), ex); + } + } + } + + public String toString() { + String toReturn = "Name: " + dbName + "\tVer: " + dbVersion + "\n"; + Set<String> keys = database.keySet(); + for (String schema : keys) { + SchemaData tableData = database.get(schema); + toReturn += " Schema: \n" + schema + "\n" + tableData.toString(); + } + return toReturn; + } + + private boolean isFiltered(String value) { + for (String filterExpression : filter) { + Pattern searchPattern = Pattern.compile(filterExpression, Pattern.DOTALL); + Matcher matcher = searchPattern.matcher(value); + if (matcher.find()) { + return true; + } + } + return false; + } + + public void addTableToExtract(String fullyqualifiedTableName) { + this.tablesToExtract.add(fullyqualifiedTableName); + } + + public void clearTableFilter() { + tablesToExtract.clear(); + } + + private SchemaData getTableInformation(String schemaPattern) throws OseeDataStoreException { + try { + SchemaData dbTables = new SchemaData(); + ResultSet tables = null; + tables = dbData.getTables(null, null, null, new String[] {"TABLE"}); + + while (tables.next()) { + String tableName = tables.getString("TABLE_NAME").toUpperCase(); + String schemaName = tables.getString("TABLE_SCHEM"); + if (tableName != null && !isFiltered(tableName) && schemaName.equalsIgnoreCase(schemaPattern)) { + boolean extract = true; + if (this.tablesToExtract != null && this.tablesToExtract.size() > 0) { + extract = tablesToExtract.contains(schemaPattern + "." + tableName); + } + + if (extract) { + TableElement tableEntry = new TableElement(); + tableEntry.addTableDescription(TableDescriptionFields.name, tableName); + tableEntry.addTableDescription(TableDescriptionFields.schema, schemaName); + getColumnInformation(tableEntry); + getColumnPrimaryKey(tableEntry); + + if (!(dbType.equals(SupportedDatabase.foxpro) || dbType.equals(SupportedDatabase.postgresql))) { + getColumnForeignKey(tableEntry); + } + getIndexInfo(tableEntry); + dbTables.addTableDefinition(tableEntry); + } + } + } + tables.close(); + return dbTables; + } catch (SQLException ex) { + throw new OseeDataStoreException(ex); + } + } + + private void getColumnInformation(TableElement aTable) throws SQLException { + ResultSet columns = null; + try { + columns = dbData.getColumns(null, aTable.getSchema(), aTable.getName(), null); + } catch (SQLException ex) { + columns = dbData.getColumns(null, null, aTable.getName(), null); + } + while (columns.next()) { + String id = columns.getString("COLUMN_NAME"); + id = id.toUpperCase(); + ColumnMetadata column = new ColumnMetadata(id); + + int dataType = columns.getInt("DATA_TYPE"); + if (dbType.equals(SupportedDatabase.foxpro)) { + if (dataType == Types.CHAR) { + dataType = Types.VARCHAR; + } + } + String dataTypeName = SQL3DataType.get(dataType).name(); + column.addColumnField(ColumnFields.type, dataTypeName); + + String defaultValue = ""; + int defaultType = columns.getInt("NULLABLE"); + switch (defaultType) { + case java.sql.DatabaseMetaData.columnNoNulls: + defaultValue = "not null"; + break; + case java.sql.DatabaseMetaData.columnNullable: + // Dont specify if Null - Let DB Decide. + defaultValue = ""; + break; + case java.sql.DatabaseMetaData.columnNullableUnknown: + default: + // Since unknown then don't specify + defaultValue = ""; + break; + } + if (!defaultValue.equals("")) { + column.addColumnField(ColumnFields.defaultValue, defaultValue); + } + + if (!dbType.equals(SupportedDatabase.foxpro)) { + // int dataType = columns.getInt("DATA_TYPE"); + switch (dataType) { + case java.sql.Types.CHAR: + case java.sql.Types.VARCHAR: + String limits = columns.getString("COLUMN_SIZE"); + if (limits != null && !limits.equals("")) { + column.addColumnField(ColumnFields.limits, limits); + } + break; + case java.sql.Types.DECIMAL: + case java.sql.Types.NUMERIC: + limits = columns.getString("COLUMN_SIZE"); + String decimal = columns.getString("DECIMAL_DIGITS"); + if (decimal != null && !decimal.equals("")) { + if (limits != null && !limits.equals("")) { + limits += "," + decimal; + } + } + if (limits != null && !limits.equals("")) { + column.addColumnField(ColumnFields.limits, limits); + } + default: + break; + } + } else { + switch (dataType) { + case java.sql.Types.CHAR: + case java.sql.Types.VARCHAR: + String limits = "255"; + if (limits != null && !limits.equals("")) { + column.addColumnField(ColumnFields.limits, limits); + } + break; + default: + break; + } + } + aTable.addColumn(column); + } + columns.close(); + } + + private void getColumnPrimaryKey(TableElement aTable) throws SQLException { + ResultSet primaryKeys = null; + try { + primaryKeys = dbData.getPrimaryKeys(null, aTable.getSchema(), aTable.getName()); + } catch (SQLException ex) { + primaryKeys = dbData.getPrimaryKeys(null, null, aTable.getName()); + } + Map<String, Set<String>> constraintKeyMap = new HashMap<String, Set<String>>(); + + while (primaryKeys.next()) { + String column = primaryKeys.getString("COLUMN_NAME"); + String keyId = primaryKeys.getString("PK_NAME"); + + if (keyId == null || keyId.equals("")) { + keyId = column + "_PK"; + } + + if (!constraintKeyMap.containsKey(keyId)) { + Set<String> set = new TreeSet<String>(); + set.add(column); + constraintKeyMap.put(keyId, set); + } else { + Set<String> set = constraintKeyMap.get(keyId); + if (!set.contains(column)) { + set.add(column); + } + } + } + + Set<String> keys = constraintKeyMap.keySet(); + for (String pk : keys) { + ConstraintElement constraint = + ConstraintFactory.getConstraint(ConstraintTypes.PRIMARY_KEY, aTable.getSchema(), pk, false); + Set<String> columnSet = constraintKeyMap.get(pk); + for (String column : columnSet) { + constraint.addColumn(column); + } + aTable.addConstraint(constraint); + } + primaryKeys.close(); + } + + private void getColumnForeignKey(TableElement aTable) throws SQLException { + ResultSet importedKeys = dbData.getImportedKeys(null, aTable.getSchema(), aTable.getName()); + + while (importedKeys.next()) { + + String appliesToColumnId = importedKeys.getString("FKCOLUMN_NAME"); + String fkeyId = importedKeys.getString("FK_NAME"); + String fKeyAddress = importedKeys.getString("FKTABLE_SCHEM"); + + String refersToTable = importedKeys.getString("PKTABLE_NAME"); + String refersToTableAddress = importedKeys.getString("PKTABLE_SCHEM"); + String referencesColumn = importedKeys.getString("PKCOLUMN_NAME"); + + OnDeleteEnum onDeleteAction = OnDeleteEnum.UNSPECIFIED; + String onDeleteRule = importedKeys.getString("DELETE_RULE"); + if (onDeleteRule != null && !onDeleteRule.equals("")) { + // System.out.println("onDelete: " + onDeleteRule); + int type = Integer.parseInt(onDeleteRule); + switch (type) { + case java.sql.DatabaseMetaData.importedKeyNoAction: + onDeleteAction = OnDeleteEnum.NO_ACTION; + break; + case java.sql.DatabaseMetaData.importedKeyRestrict: + onDeleteAction = OnDeleteEnum.RESTRICT; + break; + case java.sql.DatabaseMetaData.importedKeyCascade: + onDeleteAction = OnDeleteEnum.CASCADE; + break; + case java.sql.DatabaseMetaData.importedKeySetNull: + onDeleteAction = OnDeleteEnum.SET_NULL; + break; + case java.sql.DatabaseMetaData.importedKeySetDefault: + default: + onDeleteAction = OnDeleteEnum.UNSPECIFIED; + break; + } + } + + OnUpdateEnum onUpdateAction = OnUpdateEnum.UNSPECIFIED; + String onUpdateRule = importedKeys.getString("UPDATE_RULE"); + if (onUpdateRule != null && !onUpdateRule.equals("")) { + // System.out.println("onUpdate: " + onUpdateRule); + int type = Integer.parseInt(onUpdateRule); + switch (type) { + case java.sql.DatabaseMetaData.importedKeyNoAction: + onUpdateAction = OnUpdateEnum.NO_ACTION; + break; + case java.sql.DatabaseMetaData.importedKeyRestrict: + onUpdateAction = OnUpdateEnum.RESTRICT; + break; + case java.sql.DatabaseMetaData.importedKeyCascade: + case java.sql.DatabaseMetaData.importedKeySetNull: + case java.sql.DatabaseMetaData.importedKeySetDefault: + default: + onUpdateAction = OnUpdateEnum.UNSPECIFIED; + break; + } + } + + boolean deferrable = false; + String deferrabilityId = importedKeys.getString("DEFERRABILITY"); + if (deferrabilityId != null && !deferrabilityId.equals("")) { + int type = Integer.parseInt(deferrabilityId); + switch (type) { + case java.sql.DatabaseMetaData.importedKeyInitiallyDeferred: + case java.sql.DatabaseMetaData.importedKeyInitiallyImmediate: + deferrable = true; + break; + case java.sql.DatabaseMetaData.importedKeyNotDeferrable: + deferrable = false; + break; + default: + deferrable = false; + break; + } + } + + if (fKeyAddress == null || fKeyAddress.equals("")) { + fKeyAddress = aTable.getSchema(); + } + + if (fkeyId == null || fkeyId.equals("")) { + fkeyId = appliesToColumnId + "_FK"; + } + + if (refersToTableAddress == null || refersToTableAddress.equals("")) { + refersToTableAddress = aTable.getSchema(); + } + + ConstraintElement constraint = + ConstraintFactory.getConstraint(ConstraintTypes.FOREIGN_KEY, fKeyAddress, fkeyId, deferrable); + constraint.addColumn(appliesToColumnId); + + ReferenceClause ref = new ReferenceClause(refersToTableAddress, refersToTable); + ref.addColumn(referencesColumn); + + ref.setOnDeleteAction(onDeleteAction); + ref.setOnUpdateAction(onUpdateAction); + + ((ForeignKey) constraint).addReference(ref); + + aTable.addConstraint(constraint); + } + importedKeys.close(); + } + + private void getIndexInfo(TableElement aTable) throws SQLException { + ResultSet indexKeys = dbData.getIndexInfo(null, aTable.getSchema(), aTable.getName(), false, false); + Pattern pattern = Pattern.compile("SQL\\d+"); + + Map<String, Map<Integer, AppliesToClause>> indexMap = new HashMap<String, Map<Integer, AppliesToClause>>(); + + while (indexKeys.next()) { + String indexName = indexKeys.getString("INDEX_NAME"); + + if (indexName != null && indexName.length() > 0) { + Matcher matcher = pattern.matcher(indexName); + if (!matcher.matches()) { + if (indexKeys.getShort("TYPE") == DatabaseMetaData.tableIndexOther) { + + short ordinal = indexKeys.getShort("ORDINAL_POSITION"); + String columnName = indexKeys.getString("COLUMN_NAME"); + + String orderTypeString = indexKeys.getString("ASC_OR_DESC"); + OrderType orderType = OrderType.Undefined; + if (orderTypeString != null) { + if (orderTypeString.equalsIgnoreCase("A")) { + orderType = OrderType.Ascending; + } else if (orderTypeString.equalsIgnoreCase("D")) { + orderType = OrderType.Descending; + } + } + + Map<Integer, AppliesToClause> appliesTo = null; + if (indexMap.containsKey(indexName)) { + appliesTo = indexMap.get(indexName); + } else { + appliesTo = new HashMap<Integer, AppliesToClause>(); + indexMap.put(indexName, appliesTo); + } + appliesTo.put(new Integer(ordinal), new AppliesToClause(columnName, orderType)); + } + } + } + } + for (String indexName : indexMap.keySet()) { + Map<Integer, AppliesToClause> clauseMap = indexMap.get(indexName); + IndexElement element = new IndexElement(indexName); + + Set<Integer> index = clauseMap.keySet(); + Set<Integer> sortedIndex = new TreeSet<Integer>(); + for (Integer val : index) { + sortedIndex.add(val); + } + + for (Integer val : sortedIndex) { + AppliesToClause clause = clauseMap.get(val); + element.addAppliesTo(clause.getColumnName(), clause.getOrderType()); + } + aTable.addIndexData(element); + } + indexKeys.close(); + } +}
\ No newline at end of file diff --git a/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/utility/DbInit.java b/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/utility/DbInit.java new file mode 100644 index 00000000000..2ab28fcbe2f --- /dev/null +++ b/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/utility/DbInit.java @@ -0,0 +1,196 @@ +/******************************************************************************* + * 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.database.utility; + +import java.sql.Connection; +import java.sql.DatabaseMetaData; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.Map; +import java.util.Set; +import org.eclipse.osee.framework.database.data.SchemaData; +import org.eclipse.osee.framework.database.data.TableElement; +import org.eclipse.osee.framework.database.initialize.DbFactory; +import org.eclipse.osee.framework.database.sql.SqlFactory; +import org.eclipse.osee.framework.database.sql.SqlManager; +import org.eclipse.osee.framework.db.connection.ConnectionHandler; +import org.eclipse.osee.framework.db.connection.core.schema.SkynetDatabase; +import org.eclipse.osee.framework.db.connection.core.schema.View; +import org.eclipse.osee.framework.db.connection.exception.OseeDataStoreException; +import org.eclipse.osee.framework.db.connection.info.SupportedDatabase; + +public class DbInit { + + private static String oracleCreateViewCmd = "CREATE OR REPLACE FORCE VIEW "; + private static String derbyCreateViewCmd = "CREATE VIEW "; + private static String mysqlCreateViewCmd = "CREATE VIEW "; + private static String postgresqlCreateViewCmd = "CREATE VIEW "; + + /** + * @param connection + * @param databaseType + * @param databaseType2 + * @throws OseeDataStoreException + */ + public static void addViews(Connection connection, SupportedDatabase databaseType) throws OseeDataStoreException { + for (View view : SkynetDatabase.getSkynetViews()) { + String viewCreateCmd = ""; + if (databaseType == SupportedDatabase.derby) + viewCreateCmd = derbyCreateViewCmd; + else if (databaseType == SupportedDatabase.oracle) + viewCreateCmd = oracleCreateViewCmd; + else if (databaseType == SupportedDatabase.mysql) + viewCreateCmd = mysqlCreateViewCmd; + else if (databaseType == SupportedDatabase.postgresql) { + viewCreateCmd = postgresqlCreateViewCmd; + } else + throw new IllegalArgumentException("Unhandled database type."); + + ConnectionHandler.runPreparedUpdate(connection, viewCreateCmd + view.toString() + view.getDefinition()); + ConnectionHandler.runPreparedUpdate(connection, + "create OR REPLACE public synonym " + view.toString() + " for " + view.toString()); + } + } + + /** + * @param schemas + * @param schemas + * @param userSpecifiedConfig + * @param connection + * @param databaseType + * @param userSpecifiedConfig2 + * @param databaseType2 + * @throws Exception + */ + public static void addIndeces(Set<String> schemas, Map<String, SchemaData> userSpecifiedConfig, Connection connection, SupportedDatabase databaseType) throws OseeDataStoreException { + for (String schemaId : schemas) { + if (userSpecifiedConfig.containsKey(schemaId)) { + SchemaData userSpecifiedSchemaData = userSpecifiedConfig.get(schemaId); + DbFactory userDbFactory = new DbFactory(connection, databaseType, userSpecifiedSchemaData); + userDbFactory.createIndeces(); + } + } + } + + /** + * @param schemas + * @param userSpecifiedConfig2 + * @param databaseType2 + * @throws Exception + */ + public static void addTables(Set<String> schemas, Map<String, SchemaData> userSpecifiedConfig, Connection connection, SupportedDatabase databaseType) throws OseeDataStoreException { + for (String schemaId : schemas) { + if (userSpecifiedConfig.containsKey(schemaId)) { + SchemaData userSpecifiedSchemaData = userSpecifiedConfig.get(schemaId); + DbFactory userDbFactory = new DbFactory(connection, databaseType, userSpecifiedSchemaData); + userDbFactory.createTables(); + } + } + } + + /** + * @param schemas + * @param currentDatabaseConfig + * @param userSpecifiedConfig2 + * @param currentDatabaseConfig2 + * @param databaseType2 + * @throws Exception + */ + public static void dropTables(Set<String> schemas, Map<String, SchemaData> userSpecifiedConfig, Connection connection, SupportedDatabase databaseType, Map<String, SchemaData> currentDatabaseConfig) throws OseeDataStoreException { + for (String schemaId : schemas) { + if (currentDatabaseConfig.containsKey(schemaId)) { + SchemaData currentDbSchemaData = currentDatabaseConfig.get(schemaId); + SchemaData userSchema = userSpecifiedConfig.get(schemaId); + Map<String, TableElement> currentDBmap = currentDbSchemaData.getTableMap(); + Map<String, TableElement> userDbMap = userSchema.getTableMap(); + Set<String> currentDbKeys = currentDBmap.keySet(); + Set<String> userDbKeys = userDbMap.keySet(); + + SchemaData toDrop = new SchemaData(); + for (String userKey : userDbKeys) { + if (currentDbKeys.contains(userKey)) { + toDrop.addTableDefinition(currentDBmap.get(userKey)); + } + } + DbFactory currentDbFactory = new DbFactory(connection, databaseType, toDrop); + currentDbFactory.dropTables(); + } + } + } + + /** + * @param schemas + * @param currentDatabaseConfig + * @param userSpecifiedConfig2 + * @param currentDatabaseConfig2 + * @param databaseType2 + * @throws Exception + */ + public static void dropIndeces(Set<String> schemas, Map<String, SchemaData> userSpecifiedConfig, Connection connection, SupportedDatabase databaseType, Map<String, SchemaData> currentDatabaseConfig) throws OseeDataStoreException { + System.out.println("Drop Indeces"); + for (String schemaId : schemas) { + if (currentDatabaseConfig.containsKey(schemaId)) { + SchemaData currentDbSchemaData = currentDatabaseConfig.get(schemaId); + SchemaData userSchema = userSpecifiedConfig.get(schemaId); + Map<String, TableElement> currentDBmap = currentDbSchemaData.getTableMap(); + Map<String, TableElement> userDbMap = userSchema.getTableMap(); + Set<String> currentDbKeys = currentDBmap.keySet(); + Set<String> userDbKeys = userDbMap.keySet(); + + SchemaData toDrop = new SchemaData(); + for (String userKey : userDbKeys) { + if (currentDbKeys.contains(userKey)) { + toDrop.addTableDefinition(currentDBmap.get(userKey)); + } + } + DbFactory currentDbFactory = new DbFactory(connection, databaseType, toDrop); + currentDbFactory.dropIndeces(); + } + } + } + + /** + * @param connection + */ + public static void dropViews(Connection connection) throws OseeDataStoreException { + try { + DatabaseMetaData dbData = connection.getMetaData(); + ResultSet tables = dbData.getTables(null, null, null, new String[] {"VIEW"}); + while (tables.next()) { + String viewName = tables.getString("TABLE_NAME").toUpperCase(); + for (View viewToDrop : SkynetDatabase.getSkynetViews()) { + if (viewToDrop.toString().equalsIgnoreCase(viewName)) { + Statement statement = connection.createStatement(); + statement.executeUpdate("DROP VIEW " + viewName); + statement.close(); + } + } + } + } catch (SQLException ex) { + throw new OseeDataStoreException(ex); + } + } + + public static void createSchema(Connection connection, Set<String> schemas) throws OseeDataStoreException { + SqlManager manager = SqlFactory.getSqlManager(SupportedDatabase.getDatabaseType(connection)); + for (String schemaId : schemas) { + manager.createSchema(connection, schemaId.toLowerCase()); + } + } + + public static void dropSchema(Connection connection, Set<String> schemas) throws OseeDataStoreException { + SqlManager manager = SqlFactory.getSqlManager(SupportedDatabase.getDatabaseType(connection)); + for (String schemaId : schemas) { + manager.dropSchema(connection, schemaId.toLowerCase()); + } + } +} diff --git a/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/utility/FileUtility.java b/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/utility/FileUtility.java new file mode 100644 index 00000000000..d8a0b6f8e83 --- /dev/null +++ b/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/utility/FileUtility.java @@ -0,0 +1,83 @@ +/******************************************************************************* + * 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.database.utility; + +import java.io.File; +import java.io.FilenameFilter; +import java.net.MalformedURLException; +import java.net.URL; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import org.eclipse.osee.framework.jdk.core.db.DbConfigFileInformation; + +// TODO: this class has some overlap with methods provided in org.eclipse.osee.framework.jdk.core.Lib +public class FileUtility { + + public static boolean isValidDirectory(File directory) { + if (directory != null && directory.exists() && directory.canRead()) { + File[] listOfFiles = directory.listFiles(); + if (listOfFiles.length != 0) { + return true; + } + } + return false; + } + + public static void setupDirectoryForWrite(File directory) { + if (directory.exists() && directory.canWrite()) { + if (!directory.isDirectory()) { + directory.mkdirs(); + } + } else { + directory.mkdirs(); + } + } + + public static List<File> getFileList(File sourceDirectory, final String extension) { + File[] listOfFiles = sourceDirectory.listFiles(new FilenameFilter() { + public boolean accept(File directoryName, String filename) { + return filename.endsWith(extension) && (new File(directoryName + File.separator + filename)).canRead(); + } + }); + return Arrays.asList(listOfFiles); + } + + public static List<URL> getSchemaFileList(File sourceDirectory) { + List<File> files = getFileList(sourceDirectory, DbConfigFileInformation.getSchemaFileExtension()); + List<URL> streams = new ArrayList<URL>(); + for (File file : files) { + try { + streams.add(file.toURI().toURL()); + } catch (MalformedURLException e) { + e.printStackTrace(); + } + } + return streams; + } + + public static List<File> getDBDataFileList(File sourceDirectory) { + return getFileList(sourceDirectory, DbConfigFileInformation.getDbDataFileExtension()); + } + + public static List<URL> getDBDataFileListInputStream(File sourceDirectory) { + List<File> files = getFileList(sourceDirectory, DbConfigFileInformation.getDbDataFileExtension()); + List<URL> streams = new ArrayList<URL>(); + for (File file : files) { + try { + streams.add(file.toURI().toURL()); + } catch (MalformedURLException e) { + e.printStackTrace(); + } + } + return streams; + } +} diff --git a/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/utility/GroupSelection.java b/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/utility/GroupSelection.java new file mode 100644 index 00000000000..0849f49d60c --- /dev/null +++ b/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/utility/GroupSelection.java @@ -0,0 +1,88 @@ +/*******************************************************************************
+ * 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.database.utility;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.logging.Level;
+import org.eclipse.core.runtime.IConfigurationElement;
+import org.eclipse.core.runtime.Platform;
+import org.eclipse.osee.framework.database.DatabaseActivator;
+import org.eclipse.osee.framework.logging.OseeLog;
+import org.eclipse.osee.framework.plugin.core.util.ExtensionPoints;
+
+/**
+ * @author Andrew M. Finkbeiner
+ */
+public class GroupSelection {
+ private static final GroupSelection instance = new GroupSelection();
+ private final Map<String, List<String>> initGroups = new HashMap<String, List<String>>();
+
+ /**
+ * @param initGroups
+ */
+ private GroupSelection() {
+ super();
+ populateDbInitChoices();
+ }
+
+ public static GroupSelection getInstance() {
+ return instance;
+ }
+
+ private void populateDbInitChoices() {
+ List<IConfigurationElement> elements =
+ ExtensionPoints.getExtensionElements(DatabaseActivator.getInstance(), "AddDbInitChoice", "dbInitChoice");
+
+ for (IConfigurationElement element : elements) {
+ String choiceClass = element.getAttribute("classname");
+ try {
+ IAddDbInitChoice choice =
+ (IAddDbInitChoice) Platform.getBundle(element.getContributor().getName()).loadClass(choiceClass).newInstance();
+ choice.addDbInitChoice(this);
+ } catch (InstantiationException ex) {
+ OseeLog.log(DatabaseActivator.class, Level.SEVERE, ex);
+ } catch (IllegalAccessException ex) {
+ OseeLog.log(DatabaseActivator.class, Level.SEVERE, ex);
+ } catch (ClassNotFoundException ex) {
+ OseeLog.log(DatabaseActivator.class, Level.SEVERE, ex);
+ }
+ }
+ }
+
+ private void addCommonChoices(List<String> dbInitTasks, boolean bareBones) {
+ List<String> initTasks = new ArrayList<String>();
+ initTasks.add("org.eclipse.osee.framework.skynet.core.SkynetDbInit");
+ dbInitTasks.addAll(0, initTasks);
+ dbInitTasks.add("org.eclipse.osee.framework.skynet.core.PostDbUserCleanUp");
+ dbInitTasks.add("org.eclipse.osee.framework.skynet.core.SkynetDbBranchDataImport");
+ dbInitTasks.add("org.eclipse.osee.framework.database.PostDbInitializationProcess");
+ }
+
+ public void addChoice(String listName, List<String> dbInitTasks, boolean bareBones) {
+ addCommonChoices(dbInitTasks, bareBones);
+ initGroups.put(listName, dbInitTasks);
+ }
+
+ public List<String> getChoices() {
+ List<String> choices = new ArrayList<String>(initGroups.keySet());
+ Collections.sort(choices);
+ return choices;
+ }
+
+ public List<String> getDbInitTasksByChoiceEntry(String choice) {
+ return initGroups.get(choice);
+ }
+}
\ No newline at end of file diff --git a/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/utility/IAddDbInitChoice.java b/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/utility/IAddDbInitChoice.java new file mode 100644 index 00000000000..1f7a007b32f --- /dev/null +++ b/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/utility/IAddDbInitChoice.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.database.utility; + +/** + * @author Ryan D. Brooks + */ +public interface IAddDbInitChoice { + public abstract void addDbInitChoice(GroupSelection groupSelection); +} diff --git a/org.eclipse.osee.framework.database/support/dbrelease.xml b/org.eclipse.osee.framework.database/support/dbrelease.xml new file mode 100644 index 00000000000..84fd5bb354d --- /dev/null +++ b/org.eclipse.osee.framework.database/support/dbrelease.xml @@ -0,0 +1,88 @@ +<project name="DBRelease" default="dbrelease" basedir="..">
+
+ <property name="ECLIPSE_HOME" value="C:\Program Files\OSEE" />
+ <property name="release" value="dbrelease/" />
+ <property name="targetzip" value="${release}../oseeDatabase.zip" />
+ <property name="manifestname" value="RELEASE.MF" />
+ <property name="antdir" value="ant/" />
+ <property name="derby" value="${ECLIPSE_HOME}\plugins\org.apache.derby.core_10.1.2.1" />
+
+ <property name="eclipseruntimejar" value="org.eclipse.core.runtime_3.1.2.jar"/>
+ <property name="eclipseJFacejar" value="org.eclipse.jface_3.1.1.jar" />
+ <property name="eclipseRuntime" value="${ECLIPSE_HOME}\plugins\${eclipseruntimejar}" />
+ <property name="eclipseJFace" value="${ECLIPSE_HOME}\plugins\${eclipseJFacejar}" />
+
+ <property name="oseecore" value="osee.jdk.core/bin/" />
+ <property name="oseedb" value="osee.database/bin/" />
+ <property name="oseejini" value="osee.jini/bin/" />
+ <property name="oseeats2" value="osee.ats2/bin/" />
+ <property name="oseedefine" value="osee.define/bin/" />
+
+ <target name="clean">
+ <delete file="${manifestname}" />
+ <delete dir="${release}" />
+ </target>
+
+ <target name="createrelease">
+ <echo message="createrelease PATH=${PATH}" />
+ <mkdir dir="${PATH}" />
+ <manifest file="RELEASE.MF">
+ <attribute name="Main-Class" value="osee/database/core/OseeDbLauncher" />
+ <attribute name="Class-Path" value="oseecore.jar oseejini.jar oseedefine.jar oseeats2.jar derby.jar derbyclient.jar derbynet.jar derbytools.jar ${eclipseruntimejar} ${eclipseJFacejar}" />
+ <section name="common">
+ <attribute name="Specification-Title" value="Example" />
+ <attribute name="Specification-Version" value="${version}" />
+ <attribute name="Specification-Vendor" value="Example Organization" />
+ <attribute name="Implementation-Title" value="common" />
+ <attribute name="Implementation-Version" value="${version} ${TODAY}" />
+ <attribute name="Implementation-Vendor" value="Example Corp." />
+ </section>
+ </manifest>
+
+ <jar jarfile="${PATH}/oseedb.jar" basedir="../${oseedb}" manifest="RELEASE.MF" />
+ <jar jarfile="${PATH}/oseecore.jar" basedir="../${oseecore}" />
+ <jar jarfile="${PATH}/oseejini.jar" basedir="../${oseejini}" />
+ <jar jarfile="${PATH}/oseeats2.jar" basedir="../${oseeats2}" />
+ <jar jarfile="${PATH}/oseedefine.jar" basedir="../${oseedefine}" />
+
+ <copy toDir="${PATH}/">
+ <fileset file="${eclipseRuntime}"/>
+ <fileset file="${eclipseJFace}" />
+ </copy>
+
+ <copy toDir="${PATH}/">
+ <fileset dir="${derby}" includes="*.jar" />
+ </copy>
+
+ <copy toDir="${PATH}/DatabaseSchemaDump">
+ <fileset dir="DatabaseSchemaDump"/>
+ </copy>
+
+ <copy toDir="${PATH}/excelFiles">
+ <fileset dir="excelFiles"/>
+ </copy>
+
+ <copy toDir="${PATH}/support/">
+ <fileset file="../${oseecore}/../support/oseeSiteConfig.xml" />
+ </copy>
+ <delete file="${manifestname}" />
+ </target>
+
+ <target name="dbrelease">
+ <antcall target="createrelease">
+ <param name="PATH" value="dbrelease/" />
+ </antcall>
+ </target>
+
+ <target name="dbreleasezip">
+ <antcall target="createrelease">
+ <param name="PATH" value="temp/" />
+ </antcall>
+ <zip destfile="${targetzip}">
+ <fileset dir="temp/" />
+ </zip>
+
+ <delete dir="temp/" />
+ </target>
+
+</project>
\ No newline at end of file diff --git a/org.eclipse.osee.framework.database/support/sqlAnt.xml b/org.eclipse.osee.framework.database/support/sqlAnt.xml new file mode 100644 index 00000000000..9363f690fc2 --- /dev/null +++ b/org.eclipse.osee.framework.database/support/sqlAnt.xml @@ -0,0 +1,84 @@ +<project name="SQLAnt" default="query" basedir=".">
+
+ <!-- LOCAL DERBY PROPERTIES -->
+ <property name="driver" value="org.apache.derby.jdbc.ClientDriver"/>
+ <property name="url" value="jdbc:derby://localhost:1621/DerbyDatabase;create=true"/>
+ <property name="userid" value="osee"/>
+ <property name="password" value="osee"/>
+ <property name="driverpath" value="C:\Program Files\OSEE\plugins\org.apache.derby.core_10.1.2.1\derbyclient.jar" />
+
+ <target name="query" >
+ <sql driver="${driver}" url="${url}" userid="${userid}" password="${password}" print="true" >
+ <classpath><pathelement location="${driverpath}"/></classpath>
+ select * from OSEE_DEFINE_ATTRIBUTE_TYPE
+ </sql>
+ </target>
+
+ <target name="getAllOseeInfo" >
+ <sql driver="${driver}" url="${url}" userid="${userid}" password="${password}" print="true" >
+ <classpath><pathelement location="${driverpath}"/></classpath>
+ select * from OSEE_INFO
+ </sql>
+ </target>
+
+ <target name="insertderbyTestScriptOutputFalse" >
+ <sql driver="${driver}" url="${url}" userid="${userid}" password="${password}" print="true" >
+ <classpath><pathelement location="${driverpath}"/></classpath>
+ insert into OSEE_INFO (OSEE_VALUE, OSEE_KEY) values ('FALSE', 'SAVE_OUTFILE_IN_DB')
+ </sql>
+ </target>
+
+ <target name="saveTestScriptOutputTrue" >
+ <sql driver="${driver}" url="${url}" userid="${userid}" password="${password}" print="true" >
+ <classpath><pathelement location="${driverpath}"/></classpath>
+ UPDATE OSEE_INFO SET OSEE_VALUE = 'TRUE'
+ WHERE OSEE_KEY = 'SAVE_OUTFILE_IN_DB'
+ </sql>
+ </target>
+
+ <target name="saveTestScriptOutputFalse" >
+ <sql driver="${driver}" url="${url}" userid="${userid}" password="${password}" print="true" >
+ <classpath><pathelement location="${driverpath}"/></classpath>
+ UPDATE OSEE_INFO SET OSEE_VALUE = 'FALSE'
+ WHERE OSEE_KEY = 'SAVE_OUTFILE_IN_DB'
+ </sql>
+ </target>
+
+ <target name="testskynet" >
+ <sql driver="${driver}" url="${url}" userid="${userid}" password="${password}" print="true" >
+ <classpath><pathelement location="${driverpath}"/></classpath>
+ SELECT attr_type_id FROM OSEE_DEFINE_valid_attributes WHERE art_type_id = 20 AND gamma_id <= 100000
+ </sql>
+ </target>
+
+
+ <target name="testskynet2" >
+ <sql driver="${driver}" url="${url}" userid="${userid}" password="${password}" print="true" >
+ <classpath><pathelement location="${driverpath}"/></classpath>
+ SELECT OSEE_DEFINE_attr_base_type.attribute_class,
+ OSEE_DEFINE_attribute_type.attr_type_id,
+ OSEE_DEFINE_attribute_type.name,
+ OSEE_DEFINE_attribute_type.default_value,
+ OSEE_DEFINE_attribute_type.validity_xml,
+ OSEE_DEFINE_attribute_type.min_occurence,
+ OSEE_DEFINE_attribute_type.max_occurence,
+ OSEE_DEFINE_attribute_type.user_viewable,
+ OSEE_DEFINE_attribute_type.tip_text
+ FROM OSEE_DEFINE_attribute_type, OSEE_DEFINE_attr_base_type,transaction_gamma_view
+ WHERE OSEE_DEFINE_attr_base_type.attr_base_type_id=OSEE_DEFINE_attribute_type.attr_base_type_id
+ AND transaction_gamma_view.transaction_id=179
+ AND OSEE_DEFINE_attribute_type.gamma_id<=transaction_gamma_view.largest_gamma_id
+ </sql>
+ </target>
+
+
+ <target name="getseqtable" >
+ <sql driver="${driver}" url="${url}" userid="${userid}" password="${password}" print="true" >
+ <classpath><pathelement location="${driverpath}"/></classpath>
+ SELECT * FROM OSEE_DEFINE_SEQUENCE
+ </sql>
+ </target>
+
+</project>
+
+
|