diff options
author | rbrooks | 2007-12-08 07:45:39 +0000 |
---|---|---|
committer | rbrooks | 2007-12-08 07:45:39 +0000 |
commit | d19b50ce5d56f1f6c3bc38cba0d3d20b5291265e (patch) | |
tree | ef75eeb914538ac7400404b3aff3481db069816a | |
parent | e8f608978dd689780d59b1066920867b691ee6c4 (diff) | |
download | org.eclipse.osee-d19b50ce5d56f1f6c3bc38cba0d3d20b5291265e.tar.gz org.eclipse.osee-d19b50ce5d56f1f6c3bc38cba0d3d20b5291265e.tar.xz org.eclipse.osee-d19b50ce5d56f1f6c3bc38cba0d3d20b5291265e.zip |
[CQ 1720]
233 files changed, 22490 insertions, 0 deletions
diff --git a/org.eclipse.osee.framework.antsupport/.classpath b/org.eclipse.osee.framework.antsupport/.classpath new file mode 100644 index 00000000000..751c8f2e504 --- /dev/null +++ b/org.eclipse.osee.framework.antsupport/.classpath @@ -0,0 +1,7 @@ +<?xml version="1.0" encoding="UTF-8"?> +<classpath> + <classpathentry kind="src" path="src"/> + <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/> + <classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/> + <classpathentry kind="output" path="bin"/> +</classpath> diff --git a/org.eclipse.osee.framework.antsupport/.project b/org.eclipse.osee.framework.antsupport/.project new file mode 100644 index 00000000000..2b2e4e162e4 --- /dev/null +++ b/org.eclipse.osee.framework.antsupport/.project @@ -0,0 +1,28 @@ +<?xml version="1.0" encoding="UTF-8"?> +<projectDescription> + <name>org.eclipse.osee.framework.antsupport</name> + <comment></comment> + <projects> + </projects> + <buildSpec> + <buildCommand> + <name>org.eclipse.jdt.core.javabuilder</name> + <arguments> + </arguments> + </buildCommand> + <buildCommand> + <name>org.eclipse.pde.ManifestBuilder</name> + <arguments> + </arguments> + </buildCommand> + <buildCommand> + <name>org.eclipse.pde.SchemaBuilder</name> + <arguments> + </arguments> + </buildCommand> + </buildSpec> + <natures> + <nature>org.eclipse.pde.PluginNature</nature> + <nature>org.eclipse.jdt.core.javanature</nature> + </natures> +</projectDescription> diff --git a/org.eclipse.osee.framework.antsupport/META-INF/MANIFEST.MF b/org.eclipse.osee.framework.antsupport/META-INF/MANIFEST.MF new file mode 100644 index 00000000000..5e8fe8bac30 --- /dev/null +++ b/org.eclipse.osee.framework.antsupport/META-INF/MANIFEST.MF @@ -0,0 +1,10 @@ +Manifest-Version: 1.0 +Bundle-ManifestVersion: 2 +Bundle-Name: Antsupport Plug-in +Bundle-SymbolicName: org.eclipse.osee.framework.antsupport;singleton:=true +Bundle-Version: 1.0.0 +Bundle-Activator: org.eclipse.osee.framework.antsupport.Activator +Require-Bundle: org.eclipse.core.runtime, + org.eclipse.ant.core, + org.apache.ant +Eclipse-LazyStart: true diff --git a/org.eclipse.osee.framework.antsupport/build.properties b/org.eclipse.osee.framework.antsupport/build.properties new file mode 100644 index 00000000000..bdb761ec720 --- /dev/null +++ b/org.eclipse.osee.framework.antsupport/build.properties @@ -0,0 +1,6 @@ +source.. = src/ +output.. = bin/ +bin.includes = META-INF/,\ + .,\ + lib/,\ + plugin.xml diff --git a/org.eclipse.osee.framework.antsupport/lib/svnant-1.0.0/build.properties b/org.eclipse.osee.framework.antsupport/lib/svnant-1.0.0/build.properties new file mode 100644 index 00000000000..0a3f4f57e4a --- /dev/null +++ b/org.eclipse.osee.framework.antsupport/lib/svnant-1.0.0/build.properties @@ -0,0 +1,20 @@ +# -----------------------------------------------------------------------------
+# build.properties
+# This file is referenced by the sample build.xml file.
+# -----------------------------------------------------------------------------
+
+svnant.version=1.0.0
+
+# -----------------------------------------------------------------------------
+# all jar needed
+# -----------------------------------------------------------------------------
+lib.dir=lib
+svnant.jar=${lib.dir}/svnant.jar
+svnClientAdapter.jar=${lib.dir}/svnClientAdapter.jar
+svnjavahl.jar=${lib.dir}/svnjavahl.jar
+
+svnant.latest.url=http://subclipse.tigris.org/svn/subclipse/trunk/svnant/
+svnant.this.url=http://subclipse.tigris.org/svn/subclipse/tags/svnant/${svnant.version}/
+
+svnant.repository.user=guest
+svnant.repository.passwd=""
\ No newline at end of file diff --git a/org.eclipse.osee.framework.antsupport/lib/svnant-1.0.0/build.xml b/org.eclipse.osee.framework.antsupport/lib/svnant-1.0.0/build.xml new file mode 100644 index 00000000000..f20e2823a4c --- /dev/null +++ b/org.eclipse.osee.framework.antsupport/lib/svnant-1.0.0/build.xml @@ -0,0 +1,35 @@ +<?xml version="1.0"?>
+<!-- Sample build file used to retrieve svnant's sources -->
+<project name="svn-test" basedir="." default="checkoutThis">
+
+ <!-- all properties are in build.properties -->
+ <property file="build.properties" />
+
+ <!-- path to the svnant libraries. Usually they will be located in ANT_HOME/lib -->
+ <path id="project.classpath">
+ <pathelement location="${svnjavahl.jar}" />
+ <pathelement location="${svnant.jar}" />
+ <pathelement location="${svnClientAdapter.jar}" />
+ </path>
+
+ <!-- load the svn task -->
+ <taskdef resource="svntask.properties" classpathref="project.classpath"/>
+
+ <target name="clean">
+ <delete dir="src_latest"/>
+ <delete dir="src_${svnant.version}"/>
+ </target>
+
+ <target name="checkoutLatest">
+ <svn username="${svnant.repository.user}" password="${svnant.repository.passwd}">
+ <checkout url="${svnant.latest.url}" revision="HEAD" destPath="src_latest" />
+ </svn>
+ </target>
+
+ <target name="checkoutThis">
+ <svn username="${svnant.repository.user}" password="${svnant.repository.passwd}">
+ <checkout url="${svnant.this.url}" revision="HEAD" destPath="src_${svnant.version}" />
+ </svn>
+ </target>
+
+</project>
diff --git a/org.eclipse.osee.framework.antsupport/lib/svnant-1.0.0/changelog.txt b/org.eclipse.osee.framework.antsupport/lib/svnant-1.0.0/changelog.txt new file mode 100644 index 00000000000..bfc72bd1849 --- /dev/null +++ b/org.eclipse.osee.framework.antsupport/lib/svnant-1.0.0/changelog.txt @@ -0,0 +1,50 @@ +* 1.0.0
+- Built against svnClientAdapter r2401 and Subversion 1.3.1,
+ incorporating numerous bug fixes and improvements from both.
+ Removed dependency on commons-lang-2.0.jar.
+ Removed dependency on jakarta-regexp-1.4.jar.
+- Fixed revision parameter in Switch task (#305)
+- Added url property to Status task (#327)
+- Still lacks support for Subversion locking (introduced in SVN 1.2.0).
+
+* 1.0.0-rc1
+- Built against svnClientAdapter r1384 and Subversion 1.2.0,
+ incorporating numerous bug fixes and improvements from both.
+- Lacks support for Subversion locking (introduced in SVN 1.2.0).
+- Improved documentation.
+- New 'switch' and 'propget' commands for <svn> task.
+- Repository creation handles SVN file system type.
+- New JAR dependencies added (regexp, lang).
+- Add new/improved tests (e.g. of 'status', 'info', 'annotate',
+ 'switch', svnserve, etc.).
+- Adjustments to distribution packaging, including the removal of the
+ bundled JavaHL win32 DLLs.
+
+* 0.9.13
+- createRepository command added
+- status command added
+- linked with subversion 1.0.5
+
+* 0.9.1
+- ignore and diff commands added
+- more improvements to command line interface to subversion
+
+* 0.8.6
+- improvements to command line interface to subversion
+ (should work better on Linux)
+
+* 0.8.5
+- linked with subversion 0.35.1 and Berkeley DB 4.2.52
+- improvements to command line interface to subversion
+- cat, revert, propdel commands added
+
+* 0.8.2
+- linked with subversion 0.31.2
+- command line interface to subversion (experimental)
+- keywordadd, keywordsremove, keywordsset and diff commands added
+
+* 0.6.0
+- linked with Subversion 0.24.2
+- propset added
+
+* 0.1.0 - Initial Release
diff --git a/org.eclipse.osee.framework.antsupport/lib/svnant-1.0.0/doc/svn.html b/org.eclipse.osee.framework.antsupport/lib/svnant-1.0.0/doc/svn.html new file mode 100644 index 00000000000..051c4e25e85 --- /dev/null +++ b/org.eclipse.osee.framework.antsupport/lib/svnant-1.0.0/doc/svn.html @@ -0,0 +1,1132 @@ +<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
+<html>
+
+<head>
+ <META HTTP-EQUIV="CONTENT-TYPE" CONTENT="text/html; charset=windows-1252">
+ <TITLE>Svn Task</TITLE>
+ <META HTTP-EQUIV="Content-Language" CONTENT="en-us">
+ <link rel="stylesheet" type="text/css" href="http://tortoisesvn.tigris.org/branding/css/print.css" media="print" />
+<style type="text/css">
+body {
+ font: 80% Verdana, Arial, Helvetica, sans-serif;
+ margin: 12px; padding: 12px;
+/* background: rgb(95%,95%,80%); */
+ color: black;
+}
+h1 {
+ font-size: 200%; text-transform: lowercase; letter-spacing: 3px;
+ margin-bottom: 1em;
+ padding: 0.66em 0 0.33em 1em;
+ background: rgb(85%,85%,70%);
+}
+h2 {
+ background: rgb(85%,85%,70%);
+}
+h3 {
+ border:1px solid rgb(85%,85%,70%);
+ color: rgb(55%,55%,40%);
+ padding: 0.66em 0 0.33em 1em;
+ background-color: #f3f1f4;
+}
+.sample {
+ font-family: Courier, "Courier New", monospace;
+ background-color: #f3f1f4;
+ margin-left: 10px;
+ margin-right: 10px;
+ padding-top: 3px;
+ padding-bottom: 3px;
+ padding-left: 3px;
+ padding-right: 3px;
+ border:1px dashed black;
+ width: 50%;
+ }
+ table {
+ width: 80%;
+ border: 1px solid gray;
+ margin-bottom:1em;
+ }
+ th, td {
+ padding: 0 0.5em;
+ border-left: 1px solid #DDD;
+ border-bottom: 1px solid #DDD;
+ font: 70%
+}
+th {
+
+}
+</style>
+</head>
+
+<body lang="en-US" dir="LTR">
+
+<H1><Svn></H1>
+By <A HREF="mailto:users@subclipse.tigris.org">Cédric Chabanois et al.</A>
+
+
+<H2>Description</H2>
+<p>This task provides an interface to <A HREF="http://subversion.tigris.org/">Subversion</A>
+revision control system that is a compelling replacement for CVS in the open source community.
+<br>
+With the help of the underlying svnClientAdapter, <svn> task uses JavaHL (a
+native JNI interface to the subversion api) if it
+can find the corresponding library (e.g. svnjavahl.dll on windows).
+Otherwise it uses svn command line interface.</p>
+<H2>Parameters</H2>
+
+<table>
+ <tr>
+ <th>Attribute</th>
+ <th>Description</th>
+ <th>Required</th>
+ </tr>
+ <tr>
+ <td>username</td>
+ <td>username that will be used for all nested svn commands.</td>
+ <td>No</td>
+ </tr>
+ <tr>
+ <td>password</td>
+ <td>password that will be used for all nested svn commands.</td>
+ <td>No</td>
+ </tr>
+ <tr>
+ <td>javahl</td>
+ <td>Set to “false” to use command line client interface instead of JNI JavaHL binding.</td>
+ <td>No (Defaults to true)</td>
+ </tr>
+</table>
+
+<H2>Svn commands specified as nested elements</H2>
+<table>
+ <tr>
+ <td><a href="#add">add </a></td>
+ <td><a href="#createRepository">createRepository</a></td>
+ <td><a href="#import">import</a></td>
+ <td><a href="#move">move</a></td>
+ <td><a href="#status">status</a></td>
+ </tr>
+ <tr>
+ <td><a href="#cat">cat</a></td>
+ <td><a href="#delete">delete</a></td>
+ <td><a href="#keywordsset">keywordsset</a></td>
+ <td><a href="#propdel">propdel</a></td>
+ <td><a href="#switch">switch</a></td>
+ </tr>
+ <tr>
+ <td><a href="#checkout">checkout</a></td>
+ <td><a href="#diff">diff</a></td>
+ <td><a href="#keywordsadd">keywordsadd</a></td>
+ <td><a href="#propget">propget</a></td>
+ <td><a href="#update">update</a></td>
+ </tr>
+ <tr>
+ <td><a href="#commit">commit</a></td>
+ <td><a href="#export">export</a></td>
+ <td><a href="#keywordsremove">keywordsremove</a></td>
+ <td><a href="#propset">propset</a></td>
+ <td></td>
+ </tr>
+ <tr>
+ <td><a href="#copy">copy</a></td>
+ <td><a href="#ignore">ignore</a></td>
+ <td><a href="#mkdir">mkdir</a></td>
+ <td><a href="#revert">revert</a></td>
+ <td></td>
+ </tr>
+ </table>
+<p> </p>
+
+<H3><a name="add">add</a></H3>
+<p>You can add files and directories to svn repository with nested
+<CODE><add></CODE> elements.</p>
+<table>
+ <tr>
+ <td>Attribute</td>
+ <td>Description</td>
+ <td>Required</td>
+ </tr>
+ <tr>
+ <td>file</td>
+ <td>file to add to the repository</td>
+ <td>No</td>
+ </tr>
+ <tr>
+ <td>dir</td>
+ <td>directory to add to the repository</td>
+ <td>No</td>
+ </tr>
+ <tr>
+ <td>recurse</td>
+ <td>Set to "false" to operate on a single directory only
+ (applies only when <CODE>dir</CODE> attribute is set). Default is
+ "true"
+ </td>
+ <td>No</td>
+ </tr>
+</table>
+<p>Parameters specified as nested elements :
+<ul>
+<li>fileset <br>
+ Filesets are used to select sets of files to add to the repository. <br>
+ <B>Note that directories needed to add selected files will be added to the
+ repository even if they are not selected by the fileset.</B>
+</li>
+</ul>
+</p>
+
+<H3><a name="cat">cat</a></H3>
+<p>Get the content of a file on repository.</p>
+<table>
+ <tr>
+ <td>Attribute</td>
+ <td>Description</td>
+ <td>Required</td>
+ </tr>
+ <tr>
+ <td>destFile</td>
+ <td>Name of the destination file</td>
+ <td>No <BR>(default is the name of the file on the url)</td>
+ </tr>
+ <tr>
+ <td>url</td>
+ <td>Url of the file in repository</td>
+ <td>Yes</td>
+ </tr>
+ <tr>
+ <td>revision</td>
+ <td>revision to get.<BR>Possible values are :<BR>- a date with the
+ following format : MM/DD/YYYY HH:MM AM_PM<BR>- a revision number<BR>-
+ HEAD, BASE, COMMITED or PREV<BR>Default is "HEAD"
+ </td>
+ <td>No</td>
+ </tr>
+</table>
+
+<H3><a name="checkout">checkout</a></H3>
+<p>Check out a working copy from a repository.</p>
+<table>
+ <tr>
+ <td>Attribute</td>
+ <td>Description</td>
+ <td>Required</td>
+ </tr>
+ <tr>
+ <td>url</td>
+ <td>url to checkout from</td>
+ <td>Yes</td>
+ </tr>
+ <tr>
+ <td>recurse</td>
+ <td>Set to "false" to operate on single directory only.
+ Default is "true"
+ </td>
+ <td>No</td>
+ </tr>
+ <tr>
+ <td>destPath</td>
+ <td>destination directory</td>
+ <td>Yes</td>
+ </tr>
+ <tr>
+ <td>revision</td>
+ <td>revision to checkout.<BR>Possible values are :<BR>- a date with
+ the following format : MM/DD/YYYY HH:MM AM_PM<BR>- a revision
+ number<BR>- HEAD, BASE, COMMITED or PREV<BR>Default is "HEAD"
+ </td>
+ <td>No</td>
+ </tr>
+</table>
+<p>Parameters specified as nested elements :
+<ul>
+ <li>fileset<br>
+ Filesets are used to select sets of files to add to the repository. <br>
+ <B>Note that directories needed to add selected files will be added to the
+ repository even if they are not selected by the fileset.</B>
+ </li>
+</ul>
+</p>
+
+<p>
+<div class="sample">
+<FONT FACE="Courier New"><FONT SIZE=2><FONT COLOR="#000080"><svn</FONT>
+<FONT COLOR="#000080">javahl=</FONT><FONT COLOR="#008000">"${javahl}"</FONT><FONT COLOR="#000080">></FONT></FONT></FONT><br>
+<FONT FACE="Courier New"><FONT SIZE=2><FONT COLOR="#000080"><checkout</FONT>
+<FONT COLOR="#000080">url=</FONT><FONT COLOR="#008000">"${urlRepos}"</FONT>
+<FONT COLOR="#000080">destPath=</FONT><FONT COLOR="#008000">"workingcopy"</FONT>
+<FONT COLOR="#000080">/></FONT></FONT></FONT><br>
+<FONT FACE="Courier New"><FONT SIZE=2><FONT COLOR="#000080"></svn></FONT></FONT></FONT>
+</div>
+</p>
+
+<H3><a name="commit">commit</a></H3>
+<p>Send changes from your working copy to the repository.</p>
+<table>
+ <tr>
+ <td>Attribute</td>
+ <td>Description</td>
+ <td>Required</td>
+ </tr>
+ <tr>
+ <td>file</td>
+ <td>file to commit</td>
+ <td>No</td>
+ </tr>
+ <tr>
+ <td>recurse</td>
+ <td>Set to "false" to operate on single directory only.
+ Default is "true"<BR>Apply only when dir attribute is
+ set.
+ </td>
+ <td>No</td>
+ </tr>
+ <tr>
+ <td>dir</td>
+ <td>directory to commit</td>
+ <td>No</td>
+ </tr>
+ <tr>
+ <td>message</td>
+ <td>commit message</td>
+ <td>Yes</td>
+ </tr>
+</table>
+<p>Parameters specified as nested elements :
+<ul>
+ <li>fileset<BR>
+ Filesets are used to select sets of files to commit.
+ </li>
+</ul>
+</p>
+
+<H3><a name="copy">copy</a></H3>
+<p>Duplicate something in working copy or repository, remembering
+history.<BR>
+source and destination can each be either a working copy (WC) path or URL:
+<ul>
+ <li>WC->WC: copy and schedule for addition (with history)</li>
+ <li>WC->URL: immediately commit a copy of WC to URL</li>
+ <li>URL->WC: check out URL into WC, schedule for addition</li>
+ <li>URL->URL: complete server-side copy; used to branch & tag</li>
+</ul>
+</p>
+<br/>
+
+<table>
+ <tr>
+ <td>Attribute</td>
+ <td>Description</td>
+ <td>Required</td>
+ </tr>
+ <tr>
+ <td>srcPath</td>
+ <td>source path</td>
+ <TD ROWSPAN=2>One of the two</td>
+ </tr>
+ <tr>
+ <td>srcUrl</td>
+ <td>source url</td>
+ </tr>
+ <tr>
+ <td>testPath</td>
+ <td>destination path</td>
+ <TD ROWSPAN=2>One of the two</td>
+ </tr>
+ <tr>
+ <td>destUrl</td>
+ <td>destination url</td>
+ </tr>
+ <tr>
+ <td>message</td>
+ <td>commit message</td>
+ <td>when destUrl is set</td>
+ </tr>
+ <tr>
+ <td>revision</td>
+ <td>revision to copy from (when srcUrl is set)<BR>Possible values
+ are :<BR>- a date with the following format : MM/DD/YYYY HH:MM
+ AM_PM<BR>- a revision number<BR>- HEAD, BASE, COMMITED or
+ PREV<BR>Default is "HEAD"
+ </td>
+ <td>no</td>
+ </tr>
+</table>
+
+<H3><a name="createRepository">createRepository</a></H3>
+<p>Create a new, empty repository at path.</p>
+<table>
+ <tr>
+ <td>Attribute</td>
+ <td>Description</td>
+ <td>Required</td>
+ </tr>
+ <tr>
+ <td>path</td>
+ <td>Path where to create the new repository</td>
+ <td>Yes</td>
+ </tr>
+</table>
+<div class="sample" style="width: 597px; height: 77px">
+<p>Example: <br>
+<FONT FACE="Courier New"><FONT SIZE=2><FONT COLOR="#000080"><svn</FONT>
+<FONT COLOR="#000080">javahl=</FONT><FONT COLOR="#008000">"false"</FONT><FONT COLOR="#000080">><BR><createRepository</FONT>
+<FONT COLOR="#000080">path=</FONT><FONT COLOR="#008000">"repository"</FONT><FONT COLOR="#000080">/><BR></svn></FONT></FONT></FONT>
+</p>
+</div>
+
+<H3><a name="delete">delete</a></H3>
+<p>If run on a working copy target, the item is scheduled for
+deletion upon the next commit. Files, and directories that have
+not been committed, are immediately removed from the working copy.
+<BR>The command will not remove targets that are, or contain,
+unversioned or modified items; use the force attribute to override
+this behaviour.
+<BR>If run on an url, the item is deleted from the repository via an immediate commit.
+</p>
+<table>
+ <tr>
+ <td>Attribute</td>
+ <td>Description</td>
+ <td>Required</td>
+ </tr>
+ <tr>
+ <td>file</td>
+ <td>file to delete</td>
+ <td>No</td>
+ </tr>
+ <tr>
+ <td>url</td>
+ <td>url to delete</td>
+ <td>No</td>
+ </tr>
+ <tr>
+ <td>dir</td>
+ <td>directory to delete</td>
+ <td>No</td>
+ </tr>
+ <tr>
+ <td>message</td>
+ <td>commit message</td>
+ <td>when url attribute is set</td>
+ </tr>
+ <tr>
+ <td>force</td>
+ <td>default is "false"</td>
+ <td>No</td>
+ </tr>
+</table>
+<p>Parameters specified as nested elements :
+<ul>
+ <li>fileset<BR>
+ Filesets are used to select sets of files to delete..
+ </li>
+</ul>
+</p>
+
+<H3><a name="diff">diff</a></H3>
+<p>Display the differences between two paths (oldPath and newPath) or
+two urls (oldUrl and newUrl).
+</p>
+<table>
+ <tr>
+ <td>Attribute</td>
+ <td>Description</td>
+ <td>Required</td>
+ </tr>
+ <tr>
+ <td>oldPath</td>
+ <td>If oldUrl is not set, defaults to the path '.'</td>
+ <td>No</td>
+ </tr>
+ <tr>
+ <td>oldUrl</td>
+ <td> </td>
+ <td>No</td>
+ </tr>
+ <tr>
+ <td>oldTargetRevision</td>
+ <td>defaults to BASE or, if oldUrl is set, to HEAD</td>
+ <td>No</td>
+ </tr>
+ <tr>
+ <td>newPath</td>
+ <td>defaults to oldPath if oldUrl is not set</td>
+ <td>No</td>
+ </tr>
+ <tr>
+ <td>newUrl</td>
+ <td> </td>
+ <td>No</td>
+ </tr>
+ <tr>
+ <td>newTargetRevision</td>
+ <td>defaults to the current working version or, if newUrl is set, to HEAD</td>
+ <td>No</td>
+ </tr>
+ <tr>
+ <td>outFile</td>
+ <td>Default is 'patch'</td>
+ <td>No</td>
+ </tr>
+ <tr>
+ <td>recurse</td>
+ <td>Set to "false" to operate on single directory only.
+ Default is "true"
+ </td>
+ <td>No</td>
+ </tr>
+</table>
+<div class="sample" style="width: 749px; height: 80px">
+<p>Example : diff between BASE and current working version <br>
+<FONT SIZE=2 FACE="Courier New"><FONT COLOR="#000080"><svn</FONT>
+<FONT COLOR="#000080">javahl=</FONT><FONT COLOR="#008000">"${javahl}"</FONT><FONT COLOR="#000080">><BR><diff</FONT>
+<FONT COLOR="#000080">oldPath=</FONT><FONT COLOR="#008000">"workingcopy/diffTest/file.txt"</FONT>
+<FONT COLOR="#000080">outFile=</FONT><FONT COLOR="#008000">"workingcopy/diffTest/patch.txt"</FONT><FONT COLOR="#000080">/></FONT></FONT>
+<FONT COLOR="#000080"><FONT FACE="Courier New"><FONT SIZE=2><BR></svn></FONT></FONT></FONT>
+</p>
+</div>
+
+<H3><a name="export">export</a></H3>
+<p>
+<ol>
+ <li>
+ Exports a clean directory tree from the repository specified by <CODE>srcurl</CODE>,
+ at revision <CODE>revision</CODE> if it is given, otherwise at HEAD, into <CODE>destPath</CODE>.
+ </li>
+ <li>Exports a clean directory tree from the working copy specified by
+ <CODE>srcPath</CODE> into <CODE>destPath</CODE>. all local changes will be preserved,
+ but files not under revision control will not be copied.</li>
+</ol>
+</p>
+<br/>
+<table>
+ <tr>
+ <td>Attribute</td>
+ <td>Description</td>
+ <td>Required</td>
+ </tr>
+ <tr>
+ <td>srcUrl</td>
+ <td>source url to export from</td>
+ <td>One of the two</td>
+ </tr>
+ <tr>
+ <td>srcPath</td>
+ <td>source path to export from</td>
+ </tr>
+ <tr>
+ <td>destPath</td>
+ <td>destination path</td>
+ <td>Yes</td>
+ </tr>
+ <tr>
+ <td>revision</td>
+ <td>revision of the source url to export from. Defaults is
+ "HEAD"<BR>Possible values are :<BR>- a date with the
+ following format : MM/DD/YYYY HH:MM AM_PM<BR>- a revision number<BR>-
+ HEAD, BASE, COMMITED or PREV
+ </td>
+ <td>No</td>
+ </tr>
+</table>
+
+<H3><a name="ignore">ignore</a></H3>
+<p>Add a given file or a pattern to the ignored files list (modifies
+svn:ignore property)</p>
+<table>
+ <tr>
+ <td>Attribute</td>
+ <td>Description</td>
+ <td>Required</td>
+ </tr>
+ <tr>
+ <td>file</td>
+ <td>file to ignore</td>
+ <td>One of the two</td>
+ </tr>
+ <tr>
+ <td>dir</td>
+ <td>directory on which we will update svn:ignore property</td>
+ </tr>
+ <tr>
+ <td>pattern</td>
+ <td>pattern to add to svn:ignore on the directory<BR>Only when dir
+ is set
+ </td>
+ <td>Yes</td>
+ </tr>
+ <tr>
+ <td>recurse</td>
+ <td>Set to "true" to add the pattern recursively to
+ directories. Default is "false"<BR>Only when dir is set
+ </td>
+ <td>No</td>
+ </tr>
+</table>
+<div class="sample" style="width: 663px; height: 42px">
+<p>Example :<BR>
+<FONT SIZE=2><FONT FACE="Courier New"><FONT COLOR="#000080"><ignore</FONT>
+<FONT COLOR="#000080">dir=</FONT><FONT COLOR="#008000">"workingcopy/ignoreTest/dir1"</FONT>
+<FONT COLOR="#000080">pattern=</FONT><FONT COLOR="#008000">"*.ignore"</FONT>
+<FONT COLOR="#000080">recurse=</FONT><FONT COLOR="#008000">"true"</FONT><FONT COLOR="#000080">/></FONT></FONT></FONT>
+</p>
+</div>
+
+<H3><a name="import">import</a></H3>
+<p>Commit an unversioned file or tree into the repository.<BR>
+Recursively commit a copy of <CODE>path</CODE> to <CODE>url</CODE>.<BR>
+If <CODE>newEntry </CODE>is not set, copy top-level contents of <CODE>path</CODE>into<CODE>url</CODE>directly.
+Otherwise, create <CODE>newEntry </CODE>underneath <CODE>url </CODE>and begin copy there.
+</p>
+<table>
+ <tr>
+ <td>Attribute</td>
+ <td>Description</td>
+ <td>Required</td>
+ </tr>
+ <tr>
+ <td>path</td>
+ <td>source path to export from</td>
+ <td>Yes</td>
+ </tr>
+ <tr>
+ <td>url</td>
+ <td>source url to import to</td>
+ <td>Yes</td>
+ </tr>
+ <tr>
+ <td>newEntry</td>
+ <td> </td>
+ <td>No</td>
+ </tr>
+ <tr>
+ <td>message</td>
+ <td>commit message</td>
+ <td>Yes</td>
+ </tr>
+ <tr>
+ <td>recurse</td>
+ <td>Set to "false" to operate on single directory only.
+ Default is "true"
+ </td>
+ <td>False</td>
+ </tr>
+</table>
+
+<H3><a name="keywordsset">keywordsset</a></H3>
+<p>Keywordsset controls which keywords will be substituted on the
+given files. Valid keywords are:
+<ul>
+ <li>URL, HeadURL : The URL for the head version of the object.</li>
+ <li>Author, LastChangedBy : The last person to modify the file.</li>
+ <li>Date, LastChangedDate : The date/time the object was last modified.</li>
+ <li>Rev, LastChangedRevision : The last revision the object changed.</li>
+ <li>Id : A compressed summary of the previous</li>
+</ul>
+</p>
+<br/>
+<table>
+ <tr>
+ <td>Attribute</td>
+ <td>Description</td>
+ <td>Required</td>
+ </tr>
+ <tr>
+ <td>file</td>
+ <td>File for which keywords will be substituted</td>
+ <td>Either file, dir or filesets</td>
+ </tr>
+ <tr>
+ <td>dir</td>
+ <td>All files in this directory will have their keywords substituted (recursively)</td>
+ <td>Either file, dir or filesets</td>
+ </tr>
+ <tr>
+ <td>keywords</td>
+ <td>The keywords to substitute on the given files</td>
+ <td>No</td>
+ </tr>
+ <tr>
+ <td>HeadURL/URL<BR>Author, LastChangedBy<BR>Date,
+ LastChangedDate<BR>Rev, LastChangedRevision<BR>Id
+ </td>
+ <td>Set to “true“ the keyword to substitute it on the
+ given file.
+ </td>
+ <td>No</td>
+ </tr>
+</table>
+<p>Parameters specified as nested elements :
+<ul>
+ <li>fileset<BR>
+ Filesets are used to select sets of files on which to apply keywords substitution.
+ </li>
+</ul>
+</p>
+
+<H3><a name="keywordsadd">keywordsadd</a></H3>
+<p>Keywordsadd add some keywords to be substituted on the given
+files. Present keywords are not modified.<BR>
+The attributes are the same than for keywordsset command.</p>
+
+<H3><a name="keywordsremove">keywordsremove</a></H3>
+<p>Keywordsadd remove some keywords to be substituted on the given
+files. Other present keywords are not modified.<BR>
+The attributes are the same than for keywordsset command.</p>
+
+<H3><a name="mkdir">mkdir</a></H3>
+<p>Create a new directory under revision control.<BR>
+If target is a working copy path the directory is scheduled for addition in the
+working copy. If target is an url the directory is created in
+the repository via an immediate commit. <BR>
+In both cases all the intermediate directories must already exist.
+</p>
+<table>
+ <tr>
+ <td>Attribute</td>
+ <td>Description</td>
+ <td>Required</td>
+ </tr>
+ <tr>
+ <td>path</td>
+ <td>path to create</td>
+ <td>One of the two</td>
+ </tr>
+ <tr>
+ <td>url</td>
+ <td>url to create</td>
+ </tr>
+ <tr>
+ <td>message</td>
+ <td>commit message</td>
+ <td>Yes</td>
+ </tr>
+</table>
+
+<H3><a name="move">move</a></H3>
+<p>Move/rename something in working copy or repository.<BR><BR>
+cource and destination can both be working copy (WC) paths or
+URLs:<BR> WC -> WC: move and
+schedule for addition (with history)<BR> URL ->
+URL: complete server-side rename.
+</p>
+<table>
+ <tr>
+ <td>Attribute</td>
+ <td>Description</td>
+ <td>Required</td>
+ </tr>
+ <tr>
+ <td>srcPath</td>
+ <td>source path</td>
+ <td ROWSPAN=2>One of the two</td>
+ </tr>
+ <tr>
+ <td>srcUrl</td>
+ <td>source url</td>
+ </tr>
+ <tr>
+ <td>destPath</td>
+ <td>destination path</td>
+ <td ROWSPAN=2>One of the two</td>
+ </tr>
+ <tr>
+ <td>destUrl</td>
+ <td>destination url</td>
+ </tr>
+ <tr>
+ <td>message</td>
+ <td>commit message</td>
+ <td>Yes</td>
+ </tr>
+</table>
+
+<H3><a name="propdel">propdel</a></H3>
+<p>Remove a property from files or dirs.</p>
+<table>
+ <tr>
+ <td>Attribute</td>
+ <td>Description</td>
+ <td>Required</td>
+ </tr>
+ <tr>
+ <td>path</td>
+ <td>path of the file or directory on which to delete the property</td>
+ <td>Yes</td>
+ </tr>
+ <tr>
+ <td>name</td>
+ <td>name of the property to delete</td>
+ <td>Yes</td>
+ </tr>
+ <tr>
+ <td>recurse</td>
+ <td>if set, property will be removed recursively</td>
+ <td>No</td>
+ </tr>
+</table>
+
+<H3><a name="propget">propget</a></H3>
+<p>Get a property from a file or a directory.</p>
+<table>
+ <tr>
+ <td>Attribute</td>
+ <td>Description</td>
+ <td>Required</td>
+ </tr>
+ <tr>
+ <td>path</td>
+ <td>path of the file or directory on which to get the property</td>
+ <td>Yes</td>
+ </tr>
+ <tr>
+ <td>name</td>
+ <td>name of the property to get</td>
+ <td>Yes</td>
+ </tr>
+ <tr>
+ <td>property</td>
+ <td>the name of the property to set with the value of the svn property</td>
+ <td ROWSPAN=2>One of the two</td>
+ </tr>
+ <tr>
+ <td>file</td>
+ <td>file that will contain the value of the property</td>
+ </tr>
+</table>
+<div class="sample" style="width: 800px; height: 48px">
+<p>
+Example :<br>
+<FONT FACE="Courier New"><FONT SIZE=2><FONT COLOR="#000080"><propget</FONT>
+<FONT COLOR="#000080">path=</FONT><FONT COLOR="#008000">"workingcopy/propTest/file.png"</FONT>
+<FONT COLOR="#000080">name=</FONT><FONT COLOR="#008000">"svn:mime-type"</FONT>
+<FONT COLOR="#000080">property=</FONT><FONT COLOR="#008000">"propTest.mimeType"</FONT><FONT COLOR="#000080">/></FONT></FONT></FONT>
+</p>
+</div>
+
+<H3><a name="propset">propset</a></H3>
+<p>Set a property on files or dirs.</p>
+<table>
+ <tr>
+ <td>Attribute</td>
+ <td>Description</td>
+ <td>Required</td>
+ </tr>
+ <tr>
+ <td>path</td>
+ <td>path of the file or directory on which to set the property</td>
+ <td>Yes</td>
+ </tr>
+ <tr>
+ <td>name</td>
+ <td>name of the property to set</td>
+ <td>Yes</td>
+ </tr>
+ <tr>
+ <td>value</td>
+ <td>the value of the property</td>
+ <td ROWSPAN=2>One of the two</td>
+ </tr>
+ <tr>
+ <td>file</td>
+ <td>the file that will be used as a value</td>
+ </tr>
+ <tr>
+ <td>recurse</td>
+ <td>if set, property will be set recursively</td>
+ <td>No</td>
+ </tr>
+</table>
+<p>
+<I>Note:</I>svn recognizes the following special versioned properties but
+will store any arbitrary properties set:
+<ul>
+ <li>svn:ignore : A newline separated list of file patterns to ignore. </li>
+ <li>svn:keywords : Keywords to be expanded. Valid keywords are:
+ <ul>
+ <li>URL, HeadURL : The URL for the head version of the object.</li>
+ <li>Author, LastChangedBy : The last person to modify the file.</li>
+ <li>Date, LastChangedDate : The date/time the object was last modified.</li>
+ <li>Rev, LastChangedRevision : The last revision the object changed.</li>
+ <li>Id : A compressed summary of the previous 4 keywords. </li>
+ </ul>
+ </li>
+ <li>svn:executable : If present, make the file executable. This property cannot be set on a directory.
+ A non-recursive attempt will fail, and a recursive attempt will set
+ the property only on the file children of the directory
+ </li>
+ <li>svn:eol-style : One of 'native', 'LF', 'CR', 'CRLF'. </li>
+ <li>svn:mime-type : The mimetype of the file. Used to determine whether to merge the file, and
+ how to serve it from Apache. <BR>
+ A mimetype beginning with 'text/' (or an absent mimetype) is treated as text. Anything else is
+ treated as binary.
+ </li>
+ <li>svn:externals : A newline separated list of module
+ specifiers, each of which consists of a relative directory path,
+ optional revision flags, and an URL. For example<BR>
+ foo http://example.com/repos/zig <br>
+ foo/bar -r 1234 http://example.com/repos/zag
+ </li>
+</ul>
+</p>
+
+<H3><a name="revert">revert</a></H3>
+<p>Restore pristine working copy file (undo most local edits).</p>
+<table>
+ <tr>
+ <td>Attribute</td>
+ <td>Description</td>
+ <td>Required</td>
+ </tr>
+ <tr>
+ <td>file</td>
+ <td>file to revert</td>
+ <td>No</td>
+ </tr>
+ <tr>
+ <td>dir</td>
+ <td>directory to revert</td>
+ <td>No</td>
+ </tr>
+ <tr>
+ <td>recurse</td>
+ <td>Set to "false" to operate on a single directory only
+ (applies only when <CODE>dir</CODE> attribute is set). Default is
+ "false"</td>
+ <td>No</td>
+ </tr>
+ <tr>
+ <td>revision</td>
+ <td>revision. Defaults is "HEAD"<BR>Possible values are
+ :<BR>- a date with the following format : MM/DD/YYYY HH:MM AM_PM<BR>-
+ a revision number<BR>- HEAD, BASE, COMMITED or PREV</td>
+ <td>No</td>
+ </tr>
+</table>
+<p>Parameters specified as nested elements :
+<ul>
+ <li>fileset<BR>
+ Filesets are used to select sets of files to revert.
+ </li>
+</ul>
+</p>
+
+<H3><a name="status">status</a></H3>
+<p>Get the status of working copy files and directories.</p>
+<table>
+ <tr>
+ <td>Attribute</td>
+ <td>Description</td>
+ <td>Required</td>
+ </tr>
+ <tr>
+ <td>path</td>
+ <td>path of the file or directory</td>
+ <td>Yes</td>
+ </tr>
+ <tr>
+ <td>textStatusProperty</td>
+ <td>Name of the property to set to the status of the item</td>
+ <td>No</td>
+ </tr>
+ <tr>
+ <td>propStatusProperty</td>
+ <td>Name of the property to set to the status of the item
+ properties</td>
+ <td>No</td>
+ </tr>
+ <tr>
+ <td>revisionProperty</td>
+ <td>Name of the property to set to the revision of the item (or “”
+ if unversioned)</td>
+ <td>No</td>
+ </tr>
+ <tr>
+ <td>lastChangedRevisionProperty</td>
+ <td>Name of the property to set to the last changed revision of the
+ item (or “” if unversioned)</td>
+ <td>No</td>
+ </tr>
+ <tr>
+ <td>lastCommitAuthorProperty</td>
+ <td>Name of the property to set to the last commit author (or “”
+ if unversioned)</td>
+ <td>No</td>
+ </tr>
+ <tr>
+ <td>urlProperty</td>
+ <td>Name of the property to set to the url of the item</td>
+ <td>No</td>
+ </tr>
+</table>
+<p>
+The value of TextStatusProperty can be :
+<ul>
+ <li>non-svn</li>
+ <li>normal : no modifications</li>
+ <li>added</li>
+ <li>missing : item is missing (removed by non-svn command)</li>
+ <li>incomplete</li>
+ <li>deleted</li>
+ <li>replaced</li>
+ <li>modified</li>
+ <li>merged</li>
+ <li>conflicted</li>
+ <li>obstructed</li>
+ <li>ignored</li>
+ <li>external</li>
+ <li>unversioned</li>
+</ul>
+The value of propStatusProperty can be :
+<ul>
+ <li>normal : no modifications</li>
+ <li>conflicted</li>
+ <li>modified</li>
+</ul>
+</p>
+<p></p>
+<div class="sample">
+<p>
+Example : <br>
+<FONT FACE="Courier New"><FONT SIZE=2><FONT COLOR="#000080"><status</FONT>
+<FONT COLOR="#000080">path=</FONT><FONT COLOR="#008000">"workingcopy/statusTest/added.txt"</FONT>
+</FONT></FONT>
+<FONT COLOR="#000080"><FONT FACE="Courier New"><FONT SIZE=2>textStatusProperty=<FONT COLOR="#008000">"testStatus.textStatus"</FONT></FONT></FONT></FONT>
+<FONT FACE="Courier New"><FONT SIZE=2><FONT COLOR="#000080">propStatusProperty=</FONT><FONT COLOR="#008000">"testStatus.propStatus"</FONT></FONT></FONT>
+<FONT FACE="Courier New"><FONT SIZE=2><FONT COLOR="#000080">lastChangedRevisionProperty=</FONT><FONT COLOR="#008000">"testStatus.lastCommitRevision"</FONT></FONT></FONT>
+<FONT COLOR="#000080"><FONT FACE="Courier New"><FONT SIZE=2>revisionProperty=<FONT COLOR="#008000">"testStatus.revision"</FONT></FONT></FONT></FONT>
+<FONT FACE="Courier New"><FONT SIZE=2><FONT COLOR="#000080">lastCommitAuthorProperty=</FONT><FONT COLOR="#008000">"testStatus.lastCommitAuthor"</FONT></FONT></FONT>
+</p>
+</div>
+
+<H3><a name="switch">switch</a></H3>
+<p>Update the working copy to mirror a new URL within the repository.
+This behaviour is similar to 'svn update', and is the way to move a
+working copy to a branch or tag within the same repository.</p>
+<table>
+ <tr>
+ <td>Attribute</td>
+ <td>Description</td>
+ <td>Required</td>
+ </tr>
+ <tr>
+ <td>path</td>
+ <td>The working copy to switch to the given url</td>
+ <td>Yes</td>
+ </tr>
+ <tr>
+ <td>url</td>
+ <td>The url to switch to</td>
+ <td>Yes</td>
+ </tr>
+ <tr>
+ <td>recurse</td>
+ <td>Set to "false" to operate on a single directory only.
+ Default is "true"</td>
+ <td>No</td>
+ </tr>
+ <tr>
+ <td>revision</td>
+ <td>revision. Defaults is "HEAD"<BR>Possible values are
+ :<BR>- a date with the following format : MM/DD/YYYY HH:MM AM_PM<BR>-
+ a revision number<BR>- HEAD, BASE, COMMITED or PREV</td>
+ <td>No</td>
+ </tr>
+</table>
+<div class="sample" style="width: 674px; height: 85px">
+<p>
+Example :
+<FONT FACE="Courier New"><FONT SIZE=2><FONT COLOR="#000080"><br><svn></FONT></FONT></FONT>
+<FONT FACE="Courier New"><FONT SIZE=2><FONT COLOR="#000080"><br><switch</FONT>
+<FONT COLOR="#000080">path=</FONT><FONT COLOR="#008000">"workingcopy/switchTest"</FONT>
+<FONT COLOR="#000080">url=</FONT><FONT COLOR="#008000">"${urlRepos}/switchTestBranch"</FONT><FONT COLOR="#000080">/></FONT></FONT></FONT>
+<FONT COLOR="#000080"><FONT FACE="Courier New"><FONT SIZE=2><br></svn></FONT></FONT></FONT>
+</p>
+</div>
+
+<H3><a name="update">update</a></H3>
+<p>Bring changes from the repository into the working copy.<BR>If no
+revision given, bring working copy up-to-date with HEAD rev.
+Else synchronize working copy to revision.</p>
+<table>
+ <tr>
+ <td>Attribute</td>
+ <td>Description</td>
+ <td>Required</td>
+ </tr>
+ <tr>
+ <td>file</td>
+ <td>file to update</td>
+ <td>No</td>
+ </tr>
+ <tr>
+ <td>dir</td>
+ <td>directory to update</td>
+ <td>No</td>
+ </tr>
+ <tr>
+ <td>recurse</td>
+ <td>Set to "false" to operate on a single directory only
+ (applies only when <CODE>dir</CODE> attribute is set). Default is
+ "true"</td>
+ <td>No</td>
+ </tr>
+ <tr>
+ <td>revision</td>
+ <td>revision. Defaults is "HEAD"<BR>Possible values are
+ :<BR>- a date with the following format : MM/DD/YYYY HH:MM AM_PM<BR>-
+ a revision number<BR>- HEAD, BASE, COMMITED or PREV</td>
+ <td>No</td>
+ </tr>
+</table>
+Parameters specified as nested elements :
+<ul>
+<li>fileset<BR>
+Filesets are used to select sets of files to update.
+</li>
+</ul>
+
+<H2>Examples</H2>
+
+<p>
+<div class="sample" style="width: 843px; height: 128px">
+<FONT FACE="Courier New"><FONT SIZE=2><FONT COLOR="#000080"><svn</FONT><FONT COLOR="#000080">></FONT></FONT></FONT><br>
+<FONT COLOR="#000080"> <FONT FACE="Courier New"><FONT SIZE=2><delete></FONT></FONT></FONT><br>
+<FONT COLOR="#000080"> <FONT FACE="Courier New"><FONT SIZE=2><fileset</FONT>
+<FONT COLOR="#000080">dir=</FONT><FONT COLOR="#008000">"workingcopy/deleteTest"</FONT><FONT COLOR="#000080">></FONT></FONT></FONT><br>
+<FONT COLOR="#000080"> <FONT FACE="Courier New"><FONT SIZE=2><include</FONT>
+<FONT COLOR="#000080">name=</FONT><FONT COLOR="#008000">"**/*.del"</FONT><FONT COLOR="#000080">/></FONT></FONT></FONT>
+<FONT COLOR="#000080"> <FONT FACE="Courier New"><FONT SIZE=2></fileset></FONT></FONT></FONT><br>
+<FONT COLOR="#000080"> <FONT FACE="Courier New"><FONT SIZE=2></delete></FONT></FONT></FONT><br>
+<FONT COLOR="#000080"> <FONT FACE="Courier New"><FONT SIZE=2><commit</FONT>
+<FONT COLOR="#000080">message=</FONT><FONT COLOR="#008000">"commit
+deleted files"</FONT> <FONT COLOR="#000080">dir=</FONT><FONT COLOR="#008000">"workingcopy/deleteTest"</FONT><FONT COLOR="#000080">/></FONT></FONT></FONT><br>
+<FONT FACE="Courier New"><FONT SIZE=2><FONT COLOR="#000080"></svn></FONT></FONT></FONT>
+</div>
+deletes some files from repository (and commit changes)
+</p>
+
+<p>
+<div class="sample" style="width: 842px; height: 117px">
+<FONT FACE="Courier New"><FONT SIZE=2><FONT COLOR="#000080"><svn javahl="false"></FONT></FONT></FONT><br>
+<FONT COLOR="#000080"> <FONT FACE="Courier New"><FONT SIZE=2><add</FONT>
+<FONT COLOR="#000080">dir=</FONT><FONT COLOR="#008000">"workingcopy/propTest"</FONT><FONT COLOR="#000080">/></FONT></FONT></FONT><br>
+<FONT COLOR="#000080"> <FONT FACE="Courier New"><FONT SIZE=2><commit</FONT>
+<FONT COLOR="#000080">message=</FONT><FONT COLOR="#008000">"propTest
+added"</FONT> <FONT COLOR="#000080">dir=</FONT><FONT COLOR="#008000">"workingcopy/propTest"</FONT><FONT COLOR="#000080">/></FONT></FONT></FONT><br>
+ <FONT FACE="Courier New"><FONT SIZE=2><FONT COLOR="#000080"><propset</FONT>
+<FONT COLOR="#000080">path=</FONT><FONT COLOR="#008000">"workingcopy/propTest/file.png"</FONT>
+<FONT COLOR="#000080">name=</FONT><FONT COLOR="#008000">"svn:mime-type"</FONT>
+<FONT COLOR="#000080">value=</FONT><FONT COLOR="#008000">"image/png"</FONT><FONT COLOR="#000080">/></FONT></FONT></FONT><br>
+ <FONT FACE="Courier New"><FONT SIZE=2><FONT COLOR="#000080"><propset</FONT>
+<FONT COLOR="#000080">path=</FONT><FONT COLOR="#008000">"workingcopy/propTest/file.png"</FONT>
+<FONT COLOR="#000080">name=</FONT><FONT COLOR="#008000">"myPicture"</FONT>
+<FONT COLOR="#000080">file=</FONT><FONT COLOR="#008000">"workingcopy/propTest/icon.gif"</FONT><FONT COLOR="#000080">/></FONT></FONT></FONT><br>
+<FONT FACE="Courier New"><FONT SIZE=2><FONT COLOR="#000080"></svn></FONT></FONT></FONT>
+</div>add my_repos/propTest to repository and set two properties on file.png <br>
+subversion command line interface is used (javahl="false").
+</p>
+
+<HR>
+
+</BODY>
+</HTML>
\ No newline at end of file diff --git a/org.eclipse.osee.framework.antsupport/lib/svnant-1.0.0/lib/JAVAHL-LICENSE b/org.eclipse.osee.framework.antsupport/lib/svnant-1.0.0/lib/JAVAHL-LICENSE new file mode 100644 index 00000000000..9c3e114d766 --- /dev/null +++ b/org.eclipse.osee.framework.antsupport/lib/svnant-1.0.0/lib/JAVAHL-LICENSE @@ -0,0 +1,55 @@ +This license applies to all portions of Subversion which are not +externally-maintained libraries (e.g. apr/, apr-util/, and neon/). +Such libraries have their own licenses; we recommend you read them, as +their terms may differ from the terms below. + +This is version 1 of this license. It is also available online at +http://subversion.tigris.org/license-1.html. If newer versions of +this license are posted there (the same URL, but with the version +number incremented: .../license-2.html, .../license-3.html, and so +on), you may use a newer version instead, at your option. + +==================================================================== +Copyright (c) 2000-2005 CollabNet. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + +1. Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright +notice, this list of conditions and the following disclaimer in the +documentation and/or other materials provided with the distribution. + +3. The end-user documentation included with the redistribution, if +any, must include the following acknowledgment: "This product includes +software developed by CollabNet (http://www.Collab.Net/)." +Alternately, this acknowledgment may appear in the software itself, if +and wherever such third-party acknowledgments normally appear. + +4. The hosted project names must not be used to endorse or promote +products derived from this software without prior written +permission. For written permission, please contact info@collab.net. + +5. Products derived from this software may not use the "Tigris" name +nor may "Tigris" appear in their names without prior written +permission of CollabNet. + +THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED +WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. +IN NO EVENT SHALL COLLABNET OR ITS CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE +GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR +OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF +ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +==================================================================== + +This software consists of voluntary contributions made by many +individuals on behalf of CollabNet. + diff --git a/org.eclipse.osee.framework.antsupport/lib/svnant-1.0.0/lib/SVNCLIENTADAPTER-LICENSE b/org.eclipse.osee.framework.antsupport/lib/svnant-1.0.0/lib/SVNCLIENTADAPTER-LICENSE new file mode 100644 index 00000000000..831ab6eb2cf --- /dev/null +++ b/org.eclipse.osee.framework.antsupport/lib/svnant-1.0.0/lib/SVNCLIENTADAPTER-LICENSE @@ -0,0 +1,185 @@ +SVNClientAdapter Library License
+
+This license applies to all portions of SVNClientAdapter library, which
+are not externally-maintained libraries (e.g. JavaHL or JavaSVN).
+
+Such libraries have their own licenses; we recommend you read them, as
+their terms may differ from the terms below.
+
+=============================================================================
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
\ No newline at end of file diff --git a/org.eclipse.osee.framework.antsupport/lib/svnant-1.0.0/lib/svnClientAdapter.jar b/org.eclipse.osee.framework.antsupport/lib/svnant-1.0.0/lib/svnClientAdapter.jar Binary files differnew file mode 100644 index 00000000000..a6ce6dff1c6 --- /dev/null +++ b/org.eclipse.osee.framework.antsupport/lib/svnant-1.0.0/lib/svnClientAdapter.jar diff --git a/org.eclipse.osee.framework.antsupport/lib/svnant-1.0.0/lib/svnant.jar b/org.eclipse.osee.framework.antsupport/lib/svnant-1.0.0/lib/svnant.jar Binary files differnew file mode 100644 index 00000000000..ef9563a7507 --- /dev/null +++ b/org.eclipse.osee.framework.antsupport/lib/svnant-1.0.0/lib/svnant.jar diff --git a/org.eclipse.osee.framework.antsupport/lib/svnant-1.0.0/lib/svnjavahl.jar b/org.eclipse.osee.framework.antsupport/lib/svnant-1.0.0/lib/svnjavahl.jar Binary files differnew file mode 100644 index 00000000000..dd23d43d743 --- /dev/null +++ b/org.eclipse.osee.framework.antsupport/lib/svnant-1.0.0/lib/svnjavahl.jar diff --git a/org.eclipse.osee.framework.antsupport/lib/svnant-1.0.0/license.txt b/org.eclipse.osee.framework.antsupport/lib/svnant-1.0.0/license.txt new file mode 100644 index 00000000000..998ca05635d --- /dev/null +++ b/org.eclipse.osee.framework.antsupport/lib/svnant-1.0.0/license.txt @@ -0,0 +1,64 @@ +SvnAnt license
+
+This license applies to all portions of svnant library, which
+are not externally-maintained libraries (e.g. JavaHL).
+
+Such libraries have their own licenses; we recommend you read them, as
+their terms may differ from the terms below.
+
+/* ====================================================================
+ * The Apache Software License, Version 1.1
+ *
+ * Copyright (c) 2000 The Apache Software Foundation. All rights
+ * reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in
+ * the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * 3. The end-user documentation included with the redistribution,
+ * if any, must include the following acknowledgment:
+ * "This product includes software developed by the
+ * Apache Software Foundation (http://www.apache.org/)."
+ * Alternately, this acknowledgment may appear in the software itself,
+ * if and wherever such third-party acknowledgments normally appear.
+ *
+ * 4. The names "Apache" and "Apache Software Foundation" must
+ * not be used to endorse or promote products derived from this
+ * software without prior written permission. For written
+ * permission, please contact apache@apache.org.
+ *
+ * 5. Products derived from this software may not be called "Apache",
+ * nor may "Apache" appear in their name, without prior written
+ * permission of the Apache Software Foundation.
+ *
+ * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
+ * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
+ * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
+ * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
+ * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * <http://www.apache.org/>.
+ *
+ */
+
+
diff --git a/org.eclipse.osee.framework.antsupport/lib/svnant-1.0.0/readme.txt b/org.eclipse.osee.framework.antsupport/lib/svnant-1.0.0/readme.txt new file mode 100644 index 00000000000..b2ff93256fb --- /dev/null +++ b/org.eclipse.osee.framework.antsupport/lib/svnant-1.0.0/readme.txt @@ -0,0 +1,38 @@ +SvnAnt
+======
+You can find latest version of svnant on http://subclipse.tigris.org
+
+Installation
+============
+Put the svnant.jar and svnClientAdapter.jar files to classpath of your ant build file.
+(Or directly to your ANT_HOME/lib directory.)
+If you plan to use JavaHL instead of commandline, put the svnjavahl.jar to the classpath too.
+(An of course put the appropriate native OS library on your PATH/LD_PATH too)
+
+In the build file, load the <svn> task.
+E.g. like this:
+ <taskdef resource="svntask.properties" classpathref="project.classpath"/>
+(where svnant.jar lies in the "project.classpath")
+
+To provide access to the Subversion API, svnant uses svnClientAdapter on top of
+either the JavaHL native Subversion Java (JNI) bindings or Subverion's
+command line programs (which must be installed and in your PATH).
+See the subclipse's FAQ <http://subclipse.tigris.org/faq.html#get-javahl">
+for info how to get JavaHL for your operating system.
+
+Documentation
+=============
+Documentation of the <svn> task is in the /doc directory.
+
+Play around
+===========
+To access the sources, just type "ant" in the directory containing the
+build.xml bundled with the distribution. The default target will
+retrieve the sources corresponding to the version you have. If you
+want to get the latest sources, type "ant checkoutLatest".
+
+Once you have the sources, svnant unit tests can be invoked using the
+top level build.xml by typing "ant runTests". These tests provide a
+great set of examples of how to use svnant's Ant tasks and data types.
+
+Please send any usage questions to <mailto:users@subclipse.tigris.org>.
diff --git a/org.eclipse.osee.framework.antsupport/plugin.xml b/org.eclipse.osee.framework.antsupport/plugin.xml new file mode 100644 index 00000000000..4c12b032ecf --- /dev/null +++ b/org.eclipse.osee.framework.antsupport/plugin.xml @@ -0,0 +1,28 @@ +<?xml version="1.0" encoding="UTF-8"?> +<?eclipse version="3.2"?> +<plugin> + <extension + point="org.eclipse.ant.core.antTasks"> + <antTask + class="org.tigris.subversion.svnant.SvnTask" + eclipseRuntime="false" + headless="true" + library="lib/svnant-1.0.0/lib/svnant.jar" + name="svn"> + </antTask> + </extension> + <extension + point="org.eclipse.ant.core.extraClasspathEntries"> + <extraClasspathEntry + eclipseRuntime="true" + headless="true" + library="lib/svnant-1.0.0/lib/svnClientAdapter.jar"> + </extraClasspathEntry> + <extraClasspathEntry + eclipseRuntime="true" + headless="true" + library="lib/svnant-1.0.0/lib/svnjavahl.jar"> + </extraClasspathEntry> + </extension> + +</plugin> diff --git a/org.eclipse.osee.framework.antsupport/src/org/eclipse/osee/framework/antsupport/Activator.java b/org.eclipse.osee.framework.antsupport/src/org/eclipse/osee/framework/antsupport/Activator.java new file mode 100644 index 00000000000..99b24ddaaa5 --- /dev/null +++ b/org.eclipse.osee.framework.antsupport/src/org/eclipse/osee/framework/antsupport/Activator.java @@ -0,0 +1,60 @@ +/******************************************************************************* + * Copyright (c) 2004, 2007 Boeing. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Boeing - initial API and implementation + *******************************************************************************/ +package org.eclipse.osee.framework.antsupport; + +import org.eclipse.core.runtime.Plugin; +import org.osgi.framework.BundleContext; + +/** + * The activator class controls the plug-in life cycle + */ +public class Activator extends Plugin { + + // The plug-in ID + public static final String PLUGIN_ID = "org.eclipse.osee.framework.antsupport"; + + // The shared instance + private static Activator plugin; + + /** + * The constructor + */ + public Activator() { + } + + /* + * (non-Javadoc) + * @see org.eclipse.core.runtime.Plugins#start(org.osgi.framework.BundleContext) + */ + public void start(BundleContext context) throws Exception { + super.start(context); + plugin = this; + } + + /* + * (non-Javadoc) + * @see org.eclipse.core.runtime.Plugin#stop(org.osgi.framework.BundleContext) + */ + public void stop(BundleContext context) throws Exception { + plugin = null; + super.stop(context); + } + + /** + * Returns the shared instance + * + * @return the shared instance + */ + public static Activator getDefault() { + return plugin; + } + +} diff --git a/org.eclipse.osee.framework.database/.classpath b/org.eclipse.osee.framework.database/.classpath new file mode 100644 index 00000000000..02159672985 --- /dev/null +++ b/org.eclipse.osee.framework.database/.classpath @@ -0,0 +1,7 @@ +<?xml version="1.0" encoding="UTF-8"?>
+<classpath>
+ <classpathentry kind="src" path="src"/>
+ <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
+ <classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/>
+ <classpathentry kind="output" path="bin"/>
+</classpath>
diff --git a/org.eclipse.osee.framework.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..4eed4b89ae4 --- /dev/null +++ b/org.eclipse.osee.framework.database/META-INF/MANIFEST.MF @@ -0,0 +1,23 @@ +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.1.0.qualifier +Bundle-ClassPath: database.jar +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.initialize, + org.eclipse.osee.framework.database.initialize.tasks, + org.eclipse.osee.framework.database.initialize.tasks.relational, + org.eclipse.osee.framework.database.utility +Require-Bundle: org.eclipse.ui, + org.eclipse.ui.ide, + org.eclipse.core.runtime, + org.eclipse.osee.framework.jdk.core, + org.eclipse.core.resources, + org.eclipse.osee.framework.ui.plugin, + org.eclipse.osee.framework.plugin.core +Eclipse-LazyStart: true +Bundle-Vendor: Eclipse.org diff --git a/org.eclipse.osee.framework.database/build.properties b/org.eclipse.osee.framework.database/build.properties new file mode 100644 index 00000000000..d1306cd5bf5 --- /dev/null +++ b/org.eclipse.osee.framework.database/build.properties @@ -0,0 +1,9 @@ +source.database.jar = src/
+output.database.jar = bin/
+bin.includes = plugin.xml,\
+ database.jar,\
+ META-INF/,\
+ support/,\
+ src/
+bin.excludes = support/RelationSide.java
+
diff --git a/org.eclipse.osee.framework.database/plugin.xml b/org.eclipse.osee.framework.database/plugin.xml new file mode 100644 index 00000000000..b5ef45dcda8 --- /dev/null +++ b/org.eclipse.osee.framework.database/plugin.xml @@ -0,0 +1,54 @@ +<?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="ProductionDatabase" name="Production Database" schema="schema/ProductionDatabase.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
+ point="org.eclipse.ui.popupMenus">
+ <objectContribution
+ adaptable="true"
+ id="osee.database.projectContribution"
+ objectClass="org.eclipse.core.resources.IResource">
+ <action
+ class="org.eclipse.osee.framework.database.GenerateTypeEnumAction"
+ id="osee.define.popup.open.artifact"
+ label="Generate Type Classes"
+ menubarPath="osee.define.menu.main/main"/>
+ </objectContribution>
+
+</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>
+
+ +</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..cc9ef286727 --- /dev/null +++ b/org.eclipse.osee.framework.database/schema/IDbInitializationTask.exsd @@ -0,0 +1,107 @@ +<?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="IDbInitializationTask" name="DbInitializationTask"/>
+ </appInfo>
+ <documentation>
+ [Enter description of this extension point.]
+ </documentation>
+ </annotation>
+
+ <element name="extension">
+ <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="IDbInitializationTask"/>
+ </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/ProductionDatabase.exsd b/org.eclipse.osee.framework.database/schema/ProductionDatabase.exsd new file mode 100644 index 00000000000..3374d522439 --- /dev/null +++ b/org.eclipse.osee.framework.database/schema/ProductionDatabase.exsd @@ -0,0 +1,102 @@ +<?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="ProductionDatabase" name="Production Database"/>
+ </appInfo>
+ <documentation>
+ [Enter description of this extension point.]
+ </documentation>
+ </annotation>
+
+ <element name="extension">
+ <complexType>
+ <sequence>
+ <element ref="ProductionDatabase"/>
+ </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="ProductionDatabase">
+ <complexType>
+ <attribute name="databaseInstance" type="string" use="required">
+ <annotation>
+ <documentation>
+
+ </documentation>
+ </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/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..5d911d2e09c --- /dev/null +++ b/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/ConfigDatabase.java @@ -0,0 +1,45 @@ +/******************************************************************************* + * Copyright (c) 2004, 2007 Boeing. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Boeing - initial API and implementation + *******************************************************************************/ +package org.eclipse.osee.framework.database; + +import org.eclipse.equinox.app.IApplication; +import org.eclipse.equinox.app.IApplicationContext; +import org.eclipse.osee.framework.database.initialize.LaunchOseeDbConfigClient; + +public class ConfigDatabase implements IApplication { + + /* + * (non-Javadoc) + * + * @see org.eclipse.equinox.app.IApplication#start(org.eclipse.equinox.app.IApplicationContext) + */ + public Object start(IApplicationContext context) throws Exception { + LaunchOseeDbConfigClient.main(null); + // keepAlive = new Object(); + // synchronized (keepAlive) { + // try { + // keepAlive.wait(); + // } catch (InterruptedException e) { + // e.printStackTrace(); + // } + // } + 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..65acb22d772 --- /dev/null +++ b/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/DatabaseActivator.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; + +import java.util.List; +import org.eclipse.core.runtime.IConfigurationElement; +import org.eclipse.osee.framework.plugin.core.config.ConfigUtil; +import org.eclipse.osee.framework.plugin.core.util.ExtensionPoints; +import org.eclipse.osee.framework.ui.plugin.OseeUiActivator; + +/** + * The main plug-in class to be used in the desktop. + * + * @author Ryan D. Brooks + */ +public class DatabaseActivator extends OseeUiActivator { + + // The shared instance. + private static DatabaseActivator plugin; + + /** + * The constructor. + */ + public DatabaseActivator() { + plugin = this; + } + + /** + * Returns the shared instance. + */ + public static DatabaseActivator getInstance() { + return plugin; + } + + public boolean isProductionDb() { + List<IConfigurationElement> elements = ExtensionPoints.getExtensionElements(DatabaseActivator.getInstance(), + "ProductionDatabase", "ProductionDatabase"); + + String dbServiceId = ConfigUtil.getConfigFactory().getOseeConfig().getServiceID(); + for (IConfigurationElement element : elements) { + if (dbServiceId.equals(element.getAttribute("databaseInstance"))) { + return true; + } + } + return false; + } +}
\ No newline at end of file diff --git a/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/GenerateTypeEnumAction.java b/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/GenerateTypeEnumAction.java new file mode 100644 index 00000000000..2f9286b089e --- /dev/null +++ b/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/GenerateTypeEnumAction.java @@ -0,0 +1,158 @@ +/******************************************************************************* + * 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.util.Iterator; +import org.eclipse.core.resources.IContainer; +import org.eclipse.core.resources.IResource; +import org.eclipse.jface.action.IAction; +import org.eclipse.jface.dialogs.IDialogConstants; +import org.eclipse.jface.viewers.CheckStateChangedEvent; +import org.eclipse.jface.viewers.CheckboxTreeViewer; +import org.eclipse.jface.viewers.ICheckStateListener; +import org.eclipse.jface.viewers.ILabelProvider; +import org.eclipse.jface.viewers.ISelection; +import org.eclipse.jface.viewers.ITreeContentProvider; +import org.eclipse.jface.viewers.StructuredSelection; +import org.eclipse.jface.viewers.Viewer; +import org.eclipse.jface.viewers.ViewerFilter; +import org.eclipse.jface.window.Window; +import org.eclipse.osee.framework.ui.plugin.util.AWorkspace; +import org.eclipse.swt.SWT; +import org.eclipse.swt.layout.GridData; +import org.eclipse.swt.layout.GridLayout; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Control; +import org.eclipse.swt.widgets.Label; +import org.eclipse.swt.widgets.Shell; +import org.eclipse.swt.widgets.Tree; +import org.eclipse.ui.IActionDelegate; +import org.eclipse.ui.PlatformUI; +import org.eclipse.ui.dialogs.CheckedTreeSelectionDialog; +import org.eclipse.ui.model.WorkbenchContentProvider; +import org.eclipse.ui.model.WorkbenchLabelProvider; + +public class GenerateTypeEnumAction implements IActionDelegate { + + public GenerateTypeEnumAction() { + super(); + } + + @SuppressWarnings("unchecked") + public void run(IAction action) { + try { + StructuredSelection sel = AWorkspace.getSelection(); + Iterator i = sel.iterator(); + File selection = null; + while (i.hasNext()) { + Object obj = i.next(); + if (obj instanceof IResource) { + IResource resource = (IResource) obj; + if (resource != null) { + selection = resource.getLocation().toFile(); + if (selection != null) { + + Object destinationObj = getFolderToStoreAutoGenFilesIn(resource); + if (destinationObj instanceof IContainer) { + IContainer destinationFolder = (IContainer) destinationObj; + File storeAt = destinationFolder.getLocation().toFile(); + SkynetTypesEnumGenerator gen = new SkynetTypesEnumGenerator(); + gen.extractTypesFromSheet(selection, storeAt); + gen.finish(); + + destinationFolder.refreshLocal(IResource.DEPTH_INFINITE, null); + } + } + } + } + } + } catch (Exception e) { + e.printStackTrace(); + } + } + + private Object getFolderToStoreAutoGenFilesIn(IResource resource) { + CheckedTreeSelectionDialog resourceDialog = new ResourceSelectionTree( + PlatformUI.getWorkbench().getDisplay().getActiveShell(), new WorkbenchLabelProvider(), + new WorkbenchContentProvider()); + + resourceDialog.setInput(resource.getWorkspace().getRoot()); + resourceDialog.addFilter(new ViewerFilter() { + + @Override + public boolean select(Viewer viewer, Object parentElement, Object element) { + IResource resource = null; + if (element instanceof IContainer) { + IContainer container = (IContainer) element; + String name = container.getName(); + if (name.startsWith(".") == false && name.equals("bin") == false) { + resource = container; + } + } + if (resource != null) { + return true; + } + return false; + } + }); + resourceDialog.setMessage("Select where Auto-Generated classes should be stored."); + resourceDialog.setTitle("Select Destination"); + resourceDialog.setEmptyListMessage("No Projects Available"); + resourceDialog.setInitialSelection(resource.getParent()); + resourceDialog.setExpandedElements(new Object[] {resource.getParent()}); + int result = resourceDialog.open(); + return result != Window.CANCEL ? resourceDialog.getFirstResult() : null; + } + + public void selectionChanged(IAction action, ISelection selection) { + } + + private final class ResourceSelectionTree extends CheckedTreeSelectionDialog { + + public ResourceSelectionTree(Shell parent, ILabelProvider labelProvider, ITreeContentProvider contentProvider) { + super(parent, labelProvider, contentProvider); + } + + protected Control createDialogArea(Composite parent) { + Composite composite = new Composite(parent, SWT.NONE); + GridLayout layout = new GridLayout(); + layout.marginHeight = convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_MARGIN); + layout.marginWidth = convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_MARGIN); + layout.verticalSpacing = convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_SPACING); + layout.horizontalSpacing = convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_SPACING); + composite.setLayout(layout); + composite.setLayoutData(new GridData(GridData.FILL_BOTH)); + applyDialogFont(composite); + + Label messageLabel = createMessageArea(composite); + CheckboxTreeViewer treeViewer = createTreeViewer(composite); + GridData data = new GridData(GridData.FILL_BOTH); + data.widthHint = convertWidthInCharsToPixels(80); + data.heightHint = convertHeightInCharsToPixels(16); + Tree treeWidget = treeViewer.getTree(); + treeViewer.addCheckStateListener(new ICheckStateListener() { + + public void checkStateChanged(CheckStateChangedEvent event) { + boolean wasChecked = event.getChecked(); + getTreeViewer().setAllChecked(false); + event.getCheckable().setChecked(event.getElement(), wasChecked); + } + + }); + treeWidget.setLayoutData(data); + treeWidget.setFont(parent.getFont()); + messageLabel.setEnabled(true); + treeWidget.setEnabled(true); + return composite; + } + }; +} 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..98387a95311 --- /dev/null +++ b/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/SkynetTypesEnumGenerator.java @@ -0,0 +1,296 @@ +/******************************************************************************* + * 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.sql.SQLException; +import java.util.Arrays; +import java.util.Iterator; +import java.util.TreeSet; +import java.util.logging.Level; +import java.util.logging.Logger; +import java.util.regex.Pattern; +import org.eclipse.core.runtime.CoreException; +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.plugin.core.config.ConfigUtil; +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 Logger logger = ConfigUtil.getConfigFactory().getLogger(SkynetTypesEnumGenerator.class); + + private static final Pattern nonJavaCharP = Pattern.compile("[^a-zA-Z_0-9]"); + + private static final String relationImports = "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.IRelationLink;\n" + "import org.eclipse.osee.framework.skynet.core.relation.IRelationLinkDescriptor;\n" + "import org.eclipse.osee.framework.skynet.core.relation.RelationPersistenceManager;\n\n"; + + private static final String relationEnumCode = " private boolean sideA;\n" + "\n" + " private String typeName;\n" + " private static final RelationPersistenceManager relationManager = RelationPersistenceManager.getInstance();\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) {\n" + " IRelationLinkDescriptor desc = relationManager.getIRelationLinkDescriptor(relationType, branch);\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) {\n" + " if (isSideA())\n" + " return getDescriptor(branch).getSideAName();\n" + " else\n" + " return getDescriptor(branch).getSideBName();\n" + " }\n" + "\n" + " /**\n" + " * @return Returns the typeName.\n" + " */\n" + " public String getTypeName() {\n" + " return typeName;\n" + " }\n" + "\n" + " public IRelationLinkDescriptor getDescriptor(Branch branch) {\n" + " return relationManager.getIRelationLinkDescriptor(typeName, branch);\n" + " }\n" + " \n" + " public boolean isThisType(IRelationLink link) {\n" + " return link.getLinkDescriptor().getName().equals(typeName);\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 + * @throws SAXException + * @throws IOException + * @throws SQLException + */ + 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 SQLException, CoreException, IOException { + try { + 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(); + + } catch (Exception ex) { + logger.log(Level.SEVERE, ex.toString(), ex); + } + } + + 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 (SQLException ex) { + logger.log(Level.SEVERE, ex.toString(), ex); + } catch (ClassNotFoundException ex) { + logger.log(Level.SEVERE, ex.toString(), ex); + } catch (Exception ex) { + logger.log(Level.SEVERE, ex.toString(), ex); + } + } + + /** + * @param row + * @throws ClassNotFoundException + * @throws SQLException + */ + private void addAttributeType(String[] row) throws ClassNotFoundException, SQLException { + // String attrBaseType = row[0]; + String attributeName = row[1]; + // String defaultValue = row[2]; + // String validityXml = row[3]; + // int minOccurrence = getQuantity(row[4]); + // int maxOccurrence = getQuantity(row[5]); + // String tipText = row[6]; + + 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..74299eff634 --- /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.ui.plugin.util.db.data.SchemaData; +import org.eclipse.osee.framework.ui.plugin.util.db.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..cd033d0675d --- /dev/null +++ b/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/config/TableConfigUtility.java @@ -0,0 +1,231 @@ +/******************************************************************************* + * 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 java.util.logging.Logger; +import javax.xml.parsers.ParserConfigurationException; +import org.eclipse.osee.framework.jdk.core.util.xml.Jaxp; +import org.eclipse.osee.framework.plugin.core.config.ConfigUtil; +import org.eclipse.osee.framework.ui.plugin.util.db.data.AppliesToClause; +import org.eclipse.osee.framework.ui.plugin.util.db.data.ColumnMetadata; +import org.eclipse.osee.framework.ui.plugin.util.db.data.ConstraintElement; +import org.eclipse.osee.framework.ui.plugin.util.db.data.ConstraintFactory; +import org.eclipse.osee.framework.ui.plugin.util.db.data.ConstraintTypes; +import org.eclipse.osee.framework.ui.plugin.util.db.data.ForeignKey; +import org.eclipse.osee.framework.ui.plugin.util.db.data.IndexElement; +import org.eclipse.osee.framework.ui.plugin.util.db.data.ReferenceClause; +import org.eclipse.osee.framework.ui.plugin.util.db.data.SchemaData; +import org.eclipse.osee.framework.ui.plugin.util.db.data.TableElement; +import org.eclipse.osee.framework.ui.plugin.util.db.data.AppliesToClause.AppliesToEntries; +import org.eclipse.osee.framework.ui.plugin.util.db.data.AppliesToClause.OrderType; +import org.eclipse.osee.framework.ui.plugin.util.db.data.ConstraintElement.ConstraintFields; +import org.eclipse.osee.framework.ui.plugin.util.db.data.IndexElement.IndexFields; +import org.eclipse.osee.framework.ui.plugin.util.db.data.ReferenceClause.OnDeleteEnum; +import org.eclipse.osee.framework.ui.plugin.util.db.data.ReferenceClause.OnUpdateEnum; +import org.eclipse.osee.framework.ui.plugin.util.db.data.ReferenceClause.ReferencesFields; +import org.eclipse.osee.framework.ui.plugin.util.db.data.TableElement.ColumnFields; +import org.eclipse.osee.framework.ui.plugin.util.db.data.TableElement.TableDescriptionFields; +import org.eclipse.osee.framework.ui.plugin.util.db.data.TableElement.TableSections; +import org.eclipse.osee.framework.ui.plugin.util.db.data.TableElement.TableTags; +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 Logger logger = ConfigUtil.getConfigFactory().getLogger(TableConfigUtility.class); + 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) { + logger.log(Level.SEVERE, ex.toString(), ex); + } catch (SAXException ex) { + logger.log(Level.SEVERE, ex.toString(), ex); + } catch (IOException ex) { + logger.log(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()); + if (id.length() > 0) { + IndexElement indexData = new IndexElement(id); + if (Boolean.parseBoolean(ignore)) { + indexData.setMySqlIgnore(true); + } + if (indexType != null) { + indexData.setIndexType(indexType.getValue()); + } + 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/DatabaseNotSupportedException.java b/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/core/DatabaseNotSupportedException.java new file mode 100644 index 00000000000..71a7a0a5c88 --- /dev/null +++ b/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/core/DatabaseNotSupportedException.java @@ -0,0 +1,27 @@ +/******************************************************************************* + * Copyright (c) 2004, 2007 Boeing. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Boeing - initial API and implementation + *******************************************************************************/ +package org.eclipse.osee.framework.database.core; + +/** + * @author Roberto E. Escobar + */ +public class DatabaseNotSupportedException extends Exception { + + private static final long serialVersionUID = 155062269031207620L; + + public DatabaseNotSupportedException() { + super("Database is not supported."); + } + + public DatabaseNotSupportedException(String message) { + super("Database is not supported. \n" + message); + } +} diff --git a/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/core/DbClientThread.java b/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/core/DbClientThread.java new file mode 100644 index 00000000000..1f0cc0cb57f --- /dev/null +++ b/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/core/DbClientThread.java @@ -0,0 +1,64 @@ +/******************************************************************************* + * 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; + +import java.sql.Connection; +import java.sql.SQLException; +import java.util.logging.Level; +import java.util.logging.Logger; +import org.eclipse.osee.framework.plugin.core.config.data.DbInformation; +import org.eclipse.osee.framework.ui.plugin.util.db.DBConnection; + +/** + * @author Roberto E. Escobar + */ +public abstract class DbClientThread extends Thread { + protected Connection connection; + protected DbInformation databaseService; + protected Logger logger; + + public DbClientThread(Logger logger, String threadName, DbInformation databaseService) { + this.setName(threadName); + this.connection = null; + this.databaseService = databaseService; + this.logger = logger; + } + + public void run() { + logger.log(Level.INFO, "Starting " + getName() + "..."); + try { + connection = DBConnection.getNewConnection(databaseService, false); + connection.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED); + + processTask(); + + } catch (SQLException ex) { + logger.log(Level.SEVERE, ex.getMessage(), ex); + } catch (DatabaseNotSupportedException ex) { + logger.log(Level.SEVERE, ex.getMessage(), ex); + } catch (Exception ex) { + logger.log(Level.SEVERE, ex.getMessage(), ex); + } catch (ExceptionInInitializerError ex) { + logger.log(Level.SEVERE, ex.getMessage(), ex); + } finally { + if (connection != null) { + try { + logger.log(Level.INFO, "Closing " + getName() + " Connection..."); + connection.close(); + } catch (SQLException ex) { + logger.log(Level.SEVERE, ex.getMessage(), ex); + } + } + } + } + + public abstract void processTask() throws SQLException, DatabaseNotSupportedException, Exception; +} 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/initialize/DbComparator.java b/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/initialize/DbComparator.java new file mode 100644 index 00000000000..1806eb879b4 --- /dev/null +++ b/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/initialize/DbComparator.java @@ -0,0 +1,73 @@ +/******************************************************************************* + * Copyright (c) 2004, 2007 Boeing. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Boeing - initial API and implementation + *******************************************************************************/ +package org.eclipse.osee.framework.database.initialize; + +import java.util.Map; +import java.util.Set; +import org.eclipse.osee.framework.ui.plugin.util.db.data.SchemaData; + +/** + * @author Roberto E. Escobar + */ +public class DbComparator { + + private Map<String, SchemaData> db1; + private Map<String, SchemaData> db2; + + public DbComparator(Map<String, SchemaData> db1, Map<String, SchemaData> db2) { + this.db1 = db1; + this.db2 = db2; + } + + public boolean collectDifferences() { + boolean matched = false; + if (db1.equals(db2)) { + matched = true; + } else { + matched = false; + Set<String> db1Schemas = db1.keySet(); + Set<String> db2Schemas = db2.keySet(); + if (!db1Schemas.equals(db2Schemas)) { + // TODO - Report here - Schemas Different looking at different items - Done Comparing. + } else { + // Schemas Equal compare SchemaData + // List<SchemaData> db1DiffSchemaData = new ArrayList<SchemaData>(); + // List<SchemaData> db2DiffSchemaData = new ArrayList<SchemaData>(); + // + // for (String key : db1Schemas) { + // SchemaData db1SchemaData = db1.get(key); + // SchemaData db2SchemaData = db2.get(key); + // if (!db1SchemaData.equals(db2SchemaData)) { + // //Build TableMaps so we compare tables correctly + // Map<String, TableElement> db1TableMap = db1SchemaData.getTableMap(); + // Map<String, TableElement> db2TableMap = db2SchemaData.getTableMap(); + // + // Set<String> thisKey1 = db1TableMap.keySet(); + // Set<String> thatKey2 = db2TableMap.keySet(); + + matched = true; + + // if(thisKey1.equals(thatKey2)){ + // for(String key : thisKey1){ + // toReturn &= EqualsUtility.areEqual(thisTableMap.get(key), thatTableMap.get(key)); + // } + // } else { + // // Keys didn't equal -- Find key that didn't equal?? + // // compare other tables so you can see if anything else didn't match + // toReturn = false; + // } + } + } + // } + // } + return matched; + } +} 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..dad7a6cf57a --- /dev/null +++ b/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/initialize/DbFactory.java @@ -0,0 +1,67 @@ +/******************************************************************************* + * Copyright (c) 2004, 2007 Boeing. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Boeing - initial API and implementation + *******************************************************************************/ +package org.eclipse.osee.framework.database.initialize; + +import java.sql.Connection; +import java.sql.SQLException; +import java.util.List; +import java.util.logging.Logger; +import org.eclipse.osee.framework.plugin.core.config.ConfigUtil; +import org.eclipse.osee.framework.plugin.core.config.SupportedDatabase; +import org.eclipse.osee.framework.ui.plugin.sql.SqlFactory; +import org.eclipse.osee.framework.ui.plugin.sql.manager.SqlManager; +import org.eclipse.osee.framework.ui.plugin.util.db.data.SchemaData; +import org.eclipse.osee.framework.ui.plugin.util.db.data.TableElement; + +/** + * @author Roberto E. Escobar + */ +public class DbFactory { + + private SchemaData schemaData; + protected SqlManager sqlManager; + protected Connection connection; + protected Logger logger; + + public DbFactory(Connection connection, SupportedDatabase databaseType, SchemaData schemaData) { + this.schemaData = schemaData; + this.connection = connection; + this.sqlManager = SqlFactory.getSqlManager(databaseType); + this.logger = ConfigUtil.getConfigFactory().getLogger(DbFactory.class); + } + + public void createTables() throws SQLException, Exception { + List<TableElement> tableDefs = schemaData.getTablesOrderedByDependency(); + for (TableElement tableDef : tableDefs) { + sqlManager.createTable(connection, tableDef); + } + } + + public void dropTables() throws SQLException, Exception { + 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 SQLException, Exception { + for (TableElement tableDef : schemaData.getTableMap().values()) { + sqlManager.createIndex(connection, tableDef); + } + } + + public void dropIndeces() throws SQLException, Exception { + 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/DbTaskRunner.java b/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/initialize/DbTaskRunner.java new file mode 100644 index 00000000000..92b6c68a51e --- /dev/null +++ b/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/initialize/DbTaskRunner.java @@ -0,0 +1,58 @@ +/******************************************************************************* + * 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.sql.SQLException; +import java.util.Queue; +import org.eclipse.osee.framework.database.core.DatabaseNotSupportedException; +import org.eclipse.osee.framework.database.initialize.tasks.IDbInitializationTask; +import org.eclipse.osee.framework.plugin.core.config.SupportedDatabase; +import org.eclipse.osee.framework.ui.plugin.sql.SqlFactory; + +/** + * @author Roberto E. Escobar + */ +public class DbTaskRunner { + + private static DbTaskRunner instance = null; + + private DbTaskRunner() { + } + + public static DbTaskRunner getInstance() { + if (instance == null) instance = new DbTaskRunner(); + return instance; + } + + public void processTasks(Connection connection, Queue<IDbInitializationTask> tasks) throws SQLException, DatabaseNotSupportedException, Exception { + SupportedDatabase databaseType = SqlFactory.getDatabaseType(connection); + if (databaseType != null) { + int safetyNet = 0; + while (!tasks.isEmpty()) { + IDbInitializationTask task = tasks.remove(); + if (task.canRun()) { + task.run(connection); + safetyNet = 0; + } else { + tasks.add(task); + safetyNet++; + if (safetyNet == tasks.size() + 1) { + throw new Exception("Unable to run all of the IDbInitializationTask because canRun() failed"); + } + } + } + } else { + throw new DatabaseNotSupportedException("Connected to " + connection.getMetaData().getDatabaseProductName()); + } + System.out.println("finished the initialization"); + } +} diff --git a/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/initialize/LaunchOseeDbConfigClient.java b/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/initialize/LaunchOseeDbConfigClient.java new file mode 100644 index 00000000000..b2e6485981d --- /dev/null +++ b/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/initialize/LaunchOseeDbConfigClient.java @@ -0,0 +1,162 @@ +/******************************************************************************* + * 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 static org.eclipse.osee.framework.jdk.core.util.OseeProperties.OSEE_CONFIG_FACTORY; +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.sql.Connection; +import java.sql.SQLException; +import java.util.List; +import java.util.logging.Level; +import java.util.logging.Logger; +import org.eclipse.core.runtime.IConfigurationElement; +import org.eclipse.core.runtime.IExtension; +import org.eclipse.core.runtime.Platform; +import org.eclipse.osee.framework.database.DatabaseActivator; +import org.eclipse.osee.framework.database.core.DatabaseNotSupportedException; +import org.eclipse.osee.framework.database.core.DbClientThread; +import org.eclipse.osee.framework.database.initialize.tasks.IDbInitializationTask; +import org.eclipse.osee.framework.database.utility.GroupSelection; +import org.eclipse.osee.framework.jdk.core.util.OseeProperties; +import org.eclipse.osee.framework.plugin.core.config.ConfigUtil; +import org.eclipse.osee.framework.plugin.core.config.data.DbInformation; +import org.eclipse.osee.framework.plugin.core.config.data.DbDetailData.ConfigField; +import org.osgi.framework.Bundle; + +/** + * @author Roberto E. Escobar + */ +public class LaunchOseeDbConfigClient extends DbClientThread { + + private static BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in)); + + public LaunchOseeDbConfigClient(DbInformation databaseService) { + super(ConfigUtil.getConfigFactory().getLogger(LaunchOseeDbConfigClient.class), "Config Client Thread", + databaseService); + } + + @Override + public void processTask() throws SQLException, DatabaseNotSupportedException, Exception { + logger.log(Level.INFO, "Begin Database Initialization..."); + run(connection, GroupSelection.getInstance().getDbInitTasks()); + logger.log(Level.INFO, "Database Initialization Complete."); + } + + private static final String dbInitExtensionPointId = "org.eclipse.osee.framework.database.IDbInitializationTask"; + private Logger logger = ConfigUtil.getConfigFactory().getLogger(LaunchOseeDbConfigClient.class); + + /* + * (non-Javadoc) + * + * @see org.eclipse.osee.framework.database.initialize.tasks.IDbInitializationTask#run(java.sql.Connection) + */ + public void run(Connection connection, List<String> extensionIds) throws Exception { + for (String pointId : extensionIds) { + IExtension extension = Platform.getExtensionRegistry().getExtension(pointId); + if (extension == null) { + logger.log(Level.SEVERE, "Unable to locate extension [" + pointId + "]"); + } else { + String extsionPointId = extension.getExtensionPointUniqueIdentifier(); + if (dbInitExtensionPointId.equals(extsionPointId)) { + runDbInitTasks(extension, connection); + } else { + logger.log(Level.SEVERE, + "Unknown extension id [" + extsionPointId + "] from extension [" + pointId + "]"); + } + } + } + } + + /** + * @param skynetDbTypesExtensions + * @param extensionIds + */ + private void runDbInitTasks(IExtension extension, Connection connection) { + IConfigurationElement[] elements = extension.getConfigurationElements(); + String classname = null; + String bundleName = null; + for (IConfigurationElement el : elements) { + if (el.getName().equals("DatabaseTask")) { + classname = el.getAttribute("classname"); + bundleName = el.getContributor().getName(); + } + } + if (classname != null && bundleName != null) { + Bundle bundle = Platform.getBundle(bundleName); + try { + logger.log(Level.INFO, "Starting [" + extension.getUniqueIdentifier() + "]"); + Class<?> taskClass = bundle.loadClass(classname); + Object obj = taskClass.newInstance(); + IDbInitializationTask task = (IDbInitializationTask) obj; + task.run(connection); + // logger.log(Level.INFO, "Completed [" + extension.getUniqueIdentifier() + "]"); + } catch (Exception ex) { + logger.log(Level.SEVERE, ex.getLocalizedMessage(), ex); + } catch (NoClassDefFoundError er) { + logger.log(Level.SEVERE, er.getLocalizedMessage(), er); + } + } + } + + private static String waitForUserResponse() { + System.out.println("Enter: [Y|N]\n"); + String line = "N"; + + if (!OseeProperties.getInstance().isPromptEnabled()) { + line = "Y"; + } else { + try { + line = stdin.readLine(); + } catch (IOException ex) { + ex.printStackTrace(); + } + } + return line; + } + + public static void main(String[] args) { + System.setProperty(OSEE_CONFIG_FACTORY, + "org.eclipse.osee.framework.plugin.core.config.HeadlessEclipseConfigurationFactory"); + + Logger.getLogger("org.eclipse.osee.framework.jdk.core.util.db.ConnectionHandler").setLevel(Level.SEVERE); + Logger.getLogger("org.eclipse.osee.framework.jdk.core.util.db.DBConnection").setLevel(Level.SEVERE); + Logger.getLogger("org.eclipse.osee.framework.jdk.core.sql.manager.OracleSqlManager").setLevel(Level.SEVERE); + Logger.getLogger("org.eclipse.osee.framework.jdk.core.sql.manager.OracleSqlManager").setLevel(Level.SEVERE); + + DbInformation dbInfo = ConfigUtil.getConfigFactory().getOseeConfig().getDefaultClientData(); + String dbName = dbInfo.getDatabaseDetails().getFieldValue(ConfigField.DatabaseName); + String userName = dbInfo.getDatabaseDetails().getFieldValue(ConfigField.UserName); + + if (DatabaseActivator.getInstance().isProductionDb()) { + System.err.println("You are not allowed to run config client against production servers.\nExiting."); + System.exit(0); + } + + System.out.println("\nAre you sure you want to configure: " + dbName + ":" + userName); + String line = waitForUserResponse(); + if (line.equalsIgnoreCase("Y")) { + System.out.println("Configuring Database..."); + + LaunchOseeDbConfigClient configClient = new LaunchOseeDbConfigClient(dbInfo); + configClient.start(); + try { + configClient.join(); + } catch (InterruptedException ex) { + ex.printStackTrace(); + } + } else { + System.out.println("Database will not be configured. "); + Runtime.getRuntime().exit(0); + } + } +} diff --git a/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/initialize/tasks/DbInitializationTask.java b/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/initialize/tasks/DbInitializationTask.java new file mode 100644 index 00000000000..b152abcd66b --- /dev/null +++ b/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/initialize/tasks/DbInitializationTask.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.initialize.tasks; + +/** + * @author Donald G. Dunne + */ +public abstract class DbInitializationTask implements IDbInitializationTask { + public boolean canRun() { + return true; + } +}
\ No newline at end of file diff --git a/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/initialize/tasks/GatherStatistics.java b/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/initialize/tasks/GatherStatistics.java new file mode 100644 index 00000000000..0a146498164 --- /dev/null +++ b/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/initialize/tasks/GatherStatistics.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.initialize.tasks; + +import java.sql.Connection; +import org.eclipse.osee.framework.plugin.core.config.SupportedDatabase; +import org.eclipse.osee.framework.ui.plugin.util.db.ConnectionHandler; + +public class GatherStatistics extends DbInitializationTask { + private static final String gatherStats = "begin" + " DBMS_STATS.GATHER_SCHEMA_STATS (ownname => '', estimate_percent => 99," + " granularity => 'ALL', degree => NULL , cascade => TRUE);" + "end;"; + + private SupportedDatabase database; + + /** + * @param database + */ + public GatherStatistics(SupportedDatabase database) { + this.database = database; + } + + public void run(Connection connection) throws Exception { + System.out.println("GatherStatistics"); + if (this.database == SupportedDatabase.oracle) { + ConnectionHandler.runPreparedQuery(gatherStats); + } + } +} diff --git a/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/initialize/tasks/IDbInitializationTask.java b/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/initialize/tasks/IDbInitializationTask.java new file mode 100644 index 00000000000..65a61456c12 --- /dev/null +++ b/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/initialize/tasks/IDbInitializationTask.java @@ -0,0 +1,19 @@ +/******************************************************************************* + * 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; + +public interface IDbInitializationTask { + public abstract void run(Connection connection) throws Exception; + + public abstract boolean canRun(); +} 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..87c20f80949 --- /dev/null +++ b/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/initialize/tasks/ImportDataFromDbService.java @@ -0,0 +1,229 @@ +/******************************************************************************* + * 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.sql.SQLException; +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.database.utility.DatabaseDataExtractor; +import org.eclipse.osee.framework.database.utility.DatabaseSchemaExtractor; +import org.eclipse.osee.framework.database.utility.FileUtility; +import org.eclipse.osee.framework.jdk.core.util.OseeProperties; +import org.eclipse.osee.framework.plugin.core.config.ConfigUtil; +import org.eclipse.osee.framework.plugin.core.config.data.DbInformation; +import org.eclipse.osee.framework.ui.plugin.util.db.DBConnection; +import org.eclipse.osee.framework.ui.plugin.util.db.data.SchemaData; +import org.eclipse.osee.framework.ui.plugin.util.db.data.TableElement; + +public class ImportDataFromDbService implements IDbInitializationTask { + private Map<String, SchemaData> userSpecifiedConfig; + private static final File backupDirectory = new File("BackupDirectory"); + + public ImportDataFromDbService(Map<String, SchemaData> userSpecifiedConfig) { + this.userSpecifiedConfig = userSpecifiedConfig; + } + + public void run(Connection connection) throws Exception { + Set<String> importConnections = getImportConnections(); + for (String importFromDbService : importConnections) { + System.out.println("Import Table Data from Db: " + importFromDbService); + + DbInformation databaseService = ConfigUtil.getConfigFactory().getOseeConfig().getDatabaseService( + importFromDbService); + + Connection importConnection = null; + try { + importConnection = DBConnection.getNewConnection(databaseService, false); + } catch (SQLException ex) { + System.out.println("Unable to import table data"); + } + if (importConnection != null) { + System.out.println("Gathering information from ..." + importFromDbService); + + String userName = importConnection.getMetaData().getUserName(); + 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(OseeProperties.OSEE_IMPORT_FROM_DB_SERVICE); + } else { + tablesToImport = dataToImport.get(importFromDbService); + } + + for (String importTable : tablesToImport) { + dbDataExtractor.addTableNameToExtract(importTable); + } + dbDataExtractor.extract(); + dbDataExtractor.waitForWorkerThreads(); + + prepareFilesForImport(); + } + } + 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(OseeProperties.OSEE_IMPORT_FROM_DB_SERVICE); + if (importFromDbService == null || importFromDbService.equals("")) { + 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(OseeProperties.OSEE_IMPORT_FROM_DB_SERVICE)) { + 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 SQLException { + 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 Exception { + 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/InitTablesFromCSV.java b/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/initialize/tasks/InitTablesFromCSV.java new file mode 100644 index 00000000000..080ee7a5563 --- /dev/null +++ b/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/initialize/tasks/InitTablesFromCSV.java @@ -0,0 +1,60 @@ +/******************************************************************************* + * Copyright (c) 2004, 2007 Boeing. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Boeing - initial API and implementation + *******************************************************************************/ +package org.eclipse.osee.framework.database.initialize.tasks; + +import java.io.File; +import java.net.URL; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.SQLException; +import java.sql.Types; +import java.util.List; +import org.eclipse.osee.framework.jdk.core.db.DbConfigFileInformation; + +public class InitTablesFromCSV extends DbInitializationTask { + + private List<URL> csvTableInitData; + private String schemaName; + + public InitTablesFromCSV(String schemaName, List<URL> csvTableInitData) { + super(); + this.csvTableInitData = csvTableInitData; + this.schemaName = schemaName; + } + + public void run(Connection connection) throws Exception { + for (URL file : csvTableInitData) { + insertTableData(connection, schemaName, new File(file.getFile())); + } + } + + private void insertTableData(Connection connection, String schemaName, File file) throws SQLException { + // SYSCS_UTIL.SYSCS_IMPORT_TABLE ( + // IN SCHEMANAME VARCHAR(128), + // IN TABLENAME VARCHAR(128), + // IN FILENAME VARCHAR(32672), + // IN COLUMNDELIMITER CHAR(1), + // IN CHARACTERDELIMITER CHAR(1), + // IN CODESET VARCHAR(128), + // IN REPLACE SMALLINT) + String tableName = file.getName().replace(DbConfigFileInformation.getCSVFileExtension(), "").toUpperCase(); + PreparedStatement statement = connection.prepareStatement("CALL SYSCS_UTIL.SYSCS_IMPORT_TABLE (?,?,?,?,?,?,?)"); + statement.setString(1, schemaName); + statement.setString(2, tableName); + statement.setString(3, file.getAbsolutePath()); + statement.setNull(4, Types.CHAR); + statement.setNull(5, Types.CHAR); + statement.setNull(6, Types.VARCHAR); + statement.setInt(7, 0); + statement.execute(); + statement.close(); + } +} 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..b86e7a5ba9d --- /dev/null +++ b/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/initialize/tasks/PrintTables.java @@ -0,0 +1,79 @@ +/******************************************************************************* + * 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.ui.plugin.util.db.data.SchemaData; + +public class PrintTables extends DbInitializationTask { + + private Map<String, SchemaData> userConfig; + + public PrintTables(Map<String, SchemaData> userConfig) { + super(); + this.userConfig = userConfig; + } + + public void run(Connection connection) throws Exception { + 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; + try { + statement = connection.createStatement(); + ResultSet 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); + } + resultSet.close(); + statement.close(); + } catch (SQLException ex) { + ex.printStackTrace(); + } + } +} 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..6ddded43e19 --- /dev/null +++ b/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/initialize/tasks/relational/BackupTableData.java @@ -0,0 +1,127 @@ +/******************************************************************************* + * 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.sql.Connection; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.TreeSet; +import org.eclipse.osee.framework.database.initialize.tasks.IDbInitializationTask; +import org.eclipse.osee.framework.database.utility.DatabaseDataExtractor; +import org.eclipse.osee.framework.ui.plugin.util.db.data.SchemaData; +import org.eclipse.osee.framework.ui.plugin.util.db.data.TableElement; + +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(Connection connection) throws Exception { + 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..116c52ca4bf --- /dev/null +++ b/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/initialize/tasks/relational/RestoreTableData.java @@ -0,0 +1,132 @@ +/******************************************************************************* + * 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.sql.Connection; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Set; +import org.eclipse.osee.framework.database.initialize.tasks.IDbInitializationTask; +import org.eclipse.osee.framework.database.utility.DatabaseDataImporter; +import org.eclipse.osee.framework.plugin.core.config.SupportedDatabase; +import org.eclipse.osee.framework.ui.plugin.sql.SqlFactory; +import org.eclipse.osee.framework.ui.plugin.sql.manager.SqlManager; +import org.eclipse.osee.framework.ui.plugin.util.db.data.SchemaData; +import org.eclipse.osee.framework.ui.plugin.util.db.data.TableElement; + +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(Connection connection) throws Exception { + 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/utility/DatabaseConfigurationData.java b/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/utility/DatabaseConfigurationData.java new file mode 100644 index 00000000000..273008a80e2 --- /dev/null +++ b/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/utility/DatabaseConfigurationData.java @@ -0,0 +1,129 @@ +/******************************************************************************* + * 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.database.config.SchemaConfigUtility; +import org.eclipse.osee.framework.jdk.core.util.OseeProperties; +import org.eclipse.osee.framework.ui.plugin.util.db.data.ColumnMetadata; +import org.eclipse.osee.framework.ui.plugin.util.db.data.ConstraintElement; +import org.eclipse.osee.framework.ui.plugin.util.db.data.ForeignKey; +import org.eclipse.osee.framework.ui.plugin.util.db.data.IndexElement; +import org.eclipse.osee.framework.ui.plugin.util.db.data.ReferenceClause; +import org.eclipse.osee.framework.ui.plugin.util.db.data.SchemaData; +import org.eclipse.osee.framework.ui.plugin.util.db.data.TableElement; +import org.eclipse.osee.framework.ui.plugin.util.db.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 OseeProperties.getInstance().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..312ef2d2e96 --- /dev/null +++ b/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/utility/DatabaseDataExtractor.java @@ -0,0 +1,298 @@ +/******************************************************************************* + * 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.ResultSet; +import java.sql.ResultSetMetaData; +import java.sql.SQLException; +import java.sql.Statement; +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.logging.Logger; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import org.eclipse.osee.framework.jdk.core.db.DbConfigFileInformation; +import org.eclipse.osee.framework.plugin.core.config.ConfigUtil; +import org.eclipse.osee.framework.plugin.core.config.SupportedDatabase; +import org.eclipse.osee.framework.ui.plugin.sql.SQL3DataType; +import org.eclipse.osee.framework.ui.plugin.sql.SqlFactory; +import org.eclipse.osee.framework.ui.plugin.util.db.DbUtil; +import org.eclipse.osee.framework.ui.plugin.util.db.data.SchemaData; +import org.eclipse.osee.framework.ui.plugin.util.db.data.TableElement; +import org.eclipse.osee.framework.ui.plugin.util.db.data.TableElement.ColumnFields; +import org.eclipse.osee.framework.ui.plugin.util.db.data.TableElement.TableDescriptionFields; +import org.eclipse.osee.framework.ui.plugin.util.db.data.TableElement.TableTags; +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 Logger logger; + 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) { + this.connection = connection; + this.schemas = schemas; + this.directory = directory; + this.logger = ConfigUtil.getConfigFactory().getLogger(DatabaseDataExtractor.class); + this.workerThreads = new ArrayList<Thread>(); + this.extractTables = new TreeSet<String>(); + try { + this.dbType = SqlFactory.getDatabaseType(connection); + } catch (SQLException ex) { + logger.log(Level.SEVERE, "Invalid database type. ", ex); + } + } + + public void addTableNameToExtract(String fullyQualifiedTableName) { + this.extractTables.add(fullyQualifiedTableName); + } + + public void clearFilter() { + this.extractTables.clear(); + } + + public void extract() { + try { + FileUtility.setupDirectoryForWrite(directory); + extractData(); + } catch (IOException ex) { + logger.log(Level.SEVERE, "Directory Invalid. ", ex); + } catch (SQLException ex) { + logger.log(Level.SEVERE, "Extract Exception. ", ex); + } finally { + + } + + } + + private class DataExtractorThread extends Thread { + private TableElement table; + + public DataExtractorThread(TableElement table) { + this.table = table; + setName(table.getName() + " Extractor"); + } + + public void run() { + Statement statement = null; + ResultSet resultSet = null; + try { + resultSet = getTableData(statement, table); + Document document = buildXml(resultSet, table); + resultSet.close(); + if (document != null) { + writeDocumentToFile(document, table.getFullyQualifiedTableName()); + } + } catch (Exception ex) { + logger.log(Level.SEVERE, + "Error Processing Table [ " + table.getSchema() + "." + table.getName() + " ] Data ", ex); + } finally { + DbUtil.close(statement); + } + } + } + + public void waitForWorkerThreads() { + for (Thread worker : workerThreads) { + try { + worker.join(); + } catch (InterruptedException ex) { + logger.log(Level.SEVERE, "Thread [" + worker.getName() + "] was Interrupted. ", ex); + } + } + } + + private void extractData() throws SQLException { + 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 ResultSet getTableData(Statement statement, TableElement table) throws SQLException { + statement = connection.createStatement(); + + ResultSet rset = null; + try { + rset = statement.executeQuery(SQL_WILD_QUERY + table.getFullyQualifiedTableName()); + } catch (SQLException ex) { + rset = statement.executeQuery(SQL_WILD_QUERY + table.getName()); + } + return rset; + } + + private Document buildXml(ResultSet resultSet, TableElement table) throws SQLException { + ResultSetMetaData resultMetaData = resultSet.getMetaData(); + + ArrayList<ColumnInfo> columns = new ArrayList<ColumnInfo>(); + int numberOfColumns = resultMetaData.getColumnCount(); + for (int index = 1; index <= numberOfColumns; index++) { + ColumnInfo columnInfo = new ColumnInfo(); + columnInfo.name = resultMetaData.getColumnName(index); + columnInfo.name = columnInfo.name.toUpperCase(); + + int dataType = resultMetaData.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 (resultSet.next()) { + Element columnElement = xmlDoc.createElement(TableTags.Row.name()); + for (ColumnInfo column : columns) { + String columnValue; + switch (column.type) { + case BIGINT: + BigDecimal bigD = resultSet.getBigDecimal(column.name); + columnValue = (bigD != null ? bigD.toString() : ""); + break; + case DATE: + Date date = resultSet.getDate(column.name); + columnValue = (date != null ? date.toString() : ""); + break; + case TIME: + Time time = resultSet.getTime(column.name); + columnValue = (time != null ? time.toString() : ""); + break; + case TIMESTAMP: + Timestamp timestamp = resultSet.getTimestamp(column.name); + columnValue = (timestamp != null ? timestamp.toString() : ""); + break; + default: + columnValue = resultSet.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) { + logger.log(Level.SEVERE, "File error [" + fileString + "] ", ex); + } catch (IOException ex) { + logger.log(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..13a2504ea03 --- /dev/null +++ b/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/utility/DatabaseDataImporter.java @@ -0,0 +1,257 @@ +/******************************************************************************* + * 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.sql.SQLException; +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.logging.Logger; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; +import org.eclipse.osee.framework.jdk.core.db.DbConfigFileInformation; +import org.eclipse.osee.framework.plugin.core.config.ConfigUtil; +import org.eclipse.osee.framework.ui.plugin.sql.manager.SqlManager; +import org.eclipse.osee.framework.ui.plugin.util.db.data.ColumnDbData; +import org.eclipse.osee.framework.ui.plugin.util.db.data.ColumnMetadata; +import org.eclipse.osee.framework.ui.plugin.util.db.data.TableElement; +import org.eclipse.osee.framework.ui.plugin.util.db.data.TableElement.ColumnFields; +import org.eclipse.osee.framework.ui.plugin.util.db.data.TableElement.TableDescriptionFields; +import org.eclipse.osee.framework.ui.plugin.util.db.data.TableElement.TableTags; +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 Logger logger; + 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.logger = ConfigUtil.getConfigFactory().getLogger(DatabaseDataImporter.class); + 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) { + logger.log(Level.SEVERE, "Unable to Parse File. ", ex); + } catch (Exception ex) { + logger.log(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 SQLException, Exception { + if (tables.size() != 0) { + for (TableData tableData : tables) { + logger.log(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..00c0c92d343 --- /dev/null +++ b/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/utility/DatabaseSchemaExtractor.java @@ -0,0 +1,531 @@ +/******************************************************************************* + * 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.logging.Logger; +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.jdk.core.db.DbConfigFileInformation; +import org.eclipse.osee.framework.jdk.core.util.xml.Jaxp; +import org.eclipse.osee.framework.plugin.core.config.ConfigUtil; +import org.eclipse.osee.framework.plugin.core.config.SupportedDatabase; +import org.eclipse.osee.framework.ui.plugin.sql.SQL3DataType; +import org.eclipse.osee.framework.ui.plugin.sql.SqlFactory; +import org.eclipse.osee.framework.ui.plugin.util.db.data.AppliesToClause; +import org.eclipse.osee.framework.ui.plugin.util.db.data.ColumnMetadata; +import org.eclipse.osee.framework.ui.plugin.util.db.data.ConstraintElement; +import org.eclipse.osee.framework.ui.plugin.util.db.data.ConstraintFactory; +import org.eclipse.osee.framework.ui.plugin.util.db.data.ConstraintTypes; +import org.eclipse.osee.framework.ui.plugin.util.db.data.ForeignKey; +import org.eclipse.osee.framework.ui.plugin.util.db.data.IndexElement; +import org.eclipse.osee.framework.ui.plugin.util.db.data.ReferenceClause; +import org.eclipse.osee.framework.ui.plugin.util.db.data.SchemaData; +import org.eclipse.osee.framework.ui.plugin.util.db.data.TableElement; +import org.eclipse.osee.framework.ui.plugin.util.db.data.AppliesToClause.OrderType; +import org.eclipse.osee.framework.ui.plugin.util.db.data.ReferenceClause.OnDeleteEnum; +import org.eclipse.osee.framework.ui.plugin.util.db.data.ReferenceClause.OnUpdateEnum; +import org.eclipse.osee.framework.ui.plugin.util.db.data.TableElement.ColumnFields; +import org.eclipse.osee.framework.ui.plugin.util.db.data.TableElement.TableDescriptionFields; + +/** + * @author Roberto E. Escobar + */ +public class DatabaseSchemaExtractor { + + private static final Logger logger = ConfigUtil.getConfigFactory().getLogger(DatabaseSchemaExtractor.class); + + private Connection connection; + 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 SQLException { + super(); + this.connection = connection; + this.dbData = this.connection.getMetaData(); + this.dbName = dbData.getDatabaseProductName(); + this.dbVersion = dbData.getDatabaseProductVersion(); + this.dbType = SqlFactory.getDatabaseType(connection); + this.filter = new ArrayList<String>(); + filter.add(DEFAULT_FILTER); + this.tablesToExtract = new TreeSet<String>(); + this.schemas = schemas; + } + + 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 SQLException { + populateDatabaseMap(schemas); + } + + private void populateDatabaseMap(Set<String> schemas) throws SQLException { + 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) { + logger.log(Level.SEVERE, ex.toString(), ex); + } catch (ParserConfigurationException ex) { + logger.log(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 SQLException { + 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; + } + + 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; + } + } + // System.out.println("\nCol: " + id); + // //System.out.println("Sql Data Type: " + columns.getString("SQL_DATA_TYPE")); + // System.out.println("DataType : " + dataTypeName); + // System.out.println("Data Type Number: " + columns.getString("DATA_TYPE")); + // + // try{ + // System.out.println("Column Size?: " + columns.getString("COLUMN_SIZE")); + // } catch(SQLException ex){ + // } + // try{ + // System.out.println("Decimal Digits: " + columns.getString("DECIMAL_DIGITS")); + // } catch(SQLException ex){ + // } + // try{ + // System.out.println("Num Precision Radix: " + columns.getString("NUM_PREC_RADIX")); + // } catch(SQLException ex){ + // } + // try{ + // System.out.println("Char Octet Length: " + columns.getString("CHAR_OCTET_LENGTHE")); + // } catch(SQLException ex){ + // } + // try{ + // System.out.println("Remarks: " + columns.getString("REMARKS")); + // } catch(SQLException ex){ + // } + // try{ + // System.out.println("BUFFER_LENGTH: " + columns.getString("BUFFER_LENGTH")); + // } catch(SQLException ex){ + // } + 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..72dabcad1c1 --- /dev/null +++ b/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/utility/DbInit.java @@ -0,0 +1,181 @@ +/******************************************************************************* + * Copyright (c) 2004, 2007 Boeing. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Boeing - initial API and implementation + *******************************************************************************/ +package org.eclipse.osee.framework.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.initialize.DbFactory; +import org.eclipse.osee.framework.plugin.core.config.SupportedDatabase; +import org.eclipse.osee.framework.ui.plugin.util.db.data.SchemaData; +import org.eclipse.osee.framework.ui.plugin.util.db.data.TableElement; +import org.eclipse.osee.framework.ui.plugin.util.db.schemas.SkynetDatabase; +import org.eclipse.osee.framework.ui.plugin.util.db.schemas.View; + +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 SQLException + */ + public static void addViews(Connection connection, SupportedDatabase databaseType) throws SQLException { + for (View view : SkynetDatabase.getSkynetViews()) { + Statement statement = connection.createStatement(); + 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."); + + statement.executeUpdate(viewCreateCmd + view.toString() + view.getDefinition()); + + statement.executeUpdate("create OR REPLACE public synonym " + view.toString() + " for " + view.toString()); + statement.close(); + } + } + + /** + * @param schemas + * @param schemas + * @param userSpecifiedConfig + * @param connection + * @param databaseType + * @param userSpecifiedConfig2 + * @param databaseType2 + * @throws Exception + * @throws SQLException + */ + public static void addIndeces(Set<String> schemas, Map<String, SchemaData> userSpecifiedConfig, Connection connection, SupportedDatabase databaseType) throws SQLException, Exception { + 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 + * @throws SQLException + */ + public static void addTables(Set<String> schemas, Map<String, SchemaData> userSpecifiedConfig, Connection connection, SupportedDatabase databaseType) throws SQLException, Exception { + 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 + * @throws SQLException + */ + public static void dropTables(Set<String> schemas, Map<String, SchemaData> userSpecifiedConfig, Connection connection, SupportedDatabase databaseType, Map<String, SchemaData> currentDatabaseConfig) throws SQLException, Exception { + 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 + * @throws SQLException + */ + public static void dropIndeces(Set<String> schemas, Map<String, SchemaData> userSpecifiedConfig, Connection connection, SupportedDatabase databaseType, Map<String, SchemaData> currentDatabaseConfig) throws SQLException, Exception { + 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 + * @throws SQLException + */ + public static void dropViews(Connection connection) throws SQLException { + 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(); + } + } + } + } +} 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..7771abdbd51 --- /dev/null +++ b/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/utility/FileUtility.java @@ -0,0 +1,84 @@ +/******************************************************************************* + * Copyright (c) 2004, 2007 Boeing. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Boeing - initial API and implementation + *******************************************************************************/ +package org.eclipse.osee.framework.database.utility; + +import java.io.File; +import java.io.FilenameFilter; +import java.io.IOException; +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) throws IOException { + 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.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.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..f2d09b85341 --- /dev/null +++ b/org.eclipse.osee.framework.database/src/org/eclipse/osee/framework/database/utility/GroupSelection.java @@ -0,0 +1,122 @@ +/******************************************************************************* + * 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.BufferedReader; +import java.io.InputStreamReader; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.logging.Level; +import java.util.logging.Logger; +import org.eclipse.core.runtime.IConfigurationElement; +import org.eclipse.core.runtime.Platform; +import org.eclipse.osee.framework.database.DatabaseActivator; +import org.eclipse.osee.framework.jdk.core.util.OseeProperties; +import org.eclipse.osee.framework.jdk.core.util.Strings; +import org.eclipse.osee.framework.plugin.core.config.ConfigUtil; +import org.eclipse.osee.framework.plugin.core.util.ExtensionPoints; + +/** + * @author Andrew M. Finkbeiner + */ +public class GroupSelection { + private static final Logger logger = ConfigUtil.getConfigFactory().getLogger(GroupSelection.class); + private static final GroupSelection instance = new GroupSelection(); + private Map<String, List<String>> initGroups; + private String choice = null; + + /** + * @param initGroups + */ + private GroupSelection() { + super(); + initGroups = new LinkedHashMap<String, List<String>>(); + 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) { + logger.log(Level.SEVERE, ex.toString(), ex); + } catch (IllegalAccessException ex) { + logger.log(Level.SEVERE, ex.toString(), ex); + } catch (ClassNotFoundException ex) { + logger.log(Level.SEVERE, ex.toString(), 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); + } + + public void addChoice(String listName, List<String> dbInitTasks, boolean bareBones) { + addCommonChoices(dbInitTasks, bareBones); + initGroups.put(listName, dbInitTasks); + } + + public List<String> getDbInitTasks() { + if (choice == null) { + chooser("Select Init Group To Run.", new ArrayList<String>(initGroups.keySet())); + } + return initGroups.get(choice); + } + + private String chooser(String message, List<String> choices) { + String configChoice = OseeProperties.getInstance().getDBConfigInitChoice(); + int selection = -1; + if (false != Strings.isValid(configChoice)) { + selection = choices.indexOf(configChoice); + } + + if (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(); + } + } + } + choice = choices.get(selection); + logger.log(Level.INFO, String.format("DB Config Choice Selected: [%s]", choice)); + return 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>
+
+
diff --git a/org.eclipse.osee.framework.feature.source/.project b/org.eclipse.osee.framework.feature.source/.project new file mode 100644 index 00000000000..22f6a48f918 --- /dev/null +++ b/org.eclipse.osee.framework.feature.source/.project @@ -0,0 +1,22 @@ +<?xml version="1.0" encoding="UTF-8"?> +<projectDescription> + <name>org.eclipse.osee.framework.feature.source</name> + <comment></comment> + <projects> + </projects> + <buildSpec> + <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> + </natures> +</projectDescription> diff --git a/org.eclipse.osee.framework.feature.source/META-INF/MANIFEST.MF b/org.eclipse.osee.framework.feature.source/META-INF/MANIFEST.MF new file mode 100644 index 00000000000..b15a05f7cb8 --- /dev/null +++ b/org.eclipse.osee.framework.feature.source/META-INF/MANIFEST.MF @@ -0,0 +1,7 @@ +Manifest-Version: 1.0 +Bundle-ManifestVersion: 2 +Bundle-Name: Source Plug-in (Incubation) +Bundle-SymbolicName: org.eclipse.osee.framework.feature.source;singleton:=true +Bundle-Version: 0.1.0.qualifier +Require-Bundle: org.eclipse.pde.core +Bundle-Vendor: Eclipse.org diff --git a/org.eclipse.osee.framework.feature.source/build.properties b/org.eclipse.osee.framework.feature.source/build.properties new file mode 100644 index 00000000000..656a07d9290 --- /dev/null +++ b/org.eclipse.osee.framework.feature.source/build.properties @@ -0,0 +1,3 @@ +bin.includes = META-INF/,\ + plugin.xml,\ + src/ diff --git a/org.eclipse.osee.framework.feature.source/plugin.xml b/org.eclipse.osee.framework.feature.source/plugin.xml new file mode 100644 index 00000000000..4e702eba3b3 --- /dev/null +++ b/org.eclipse.osee.framework.feature.source/plugin.xml @@ -0,0 +1,11 @@ +<?xml version="1.0" encoding="UTF-8"?> +<?eclipse version="3.2"?> +<plugin> + <extension + point="org.eclipse.pde.core.source"> + <location + path="src"> + </location> + </extension> + +</plugin> diff --git a/org.eclipse.osee.framework.feature/.project b/org.eclipse.osee.framework.feature/.project new file mode 100644 index 00000000000..56e4f78956a --- /dev/null +++ b/org.eclipse.osee.framework.feature/.project @@ -0,0 +1,17 @@ +<?xml version="1.0" encoding="UTF-8"?> +<projectDescription> + <name>org.eclipse.osee.framework.feature</name> + <comment></comment> + <projects> + </projects> + <buildSpec> + <buildCommand> + <name>org.eclipse.pde.FeatureBuilder</name> + <arguments> + </arguments> + </buildCommand> + </buildSpec> + <natures> + <nature>org.eclipse.pde.FeatureNature</nature> + </natures> +</projectDescription> diff --git a/org.eclipse.osee.framework.feature/build.properties b/org.eclipse.osee.framework.feature/build.properties new file mode 100644 index 00000000000..add83c7a24c --- /dev/null +++ b/org.eclipse.osee.framework.feature/build.properties @@ -0,0 +1,5 @@ +bin.includes = feature.xml,\ + epl-v10.html,\ + feature.properties,\ + license.html,\ + osee_32.png diff --git a/org.eclipse.osee.framework.feature/epl-v10.html b/org.eclipse.osee.framework.feature/epl-v10.html new file mode 100644 index 00000000000..ed4b196655e --- /dev/null +++ b/org.eclipse.osee.framework.feature/epl-v10.html @@ -0,0 +1,328 @@ +<html xmlns:o="urn:schemas-microsoft-com:office:office" +xmlns:w="urn:schemas-microsoft-com:office:word" +xmlns="http://www.w3.org/TR/REC-html40"> + +<head> +<meta http-equiv=Content-Type content="text/html; charset=windows-1252"> +<meta name=ProgId content=Word.Document> +<meta name=Generator content="Microsoft Word 9"> +<meta name=Originator content="Microsoft Word 9"> +<link rel=File-List +href="./Eclipse%20EPL%202003_11_10%20Final_files/filelist.xml"> +<title>Eclipse Public License - Version 1.0</title> +<!--[if gte mso 9]><xml> + <o:DocumentProperties> + <o:Revision>2</o:Revision> + <o:TotalTime>3</o:TotalTime> + <o:Created>2004-03-05T23:03:00Z</o:Created> + <o:LastSaved>2004-03-05T23:03:00Z</o:LastSaved> + <o:Pages>4</o:Pages> + <o:Words>1626</o:Words> + <o:Characters>9270</o:Characters> + <o:Lines>77</o:Lines> + <o:Paragraphs>18</o:Paragraphs> + <o:CharactersWithSpaces>11384</o:CharactersWithSpaces> + <o:Version>9.4402</o:Version> + </o:DocumentProperties> +</xml><![endif]--><!--[if gte mso 9]><xml> + <w:WordDocument> + <w:TrackRevisions/> + </w:WordDocument> +</xml><![endif]--> +<style> +<!-- + /* Font Definitions */ +@font-face + {font-family:Tahoma; + panose-1:2 11 6 4 3 5 4 4 2 4; + mso-font-charset:0; + mso-generic-font-family:swiss; + mso-font-pitch:variable; + mso-font-signature:553679495 -2147483648 8 0 66047 0;} + /* Style Definitions */ +p.MsoNormal, li.MsoNormal, div.MsoNormal + {mso-style-parent:""; + margin:0in; + margin-bottom:.0001pt; + mso-pagination:widow-orphan; + font-size:12.0pt; + font-family:"Times New Roman"; + mso-fareast-font-family:"Times New Roman";} +p + {margin-right:0in; + mso-margin-top-alt:auto; + mso-margin-bottom-alt:auto; + margin-left:0in; + mso-pagination:widow-orphan; + font-size:12.0pt; + font-family:"Times New Roman"; + mso-fareast-font-family:"Times New Roman";} +p.BalloonText, li.BalloonText, div.BalloonText + {mso-style-name:"Balloon Text"; + margin:0in; + margin-bottom:.0001pt; + mso-pagination:widow-orphan; + font-size:8.0pt; + font-family:Tahoma; + mso-fareast-font-family:"Times New Roman";} +@page Section1 + {size:8.5in 11.0in; + margin:1.0in 1.25in 1.0in 1.25in; + mso-header-margin:.5in; + mso-footer-margin:.5in; + mso-paper-source:0;} +div.Section1 + {page:Section1;} +--> +</style> +</head> + +<body lang=EN-US style='tab-interval:.5in'> + +<div class=Section1> + +<p align=center style='text-align:center'><b>Eclipse Public License - v 1.0</b> +</p> + +<p><span style='font-size:10.0pt'>THE ACCOMPANYING PROGRAM IS PROVIDED UNDER +THE TERMS OF THIS ECLIPSE PUBLIC LICENSE ("AGREEMENT"). ANY USE, +REPRODUCTION OR DISTRIBUTION OF THE PROGRAM CONSTITUTES RECIPIENT'S ACCEPTANCE +OF THIS AGREEMENT.</span> </p> + +<p><b><span style='font-size:10.0pt'>1. DEFINITIONS</span></b> </p> + +<p><span style='font-size:10.0pt'>"Contribution" means:</span> </p> + +<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>a) +in the case of the initial Contributor, the initial code and documentation +distributed under this Agreement, and<br clear=left> +b) in the case of each subsequent Contributor:</span></p> + +<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>i) +changes to the Program, and</span></p> + +<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>ii) +additions to the Program;</span></p> + +<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>where +such changes and/or additions to the Program originate from and are distributed +by that particular Contributor. A Contribution 'originates' from a Contributor +if it was added to the Program by such Contributor itself or anyone acting on +such Contributor's behalf. Contributions do not include additions to the +Program which: (i) are separate modules of software distributed in conjunction +with the Program under their own license agreement, and (ii) are not derivative +works of the Program. </span></p> + +<p><span style='font-size:10.0pt'>"Contributor" means any person or +entity that distributes the Program.</span> </p> + +<p><span style='font-size:10.0pt'>"Licensed Patents " mean patent +claims licensable by a Contributor which are necessarily infringed by the use +or sale of its Contribution alone or when combined with the Program. </span></p> + +<p><span style='font-size:10.0pt'>"Program" means the Contributions +distributed in accordance with this Agreement.</span> </p> + +<p><span style='font-size:10.0pt'>"Recipient" means anyone who +receives the Program under this Agreement, including all Contributors.</span> </p> + +<p><b><span style='font-size:10.0pt'>2. GRANT OF RIGHTS</span></b> </p> + +<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>a) +Subject to the terms of this Agreement, each Contributor hereby grants Recipient +a non-exclusive, worldwide, royalty-free copyright license to<span +style='color:red'> </span>reproduce, prepare derivative works of, publicly +display, publicly perform, distribute and sublicense the Contribution of such +Contributor, if any, and such derivative works, in source code and object code +form.</span></p> + +<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>b) +Subject to the terms of this Agreement, each Contributor hereby grants +Recipient a non-exclusive, worldwide,<span style='color:green'> </span>royalty-free +patent license under Licensed Patents to make, use, sell, offer to sell, import +and otherwise transfer the Contribution of such Contributor, if any, in source +code and object code form. This patent license shall apply to the combination +of the Contribution and the Program if, at the time the Contribution is added +by the Contributor, such addition of the Contribution causes such combination +to be covered by the Licensed Patents. The patent license shall not apply to +any other combinations which include the Contribution. No hardware per se is +licensed hereunder. </span></p> + +<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>c) +Recipient understands that although each Contributor grants the licenses to its +Contributions set forth herein, no assurances are provided by any Contributor +that the Program does not infringe the patent or other intellectual property +rights of any other entity. Each Contributor disclaims any liability to Recipient +for claims brought by any other entity based on infringement of intellectual +property rights or otherwise. As a condition to exercising the rights and +licenses granted hereunder, each Recipient hereby assumes sole responsibility +to secure any other intellectual property rights needed, if any. For example, +if a third party patent license is required to allow Recipient to distribute +the Program, it is Recipient's responsibility to acquire that license before +distributing the Program.</span></p> + +<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>d) +Each Contributor represents that to its knowledge it has sufficient copyright +rights in its Contribution, if any, to grant the copyright license set forth in +this Agreement. </span></p> + +<p><b><span style='font-size:10.0pt'>3. REQUIREMENTS</span></b> </p> + +<p><span style='font-size:10.0pt'>A Contributor may choose to distribute the +Program in object code form under its own license agreement, provided that:</span> +</p> + +<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>a) +it complies with the terms and conditions of this Agreement; and</span></p> + +<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>b) +its license agreement:</span></p> + +<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>i) +effectively disclaims on behalf of all Contributors all warranties and +conditions, express and implied, including warranties or conditions of title +and non-infringement, and implied warranties or conditions of merchantability +and fitness for a particular purpose; </span></p> + +<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>ii) +effectively excludes on behalf of all Contributors all liability for damages, +including direct, indirect, special, incidental and consequential damages, such +as lost profits; </span></p> + +<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>iii) +states that any provisions which differ from this Agreement are offered by that +Contributor alone and not by any other party; and</span></p> + +<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>iv) +states that source code for the Program is available from such Contributor, and +informs licensees how to obtain it in a reasonable manner on or through a +medium customarily used for software exchange.<span style='color:blue'> </span></span></p> + +<p><span style='font-size:10.0pt'>When the Program is made available in source +code form:</span> </p> + +<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>a) +it must be made available under this Agreement; and </span></p> + +<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>b) a +copy of this Agreement must be included with each copy of the Program. </span></p> + +<p><span style='font-size:10.0pt'>Contributors may not remove or alter any +copyright notices contained within the Program. </span></p> + +<p><span style='font-size:10.0pt'>Each Contributor must identify itself as the +originator of its Contribution, if any, in a manner that reasonably allows +subsequent Recipients to identify the originator of the Contribution. </span></p> + +<p><b><span style='font-size:10.0pt'>4. COMMERCIAL DISTRIBUTION</span></b> </p> + +<p><span style='font-size:10.0pt'>Commercial distributors of software may +accept certain responsibilities with respect to end users, business partners +and the like. While this license is intended to facilitate the commercial use +of the Program, the Contributor who includes the Program in a commercial +product offering should do so in a manner which does not create potential +liability for other Contributors. Therefore, if a Contributor includes the +Program in a commercial product offering, such Contributor ("Commercial +Contributor") hereby agrees to defend and indemnify every other +Contributor ("Indemnified Contributor") against any losses, damages and +costs (collectively "Losses") arising from claims, lawsuits and other +legal actions brought by a third party against the Indemnified Contributor to +the extent caused by the acts or omissions of such Commercial Contributor in +connection with its distribution of the Program in a commercial product +offering. The obligations in this section do not apply to any claims or Losses +relating to any actual or alleged intellectual property infringement. In order +to qualify, an Indemnified Contributor must: a) promptly notify the Commercial +Contributor in writing of such claim, and b) allow the Commercial Contributor +to control, and cooperate with the Commercial Contributor in, the defense and +any related settlement negotiations. The Indemnified Contributor may participate +in any such claim at its own expense.</span> </p> + +<p><span style='font-size:10.0pt'>For example, a Contributor might include the +Program in a commercial product offering, Product X. That Contributor is then a +Commercial Contributor. If that Commercial Contributor then makes performance +claims, or offers warranties related to Product X, those performance claims and +warranties are such Commercial Contributor's responsibility alone. Under this +section, the Commercial Contributor would have to defend claims against the +other Contributors related to those performance claims and warranties, and if a +court requires any other Contributor to pay any damages as a result, the +Commercial Contributor must pay those damages.</span> </p> + +<p><b><span style='font-size:10.0pt'>5. NO WARRANTY</span></b> </p> + +<p><span style='font-size:10.0pt'>EXCEPT AS EXPRESSLY SET FORTH IN THIS +AGREEMENT, THE PROGRAM IS PROVIDED ON AN "AS IS" BASIS, WITHOUT +WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED INCLUDING, +WITHOUT LIMITATION, ANY WARRANTIES OR CONDITIONS OF TITLE, NON-INFRINGEMENT, +MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Each Recipient is solely +responsible for determining the appropriateness of using and distributing the +Program and assumes all risks associated with its exercise of rights under this +Agreement , including but not limited to the risks and costs of program errors, +compliance with applicable laws, damage to or loss of data, programs or +equipment, and unavailability or interruption of operations. </span></p> + +<p><b><span style='font-size:10.0pt'>6. DISCLAIMER OF LIABILITY</span></b> </p> + +<p><span style='font-size:10.0pt'>EXCEPT AS EXPRESSLY SET FORTH IN THIS +AGREEMENT, NEITHER RECIPIENT NOR ANY CONTRIBUTORS SHALL HAVE ANY LIABILITY FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING WITHOUT LIMITATION LOST PROFITS), HOWEVER CAUSED AND ON ANY THEORY +OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OR DISTRIBUTION OF +THE PROGRAM OR THE EXERCISE OF ANY RIGHTS GRANTED HEREUNDER, EVEN IF ADVISED OF +THE POSSIBILITY OF SUCH DAMAGES.</span> </p> + +<p><b><span style='font-size:10.0pt'>7. GENERAL</span></b> </p> + +<p><span style='font-size:10.0pt'>If any provision of this Agreement is invalid +or unenforceable under applicable law, it shall not affect the validity or +enforceability of the remainder of the terms of this Agreement, and without +further action by the parties hereto, such provision shall be reformed to the +minimum extent necessary to make such provision valid and enforceable.</span> </p> + +<p><span style='font-size:10.0pt'>If Recipient institutes patent litigation +against any entity (including a cross-claim or counterclaim in a lawsuit) +alleging that the Program itself (excluding combinations of the Program with +other software or hardware) infringes such Recipient's patent(s), then such +Recipient's rights granted under Section 2(b) shall terminate as of the date +such litigation is filed. </span></p> + +<p><span style='font-size:10.0pt'>All Recipient's rights under this Agreement +shall terminate if it fails to comply with any of the material terms or +conditions of this Agreement and does not cure such failure in a reasonable +period of time after becoming aware of such noncompliance. If all Recipient's +rights under this Agreement terminate, Recipient agrees to cease use and +distribution of the Program as soon as reasonably practicable. However, +Recipient's obligations under this Agreement and any licenses granted by +Recipient relating to the Program shall continue and survive. </span></p> + +<p><span style='font-size:10.0pt'>Everyone is permitted to copy and distribute +copies of this Agreement, but in order to avoid inconsistency the Agreement is +copyrighted and may only be modified in the following manner. The Agreement +Steward reserves the right to publish new versions (including revisions) of +this Agreement from time to time. No one other than the Agreement Steward has +the right to modify this Agreement. The Eclipse Foundation is the initial +Agreement Steward. The Eclipse Foundation may assign the responsibility to +serve as the Agreement Steward to a suitable separate entity. Each new version +of the Agreement will be given a distinguishing version number. The Program +(including Contributions) may always be distributed subject to the version of +the Agreement under which it was received. In addition, after a new version of +the Agreement is published, Contributor may elect to distribute the Program +(including its Contributions) under the new version. Except as expressly stated +in Sections 2(a) and 2(b) above, Recipient receives no rights or licenses to +the intellectual property of any Contributor under this Agreement, whether +expressly, by implication, estoppel or otherwise. All rights in the Program not +expressly granted under this Agreement are reserved.</span> </p> + +<p><span style='font-size:10.0pt'>This Agreement is governed by the laws of the +State of New York and the intellectual property laws of the United States of +America. No party to this Agreement will bring a legal action under this +Agreement more than one year after the cause of action arose. Each party waives +its rights to a jury trial in any resulting litigation.</span> </p> + +<p class=MsoNormal><![if !supportEmptyParas]> <![endif]><o:p></o:p></p> + +</div> + +</body> + +</html>
\ No newline at end of file diff --git a/org.eclipse.osee.framework.feature/feature.properties b/org.eclipse.osee.framework.feature/feature.properties new file mode 100644 index 00000000000..041b468f559 --- /dev/null +++ b/org.eclipse.osee.framework.feature/feature.properties @@ -0,0 +1,144 @@ +############################################################################### +# Copyright (c) 2004, 2007 Boeing and others. +# 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 +############################################################################### +# feature.properties +# contains externalized strings for feature.xml +# "%foo" in feature.xml corresponds to the key "foo" in this file +# java.io.Properties file (ISO 8859-1 with "\" escapes) +# This file should be translated. + +# "featureName" property - name of the feature +featureName=Open System Engineering Environment + +# "providerName" property - name of the company that provides the feature +providerName=Eclipse.org + +# "updateSiteName" property - label for the update site +updateSiteName=OSEE Update + +# "description" property - description of the feature +description=Open System Engineering Environment + +# "copyright" property - text of the "Feature Update Copyright" +copyright=\ +Copyright (c) 2004, 2007 Boeing and others.\n\ +All rights reserved. This program and the accompanying materials\n\ +are made available under the terms of the Eclipse Public License v1.0\n\ +which accompanies this distribution, and is available at\n\ +http://www.eclipse.org/legal/epl-v10.html\n\ +\n\ +Contributors:\n\ + Boeing - initial API and implementation\n +################ end of copyright property #################################### + +# "licenseURL" property - URL of the "Feature License" +# do not translate value - just change to point to a locale-specific HTML page +licenseURL=license.html + +# "license" property - text of the "Feature Update License" +# should be plain text version of license agreement pointed to be "licenseURL" +license=\ +ECLIPSE FOUNDATION SOFTWARE USER AGREEMENT\n\ +March 17, 2005\n\ +\n\ +Usage Of Content\n\ +\n\ +THE ECLIPSE FOUNDATION MAKES AVAILABLE SOFTWARE, DOCUMENTATION, INFORMATION AND/OR\n\ +OTHER MATERIALS FOR OPEN SOURCE PROJECTS (COLLECTIVELY "CONTENT").\n\ +USE OF THE CONTENT IS GOVERNED BY THE TERMS AND CONDITIONS OF THIS\n\ +AGREEMENT AND/OR THE TERMS AND CONDITIONS OF LICENSE AGREEMENTS OR\n\ +NOTICES INDICATED OR REFERENCED BELOW. BY USING THE CONTENT, YOU\n\ +AGREE THAT YOUR USE OF THE CONTENT IS GOVERNED BY THIS AGREEMENT\n\ +AND/OR THE TERMS AND CONDITIONS OF ANY APPLICABLE LICENSE AGREEMENTS\n\ +OR NOTICES INDICATED OR REFERENCED BELOW. IF YOU DO NOT AGREE TO THE\n\ +TERMS AND CONDITIONS OF THIS AGREEMENT AND THE TERMS AND CONDITIONS\n\ +OF ANY APPLICABLE LICENSE AGREEMENTS OR NOTICES INDICATED OR REFERENCED\n\ +BELOW, THEN YOU MAY NOT USE THE CONTENT.\n\ +\n\ +Applicable Licenses\n\ +\n\ +Unless otherwise indicated, all Content made available by the Eclipse Foundation\n\ +is provided to you under the terms and conditions of the Eclipse Public\n\ +License Version 1.0 ("EPL"). A copy of the EPL is provided with this\n\ +Content and is also available at http://www.eclipse.org/legal/epl-v10.html.\n\ +For purposes of the EPL, "Program" will mean the Content.\n\ +\n\ +Content includes, but is not limited to, source code, object code,\n\ +documentation and other files maintained in the Eclipse.org CVS\n\ +repository ("Repository") in CVS modules ("Modules") and made available\n\ +as downloadable archives ("Downloads").\n\ +\n\ + - Content may be structured and packaged into modules to facilitate delivering,\n\ + extending, and upgrading the Content. Typical modules may include plug-ins ("Plug-ins"),\n\ + plug-in fragments ("Fragments"), and features ("Features").\n\ + - Each Plug-in or Fragment may be packaged as a sub-directory or JAR (Java? ARchive)\n\ + in a directory named "plugins".\n\ + - A Feature is a bundle of one or more Plug-ins and/or Fragments and associated material.\n\ + Each Feature may be packaged as a sub-directory in a directory named "features".\n\ + Within a Feature, files named "feature.xml" may contain a list of the names and version\n\ + numbers of the Plug-ins and/or Fragments associated with that Feature.\n\ + - Features may also include other Features ("Included Features"). Within a Feature, files\n\ + named "feature.xml" may contain a list of the names and version numbers of Included Features.\n\ +\n\ +Features may also include other Features ("Included Features"). Files named\n\ +"feature.xml" may contain a list of the names and version numbers of\n\ +Included Features.\n\ +\n\ +The terms and conditions governing Plug-ins and Fragments should be\n\ +contained in files named "about.html" ("Abouts"). The terms and\n\ +conditions governing Features and Included Features should be contained\n\ +in files named "license.html" ("Feature Licenses"). Abouts and Feature\n\ +Licenses may be located in any directory of a Download or Module\n\ +including, but not limited to the following locations:\n\ +\n\ + - The top-level (root) directory\n\ + - Plug-in and Fragment directories\n\ + - Inside Plug-ins and Fragments packaged as JARs\n\ + - Sub-directories of the directory named "src" of certain Plug-ins\n\ + - Feature directories\n\ +\n\ +Note: if a Feature made available by the Eclipse Foundation is installed using the\n\ +Eclipse Update Manager, you must agree to a license ("Feature Update\n\ +License") during the installation process. If the Feature contains\n\ +Included Features, the Feature Update License should either provide you\n\ +with the terms and conditions governing the Included Features or inform\n\ +you where you can locate them. Feature Update Licenses may be found in\n\ +the "license" property of files named "feature.properties". Such Abouts,\n\ +Feature Licenses and Feature Update Licenses contain the terms and\n\ +conditions (or references to such terms and conditions) that govern your\n\ +use of the associated Content in that directory.\n\ +\n\ +THE ABOUTS, FEATURE LICENSES AND FEATURE UPDATE LICENSES MAY REFER\n\ +TO THE EPL OR OTHER LICENSE AGREEMENTS, NOTICES OR TERMS AND CONDITIONS.\n\ +SOME OF THESE OTHER LICENSE AGREEMENTS MAY INCLUDE (BUT ARE NOT LIMITED TO):\n\ +\n\ + - Common Public License Version 1.0 (available at http://www.eclipse.org/legal/cpl-v10.html)\n\ + - Apache Software License 1.1 (available at http://www.apache.org/licenses/LICENSE)\n\ + - Apache Software License 2.0 (available at http://www.apache.org/licenses/LICENSE-2.0)\n\ + - IBM Public License 1.0 (available at http://oss.software.ibm.com/developerworks/opensource/license10.html)\n\ + - Metro Link Public License 1.00 (available at http://www.opengroup.org/openmotif/supporters/metrolink/license.html)\n\ + - Mozilla Public License Version 1.1 (available at http://www.mozilla.org/MPL/MPL-1.1.html)\n\ +\n\ +IT IS YOUR OBLIGATION TO READ AND ACCEPT ALL SUCH TERMS AND CONDITIONS PRIOR\n\ +TO USE OF THE CONTENT. If no About, Feature License or Feature Update License\n\ +is provided, please contact the Eclipse Foundation to determine what terms and conditions\n\ +govern that particular Content.\n\ +\n\ +Cryptography\n\ +\n\ +Content may contain encryption software. The country in which you are\n\ +currently may have restrictions on the import, possession, and use,\n\ +and/or re-export to another country, of encryption software. BEFORE\n\ +using any encryption software, please check the country's laws,\n\ +regulations and policies concerning the import, possession, or use,\n\ +and re-export of encryption software, to see if this is permitted.\n\ +\n\ +Java and all Java-based trademarks are trademarks of Sun Microsystems, Inc. in the United States, other countries, or both.\n +########### end of license property ########################################## diff --git a/org.eclipse.osee.framework.feature/feature.xml b/org.eclipse.osee.framework.feature/feature.xml new file mode 100644 index 00000000000..e5750630144 --- /dev/null +++ b/org.eclipse.osee.framework.feature/feature.xml @@ -0,0 +1,169 @@ +<?xml version="1.0" encoding="UTF-8"?>
+<feature
+ id="org.eclipse.osee.framework.feature"
+ label="OSEE Framework (Incubation)"
+ version="0.1.0.qualifier"
+ provider-name="Eclipse.org"
+ plugin="org.eclipse.osee.framework.ui.product">
+
+ <description url="http://www.example.com/description">
+ [Enter Feature Description here.]
+ </description>
+
+ <copyright url="http://www.example.com/copyright">
+ [Enter Copyright Description here.]
+ </copyright>
+
+ <license url="%licenseURL">
+ %license
+ </license>
+
+ <url>
+ <update url="http://lba-cte.msc.az.boeing.com:31110/osee/lba_updatesite/"/>
+ </url>
+
+ <requires>
+ <import plugin="org.eclipse.ui"/>
+ <import plugin="org.eclipse.core.runtime"/>
+ <import plugin="org.eclipse.core.resources"/>
+ <import plugin="org.junit"/>
+ <import plugin="org.eclipse.ui.ide"/>
+ <import plugin="org.apache.xerces"/>
+ <import plugin="org.apache.ant"/>
+ <import plugin="org.eclipse.ui.editors"/>
+ <import plugin="org.eclipse.update.core"/>
+ <import plugin="org.eclipse.ui.views"/>
+ <import plugin="org.eclipse.ant.core"/>
+ <import plugin="org.eclipse.gef"/>
+ <import plugin="com.ibm.icu"/>
+ <import plugin="org.eclipse.swt"/>
+ <import plugin="org.eclipse.jface"/>
+ <import plugin="org.eclipse.pde.core"/>
+ </requires>
+
+ <plugin
+ id="org.eclipse.osee.framework.database"
+ download-size="0"
+ install-size="0"
+ version="0.0.0"/>
+
+ <plugin
+ id="org.eclipse.osee.framework.jdk.core"
+ download-size="0"
+ install-size="0"
+ version="0.0.0"/>
+
+ <plugin
+ id="org.eclipse.osee.framework.jini"
+ download-size="0"
+ install-size="0"
+ version="0.0.0"/>
+
+ <plugin
+ id="org.eclipse.osee.framework.messaging.event.skynet"
+ download-size="0"
+ install-size="0"
+ version="0.0.0"/>
+
+ <plugin
+ id="org.eclipse.osee.framework.plugin.core"
+ download-size="0"
+ install-size="0"
+ version="0.0.0"/>
+
+ <plugin
+ id="org.eclipse.osee.framework.skynet.core"
+ download-size="0"
+ install-size="0"
+ version="0.0.0"/>
+
+ <plugin
+ id="org.eclipse.osee.framework.svn"
+ download-size="0"
+ install-size="0"
+ version="0.0.0"/>
+
+ <plugin
+ id="org.eclipse.osee.framework.templates"
+ download-size="0"
+ install-size="0"
+ version="0.0.0"
+ unpack="false"/>
+
+ <plugin
+ id="org.eclipse.osee.framework.updater"
+ download-size="0"
+ install-size="0"
+ version="0.0.0"
+ unpack="false"/>
+
+ <plugin
+ id="ganymed.ssh"
+ download-size="0"
+ install-size="0"
+ version="0.0.0"/>
+
+ <plugin
+ id="javax.mail"
+ download-size="0"
+ install-size="0"
+ version="0.0.0"/>
+
+ <plugin
+ id="net.jini"
+ download-size="0"
+ install-size="0"
+ version="0.0.0"/>
+
+ <plugin
+ id="org.tigris.subversion.svnant"
+ download-size="0"
+ install-size="0"
+ version="0.0.0"/>
+
+ <plugin
+ id="quartz.timer"
+ download-size="0"
+ install-size="0"
+ version="0.0.0"/>
+
+ <plugin
+ id="org.postgresql.driver"
+ download-size="0"
+ install-size="0"
+ version="0.0.0"/>
+
+ <plugin
+ id="org.eclipse.osee.framework.feature.source"
+ download-size="0"
+ install-size="0"
+ version="0.0.0"/>
+
+ <plugin
+ id="org.eclipse.mylyn.zest.core"
+ download-size="0"
+ install-size="0"
+ version="0.0.0"
+ unpack="false"/>
+
+ <plugin
+ id="org.eclipse.mylyn.zest.layouts"
+ download-size="0"
+ install-size="0"
+ version="0.0.0"
+ unpack="false"/>
+
+ <plugin
+ id="jakarta.commons.net"
+ download-size="0"
+ install-size="0"
+ version="0.0.0"/>
+
+ <plugin
+ id="org.apache.commons.lang"
+ download-size="0"
+ install-size="0"
+ version="0.0.0"
+ unpack="false"/>
+
+</feature>
diff --git a/org.eclipse.osee.framework.feature/license.html b/org.eclipse.osee.framework.feature/license.html new file mode 100644 index 00000000000..8d844b3b945 --- /dev/null +++ b/org.eclipse.osee.framework.feature/license.html @@ -0,0 +1,80 @@ +<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN"> +<html> +<head> +<meta http-equiv=Content-Type content="text/html; charset=iso-8859-1"> +<title>Eclipse.org Software User Agreement</title> +</head> + +<body lang="EN-US" link=blue vlink=purple> +<h2>Eclipse Foundation Software User Agreement</h2> +<p>March 17, 2005</p> + +<h3>Usage Of Content</h3> + +<p>THE ECLIPSE FOUNDATION MAKES AVAILABLE SOFTWARE, DOCUMENTATION, INFORMATION AND/OR OTHER MATERIALS FOR OPEN SOURCE PROJECTS + (COLLECTIVELY "CONTENT"). USE OF THE CONTENT IS GOVERNED BY THE TERMS AND CONDITIONS OF THIS AGREEMENT AND/OR THE TERMS AND + CONDITIONS OF LICENSE AGREEMENTS OR NOTICES INDICATED OR REFERENCED BELOW. BY USING THE CONTENT, YOU AGREE THAT YOUR USE + OF THE CONTENT IS GOVERNED BY THIS AGREEMENT AND/OR THE TERMS AND CONDITIONS OF ANY APPLICABLE LICENSE AGREEMENTS OR + NOTICES INDICATED OR REFERENCED BELOW. IF YOU DO NOT AGREE TO THE TERMS AND CONDITIONS OF THIS AGREEMENT AND THE TERMS AND + CONDITIONS OF ANY APPLICABLE LICENSE AGREEMENTS OR NOTICES INDICATED OR REFERENCED BELOW, THEN YOU MAY NOT USE THE CONTENT.</p> + +<h3>Applicable Licenses</h3> + +<p>Unless otherwise indicated, all Content made available by the Eclipse Foundation is provided to you under the terms and conditions of the Eclipse Public License Version 1.0 + ("EPL"). A copy of the EPL is provided with this Content and is also available at <a href="http://www.eclipse.org/legal/epl-v10.html">http://www.eclipse.org/legal/epl-v10.html</a>. + For purposes of the EPL, "Program" will mean the Content.</p> + +<p>Content includes, but is not limited to, source code, object code, documentation and other files maintained in the Eclipse.org CVS repository ("Repository") in CVS + modules ("Modules") and made available as downloadable archives ("Downloads").</p> + +<ul> + <li>Content may be structured and packaged into modules to facilitate delivering, extending, and upgrading the Content. Typical modules may include plug-ins ("Plug-ins"), plug-in fragments ("Fragments"), and features ("Features").</li> + <li>Each Plug-in or Fragment may be packaged as a sub-directory or JAR (Java™ ARchive) in a directory named "plugins".</li> + <li>A Feature is a bundle of one or more Plug-ins and/or Fragments and associated material. Each Feature may be packaged as a sub-directory in a directory named "features". Within a Feature, files named "feature.xml" may contain a list of the names and version numbers of the Plug-ins + and/or Fragments associated with that Feature.</li> + <li>Features may also include other Features ("Included Features"). Within a Feature, files named "feature.xml" may contain a list of the names and version numbers of Included Features.</li> +</ul> + +<p>The terms and conditions governing Plug-ins and Fragments should be contained in files named "about.html" ("Abouts"). The terms and conditions governing Features and +Included Features should be contained in files named "license.html" ("Feature Licenses"). Abouts and Feature Licenses may be located in any directory of a Download or Module +including, but not limited to the following locations:</p> + +<ul> + <li>The top-level (root) directory</li> + <li>Plug-in and Fragment directories</li> + <li>Inside Plug-ins and Fragments packaged as JARs</li> + <li>Sub-directories of the directory named "src" of certain Plug-ins</li> + <li>Feature directories</li> +</ul> + +<p>Note: if a Feature made available by the Eclipse Foundation is installed using the Eclipse Update Manager, you must agree to a license ("Feature Update License") during the +installation process. If the Feature contains Included Features, the Feature Update License should either provide you with the terms and conditions governing the Included Features or +inform you where you can locate them. Feature Update Licenses may be found in the "license" property of files named "feature.properties" found within a Feature. +Such Abouts, Feature Licenses, and Feature Update Licenses contain the terms and conditions (or references to such terms and conditions) that govern your use of the associated Content in +that directory.</p> + +<p>THE ABOUTS, FEATURE LICENSES, AND FEATURE UPDATE LICENSES MAY REFER TO THE EPL OR OTHER LICENSE AGREEMENTS, NOTICES OR TERMS AND CONDITIONS. SOME OF THESE +OTHER LICENSE AGREEMENTS MAY INCLUDE (BUT ARE NOT LIMITED TO):</p> + +<ul> + <li>Common Public License Version 1.0 (available at <a href="http://www.eclipse.org/legal/cpl-v10.html">http://www.eclipse.org/legal/cpl-v10.html</a>)</li> + <li>Apache Software License 1.1 (available at <a href="http://www.apache.org/licenses/LICENSE">http://www.apache.org/licenses/LICENSE</a>)</li> + <li>Apache Software License 2.0 (available at <a href="http://www.apache.org/licenses/LICENSE-2.0">http://www.apache.org/licenses/LICENSE-2.0</a>)</li> + <li>IBM Public License 1.0 (available at <a href="http://oss.software.ibm.com/developerworks/opensource/license10.html">http://oss.software.ibm.com/developerworks/opensource/license10.html</a>)</li> + <li>Metro Link Public License 1.00 (available at <a href="http://www.opengroup.org/openmotif/supporters/metrolink/license.html">http://www.opengroup.org/openmotif/supporters/metrolink/license.html</a>)</li> + <li>Mozilla Public License Version 1.1 (available at <a href="http://www.mozilla.org/MPL/MPL-1.1.html">http://www.mozilla.org/MPL/MPL-1.1.html</a>)</li>
+ <li>Ganymed license - Swiss Federal Institute of Technology (available at <a href="http://www.ganymed.ethz.ch/ssh2/">http://www.mozilla.org/MPL/MPL-1.1.html</a>)</li>
+</ul> + +<p>IT IS YOUR OBLIGATION TO READ AND ACCEPT ALL SUCH TERMS AND CONDITIONS PRIOR TO USE OF THE CONTENT. If no About, Feature License, or Feature Update License is provided, please +contact the Eclipse Foundation to determine what terms and conditions govern that particular Content.</p> + +<h3>Cryptography</h3> + +<p>Content may contain encryption software. The country in which you are currently may have restrictions on the import, possession, and use, and/or re-export to + another country, of encryption software. BEFORE using any encryption software, please check the country's laws, regulations and policies concerning the import, + possession, or use, and re-export of encryption software, to see if this is permitted.</p> + +<small>Java and all Java-based trademarks are trademarks of Sun Microsystems, Inc. in the United States, other countries, or both.</small> +</body> +</html> diff --git a/org.eclipse.osee.framework.feature/osee_32.png b/org.eclipse.osee.framework.feature/osee_32.png Binary files differnew file mode 100644 index 00000000000..5e36a1842e6 --- /dev/null +++ b/org.eclipse.osee.framework.feature/osee_32.png diff --git a/org.eclipse.osee.framework.jdk.core/.classpath b/org.eclipse.osee.framework.jdk.core/.classpath new file mode 100644 index 00000000000..6e16b23d695 --- /dev/null +++ b/org.eclipse.osee.framework.jdk.core/.classpath @@ -0,0 +1,7 @@ +<?xml version="1.0" encoding="UTF-8"?>
+<classpath>
+ <classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/>
+ <classpathentry kind="src" path="src"/>
+ <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
+ <classpathentry kind="output" path="bin"/>
+</classpath>
diff --git a/org.eclipse.osee.framework.jdk.core/.project b/org.eclipse.osee.framework.jdk.core/.project new file mode 100644 index 00000000000..c729976c89e --- /dev/null +++ b/org.eclipse.osee.framework.jdk.core/.project @@ -0,0 +1,28 @@ +<?xml version="1.0" encoding="UTF-8"?>
+<projectDescription>
+ <name>org.eclipse.osee.framework.jdk.core</name>
+ <comment></comment>
+ <projects>
+ </projects>
+ <buildSpec>
+ <buildCommand>
+ <name>org.eclipse.jdt.core.javabuilder</name>
+ <arguments>
+ </arguments>
+ </buildCommand>
+ <buildCommand>
+ <name>org.eclipse.pde.ManifestBuilder</name>
+ <arguments>
+ </arguments>
+ </buildCommand>
+ <buildCommand>
+ <name>org.eclipse.pde.SchemaBuilder</name>
+ <arguments>
+ </arguments>
+ </buildCommand>
+ </buildSpec>
+ <natures>
+ <nature>org.eclipse.pde.PluginNature</nature>
+ <nature>org.eclipse.jdt.core.javanature</nature>
+ </natures>
+</projectDescription>
diff --git a/org.eclipse.osee.framework.jdk.core/.settings/org.eclipse.jdt.core.prefs b/org.eclipse.osee.framework.jdk.core/.settings/org.eclipse.jdt.core.prefs new file mode 100644 index 00000000000..850a818aca8 --- /dev/null +++ b/org.eclipse.osee.framework.jdk.core/.settings/org.eclipse.jdt.core.prefs @@ -0,0 +1,47 @@ +#Sun Aug 20 08:34:27 MST 2006 +eclipse.preferences.version=1 +org.eclipse.jdt.core.compiler.problem.annotationSuperInterface=warning +org.eclipse.jdt.core.compiler.problem.autoboxing=ignore +org.eclipse.jdt.core.compiler.problem.deprecation=warning +org.eclipse.jdt.core.compiler.problem.deprecationInDeprecatedCode=disabled +org.eclipse.jdt.core.compiler.problem.deprecationWhenOverridingDeprecatedMethod=disabled +org.eclipse.jdt.core.compiler.problem.discouragedReference=warning +org.eclipse.jdt.core.compiler.problem.emptyStatement=ignore +org.eclipse.jdt.core.compiler.problem.fieldHiding=ignore +org.eclipse.jdt.core.compiler.problem.finalParameterBound=warning +org.eclipse.jdt.core.compiler.problem.finallyBlockNotCompletingNormally=warning +org.eclipse.jdt.core.compiler.problem.forbiddenReference=error +org.eclipse.jdt.core.compiler.problem.hiddenCatchBlock=warning +org.eclipse.jdt.core.compiler.problem.incompatibleNonInheritedInterfaceMethod=warning +org.eclipse.jdt.core.compiler.problem.incompleteEnumSwitch=ignore +org.eclipse.jdt.core.compiler.problem.indirectStaticAccess=ignore +org.eclipse.jdt.core.compiler.problem.localVariableHiding=ignore +org.eclipse.jdt.core.compiler.problem.methodWithConstructorName=warning +org.eclipse.jdt.core.compiler.problem.missingDeprecatedAnnotation=ignore +org.eclipse.jdt.core.compiler.problem.missingOverrideAnnotation=ignore +org.eclipse.jdt.core.compiler.problem.missingSerialVersion=warning +org.eclipse.jdt.core.compiler.problem.noEffectAssignment=warning +org.eclipse.jdt.core.compiler.problem.noImplicitStringConversion=warning +org.eclipse.jdt.core.compiler.problem.nonExternalizedStringLiteral=ignore +org.eclipse.jdt.core.compiler.problem.overridingPackageDefaultMethod=warning +org.eclipse.jdt.core.compiler.problem.possibleAccidentalBooleanAssignment=ignore +org.eclipse.jdt.core.compiler.problem.specialParameterHidingField=disabled +org.eclipse.jdt.core.compiler.problem.staticAccessReceiver=warning +org.eclipse.jdt.core.compiler.problem.suppressWarnings=enabled +org.eclipse.jdt.core.compiler.problem.syntheticAccessEmulation=ignore +org.eclipse.jdt.core.compiler.problem.typeParameterHiding=warning +org.eclipse.jdt.core.compiler.problem.uncheckedTypeOperation=ignore +org.eclipse.jdt.core.compiler.problem.undocumentedEmptyBlock=ignore +org.eclipse.jdt.core.compiler.problem.unhandledWarningToken=warning +org.eclipse.jdt.core.compiler.problem.unnecessaryElse=ignore +org.eclipse.jdt.core.compiler.problem.unnecessaryTypeCheck=ignore +org.eclipse.jdt.core.compiler.problem.unqualifiedFieldAccess=ignore +org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownException=ignore +org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionWhenOverriding=disabled +org.eclipse.jdt.core.compiler.problem.unusedImport=warning +org.eclipse.jdt.core.compiler.problem.unusedLocal=warning +org.eclipse.jdt.core.compiler.problem.unusedParameter=ignore +org.eclipse.jdt.core.compiler.problem.unusedParameterWhenImplementingAbstract=disabled +org.eclipse.jdt.core.compiler.problem.unusedParameterWhenOverridingConcrete=disabled +org.eclipse.jdt.core.compiler.problem.unusedPrivateMember=warning +org.eclipse.jdt.core.compiler.problem.varargsArgumentNeedCast=warning diff --git a/org.eclipse.osee.framework.jdk.core/META-INF/MANIFEST.MF b/org.eclipse.osee.framework.jdk.core/META-INF/MANIFEST.MF new file mode 100644 index 00000000000..aa9c7542644 --- /dev/null +++ b/org.eclipse.osee.framework.jdk.core/META-INF/MANIFEST.MF @@ -0,0 +1,36 @@ +Manifest-Version: 1.0 +Bundle-ManifestVersion: 2 +Bundle-Name: OSEE JDK Core Plug-in (Incubation) +Bundle-SymbolicName: org.eclipse.osee.framework.jdk.core;singleton:=true +Bundle-Version: 0.1.0.qualifier +Bundle-ClassPath: core.jar +Bundle-Vendor: Eclipse.org +Export-Package: org.eclipse.osee.framework.jdk.core.collection.tree, + org.eclipse.osee.framework.jdk.core.db, + org.eclipse.osee.framework.jdk.core.directory, + org.eclipse.osee.framework.jdk.core.persistence, + org.eclipse.osee.framework.jdk.core.reportdata, + org.eclipse.osee.framework.jdk.core.stateMachine, + org.eclipse.osee.framework.jdk.core.text, + org.eclipse.osee.framework.jdk.core.text.change, + org.eclipse.osee.framework.jdk.core.text.rules, + org.eclipse.osee.framework.jdk.core.text.tool, + org.eclipse.osee.framework.jdk.core.type, + org.eclipse.osee.framework.jdk.core.util, + org.eclipse.osee.framework.jdk.core.util.benchmark, + org.eclipse.osee.framework.jdk.core.util.io, + org.eclipse.osee.framework.jdk.core.util.io.streams, + org.eclipse.osee.framework.jdk.core.util.io.xml, + org.eclipse.osee.framework.jdk.core.util.io.xml.excel, + org.eclipse.osee.framework.jdk.core.util.network, + org.eclipse.osee.framework.jdk.core.util.requirement, + org.eclipse.osee.framework.jdk.core.util.time, + org.eclipse.osee.framework.jdk.core.util.windows, + org.eclipse.osee.framework.jdk.core.util.xml, + org.eclipse.osee.framework.jdk.core.util.xml.excel, + org.eclipse.osee.framework.jdk.core.util.xml.parser, + org.eclipse.osee.framework.jdk.core.validate +Require-Bundle: org.junit, + javax.mail, + org.eclipse.core.runtime +Eclipse-LazyStart: true diff --git a/org.eclipse.osee.framework.jdk.core/build.properties b/org.eclipse.osee.framework.jdk.core/build.properties new file mode 100644 index 00000000000..13110ee8b6d --- /dev/null +++ b/org.eclipse.osee.framework.jdk.core/build.properties @@ -0,0 +1,7 @@ +bin.includes = META-INF/,\ + lib/,\ + plugin.xml,\ + core.jar +source.core.jar = src/ +output.core.jar = bin/ +jars.compile.order = core.jar diff --git a/org.eclipse.osee.framework.jdk.core/plugin.xml b/org.eclipse.osee.framework.jdk.core/plugin.xml new file mode 100644 index 00000000000..5bd0a812edc --- /dev/null +++ b/org.eclipse.osee.framework.jdk.core/plugin.xml @@ -0,0 +1,6 @@ +<?xml version="1.0" encoding="UTF-8"?> +<?eclipse version="3.0"?> +<plugin>
+ <extension-point id="DefaultMailServer" name="Default Mail Server" schema="schema/DefaultMailServer.exsd"/>
+ +</plugin> diff --git a/org.eclipse.osee.framework.jdk.core/schema/DefaultMailServer.exsd b/org.eclipse.osee.framework.jdk.core/schema/DefaultMailServer.exsd new file mode 100644 index 00000000000..644d1553e72 --- /dev/null +++ b/org.eclipse.osee.framework.jdk.core/schema/DefaultMailServer.exsd @@ -0,0 +1,102 @@ +<?xml version='1.0' encoding='UTF-8'?>
+<!-- Schema file written by PDE -->
+<schema targetNamespace="org.eclipse.osee.framework.jdk.core">
+<annotation>
+ <appInfo>
+ <meta.schema plugin="org.eclipse.osee.framework.jdk.core" id="DefaultMailServer" name="Default Mail Server"/>
+ </appInfo>
+ <documentation>
+ [Enter description of this extension point.]
+ </documentation>
+ </annotation>
+
+ <element name="extension">
+ <complexType>
+ <sequence>
+ <element ref="mailServer"/>
+ </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="mailServer">
+ <complexType>
+ <attribute name="serverAddress" type="string" use="required">
+ <annotation>
+ <documentation>
+
+ </documentation>
+ </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.jdk.core/src/org/eclipse/osee/framework/jdk/core/collection/tree/Tree.java b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/collection/tree/Tree.java new file mode 100644 index 00000000000..ee888853689 --- /dev/null +++ b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/collection/tree/Tree.java @@ -0,0 +1,29 @@ +/******************************************************************************* + * Copyright (c) 2004, 2007 Boeing. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Boeing - initial API and implementation + *******************************************************************************/ +package org.eclipse.osee.framework.jdk.core.collection.tree; + +public class Tree<treeType> { + + private TreeNode<treeType> root; + + public Tree() { + this.root = new TreeNode<treeType>(); + } + + public Tree(treeType self) { + this.root = new TreeNode<treeType>(self); + } + + public TreeNode<treeType> getRoot() { + return root; + } + +} diff --git a/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/collection/tree/TreeNode.java b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/collection/tree/TreeNode.java new file mode 100644 index 00000000000..087ceead472 --- /dev/null +++ b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/collection/tree/TreeNode.java @@ -0,0 +1,60 @@ +/******************************************************************************* + * Copyright (c) 2004, 2007 Boeing. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Boeing - initial API and implementation + *******************************************************************************/ +package org.eclipse.osee.framework.jdk.core.collection.tree; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; + +public class TreeNode<treeType> { + + private treeType myself; + private TreeNode<treeType> parent; + private List<TreeNode<treeType>> children; + + protected TreeNode(TreeNode<treeType> parent, treeType myself) { + this.parent = parent; + this.myself = myself; + this.children = new ArrayList<TreeNode<treeType>>(); + } + + public TreeNode(treeType myself) { + this(null, myself); + } + + public TreeNode() { + this(null); + } + + public TreeNode<treeType> getParent() { + return parent; + } + + public treeType getSelf() { + return myself; + } + + public List<TreeNode<treeType>> getChildren() { + return children; + } + + public TreeNode<treeType> addChild(treeType child) { + TreeNode<treeType> newchild = new TreeNode<treeType>(this, child); + this.children.add(newchild); + return newchild; + } + + public void addChildren(Collection<treeType> children) { + for (treeType child : children) { + this.addChild(child); + } + } +} diff --git a/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/db/DbConfigFileInformation.java b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/db/DbConfigFileInformation.java new file mode 100644 index 00000000000..93cfa940eb9 --- /dev/null +++ b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/db/DbConfigFileInformation.java @@ -0,0 +1,33 @@ +/******************************************************************************* + * Copyright (c) 2004, 2007 Boeing. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Boeing - initial API and implementation + *******************************************************************************/ +package org.eclipse.osee.framework.jdk.core.db; + +/** + * @author Roberto E. Escobar + */ +public class DbConfigFileInformation { + + public static String getSchemaFileExtension() { + return ".SCHEMA.xml"; + } + + public static String getDbDataFileExtension() { + return ".DATA.xml"; + } + + public static String getSkyNetFileExtension() { + return ".xml"; + } + + public static String getCSVFileExtension() { + return ".csv"; + } +} diff --git a/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/directory/DirectoryPerson.java b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/directory/DirectoryPerson.java new file mode 100644 index 00000000000..9224873eb64 --- /dev/null +++ b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/directory/DirectoryPerson.java @@ -0,0 +1,413 @@ +/******************************************************************************* + * 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.jdk.core.directory; + +import java.io.Serializable; +import java.util.ArrayList; + +/** + * @author Jeff C. Phillips + */ +public class DirectoryPerson implements Comparable<Object>, Serializable { + + /** + * + */ + private static final long serialVersionUID = -2333305323300083640L; + private ArrayList<Integer> policies = null; + private int bemsid; + private int bluesId; + private String building; + private String city; + private String country; + private String department; + private String departmentName; + private String email; + private String externalCompany; + private String fullName; + private String hRDeptDesc; + private String hRDeptNumber; + private String mailCode; + private String mailStop; + private String manager; + private String personType; + private String phone; + private String searchName; + private String sponsor; + private String state; + private String title; + private String uSPersonStatus; + private boolean hasPolicy = false; + + public DirectoryPerson() { + policies = new ArrayList<Integer>(); + bemsid = -1; + bluesId = -1; + building = ""; + city = ""; + country = ""; + department = ""; + departmentName = ""; + email = ""; + externalCompany = ""; + fullName = ""; + hRDeptDesc = ""; + hRDeptNumber = ""; + mailCode = ""; + mailStop = ""; + manager = ""; + personType = ""; + phone = ""; + searchName = ""; + sponsor = ""; + state = ""; + title = ""; + uSPersonStatus = ""; + } + + /** + * @return Returns the fullName. + */ + public String getFullName() { + return fullName; + } + + /** + * @param fullName The fullName to set. + */ + public void setFullName(String fullName) { + this.fullName = fullName; + } + + /** + * @return Returns the bems. + */ + public int getBemsid() { + return bemsid; + } + + /** + * @param bems The bems to set. + */ + public void setBemsid(int bems) { + this.bemsid = bems; + } + + /** + * @return Returns the bluesId. + */ + public int getBluesId() { + return bluesId; + } + + /** + * @param bluesId The bluesId to set. + */ + public void setBluesId(int bluesId) { + this.bluesId = bluesId; + } + + /** + * @return Returns the building. + */ + public String getBuilding() { + return building; + } + + /** + * @param building The building to set. + */ + public void setBuilding(String building) { + this.building = building; + } + + /** + * @return Returns the city. + */ + public String getCity() { + return city; + } + + /** + * @param city The city to set. + */ + public void setCity(String city) { + this.city = city; + } + + /** + * @return Returns the country. + */ + public String getCountry() { + return country; + } + + /** + * @param country The country to set. + */ + public void setCountry(String country) { + this.country = country; + } + + /** + * @return Returns the department. + */ + public String getDepartment() { + return department; + } + + /** + * @param department The department to set. + */ + public void setDepartment(String department) { + this.department = department; + } + + /** + * @return Returns the departmentName. + */ + public String getDepartmentName() { + return departmentName; + } + + /** + * @param departmentName The departmentName to set. + */ + public void setDepartmentName(String departmentName) { + this.departmentName = departmentName; + } + + /** + * @return Returns the email. + */ + public String getEmail() { + return email; + } + + /** + * @param email The email to set. + */ + public void setEmail(String email) { + this.email = email; + } + + /** + * @return Returns the externalCompany. + */ + public String getExternalCompany() { + return externalCompany; + } + + /** + * @param externalCompany The externalCompany to set. + */ + public void setExternalCompany(String externalCompany) { + this.externalCompany = externalCompany; + } + + /** + * @return Returns the hRDeptDesc. + */ + public String getHRDeptDesc() { + return hRDeptDesc; + } + + /** + * @param deptDesc The hRDeptDesc to set. + */ + public void setHRDeptDesc(String deptDesc) { + hRDeptDesc = deptDesc; + } + + /** + * @return Returns the hRDeptNumber. + */ + public String getHRDeptNumber() { + return hRDeptNumber; + } + + /** + * @param deptNumber The hRDeptNumber to set. + */ + public void setHRDeptNumber(String deptNumber) { + hRDeptNumber = deptNumber; + } + + /** + * @return Returns the mailCode. + */ + public String getMailCode() { + return mailCode; + } + + /** + * @param mailCode The mailCode to set. + */ + public void setMailCode(String mailCode) { + this.mailCode = mailCode; + } + + /** + * @return Returns the mailStop. + */ + public String getMailStop() { + return mailStop; + } + + /** + * @param mailStop The mailStop to set. + */ + public void setMailStop(String mailStop) { + this.mailStop = mailStop; + } + + /** + * @return Returns the manager. + */ + public String getManager() { + return manager; + } + + /** + * @param manager The manager to set. + */ + public void setManager(String manager) { + this.manager = manager; + } + + /** + * @return Returns the personType. + */ + public String getPersonType() { + return personType; + } + + /** + * @param personType The personType to set. + */ + public void setPersonType(String personType) { + this.personType = personType; + } + + /** + * @return Returns the phone. + */ + public String getPhone() { + return phone; + } + + /** + * @param phone The phone to set. + */ + public void setPhone(String phone) { + this.phone = phone; + } + + /** + * @return Returns the searchName. + */ + public String getSearchName() { + return searchName; + } + + /** + * @param searchName The searchName to set. + */ + public void setSearchName(String searchName) { + this.searchName = searchName; + } + + /** + * @return Returns the sponsor. + */ + public String getSponsor() { + return sponsor; + } + + /** + * @param sponsor The sponsor to set. + */ + public void setSponsor(String sponsor) { + this.sponsor = sponsor; + } + + /** + * @return Returns the state. + */ + public String getState() { + return state; + } + + /** + * @param state The state to set. + */ + public void setState(String state) { + this.state = state; + } + + /** + * @return Returns the title. + */ + public String getTitle() { + return title; + } + + /** + * @param title The title to set. + */ + public void setTitle(String title) { + this.title = title; + } + + /** + * @return Returns the uSPersonStatus. + */ + public String getUSPersonStatus() { + return uSPersonStatus; + } + + /** + * @param personStatus The uSPersonStatus to set. + */ + public void setUSPersonStatus(String personStatus) { + uSPersonStatus = personStatus; + } + + public int compareTo(Object person) { + return fullName.compareTo(((DirectoryPerson) person).fullName); + } + + /** + * @return Returns the policies. + */ + public ArrayList<Integer> getPolicies() { + return policies; + } + + /** + * @param policies The policies to set. + */ + public void setPolicies(ArrayList<Integer> policies) { + this.policies = policies; + } + + public boolean isHasPolicy() { + return hasPolicy; + } + + public void setHasPolicy(boolean hasPolicy) { + this.hasPolicy = hasPolicy; + } + + public String toString() { + return fullName + " : " + this.bemsid + " : " + email; + } +} diff --git a/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/persistence/TwoWayXmlizable.java b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/persistence/TwoWayXmlizable.java new file mode 100644 index 00000000000..698c50eb602 --- /dev/null +++ b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/persistence/TwoWayXmlizable.java @@ -0,0 +1,19 @@ +/******************************************************************************* + * 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.jdk.core.persistence; + +import org.w3c.dom.Element; + +public interface TwoWayXmlizable extends Xmlizable { + public abstract void initializeFromXml(Element root); + + public abstract boolean isInitialized(); +} diff --git a/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/persistence/Unique.java b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/persistence/Unique.java new file mode 100644 index 00000000000..de8a9d3b06b --- /dev/null +++ b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/persistence/Unique.java @@ -0,0 +1,22 @@ +/******************************************************************************* + * Copyright (c) 2004, 2007 Boeing. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Boeing - initial API and implementation + *******************************************************************************/ +package org.eclipse.osee.framework.jdk.core.persistence; + +/** + * @author Ryan D. Brooks + */ +public interface Unique { + public String getGuid(); + + public String getDescriptiveName(); + + public void setDescriptiveName(String humanId); +} diff --git a/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/persistence/Xmlizable.java b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/persistence/Xmlizable.java new file mode 100644 index 00000000000..83f89ff51d4 --- /dev/null +++ b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/persistence/Xmlizable.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.jdk.core.persistence; + +import org.w3c.dom.Document; +import org.w3c.dom.Element; + +/** + * @author Ryan D. Brooks + */ +public interface Xmlizable { + public Element toXml(Document doc); +} diff --git a/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/reportdata/ReportData.java b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/reportdata/ReportData.java new file mode 100644 index 00000000000..4bc2c64eb13 --- /dev/null +++ b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/reportdata/ReportData.java @@ -0,0 +1,74 @@ +/******************************************************************************* + * 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.jdk.core.reportdata; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.List; +import org.eclipse.osee.framework.jdk.core.util.GUID; + +public class ReportData implements Serializable { + + /** + * + */ + private static final long serialVersionUID = 6645261625619889708L; + + private List<String> headers; + private List<ReportDataItem> items; + + /** + * Creates the ReportData class with the given headers. The number of headers should match the values passed into + * <code>addItem</code>. + * + * @param headers The headers for the data to be added. + */ + public ReportData(List<String> headers) { + this.headers = headers; + items = new ArrayList<ReportDataItem>(); + } + + /** + * Adds an item to the ReportData + * + * @param guid The GUID corresponding to the item added + * @param values The values (such as username, script name) associated with the item. These should match the headers. + */ + public void addItem(GUID guid, ArrayList<String> values) { + ReportDataItem item = new ReportDataItem(guid, values); + items.add(item); + } + + public void clearItems() { + items.clear(); + } + + /** + * @param headers The headers to set. + */ + public void setHeaders(List<String> headers) { + this.headers = headers; + } + + /** + * @return Returns the headers. + */ + public List<String> getHeaders() { + return headers; + } + + /** + * @return Returns the items. + */ + public List<ReportDataItem> getItems() { + return items; + } +} diff --git a/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/reportdata/ReportDataItem.java b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/reportdata/ReportDataItem.java new file mode 100644 index 00000000000..5ac525c7f08 --- /dev/null +++ b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/reportdata/ReportDataItem.java @@ -0,0 +1,42 @@ +/******************************************************************************* + * Copyright (c) 2004, 2007 Boeing. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Boeing - initial API and implementation + *******************************************************************************/ +package org.eclipse.osee.framework.jdk.core.reportdata; + +import java.io.Serializable; +import java.util.ArrayList; +import org.eclipse.osee.framework.jdk.core.util.GUID; + +public class ReportDataItem implements Serializable { + + private static final long serialVersionUID = 7072248922173369711L; + + private GUID guid; + private ArrayList<String> cells; + + public ReportDataItem(GUID guid, ArrayList<String> items) { + this.guid = guid; + this.cells = items; + } + + /** + * @return Returns the guid. + */ + public GUID getGuid() { + return guid; + } + + /** + * @return Returns the cells. + */ + public ArrayList<String> getCells() { + return cells; + } +} diff --git a/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/reportdata/ReportDataListener.java b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/reportdata/ReportDataListener.java new file mode 100644 index 00000000000..a998d631fab --- /dev/null +++ b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/reportdata/ReportDataListener.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.jdk.core.reportdata; + +import java.rmi.Remote; +import java.rmi.RemoteException; + +public interface ReportDataListener extends Remote { + public void updateData(ReportData data) throws RemoteException; +} diff --git a/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/stateMachine/IState.java b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/stateMachine/IState.java new file mode 100644 index 00000000000..ac8bb165bfa --- /dev/null +++ b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/stateMachine/IState.java @@ -0,0 +1,24 @@ +/******************************************************************************* + * 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.jdk.core.stateMachine; + +/** + * A single state in a contructed state machine. All implementers should calculate and control what the next state in + * the machine should be. + */ +public interface IState { + /** + * Called by the state machine controller to start this particular state. + * + * @return The next state the controller should run or null if the machine should terminate + */ + public IState run(); +} diff --git a/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/stateMachine/StateController.java b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/stateMachine/StateController.java new file mode 100644 index 00000000000..f455b0306b7 --- /dev/null +++ b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/stateMachine/StateController.java @@ -0,0 +1,45 @@ +/******************************************************************************* + * Copyright (c) 2004, 2007 Boeing. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Boeing - initial API and implementation + *******************************************************************************/ +package org.eclipse.osee.framework.jdk.core.stateMachine; + +/** + * Runs each state of the stateMachine defined. Each state will calculate and know which state to go to next so this is + * really a dumb controller, calling the run method of whatever state the current state returned from being run. + */ +public class StateController { + private IState nextState; + private boolean isRunning; + + public StateController(IState initialState) { + isRunning = true; + nextState = initialState; + } + + /** + * Calls the run method of the next state. + */ + public void runNextState() { + if (isRunning) nextState = nextState.run(); + if (nextState == null) isRunning = false; + } + + public boolean isRunning() { + return isRunning; + } + + /** + * causes machine to terminate on next ivocation of the controller's run method. + */ + public void turnMachineOff() { + isRunning = false; + } + +} diff --git a/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/stateMachine/WaitState.java b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/stateMachine/WaitState.java new file mode 100644 index 00000000000..b586792c21b --- /dev/null +++ b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/stateMachine/WaitState.java @@ -0,0 +1,41 @@ +/******************************************************************************* + * Copyright (c) 2004, 2007 Boeing. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Boeing - initial API and implementation + *******************************************************************************/ +package org.eclipse.osee.framework.jdk.core.stateMachine; + +/** + * allows a state machine to wait for a certain number of cycles before continuing. Notice that if a state needs to wait + * only one cycle, a wait state should not be used as it would really be two cycles ( one to run the wait state then one + * to start the next state). Instead that state could simply return an instance of the next state to run as normal. + */ +public class WaitState implements IState { + + int iterationsToWait; + IState nextRealStateToRun; + + /** + * @param iterationsToWait The number of times this state will be run + * @param nextRealStateToRun The next state to run after waiting + */ + public WaitState(int iterationsToWait, IState nextRealStateToRun) { + this.iterationsToWait = iterationsToWait; + this.nextRealStateToRun = nextRealStateToRun; + } + + public IState run() { + iterationsToWait--; + if (iterationsToWait <= 0) + return nextRealStateToRun; + else + return this; + + } + +} diff --git a/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/text/CsdmParams.java b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/text/CsdmParams.java new file mode 100644 index 00000000000..3f18b02abc9 --- /dev/null +++ b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/text/CsdmParams.java @@ -0,0 +1,79 @@ +/******************************************************************************* + * 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.jdk.core.text; + +import java.io.BufferedReader; +import java.io.BufferedWriter; +import java.io.FileWriter; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.StringTokenizer; +import org.eclipse.osee.framework.jdk.core.util.Lib; + +/** + * @author Ryan D. Brooks + */ +public class CsdmParams { + protected BufferedReader in; + protected BufferedWriter out; + + public CsdmParams() { + try { + in = new BufferedReader(new InputStreamReader(System.in)); + out = new BufferedWriter(new FileWriter("csdm_params.csv")); + } catch (IOException ex) { + System.out.println(ex); + } + } + + protected void finalize() throws IOException { + out.close(); + in.close(); + } + + public static void main(String args[]) throws IOException { + CsdmParams gen = new CsdmParams(); + gen.genThreats(); + gen.finalize(); + } + + public void genThreats() throws IOException { + for (int i = 0; i < 32; i++) { + String numStr = Lib.padLeading(String.valueOf(i), '0', 2); + out.write("THRT_LAT_" + numStr + ",IEEE64,19346,\n"); + out.write("THRT_LAT_Z_" + numStr + ",IEEE64,19347,\n"); + out.write("THRT_LONG_" + numStr + ",IEEE64,19346,\n"); + out.write("THRT_LONG_Z_" + numStr + ",IEEE64,19347,\n"); + out.write("THRT_DETECT_" + numStr + ",IEEE64,19346,\n"); + out.write("THRT_DETECT_Z_" + numStr + ",IEEE64,19347,\n"); + out.write("THRT_LETHAL_" + numStr + ",IEEE64,19346,\n"); + out.write("THRT_LETHAL_Z_" + numStr + ",IEEE64,19347,\n"); + out.write("THRT_HEIGHT_ABOVE_" + numStr + ",ANALOG,19154,-2_147_483_648 to 2_147_483_647\n"); + out.write("THRT_COUNT_" + numStr + ",ANALOG,5461,0 to 255\n"); + out.write("THRT_STAT_OK_" + numStr + ",ENUM,162,\"0=FALSE, 1=TRUE\"\n"); + out.write("SPARE,SPARE,0,\n"); + } + } + + public void parseAda() throws IOException { + String line = null; + while ((line = in.readLine()) != null) { + StringTokenizer strTok = new StringTokenizer(line, " ."); + if (strTok.countTokens() == 4) { + String adaName = strTok.nextToken(); + out.write(adaName + ", "); + out.write(strTok.nextToken() + ", "); + out.write(strTok.nextToken() + ", "); + out.write(strTok.nextToken() + "\n"); + } + } + } +} diff --git a/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/text/ExtractComments.java b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/text/ExtractComments.java new file mode 100644 index 00000000000..de9f0a9dbed --- /dev/null +++ b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/text/ExtractComments.java @@ -0,0 +1,131 @@ +/******************************************************************************* + * 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.jdk.core.text; + +import java.io.BufferedReader; +import java.io.FileNotFoundException; +import java.io.FileReader; +import java.io.FileWriter; +import java.io.IOException; +import java.util.ArrayList; + +/** + * @author Ryan D. Brooks + */ +public class ExtractComments { + protected BufferedReader in; + protected String line; + protected ArrayList<String> comments; + protected int count; + + public ExtractComments() { + in = null; + line = null; + comments = new ArrayList<String>(); + } + + public Object[] extract(String sourceFile) { + try { + in = new BufferedReader(new FileReader(sourceFile)); + } catch (FileNotFoundException ex) { + System.err.println(ex); + throw new IllegalArgumentException(ex.toString()); + } + + try { + while ((line = in.readLine()) != null) { + handleComments(); + } + } catch (IOException ex) { + System.err.println(ex); + System.exit(2); + } + return comments.toArray(); + } + + protected void handleComments() { + try { + while (line != null) { + String tLine = line.trim(); + if (tLine.startsWith("/*")) { + comments.add(++count + line); + while (tLine != null && !tLine.endsWith("*/")) { + tLine = in.readLine().trim(); + comments.add(++count + line); + } + } else if (!tLine.startsWith("//")) { + //a logical LOC might have a comment folloing it on the same line + line = stripOffComment(tLine); + return; + } + comments.add(++count + line); + line = in.readLine(); + } + } catch (IOException ex) { + System.err.println(ex); + return; + } + } + + public String stripOffComment(String line) { + int pos = line.lastIndexOf("//"); + if (pos != -1) { //if a comment is indeed there (maybe) + //the single line comment symbol might be part of a string literal + //this is hard because the string delimiter might also be part of a string literal + if (!insideStringLiteral(line, pos)) { + comments.add(++count + this.line); + return line.substring(0, pos).trim(); + } + } + count++; + return line; + } + + public boolean insideStringLiteral(String str, int pos) { + int index = 0; + boolean inside = false; + + char[] chars = new char[str.length()]; + str.getChars(0, chars.length, chars, 0); + + while (index < pos) { + if (chars[index] == '\\' && chars[index + 1] == '\"') { + index++; // skip over literal quotation marks + } else if (chars[index] == '\"') { + inside = !inside; + } + index++; + } + return inside; + } + + public static void main(String[] args) { + if (args.length < 1) { + System.out.println("Usage: ExtractComments [source file]"); + return; + } + ExtractComments app = new ExtractComments(); + Object[] text = app.extract(args[0]); + + try { + FileWriter out = new FileWriter("comments.txt"); + for (int i = 0; i < text.length; i++) { + String str = (String) text[i]; + out.write(str, 0, str.length()); + out.write('\n'); + } + out.close(); + } catch (IOException ex) { + System.err.println(ex); + return; + } + } +} diff --git a/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/text/ExtractText.java b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/text/ExtractText.java new file mode 100644 index 00000000000..cb789e6b39b --- /dev/null +++ b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/text/ExtractText.java @@ -0,0 +1,97 @@ +/******************************************************************************* + * 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.jdk.core.text; + +import java.io.BufferedReader; +import java.io.FileReader; +import java.io.FileWriter; +import java.io.IOException; + +/** + * @author Ryan D. Brooks + */ +public class ExtractText { + protected String line; + protected int lineNum; + protected BufferedReader in; + protected FileWriter out; + + public ExtractText(String sourceFile) { + try { + in = new BufferedReader(new FileReader(sourceFile)); + out = new FileWriter("sourceText.txt"); + line = null; + lineNum = 0; + + while ((line = in.readLine()) != null) { + int pos = line.indexOf("/*"); + if (pos != -1) { // beginning of block comment unless in a string literal + if (!insideStringLiteral(line, pos)) { + //find whole block and write to file + pos = line.indexOf("*/"); + while (line != null && pos == -1) { + writeText(); + line = in.readLine(); + pos = line.indexOf("*/"); + } + writeText(); + } else { // line contains a string + writeText(); + } + } else if (line.indexOf("//") != -1) { // line contains a single line comment or string literal + writeText(); + } else if ((pos = line.indexOf("\"")) != -1 && line.charAt(pos + 1) != '\'') { // line contains a string literal + writeText(); + } + // line does not contain text + lineNum++; + } + in.close(); + out.close(); + } catch (IOException ex) { + System.err.println(ex); + return; + } + } + + protected void writeText() throws IOException { + String str = String.valueOf(++lineNum); + out.write(str, 0, str.length()); + out.write(line, 0, line.length()); + out.write('\n'); + } + + public static boolean insideStringLiteral(String str, int pos) { + int index = 0; + boolean inside = false; + + char[] chars = new char[str.length()]; + str.getChars(0, chars.length, chars, 0); + + while (index < pos) { + if (chars[index] == '\\' && chars[index + 1] == '\"') { + index++; // skip over literal quotation marks + } else if (chars[index] == '\"') { + inside = !inside; + } + index++; + } + return inside; + } + + public static void main(String[] args) { + if (args.length < 1) { + System.out.println("Usage: ExtractText [source file]"); + return; + } + new ExtractText(args[0]); + } +} diff --git a/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/text/FileToBufferConvert.java b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/text/FileToBufferConvert.java new file mode 100644 index 00000000000..2d4e94cd6a9 --- /dev/null +++ b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/text/FileToBufferConvert.java @@ -0,0 +1,22 @@ +/******************************************************************************* + * Copyright (c) 2004, 2007 Boeing. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Boeing - initial API and implementation + *******************************************************************************/ +package org.eclipse.osee.framework.jdk.core.text; + +import java.io.File; +import java.io.IOException; +import java.text.ParseException; + +/** + * @author Ryan D. Brooks + */ +public interface FileToBufferConvert { + public CharSequence fileToCharSequence(File file) throws IOException, ParseException; +}
\ No newline at end of file diff --git a/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/text/FindResults.java b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/text/FindResults.java new file mode 100644 index 00000000000..12a468b175b --- /dev/null +++ b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/text/FindResults.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.jdk.core.text; + +import java.io.File; +import java.io.IOException; +import java.io.Writer; +import java.util.HashMap; +import java.util.Iterator; +import java.util.LinkedHashSet; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.Map.Entry; + +/** + * @author Ryan D. Brooks + */ +public class FindResults { + private HashMap<String, HashMap<File, List<String>>> results; + + public FindResults(int initialCapacity) { + results = new HashMap<String, HashMap<File, List<String>>>(initialCapacity * 4 / 3); + } + + public void addMatch(String pattern, File file, String region) { + HashMap<File, List<String>> fileMatches = results.get(pattern); + + if (fileMatches == null) { + fileMatches = new HashMap<File, List<String>>(); + results.put(pattern, fileMatches); + } + + List<String> regions = fileMatches.get(file); + if (regions == null) { + regions = new LinkedList<String>(); + fileMatches.put(file, regions); + } + regions.add(region); + } + + public void writeFindResutls(Writer out) throws IOException { + for (FindResults.FindResultsIterator i = iterator(); i.hasNext();) { + // write out the file name, pattern, and region surrounding match + out.write(i.currentPattern); + out.write('@'); + out.write(i.currentFile.getName()); + out.write('@'); + if (i.currentRegion != null) { + out.write(i.currentRegion); + } + out.write("\n"); + } + } + + public FindResultsIterator iterator() { + return new FindResultsIterator(); + } + + /** + * @author Ryan D. Brooks + */ + public class FindResultsIterator { + private Iterator<Entry<String, HashMap<File, List<String>>>> patternIterator; + private Iterator<Entry<File, List<String>>> fileIterator; + private Iterator<String> listIterator; + private boolean more; + public String currentPattern; + public File currentFile; + public String currentRegion; + + private FindResultsIterator() { + reset(); + } + + public void reset() { + this.more = true; + this.patternIterator = results.entrySet().iterator(); + this.listIterator = null; + this.fileIterator = null; + } + + // assumption every the list and file itorator's will have at least one item + private void primePump() { + if (listIterator == null || !listIterator.hasNext()) { + if (fileIterator == null || !fileIterator.hasNext()) { + if (!patternIterator.hasNext()) { + more = false; + return; + } + Map.Entry<String, HashMap<File, List<String>>> entry = patternIterator.next(); + currentPattern = entry.getKey(); + HashMap<File, List<String>> fileMatches = entry.getValue(); + fileIterator = fileMatches.entrySet().iterator(); + } + Map.Entry<File, List<String>> entry = fileIterator.next(); + currentFile = entry.getKey(); + List<String> list = entry.getValue(); + listIterator = list.iterator(); + } + currentRegion = listIterator.next(); + } + + public boolean hasNext() { + primePump(); + return more; + } + } + + /** + * Returns a simple set of all files that had matches (or anti-matches) + */ + public Set<File> getFileSet() { + Set<File> files = new LinkedHashSet<File>(1000); + for (Iterator<Entry<String, HashMap<File, List<String>>>> i = results.entrySet().iterator(); i.hasNext();) { + Map.Entry<String, HashMap<File, List<String>>> entry = i.next(); + HashMap<File, List<String>> fileMatches = entry.getValue(); + files.addAll(fileMatches.keySet()); + } + return files; + } + + public HashMap<String, List<File>> getRegionToFileMapping() { + HashMap<String, List<File>> mapping = new HashMap<String, List<File>>(1000); + for (FindResultsIterator i = iterator(); i.hasNext();) { + List<File> files = mapping.get(i.currentRegion); + if (files == null) { + files = new LinkedList<File>(); + mapping.put(i.currentRegion, files); + } + files.add(i.currentFile); + } + return mapping; + } + + public IteratorPerPattern getIteratorForPattern(String pattern) { + return new IteratorPerPattern(pattern); + } + + /** + * @author Ryan D. Brooks + */ + public class IteratorPerPattern { + private String pattern; + private Iterator<Entry<File, List<String>>> fileIterator; + private Iterator<String> listIterator; + private boolean more; + public File currentFile; + public String currentRegion; + + private IteratorPerPattern(String pattern) { + this.pattern = pattern; + reset(); + } + + public void reset() { + HashMap<File, List<String>> fileMatches = results.get(pattern); + this.fileIterator = fileMatches.entrySet().iterator(); + this.listIterator = null; + this.more = true; + } + + // assumption every the list and file itorator's will have at least one item + private void primePump() { + if (listIterator == null || !listIterator.hasNext()) { + if (!fileIterator.hasNext()) { + more = false; + return; + } + Map.Entry<File, List<String>> entry = fileIterator.next(); + currentFile = entry.getKey(); + List<String> list = entry.getValue(); + listIterator = list.iterator(); + } + currentRegion = listIterator.next(); + } + + public boolean hasNext() { + primePump(); + return more; + } + } +}
\ No newline at end of file diff --git a/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/text/Range.java b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/text/Range.java new file mode 100644 index 00000000000..370ebeba21b --- /dev/null +++ b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/text/Range.java @@ -0,0 +1,26 @@ +/******************************************************************************* + * 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.jdk.core.text; + +/** + * @author Ryan D. Brooks + */ +public class Range { + public int start; + public int end; + public int length; + + public Range(int start, int end) { + this.start = start; + this.end = end; + this.length = end - start; + } +}
\ No newline at end of file diff --git a/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/text/Rule.java b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/text/Rule.java new file mode 100644 index 00000000000..bc43d2b3e7c --- /dev/null +++ b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/text/Rule.java @@ -0,0 +1,194 @@ +/******************************************************************************* + * 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.jdk.core.text; + +import java.io.File; +import java.io.IOException; +import java.net.URL; +import java.net.URLClassLoader; +import java.util.Collection; +import java.util.List; +import java.util.logging.Level; +import java.util.logging.Logger; +import java.util.regex.Pattern; +import javax.xml.parsers.ParserConfigurationException; +import org.eclipse.osee.framework.jdk.core.text.change.ChangeSet; +import org.eclipse.osee.framework.jdk.core.util.Lib; + +/** + * @author Ryan D. Brooks + */ +public abstract class Rule { + private String outExtension; + private String currentOutfileName; + private File inputFile; + private String subdirectoryName; + private Pattern fileNamePattern; + protected boolean ruleWasApplicable; + protected Logger logger; + + public Rule() { + this("done"); + } + + public Rule(String outExtension) { + this.outExtension = outExtension; + this.ruleWasApplicable = false; + logger = Logger.getLogger(this.getClass().getName()); + logger.setLevel(Level.ALL); + this.subdirectoryName = null; + } + + public abstract ChangeSet computeChanges(CharSequence seq); + + public void process(Collection<File> list) { + for (File file : list) { + try { + process(file); + } catch (Exception ex) { + System.out.println(currentOutfileName + ": " + ex.getMessage()); + } + } + } + + public void process(File file) throws IOException { + if (file.isDirectory()) { + List<File> files = Lib.recursivelyListFiles(file, fileNamePattern); + for (File aFile : files) { + try { + process(aFile); + } catch (Exception ex) { + System.out.println(currentOutfileName + ": " + ex.getMessage()); + } + } + } else { + inputFile = file; + process(file, getResultFile(file)); + } + } + + public void process(File inFile, File outFile) throws IOException { + File subdirectory; + if (subdirectoryName != null) { + File parent = outFile.getParentFile(); + subdirectory = new File(parent, subdirectoryName); + subdirectory.mkdir(); + outFile = new File(subdirectory, outFile.getName()); + } + + this.currentOutfileName = outFile.getName(); + if (inFile.exists()) { + RulesLogHandler handler = null; + ChangeSet changeSet = null; + try { + handler = new RulesLogHandler(new File(Lib.changeExtension(outFile.getPath(), "xml"))); + logger.addHandler(handler); + ruleWasApplicable = false; + changeSet = computeChanges(Lib.fileToCharBuffer(inFile)); + } catch (ParserConfigurationException ex) { + logger.log(Level.SEVERE, ex.toString(), ex); + } finally { + if (handler != null) { + handler.close(); + logger.removeHandler(handler); + } + } + if (ruleWasApplicable) { + if (subdirectoryName == null) { + System.out.println("Rule was applied to " + currentOutfileName); + } else + System.out.println("Rule was applied to " + subdirectoryName + currentOutfileName); + + if (changeSet != null) changeSet.applyChanges(outFile); + } + // else { + // System.out.println("Not applicable to " + currentFileName); + // } + + } else { + System.out.println("The file " + inFile + " does not exist!"); + } + } + + protected File getResultFile(File file) { + + if (outExtension == null) { + return file; + } + + return new File(Lib.stripExtension(file.getPath()) + "." + outExtension); + } + + public static void main(String[] args) throws Exception { + if (args.length < 3) { + System.out.println("Usage: " + Rule.class.getName() + " <ruleClassPath> <ruleClass> <file list>"); + return; + } + + String ruleName = args[1]; + String classPath = args[0]; + try { + URLClassLoader classLoader = new URLClassLoader(new URL[] {Lib.getUrlFromString(classPath)}); + System.out.println("class path: " + classLoader.getURLs()[0]); + Object obj = classLoader.loadClass(ruleName).newInstance(); + + if (obj instanceof org.eclipse.osee.framework.jdk.core.text.Rule) { + Rule rule = (Rule) obj; + for (int i = 2; i < args.length; i++) { + try { + rule.process(new File(args[i])); + } catch (Exception ex) { + System.out.println("Exception in Rule!!! " + rule.currentOutfileName + ": " + ex.getMessage()); + ex.printStackTrace(); + } + } + } else { + throw new IllegalArgumentException(ruleName + " is not of type text.Rule."); + } + } catch (InstantiationException ex) { + System.out.println(ex); + } catch (IllegalAccessException ex) { + System.out.println(ex); + } catch (ClassNotFoundException ex) { + System.out.println(ex); + } + } + + public boolean ruleWasApplicable() { + return ruleWasApplicable; + } + + /** + * @return Returns the currentFileName. + */ + public String getCurrentOutfileName() { + return currentOutfileName; + } + + /** + * @param ruleWasApplicable The ruleWasApplicable to set. + */ + public void setRuleWasApplicable(boolean ruleWasApplicable) { + this.ruleWasApplicable = ruleWasApplicable; + } + + public File getInputFile() { + return inputFile; + } + + public void setSubdirectoryNameToPlaceResultFilesIn(String subdirectoryName) { + this.subdirectoryName = subdirectoryName; + } + + public void setFileNamePattern(Pattern fileNamePattern) { + this.fileNamePattern = fileNamePattern; + } +}
\ No newline at end of file diff --git a/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/text/RuleRecord.java b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/text/RuleRecord.java new file mode 100644 index 00000000000..e8b736dcf6f --- /dev/null +++ b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/text/RuleRecord.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.jdk.core.text; + +import java.util.logging.Level; +import java.util.logging.LogRecord; +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 Michael A. Winston + */ +public class RuleRecord extends LogRecord implements Xmlizable { + + private static final long serialVersionUID = 6974861818239720347L; + + /** + * RuleRecord Constructor. This is an abstract class so this constructor is called via the super() call from the + * extended class. This sets the source, the logging level, the log message and whether a timestamp should be + * included. + * + * @param level The logging level. + * @param msg The log message. + */ + public RuleRecord(Level level, String msg) { + super(level, msg); + } + + /** + * Converts log element to XML format. + * + * @return xml formated element. + */ + public Element toXml(Document doc) { + Element recordElement = Jaxp.createElement(doc, getLevel().getName(), getMessage()); + return recordElement; + } + +}
\ No newline at end of file diff --git a/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/text/RulesLogHandler.java b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/text/RulesLogHandler.java new file mode 100644 index 00000000000..fefecb6e140 --- /dev/null +++ b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/text/RulesLogHandler.java @@ -0,0 +1,104 @@ +/******************************************************************************* + * 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.jdk.core.text; + +import java.io.File; +import java.io.IOException; +import java.util.logging.Handler; +import java.util.logging.LogRecord; +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.transform.TransformerException; +import org.eclipse.osee.framework.jdk.core.util.xml.Jaxp; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import com.sun.org.apache.xml.internal.serialize.OutputFormat; + +/** + * @author Ryan D. Brooks + * @author Andrew M. Finkbeiner + */ +public class RulesLogHandler extends Handler { + + private Document document; + private File outFile; + private Element rootElement; + + /** + * RulesLogHandler Constructor. Sets the file to log to and the test script that will be logged. It also establishes + * the XML format to be used. + * + * @param outFile Reference to the file that will be used to output the log. + * @throws ParserConfigurationException + */ + public RulesLogHandler(File outFile) throws ParserConfigurationException { + super(); + this.outFile = outFile; + document = Jaxp.newDocument(); + rootElement = document.createElement("Rule"); + document.appendChild(rootElement); + } + + /** + * Write out the log records as XML. + */ + public void writeOutFile() { + // only write the XML file if there is something to write + if (rootElement.hasChildNodes()) { + try { + // create an XMLOutputter that indents using 3 spaces and uses new lines + OutputFormat format = new OutputFormat(document); + format.setIndenting(true); + format.setIndent(3); + Jaxp.writeXmlDocument(document, outFile, format); + } catch (IOException ex) { + ex.printStackTrace(); + } catch (TransformerException ex) { + ex.printStackTrace(); + } + } + } + + /* + * (non-Javadoc) + * + * @see java.util.logging.Handler#publish(java.util.logging.LogRecord) + */ + public void publish(LogRecord logRecord) { + if (!isLoggable(logRecord)) { + return; + } + + if (logRecord instanceof RuleRecord) { + RuleRecord record = (RuleRecord) logRecord; + rootElement.appendChild(record.toXml(document)); + } else { + rootElement.appendChild(Jaxp.createElement(document, logRecord.getLevel().getName(), logRecord.getMessage())); + } + } + + /* + * (non-Javadoc) + * + * @see java.util.logging.Handler#close() + */ + public void close() throws SecurityException { + writeOutFile(); + } + + /* + * (non-Javadoc) don't call this method + * + * @see java.util.logging.Handler#flush() + */ + public void flush() { + throw new UnsupportedOperationException(); + } +}
\ No newline at end of file diff --git a/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/text/change/ChOps.java b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/text/change/ChOps.java new file mode 100644 index 00000000000..3b622798e7f --- /dev/null +++ b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/text/change/ChOps.java @@ -0,0 +1,58 @@ +/******************************************************************************* + * 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.jdk.core.text.change; + +/** + * @author Ryan D. Brooks + */ +public class ChOps { + + /** + * take a string containing one or more "\n" and replace with a new line char then replace all "\\n" with "\n" + * + * @param src + * @param srcStartIndex + * @param srcEndIndex + * @return char[] + */ + public static char[] embedNewLines(char[] src, int srcStartIndex, int srcEndIndex) { + int stop = srcEndIndex - 1; //don't loop for the last char so we can use src[i+1] + int replaceCount = 0; + for (int i = srcStartIndex; i < stop; i++) { + if (src[i] == '\\') { + i++; + if (src[i] == '\\' || src[i] == 'n') { + replaceCount++; + } + } + } + + char[] result = new char[srcEndIndex - srcStartIndex - replaceCount]; + + int srcPos = srcStartIndex; + for (int i = 0; i < result.length; i++) { + if (src[srcPos] == '\\') { + if (src[srcPos + 1] == '\\') { + srcPos += 2; // skip over the two escaped chars + result[i] = '\\'; // and replace them here + } else if (src[srcPos + 1] == 'n') { + srcPos += 2; // skip over the two escaped chars + result[i] = '\n'; // and replace them here + } else { + result[i] = src[srcPos++]; + } + } else { + result[i] = src[srcPos++]; + } + } + return result; + } +} diff --git a/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/text/change/ChangeSet.java b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/text/change/ChangeSet.java new file mode 100644 index 00000000000..88ee801e250 --- /dev/null +++ b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/text/change/ChangeSet.java @@ -0,0 +1,237 @@ +/******************************************************************************* + * 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.jdk.core.text.change; + +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileWriter; +import java.io.IOException; +import java.io.Writer; +import java.nio.CharBuffer; + +/** + * @author Ryan D. Brooks + */ +public class ChangeSet { + private CharacterChanger firstChange; + private CharacterChanger lastChange; + private char[] sourceChars; + private CharSequence source; + + /** + * public ChangeSet(char[] sourceChars) { this.sourceChars = sourceChars; } + */ + + public ChangeSet(CharSequence source) { + if (source instanceof CharBuffer) { + CharBuffer charBuf = (CharBuffer) source; + if (charBuf.hasArray()) { + sourceChars = charBuf.array(); + return; + } + } + if (source instanceof String) { + sourceChars = ((String) source).toCharArray(); + } + this.source = source; + } + + private int copyFromSource(int srcStrartIndex, int srcEndIndex, char[] dest, int destPos) { + if (sourceChars != null) { + int length = srcEndIndex - srcStrartIndex; + System.arraycopy(sourceChars, srcStrartIndex, dest, destPos, length); + return destPos + length; + } else { + for (int i = srcStrartIndex; i < srcEndIndex; i++) { + dest[destPos++] = source.charAt(i); + } + return destPos; + } + } + + private void writeFromSource(int srcStrartIndex, int srcEndIndex, Writer writer) throws IOException { + if (sourceChars != null) { + writer.write(sourceChars, srcStrartIndex, srcEndIndex - srcStrartIndex); + } else { + for (int i = srcStrartIndex; i < srcEndIndex; i++) { + writer.write(source.charAt(i)); + } + } + } + + public int getSourceLength() { + if (sourceChars == null) { + return source.length(); + } + return sourceChars.length; + } + + public void applyChanges(char[] dest, int destPos) { + int lastEndIndex = 0; + + CharacterChanger change = firstChange; + while (change != null) { + destPos = copyFromSource(lastEndIndex, change.getStartIndex(), dest, destPos); + lastEndIndex = change.getEndIndex(); + destPos = change.applyChange(dest, destPos); + change = change.next(); + } + copyFromSource(lastEndIndex, getSourceLength(), dest, destPos); + } + + /** + * Make sure this writer is buffered if source is only a CharSequence + * + * @param writer + * @throws IOException + */ + public void applyChanges(Writer writer) throws IOException { + int lastEndIndex = 0; + + CharacterChanger change = firstChange; + while (change != null) { + writeFromSource(lastEndIndex, change.getStartIndex(), writer); + lastEndIndex = change.getEndIndex(); + change.applyChange(writer); + change = change.next(); + } + writeFromSource(lastEndIndex, getSourceLength(), writer); + } + + public void applyChanges(File outFile) throws IOException { + BufferedWriter writer = new BufferedWriter(new FileWriter(outFile)); + applyChanges(writer); + writer.close(); + } + + public void insertBefore(int index, char[] newChars, int offset, int length) { + addChanger(new CharArrayChange(index, index, newChars, offset, length)); + } + + public void insertBefore(int index, char[] newChars) { + addChanger(new CharArrayChange(index, index, newChars)); + } + + public void insertBefore(int index, char newChar) { + addChanger(new CharChange(index, index, newChar)); + } + + public void insertBefore(int index, String newChar) { + insertBefore(index, newChar.toCharArray()); + } + + public void replace(int srcStartIndex, int srcEndIndex, char[] newChars, int offset, int length) { + addChanger(new CharArrayChange(srcStartIndex, srcEndIndex, newChars, offset, length)); + } + + public void replace(int srcStartIndex, int srcEndIndex, char[] newChars) { + addChanger(new CharArrayChange(srcStartIndex, srcEndIndex, newChars)); + } + + public void replace(int srcStartIndex, int srcEndIndex, char newChar) { + addChanger(new CharChange(srcStartIndex, srcEndIndex, newChar)); + } + + public void replace(int srcStartIndex, int srcEndIndex, String newChar) { + replace(srcStartIndex, srcEndIndex, newChar.toCharArray()); + } + + public void delete(int srcStartIndex, int srcEndIndex) { + addChanger(new DeleteChange(srcStartIndex, srcEndIndex)); + } + + /** + * replaces may not overlap deletes my overlap, but they must be conbining into a single delete optional, conbine + * adjacent deletes adjacent inserts may be done at the same index if start is < last end and not a delete since all + * changes are placed in order and normalized as they are added the list of changes is always in order and normalized + */ + private void addChanger(CharacterChanger changer) { + if (firstChange == null) { // if the change set is currently empty + firstChange = changer; // no normalization needed since there is only one changer + lastChange = firstChange; + } else { + if (changer.getStartIndex() < lastChange.getStartIndex()) { // if change belongs somewhere before the end + + CharacterChanger current = firstChange; + CharacterChanger previous = null; + // search for insertion point + while (current.getStartIndex() <= changer.getStartIndex()) { + previous = current; + current = current.next(); // there should always be a next since we already checked that this changer does not belong on the end + } + addNormalized(previous, changer, current); + } else { // changer belongs on the end so skip search for insertion point + addNormalized(lastChange, changer, null); + } + } + } + + private void addNormalized(CharacterChanger previous, CharacterChanger changer, CharacterChanger next) { + // assumptions: if next is non-null, changer.srcEndIndex < next.srcStartIndex + // previous.srcEndIndex <= changer.srcEndIndex + // the current set of changes have no overlaps (i.e. is already normalized) + + // if these changes are adjacent deletes, just combine them + if (lastChange instanceof DeleteChange && next instanceof DeleteChange) { + //lastChange.setDeletionRange + } + + if (previous == null) { // if belongs at the head + firstChange = changer; + } else { // else insert in between + overlapping(previous.getEndIndex(), changer.getStartIndex()); + previous.setNext(changer); + } + if (next == null) { + lastChange = changer; + } else { + overlapping(changer.getEndIndex(), next.getStartIndex()); + changer.setNext(next); + } + } + + private void overlapping(int a, int b) { + if (a > b) { + throw new IllegalArgumentException( + "Overlapping changes are not currently allowed " + a + " > " + b + " " + new String(sourceChars, b - 4, + 20)); + } + } + + public int getLengthDelta() { + int lengthDelta = 0; + + CharacterChanger change = firstChange; + while (change != null) { + lengthDelta += change.getLengthDelta(); + change = change.next(); + } + return lengthDelta; + } + + public CharSequence applyChangesToSelf() { + this.sourceChars = toCharArray(); + this.source = CharBuffer.wrap(sourceChars); + this.firstChange = null; + this.lastChange = null; + return source; + } + + public char[] toCharArray() { + char[] chars = new char[getLengthDelta() + getSourceLength()]; + applyChanges(chars, 0); + return chars; + } + + public String toString() { + return new String(toCharArray()); + } +} diff --git a/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/text/change/CharArrayChange.java b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/text/change/CharArrayChange.java new file mode 100644 index 00000000000..89f5ffbb19a --- /dev/null +++ b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/text/change/CharArrayChange.java @@ -0,0 +1,86 @@ +/******************************************************************************* + * 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.jdk.core.text.change; + +import java.io.IOException; +import java.io.Writer; + +/** + * @author Ryan D. Brooks + */ +public class CharArrayChange implements CharacterChanger { + private int srcStartIndex; + private int srcEndIndex; + private char[] newChars; + private int offset; + private int length; + private CharacterChanger next; + + /** + * + */ + public CharArrayChange(int srcStartIndex, int srcEndIndex, char[] newChars, int offset, int length) { + super(); + this.srcStartIndex = srcStartIndex; + this.srcEndIndex = srcEndIndex; + this.newChars = newChars; + this.offset = offset; + this.length = length; + } + + public CharArrayChange(int srcStartIndex, int srcEndIndex, char[] newChars) { + this(srcStartIndex, srcEndIndex, newChars, 0, newChars.length); + } + + /* (non-Javadoc) + * @see text.change.CharacterChanger#getStartIndex() + */ + public int getStartIndex() { + return srcStartIndex; + } + + /* (non-Javadoc) + * @see text.change.CharacterChanger#getEndIndex() + */ + public int getEndIndex() { + return srcEndIndex; + } + + /* (non-Javadoc) + * @see text.change.CharacterChanger#applyChange(char[], int) + */ + public int applyChange(char[] dest, int destPos) { + System.arraycopy(newChars, offset, dest, destPos, length); + return destPos + length; + } + + public void applyChange(Writer writer) throws IOException { + writer.write(newChars, offset, length); + } + + /* (non-Javadoc) + * @see text.change.CharacterChanger#next() + */ + public CharacterChanger next() { + return next; + } + + /* (non-Javadoc) + * @see text.change.CharacterChanger#setNext(text.change.CharacterChanger) + */ + public void setNext(CharacterChanger next) { + this.next = next; + } + + public int getLengthDelta() { + return length - srcEndIndex + srcStartIndex; + } +} diff --git a/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/text/change/CharChange.java b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/text/change/CharChange.java new file mode 100644 index 00000000000..691ac97487e --- /dev/null +++ b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/text/change/CharChange.java @@ -0,0 +1,78 @@ +/******************************************************************************* + * Copyright (c) 2004, 2007 Boeing. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Boeing - initial API and implementation + *******************************************************************************/ +package org.eclipse.osee.framework.jdk.core.text.change; + +import java.io.IOException; +import java.io.Writer; + +/** + * @author Ryan D. Brooks + */ +public class CharChange implements CharacterChanger { + private int srcStartIndex; + private int srcEndIndex; + private char newChar; + private CharacterChanger next; + + /** + * + */ + public CharChange(int srcStartIndex, int srcEndIndex, char newChar) { + super(); + this.srcStartIndex = srcStartIndex; + this.srcEndIndex = srcEndIndex; + this.newChar = newChar; + } + + /* (non-Javadoc) + * @see text.change.CharacterChanger#getStartIndex() + */ + public int getStartIndex() { + return srcStartIndex; + } + + /* (non-Javadoc) + * @see text.change.CharacterChanger#getEndIndex() + */ + public int getEndIndex() { + return srcEndIndex; + } + + /* (non-Javadoc) + * @see text.change.CharacterChanger#applyChange(char[], int) + */ + public int applyChange(char[] dest, int destPos) { + dest[destPos] = newChar; + return destPos + 1; + } + + public void applyChange(Writer writer) throws IOException { + writer.write(newChar); + } + + /* (non-Javadoc) + * @see text.change.CharacterChanger#next() + */ + public CharacterChanger next() { + return next; + } + + /* (non-Javadoc) + * @see text.change.CharacterChanger#setNext(text.change.CharacterChanger) + */ + public void setNext(CharacterChanger next) { + this.next = next; + } + + public int getLengthDelta() { + return 1 - srcEndIndex + srcStartIndex; + } +} diff --git a/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/text/change/CharacterChanger.java b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/text/change/CharacterChanger.java new file mode 100644 index 00000000000..ad667c15221 --- /dev/null +++ b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/text/change/CharacterChanger.java @@ -0,0 +1,33 @@ +/******************************************************************************* + * Copyright (c) 2004, 2007 Boeing. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Boeing - initial API and implementation + *******************************************************************************/ +package org.eclipse.osee.framework.jdk.core.text.change; + +import java.io.IOException; +import java.io.Writer; + +/** + * @author Ryan D. Brooks + */ +public interface CharacterChanger { + public int getStartIndex(); + + public int getEndIndex(); + + public int applyChange(char[] dest, int destPos); + + public void applyChange(Writer writer) throws IOException; + + public CharacterChanger next(); + + public void setNext(CharacterChanger next); + + public int getLengthDelta(); +} diff --git a/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/text/change/DeleteChange.java b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/text/change/DeleteChange.java new file mode 100644 index 00000000000..3e25a2b6148 --- /dev/null +++ b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/text/change/DeleteChange.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.jdk.core.text.change; + +import java.io.Writer; + +/** + * @author Ryan D. Brooks + */ +public class DeleteChange implements CharacterChanger { + private int srcStartIndex; + private int srcEndIndex; + private CharacterChanger next; + + /** + * + */ + public DeleteChange(int srcStartIndex, int srcEndIndex) { + super(); + this.srcStartIndex = srcStartIndex; + this.srcEndIndex = srcEndIndex; + } + + public void coalesce(DeleteChange overlapping) { + DeleteChange changeA = null; + DeleteChange changeB = null; + + // make changeA be the one with the smaller srcStartIndex + if (overlapping.srcStartIndex < srcStartIndex) { + changeA = overlapping; + changeB = this; + } else { + changeA = this; + changeB = overlapping; + } + + if (changeB.srcStartIndex > changeA.srcEndIndex) { // Note: delete 2,5 is not adjacent to 6,7 (char 5 is not deleted) + throw new IllegalArgumentException("Tried to coalesce non-adjacent, non-overlapping DeleteChanges"); + } + this.srcStartIndex = changeA.srcStartIndex; + this.srcEndIndex = changeB.srcEndIndex; + } + + /* (non-Javadoc) + * @see text.change.CharacterChanger#getStartIndex() + */ + public int getStartIndex() { + return srcStartIndex; + } + + /* (non-Javadoc) + * @see text.change.CharacterChanger#getEndIndex() + */ + public int getEndIndex() { + return srcEndIndex; + } + + /* (non-Javadoc) + * @see text.change.CharacterChanger#applyChange(char[], int) + */ + public int applyChange(char[] dest, int destPos) { + return destPos; + } + + public void applyChange(Writer writer) { + return; + } + + /* (non-Javadoc) + * @see text.change.CharacterChanger#next() + */ + public CharacterChanger next() { + return next; + } + + /* (non-Javadoc) + * @see text.change.CharacterChanger#setNext(text.change.CharacterChanger) + */ + public void setNext(CharacterChanger next) { + this.next = next; + } + + public int getLengthDelta() { + return srcStartIndex - srcEndIndex; + } +} diff --git a/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/text/change/SimpleCharSequence.java b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/text/change/SimpleCharSequence.java new file mode 100644 index 00000000000..c6d6f1d91f8 --- /dev/null +++ b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/text/change/SimpleCharSequence.java @@ -0,0 +1,64 @@ +/******************************************************************************* + * 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.jdk.core.text.change; + +/** + * @author Ryan D. Brooks + */ +public class SimpleCharSequence implements CharSequence { + private char[] chars; + private int startIndex; + private int endIndex; + + /** + * + */ + public SimpleCharSequence(char[] chars, int startIndex, int endIndex) { + super(); + this.chars = chars; + this.startIndex = startIndex; + this.endIndex = endIndex; + } + + public SimpleCharSequence(char[] chars) { + this(chars, 0, chars.length); + } + + /* (non-Javadoc) + * @see java.lang.CharSequence#length() + */ + public int length() { + return endIndex - startIndex; + } + + /* (non-Javadoc) + * @see java.lang.CharSequence#charAt(int) + */ + public char charAt(int index) { + return chars[index + startIndex]; + } + + /* (non-Javadoc) + * @see java.lang.CharSequence#subSequence(int, int) + */ + public CharSequence subSequence(int start, int end) { + return new SimpleCharSequence(chars, start + startIndex, end + startIndex); + } + + public String toString() { + return new String(chars, startIndex, endIndex - startIndex); + } + + public boolean equals(Object obj) { + // TODO: implement + return false; + } +} diff --git a/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/text/rules/AdddistributionStatement.java b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/text/rules/AdddistributionStatement.java new file mode 100644 index 00000000000..f299bc7cd56 --- /dev/null +++ b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/text/rules/AdddistributionStatement.java @@ -0,0 +1,41 @@ +/******************************************************************************* + * Copyright (c) 2004, 2007 Boeing. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Boeing - initial API and implementation + *******************************************************************************/ +package org.eclipse.osee.framework.jdk.core.text.rules; + +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import org.eclipse.osee.framework.jdk.core.text.Rule; +import org.eclipse.osee.framework.jdk.core.text.change.ChangeSet; + +/** + * @author Ryan D. Brooks + */ +public class AdddistributionStatement extends Rule { + private static final Pattern classDeclarationP = Pattern.compile("^[/\\s\\*]*(?:Created on [^\n]+)?[\\s\\*]*(?:PLACE_YOUR_DISTRIBUTION_STATEMENT_RIGHT_HERE)?[/\\s\\*]*package"); + private static final char[] distributionStatement = "/*******************************************************************************\n * Copyright (c) 2004, 2007 Boeing.\n * All rights reserved. This program and the accompanying materials\n * are made available under the terms of the Eclipse Public License v1.0\n * which accompanies this distribution, and is available at\n * http://www.eclipse.org/legal/epl-v10.html\n *\n * Contributors:\n * Boeing - initial API and implementation\n *******************************************************************************/\n".toCharArray(); + + public AdddistributionStatement() { + super(null); + setFileNamePattern(Pattern.compile(".*\\.java")); + } + + public ChangeSet computeChanges(CharSequence seq) { + ChangeSet changeSet = new ChangeSet(seq); + + Matcher matcher = classDeclarationP.matcher(seq); + if (matcher.find()) { + setRuleWasApplicable(true); + changeSet.replace(0, matcher.end(), distributionStatement); + } + + return changeSet; + } +}
\ No newline at end of file diff --git a/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/text/rules/HtmlTableBuilder.java b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/text/rules/HtmlTableBuilder.java new file mode 100644 index 00000000000..31a0a1cc544 --- /dev/null +++ b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/text/rules/HtmlTableBuilder.java @@ -0,0 +1,70 @@ +/******************************************************************************* + * 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.jdk.core.text.rules; + +import java.io.File; +import java.io.IOException; +import org.eclipse.osee.framework.jdk.core.text.Rule; +import org.eclipse.osee.framework.jdk.core.text.change.ChangeSet; + +/** + * @author Ryan D. Brooks + */ +public class HtmlTableBuilder extends Rule { + + public HtmlTableBuilder() { + super("html"); + } + + public ChangeSet computeChanges(CharSequence seq) { + ChangeSet changeSet = new ChangeSet(seq); + + changeSet.insertBefore(0, "<html>\n<body>\n<table cellpadding=2 cellspacing=0 border=1>\n".toCharArray()); + + char[] rowStartChars = {'\t', '<', 't', 'r', '>', '\n'}; + char[] cellStartChars = "\t\t<td>".toCharArray(); + char[] cellEndChars = "</td>\n".toCharArray(); + char[] rowEndChars = {'\t', '<', '/', 't', 'r', '>', '\n'}; + + int lineStart = 0; + int lineEnd = 0; + int length = seq.length(); + for (int i = 0; i < length; i++) { + if (seq.charAt(i) == '\n') { /* find the lineEnd of a line */ + lineEnd = i + 1; + changeSet.insertBefore(lineStart, rowStartChars); + + int tabStart = lineStart; + for (int k = lineStart; k < lineEnd; k++) { + if (seq.charAt(k) == '\t' || k == i) { // if tab or end of line + changeSet.insertBefore(tabStart, cellStartChars); + tabStart = k + 1; + changeSet.replace(k, tabStart, cellEndChars); + } + } + changeSet.insertBefore(lineEnd, rowEndChars); + lineStart = lineEnd; + } + } + changeSet.insertBefore(length, "</table>\n</body>\n</html>".toCharArray()); + + return changeSet; + } + + public static void main(String[] args) throws IOException { + StringBuffer buffer = new StringBuffer(); + buffer.append(System.getProperty("user.home")); + buffer.append(File.separator); + buffer.append(HtmlTableBuilder.class.getName()); + buffer.append(".table.txt"); + new HtmlTableBuilder().process(new File(buffer.toString())); + } +} diff --git a/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/text/rules/HushHtmlScriptErrors.java b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/text/rules/HushHtmlScriptErrors.java new file mode 100644 index 00000000000..8db015a7ab4 --- /dev/null +++ b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/text/rules/HushHtmlScriptErrors.java @@ -0,0 +1,79 @@ +/******************************************************************************* + * 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.jdk.core.text.rules; + +import java.io.File; +import java.io.IOException; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import org.eclipse.osee.framework.jdk.core.text.Rule; +import org.eclipse.osee.framework.jdk.core.text.change.ChangeSet; + +/** + * This rule is to be used on html files. It adds error handling so that unsupported java scripting calls do not result + * in pesky windows being shown to the user. For example, when javadoc produced API's are viewed through the eclipse + * help system and the javadoc attempts to set the title of the parent. + * + * @author Robert A. Fisher + */ +public class HushHtmlScriptErrors extends Rule { + + // This is the code that must be entered in to the HTML to hush script errors + private final static String HUSH = "\nfunction handleError() {\n" + "return true;\n" + "}\n\n" + "window.onerror = handleError;\n"; + + public HushHtmlScriptErrors() { + super(null); + } + + public ChangeSet computeChanges(CharSequence seq) { + Pattern detectHusherInPlace = Pattern.compile("function handleError"); + Pattern findJavaScriptArea = Pattern.compile("<SCRIPT type=\"text/javascript\">"); + ChangeSet changeSet = new ChangeSet(seq); + + // Only add in hushing if it is not in place + Matcher matchHusher = detectHusherInPlace.matcher(seq); + if (!matchHusher.find()) { + + Matcher matcher = findJavaScriptArea.matcher(seq); + if (matcher.find()) { + ruleWasApplicable = true; + + changeSet.insertBefore(matcher.end() + 1, HUSH); + } + } + + return changeSet; + } + + public static void main(String[] args) { + HushHtmlScriptErrors hushRule = new HushHtmlScriptErrors(); + for (int i = 0; i < args.length; i++) { + try { + System.out.print("File " + (i + 1) + "/" + (args.length) + ":"); + hushRule.process(new File(args[i])); + } catch (Exception ex) { + System.out.println("Exception in Rule!!! " + hushRule.getCurrentOutfileName() + ": " + ex.getMessage()); + ex.printStackTrace(); + } + } + System.out.println("Finished"); + } + + /* + * (non-Javadoc) + * @see org.eclipse.osee.framework.jdk.core.text.Rule#process(java.io.File, java.io.File) + */ + public void process(File inFile, File outFile) throws IOException { + //Filter files being processed by this to only be of type .html + if (inFile.getName().endsWith(".html")) super.process(inFile, outFile); + } + +} diff --git a/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/text/rules/MultilineStrLiteral.java b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/text/rules/MultilineStrLiteral.java new file mode 100644 index 00000000000..39a783f5205 --- /dev/null +++ b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/text/rules/MultilineStrLiteral.java @@ -0,0 +1,50 @@ +/******************************************************************************* + * 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.jdk.core.text.rules; + +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import org.eclipse.osee.framework.jdk.core.text.Rule; +import org.eclipse.osee.framework.jdk.core.text.change.ChangeSet; + +/** + * @author Ryan D. Brooks + */ +public class MultilineStrLiteral extends Rule { + public static final Pattern wrappedStrLiteralP = Pattern.compile("\n[^\"\n]+(\"[ \t]*\n)[^\"]*?\n(\\s*\")"); + public static final Pattern signleLineP = Pattern.compile("[^\n]*\n"); + + public MultilineStrLiteral() { + super(null); // don't change extension on resulting file (i.e. overwrite the original file) + } + + public ChangeSet computeChanges(CharSequence seq) { + Matcher signleLineM = signleLineP.matcher(""); + Matcher wrappedStrLiteralM = wrappedStrLiteralP.matcher(seq); + ChangeSet changeSet = new ChangeSet(seq); + char[] terminateLineChars = new char[] {'\\', 'n', '\"'}; + + while (wrappedStrLiteralM.find()) { + ruleWasApplicable = true; + // delete the first quote and following white-space up to and including the first new line + changeSet.delete(wrappedStrLiteralM.start(1), wrappedStrLiteralM.end(1)); + + int subIndex = wrappedStrLiteralM.end(1); + signleLineM.reset(seq.subSequence(subIndex, wrappedStrLiteralM.start(2))); + while (signleLineM.find()) { + changeSet.insertBefore(subIndex + signleLineM.start(0), '\"'); + changeSet.insertBefore(subIndex + signleLineM.end(0) - 1, terminateLineChars); + } + changeSet.delete(wrappedStrLiteralM.start(2) - 1, wrappedStrLiteralM.end(2)); + } + return changeSet; + } +}
\ No newline at end of file diff --git a/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/text/rules/ReplaceAll.java b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/text/rules/ReplaceAll.java new file mode 100644 index 00000000000..24a8df394c8 --- /dev/null +++ b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/text/rules/ReplaceAll.java @@ -0,0 +1,97 @@ +/******************************************************************************* + * 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.jdk.core.text.rules; + +import java.io.File; +import java.io.IOException; +import java.util.List; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import org.eclipse.osee.framework.jdk.core.text.Rule; +import org.eclipse.osee.framework.jdk.core.text.change.ChOps; +import org.eclipse.osee.framework.jdk.core.text.change.ChangeSet; +import org.eclipse.osee.framework.jdk.core.util.Lib; + +/** + * @author Ryan D. Brooks + */ +public class ReplaceAll extends Rule { + private Pattern pattern; + private char[][] replacements; + + public ReplaceAll(Pattern pattern, String replacement) { + this(pattern, new String[] {replacement}); + } + + public ReplaceAll(Pattern pattern, String[] replacements) { + super(null); // don't change extension on resulting file (i.e. overwrite the original file) + this.pattern = pattern; + this.replacements = new char[replacements.length][]; + for (int i = 0; i < replacements.length; i++) { + char[] chars = replacements[i].toCharArray(); + this.replacements[i] = ChOps.embedNewLines(chars, 0, chars.length); + } + } + + public ReplaceAll(String patternStr, String[] replacements) { + this(Pattern.compile(patternStr), replacements); + } + + public ReplaceAll(String patternStr, String replacement) { + this(Pattern.compile(patternStr), replacement); + } + + public ChangeSet computeChanges(CharSequence seq) { + Matcher matcher = pattern.matcher(seq); + + ChangeSet changeSet = new ChangeSet(seq); + + while (matcher.find()) { + ruleWasApplicable = true; + + int numGroups = matcher.groupCount(); + if (numGroups == 0) { + changeSet.replace(matcher.start(), matcher.end(), replacements[0]); + } else { + for (int i = 0; i < numGroups; i++) { + int start = matcher.start(i + 1); + if (start > -1) { + changeSet.replace(start, matcher.end(i + 1), replacements[i]); + } + } + } + } + return changeSet; + } + + public static void main(String[] args) { + if (args.length < 3) { + System.out.println("Usage: java text.rules.ReplaceAll <pattern> <replace str or file> <directory> <fileName pattern>"); + return; + } + + try { + Rule rule = null; + if (new File(args[1]).exists()) { + List<String> list = Lib.readListFromFile(args[1]); + String[] strs = new String[list.size()]; + list.toArray(strs); + rule = new ReplaceAll(Pattern.compile(args[0]), strs); + } else { + rule = new ReplaceAll(Pattern.compile(args[0]), args[1]); + } + + rule.process(Lib.recursivelyListFiles(new File(args[2]), Pattern.compile(args[3]))); + } catch (IOException e) { + e.printStackTrace(); + } + } +}
\ No newline at end of file diff --git a/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/text/rules/Unique.java b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/text/rules/Unique.java new file mode 100644 index 00000000000..7d2cc4d26f1 --- /dev/null +++ b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/text/rules/Unique.java @@ -0,0 +1,40 @@ +/******************************************************************************* + * Copyright (c) 2004, 2007 Boeing. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Boeing - initial API and implementation + *******************************************************************************/ +package org.eclipse.osee.framework.jdk.core.text.rules; + +import java.util.LinkedHashSet; +import org.eclipse.osee.framework.jdk.core.text.Rule; +import org.eclipse.osee.framework.jdk.core.text.change.ChangeSet; + +/** + * @author Ryan D. Brooks + */ +public class Unique extends Rule { + public ChangeSet computeChanges(CharSequence seq) { + LinkedHashSet<Object> set = new LinkedHashSet<Object>(); + int start = 0; + int end = 0; + int length = seq.length(); + ChangeSet changeSet = new ChangeSet(seq); + + for (int i = 0; i < length; i++) { + if (seq.charAt(i) == '\n') { + end = i + 1; + if (!set.add(seq.subSequence(start, end))) { // if set already contains this line + changeSet.delete(start, end); // then skip over it + } + start = end; + } + } + ruleWasApplicable = true; + return changeSet; + } +}
\ No newline at end of file diff --git a/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/text/tool/CompareLists.java b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/text/tool/CompareLists.java new file mode 100644 index 00000000000..aa1e4e358b5 --- /dev/null +++ b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/text/tool/CompareLists.java @@ -0,0 +1,77 @@ +/******************************************************************************* + * 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.jdk.core.text.tool; + +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileWriter; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.Set; +import org.eclipse.osee.framework.jdk.core.util.Collections; +import org.eclipse.osee.framework.jdk.core.util.Lib; +import org.eclipse.osee.framework.jdk.core.util.io.MatchFilter; + +/** + * @author Ryan D. Brooks + */ +public class CompareLists { + + public static void main(String[] args) throws IOException { + + if (args.length != 4 && args.length != 2) { + System.out.println("Usage: java text.CompareLists <directory_1> <ext_1> <directory_2> <ext_2>"); + System.out.println("or : java text.CompareLists <path1> <path2>"); + return; + } + + if (args.length == 4) { + writeDiff(Lib.readListFromDir(args[0], new MatchFilter(".*\\." + args[1])), Lib.readListFromDir(args[2], + new MatchFilter(".*\\." + args[3])), new File("list_diff.txt"), + "Directory \"" + args[0] + "\", files with extension \"" + args[1] + "\"", + "Directory \"" + args[2] + "\", files with extension \"" + args[3] + "\""); + } else { + writeDiff(Lib.readListFromFile(args[0]), Lib.readListFromFile(args[1]), new File("list_diff.txt"), args[0], + args[1]); + } + } + + @SuppressWarnings("unchecked") + public static void writeDiff(Collection listA, Collection listB, File file, String listDescription1, String listDescription2) throws IOException { + BufferedWriter out = new BufferedWriter(new FileWriter(file)); + //Enforce uniqueness + Set setA = Collections.toSet(listA); + Set setB = Collections.toSet(listB); + + out.write("Items only in list A (" + listDescription1 + ")\n\n"); + List complement = Collections.setComplement(setA, setB); + for (int i = 0; i < complement.size(); i++) { + out.write(complement.get(i) + "\n"); + } + + out.write("\nItems only in list B (" + listDescription2 + ")\n\n"); + complement = Collections.setComplement(setB, setA); + for (int i = 0; i < complement.size(); i++) { + out.write(complement.get(i) + "\n"); + } + + //The intersection of two sets A and B is the set of elements common to A and B. + out.write("\nItems in both lists\n\n"); + ArrayList intersection = Collections.setIntersection(setA, setB); + for (int i = 0; i < intersection.size(); i++) { + out.write(intersection.get(i) + "\n"); + } + out.close(); + System.out.println("Finished processing. Output is in file \"list_diff.txt\""); + } +} diff --git a/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/text/tool/CountAscii.java b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/text/tool/CountAscii.java new file mode 100644 index 00000000000..bc673406169 --- /dev/null +++ b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/text/tool/CountAscii.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.jdk.core.text.tool; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; +import org.eclipse.osee.framework.jdk.core.util.io.MatchFilter; + +/** + * @author Ryan D. Brooks + */ +public class CountAscii { + + public static void main(String[] args) throws IOException { + if (args.length < 1) { + System.out.println("Usage: java text.CountAscii <directory of files>"); + return; + } + + int[] letterCount = new int[128]; + + File directory = new File(args[0]); + File[] files = directory.listFiles(new MatchFilter(".*\\.c")); + System.out.println("Found " + files.length + " files."); + + for (int i = 0; i < files.length; i++) { + BufferedReader in = new BufferedReader(new FileReader(files[i])); + int c = 0; + + while ((c = in.read()) != -1) { + letterCount[c]++; + } + in.close(); + } + + for (int i = 0; i < letterCount.length; i++) { + System.out.println((char) i + ": " + letterCount[i]); + } + /* + int total = 0; + for(int i=0; i<letterCount.length; i++) { + total += letterCount[i]; + }*/ + } +} diff --git a/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/text/tool/Find.java b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/text/tool/Find.java new file mode 100644 index 00000000000..4a8d25ac1c0 --- /dev/null +++ b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/text/tool/Find.java @@ -0,0 +1,234 @@ +/******************************************************************************* + * Copyright (c) 2004, 2007 Boeing. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Boeing - initial API and implementation + *******************************************************************************/ +package org.eclipse.osee.framework.jdk.core.text.tool; + +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileWriter; +import java.io.IOException; +import java.io.OutputStreamWriter; +import java.io.Writer; +import java.text.ParseException; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Iterator; +import java.util.List; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import org.eclipse.osee.framework.jdk.core.text.FileToBufferConvert; +import org.eclipse.osee.framework.jdk.core.text.FindResults; +import org.eclipse.osee.framework.jdk.core.util.Lib; + +/** + * @author Ryan D. Brooks + */ +public class Find { + private Collection<File> files; + private FindResults results; + private FileToBufferConvert converter; + private int precedingCount; + private int trailingCount; + private Matcher[] matchers; + private boolean[] matcherUsed; + + /** + * @param patterns a Collection of strings that are regular expressions + * @param files + * @param converter + */ + public Find(Collection<String> patterns, Collection<File> files, FileToBufferConvert converter) { + this.files = files; + this.converter = converter; + this.precedingCount = 0; + this.trailingCount = 0; + this.results = new FindResults(patterns.size()); + + this.matchers = new Matcher[patterns.size()]; + int i = 0; + for (String pattern : patterns) { + // the empty string is never used in the search because a matcher.reset happens first + matchers[i++] = Pattern.compile(pattern).matcher(""); + } + this.matcherUsed = new boolean[matchers.length]; + } + + private static FileToBufferConvert simpleToBuffer = new SimpleFileToBufferConvert(); + + private static ArrayList<String> toList(String pattern) { + ArrayList<String> patterns = new ArrayList<String>(); + patterns.add(pattern); + return patterns; + } + + public Find(String pattern, File topLevelSearchDir, String fileNamePattern) { + this(toList(pattern), Lib.recursivelyListFiles(topLevelSearchDir, Pattern.compile(fileNamePattern)), + simpleToBuffer); + } + + public static void main(String[] args) throws IOException { + if (args.length < 7) { + System.out.println("Usage: java text.Find <pattern-list file or pattern> <search directory> <fileName pattern> <leading pad> <trailing pad> <negative: true|false> <ignoreComments: true|false>"); + return; + } + + ArrayList<String> patterns = null; + if (new File(args[0]).exists()) { + patterns = Lib.readListFromFile(args[0]); + } else { + patterns = new ArrayList<String>(); + patterns.add(args[0]); + } + File resultFile = new File("results.txt"); + BufferedWriter out = new BufferedWriter(new FileWriter(resultFile)); + + List<File> files = Lib.recursivelyListFiles(new File(args[1]), Pattern.compile(args[2])); + System.out.println("Searching " + files.size() + " files..."); + if (files.size() == 0) { + return; + } + + FileToBufferConvert toBuffer = null; + if (Boolean.valueOf(args[6]).booleanValue()) { + toBuffer = new StripBlockComments(); + } else { + toBuffer = simpleToBuffer; + } + + Find app = new Find(patterns, files, toBuffer); + app.setRegionPadding(Integer.parseInt(args[3]), Integer.parseInt(args[4])); + + if (Boolean.valueOf(args[5]).booleanValue()) { + app.findMeNot(); + } else { + app.find(999999, true); + } + OutputStreamWriter stdOut = new OutputStreamWriter(System.out); + stdOut.write(resultFile.getAbsolutePath()); + + app.writeUnusedPatterns(stdOut); + app.getResults().writeFindResutls(out); + out.close(); + } + + public void setRegionPadding(int precedingCount, int trailingCount) { + this.precedingCount = precedingCount; + this.trailingCount = trailingCount; + } + + public FindResults getResults() { + return results; + } + + /** + * Search a given file for all patterns: maxIsPerPattern == true up to maxMatches of any single pattern (then search + * the same file for the next pattern) otherwise up to a maxMatches for all patterns in a given file(then end search + * of that file and start on the next one) + * + * @param maxMatches + * @param maxIsPerPattern + */ + public void find(int maxMatches, boolean maxIsPerPattern) { + for (Iterator<File> iter = files.iterator(); iter.hasNext();) { // for each file + + File file = iter.next(); + CharSequence buf = null; + try { + buf = converter.fileToCharSequence(file); + } catch (Exception ex) { + System.out.println("In File " + file + ": " + ex); + continue; + } + + int numMatches = 0; + for (int i = 0; i < matchers.length; i++) { + matchers[i].reset(buf); + if (maxIsPerPattern) { + numMatches = 0; // new pattern matcher so reset the match count + } + + if (numMatches == maxMatches) { // can only be true if maxIsPerPattern is false + break; // don't look for any more matches in this file + } + + // find each pattern at most maxMatches per file + while (matchers[i].find() && numMatches++ < maxMatches) { + matcherUsed[i] = true; + // System.out.println(files[f].getName() + " " + matchers[i].group()); + + String region = null; + if (matchers[i].groupCount() == 0) { + if (precedingCount == 0 && trailingCount == 0) { + region = matchers[i].group(); + } else { + int start = matchers[i].start() - precedingCount; + if (start < 0) { + start = 0; + } + int end = matchers[i].end() + trailingCount; + if (end > buf.length()) { + end = buf.length(); + } + region = buf.subSequence(start, end).toString(); + } + } else { + region = matchers[i].group(1); + } + results.addMatch(matchers[i].pattern().pattern(), file, region); + } + } + } + } + + /** + * Search a given file list for all patterns: maxIsPerPattern == true up to maxMatches of any single pattern (then + * search the same file for the next pattern) otherwise up to a maxMatches for all patterns in a given file(then end + * search of that file and start on the next one) + */ + public void findMeNot() { + for (Iterator<File> iter = files.iterator(); iter.hasNext();) { // for each file + + File file = iter.next(); + CharSequence buf = null; + try { + buf = converter.fileToCharSequence(file); + } catch (ParseException ex) { + System.out.println(ex); + continue; + } catch (IOException ex) { + System.out.println(ex); + continue; + } + + for (int i = 0; i < matchers.length; i++) { + matchers[i].reset(buf); + if (!matchers[i].find()) { + matcherUsed[i] = true; + results.addMatch(matchers[i].pattern().pattern(), file, "findMeNot"); + } + } + } + } + + public void writeUnusedPatterns(Writer out) throws IOException { + boolean titleNotYetPrinted = true; + for (int i = 0; i < matcherUsed.length; i++) { + if (!matcherUsed[i]) { + if (titleNotYetPrinted) { + out.write("Patterns that were never used\n"); + titleNotYetPrinted = false; + } + out.write(matchers[i].pattern().pattern()); + out.write('\n'); + } + } + out.flush(); + } +}
\ No newline at end of file diff --git a/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/text/tool/FindNonLocalFunctionCalls.java b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/text/tool/FindNonLocalFunctionCalls.java new file mode 100644 index 00000000000..bedf4967960 --- /dev/null +++ b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/text/tool/FindNonLocalFunctionCalls.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.jdk.core.text.tool; + +import java.io.File; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Iterator; +import java.util.LinkedHashSet; +import java.util.Set; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import org.eclipse.osee.framework.jdk.core.util.Lib; + +/** + * @author Ryan D. Brooks + */ +public class FindNonLocalFunctionCalls { + public static final Pattern functionCallPattern = Pattern.compile("\\W(\\w+)\\s*\\([^;{]*?\\)\\s*;"); + public static final Pattern functionDefPattern = Pattern.compile("\\W(\\w+)\\s*\\([^;{]*?\\)\\s*\\{"); + private LinkedHashSet<String> set; + private File[] files; + + public FindNonLocalFunctionCalls(File[] files) { + this.files = files; + set = new LinkedHashSet<String>(); + } + + public static void main(String[] args) { + File[] files = new File[args.length]; + for (int i = 0; i < args.length; i++) { + files[i] = new File(args[i]); + } + FindNonLocalFunctionCalls app = new FindNonLocalFunctionCalls(files); + app.searchFiles(); + app.print(); + } + + public void searchFiles() { + for (int i = 0; i < files.length; i++) { + try { + look(Lib.stripBlockComments(Lib.fileToCharBuffer(files[i]))); + } catch (Exception ex) { + ex.printStackTrace(); + } + } + } + + private void look(CharSequence seq) { + ArrayList<String> localFunctions = new ArrayList<String>(); + Matcher functionDefM = functionDefPattern.matcher(seq); + while (functionDefM.find()) { + localFunctions.add(functionDefM.group(1)); + } + + Matcher functionCallM = functionCallPattern.matcher(seq); + while (functionCallM.find()) { + if (!localFunctions.contains(functionCallM.group(1))) { + set.add(functionCallM.group(1)); + } + } + } + + public Set<String> getResultSet() { + return set; + } + + public void print() { + ArrayList<String> list = new ArrayList<String>(set); + Collections.sort(list); + for (Iterator<String> iter = list.iterator(); iter.hasNext();) { + System.out.println(iter.next()); + } + } +}
\ No newline at end of file diff --git a/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/text/tool/FunctionCallStats.java b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/text/tool/FunctionCallStats.java new file mode 100644 index 00000000000..699b4e6f113 --- /dev/null +++ b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/text/tool/FunctionCallStats.java @@ -0,0 +1,93 @@ +/******************************************************************************* + * 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.jdk.core.text.tool; + +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileWriter; +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.regex.Pattern; +import org.eclipse.osee.framework.jdk.core.text.FindResults; +import org.eclipse.osee.framework.jdk.core.util.Lib; + +/** + * @author Ryan D. Brooks + */ +public class FunctionCallStats { + @SuppressWarnings("unchecked") + public static void main(String[] args) throws IOException { + if (args.length < 2) { + System.out.println("Usage: FunctionCallStats <search directory> <fileName pattern>"); + return; + } + + ArrayList<String> patterns = new ArrayList<String>(); + patterns.add("\\W(\\w+)\\s*\\([^;{]*?\\)\\s*;"); + + BufferedWriter out = new BufferedWriter(new FileWriter("results.csv")); + + List files = Lib.recursivelyListFiles(new File(args[0]), Pattern.compile(args[1])); + System.out.println("Searching " + files.size() + " files..."); + + FindNonLocalFunctionCalls nonLocalFindApp = new FindNonLocalFunctionCalls( + (File[]) files.toArray(new File[files.size()])); + nonLocalFindApp.searchFiles(); + Set nonLocalFunctions = nonLocalFindApp.getResultSet(); + + Find app = new Find(patterns, files, new StripBlockComments()); + app.setRegionPadding(0, 0); + app.find(999999, true); + FindResults results = app.getResults(); + + class Counter { + public int count = 0; + } + + String lastFileName = null; + HashMap functions = new HashMap(1000); + for (FindResults.FindResultsIterator i = results.iterator(); i.hasNext();) { + String currentFileName = i.currentFile.getName(); + + if (i.currentRegion != null) { + if (!currentFileName.equals(lastFileName)) { + for (Iterator functionsIterator = functions.entrySet().iterator(); functionsIterator.hasNext();) { + Map.Entry entry = (Map.Entry) functionsIterator.next(); + String functionName = (String) entry.getKey(); + if (nonLocalFunctions.contains(functionName)) { + out.write(lastFileName); + out.write(','); + out.write(functionName); + out.write(','); + out.write(String.valueOf(((Counter) entry.getValue()).count)); + out.write('\n'); + } + } + lastFileName = currentFileName; + functions.clear(); + } + + Counter counter = (Counter) functions.get(i.currentRegion); + if (counter == null) { + counter = new Counter(); + } + counter.count++; + functions.put(i.currentRegion, counter); + } + } + out.close(); + } +}
\ No newline at end of file diff --git a/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/text/tool/ReplaceRcsLog.java b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/text/tool/ReplaceRcsLog.java new file mode 100644 index 00000000000..e850b3500f5 --- /dev/null +++ b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/text/tool/ReplaceRcsLog.java @@ -0,0 +1,103 @@ +/******************************************************************************* + * 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.jdk.core.text.tool; + +import java.io.File; +import java.io.IOException; +import java.nio.CharBuffer; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import org.eclipse.osee.framework.jdk.core.text.Range; +import org.eclipse.osee.framework.jdk.core.text.change.ChangeSet; +import org.eclipse.osee.framework.jdk.core.util.Lib; +import org.eclipse.osee.framework.jdk.core.util.io.MatchFilter; + +/** + * @author Ryan D. Brooks + */ +public class ReplaceRcsLog { + private static final Pattern logStartP = Pattern.compile("\\$Log.*\\s+"); + private static final Pattern revP = Pattern.compile("Revision \\d+\\.\\d+.*"); + private static final Pattern revEndP = Pattern.compile("\n[* \t/\\\\]*\n"); + + public static void main(String[] args) { + if (args.length < 3) { + System.out.println("Usage: java text.ReplaceRcsLog <dir for history> <dir for content> <result dir>"); + return; + } + + ReplaceRcsLog app = new ReplaceRcsLog(); + app.replaceRcsLogs(new File(args[0]), new File(args[1]), new File(args[2])); + } + + /** + * @param directoryA directory of test files will have their rcs log extracted + * @param directoryB directory of test files that will have their content preserved and log replaced + * @param resultDir + */ + public void replaceRcsLogs(File directoryA, File directoryB, File resultDir) { + File[] files = directoryA.listFiles(new MatchFilter(".*\\.(c|mac|h)")); + + for (int i = 0; i < files.length; i++) { + File fileB = new File(directoryB, files[i].getName()); + if (fileB.exists()) { + replaceRcsLog(files[i], fileB, new File(resultDir, files[i].getName())); + } + } + } + + public void replaceRcsLog(File historyFile, File contentFile, File resultFile) { + + CharBuffer historySeq; + CharBuffer contentSeq; + try { + historySeq = Lib.fileToCharBuffer(historyFile); + Range historyRange = findRcsLog(historySeq); + + contentSeq = Lib.fileToCharBuffer(contentFile); + Range contentRange = findRcsLog(contentSeq); + + ChangeSet changeSet = new ChangeSet(contentSeq); + changeSet.replace(contentRange.start, contentRange.end, historySeq.array(), historyRange.start, + historyRange.length); + changeSet.applyChanges(resultFile); + } catch (IOException ex) { + ex.printStackTrace(); + return; + } catch (IllegalArgumentException ex) { + System.out.println(historyFile + ": " + ex.getMessage()); + return; + } + } + + public static Range findRcsLog(CharSequence seq) throws IllegalArgumentException { + Matcher logStartM = logStartP.matcher(seq); + if (!logStartM.find()) { + throw new IllegalArgumentException(" is missing $Log"); + } + int firstRevStartIndex = logStartM.end(); // first char of actual revision info + + Matcher revM = revP.matcher(seq); + int lastRevStartIndex = 0; + while (revM.find()) { + lastRevStartIndex = revM.start(); + } // this loop with cause the last revsion to be found (usually 1.1) + + Matcher revEndM = revEndP.matcher(seq); + int lastRevEndIndex = 0; + if (!revEndM.find(lastRevStartIndex)) { + throw new IllegalArgumentException(" didn't find end of revision info"); + } + lastRevEndIndex = revEndM.start() + 1; // include the last new line + + return new Range(firstRevStartIndex, lastRevEndIndex); + } +}
\ No newline at end of file diff --git a/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/text/tool/RpcrSignalChanges.java b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/text/tool/RpcrSignalChanges.java new file mode 100644 index 00000000000..8287766f7f0 --- /dev/null +++ b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/text/tool/RpcrSignalChanges.java @@ -0,0 +1,98 @@ +/******************************************************************************* + * 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.jdk.core.text.tool; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileReader; +import java.io.IOException; +import java.util.ArrayList; +import java.util.NoSuchElementException; +import java.util.StringTokenizer; + +/** + * @author Ryan D. Brooks + */ +public class RpcrSignalChanges { + public String rpcrName; + public ArrayList<String> signals; + public boolean mux; + + public RpcrSignalChanges(File file) throws IOException { + rpcrName = file.getName().substring(0, 4); + this.signals = new ArrayList<String>(500); + + BufferedReader in = null; + try { + in = new BufferedReader(new FileReader(file)); + } catch (FileNotFoundException ex) { + System.err.println(ex); + throw new IllegalArgumentException(ex.toString()); + } + + String line = null; + // if line 6 starts with " Signal Name", then these are mux changes + for (int j = 0; j < 6; j++) { + line = in.readLine(); + } + + mux = line.startsWith(" Signal Name"); + + while ((line = in.readLine()) != null) { + String result = extractSignal(line); + if (result != null) { + signals.add(result); + } + } + in.close(); + } + + protected String extractSignal(String line) { + try { + StringTokenizer tok = new StringTokenizer(line); + if (!tok.hasMoreTokens()) { + System.out.println("blank line"); + return null; + } + String changeSymbol = tok.nextToken(); + + if (changeSymbol.equals("+") || changeSymbol.equals(">")) { + if (!tok.nextToken().equals("is:")) { + throw new IllegalArgumentException("Ryan --> you didn't think of everyting. Duh!"); + } + if (line.charAt(6) != ' ') { // there is either a mux name or a fiber interface + if (mux) { + return line.substring(6, 25).trim(); + } else { + tok.nextToken(); // skip interface name + String elementName = tok.nextToken(); + String lmName = tok.nextToken(); + return "l_" + lmName.toLowerCase() + "__" + elementName.toLowerCase(); + } + } + } + } catch (NoSuchElementException ex) { + System.out.println(ex + line); + System.exit(1); + } + return null; + } + + public boolean affectsLine(String line) { + for (int i = 0; i < signals.size(); i++) { + if (line.indexOf((String) signals.get(i)) != -1) { + return true; + } + } + return false; + } +} diff --git a/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/text/tool/SignalChanges.java b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/text/tool/SignalChanges.java new file mode 100644 index 00000000000..1ad00a7b132 --- /dev/null +++ b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/text/tool/SignalChanges.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.jdk.core.text.tool; + +import java.io.BufferedReader; +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileReader; +import java.io.FileWriter; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; +import org.eclipse.osee.framework.jdk.core.util.io.MatchFilter; + +/** + * @author Ryan D. Brooks + */ +public class SignalChanges { + + public static void main(String[] args) throws IOException { + if (args.length < 1) { + System.out.println("Usage: java text.SignalChanges <.dat directory> <scirpt source directory>"); + return; + } + + ArrayList<Object> list = loadList(args[0]); + writeSignalChanges(list, new File(args[0], "cdb_changes.txt"), new File(args[0], "mux_changes.txt")); + writeChangeVerification(args[1], list); + } + + // return list of RpcrSignalChanges found in the dat files in the given directory + public static ArrayList<Object> loadList(String path) throws IOException { + ArrayList<Object> list = new ArrayList<Object>(20); + + File directory = new File(path); + File[] files = directory.listFiles(new MatchFilter(".*\\.txt")); + Arrays.sort(files); + System.out.println("Found " + files.length + " dat files in " + path + "."); + + for (int i = 0; i < files.length; i++) { + list.add(new RpcrSignalChanges(files[i])); + } + return list; + } + + public static void writeChangeVerification(String scriptsPath, ArrayList<Object> changesList) throws IOException { + BufferedWriter out = new BufferedWriter(new FileWriter("rpcr_list.txt")); + + File directory = new File(scriptsPath); + File[] files = directory.listFiles(new MatchFilter(".*\\.c")); + Arrays.sort(files); + System.out.println("Found " + files.length + " script files in " + scriptsPath + "."); + + for (int i = 0; i < changesList.size(); i++) { + RpcrSignalChanges rpCh = (RpcrSignalChanges) changesList.get(i); + out.write(rpCh.rpcrName + "\n"); + + for (int j = 0; j < files.length; j++) { + BufferedReader in = new BufferedReader(new FileReader(files[j])); + + String line = null; + while ((line = in.readLine()) != null) { + if (rpCh.affectsLine(line)) { + out.write("\t" + files[j].getName() + "\n"); + break; + } + } + in.close(); + } + out.flush(); + } + out.close(); + } + + public static void writeSignalChanges(ArrayList<Object> changesList, File outputFile, File muxOutputFile) throws IOException { + BufferedWriter out = new BufferedWriter(new FileWriter(outputFile)); + BufferedWriter muxOut = new BufferedWriter(new FileWriter(muxOutputFile)); + + for (int i = 0; i < changesList.size(); i++) { + RpcrSignalChanges rpcrCng = (RpcrSignalChanges) changesList.get(i); + if (rpcrCng.mux) { + for (int j = 0; j < rpcrCng.signals.size(); j++) { + muxOut.write(rpcrCng.rpcrName + "," + rpcrCng.signals.get(j) + "\n"); + } + } else { + for (int j = 0; j < rpcrCng.signals.size(); j++) { + out.write(rpcrCng.rpcrName + " " + rpcrCng.signals.get(j) + "\n"); + } + } + } + out.close(); + muxOut.close(); + } +} diff --git a/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/text/tool/SimpleFileToBufferConvert.java b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/text/tool/SimpleFileToBufferConvert.java new file mode 100644 index 00000000000..a1b4b14c210 --- /dev/null +++ b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/text/tool/SimpleFileToBufferConvert.java @@ -0,0 +1,29 @@ +/*******************************************************************************
+ * Copyright (c) 2004, 2007 Boeing.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Boeing - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.osee.framework.jdk.core.text.tool;
+
+import java.io.File;
+import java.io.IOException;
+import org.eclipse.osee.framework.jdk.core.text.FileToBufferConvert;
+import org.eclipse.osee.framework.jdk.core.util.Lib;
+
+/**
+ * @author Ryan D. Brooks
+ */
+public class SimpleFileToBufferConvert implements FileToBufferConvert {
+
+ /* (non-Javadoc)
+ * @see org.eclipse.osee.framework.jdk.core.text.FileToBufferConvert#fileToCharSequence(java.io.File)
+ */
+ public CharSequence fileToCharSequence(File file) throws IOException {
+ return Lib.fileToCharBuffer(file);
+ }
+}
\ No newline at end of file diff --git a/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/text/tool/SourceCount.java b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/text/tool/SourceCount.java new file mode 100644 index 00000000000..94c1ad4c9ea --- /dev/null +++ b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/text/tool/SourceCount.java @@ -0,0 +1,115 @@ +/******************************************************************************* + * Copyright (c) 2004, 2007 Boeing. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Boeing - initial API and implementation + *******************************************************************************/ +package org.eclipse.osee.framework.jdk.core.text.tool; + +import java.io.BufferedReader; +import java.io.FileNotFoundException; +import java.io.FileReader; +import java.io.IOException; + +/** + * @author Ryan D. Brooks + */ +public class SourceCount { + protected BufferedReader in; + protected String line; + + public SourceCount() { + in = null; + line = null; + } + + public int countLOC(String sourceFile) { + try { + in = new BufferedReader(new FileReader(sourceFile)); + } catch (FileNotFoundException ex) { + System.err.println(ex); + System.exit(1); + } + + int count = 0; + try { + while ((line = in.readLine()) != null) { + ignoreComments(); + if (line != null) { //a comment might be the last line of the file + if (line.endsWith("{") || line.endsWith(";")) { // if logical LOC + count++; + } + } + } + } catch (IOException ex) { + System.err.println(ex); + System.exit(2); + } + return count; + } + + protected void ignoreComments() { + try { + while (line != null) { + line = line.trim(); + if (line.startsWith("/*")) { + while (line != null && !line.endsWith("*/")) { + line = in.readLine().trim(); + } + } else if (!line.startsWith("//")) { + //a logical LOC might have a comment folloing it on the same line + line = stripOffComment(line); + return; + } + line = in.readLine(); + } + } catch (IOException ex) { + System.err.println(ex); + System.exit(2); + } + } + + public static String stripOffComment(String line) { + int pos = line.lastIndexOf("//"); + if (pos != -1) { //if a comment is indeed there (maybe) + //the single line comment symbol might be part of a string literal + //this is hard because the string delimiter might also be part of a string literal + if (!insideStringLiteral(line, pos)) { + return line.substring(0, pos).trim(); + } + } + return line; + } + + public static boolean insideStringLiteral(String str, int pos) { + int index = 0; + boolean inside = false; + + char[] chars = new char[str.length()]; + str.getChars(0, chars.length, chars, 0); + + while (index < pos) { + if (chars[index] == '\\' && chars[index + 1] == '\"') { + index++; // skip over literal quotation marks + } else if (chars[index] == '\"') { + inside = !inside; + } + index++; + } + return inside; + } + + public static void main(String[] args) { + if (args.length < 1) { + System.out.println("Usage: SourceCount [source file]"); + return; + } + SourceCount app = new SourceCount(); + int loc = app.countLOC(args[0]); + System.out.println("Logical LOC: " + loc); + } +} diff --git a/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/text/tool/StripBlockComments.java b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/text/tool/StripBlockComments.java new file mode 100644 index 00000000000..56329b1acff --- /dev/null +++ b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/text/tool/StripBlockComments.java @@ -0,0 +1,25 @@ +/******************************************************************************* + * 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.jdk.core.text.tool; + +import java.io.File; +import java.io.IOException; +import org.eclipse.osee.framework.jdk.core.text.FileToBufferConvert; +import org.eclipse.osee.framework.jdk.core.util.Lib; + +/** + * @author Ryan D. Brooks + */ +public class StripBlockComments implements FileToBufferConvert { + public CharSequence fileToCharSequence(File file) throws IOException { + return Lib.stripBlockComments(Lib.fileToCharBuffer(file)); + } +}
\ No newline at end of file diff --git a/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/type/AddingDoubleMap.java b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/type/AddingDoubleMap.java new file mode 100644 index 00000000000..8d6022bda3f --- /dev/null +++ b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/type/AddingDoubleMap.java @@ -0,0 +1,64 @@ +/******************************************************************************* + * 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.jdk.core.type; + +import java.util.Collection; +import java.util.HashMap; +import java.util.Set; +import java.util.Map.Entry; + +/** + * @author Donald G. Dunne + */ +public class AddingDoubleMap<K> { + private final HashMap<K, MutableDouble> addingMap; + + public AddingDoubleMap(int initialCapacity) { + addingMap = new HashMap<K, MutableDouble>(initialCapacity); + } + + public AddingDoubleMap() { + addingMap = new HashMap<K, MutableDouble>(); + } + + public double get(K key) { + for (Entry<K, MutableDouble> entry : getCounts()) { + if (entry.getKey().equals(key)) return entry.getValue().getValue(); + } + return 0; + } + + public boolean contains(K key) { + for (Entry<K, MutableDouble> entry : getCounts()) { + if (entry.getKey().equals(key)) return true; + } + return false; + } + + public void put(K key, double byAmmount) { + MutableDouble count = addingMap.get(key); + if (count == null) { + addingMap.put(key, new MutableDouble(byAmmount)); + } else { + count.getValueAndInc(byAmmount); + } + } + + public void put(Collection<K> keys, double byAmmount) { + for (K key : keys) { + put(key, byAmmount); + } + } + + public Set<Entry<K, MutableDouble>> getCounts() { + return addingMap.entrySet(); + } +} diff --git a/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/type/CompositeKeyHashMap.java b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/type/CompositeKeyHashMap.java new file mode 100644 index 00000000000..19f56c7ed8b --- /dev/null +++ b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/type/CompositeKeyHashMap.java @@ -0,0 +1,142 @@ +/******************************************************************************* + * Copyright (c) 2004, 2007 Boeing. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Boeing - initial API and implementation + *******************************************************************************/ +package org.eclipse.osee.framework.jdk.core.type; + +import java.util.Collection; +import java.util.HashMap; +import java.util.Map; +import java.util.Set; + +/** + * A hash map implementation that uses composite keys + * + * @author Ken J. Aguilar + * @param <KeyOne> + * @param <KeyTwo> + * @param <Value> + */ +public class CompositeKeyHashMap<KeyOne, KeyTwo, Value> implements Map<CompositeKeyHashMap.CompositeKey<KeyOne, KeyTwo>, Value> { + + private final Map<CompositeKey<KeyOne, KeyTwo>, Value> map; + + public static final class CompositeKey<A, B> { + private final A key1; + private final B key2; + private final int hashcode; + + public CompositeKey(A key1, B key2) { + super(); + this.key1 = key1; + this.key2 = key2; + hashcode = key1.hashCode() ^ key2.hashCode(); + } + + public A getKey1() { + return key1; + } + + public B getKey2() { + return key2; + } + + @Override + public boolean equals(Object obj) { + if (obj instanceof CompositeKey) { + final CompositeKey<A, B> otherKey = (CompositeKey<A, B>) obj; + return otherKey.key1.equals(key1) && otherKey.key2.equals(key2); + } + return false; + } + + @Override + public int hashCode() { + return hashcode; + } + + } + + public CompositeKeyHashMap() { + map = new HashMap<CompositeKey<KeyOne, KeyTwo>, Value>(); + } + + public CompositeKeyHashMap(Map<CompositeKey<KeyOne, KeyTwo>, Value> map) { + this.map = map; + } + + public CompositeKeyHashMap(int count) { + map = new HashMap<CompositeKey<KeyOne, KeyTwo>, Value>(count); + } + + public void clear() { + map.clear(); + } + + public boolean containsKey(Object key) { + return map.containsKey(key); + } + + public boolean containsKey(KeyOne a, KeyTwo b) { + return map.containsKey(new CompositeKey<KeyOne, KeyTwo>(a, b)); + } + + public boolean containsValue(Object value) { + return map.containsValue(value); + } + + public Set<Map.Entry<CompositeKey<KeyOne, KeyTwo>, Value>> entrySet() { + return map.entrySet(); + } + + public Value get(Object key) { + return map.get(key); + } + + public Value get(KeyOne a, KeyTwo b) { + return map.get(new CompositeKey<KeyOne, KeyTwo>(a, b)); + } + + public boolean isEmpty() { + return map.isEmpty(); + } + + public Set<CompositeKey<KeyOne, KeyTwo>> keySet() { + return map.keySet(); + } + + public Value put(CompositeKey<KeyOne, KeyTwo> key, Value value) { + return map.put(key, value); + } + + public Value put(KeyOne a, KeyTwo b, Value value) { + return map.put(new CompositeKey<KeyOne, KeyTwo>(a, b), value); + } + + public void putAll(Map<? extends CompositeKey<KeyOne, KeyTwo>, ? extends Value> m) { + map.putAll(m); + } + + public Value remove(Object key) { + return map.remove(key); + } + + public Value remove(KeyOne a, KeyTwo b) { + return map.remove(new CompositeKey<KeyOne, KeyTwo>(a, b)); + } + + public int size() { + return map.size(); + } + + public Collection<Value> values() { + return map.values(); + } + +} diff --git a/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/type/CountingMap.java b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/type/CountingMap.java new file mode 100644 index 00000000000..71e2115cb06 --- /dev/null +++ b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/type/CountingMap.java @@ -0,0 +1,75 @@ +/******************************************************************************* + * 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.jdk.core.type; + +import java.util.Collection; +import java.util.HashMap; +import java.util.Set; +import java.util.Map.Entry; + +/** + * @author Ryan D. Brooks + */ +public class CountingMap<K> { + private final HashMap<K, MutableInteger> countingMap; + + public CountingMap(int initialCapacity) { + countingMap = new HashMap<K, MutableInteger>(initialCapacity); + } + + public CountingMap() { + countingMap = new HashMap<K, MutableInteger>(); + } + + public int get(K key) { + MutableInteger count = countingMap.get(key); + if (count == null) { + return 0; + } + return count.getValue(); + } + + public boolean contains(K key) { + return countingMap.containsKey(key); + } + + public void put(K key) { + MutableInteger count = countingMap.get(key); + if (count == null) { + countingMap.put(key, new MutableInteger(1)); + } else { + count.getValueAndInc(); + } + } + + public void put(K key, int byAmt) { + MutableInteger count = countingMap.get(key); + if (count == null) { + countingMap.put(key, new MutableInteger(byAmt)); + } else { + count.getValueAndInc(byAmt); + } + } + + public void put(Collection<K> keys) { + for (K key : keys) { + put(key); + } + } + + public Set<Entry<K, MutableInteger>> getCounts() { + return countingMap.entrySet(); + } + + public void clear() { + countingMap.clear(); + } +} diff --git a/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/type/DoubleKeyHashMap.java b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/type/DoubleKeyHashMap.java new file mode 100644 index 00000000000..0a2c2a8a3a2 --- /dev/null +++ b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/type/DoubleKeyHashMap.java @@ -0,0 +1,108 @@ +/******************************************************************************* + * Copyright (c) 2004, 2007 Boeing. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Boeing - initial API and implementation + *******************************************************************************/ +package org.eclipse.osee.framework.jdk.core.type; + +import java.util.Collection; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +public class DoubleKeyHashMap<KeyOne, KeyTwo, Value> { + + HashMap<KeyOne, HashMap<KeyTwo, Value>> k1ToHashMap; + + public DoubleKeyHashMap() { + k1ToHashMap = new HashMap<KeyOne, HashMap<KeyTwo, Value>>(); + } + + public Map<KeyOne, KeyTwo> keySet() { + Map<KeyOne, KeyTwo> keySet = new HashMap<KeyOne, KeyTwo>(); + for (KeyOne one : k1ToHashMap.keySet()) { + for (KeyTwo two : k1ToHashMap.get(one).keySet()) { + keySet.put(one, two); + } + } + return keySet; + + } + + public Value get(KeyOne k1, KeyTwo k2) { + HashMap<KeyTwo, Value> o = k1ToHashMap.get(k1); + if (o != null) { + return o.get(k2); + } + return null; + } + + public Value put(KeyOne k1, KeyTwo k2, Value v) { + Value returnV = null; + HashMap<KeyTwo, Value> o = k1ToHashMap.get(k1); + if (o != null) { + returnV = o.put(k2, v); + } else { + o = new HashMap<KeyTwo, Value>(); + returnV = o.put(k2, v); + k1ToHashMap.put(k1, o); + } + return returnV; + } + + public Value remove(KeyOne k1, KeyTwo k2) { + Value value = null; + HashMap<KeyTwo, Value> o = k1ToHashMap.get(k1); + if (o != null) { + value = o.remove(k2); + if (o.size() == 0) { + k1ToHashMap.remove(o); + } + } + return value; + } + + public String toString() { + return k1ToHashMap.toString(); + } + + /** + * The collection provided by this method is not backed by this DoubleKeyHashMap, and thusly any modifications to + * Collection will not modify the map, and future modifications to the map will not modify the Collection. + * + * @return Return value collection + */ + public Collection<Value> allValues() { + Collection<Value> values = new HashSet<Value>(); + for (HashMap<KeyTwo, Value> map : k1ToHashMap.values()) { + values.addAll(map.values()); + } + return values; + } + + public Map<KeyTwo, Value> getSubHash(KeyOne k1) { + return k1ToHashMap.get(k1); + } + + public boolean containsKey(KeyOne k1, KeyTwo k2) { + return (k1ToHashMap.containsKey(k1) && k1ToHashMap.get(k1).containsKey(k2)); + } + + public void clear() { + k1ToHashMap.clear(); + } + + public boolean isEmpty() { + return k1ToHashMap.size() == 0; + } + + public Set<KeyOne> getKeySetOne() { + return k1ToHashMap.keySet(); + } +} diff --git a/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/type/DoublePoint.java b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/type/DoublePoint.java new file mode 100644 index 00000000000..88e1d4bd022 --- /dev/null +++ b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/type/DoublePoint.java @@ -0,0 +1,67 @@ +/******************************************************************************* + * Copyright (c) 2004, 2007 Boeing. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Boeing - initial API and implementation + *******************************************************************************/ +package org.eclipse.osee.framework.jdk.core.type; + +/** + * @author Charles Shaw + */ +public class DoublePoint { + + protected double x; + protected double y; + + /** + * @param x The x coordinate of the point. + * @param y The y coordinate of the point. + */ + public DoublePoint(double x, double y) { + super(); + this.x = x; + this.y = y; + } + + public DoublePoint() { + super(); + this.x = 0.0; + this.y = 0.0; + } + + public double getX() { + return x; + } + + public void setX(double x) { + this.x = x; + } + + public double getY() { + return y; + } + + public void setY(double y) { + this.y = y; + } + + public boolean equals(Object object) { + boolean matches = false; + + if (object instanceof DoublePoint) { + DoublePoint point = (DoublePoint) object; + matches = (point.x == this.x) && (point.y == this.y); + } + + return matches; + } + + public String toString() { + return "(" + x + ", " + y + ")"; + } +} diff --git a/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/type/FixedSizePriorityQueue.java b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/type/FixedSizePriorityQueue.java new file mode 100644 index 00000000000..6df849ff64f --- /dev/null +++ b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/type/FixedSizePriorityQueue.java @@ -0,0 +1,54 @@ +/******************************************************************************* + * 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.jdk.core.type; + +import java.util.Comparator; +import java.util.PriorityQueue; + +/** + * Creates a PriorityQueue of fixed size. Once the queue has become full, attempts to add elements will result in the + * least (or smallest) element being removed from the queue. + * + * @author David Diepenbrock + */ +public class FixedSizePriorityQueue<E> extends PriorityQueue<E> { + + private static final long serialVersionUID = 6408445028193363641L; + + private final int qSize; + + public FixedSizePriorityQueue(int size, Comparator<E> comparator) { + super(size, comparator); + this.qSize = size; + } + + public FixedSizePriorityQueue(int size) { + super(size); + this.qSize = size; + } + + public FixedSizePriorityQueue(int size, E initialElement) { + this(size); + this.add(initialElement); + } + + @Override + public boolean add(E o) { + return this.offer(o); + } + + @Override + public boolean offer(E o) { + if (size() >= qSize) this.poll(); + return super.offer(o); + } + +} diff --git a/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/type/HashCollection.java b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/type/HashCollection.java new file mode 100644 index 00000000000..a4caa19fe70 --- /dev/null +++ b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/type/HashCollection.java @@ -0,0 +1,91 @@ +/******************************************************************************* + * Copyright (c) 2004, 2007 Boeing. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Boeing - initial API and implementation + *******************************************************************************/ +package org.eclipse.osee.framework.jdk.core.type; + +import java.util.Collection; + +/** + * A Map of keys to multiple values. Collections of values are stored in the Map. The type of Collection can be + * specified at construction, if desired. All Collections returned by methods are backed by the HashCollection, so + * changes to the HashCollection are reflected in the Collection, and vice-versa. However, modifications to the + * Collection outside of this class are generally discouraged because removal of the last item would then not guarantee + * removal of the key. + * <p> + * The implementation is tied to the HashCollectionPlus class, providing a null Object for the "plus" object. + * + * @author David Diepenbrock + */ +public class HashCollection<K, V> extends HashCollectionPlus<K, V, Object> { + + private static IPlusProvider<Object> provider = new IPlusProvider<Object>() { + public Object newObject() { + return null; + } + }; + + /******************************************************************************************************************** + * Constructors + *******************************************************************************************************************/ + + /** + * @see HashCollectionPlus#HashCollectionPlus(boolean, Class, int, float, IPlusProvider) + */ + @SuppressWarnings("unchecked") + public HashCollection(boolean isSynchronized, Class<? extends Collection> collectionType, int initialCapacity, float loadFactor) { + super(isSynchronized, collectionType, initialCapacity, loadFactor, provider); + } + + /** + * @see HashCollectionPlus#HashCollectionPlus(boolean, Class, int, IPlusProvider) + */ + @SuppressWarnings("unchecked") + public HashCollection(boolean isSynchronized, Class<? extends Collection> collectionType, int initialCapacity) { + super(isSynchronized, collectionType, initialCapacity, provider); + } + + /** + * @see HashCollectionPlus#HashCollectionPlus(boolean, Class, IPlusProvider) + */ + @SuppressWarnings("unchecked") + public HashCollection(boolean isSynchronized, Class<? extends Collection> collectionType) { + super(isSynchronized, collectionType, provider); + } + + /** + * Creates an unsynchronized HashCollection using a default Collection type + * + * @see HashCollection#HashCollection(boolean, Class, int, float) + * @see HashCollectionPlus#DEFAULT_COLLECTION_TYPE + */ + public HashCollection(int initialCapacity, float loadFactor) { + this(false, DEFAULT_COLLECTION_TYPE, initialCapacity, loadFactor); + } + + /** + * Creates an unsynchronized HashCollection using a default Collection type + * + * @see HashCollection#HashCollection(boolean, Class, int) + * @see HashCollectionPlus#DEFAULT_COLLECTION_TYPE + */ + public HashCollection(int initialCapacity) { + this(false, DEFAULT_COLLECTION_TYPE, initialCapacity); + } + + /** + * Creates an unsynchronized HashCollection using a default Collection type + * + * @see HashCollection#HashCollection(boolean, Class) + * @see HashCollectionPlus#DEFAULT_COLLECTION_TYPE + */ + public HashCollection() { + this(false, DEFAULT_COLLECTION_TYPE); + } +} diff --git a/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/type/HashCollectionPlus.java b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/type/HashCollectionPlus.java new file mode 100644 index 00000000000..8abe3637b72 --- /dev/null +++ b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/type/HashCollectionPlus.java @@ -0,0 +1,269 @@ +/******************************************************************************* + * 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.jdk.core.type; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; +import java.util.Set; + +/** + * A Map of keys to multiple values. Collections of values are stored in the Map. The type of Collection can be + * specified at construction, if desired. All Collections returned by methods are backed by the HashCollection, so + * changes to the HashCollection are reflected in the Collection, and vice-versa. However, modifications to the + * Collection outside of this class are generally discouraged because removal of the last item would then not guarantee + * removal of the key. The mapping also contains a "plus" object. This object can store additional information about the + * key. At construction a class of type IPlusProvider must be provided. This provider will generate instances of this + * "plus" object whenever a new key is added to the Map. When all of the items in the Collection are removed, the entire + * key is removed from the table - therefore, the "plus" object is only available as long as the Collection for a given + * key is not empty. + * + * @author David Diepenbrock + */ +public class HashCollectionPlus<K, V, O> { + + private boolean isSynchronized; + @SuppressWarnings("unchecked") + private Class<? extends Collection> collectionType; + private IPlusProvider<O> plusProvider; + + private Map<K, ObjectPair<Collection<V>, O>> map; + @SuppressWarnings("unchecked") + public static final Class<? extends Collection> DEFAULT_COLLECTION_TYPE = ArrayList.class; + + /******************************************************************************************************************** + * Constructors + *******************************************************************************************************************/ + + /** + * @param isSynchronized - If true, the Map & Collection will both be synchronized using the + * Collections.synchronizedMap & Collections.synchronizedCollection. otherwise, this class will not be + * synchronzied and therefore not threadsafe. + * @param collectionType The type of collection to use to as the values within the HashMap. + * @param initialCapacity + * @param plusProvider + * @see HashMap#HashMap(int, float) + */ + @SuppressWarnings("unchecked") + public HashCollectionPlus(boolean isSynchronized, Class<? extends Collection> collectionType, int initialCapacity, float loadFactor, IPlusProvider<O> plusProvider) { + + if (isSynchronized) + map = Collections.synchronizedMap(new HashMap<K, ObjectPair<Collection<V>, O>>(initialCapacity, loadFactor)); + else + map = new HashMap<K, ObjectPair<Collection<V>, O>>(initialCapacity, loadFactor); + + this.isSynchronized = isSynchronized; + this.collectionType = collectionType; + this.plusProvider = plusProvider; + } + + /** + * @param isSynchronized - If true, the Map & Collection will both be synchronized using the + * Collections.synchronizedMap & Collections.synchronizedCollection. otherwise, this class will not be + * synchronzied and therefore not threadsafe. + * @param collectionType - The type of collection to use to as the values within the HashMap. + * @param initialCapacity + * @param plusProvider + * @see HashMap#HashMap(int) + */ + @SuppressWarnings("unchecked") + public HashCollectionPlus(boolean isSynchronized, Class<? extends Collection> collectionType, int initialCapacity, IPlusProvider<O> plusProvider) { + if (isSynchronized) + map = Collections.synchronizedMap(new HashMap<K, ObjectPair<Collection<V>, O>>(initialCapacity)); + else + map = new HashMap<K, ObjectPair<Collection<V>, O>>(initialCapacity); + + this.isSynchronized = isSynchronized; + this.collectionType = collectionType; + this.plusProvider = plusProvider; + } + + /** + * @param isSynchronized - If true, the Map & Collection will both be synchronized using the + * Collections.synchronizedMap & Collections.synchronizedCollection. otherwise, this class will not be + * synchronzied and therefore not threadsafe. + * @param collectionType - The type of collection to use to as the values within the HashMap. + * @param plusProvider + * @see HashMap#HashMap() + */ + @SuppressWarnings("unchecked") + public HashCollectionPlus(boolean isSynchronized, Class<? extends Collection> collectionType, IPlusProvider<O> plusProvider) { + if (isSynchronized) + map = Collections.synchronizedMap(new HashMap<K, ObjectPair<Collection<V>, O>>()); + else + map = new HashMap<K, ObjectPair<Collection<V>, O>>(); + + this.isSynchronized = isSynchronized; + this.collectionType = collectionType; + this.plusProvider = plusProvider; + } + + /** + * Creates an unsynchronized HashCollectionPlus using a default Collection type (ArrayList) + * + * @see HashMap#HashMap(int, float) + */ + public HashCollectionPlus(int initialCapacity, float loadFactor, IPlusProvider<O> plusProvider) { + this(false, DEFAULT_COLLECTION_TYPE, initialCapacity, loadFactor, plusProvider); + } + + /** + * Creates an unsynchronized HashCollectionPlus using a default Collection type (ArrayList) + * + * @see HashMap#HashMap(int) + */ + public HashCollectionPlus(int initialCapacity, IPlusProvider<O> plusProvider) { + this(false, DEFAULT_COLLECTION_TYPE, initialCapacity, plusProvider); + } + + /** + * Creates an unsynchronized HashCollectionPlus using a default Collection type (ArrayList) + * + * @see HashMap#HashMap() + */ + public HashCollectionPlus(IPlusProvider<O> plusProvider) { + this(false, DEFAULT_COLLECTION_TYPE, plusProvider); + } + + /******************************************************************************************************************** + * Methods + *******************************************************************************************************************/ + + /** + * Adds the value to the collection specified by the key. If there is not a collection for the given key, a new + * collection is created and added to the hash. + * + * @param key The key whose collection we will add value to. + * @param value The value to be added. + * @return the collection containing value and all other items associated with the key. + */ + @SuppressWarnings("unchecked") + public Collection<V> put(K key, V value) { + ObjectPair<Collection<V>, O> objectPair = map.get(key); + if (objectPair == null) { + try { + Collection<V> items; + if (isSynchronized) + items = Collections.synchronizedCollection(collectionType.newInstance()); + else + items = collectionType.newInstance(); + + objectPair = new ObjectPair(items, plusProvider.newObject()); + map.put(key, objectPair); + } catch (InstantiationException ex) { + ex.printStackTrace(); + return null; + } catch (IllegalAccessException ex) { + ex.printStackTrace(); + return null; + } + } + objectPair.object1.add(value); + return objectPair.object1; + } + + /** + * Adds all of the items in the Collection values to the collection for the specified key. + * + * @param key The key to add the values to + * @param values The values to be added + * @return The collection for the key, containing all values. + */ + public Collection<V> put(K key, Collection<V> values) { + Collection<V> items = null; + + for (V value : values) { + if (items == null) + items = this.put(key, value); + else + items.add(value); + } + return items; + } + + /** + * @param key The key whose collection we will remove value from. + * @param value The value to be removed + * @return true iff the value was removed from the collection for key. + */ + public boolean removeValue(K key, V value) { + ObjectPair<Collection<V>, O> objectPair = map.get(key); + + if (objectPair != null) { + Collection<V> items = objectPair.object1; + if (items != null) { + if (items.remove(value)) { + if (items.isEmpty()) map.remove(key); + return true; + } + } + } + return false; + } + + /** + * Returns the Collection of items for this key, or null if the key does not exist. + * + * @param key + * @return Return value collection reference + */ + public Collection<V> getValues(K key) { + ObjectPair<Collection<V>, O> objectPair = map.get(key); + if (objectPair != null) return map.get(key).object1; + return null; + } + + /** + * Returns the "plus" object associated with the key, or null if the key does not exist. + * + * @param key + * @return Return object reference + */ + public O getPlusObject(K key) { + ObjectPair<Collection<V>, O> objectPair = map.get(key); + if (objectPair != null) return map.get(key).object2; + return null; + } + + public Set<K> keySet() { + return map.keySet(); + } + + public void clear() { + map.clear(); + } + + public boolean containsKey(K key) { + return map.containsKey(key); + } + + public boolean isEmpty() { + return map.isEmpty(); + } + + /** + * The total number of key-value combinations + */ + public int size() { + int size = 0; + Set<K> keySet = keySet(); + + synchronized (map) { + for (K key : keySet) { + size += getValues(key).size(); + } + } + return size; + } + +} diff --git a/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/type/HashCollectionPlusMap.java b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/type/HashCollectionPlusMap.java new file mode 100644 index 00000000000..71c511d2360 --- /dev/null +++ b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/type/HashCollectionPlusMap.java @@ -0,0 +1,73 @@ +/******************************************************************************* + * Copyright (c) 2004, 2007 Boeing. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Boeing - initial API and implementation + *******************************************************************************/ +package org.eclipse.osee.framework.jdk.core.type; + +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; + +/** + * A HashCollectionPlus which maintains a map as the "plus" object. + * + * @see HashCollectionPlus + * @author David Diepenbrock + */ +public class HashCollectionPlusMap<K, V, P, S> extends HashCollectionPlus<K, V, Map<P, S>> { + + /** + * Creates using a synchronized map for the "plus" object regardless of the isSynchronized flag, which is passed on + * to the HashCollectionPlus super object. + * + * @see HashCollectionPlus#HashCollectionPlus(boolean, Class, IPlusProvider) + */ + public HashCollectionPlusMap(boolean isSynchronized, Class<? extends Collection<?>> collectionType) { + super(isSynchronized, collectionType, new IPlusProvider<Map<P, S>>() { + public Map<P, S> newObject() { + return Collections.synchronizedMap(new HashMap<P, S>()); + } + }); + } + + /** + * Returns the value from the "plus" map associated with the two keys provided + * + * @param key The key to the hashCollection + * @param mapKey The key to the "plus" map + * @return The associated value, or null if either key had no associated entry. + */ + public S getMapValue(K key, P mapKey) { + S value = null; + Map<P, S> theMap = this.getPlusObject(key); + if (theMap != null) { + value = theMap.get(mapKey); + } + return value; + } + + /** + * Sets the value from the "plus" map associated with the two keys provided + * + * @param key The key to the hashCollection + * @param mapKey The key to the "plus" map + * @param value The value to set into the "plus" map for the mapKey + * @return true if the value was successfully set + */ + public boolean setMapValue(K key, P mapKey, S value) { + Map<P, S> theMap = this.getPlusObject(key); + if (theMap != null) { + theMap.put(mapKey, value); + return true; + } + return false; + } + +} diff --git a/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/type/IInputListener.java b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/type/IInputListener.java new file mode 100644 index 00000000000..4a742b0ef83 --- /dev/null +++ b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/type/IInputListener.java @@ -0,0 +1,31 @@ +/******************************************************************************* + * 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.jdk.core.type; + +import java.util.Collection; + +/** + * @author Roberto E. Escobar + */ +public interface IInputListener<T> { + + void addNode(T node); + + void addNodes(Collection<T> nodes); + + void removeNode(T node); + + void removeAll(); + + void nodeChanged(T inNode); + + void inputChanged(); +} diff --git a/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/type/IPlusProvider.java b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/type/IPlusProvider.java new file mode 100644 index 00000000000..c6813ea66f6 --- /dev/null +++ b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/type/IPlusProvider.java @@ -0,0 +1,25 @@ +/******************************************************************************* + * 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.jdk.core.type; + +/** + * This object is designed for use with the HashCollectionPlus in order to provide new objects of a particular type. + * + * @author David Diepenbrock + */ +public interface IPlusProvider<O> { + + /** + * @return a new object of type O. + */ + public O newObject(); + +} diff --git a/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/type/InputManager.java b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/type/InputManager.java new file mode 100644 index 00000000000..cc4b69d27f8 --- /dev/null +++ b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/type/InputManager.java @@ -0,0 +1,135 @@ +/******************************************************************************* + * 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.jdk.core.type; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Set; + +/** + * @author Roberto E. Escobar + */ +public class InputManager<T> implements IInputListener<T> { + + private List<T> inputList; + private Set<IInputListener<T>> changeListeners; + + public InputManager() { + super(); + inputList = Collections.synchronizedList(new ArrayList<T>()); + changeListeners = Collections.synchronizedSet(new HashSet<IInputListener<T>>()); + } + + public List<T> getInputList() { + return inputList; + } + + public void addNode(T inNode) { + synchronized (inputList) { + inputList.add(inputList.size(), inNode); + } + synchronized (changeListeners) { + Iterator<IInputListener<T>> iterator = changeListeners.iterator(); + while (iterator.hasNext()) + (iterator.next()).addNode(inNode); + } + } + + public void addNodes(Collection<T> inNode) { + synchronized (inputList) { + this.inputList.addAll(inNode); + } + synchronized (changeListeners) { + Iterator<IInputListener<T>> iterator = changeListeners.iterator(); + while (iterator.hasNext()) + (iterator.next()).addNodes(inNode); + } + } + + public void removeNode(T inNode) { + synchronized (inputList) { + this.inputList.remove(inNode); + } + synchronized (changeListeners) { + Iterator<IInputListener<T>> iterator = changeListeners.iterator(); + while (iterator.hasNext()) + (iterator.next()).removeNode(inNode); + } + } + + public void nodeChanged(T inNode) { + synchronized (changeListeners) { + Iterator<IInputListener<T>> iterator = changeListeners.iterator(); + while (iterator.hasNext()) + (iterator.next()).nodeChanged(inNode); + } + } + + public void inputChanged() { + synchronized (changeListeners) { + Iterator<IInputListener<T>> iterator = changeListeners.iterator(); + while (iterator.hasNext()) + (iterator.next()).inputChanged(); + } + } + + public void removeAll() { + synchronized (inputList) { + this.inputList.clear(); + } + synchronized (changeListeners) { + Iterator<IInputListener<T>> iterator = changeListeners.iterator(); + while (iterator.hasNext()) { + (iterator.next()).removeAll(); + } + } + } + + public void addInputListener(IInputListener<T> listener) { + synchronized (changeListeners) { + changeListeners.add(listener); + } + + for (T node : inputList) { + listener.addNode(node); + } + } + + public void removeInputListener(IInputListener<T> listener) { + synchronized (changeListeners) { + changeListeners.remove(listener); + } + } + + public String toString() { + synchronized (inputList) { + String toReturn = ""; + for (int i = 0; i < inputList.size(); i++) { + T node = (T) inputList.get(i); + toReturn += node.toString(); + } + return toReturn + "\n\n"; + } + } + + public void dispose() { + synchronized (inputList) { + inputList.clear(); + } + synchronized (changeListeners) { + changeListeners.clear(); + } + } +} diff --git a/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/type/MutableBoolean.java b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/type/MutableBoolean.java new file mode 100644 index 00000000000..39d6c064b75 --- /dev/null +++ b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/type/MutableBoolean.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.jdk.core.type; + +/** + * This class implements a boolean that can be passed around and modified through a group of methods. + * + * @author Chris Austin + */ +public class MutableBoolean { + private boolean value; + + public MutableBoolean(boolean value) { + this.value = value; + } + + public boolean getValue() { + return value; + } + + public void setValue(boolean value) { + this.value = value; + } + + public String toString() { + return Boolean.toString(value); + } +} diff --git a/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/type/MutableDouble.java b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/type/MutableDouble.java new file mode 100644 index 00000000000..8cce695a5bc --- /dev/null +++ b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/type/MutableDouble.java @@ -0,0 +1,42 @@ +/******************************************************************************* + * Copyright (c) 2004, 2007 Boeing. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Boeing - initial API and implementation + *******************************************************************************/ +package org.eclipse.osee.framework.jdk.core.type; + +/** + * This class implements an double that can be passed around and modified through a group of methods. It also allows the + * double value to be retrieved then post incremented automatically. This is a nice functionality where a common counter + * needs to be used within calling methods, but it is not convenient to return the latest index via the return value. + * + * @author Donald G. Dunne + */ +public class MutableDouble { + private double value; + + public MutableDouble(double value) { + this.value = value; + } + + public double getValue() { + return value; + } + + public double getValueAndInc(double byAmmount) { + return value += byAmmount; + } + + public void setValue(double value) { + this.value = value; + } + + public String toString() { + return Double.toString(value); + } +} diff --git a/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/type/MutableInteger.java b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/type/MutableInteger.java new file mode 100644 index 00000000000..eb43eafac04 --- /dev/null +++ b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/type/MutableInteger.java @@ -0,0 +1,47 @@ +/******************************************************************************* + * Copyright (c) 2004, 2007 Boeing. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Boeing - initial API and implementation + *******************************************************************************/ +package org.eclipse.osee.framework.jdk.core.type; + +/** + * This class implements an integer that can be passed around and modified through a group of methods. It also allows + * the integer value to be retrieved then post incremented automatically. This is a nice functionality where a common + * counter needs to be used within calling methods, but it is not convenient to return the latest index via the return + * value. + * + * @author Robert A. Fisher + */ +public class MutableInteger { + private int value; + + public MutableInteger(int value) { + this.value = value; + } + + public int getValue() { + return value; + } + + public int getValueAndInc() { + return value++; + } + + public int getValueAndInc(int byAmt) { + return value += byAmt; + } + + public void setValue(int value) { + this.value = value; + } + + public String toString() { + return Integer.toString(value); + } +} diff --git a/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/type/ObjectPair.java b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/type/ObjectPair.java new file mode 100644 index 00000000000..0841cd24fc9 --- /dev/null +++ b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/type/ObjectPair.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.jdk.core.type; + +public class ObjectPair<O, T> { + public final O object1; + public final T object2; + + public ObjectPair(O object1, T object2) { + this.object1 = object1; + this.object2 = object2; + } +} diff --git a/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/type/ObjectTriplet.java b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/type/ObjectTriplet.java new file mode 100644 index 00000000000..9857c25d90d --- /dev/null +++ b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/type/ObjectTriplet.java @@ -0,0 +1,23 @@ +/******************************************************************************* + * 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.jdk.core.type; + +public class ObjectTriplet<T, U, V> { + public final T object1; + public final U object2; + public final V object3; + + public ObjectTriplet(T object1, U object2, V object3) { + this.object1 = object1; + this.object2 = object2; + this.object3 = object3; + } +}
\ No newline at end of file diff --git a/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/type/Pair.java b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/type/Pair.java new file mode 100644 index 00000000000..e346ff01c6a --- /dev/null +++ b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/type/Pair.java @@ -0,0 +1,47 @@ +/******************************************************************************* + * Copyright (c) 2004, 2007 Boeing. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Boeing - initial API and implementation + *******************************************************************************/ +package org.eclipse.osee.framework.jdk.core.type; + +import java.io.Serializable; + +/** + * @author Roberto E. Escobar + */ +public class Pair<T, K> implements Serializable { + private static final long serialVersionUID = 1764353834209869140L; + private T key; + private K value; + + public Pair(T key, K value) { + this.key = key; + this.value = value; + } + + public T getKey() { + return key; + } + + public K getValue() { + return value; + } + + public void setKey(T key) { + this.key = key; + } + + public void setValue(K value) { + this.value = value; + } + + public String toString() { + return String.format("[%s, %s]", key.toString(), value.toString()); + } +} diff --git a/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/type/SimpleEnum.java b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/type/SimpleEnum.java new file mode 100644 index 00000000000..7d3a4740c70 --- /dev/null +++ b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/type/SimpleEnum.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.jdk.core.type; + +/** + * @author Donald G. Dunne + */ +public abstract class SimpleEnum { + + public final transient int value; + public final String name; + + protected SimpleEnum(int value, String name) { + this.value = value; + this.name = name; + } + + public final String toString() { + return name; + } + + public final boolean equals(Object obj) { + return super.equals(obj); + } + + public final int hashCode() { + return value; + } + +} diff --git a/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/type/TreeObject.java b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/type/TreeObject.java new file mode 100644 index 00000000000..a489fbaa80c --- /dev/null +++ b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/type/TreeObject.java @@ -0,0 +1,69 @@ +/******************************************************************************* + * Copyright (c) 2004, 2007 Boeing. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Boeing - initial API and implementation + *******************************************************************************/ +package org.eclipse.osee.framework.jdk.core.type; + +/** + * @author Roberto E. Escobar + */ +public class TreeObject { + private String name; + private TreeParent parent; + private boolean isCurrent; + private boolean isChecked; + + public TreeObject(String name) { + this.name = name; + } + + public TreeObject() { + this(""); + } + + public void setName(String name) { + this.name = name; + } + + public String getName() { + return name; + } + + public void setParent(TreeParent parent) { + this.parent = parent; + } + + public TreeParent getParent() { + return parent; + } + + public String toString() { + return getName(); + } + + public boolean isCurrent() { + return isCurrent; + } + + public void setCurrent(boolean isCurrent) { + this.isCurrent = isCurrent; + } + + public boolean isChecked() { + return isChecked; + } + + public void setChecked(boolean isChecked) { + this.isChecked = isChecked; + } + + public Object getAdapter(Class<?> adapter) { + return null; + } +} diff --git a/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/type/TreeParent.java b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/type/TreeParent.java new file mode 100644 index 00000000000..e6c82a4446f --- /dev/null +++ b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/type/TreeParent.java @@ -0,0 +1,47 @@ +/******************************************************************************* + * Copyright (c) 2004, 2007 Boeing. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Boeing - initial API and implementation + *******************************************************************************/ +package org.eclipse.osee.framework.jdk.core.type; + +import java.util.ArrayList; + +/** + * @author Roberto E. Escobar + */ +public class TreeParent extends TreeObject { + private ArrayList<TreeObject> children; + + public TreeParent(String name) { + super(name); + children = new ArrayList<TreeObject>(); + } + + public TreeParent() { + this(""); + } + + public void addChild(TreeObject child) { + children.add(child); + child.setParent(this); + } + + public void removeChild(TreeObject child) { + children.remove(child); + child.setParent(null); + } + + public TreeObject[] getChildren() { + return (TreeObject[]) children.toArray(new TreeObject[children.size()]); + } + + public boolean hasChildren() { + return children.size() > 0; + } +} diff --git a/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/AEmail.java b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/AEmail.java new file mode 100644 index 00000000000..26d753b18ae --- /dev/null +++ b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/AEmail.java @@ -0,0 +1,345 @@ +/******************************************************************************* + * 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.jdk.core.util; + +import java.io.File; +import java.util.Properties; +import javax.activation.DataHandler; +import javax.activation.DataSource; +import javax.activation.FileDataSource; +import javax.mail.Message; +import javax.mail.MessagingException; +import javax.mail.Multipart; +import javax.mail.Session; +import javax.mail.Transport; +import javax.mail.internet.AddressException; +import javax.mail.internet.InternetAddress; +import javax.mail.internet.MimeBodyPart; +import javax.mail.internet.MimeMessage; +import javax.mail.internet.MimeMultipart; +import org.eclipse.core.runtime.IConfigurationElement; +import org.eclipse.core.runtime.IExtension; +import org.eclipse.core.runtime.IExtensionPoint; +import org.eclipse.core.runtime.IExtensionRegistry; +import org.eclipse.core.runtime.Platform; + +/** + * @author Michael A. Winston + */ +public class AEmail extends MimeMessage { + protected static final String emailType = "mail.smtp.host"; + protected static final String HTMLHead = "<html><body>\n"; + protected static final String HTMLEnd = "</body></html>\n"; + + public static final String plainText = "text/plain"; + public static final String HTMLText = "text/html"; + + private String body = null; + private String bodyType = null; + private Multipart mainMessage; + + /** + * Default constructor + */ + public AEmail() { + super(getSession()); + mainMessage = new MimeMultipart(); + } + + /** + * Constructs an AEmail with the given arguments + * + * @param recipients - a list of valid addresses to send the message TO + * @param from - the sender of the message + * @param replyTo - a valid address of who the message should reply to + * @param subject - the subject of the message + */ + public AEmail(String[] recipients, String from, String replyTo, String subject) { + this(recipients, from, replyTo, subject, null); + } + + /** + * Constructs an AEmail with the given arguments + * + * @param recipients - a list of valid addresses to send the message TO + * @param from - the sender of the message + * @param replyTo - a valid address of who the message should reply to + * @param subject - the subject of the message + * @param textBody - the plain text of the body + */ + public AEmail(String[] recipients, String from, String replyTo, String subject, String textBody) { + this(); + try { + setRecipients(recipients); + setFrom(from); + setSubject(subject); + setReplyTo(replyTo); + + if (textBody != null) setBody(textBody); + + } catch (MessagingException e) { + e.printStackTrace(); + } + } + + /** + * Adds a single address to the recipient list + * + * @param addresses - a valid address to send the message TO + * @throws MessagingException + */ + public void addRecipients(String addresses) throws MessagingException { + addRecipients(Message.RecipientType.TO, addresses); + } + + /** + * Adds a list of addresses to the recipient list + * + * @param addresses - a list of valid addresses to send the message TO + * @throws MessagingException + */ + public void addRecipients(String[] addresses) throws MessagingException { + addRecipients(Message.RecipientType.TO, addresses); + } + + /** + * Adds a list of addresses to the corresponding recipient list + * + * @param type - specifies which field the address should be put in + * @param addresses - a list of valid addresses to send the message + * @throws MessagingException + */ + public void addRecipients(Message.RecipientType type, String[] addresses) throws MessagingException { + if (addresses != null) { + + InternetAddress newAddresses[] = new InternetAddress[addresses.length]; + + for (int i = 0; i < addresses.length; i++) { + newAddresses[i] = new InternetAddress(addresses[i]); + } + + addRecipients(type, newAddresses); + } + } + + /** + * Sets the recipient TO field + * + * @param addresses - a valid address to send the message TO + * @throws MessagingException + */ + public void setRecipients(String addresses) throws MessagingException { + setRecipients(Message.RecipientType.TO, addresses); + } + + /** + * Sets a list of addresses to the recipient list + * + * @param addresses - a list of valid addresses to send the message TO + * @throws MessagingException + */ + public void setRecipients(String[] addresses) throws MessagingException { + setRecipients(Message.RecipientType.TO, addresses); + } + + /** + * Sets a list of addresses to the corresponding recipient list + * + * @param type - specifies which field the address should be put in + * @param addresses - a list of valid addresses to send the message + * @throws MessagingException + */ + public void setRecipients(Message.RecipientType type, String[] addresses) throws MessagingException { + if (addresses != null) { + + InternetAddress newAddresses[] = new InternetAddress[addresses.length]; + + for (int i = 0; i < addresses.length; i++) { + newAddresses[i] = new InternetAddress(addresses[i]); + } + + setRecipients(type, newAddresses); + } + } + + /** + * Sets the from address + * + * @param address - the user name the message is from + * @throws AddressException + * @throws MessagingException + */ + // Set all the From Values + public void setFrom(String address) throws AddressException, MessagingException { + setFrom(new InternetAddress(address)); + } + + /** + * Sets the address to reply to (if different than the from addresss) + * + * @param address - a valid address to reply to + * @throws MessagingException + */ + public void setReplyTo(String address) throws MessagingException { + InternetAddress replyAddresses[] = new InternetAddress[1]; + replyAddresses[0] = new InternetAddress(address); + setReplyTo(replyAddresses); + } + + /** + * Gets the current Body Type of the message. NULL if one is not selected yet. + * + * @return A String representation of the current Body Type + */ + // Set the Body + public String getBodyType() { + return bodyType; + } + + /** + * Sets the text in the body of the message. + * + * @param text - the text to for the body of the message + */ + public void setBody(String text) { + body = text; + bodyType = plainText; + } + + /** + * Adds text to the body if the Body Type is "plain". If the body doesn't exist yet, then calls setBody. + * + * @param text - the text to add to the body + */ + public void addBody(String text) { + if (bodyType == null) + setBody(text); + else if (bodyType.equals(plainText)) body += text; + } + + /** + * Sets the text in the body of the HTML message. This will already add the <html><body> and + * </body></html> tags. + * + * @param htmlText - the text for the body of the HTML message + */ + public void setHTMLBody(String htmlText) { + bodyType = HTMLText; + body = HTMLHead + htmlText; + } + + /** + * Adds text to the HTML body if the Body Type is "html". If the body doesn't exist yet, then calls setHTMLBody. + * + * @param htmlText - the text to add to the HTML body + */ + public void addHTMLBody(String htmlText) { + if (bodyType == null) + setHTMLBody(htmlText); + else if (bodyType.equals(HTMLText)) body += htmlText; + + } + + /** + * Sends the message. + */ + public void send() { + SendThread sendThread = new SendThread(this); + sendThread.start(); + } + + private class SendThread extends Thread { + + private final AEmail email; + + public SendThread(AEmail email) { + this.email = email; + } + + @Override + public void run() { + super.run(); + MimeBodyPart messageBodyPart = new MimeBodyPart(); + + if (bodyType == null) { + bodyType = plainText; + body = ""; + } else if (bodyType.equals(HTMLText)) body += HTMLEnd; + + try { + messageBodyPart.setContent(body, bodyType); + mainMessage.addBodyPart(messageBodyPart, 0); + setContent(mainMessage); + Transport.send(email); + } catch (Exception ex) { + ex.printStackTrace(); + } + } + } + + private static String getMailServer() { + IExtensionRegistry extensionRegistry = Platform.getExtensionRegistry(); + + if (extensionRegistry == null) { + throw new IllegalStateException("The extension registry is unavailable"); + } + + String extensionPointId = "org.eclipse.osee.framework.jdk.core.DefaultMailServer"; + IExtensionPoint point = extensionRegistry.getExtensionPoint(extensionPointId); + if (point == null) { + throw new IllegalArgumentException("The extension point " + extensionPointId + " does not exist"); + } + + for (IExtension extension : point.getExtensions()) { + IConfigurationElement[] elements = extension.getConfigurationElements(); + + for (IConfigurationElement element : elements) { + return element.getAttribute("serverAddress"); + } + } + throw new IllegalStateException( + "No mail server defined. Use the extension point " + extensionPointId + " to define one."); + } + + /** + * Gets the current session + * + * @return the Current SMTP Session + */ + private static Session getSession() { + Properties props = System.getProperties(); + props.put(emailType, getMailServer()); + + return Session.getDefaultInstance(props, null); + } + + /** + * Adds an attachment to an email + * + * @param source + * @param attachmentName + * @throws MessagingException + */ + public void addAttachment(DataSource source, String attachmentName) throws MessagingException { + MimeBodyPart messageBodyPart = new MimeBodyPart(); + messageBodyPart.setDataHandler(new DataHandler(source)); + messageBodyPart.setFileName(attachmentName); + mainMessage.addBodyPart(messageBodyPart); + } + + public void addAttachment(File file) throws MessagingException { + addAttachment(new FileDataSource(file), file.getName()); + } + + public void addAttachment(String contents, String attachmentName) throws MessagingException { + addAttachment(new StringDataSource(contents, attachmentName), attachmentName); + } +} diff --git a/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/AFile.java b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/AFile.java new file mode 100644 index 00000000000..a40e61ffb30 --- /dev/null +++ b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/AFile.java @@ -0,0 +1,116 @@ +/******************************************************************************* + * Copyright (c) 2004, 2007 Boeing. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Boeing - initial API and implementation + *******************************************************************************/ +package org.eclipse.osee.framework.jdk.core.util; + +import java.io.BufferedInputStream; +import java.io.BufferedReader; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.OutputStreamWriter; +import java.io.PrintWriter; +import java.nio.channels.FileChannel; + +/** + * @author Donald G. Dunne + */ +public class AFile { + + public static String justFilename(String filename) { + File file = new File(filename); + return file.getName(); + } + + public static String justPath(String filename) { + File file = new File(filename); + filename = filename.replaceAll(file.getName(), ""); + return filename; + } + + public static void writeFile(String filename, String data) { + PrintWriter out2 = null; + try { + out2 = new PrintWriter(new OutputStreamWriter(new FileOutputStream(filename), "UTF-8")); + out2.println(data); + } catch (IOException e) { + System.out.println("e *" + e + "*"); + } finally { + if (out2 != null) out2.close(); + } + } + + public static void writeFile(File file, String data) { + writeFile(file.getAbsolutePath(), data); + } + + public static String readFile(String filename) { + File from_file = new File(filename); + return readFile(from_file); + } + + public static String readFile(File file) { + try { + FileInputStream fis = new FileInputStream(file); + return readFile(fis); + } catch (FileNotFoundException ex) { + ex.printStackTrace(); + System.out.println("readFile ERROR: File Not Found" + ex); + return null; + } + } + + public static String readFile(InputStream stream) { + String line; + BufferedInputStream bis = null; + StringBuffer buffer = new StringBuffer(); + BufferedReader br = null; + try { + bis = new BufferedInputStream(stream); + br = new BufferedReader(new InputStreamReader(bis, "UTF-8")); + } catch (Throwable e) { + System.out.println("readFile ERROR: Can't open file"); + return null; + } + try { + while ((line = br.readLine()) != null) { + buffer.append(line + "\n"); + } + br.close(); + } catch (IOException e) { + System.out.println("ERROR: users.xml: Can't read file"); + return null; + } + String orig = new String(buffer.toString()); + return orig; + } + + public static boolean copy(String src, String dest) { + try { + // Create channel on the source + FileChannel srcChannel = new FileInputStream(src).getChannel(); + // Create channel on the destination + FileChannel dstChannel = new FileOutputStream(dest).getChannel(); + // Copy file contents from source to destination + dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); + // Close the channels + srcChannel.close(); + dstChannel.close(); + } catch (IOException e) { + System.out.println("AFile:copy *" + e + "*"); + return false; + } + return true; + } +}
\ No newline at end of file diff --git a/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/AHTML.java b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/AHTML.java new file mode 100644 index 00000000000..beb6833b860 --- /dev/null +++ b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/AHTML.java @@ -0,0 +1,456 @@ +/******************************************************************************* + * 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.jdk.core.util; + +import java.io.BufferedReader; +import java.io.InputStreamReader; +import java.net.InetSocketAddress; +import java.net.Proxy; +import java.net.URL; +import java.net.URLConnection; +import java.util.Collection; +import java.util.List; + +/** + * @author Michael A. Winston + */ +public class AHTML { + private static final String HTTP_CHARSET_ENCODING = "<meta http-equiv=\"Content-Type\" content=\"text/html;charset=utf-8\">"; + private static final String begin = "<table "; + public final static String LABEL_FONT = "<font color=\"darkcyan\" face=\"Arial\" size=\"-1\">"; + + public static String getHyperlink(String url, String name) { + return String.format("<a href=\"%s\">%s</a>", url, name); + } + + public static String textToHtml(String text) { + String str = new String(text); + str = str.replaceAll("&", "&"); + str = str.replaceAll(">", ">"); + str = str.replaceAll("<", "<"); + str = str.replaceAll("\"", """); + str = str.replaceAll("\\n", "<br>"); + str = str.replaceAll("\t", " "); + str = str.replaceAll("[\\x0B\\f\\r]+", ""); + return str; + } + + public static String htmlToText(String html) { + String str = new String(html); + str = str.replaceAll("&", "&"); + str = str.replaceAll(">", ">"); + str = str.replaceAll("<", "<"); + str = str.replaceAll(""", "\""); + str = str.replaceAll(" ", " "); + return str; + } + + public static String getUrlPageHtml(String urlStr, InetSocketAddress addr) { + StringBuffer buffer = new StringBuffer(); + try { + URL url = new URL(urlStr); + URLConnection connection = url.openConnection(new Proxy(Proxy.Type.HTTP, addr)); + BufferedReader rd = new BufferedReader(new InputStreamReader(connection.getInputStream())); + String line = null; + while ((line = rd.readLine()) != null) { + buffer.append(line); + } + rd.close(); + return buffer.toString(); + } catch (Exception ex) { + ex.printStackTrace(); + return simplePage("Exception opening url " + ex.getLocalizedMessage()); + } + } + + public static String titledPage(String title, String text) { + return simplePage("<head><title>" + title + "</title></head>" + text); + } + + public static String pageEncoding(String html) { + return HTTP_CHARSET_ENCODING + html; + } + + public static String simplePage(String text) { + return pageEncoding("<html>" + text + "</html>"); + } + + public static String getLabelStr(String labelFont, String str) { + return labelFont + "<b>" + textToHtml(str) + "</b></font>\r\n"; + } + + public static String getLabelValueStr(String labelFont, String label, String value) { + return getLabelStr(labelFont, label) + value; + } + + public static String color(String color, String str) { + return "<font color=\"" + color + "\">" + str + "</font>\r\n"; + } + + public static String boldColor(String color, String str) { + return "<font color=\"" + color + "\"><b>" + textToHtml(str) + "</b></font>\r\n"; + } + + public static String bold(String str) { + return "<b>" + textToHtml(str) + "</b>"; + } + + public static String boldColorTags(String color, String str) { + return "<font color=\"" + color + "\"><b>" + str + "</b></font>\r\n"; + } + + public static String imageBlock(String description, String filename) { + String filenames[] = new String[1]; + filenames[0] = filename; + return imageBlock(description, filenames); + } + + public static String imageBlock(String description, String filenames[]) { + String str = "<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\"><tr><td>\r\n"; + if (!description.equals("")) { + str += description; + str += AHTML.newline(); + } + for (int i = 0; i < filenames.length; i++) { + str += "<IMG SRC=\"" + filenames[i] + "\"><br>\r\n"; + } + str += "</td></tr></table>\r\n"; + return str; + } + + public static String urlBlock(String description, String urls[]) { + String str = "<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\">\r\n"; + if (!description.equals("")) { + str += description; + str += AHTML.newline(); + } + for (int i = 0; i < urls.length; i++) { + str += "<A HREF=\"" + urls[i] + "\">" + urls[i] + "</A><br>\r\n"; + } + str += "</td></tr></table>\r\n"; + return str; + } + + public static String heading(int heading, String str, String id) { + return "<h" + heading + (id != null && !id.equals("") ? " id=\"" + id + "\"" : "") + ">" + textToHtml(str) + "</h" + heading + ">\r\n"; + } + + public static String heading(int heading, String str) { + return heading(heading, str, null); + } + + public static String padSpace(int num, String str) { + String out = ""; + for (int i = 0; i < num; i++) { + out += " "; + } + out += str; + return out; + } + + public static String addSpace(int num) { + String out = ""; + for (int i = 0; i < num; i++) { + out += " "; + } + return out; + } + + public static String para(String str) { + return "<p>" + textToHtml(str) + "</p>\r\n"; + } + + public static String italics(String str) { + return "<i>" + textToHtml(str) + "</i>\r\n"; + } + + public static String pre(String str) { + return "<pre>" + str + "</pre>\r\n"; + } + + public static String newline() { + return newline(1); + } + + public static String newline(int num) { + String str = ""; + for (int i = 0; i < num; i++) { + str += "<br>"; + } + return str + "\r\n"; + } + + public static String name(int num) { + return nameTarget("" + num); + } + + /** + * Create target for hyperlink to jump to + * + * @param str + * @return Return name target string + */ + public static String nameTarget(String str) { + if (str == null) { + return ""; + } + return "<A NAME=\"" + str + "\">\r\n"; + } + + /** + * Create <a href> hyperlink to nameTarget + * + * @param num + * @param text + * @return Return name link string + */ + public static String nameLink(int num, String text) { + return nameLink("" + num, text); + } + + /** + * Create <a href> hyperlink to nameTarget + * + * @param name + * @param text + * @return Return name link string + */ + public static String nameLink(String name, String text) { + return "<A HREF=\"#" + name + "\">" + text + "</A>"; + } + + /** + * Create <a href> hyperlink to nameTarget using name as hyperlink tag and display text + * + * @param name + * @return Return name link string + */ + public static String nameLink(String name) { + return "<A HREF=\"#" + name + "\">" + name + "</A>"; + } + + public static String simpleTable(String str) { + return simpleTable(str, 100); + } + + /** + * Create a table with one row/colum containing str + * + * @param str + * @param width + * @return return simple table string + */ + public static String simpleTable(String str, int width) { + return new String( + "<table border=\"0\" cellpadding=\"3\" cellspacing=\"0\" width=\"" + width + "%\">\r\n" + "<tr><td>" + str + "</td></tr>\r\n" + "</table>\r\n"); + } + + /** + * Create a table with one row/colum containing str + * + * @param str + * @param width + * @param bgcolor + * @return Return border table string + */ + public static String borderTable(String str, int width, String bgcolor, String caption) { + return startBorderTable(width, bgcolor, caption) + str + endBorderTable(); + } + + public static String startBorderTable(int width, String bgcolor, String caption) { + String capStr = ""; + if (!caption.equals("")) capStr = "<caption ALIGN=top>" + caption + "</caption>"; + return "<table border=\"1\" align=\"center\" bgcolor=\"" + bgcolor + "\" cellpadding=\"3\" cellspacing=\"0\" width=\"" + width + "%\">\r\n" + capStr + "<tr><td>"; + } + + public static String endBorderTable() { + return "</td></tr>\r\n</table>\r\n"; + } + + /** + * Create a table with one row multi column containing str[] + * + * @param str = array of strings for columns + * @return Return multi-column table string + */ + public static String multiColumnTable(String[] str) { + return multiColumnTable(str, 85); + } + + /** + * Create a table with one row multi column containing str[] + * + * @param str - array of strings for columns + * @param width - percent (1..100) of screen for table + * @return Return multi-column table string + */ + public static String multiColumnTable(String[] str, int width) { + String s = "<table border=\"0\" cellpadding=\"3\" cellspacing=\"0\" width=\"" + width + "%\"><tr>\r\n"; + for (int i = 0; i < str.length; i++) { + s += "<td>" + str[i] + "</td>\r\n"; + } + s += "</tr></table>\r\n"; + return s; + } + + public static String beginMultiColumnTable(int width) { + return beginMultiColumnTable(width, 0); + } + + public static String beginMultiColumnTable(int width, int border) { + return beginMultiColumnTable(width, border, null); + } + + public static String beginMultiColumnTable(int width, int border, Integer color) { + return "<table border=\"" + border + "\" " + (color != null ? "color=\"" + color + "\"" : "") + " cellpadding=\"3\" cellspacing=\"0\" width=\"" + width + "%\">"; + } + + public static String endMultiColumnTable() { + return "</table>\r\n"; + } + + public static String addRowMultiColumnTable(String[] str) { + return addRowMultiColumnTable(str, null, null); + } + + public static String addRowMultiColumnTable(String[] str, String[] colOptions) { + return addRowMultiColumnTable(str, colOptions, null); + } + + public static String addRowMultiColumnTable(String[] str, String[] colOptions, String backgroundColor) { + String s = "<tr>"; + if (backgroundColor != null) s = "<tr bgcolor=\"" + backgroundColor + "\">"; + String show = ""; + for (int i = 0; i < str.length; i++) { + show = str[i]; + if (show == null || show.equals("")) show = AHTML.addSpace(1); + String colOptionStr = ""; + if (colOptions != null) colOptionStr = colOptions[i]; + s += "<td" + ((colOptionStr != null && !colOptionStr.equals("")) ? colOptionStr : "") + ">" + show + "</td>\r\n"; + } + s += "</tr>"; + return s; + } + + public static String addRowSpanMultiColumnTable(String str, int span) { + return "<tr><td colspan=" + span + ">" + str + "</td>\r\n</tr>"; + } + + public static class CellItem { + String text; + private final String fgColor; + private final String bgColor; + + public CellItem(String text) { + this(text, null, null); + } + + public CellItem(String text, String fgColor, String bgColor) { + this.text = text; + this.fgColor = fgColor; + this.bgColor = bgColor; + } + } + + public static String addRowMultiColumnTable(Collection<CellItem> items) { + String s = "<tr>"; + for (CellItem item : items) { + if (item.text == null || item.text.equals("")) item.text = "."; + if (item.fgColor != null && item.bgColor != null) + s += "<td bgcolor=\"" + item.bgColor + "\">" + AHTML.color(item.fgColor, item.text) + "</td>\r\n"; + else if (item.bgColor != null) + s += "<td bgcolor=\"" + item.bgColor + "\">" + item.text + "</td>\r\n"; + else if (item.fgColor != null) + s += "<td>" + AHTML.color(item.fgColor, item.text) + "</td>\r\n"; + else + s += "<td>" + item.text + "</td>\r\n"; + } + s += "</tr>"; + return s; + } + + public static String addHeaderRowMultiColumnTable(String[] str) { + return addHeaderRowMultiColumnTable(str, null); + } + + public static String addHeaderRowMultiColumnTable(String[] str, Integer width[]) { + String s = "<tr>"; + String widthStr = ""; + for (int i = 0; i < str.length; i++) { + if (width != null) widthStr = " width =\"" + width[i] + "\""; + s += "<th" + widthStr + ">" + str[i] + "</th>\r\n"; + } + s += "</tr>"; + return s; + } + + public static String addSimpleTableRow(String str) { + String s = "<tr><td>" + str + "</td></tr>\r\n"; + return s; + } + + public static String beginSimpleTable() { + return new String("<table border=\"0\" cellpadding=\"10\" cellspacing=\"0\" width=\"100%\">\r\n"); + } + + public static String beginSimpleTable(int border, int width) { + return new String("<table border=\"" + border + "\" cellpadding=\"10\" cellspacing=\"0\" width=\"+width+%\">\r\n"); + } + + public static String endSimpleTable() { + return new String("</table>\r\n"); + } + + public static String createTable(List<String> datas, String[] headers, int numColumns, int cellPadding, int border) { + StringBuilder table = new StringBuilder(begin); + + if (datas == null) { + throw new IllegalArgumentException("The data can not be null"); + } + if (datas.size() % numColumns != 0) { + throw new IllegalArgumentException( + "The table could not be created becuase the data does not match the column size"); + } + if (border > 0) { + table.append("border=\"" + border + "\""); + } + if (cellPadding > 0) { + table.append("cellpadding=\"" + cellPadding + "\""); + } + table.append(">"); + + if (headers != null && headers.length == numColumns) { + table.append("<tr>"); + for (String header : headers) { + table.append("<th>" + header + "</th>"); + } + table.append("</tr>"); + } + + int colIndex = 0; + for (String data : datas) { + + if (colIndex == 0) { + table.append("<tr>"); + } + table.append("<td>" + data + "</td>"); + colIndex++; + + if (colIndex == numColumns) { + table.append("</tr>"); + colIndex = 0; + } + } + return table.toString(); + } + +}
\ No newline at end of file diff --git a/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/AXml.java b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/AXml.java new file mode 100644 index 00000000000..1f276e97d21 --- /dev/null +++ b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/AXml.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.jdk.core.util; + +import java.util.Vector; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * @author Donald G. Dunne + */ +public class AXml { + + public static String getRootTag(String xmlStr) { + Matcher m; + m = Pattern.compile("^[\r\n \t]*<.*?>[\r\n \t]*<(.*?)>", Pattern.MULTILINE | Pattern.DOTALL).matcher(xmlStr); + if (m.find()) { + return m.group(1); + } + return ""; + } + + /** + * Returns <elementName>data</elementName> NOTE: data is not sent through AXml.textToXml + * + * @param elementName + * @param data + * @return String <elementName>data</elementName> + */ + public static String addTagData(String elementName, String data) { + return addTagData(elementName, data, false); + } + + public static String addTagData(String elementName, String data, boolean newLine) { + String str = "<" + elementName + ">" + data + "</" + elementName + ">"; + if (newLine) + return str + "\n"; + else + return str; + } + + public static String[] getTagDataArray(String xmlStr, String xmlRoot) { + Vector<String> v = new Vector<String>(); + Matcher m; + m = Pattern.compile("<" + xmlRoot + ">(.*?)</" + xmlRoot + ">", Pattern.MULTILINE | Pattern.DOTALL).matcher( + xmlStr); + while (m.find()) { + v.add(xmlToText(m.group(1))); + } + return (String[]) v.toArray(new String[v.size()]); + } + + /** + * Returns data betweeen <xmlRoot> and </xmlRoot> from xmlStr + * + * @param xmlStr + * @param xmlRoot + * @return Return tag string + */ + public static String getTagData(String xmlStr, String xmlRoot) { + String tags[] = getTagDataArray(xmlStr, xmlRoot); + if (tags.length > 0) { + return tags[0]; + } + return ""; + } + + public static int getTagIntData(String xmlStr, String xmlRoot) { + String tags[] = getTagDataArray(xmlStr, xmlRoot); + if (tags.length > 0) { + String intStr = tags[0]; + return (new Integer(intStr)).intValue(); + } + return 0; + } + + public static Boolean getTagBooleanData(String xmlStr, String xmlRoot) { + String tags[] = getTagDataArray(xmlStr, xmlRoot); + if (tags.length > 0) { + String intStr = tags[0]; + return (intStr.equals("true") ? true : false); + } + return false; + } + + /** + * Given text strings containing xml reserved characters, replace with valid xml representation characters > => & gt; < => & + * lt; & => & amp; ' => & apos; " => & quot; + * + * @param text text to be converted to valid XML representation characters + * @return String valid xml string + */ + public static String textToXml(String text) { + if (text == null || text.equals("")) return ""; + String str = new String(text); + str = str.replaceAll("&", "&"); + str = str.replaceAll(">", ">"); + str = str.replaceAll("<", "<"); + str = str.replaceAll("'", "'"); + str = str.replaceAll("\"", """); + return str; + } + + /** + * Given xml strings containing xml reserved characters, replace with displayable characters > <= & gt; < <= & lt; & <= & + * amp; ' <= & apos; " <= & quot; + * + * @param xml + * @return displayable string + */ + public static String xmlToText(String xml) { + if (xml == null || xml.equals("")) return ""; + String str = new String(xml); + str = str.replaceAll(">", ">"); + str = str.replaceAll("<", "<"); + str = str.replaceAll("'", "'"); + str = str.replaceAll(""", "\""); + str = str.replaceAll("&", "&"); + return str; + } + +} diff --git a/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/ByteUtil.java b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/ByteUtil.java new file mode 100644 index 00000000000..8204ebbeeb9 --- /dev/null +++ b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/ByteUtil.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.jdk.core.util; + +import java.io.PrintStream; +import java.nio.ByteBuffer; + +/** + * @author Ryan D. Brooks + * @author Andrew M. Finkbeiner + */ +public class ByteUtil { + + public static void printBinary(byte[] data, int bytesPerGroup, int groupPerLine, PrintStream out) { + int groups = 0; + for (int i = 0; i < data.length; i++) { + out.print(ByteUtil.toBinaryString(data[i])); + if ((i + 1) % bytesPerGroup == 0) { + out.print(" "); + groups++; + if ((groups) % groupPerLine == 0) { + out.println(); + } + } + } + } + + public static void printHex(byte[] data, int bytesPerGroup, int groupPerLine, PrintStream out) { + int groups = 0; + for (int i = 0; i < data.length; i++) { + out.print(ByteUtil.toHexString(data[i])); + if ((i + 1) % bytesPerGroup == 0) { + out.print(" "); + groups++; + if ((groups) % groupPerLine == 0) { + out.println(); + } + } + } + } + + public static void printHex(byte[] data, int bytesPerGroup, int groupPerLine, StringBuilder strBuilder) { + int groups = 0; + for (int i = 0; i < data.length; i++) { + strBuilder.append(ByteUtil.toHexString(data[i])); + if ((i + 1) % bytesPerGroup == 0) { + strBuilder.append(" "); + groups++; + } + } + } + + public static void printHex(byte[] data, int bytesPerGroup, int groupPerLine, boolean isSpaced, StringBuilder strBuilder) { + int groups = 0; + for (int i = 0; i < data.length; i++) { + strBuilder.append(ByteUtil.toHexString(data[i])); + if ((i + 1) % bytesPerGroup == 0 && isSpaced) { + strBuilder.append(" "); + groups++; + } + } + } + + /** + * NOTE the SDK supplies a Integer.toBinaryString but it is not formatted to a standard number of chars so it was not + * a good option. + * + * @param b + * @return String + */ + public static String toBinaryString(byte b) { + StringBuffer sb = new StringBuffer(); + sb.append(((b >> 7) & 0x01)); + sb.append(((b >> 6) & 0x01)); + sb.append(((b >> 5) & 0x01)); + sb.append(((b >> 4) & 0x01)); + sb.append(((b >> 3) & 0x01)); + sb.append(((b >> 2) & 0x01)); + sb.append(((b >> 1) & 0x01)); + sb.append((b & 0x01)); + return sb.toString(); + } + + public static byte[] toBytes(long n) { + byte[] bytes = new byte[8]; + toBytes(bytes, 0, n); + return bytes; + } + + public static void toBytes(byte[] bytes, int startPos, long n) { + for (int i = startPos + 7; i >= startPos; i--) { + bytes[i] = (byte) (n); + n >>>= 8; + } + } + + public static void toBytes(byte[] bytes, int startPos, int n) { + for (int i = startPos + 3; i >= startPos; i--) { + bytes[i] = (byte) (n); + n >>>= 8; + } + } + + public static String toHexString(byte b) { + String temp = Integer.toHexString(b); + if (temp.length() >= 2) + return temp.substring(temp.length() - 2).toUpperCase(); + else + return "0" + temp.substring(0).toUpperCase(); + } + + /** + * Build a long from first 8 bytes of the array. + * + * @param b The byte[] to convert. + * @return A long. + */ + public static long toLong(byte[] b) { + if (b.length != 8) { + throw new IllegalArgumentException(); + } + + return ((((long) b[7]) & 0xFF) + ((((long) b[6]) & 0xFF) << 8) + ((((long) b[5]) & 0xFF) << 16) + ((((long) b[4]) & 0xFF) << 24) + ((((long) b[3]) & 0xFF) << 32) + ((((long) b[2]) & 0xFF) << 40) + ((((long) b[1]) & 0xFF) << 48) + ((((long) b[0]) & 0xFF) << 56)); + } + + /** + * + */ + public ByteUtil() { + super(); + } + + /** + * writes message data to a buffer in hex format + * + * @param data + * @param offset + */ + public static void printByteDump(StringBuilder strBuilder, byte[] data, int offset, int length, int columnNum) { + printByteDump(strBuilder, data, offset, length, columnNum, true); + } + + /** + * writes message data to a buffer in hex format + * + * @param data + * @param offset + */ + public static void printByteDump(StringBuilder strBuilder, byte[] data, int offset, int length, int columnNum, boolean hex) { + int columnCount = 0; + final int endIndex = offset + length; + for (int i = offset; i < endIndex; i++) { + if (columnCount == columnNum) { + strBuilder.append('\n'); + columnCount = 0; + } + if (hex) { + strBuilder.append(String.format("%02x ", data[i])); + } else { + strBuilder.append(String.format("%d ", data[i])); + } + columnCount++; + } + strBuilder.append('\n'); + } + + public static void printByteDump(StringBuilder strBuilder, ByteBuffer data, int offset, int length, int columnNum) { + int currentPosition = data.position(); + // data.position(offset); + int columnCount = 0; + final int endIndex = offset + length; + for (int i = offset; i < endIndex; i++) { + if (columnCount == columnNum) { + strBuilder.append('\n'); + columnCount = 0; + } + strBuilder.append(String.format("%02x ", data.get(i))); + columnCount++; + } + strBuilder.append('\n'); + + data.position(currentPosition); + } + + public static void main(String[] args) { + System.out.println(ByteUtil.toHexString((byte) 128)); + } +}
\ No newline at end of file diff --git a/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/CmdLineArgs.java b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/CmdLineArgs.java new file mode 100644 index 00000000000..3b73e2ffaf0 --- /dev/null +++ b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/CmdLineArgs.java @@ -0,0 +1,43 @@ +/******************************************************************************* + * Copyright (c) 2004, 2007 Boeing. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Boeing - initial API and implementation + *******************************************************************************/ +package org.eclipse.osee.framework.jdk.core.util; + +import java.util.HashMap; + +public class CmdLineArgs { + + private HashMap<String, String> cmdArgs; + + public CmdLineArgs(String[] args) { + cmdArgs = new HashMap<String, String>(); + + for (int i = 0; i < args.length; i++) { + if (args[i].matches("-\\w.*")) { + if ((i + 1 < args.length) && (!args[i + 1].matches("-\\D.*"))) { + cmdArgs.put(args[i], args[i + 1]); + i++; + } else { + cmdArgs.put(args[i], null); + } + } else { + cmdArgs.put(args[i], null); + } + } + } + + public String get(String key) { + return cmdArgs.get(key); + } + + public HashMap<String, String> getArgs() { + return cmdArgs; + } +} diff --git a/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/Collections.java b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/Collections.java new file mode 100644 index 00000000000..57145bc6b11 --- /dev/null +++ b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/Collections.java @@ -0,0 +1,149 @@ +/******************************************************************************* + * Copyright (c) 2004, 2007 Boeing. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Boeing - initial API and implementation + *******************************************************************************/ +package org.eclipse.osee.framework.jdk.core.util; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Iterator; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Set; + +/** + * @author David Diepenbrock + */ +public class Collections { + + /** + * An flexible alternative for converting a Collection to a String. + * + * @param c The Collection to convert to a String + * @param start The String to place at the beginning of the returned String + * @param separator The String to place in between elements of the Collection c. + * @param end The String to place at the end of the returned String + * @return A String which starts with 'start', followed by the elements in the Collection c separated by 'separator', + * ending with 'end'. + */ + @SuppressWarnings("unchecked") + public static String toString(Collection c, String start, String separator, String end) { + Iterator i = c.iterator(); + StringBuilder myString = new StringBuilder(); + + if (start != null) myString.append(start); + + boolean first = true; + while (i.hasNext()) { + if (!first) myString.append(separator); + myString.append(i.next().toString()); + first = false; + } + + if (end != null) myString.append(end); + + return myString.toString(); + } + + public static String toString(String separator, Object... objects) { + Collection<Object> objectsCol = new ArrayList<Object>(objects.length); + for (Object obj : objects) + objectsCol.add(obj); + return toString(objectsCol, null, separator, null); + } + + @SuppressWarnings("unchecked") + public static String toString(String separator, Collection c) { + return toString(c, null, separator, null); + } + + /** + * The resultant set is those elements in superSet which are not in the subSet + * + * @param superSet + * @param subList + * @return Return complement list reference + */ + @SuppressWarnings("unchecked") + public static List setComplement(Collection superSet, Collection subList) { + ArrayList<Object> complement = new ArrayList<Object>(superSet.size()); + for (Object obj : superSet) { + if (!subList.contains(obj)) { + complement.add(obj); + } + } + return complement; + } + + /** + * @param listA + * @param listB + * @return The intersection of two sets A and B is the set of elements common to A and B + */ + @SuppressWarnings("unchecked") + public static ArrayList setIntersection(Collection listA, Collection listB) { + ArrayList<Object> intersection = new ArrayList<Object>(listA.size()); + + for (Object obj : listA) { + if (listB.contains(obj)) { + intersection.add(obj); + } + } + return intersection; + } + + @SuppressWarnings("unchecked") + public static Set toSet(Collection collection) { + Set set = null; + if (collection instanceof Set) { + set = (Set) collection; + } else { + set = new LinkedHashSet(); + set.addAll(collection); + } + return set; + } + + public static List<Object> getAggregateTree(List<Object> items, int maxPerList) { + if (items == null) throw new IllegalArgumentException("items can not be null"); + if (maxPerList < 2) throw new IllegalArgumentException("maxPerList can not be less than 2"); + + if (items.size() > maxPerList) { + return (recursiveAggregateTree(items, maxPerList)); + } else { + return new ArrayList<Object>(items); + } + } + + private static ArrayList<Object> recursiveAggregateTree(List<Object> items, int maxPerList) { + if (items.size() > maxPerList) { + ArrayList<Object> aggregateList = new ArrayList<Object>(maxPerList); + ArrayList<Object> childList = null; + + for (Object item : items) { + if (childList == null || childList.size() == maxPerList) { + childList = new ArrayList<Object>(maxPerList); + aggregateList.add(childList); + } + childList.add(item); + } + childList.trimToSize(); + + aggregateList = recursiveAggregateTree(aggregateList, maxPerList); + + aggregateList.trimToSize(); + + return aggregateList; + } else { + // This is a safe blind cast since only subsequent calls of this method will end up here + // and this method always uses ArrayList<Object> + return (ArrayList<Object>) items; + } + } +} diff --git a/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/Email.java b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/Email.java new file mode 100644 index 00000000000..56568bb2d30 --- /dev/null +++ b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/Email.java @@ -0,0 +1,58 @@ +/******************************************************************************* + * 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.jdk.core.util; + +import java.io.File; +import javax.mail.Message; +import javax.mail.MessagingException; + +public class Email { + + public Email() { + + } + + public void sendEmail(String email, String title, String message) throws MessagingException { + sendEmailWithAttachment(email, title, message, null); + } + + public void sendEmailWithAttachment(String email, String title, String message, File file) throws MessagingException { + sendEmailWithAttachments(email, title, message, new File[] {file}); + } + + public void sendEmailWithAttachment(String email, String title, String message, String content, String attachmentName) throws MessagingException { + AEmail emailMessage = createEmail(email, title, message); + emailMessage.addAttachment(content, attachmentName); + emailMessage.send(); + } + + public void sendEmailWithAttachments(String email, String title, String message, File[] files) throws MessagingException { + + AEmail emailMessage = createEmail(email, title, message); + + if (files != null) { + for (File file : files) + emailMessage.addAttachment(file); + } + + emailMessage.send(); + } + + private AEmail createEmail(String email, String title, String message) throws MessagingException { + + AEmail emailMessage = new AEmail(null, email, email, title); + emailMessage.setRecipients(Message.RecipientType.TO, email); + emailMessage.setRecipients(Message.RecipientType.CC, email); + emailMessage.setRecipients(Message.RecipientType.BCC, email); + emailMessage.addHTMLBody(message); + return emailMessage; + } +} diff --git a/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/EnumBase.java b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/EnumBase.java new file mode 100644 index 00000000000..b2efab52a0e --- /dev/null +++ b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/EnumBase.java @@ -0,0 +1,58 @@ +/******************************************************************************* + * 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.jdk.core.util; + +import javax.print.attribute.EnumSyntax; + +/** + * @author Ryan D. Brooks + * @author Andrew M. Finkbeiner + */ +public abstract class EnumBase extends EnumSyntax { + //TODO We need to possibly refactor getEnum and rework the structure of the enums??? + + protected abstract String[] getStringTable(); + + protected abstract EnumSyntax[] getEnumValueTable(); + + protected EnumBase(int value) { + + super(value); + } + + protected static EnumBase getEnum(String str, String[] stringTable, EnumBase[] enumValueTable) { + + for (int i = 0; i < stringTable.length; i++) { + if (stringTable[i].toUpperCase().equals(str.toUpperCase())) return enumValueTable[i]; + } + + throw new IllegalArgumentException("Not a valid enumeration name: " + str); + // TODO - We might want to come back and make this more efficient later!!! + // This was a binary search, but was changed because it was forcing the tables to have to be + // in the correct binary search order to work. + + } + + protected static EnumBase getEnum(int value, EnumBase[] enumValueTable) { + + return enumValueTable[value - enumValueTable[0].getValue()]; + } + + protected int getOffset() { + + return getEnumValueTable()[0].getValue(); + } + + public String getName() { + + return getStringTable()[getValue() - getOffset()]; + } +}
\ No newline at end of file diff --git a/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/Enums.java b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/Enums.java new file mode 100644 index 00000000000..341aeeeb36e --- /dev/null +++ b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/Enums.java @@ -0,0 +1,24 @@ +/******************************************************************************* + * 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.jdk.core.util; + +/** + * @author Donald G. Dunne + */ +public class Enums { + + public static String getCommaDeliminatedString(Enum<?>[] enums) { + StringBuffer sb = new StringBuffer(); + for (Enum<?> e : enums) + sb.append(e.name() + ","); + return sb.toString().replaceFirst(",$", ""); + } +} diff --git a/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/GUID.java b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/GUID.java new file mode 100644 index 00000000000..e3ef714b8a1 --- /dev/null +++ b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/GUID.java @@ -0,0 +1,109 @@ +/******************************************************************************* + * 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.jdk.core.util; + +import java.io.Serializable; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import sun.misc.CharacterEncoder; + +/** + * @author Ryan D. Brooks + * @author Robert A. Fisher + */ +public class GUID implements Serializable { + private final long time; + private final int hash; + private final int rand; + private final String guidString; + private static final long serialVersionUID = -3849714490764637010L; + + private static final ThreadLocal<byte[]> threadLocalBytes = new ThreadLocal<byte[]>() { + protected synchronized byte[] initialValue() { + return new byte[16]; + } + }; + + private static final ThreadLocal<CharacterEncoder> threadLocalEncoder = new ThreadLocal<CharacterEncoder>() { + protected synchronized CharacterEncoder initialValue() { + return new sun.misc.BASE64Encoder(); + } + }; + + public static boolean isValid(String guid) { + if (guid.length() != 22) { + return false; + } + Matcher m = Pattern.compile("^[0-9A-Za-z\\+_]+$").matcher(guid); + if (!m.find()) { + return false; + } + return true; + } + + public GUID() { + this(GUIDType.ARTIFACT); + } + + public GUID(GUIDType type) { + this.time = System.currentTimeMillis(); + this.hash = Thread.currentThread().hashCode(); + this.rand = (int) (Math.random() * Integer.MAX_VALUE); + + this.guidString = toGuidString(time, hash, rand, type); + } + + public static String generateGuidStr() { + return generateGuidStr(GUIDType.ARTIFACT); + } + + public static String generateGuidStr(GUIDType type) { + long time = System.currentTimeMillis(); + int hash = Thread.currentThread().hashCode(); + int rand = (int) (Math.random() * Integer.MAX_VALUE); + return toGuidString(time, hash, rand, type); + } + + private static String toGuidString(long time, int hash, int rand, GUIDType type) { + byte[] rawBytes = (byte[]) threadLocalBytes.get(); + ByteUtil.toBytes(rawBytes, 0, time); + ByteUtil.toBytes(rawBytes, 8, hash); + ByteUtil.toBytes(rawBytes, 12, rand); + + CharacterEncoder base64Encoder = (CharacterEncoder) threadLocalEncoder.get(); + /* + * 64 = 2^6 64^22 > 2^128 (2^6)^22 > 2^128 2^132 > 2^128 thus a 22 digit base64 number is + * needed to represent a 16 byte number + */ + return type + base64Encoder.encode(rawBytes).replace('/', '_').substring(1, 22); + } + + public boolean equals(Object other) { + + if (other instanceof GUID) { + return this.time == ((GUID) other).time && this.hash == ((GUID) other).hash && this.rand == ((GUID) other).rand; + } + + return false; + } + + public int hashCode() { + int result = 17; + result = result + (int) (time ^ (time >>> 32)); + result = 37 * result + hash; + result = 37 * result + rand; + return result; + } + + public String toString() { + return guidString; + } +}
\ No newline at end of file diff --git a/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/GUIDTest.java b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/GUIDTest.java new file mode 100644 index 00000000000..4ebf6c763cd --- /dev/null +++ b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/GUIDTest.java @@ -0,0 +1,30 @@ +/******************************************************************************* + * 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.jdk.core.util; + +public class GUIDTest { + + /** + * @param args + */ + public static void main(String[] args) { + + while (true) { + String g = GUID.generateGuidStr(); + if (g.substring(1, 2).matches("^[A-Za-z]{2}$")) { + System.err.println("ERROR " + g); + } else + System.out.println("g *" + g + "*"); + } + + } + +} diff --git a/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/GUIDType.java b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/GUIDType.java new file mode 100644 index 00000000000..5951d2ef84e --- /dev/null +++ b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/GUIDType.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.jdk.core.util; + +/** + * @author Robert A. Fisher + */ +public enum GUIDType { + ARTIFACT("A"), ARTIFACT_VERSION("B"); + + private final String prefixChar; + + private GUIDType(String prefixChar) { + this.prefixChar = prefixChar; + } + + public String toString() { + return prefixChar; + } +} diff --git a/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/IAbbreviated.java b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/IAbbreviated.java new file mode 100644 index 00000000000..9d4c307746c --- /dev/null +++ b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/IAbbreviated.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.jdk.core.util; + +/** + * An interface describing items that can provide an abbreviation name. + * + * @author Robert A. Fisher + */ +public interface IAbbreviated { + public String getAbbreviation(); +} diff --git a/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/IConsoleInputListener.java b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/IConsoleInputListener.java new file mode 100644 index 00000000000..072171025ed --- /dev/null +++ b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/IConsoleInputListener.java @@ -0,0 +1,15 @@ +/******************************************************************************* + * 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.jdk.core.util; + +public interface IConsoleInputListener { + void lineRead(String line); +} diff --git a/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/JarCreator.java b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/JarCreator.java new file mode 100644 index 00000000000..337813ad4b7 --- /dev/null +++ b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/JarCreator.java @@ -0,0 +1,122 @@ +/******************************************************************************* + * 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.jdk.core.util; + +import java.io.File; +import java.io.FileFilter; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.util.jar.Attributes; +import java.util.jar.JarEntry; +import java.util.jar.JarOutputStream; +import java.util.jar.Manifest; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * @author Ryan D. Brooks + * @author Andrew M. Finkbeiner + */ +public class JarCreator { + private JarOutputStream out; + private byte[] buffer; + + /** + * @throws IOException + * @throws FileNotFoundException + */ + public JarCreator(File path, String title, String version) throws FileNotFoundException, IOException { + super(); + Manifest manifest = new Manifest(); + Attributes attributes = manifest.getMainAttributes(); + attributes.put(Attributes.Name.MANIFEST_VERSION, "1.0"); + attributes.putValue("Implementation-Title", title); + attributes.putValue("Implementation-Version", version); + out = new JarOutputStream(new FileOutputStream(path), manifest); + buffer = new byte[20480]; + } + + private void addFile(File file, String pathInJar) throws IOException { + + out.putNextEntry(new JarEntry(pathInJar.replace('\\', '/'))); + + // Read the file and write it to the jar. + FileInputStream in = new FileInputStream(file); + int bytesRead; + while ((bytesRead = in.read(buffer)) != -1) { + out.write(buffer, 0, bytesRead); + } + in.close(); + } + + /** + * @param path + * @param rootPathPos + * @throws IOException + */ + private void addRelativeToPosition(File path, int rootPathPos, FileFilter filenameFilter) throws IOException { + if (path.isDirectory()) { + File[] files = path.listFiles(filenameFilter); + for (int i = 0; i < files.length; i++) { + addRelativeToPosition(files[i], rootPathPos, filenameFilter); + } + } else { + addFile(path, path.getAbsolutePath().substring(rootPathPos)); + } + } + + /** + * just an entry point into the recursive addRelativeTo so the (unchanging) rootPathPos can be computed once + */ + private void addDirectoryContents(File directory, FileFilter filenameFilter) throws IOException { + if (directory.isDirectory()) { + int rootPathPos = directory.getPath().length() + 1; + addRelativeToPosition(directory, rootPathPos, filenameFilter); + } else { + throw new IllegalArgumentException("Must be a directory: " + directory); + } + } + + public void addFileRelativeTo(File path, String relativeTo) throws IOException { + addRelativeToPosition(path, relativeTo.length() + 1, null); + } + + public void addDirectoryContents(File directory) throws IOException { + addDirectoryContents(directory, (FilenameAndDirectoryFilter) null); + } + + public void addDirectoryContents(File directory, String fileNamePattern) throws IOException { + addDirectoryContents(directory, new FilenameAndDirectoryFilter(fileNamePattern)); + } + + public void close() throws IOException { + out.close(); + } + + private class FilenameAndDirectoryFilter implements FileFilter { + private Matcher matcher; + + public FilenameAndDirectoryFilter(String pattern) { + this.matcher = Pattern.compile(pattern).matcher(""); + } + + public boolean accept(File pathname) { + if (pathname.isDirectory()) { + return true; + } + matcher.reset(pathname.getName()); + return matcher.matches(); + } + + } +} diff --git a/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/Lib.java b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/Lib.java new file mode 100644 index 00000000000..33a28586b3a --- /dev/null +++ b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/Lib.java @@ -0,0 +1,1329 @@ +/******************************************************************************* + * 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.jdk.core.util; + +import java.awt.Image; +import java.io.BufferedInputStream; +import java.io.BufferedOutputStream; +import java.io.BufferedReader; +import java.io.BufferedWriter; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.FileReader; +import java.io.FileWriter; +import java.io.FilenameFilter; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.OutputStream; +import java.io.OutputStreamWriter; +import java.io.PrintWriter; +import java.io.Reader; +import java.io.StringWriter; +import java.io.Writer; +import java.net.MalformedURLException; +import java.net.URL; +import java.net.URLConnection; +import java.nio.CharBuffer; +import java.security.CodeSource; +import java.security.ProtectionDomain; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.LinkedList; +import java.util.List; +import java.util.jar.Attributes; +import java.util.jar.JarEntry; +import java.util.jar.JarFile; +import java.util.jar.JarInputStream; +import java.util.jar.Manifest; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import java.util.zip.ZipEntry; +import java.util.zip.ZipInputStream; +import java.util.zip.ZipOutputStream; +import javax.swing.ImageIcon; +import org.eclipse.osee.framework.jdk.core.text.change.ChangeSet; +import org.eclipse.osee.framework.jdk.core.util.io.IOInputThread; +import org.eclipse.osee.framework.jdk.core.util.io.IOOutputThread; +import org.eclipse.osee.framework.jdk.core.util.io.InputBufferThread; +import org.eclipse.osee.framework.jdk.core.util.io.MatchFilter; + +/** + * @author Ryan D. Brooks + */ +public final class Lib { + public final static Runtime runtime = Runtime.getRuntime(); + + public final static String jarPath = getJarPath(Lib.class); + + public final static String basePath = getBasePath(); + + public final static String lineSeparator = System.getProperty("line.separator"); + + public static String toFirstCharUpperCase(String str) { + if (str == null) { + return null; + } + char[] chars = str.toCharArray(); + chars[0] = Character.toUpperCase(str.charAt(0)); + return new String(chars); + } + + public static int numOccurances(String str, String regex) { + int x = 0; + Matcher m = Pattern.compile(regex).matcher(str); + while (m.find()) + x++; + return x; + } + + public static String exceptionToString(Throwable ex) { + StringBuilder sb = new StringBuilder(); + exceptionToString(ex, sb); + return sb.toString(); + } + + public static boolean validateEmail(String toValidate) { + Pattern pattern = Pattern.compile( + "^[a-z0-9\\._-]" + "+@([a-z0-9][a-z0-9-]*" + "[a-z0-9]\\.)+" + "([a-z]+\\.)?([a-z]+)$", + Pattern.CASE_INSENSITIVE); + Matcher matcher = pattern.matcher(toValidate); + return matcher.find(); + } + + private static void exceptionToString(Throwable ex, StringBuilder sb) { + sb.append(ex.getMessage() + "\n"); + StackTraceElement st[] = ex.getStackTrace(); + for (int i = 0; i < st.length; i++) { + StackTraceElement ste = st[i]; + sb.append(" at " + ste.toString() + "\n"); + } + Throwable cause = ex.getCause(); + if (cause != null) { + sb.append(" caused by "); + exceptionToString(cause, sb); + } + } + + public static String changeExtension(String str, String newExt) { + int pos = str.lastIndexOf('.'); + if (pos == -1) { // was -1 before + 1 + return str + "." + newExt; + } + return str.substring(0, pos + 1) + newExt; + } + + /** + * this version of changeExtension will work even if the extension we want to replace contains a . + * + * @param str + * @param oldExt + * @param newExt + * @return String + */ + public static String changeExtension(String str, String oldExt, String newExt) { + int pos = str.lastIndexOf(oldExt); + if (pos == -1) { + return str + "." + newExt; + } + return str.substring(0, pos) + newExt; + } + + /** + * Move an object one before the previous object + * + * @param list + * @param obj + * @return true if successful + */ + public static boolean moveBack(ArrayList<Object> list, Object obj) { + if (list.contains(obj)) { + int index = list.indexOf(obj); + if (index > 0) { + list.remove(index); + list.add(index - 1, obj); + return true; + } + } + return false; + } + + /** + * Move an object one after the next object + * + * @param obj + * @return true if successful + */ + public static boolean moveForward(ArrayList<Object> list, Object obj) { + int size = list.size(); + if (list.contains(obj)) { + int index = list.indexOf(obj); + if (index < (size - 1)) { + list.remove(index); + list.add(index + 1, obj); + return true; + } + } + return false; + } + + public static void copyDirectory(File source, File destination) throws IOException { + File[] files = source.listFiles(); + + for (int i = 0; i < files.length; i++) { + if (files[i].isDirectory()) { + File dir = new File(destination, files[i].getName()); + dir.mkdir(); + copyDirectory(files[i], dir); + } else { // else is a file + copyFile(files[i], destination); + } + } + } + + public static String exceptionToString(Exception ex) { + StringWriter stringWriter = new StringWriter(); + PrintWriter printWriter = new PrintWriter(stringWriter); + ex.printStackTrace(printWriter); + return stringWriter.toString(); + } + + public static void copyFile(File source, File destination) throws IOException { + FileInputStream in = new FileInputStream(source); + FileOutputStream out = null; + + if (destination.isDirectory()) { + out = new FileOutputStream(new File(destination, source.getName())); + } else { + destination.delete(); // to work around some file permission + // problems + out = new FileOutputStream(destination); + } + + byte[] bytes = new byte[(int) source.length()]; + in.read(bytes); + out.write(bytes); + + in.close(); + out.close(); + } + + public static void copyFiles(File source, File destination) throws IOException { + copyFiles(source, null, destination); + } + + public static void copyFiles(File source, FilenameFilter filter, File destination) throws IOException { + File[] files = source.listFiles(filter); + if (!source.exists()) { + throw new IllegalArgumentException("the directory " + source + " does not exist."); + } + + if (files != null) { + for (int i = 0; i < files.length; i++) { + if (files[i].isFile()) { + copyFile(files[i], destination); + } + } + } + } + + public static Image createImage(String path) { + return createImageIcon(path).getImage(); + } + + public static ImageIcon createImageIcon(Class<?> clasaRef, String path) { + URL imgURL = clasaRef.getResource(path); + if (imgURL != null) { + return new ImageIcon(imgURL); + } else { + System.err.println("Couldn't find the resource: " + path); + return null; + } + } + + /** Returns an ImageIcon, or null if the path was invalid. */ + public static ImageIcon createImageIcon(String path) { + return createImageIcon(Lib.class, path); + } + + public static void deleteDir(File directory) { + File[] files = directory.listFiles(); + if (files == null) { + return; + } + + for (int i = 0; i < files.length; i++) { + if (files[i].isDirectory()) { + deleteDir(files[i]); + } else { // else is a file + files[i].delete(); + } + } + directory.delete(); + } + + public static void deleteContents(File directory) { + deleteContents(directory, null); + } + + public static void deleteContents(File directory, FilenameFilter filter) { + File[] files = directory.listFiles(filter); + + for (int i = 0; i < files.length; i++) { + if (files[i].isDirectory()) { + deleteContents(files[i]); + } + files[i].delete(); + } + } + + public static String inputStreamToString(InputStream in) throws IOException { + return inputStreamToStringBuffer(in).toString(); + } + + public static StringBuffer inputStreamToStringBuffer(InputStream in) throws IOException { + InputStreamReader reader = new InputStreamReader(in, "UTF-8"); + StringBuffer strB = new StringBuffer(1000); + char[] chars = new char[1000]; + int readCount = 0; + while ((readCount = reader.read(chars)) != -1) { + strB.append(chars, 0, readCount); + } + return strB; + } + + public static byte[] inputStreamToBytes(InputStream in) throws IOException { + byte[] bytes = new byte[2024]; + ByteArrayOutputStream out = new ByteArrayOutputStream(2024); + + int numBytesRead; + while ((numBytesRead = in.read(bytes)) != -1) { + out.write(bytes, 0, numBytesRead); + } + return out.toByteArray(); + } + + public static void inputStreamToFile(InputStream in, File outFile) throws IOException { + byte[] bytes = new byte[2024]; + FileOutputStream out = new FileOutputStream(outFile); + + int numBytesRead; + while ((numBytesRead = in.read(bytes)) != -1) { + out.write(bytes, 0, numBytesRead); + } + out.close(); + } + + public static CharBuffer inputStreamToCharBuffer(InputStream in) throws IOException { + StringBuffer strB = inputStreamToStringBuffer(in); + char[] chars = new char[strB.length()]; + strB.getChars(0, strB.length(), chars, 0); + return CharBuffer.wrap(chars); + } + + public static java.io.InputStream stringToInputStream(String xml) throws Exception { + if (xml == null) return null; + xml = xml.trim(); + java.io.InputStream in = null; + in = new java.io.ByteArrayInputStream(xml.getBytes("UTF-8")); + return in; + } + + public static String fileToString(File file) throws IOException { + Reader in = new InputStreamReader(new FileInputStream(file), "UTF-8"); + char[] chars = new char[(int) file.length()]; + in.read(chars); + in.close(); + return new String(chars); + } + + public static byte[] fileToBytes(File file) throws IOException { + InputStream inputStream = new FileInputStream(file); + byte[] bytes = new byte[(int) file.length()]; + inputStream.read(bytes); + inputStream.close(); + return bytes; + } + + /** + * usage: char[] buf = new char[5500000]; for (Iterator iter = files.iterator(); iter.hasNext(); ) { // for each file + * File file = (File)iter.next(); buf = Lib.fileToChars(file, buf); + * + * @param file + * @param buf + * @return char[] + * @throws IOException + */ + public static char[] fileToChars(File file, char[] buf) throws IOException { + FileReader in = new FileReader(file); + int size = (int) file.length(); + + if (buf == null) { + buf = new char[size]; + } else if (size > buf.length) { + buf = null; + System.gc(); // since the currently allocated buf might already + // be quite large + buf = new char[size]; + } + + in.read(buf); + in.close(); + return buf; + } + + public static CharBuffer fileToCharBuffer(File file) throws IOException { + FileReader in = new FileReader(file); + char[] chars = new char[(int) file.length()]; + in.read(chars); + in.close(); + return CharBuffer.wrap(chars); + } + + public static String fillString(char c, int n) { + char[] chars = new char[n]; + for (int i = 0; i < n; chars[i++] = c) { + // must leave empty block here so the following line won't become + // part of the loop + } + return new String(chars); + } + + public static String getExtension(String str) { + return str.substring(str.lastIndexOf('.') + 1); + } + + public static int handleProcess(Process proc) { + return handleProcess(proc, new PrintWriter(System.out, true)); + } + + public static int handleProcess(Process proc, Writer output, String errName, String outName) { + return handleProcess(proc, output, errName, outName, true); + } + + public static int handleProcess(Process proc, Writer output, String errName, String outName, boolean verbose) { + try { + IOOutputThread errThread = new IOOutputThread(output, new BufferedReader(new InputStreamReader( + proc.getErrorStream())), verbose); + IOOutputThread outThread = new IOOutputThread(output, new BufferedReader(new InputStreamReader( + proc.getInputStream())), verbose); + + errThread.setName(errName); + outThread.setName(outName); + errThread.start(); + outThread.start(); + proc.waitFor(); + int exitCode = proc.exitValue(); + if (exitCode != 0) { + output.write("Process exit code is: " + exitCode + "\n"); + } + int count = 0; + while (errThread.isAlive() || outThread.isAlive()) { + if (count > 10) break; + synchronized (Thread.currentThread()) { + Thread.currentThread().wait(500); + } + count++; + } + output.flush(); + return exitCode; + } catch (IOException ex) { + System.err.println(ex); + } catch (InterruptedException e) { + e.printStackTrace(); + } + return Integer.MIN_VALUE; + } + + public static int handleProcess(Process proc, Writer output) { + return handleProcess(proc, output, "err", "out"); + } + + public static int handleProcess(Process proc, Writer output, boolean verbose) { + return handleProcess(proc, output, "err", "out", verbose); + } + + /** + * Sets up an error, input, and output stream for the given process. The error stream gives all information coming + * FROM the process through it's err stream. The "outThread" will be what come from the FROM the process through it's + * normal output stream. The "inThread" is the stream for issuing commands TO the process. + * + * @param proc The process whose streams we are setting up + * @param output Where all info coming FROM the minicom is sent + * @param input Where all data going TO the minicom is sent + * @return An array of threads in the following order:<br> + * --index 0 = Err Stream<br> + * --index 1 = output stream<br> + * --index 2 = input stream<br> + */ + public static Thread[] handleMinicomProcess(Process proc, Writer output, Reader input) { + IOOutputThread errThread = new IOOutputThread(output, new BufferedReader(new InputStreamReader( + proc.getErrorStream()))); + + InputBufferThread outThread = new InputBufferThread(new BufferedReader(new InputStreamReader( + proc.getInputStream()))); + + errThread.setName("err"); + outThread.setName("out"); + errThread.start(); + outThread.start(); + + if (input != null) { + IOInputThread inThread = new IOInputThread(input, new BufferedWriter(new OutputStreamWriter( + proc.getOutputStream()))); + inThread.setName("in"); + inThread.start(); + return new Thread[] {errThread, outThread, inThread}; + } + return new Thread[] {errThread, outThread}; + } + + public static Thread[] handleProcessNoWait(Process proc, Writer output) { + return handleProcessNoWait(proc, output, output, null); + } + + public static Thread[] handleProcessNoWait(Process proc, Writer output, boolean verbose) { + return handleProcessNoWait(proc, output, output, null, "err", "out", verbose); + } + + public static Thread[] handleProcessNoWait(Process proc, Writer output, Writer errorWriter, Reader reader) { + return handleProcessNoWait(proc, output, errorWriter, reader, "err", "out", true); + } + + public static Thread[] handleProcessNoWait(Process proc, Writer outputWriter, Writer errorWriter, Reader reader, String errName, String outName) { + return handleProcessNoWait(proc, outputWriter, errorWriter, reader, errName, outName, true); + } + + public static Thread[] handleProcessNoWait(Process proc, Writer outputWriter, Writer errorWriter, Reader reader, String errName, String outName, boolean verbose) { + IOOutputThread errThread = new IOOutputThread(errorWriter, new BufferedReader(new InputStreamReader( + proc.getErrorStream())), verbose); + IOOutputThread outThread = new IOOutputThread(outputWriter, new BufferedReader(new InputStreamReader( + proc.getInputStream())), verbose); + errThread.setName(errName); + outThread.setName(outName); + errThread.start(); + outThread.start(); + if (reader != null) { + IOInputThread inThread = new IOInputThread(reader, new BufferedWriter(new OutputStreamWriter( + proc.getOutputStream()))); + inThread.setName("in"); + inThread.start(); + return new Thread[] {errThread, outThread, inThread}; + } + return new Thread[] {errThread, outThread}; + } + + public static void makeDirClean(File directory) { + if (directory.exists()) { + Lib.deleteContents(directory); + } else { + directory.mkdir(); + } + } + + public static void moveFiles(File source, File destination) { + moveFiles(source, null, destination); + } + + public static void moveFiles(File source, FilenameFilter filter, File destination) { + File[] files = source.listFiles(filter); + + for (int i = 0; i < files.length; i++) { + if (files[i].isFile()) { + files[i].renameTo(new File(destination, files[i].getName())); + } + } + } + + public static String padLeading(String str, char c, int n) { + char[] chars = new char[n]; + int pos = Math.min(n, str.length()); + str.getChars(0, pos, chars, n - pos); + for (int i = 0; i < n - pos; chars[i++] = c) { + // must leave empty block here so the following line won't become + // part of the loop + } + return new String(chars); + } + + public static String padTrailing(String str, char c, int n) { + char[] chars = new char[n]; + int pos = Math.min(n, str.length()); + str.getChars(0, pos, chars, 0); + for (int i = pos; i < n; chars[i++] = c) { + // must leave empty block here so the following line won't become + // part of the loop + } + return new String(chars); + } + + public static int printAndExec(String[] callAndArgs) { + return printAndExec(callAndArgs, null, new BufferedWriter(new PrintWriter(System.out, true))); + } + + public static int printAndExec(String[] callAndArgs, File dir) { + return printAndExec(callAndArgs, dir, new PrintWriter(System.out, true)); + } + + public static int printAndExec(String[] callAndArgs, File dir, Writer output) { + try { + for (int j = 0; j < callAndArgs.length; j++) { + output.write(callAndArgs[j] + " "); + } + output.write("\n"); + output.flush(); + + return Lib.handleProcess(runtime.exec(callAndArgs, null, dir), output); + } catch (IOException ex) { + System.err.println("error: " + ex); + return -1; + } + } + + public static ArrayList<String> readListFromDir(File directory, FilenameFilter filter, boolean keepExtension) { + ArrayList<String> list = new ArrayList<String>(400); + + if (directory == null) { + System.out.println("Invalid path: " + directory); + return list; + } + + File[] files = directory.listFiles(filter); + if (files == null) { + System.out.println("Invalid path: " + directory); + return list; + } + if (files.length > 0) { + Arrays.sort(files); + } + + if (keepExtension) { + for (int i = 0; i < files.length; i++) { + list.add(files[i].getName()); + } + } else { + for (int i = 0; i < files.length; i++) { + list.add(Lib.stripExtension(files[i].getName())); + } + } + + return list; + } + + public static ArrayList<String> readListFromDir(String directory, FilenameFilter filter) { + return readListFromDir(new File(directory), filter, false); + } + + public static ArrayList<String> readListFromFile(File file, boolean keepExtension) throws IOException { + BufferedReader in = new BufferedReader(new FileReader(file)); + ArrayList<String> list = new ArrayList<String>(120); + + String line = null; + + if (keepExtension) { + while ((line = in.readLine()) != null) { + list.add(line); + } + } else { + while ((line = in.readLine()) != null) { + list.add(Lib.stripExtension(line)); + } + } + in.close(); + return list; + } + + public static ArrayList<String> readListFromFile(String file) throws IOException { + return readListFromFile(new File(file), true); + } + + public static boolean isLink(File file) { + if (!file.exists()) { + return true; + } + try { + return !file.getAbsolutePath().equals(file.getCanonicalPath()); + } catch (IOException ex) { + return true; + } + } + + public static List<File> recursivelyListFilesAndDirectories(ArrayList<File> fileList, File rootPath, Pattern fileNameP, boolean includeDirectories) { + LinkedList<File> dirList = new LinkedList<File>(); + dirList.add(rootPath); + + Matcher fileNameM = null; + if (fileNameP != null) { + fileNameM = fileNameP.matcher(""); + } + + while (!dirList.isEmpty()) { + File parent = dirList.removeFirst(); + if (parent == null) { + System.out.println("Invalid path."); + continue; + } + + if (parent.getName().startsWith(".Rational")) { + continue; + } + + File[] files = parent.listFiles(); + if (files == null) { + System.out.println("Invalid path: " + parent); + continue; + } + + for (int i = 0; i < files.length; i++) { + if (files[i].isDirectory()) { + dirList.add(files[i]); + if (includeDirectories) { + fileList.add(files[i]); + } + } else { // else is a file + if (fileNameM == null) { + fileList.add(files[i]); + } else { + fileNameM.reset(files[i].getPath()); + if (fileNameM.matches()) { + fileList.add(files[i]); + } + } + } + } + } + return fileList; + } + + /** + * Returns an array list of File objects + * + * @param fileList + * @param rootPath + * @param fileNameP + * @return List + */ + public static List<File> recursivelyListFiles(ArrayList<File> fileList, File rootPath, Pattern fileNameP) { + return recursivelyListFilesAndDirectories(fileList, rootPath, fileNameP, false); + } + + public static List<File> recursivelyListFiles(File rootPath, Pattern fileNameP) { + return recursivelyListFiles(new ArrayList<File>(400), rootPath, fileNameP); + } + + /** + * Assumptions: block comments are not nested and comment blocks have an ending Note: may be fooled by string + * literals that contains the block comment indicators + * + * @param charBuf + * @return CharBuffer + */ + public static CharBuffer stripBlockComments(CharBuffer charBuf) { + char[] chars = charBuf.array(); + int i = 0; + int k = 0; + + try { + while (i < chars.length) { + if (chars[i] == '/' && chars[i + 1] == '*') { + i += 2; + while (!(chars[i++] == '*' && chars[i] == '/')) { + // must leave empty block here so the following line + // won't become part of the loop + } + i++; + } else { + chars[k++] = chars[i++]; + } + } + charBuf.limit(k); + return charBuf; + } catch (ArrayIndexOutOfBoundsException ex) { + throw new IllegalArgumentException("Incorrectly formatted comments."); + } + } + + public static String stripExtension(String str) { + int pos = str.lastIndexOf('.'); + if (pos == -1) { + return str; + } + return str.substring(0, pos); + } + + // replaces the first capturing group of the match in fileToModify with + // replaceSeq and write this back to fileToModify + public static boolean updateFile(File fileToModify, Pattern pattern, CharSequence replaceSeq) throws IOException { + CharBuffer modifyBuf = Lib.fileToCharBuffer(fileToModify); + + Matcher matcher = pattern.matcher(modifyBuf); + if (!matcher.find()) { + System.out.println(fileToModify.getPath() + " does not contain the pattern: " + pattern.pattern()); + return false; + } + CharBuffer topSection = (CharBuffer) modifyBuf.subSequence(0, matcher.start(1)); // everything + // before the + // pattern + CharBuffer bottomSection = null; + int bottomLen = 0; + if (matcher.end(1) != modifyBuf.length()) { + bottomSection = (CharBuffer) modifyBuf.subSequence(matcher.end(1), modifyBuf.length()); + bottomLen = bottomSection.length(); + } + + CharBuffer outBuf = CharBuffer.allocate(topSection.length() + replaceSeq.length() + bottomLen); + outBuf.put(topSection); + if (replaceSeq instanceof String) { + outBuf.put((String) replaceSeq); + } else if (replaceSeq instanceof CharBuffer) { + outBuf.put((CharBuffer) replaceSeq); + } else { + outBuf.put(replaceSeq.toString()); + } + if (bottomSection != null) { + outBuf.put(bottomSection); + } + Lib.writeCharBufferToFile(outBuf, fileToModify); + + return true; + } + + public static boolean updateFile(File fileToModify, Pattern pattern, File original) throws IOException { + return updateFile(fileToModify, pattern, fileToCharBuffer(original)); + } + + public static void writeCharBufferToFile(CharBuffer charBuf, File outFile) throws IOException { + FileWriter out = new FileWriter(outFile); + out.write(charBuf.array(), 0, charBuf.limit()); + out.close(); + } + + /** + * test the underlying system's timing precision + * + * @param args + */ + public static void main(String[] args) { + // long[] times = new long[1000]; + // + // times[0] = System.nanoTime(); + // for (int i = 1; i < times.length; i++) { + // times[i] = times[i - 1]; + // // Busy wait until system time changes: + // while (times[i] == times[i - 1]) { + // times[i] = System.nanoTime(); + // } + // } + // + // for (int i = 1; i < times.length; i++) { + // System.out.println(times[i] - times[i - 1]); + // } + + try { + String toCompress = ";laksdjf;aljkd;lfajds;ljfa;jdsf;lajdsfja;dsjfa;"; + System.out.println(toCompress.length()); + byte[] compressed = Lib.compressFile(new ByteArrayInputStream(toCompress.getBytes())); + byte[] decompressed = Lib.decompressBytes(compressed); + System.out.println(compressed.length); + System.out.println(decompressed.length); + } catch (IOException e) { + e.printStackTrace(); + } + + } + + public static String getBasePath() { + return Lib.getBasePath(Lib.class); + } + + public static String getJarPath(Class<Lib> base) { + // the leading '/' tells getResource not to append the package name + // (instead the leading / is just stripped off) + String className = "/" + base.getName().replace('.', '/') + ".class"; + String path = base.getResource(className).getPath(); + + int pos = path.lastIndexOf("!"); + if (pos == -1) { // class is not in a jar file + return null; + } else { // class is in a jar file + String jarpath = path.substring("file:".length(), pos); + return jarpath.replaceAll("%20", " "); + } + } + + /** + * @param base + * @return The path which was used to load the class file. If the file was loaded from a .jar, then the full path to + * the jar. If the file was loaded from a .class, then the path up to the root of the package. + */ + public static String getClassLoadPath(Class<?> base) { + /* + * Using the getProtectionDomain() method seems to be yield more consistent results than + * getResource(className).getPath(); particularly when being run with the Eclipse class + * loader. It was found that the Eclipse class loader did not always return the full path when + * asked for the resource. + */ + + ProtectionDomain pd = base.getProtectionDomain(); + CodeSource cs = pd.getCodeSource(); + URL csLoc = cs.getLocation(); + String path = csLoc.getPath(); + path = path.replaceAll("%20", " "); + return path; + } + + public static String getBasePath(Class<?> base) { + String path = getClassLoadPath(base); + path = path.replaceAll("%20", " "); + + if (path.endsWith(".jar")) { + int end = path.lastIndexOf('/'); + path = path.substring(0, end); + } + return path; + + } + + public static URL resolveToUrl(String path) { + URL url = null; + System.out.println("resolveToUrl: " + path); + if (path != null && !path.equals("")) { + if (path.indexOf("://") == -1) { // if not a full URL yet + if (!path.startsWith("/")) { // if not absolute then prepend + // base path + try { + path = new File(Lib.basePath + "/" + path).getCanonicalPath(); + } catch (IOException e) { + e.printStackTrace(); + } + } + path = "file://" + path; + } + try { + url = new URL(path); + } catch (MalformedURLException ex) { + ex.printStackTrace(); + } + } + return url; + } + + public static String escapeForRegex(String text) { + char[] chars = text.toCharArray(); + StringBuffer strB = new StringBuffer(chars.length + 5); + + for (int i = 0; i < chars.length; i++) { + switch (chars[i]) { + case '\\': + case '[': + case ']': + case '.': + case '{': + case '}': + case '^': + case '$': + case '?': + case '*': + case '+': + case '|': + strB.append('\\'); + } + strB.append(chars[i]); + } + return strB.toString(); + } + + public static String determineGroup() { + try { + Process proc = Runtime.getRuntime().exec( + new String[] {"/usr/bin/bash", "-c", "touch whichGroup; ls -g whichGroup; rm whichGroup"}, null, + new File("/tmp")); + BufferedReader inOutput = new BufferedReader(new InputStreamReader(proc.getInputStream())); + String line = inOutput.readLine(); + return line.substring(15, line.indexOf(' ', 16)); // 15 based on + // format of + // line printed + // by ls + } catch (IOException ex) { + System.out.println(ex); + return "no group"; + } + } + + /** + * Returns a list of the arguments in the source String passed. It assumes that the first character is a '(' and + * matches till it finds the matching ')'. + * + * @param source + * @return String[] + */ + public static String[] getArguments(String source) { + ArrayList<String> theResults = new ArrayList<String>(); + try { + if (source.charAt(0) != '(') { + System.err.println("In getArguments, first char must be \'(\'."); + return null; + } + + int currentArg = 1; + int startPos = 1; + int parens = 0; + boolean foundValidChar = false; + + for (int i = 1; i < source.length(); i++) { + char theChar = source.charAt(i); + + if (theChar == '(') + parens++; + else if (theChar == ')') { + parens--; + if (parens < 0) { + theResults.add(source.substring(startPos, i)); + break; + } + } else if (theChar == ',' && parens == 0) { + theResults.add(source.substring(startPos, i)); + startPos = i + 1; + currentArg++; + foundValidChar = false; + } else if (!foundValidChar) { + if (Character.isWhitespace(theChar)) + startPos++; + else + foundValidChar = true; + } + } + + String[] theTrueResults = new String[theResults.size()]; + theResults.toArray(theTrueResults); + + if (theTrueResults.length != currentArg) System.err.println("In getArguments, number of argument mismatch."); + + return theTrueResults; + } catch (Exception e) { + e.printStackTrace(); + return null; + } + } + + public static int getArgsLength(String source) { + try { + if (source.charAt(0) != '(') { + System.err.println("In getArguments, first char must be \'(\'."); + return -1; + } + int parens = 0; + + for (int i = 1; i < source.length(); i++) { + char theChar = source.charAt(i); + + if (theChar == '(') + parens++; + else if (theChar == ')') { + parens--; + if (parens < 0) { + return i - 1; + } + } + } + + System.err.println("In getArguments, problem occurred."); + return -1; + } catch (Exception e) { + e.printStackTrace(); + return -1; + } + } + + /** + * Returns a list of Strings representing each comma separated string in the string passed. It ignores commas inside () + * or {}. + * + * @param source + * @return String[] + */ + public static String[] getCommaSeparatedItems(String source) { + ArrayList<String> theResults = new ArrayList<String>(); + int startPos = 0; + int parensCount = 0; + + for (int i = 0; i < source.length(); i++) { + char theChar = source.charAt(i); + + if (theChar == '(' || theChar == '{') + parensCount++; + else if (theChar == ')' || theChar == '}') + parensCount--; + else if (parensCount == 0 && theChar == ',') { + theResults.add(source.substring(startPos, i).trim()); + startPos = i + 1; + } + } + theResults.add(source.substring(startPos).trim()); + String[] results = new String[theResults.size()]; + theResults.toArray(results); + return results; + } + + /** + * Finds the index of the closing bracket for a function. + * + * @param start -the index of the character AFTER the opening bracket for the function + * @param seq -sequence containing the local function + * @return -the index of the matching bracket to the opening bracket of this function + */ + public static int findTheEnd(int start, CharSequence seq) { + int stack = 1; + char[] array = seq.subSequence(start, seq.length()).toString().toCharArray(); + int i; + // print( "checking: " + seq.subSequence(start, + // seq.length()).toString()); + for (i = 0; i < array.length; i++) { + // System.out.print( array[i]); + if (array[i] == '/' && array[i + 1] == '*') { + + while (array[i] != '*' || array[i + 1] != '/') { + i++; + } + } + if (array[i] == '"') { + i++; + while (array[i] != '"' || array[i - 1] == '\\') { + i++; + } + } + if (array[i] == '{') { + stack++; + + } else if (array[i] == '}') { + stack--; + + } + if (stack == 0) { + return start + i - 1; + } + } + return start + i - 1; + + } + + public static final URL getUrlFromString(String path) throws MalformedURLException { + if (!path.matches("(file://|http://|C:).*")) { + return new URL("file://" + path); + } + return new URL(path); + } + + public static final URL[] getUrlFromString(String[] path) throws MalformedURLException { + URL[] urls = new URL[path.length]; + for (int i = 0; i < urls.length; i++) { + urls[i] = getUrlFromString(path[i]); + } + return urls; + } + + public static final String convertToJavaClassName(String name) { + ChangeSet changeSet = new ChangeSet(name); + Matcher matcher = Pattern.compile("_([a-zA-Z])").matcher(changeSet.toString()); + + changeSet.replace(0, 1, Character.toUpperCase(name.charAt(0))); + while (matcher.find()) + changeSet.replace(matcher.start(), matcher.end(), Character.toUpperCase(matcher.group(1).charAt(0))); + + return changeSet.applyChangesToSelf().toString(); + } + + public static URL getJarFileURL(File directory, String title, String version) throws IOException { + if (!directory.isDirectory()) { + throw new IllegalArgumentException(directory.getPath() + " is not a valid directory."); + } + File[] jars = directory.listFiles(new MatchFilter(".*\\.jar")); + for (int i = 0; i < jars.length; i++) { + JarFile jar = new JarFile(jars[i]); + Attributes attributes = jar.getManifest().getMainAttributes(); + String jarTitle = attributes.getValue("Implementation-Title"); + String jarVersion = attributes.getValue("Implementation-Version"); + if (jarTitle != null && jarVersion != null && jarTitle.equals(title) && jarVersion.equals(version)) { + return jars[i].toURL(); + } + } + throw new IllegalArgumentException("The specified version: " + version + " for " + title + " was not found."); + } + + public static URL[] getClasspath() throws MalformedURLException { + String[] strPaths = System.getProperty("java.class.path").split(System.getProperty("path.separator")); + URL[] urlPaths = new URL[strPaths.length]; + for (int i = 0; i < strPaths.length; i++) { + urlPaths[i] = new File(strPaths[i]).toURL(); + } + return urlPaths; + } + + public static String getJarFileVersion(String jarFilePath) throws IOException { + Manifest manifest; + File jarFile = new File(jarFilePath); + if (!jarFile.isFile()) {// maybe it's an http connection + try { + URL u = new URL(jarFilePath); + URLConnection uc = u.openConnection(); + JarInputStream jis = new JarInputStream(uc.getInputStream()); + manifest = jis.getManifest(); + } catch (Exception ex) { + throw new IllegalArgumentException(jarFilePath + " is not a valid file or URL."); + } + } else { + manifest = new JarFile(jarFile).getManifest(); + } + return manifest.getMainAttributes().getValue("Implementation-Version"); + } + + public static String getElapseString(long startTime) { + return String.valueOf((System.currentTimeMillis() - startTime) / 1000.0) + " secs"; + } + + public static boolean isWindows() { + return System.getProperty("os.name").indexOf("indows") != -1; + } + + public static void writeBytesToFile(byte[] data, File file) throws IOException { + OutputStream os = new FileOutputStream(file); + os.write(data); + os.close(); + } + + public static void extractJarEntry(File jarFile, File destination, String entry) throws IOException { + if (!destination.getParentFile().exists()) { + destination.getParentFile().mkdirs(); + } + int BUFFER = 2048; + try { + JarFile jarfile = new JarFile(jarFile.getAbsolutePath()); + JarEntry jarEntry = jarfile.getJarEntry(entry); + BufferedInputStream is = new BufferedInputStream(jarfile.getInputStream(jarEntry)); + int count; + long total = 0; + byte data[] = new byte[BUFFER]; + FileOutputStream fos = new FileOutputStream(destination); + BufferedOutputStream dest = new BufferedOutputStream(fos, BUFFER); + while ((count = is.read(data, 0, BUFFER)) != -1) { + dest.write(data, 0, count); + total += BUFFER; + } + dest.flush(); + dest.close(); + is.close(); + } catch (Exception ex) { + String information = "JarFile: " + (jarFile != null ? jarFile.getAbsolutePath() : "NULL") + "\n" + "Entry: " + (entry != null ? entry.toString() : "NULL") + "\n" + "Destination: " + (destination != null ? destination.getAbsoluteFile().toString() : "NULL") + "\n"; + throw new IOException(information + ex.getMessage()); + } + } + + public static byte[] compressFile(InputStream in) throws IOException { + // Create a buffer for reading the files + byte[] buf = new byte[1024]; + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + ZipOutputStream out = new ZipOutputStream(bos); + + // Add ZIP entry to output stream. + out.putNextEntry(new ZipEntry(in.toString())); + + // Transfer bytes from the file to the ZIP file + int len; + while ((len = in.read(buf)) > 0) { + out.write(buf, 0, len); + } + + out.closeEntry(); + in.close(); + + // Complete the ZIP file + out.close(); + + return bos.toByteArray(); + } + + public static byte[] compressFile(File file) throws IOException { + // Create a buffer for reading the files + byte[] buf = new byte[1024]; + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + ZipOutputStream out = new ZipOutputStream(bos); + FileInputStream in = new FileInputStream(file); + + // Add ZIP entry to output stream. + out.putNextEntry(new ZipEntry(file.getName())); + + // Transfer bytes from the file to the ZIP file + int len; + while ((len = in.read(buf)) > 0) { + out.write(buf, 0, len); + } + + out.closeEntry(); + in.close(); + + // Complete the ZIP file + out.close(); + + return bos.toByteArray(); + } + + public static byte[] decompressBytes(byte[] bytes) throws IOException { + ByteArrayOutputStream out = null; + // Open the ZIP file + ZipInputStream in = new ZipInputStream(new ByteArrayInputStream(bytes)); + + // Get the first entry + in.getNextEntry(); + + // Open the output file + out = new ByteArrayOutputStream(); + + // Transfer bytes from the ZIP file to the output file + byte[] buf = new byte[1024]; + int len; + while ((len = in.read(buf)) > 0) { + out.write(buf, 0, len); + } + + // Close the streams + out.close(); + in.close(); + return out.toByteArray(); + } + + public static void chmod777(File file) { + if (file == null || !file.exists()) return; + try { + String command = "chmod 777 " + file.getAbsolutePath(); + Runtime r = Runtime.getRuntime(); + Process p = r.exec(command); + + Lib.handleProcess(p); + } catch (IOException ioe) { + ioe.printStackTrace(); + } + } + + public static String getSortedJavaArrayInitializer(String[] strings) { + Arrays.sort(strings); + StringBuilder strB = new StringBuilder(); + strB.append("new String[] {\""); + for (String element : strings) { + strB.append(element); + strB.append("\", \""); + } + strB.replace(strB.length() - 3, strB.length(), "};"); + return strB.toString(); + } +}
\ No newline at end of file diff --git a/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/Network.java b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/Network.java new file mode 100644 index 00000000000..9f6485404aa --- /dev/null +++ b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/Network.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.jdk.core.util; + +import java.net.InetAddress; +import java.net.UnknownHostException; + +public class Network { + + public static InetAddress getValidIP() throws UnknownHostException { + InetAddress[] addrs; + // Cannot just grab the localhost address because the user might have more than one NIC. + addrs = getLocalNetworkAdapters(); + + for (int j = 0; j < addrs.length; j++) { + if (!addrs[j].getHostAddress().matches("192.*")) { + return addrs[j]; + } + } + return addrs[0]; + } + + public static InetAddress[] getLocalNetworkAdapters() throws UnknownHostException { + return InetAddress.getAllByName(InetAddress.getLocalHost().getHostName()); + } +} diff --git a/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/Objects.java b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/Objects.java new file mode 100644 index 00000000000..0fc6e834c72 --- /dev/null +++ b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/Objects.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.jdk.core.util; + +/** + * Utility class for methods useful to all Object's + * + * @author Robert A. Fisher + */ +public final class Objects { + + /** + * Produces a hash code that uses all of the supplied values. This method is guaranteed to return the same value + * given the same input. + * + * @param PRIME_1 + * @param PRIME_2 + * @param data + */ + public static int hashCode(int PRIME_1, int PRIME_2, Object... data) { + int result = PRIME_1; + + for (Object val : data) { + result = PRIME_2 * result + val.hashCode(); + } + + return result; + } + +} diff --git a/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/OseeProperties.java b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/OseeProperties.java new file mode 100644 index 00000000000..226db4cda51 --- /dev/null +++ b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/OseeProperties.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.jdk.core.util; + +import java.util.logging.Logger; + +public class OseeProperties { + + public static final String OSEE_CONFIG_FACTORY = "OseeConfigFactory"; + public static final String OSEE_AUTHENTICATION_PROVIDER_ID = "OseeAuthenticationProviderId"; + public static final String OSEE_CONFIG_FILE = "OseeConfig"; + public static final String DEFAULT_DB_CONNECTION = "DefaultDbConnection"; + public static final String OSEE_IMPORT_FROM_DB_SERVICE = "OseeImportFromDbService"; + public static final String OSEE_TIMING_LOG = "OseeTimingLog"; + public static final String OSEE_BENCHMARK = "osee.benchmark"; + public static final String OSEE_JINI_SERVICE_GROUPS = "osee.jini.lookup.groups"; + public static final String OSEE_CMD_CONSOLE = "osee.cmd.console"; + public static final String OSEE_HTTP_PORT = "osee.http.port"; + public static final String OSEE_DEVELOPER = "Developer"; + + public static final String OSEE_NO_PROMPT = "OseeNoPrompt"; + private static final String OSEE_USE_FILE_SPECIFIED_SCHEMAS = "OseeUseFileSpecifiedSchemas"; + private static final String PRINT_SQL = "PrintSql"; + private static final String DONT_LOG_USAGE = "DontLogUsage"; + private static final String OSEE_DB_CONFIG_INIT_CHOICE = "osee.db.config.init.choice"; + + private static OseeProperties instance = null; + private static Logger logger = null; + + private OseeProperties() { + if (logger == null) { + logger = Logger.getLogger("org.eclipse.osee.framework.jdk.core.util.OseeProperties"); + } + } + + public static OseeProperties getInstance() { + if (instance == null) { + instance = new OseeProperties(); + } + return instance; + } + + public String[] getOseeJiniServiceGroups() { + String serviceGroup = System.getProperty(OSEE_JINI_SERVICE_GROUPS); + // String[] filterGroups = null; + if (serviceGroup != null && serviceGroup.length() > 0) { + String[] values = serviceGroup.split(","); + for (int index = 0; index < values.length; index++) { + values[index] = values[index].trim(); + } + return values; + } + + // if (filterGroups == null) { + // filterGroups = ConfigUtil.getConfigFactory().getOseeConfig().getJiniServiceGroups(); + // } + // if (filterGroups == null || filterGroups.length > 0) { + // logger.log(Level.SEVERE, "[-D" + OseeProperties.OSEE_JINI_SERVICE_GROUPS + "] was not + // set.\n" + // + "Please enter the Jini Group this service register with."); + // System.exit(1); + // } + return null; + } + + public boolean isAtsUseWorkflowFiles() { + return System.getProperty("AtsUseWorkflowFiles") != null; + } + + public boolean isAtsAdmin() { + return System.getProperty("AtsAdmin") != null; + } + + public boolean isDeveloper() { + return System.getProperty(OSEE_DEVELOPER) != null || isAtsAdmin(); + } + + public String getAuthenticationProviderId() { + return System.getProperty(OSEE_AUTHENTICATION_PROVIDER_ID); + } + + public boolean isAtsShowUser() { + return System.getProperty("AtsShowUser") != null; + } + + public boolean isAtsIgnoreConfigUpgrades() { + return System.getProperty("AtsIgnoreConfigUpgrades") != null; + } + + public boolean isAtsDisableEmail() { + return System.getProperty("AtsDisableEmail") != null; + } + + public boolean isAtsAlwaysEmailMe() { + return System.getProperty("AtsAlwaysEmailMe") != null; + } + + public boolean isEmailMe() { + return System.getProperty("EmailMe") != null; + } + + public boolean isPromptEnabled() { + return !getBooleanProperty(OSEE_NO_PROMPT); + } + + public boolean useSchemasSpecifiedInDbConfigFiles() { + return getBooleanProperty(OSEE_USE_FILE_SPECIFIED_SCHEMAS); + } + + public boolean isPrintSqlEnabled() { + return System.getProperty(PRINT_SQL) != null; + } + + public boolean isUsageLoggingEnabled() { + return System.getProperty(DONT_LOG_USAGE) == null; + } + + private boolean getBooleanProperty(String key) { + String propertyValue = System.getProperty(key, "false"); + if (propertyValue != null && propertyValue.equalsIgnoreCase("true")) { + return true; + } + return false; + } + + public String getDBConfigInitChoice() { + return System.getProperty(OSEE_DB_CONFIG_INIT_CHOICE, ""); + } + + public void setDBConfigInitChoice(String value) { + System.setProperty(OSEE_DB_CONFIG_INIT_CHOICE, value); + } +} diff --git a/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/OseeUser.java b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/OseeUser.java new file mode 100644 index 00000000000..c248106b475 --- /dev/null +++ b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/OseeUser.java @@ -0,0 +1,24 @@ +/******************************************************************************* + * 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.jdk.core.util; + +/** + * @author Andrew M. Finkbeiner + */ +public interface OseeUser { + String getEmail(); + + String getName(); + + String getUserID(); + + boolean isActive(); +} diff --git a/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/PersistenceMemo.java b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/PersistenceMemo.java new file mode 100644 index 00000000000..8cc5df3eb84 --- /dev/null +++ b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/PersistenceMemo.java @@ -0,0 +1,27 @@ +/******************************************************************************* + * Copyright (c) 2004, 2007 Boeing. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Boeing - initial API and implementation + *******************************************************************************/ +package org.eclipse.osee.framework.jdk.core.util; + +/** + * Implemented by items that store persistence layer specific information. These items can then be attached to + * persistable items to the persistence manager can place implementation specific data on the object that it needs to + * function properly.<br/><br/> One example of information stored in such an item would be unique database id's that + * the persistence layer will use for identifying the item in the database. Storing this in the memo allows the + * persisted object class to remain unchanged if the persistence manager is changed out.<br/><br/> Only the + * persistence manager that places a particular memo on an object should ever read it off the object and use it since + * the persistence memos are only intended to remove the implementation details that are specific to a particular + * persistence manager design. + * + * @author Robert A. Fisher + */ +public interface PersistenceMemo { + +} diff --git a/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/PersistenceObject.java b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/PersistenceObject.java new file mode 100644 index 00000000000..484e670d5f0 --- /dev/null +++ b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/PersistenceObject.java @@ -0,0 +1,32 @@ +/******************************************************************************* + * 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.jdk.core.util; + +/** + * Implemented by objects that are handled by a persistence manager. + * + * @author Robert A. Fisher + */ +public interface PersistenceObject { + + /** + * @return The <code>PersistenceMemo</code> set on this object. + */ + public PersistenceMemo getPersistenceMemo(); + + /** + * Set the persistence memo for this object. This should only be called by the persistence manager that is handling + * this object. + * + * @param memo The persistence memo to assign to this object. + */ + public void setPersistenceMemo(PersistenceMemo memo); +} diff --git a/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/Readers.java b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/Readers.java new file mode 100644 index 00000000000..0a3ebcf8181 --- /dev/null +++ b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/Readers.java @@ -0,0 +1,149 @@ +/******************************************************************************* + * Copyright (c) 2004, 2007 Boeing. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Boeing - initial API and implementation + *******************************************************************************/ +package org.eclipse.osee.framework.jdk.core.util; + +import java.io.IOException; +import java.io.Reader; +import java.util.Arrays; + +/** + * @author Robert A. Fisher + */ +public final class Readers { + + /** + * Forward a reader until just after the balanced close of the given xml element name. It is assumed that the + * balanced open end of the element was just read off of the reader. + * + * @param reader The reader to pull the data from + * @param appendable If supplied, all data read from the reader is appended to the appendable + * @param elementName The name of the element, including the namespace if applicable + * @throws IllegalArgumentException If reader is null + * @throws IllegalArgumentException If elementName is null + * @throws IllegalStateException If the balanced closing tag is not found before the reader is emptied + * @throws IOException + */ + public static final void xmlForward(Reader reader, Appendable appendable, CharSequence elementName) throws IOException { + if (reader == null) throw new IllegalArgumentException("reader can not be null"); + if (elementName == null) throw new IllegalArgumentException("elementName can not be null"); + + final String CLOSE_TAG = "</" + elementName + ">"; + final String EMPTY_TAG = "<" + elementName + "/>"; + final String OPEN_TAG = "<" + elementName + ">"; + final String OPEN_TAG_WITH_ATTR = "<" + elementName + " "; + final CharSequence[] TAGS = new CharSequence[] {CLOSE_TAG, EMPTY_TAG, OPEN_TAG, OPEN_TAG_WITH_ATTR}; + + int elementDepthCount = 1; + StringBuilder read = null; + if (appendable != null) { + read = new StringBuilder(); + } + + CharSequence stopTag; + + while (elementDepthCount > 0) { + if ((stopTag = forward(reader, appendable, TAGS)) == null) { + throw new IllegalStateException("end of reader met when expecting an end of a tag"); + } + + if (stopTag == CLOSE_TAG) { + elementDepthCount--; + } else if (stopTag == OPEN_TAG) { + elementDepthCount++; + } else if (stopTag == OPEN_TAG_WITH_ATTR) { + if (forward(reader, (Appendable) read, ">") == null) { + throw new IllegalStateException("end of reader met when expecting >"); + } + + if (!read.toString().endsWith("/>")) { + elementDepthCount++; + } + + if (appendable != null) { + appendable.append(read); + read.setLength(0); + } + } else if (stopTag == EMPTY_TAG) { + // no effect on the stack count + } else { + throw new IllegalStateException("unexpected element returned"); + } + } + } + + /** + * Forward a reader to just after the specified CharSequence. + * + * @return The sequence that was found which stopped the forwarding. A null is returned if no sequence was found + * @throws IOException + * @throws IllegalArgumentException if any parameter is null + * @throws IllegalArgumentException if any of the sequences elements are length zero + */ + public static final CharSequence forward(Reader reader, CharSequence... sequences) throws IOException { + return forward(reader, null, sequences); + } + + /** + * Forward a reader to just after the specified CharSequence. If an appendable is supplied then all characters + * consumed from the reader will be appended to the appendable. + * + * @return The sequence that was found which stopped the forwarding. A null is returned if no sequence was found + * @throws IOException + * @throws IllegalArgumentException if reader is null + * @throws IllegalArgumentException if sequences is null + * @throws IllegalArgumentException if any of the sequences elements are length zero + */ + public static final CharSequence forward(Reader reader, Appendable appendable, CharSequence... sequences) throws IOException { + if (reader == null) throw new IllegalArgumentException("reader can not be null"); + if (sequences == null) throw new IllegalArgumentException("sequences can not be null"); + if (sequences.length == 0) throw new IllegalArgumentException("must provide at least one sequence"); + + // Precalculate all of the lengths and check for unacceptable data + int[] lengths = new int[sequences.length]; + for (int x = 0; x < sequences.length; x++) { + if (sequences[x] == null) { + throw new IllegalArgumentException("character sequence can not be null"); + } + + lengths[x] = sequences[x].length(); + + if (lengths[x] == 0) { + throw new IllegalArgumentException("character sequence can not have length zero"); + } + } + + int[] seqIndex = new int[sequences.length]; + Arrays.fill(seqIndex, 0); + + char[] buffer = new char[1]; + + while (reader.read(buffer) != -1) { + if (appendable != null) { + appendable.append(buffer[0]); + } + + for (int x = 0; x < sequences.length; x++) { + // Check if the last value read is inline with the next valid character for the sequence + if (sequences[x].charAt(seqIndex[x]) == buffer[0]) { + seqIndex[x]++; + // Check if the whole sequence has been detected in the stream + if (seqIndex[x] == lengths[x]) { + return sequences[x]; + } + } else { + seqIndex[x] = 0; + } + } + } + + return null; + } +} diff --git a/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/RegExpressLib.java b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/RegExpressLib.java new file mode 100644 index 00000000000..d313e0f8ae6 --- /dev/null +++ b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/RegExpressLib.java @@ -0,0 +1,40 @@ +/******************************************************************************* + * Copyright (c) 2004, 2007 Boeing. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Boeing - initial API and implementation + *******************************************************************************/ +package org.eclipse.osee.framework.jdk.core.util; + +import java.util.regex.Pattern; + +/** + * @author Andy Jury + */ + +public class RegExpressLib { + + public static final Pattern findRegExpressNotInComment(String str) { + + String notInComment = "(?:/\\*.*?\\*/)"; + + return Pattern.compile(notInComment + "|" + str, Pattern.DOTALL); + } + + public static final Pattern findRegExpressNotInQuotes(String str) { + + String notInQuotes = "(?:\".*?[^\\\\]\")"; + + return Pattern.compile(notInQuotes + "|" + str); + } + + public static final Pattern findCMathFunctionNotInQuotes(String str) { + + return findRegExpressNotInQuotes("[^.\\w](" + str + "\\s*?)\\(.*?"); + } + +} diff --git a/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/Sets.java b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/Sets.java new file mode 100644 index 00000000000..dab3f7048c5 --- /dev/null +++ b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/Sets.java @@ -0,0 +1,45 @@ +/******************************************************************************* + * Copyright (c) 2004, 2007 Boeing. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Boeing - initial API and implementation + *******************************************************************************/ +package org.eclipse.osee.framework.jdk.core.util; + +import java.util.HashSet; +import java.util.Set; + +/** + * Utility methods for <code>Set</code>'s. + * + * @author Robert A. Fisher + */ +public class Sets { + + /** + * Compute the intersection of two sets, and return the resulting set. + * + * @throws IllegalArgumentException if either argument is null. + */ + public static <A extends Object> Set<A> intersect(Set<A> set1, Set<A> set2) { + if (set1 == null) throw new IllegalArgumentException("set1 can not be null."); + if (set2 == null) throw new IllegalArgumentException("set2 can not be null."); + + Set<A> intersection = new HashSet<A>(); + + // Pick the smaller of the two sets as this will be the largest + // possible intersection. + boolean set1Larger = set1.size() > set2.size(); + Set<A> baseSet = set1Larger ? set2 : set1; + Set<A> otherSet = set1Larger ? set1 : set2; + + for (A item : baseSet) + if (otherSet.contains(item)) intersection.add(item); + + return intersection; + } +} diff --git a/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/StringDataSource.java b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/StringDataSource.java new file mode 100644 index 00000000000..4085c0e4c45 --- /dev/null +++ b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/StringDataSource.java @@ -0,0 +1,50 @@ +/******************************************************************************* + * 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.jdk.core.util; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import javax.activation.DataSource; + +public class StringDataSource implements DataSource { + + private String data; + private String name; + + /** + * @param data + * @param name + */ + public StringDataSource(String data, String name) { + super(); + this.data = data; + this.name = name; + } + + public String getContentType() { + return "text/plain"; + } + + public InputStream getInputStream() throws IOException { + return new ByteArrayInputStream(data.getBytes()); + } + + public String getName() { + return name; + } + + public OutputStream getOutputStream() throws IOException { + throw new UnsupportedOperationException(); + } + +} diff --git a/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/StringFormat.java b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/StringFormat.java new file mode 100644 index 00000000000..8a2c9c3b78f --- /dev/null +++ b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/StringFormat.java @@ -0,0 +1,58 @@ +/******************************************************************************* + * 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.jdk.core.util; + +import java.util.List; + +public class StringFormat { + + public static String separateWith(String[] items, String separateWith) { + StringBuilder string = new StringBuilder(); + boolean first = true; + for (String item : items) { + if (first) + first = false; + else + string.append(separateWith); + string.append(item); + } + + return string.toString(); + } + + public static String commaSeparate(String[] items) { + return separateWith(items, ","); + } + + public static String listToCommaSeparatedString(List<String> list) { + return commaSeparate(list.toArray(new String[list.size()])); + } + + public static String listToValueSeparatedString(List<String> list, String value) { + return separateWith(list.toArray(new String[list.size()]), value); + } + + public static String padWithLeadingZeroes(String toPad, int length) { + char[] charArray = new char[20]; + int charArrayIndex = charArray.length - 1; + for (int index = toPad.length() - 1; index >= 0; index--, charArrayIndex--) { + charArray[charArrayIndex] = toPad.charAt(index); + } + for (; charArrayIndex >= 0; charArrayIndex--) { + charArray[charArrayIndex] = '0'; + } + return new String(charArray); + } + + public static String truncate(String str, int length) { + return str.substring(0, Math.min(length, str.length())); + } +} diff --git a/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/Strings.java b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/Strings.java new file mode 100644 index 00000000000..fded4f893b0 --- /dev/null +++ b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/Strings.java @@ -0,0 +1,31 @@ +/******************************************************************************* + * 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.jdk.core.util; + +/** + * @author Jeff C. Phillips + */ +public class Strings { + + public static String truncate(String string, int length) { + + if (string.length() > length) { + return string.substring(0, length); + } + + return string; + } + + public static boolean isValid(String value) { + return value != null && value.length() > 0; + } +} diff --git a/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/ThreadKeyLocal.java b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/ThreadKeyLocal.java new file mode 100644 index 00000000000..e7ca34dd266 --- /dev/null +++ b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/ThreadKeyLocal.java @@ -0,0 +1,65 @@ +/******************************************************************************* + * Copyright (c) 2004, 2007 Boeing. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Boeing - initial API and implementation + *******************************************************************************/ +package org.eclipse.osee.framework.jdk.core.util; + +import java.util.HashMap; +import java.util.Map; + +/** + * @author Jeff C. Phillips + * @author Robert A. Fisher + */ +public class ThreadKeyLocal<K, T> { + + private ThreadLocal<Map<K, T>> keyToValueMaps = new ThreadLocal<Map<K, T>>() { + + /* + * (non-Javadoc) + * + * @see java.lang.ThreadLocal#initialValue() + */ + @Override + protected Map<K, T> initialValue() { + return new HashMap<K, T>(); + } + }; + + public T get(K key) { + Map<K, T> map = keyToValueMaps.get(); + + T value = map.get(key); + + if (value == null) { + value = initialValue(); + map.put(key, value); + } + + return value; + } + + public void remove(K key) { + keyToValueMaps.get().remove(key); + } + + public void set(K key, T value) { + keyToValueMaps.get().put(key, value); + } + + /** + * Typically an anonymous inner class will be used and this method will be overridden to provide desired initial + * value. + * + * @return Returns value + */ + protected T initialValue() { + return null; + } +} diff --git a/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/benchmark/Benchmark.java b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/benchmark/Benchmark.java new file mode 100644 index 00000000000..45baa8667fd --- /dev/null +++ b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/benchmark/Benchmark.java @@ -0,0 +1,263 @@ +/******************************************************************************* + * 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.jdk.core.util.benchmark; + +import java.text.MessageFormat; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Vector; +import org.eclipse.osee.framework.jdk.core.util.OseeProperties; + +/** + * Takes time measurements and provides some simple statistics. Useful for determining elapsed time between two points + * in frequently executed code.<BR> + * <P> + * <B>NOTE: </B>To enable benchmarking the JVM argument -Dosee.benchmark must be specified otherwise this code does + * nothing + * + * @author Ken J. Aguilar + */ +public class Benchmark { + + public static final boolean BENCHMARKS_ENABLED = System.getProperty(OseeProperties.OSEE_BENCHMARK) != null ? true : false; + + private final long threshold; + private long totalSamples; + private long startTime; + private long totalTime; + private long exceedCount; + private long longestSample; + private long shortestSample; + private long totalExceedAmount; + private static final Vector<Benchmark> list = new Vector<Benchmark>(16); + private final HashMap<String, Integer> exceeders = new HashMap<String, Integer>(100); + private final String name; + + public Benchmark(String name) { + this(name, Long.MAX_VALUE); + } + + /** + * @param threshold if samples exceed this time (in microseconds) then the exceed count will be incremented + */ + public Benchmark(String name, long threshold) { + this.name = name; + synchronized (list) { + list.add(this); + } + this.threshold = threshold; + totalSamples = 0; + totalTime = 0; + exceedCount = 0; + longestSample = 0; + shortestSample = Long.MAX_VALUE; + startTime = Long.MIN_VALUE; + totalExceedAmount = 0; + } + + public static void resetAll() { + synchronized (list) { + for (Benchmark bm : list) { + bm.totalSamples = 0; + bm.totalTime = 0; + bm.exceedCount = 0; + bm.longestSample = 0; + bm.shortestSample = Long.MAX_VALUE; + bm.startTime = Long.MIN_VALUE; + bm.totalExceedAmount = 0; + bm.exceeders.clear(); + } + } + + } + + /** + * Begins the sample + */ + public void startSample() { + if (!BENCHMARKS_ENABLED) return; + startSample(System.nanoTime()); + } + + public void startSample(long time) { + if (!BENCHMARKS_ENABLED) return; + startTime = time; + } + + public void samplePoint() { + if (!BENCHMARKS_ENABLED) return; + samplePoint(System.nanoTime()); + } + + /** + * Measures time between sample points + */ + public void samplePoint(long time) { + if (!BENCHMARKS_ENABLED) return; + if (startTime == Long.MIN_VALUE) { + // this is the first time samplePoint was called + startTime = time; + } else { + final long duration = (time - startTime) / 1000; + totalTime += duration; + if (duration > threshold) { + exceedCount++; + totalExceedAmount += threshold - duration; + } + if (duration > longestSample) { + longestSample = duration; + } + if (duration < shortestSample) { + shortestSample = duration; + } + + totalSamples++; + startTime = time; + } + } + + public boolean endSample() { + if (!BENCHMARKS_ENABLED) return false; + return endSample(System.nanoTime()); + } + + /** + * Ends the sample. Measures the elapsed time between the start of the sample and the time this method is called. + */ + public boolean endSample(long time) { + boolean exceeded = false; + if (!BENCHMARKS_ENABLED) return exceeded; + final long duration = (time - startTime) / 1000; + totalTime += duration; + if (duration > threshold) { + exceedCount++; + totalExceedAmount += threshold - duration; + exceeded = true; + } + if (duration > longestSample) { + longestSample = duration; + } + if (duration < shortestSample) { + shortestSample = duration; + } + + totalSamples++; + return exceeded; + } + + /** + * @return the number of samples that exceeded the threshold + */ + public long getExceedCount() { + return exceedCount; + } + + /** + * @return the longest sample in microseconds + */ + public long getLongestSample() { + return longestSample; + } + + /** + * @return the threshold value in microseconds. If no threshold was set this will return <CODE>Long.MAX_VALUE</CODE> + */ + public long getThreshold() { + return threshold; + } + + /** + * @return the total samples taken + */ + public long getTotalSamples() { + return totalSamples; + } + + /** + * @return the average of the samples in microseconds + */ + public long getAverage() { + if (totalSamples > 0) { + return totalTime / totalSamples; + } else { + return Long.MAX_VALUE; + } + } + + /** + * @return the shortest sample taken in microseconds + */ + public long getShortestSample() { + return shortestSample; + } + + public String getName() { + return name; + } + + public long getAverageExceedAmount() { + if (exceedCount == 0) { + return 0; + } + return Math.abs(totalExceedAmount / exceedCount); + } + + public static void main(String[] args) { + Benchmark bm = new Benchmark("unit test", 10000); + + // System.out.printf("benchmarking is %s\n", BENCHMARKS_ENABLED ? "enabled" : "disabled"); + if (BENCHMARKS_ENABLED) + System.out.println("benchmarking is enabled"); + else + System.out.println("benchmarking is disabled"); + for (int i = 0; i < 1000; i++) { + bm.startSample(); + try { + Thread.sleep((i % 2) == 0 ? 5 : 10); + } catch (InterruptedException ex) { + ex.printStackTrace(); + } + bm.endSample(); + } + + // Sorry Need to keep this java 1.4 compatible + Object[] formatArgs = {new Long(bm.getTotalSamples()), new Float(bm.getLongestSample() / 1000), + new Float(bm.getShortestSample() / 1000), new Float(bm.getAverage() / 1000), new Long(bm.getExceedCount())}; + MessageFormat outmessage = new MessageFormat( + "total samples: {0,number,integer}, max time: {1,number,integer}ms, min: {2,number,integer}ms, average: {3,number,integer}ms, exceed count: {4,number,integer}"); + + System.out.println(outmessage.format(formatArgs)); + + } + + public void addExceeder(String exceeder) { + Integer c = exceeders.get(exceeder); + if (c == null) { + exceeders.put(exceeder, 1); + } else { + exceeders.put(exceeder, c + 1); + } + } + + public Collection<Map.Entry<String, Integer>> getExceeders() { + return exceeders.entrySet(); + } + + public static List<Benchmark> getAllBenchamrks() { + synchronized (list) { + return new ArrayList<Benchmark>(list); + } + } + +} diff --git a/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/images/Pawprint.jpg b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/images/Pawprint.jpg Binary files differnew file mode 100644 index 00000000000..06752a1ec52 --- /dev/null +++ b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/images/Pawprint.jpg diff --git a/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/images/done.gif b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/images/done.gif Binary files differnew file mode 100644 index 00000000000..e4247311cd1 --- /dev/null +++ b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/images/done.gif diff --git a/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/images/go.gif b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/images/go.gif Binary files differnew file mode 100644 index 00000000000..7b177f0035a --- /dev/null +++ b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/images/go.gif diff --git a/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/images/not_done.gif b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/images/not_done.gif Binary files differnew file mode 100644 index 00000000000..68d265f91b6 --- /dev/null +++ b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/images/not_done.gif diff --git a/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/io/CharBackedInputStream.java b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/io/CharBackedInputStream.java new file mode 100644 index 00000000000..c44067f78af --- /dev/null +++ b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/io/CharBackedInputStream.java @@ -0,0 +1,186 @@ +/******************************************************************************* + * 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.jdk.core.util.io; + +import java.io.IOException; +import java.io.InputStream; +import java.io.Writer; +import java.nio.BufferUnderflowException; +import java.nio.ByteBuffer; +import java.nio.CharBuffer; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.Charset; +import java.nio.charset.CharsetEncoder; +import java.util.LinkedList; + +/** + * @author Ryan D. Brooks + */ +public class CharBackedInputStream extends InputStream implements Appendable { + //don't change!!!! this is for java 1.4 compatability + //private LinkedList<ByteBuffer> backers; + private LinkedList<ByteBuffer> backers; + private ByteBuffer currentBacker; + private CharsetEncoder encoder; + private Writer writer; + + /** + * @author Ryan D. Brooks + */ + public class InputStreamWriter extends Writer { + + public InputStreamWriter() { + super(); + } + + /** + * @param lock + */ + public InputStreamWriter(Object lock) { + super(lock); + } + + /* (non-Javadoc) + * @see java.io.Writer#write(char[], int, int) + */ + public void write(char[] cbuf, int off, int len) throws IOException { + addBackingSource(cbuf, off, len); + } + + /* (non-Javadoc) + * @see java.io.Flushable#flush() + */ + public void flush() throws IOException { + } + + /* (non-Javadoc) + * @see java.io.Closeable#close() + */ + public void close() throws IOException { + } + + public void write(CharSequence str) throws CharacterCodingException { + addBackingSource(str); + } + + public void write(String str, int off, int len) throws CharacterCodingException { + addBackingSource(str, off, len); + } + } + + /** + * @throws CharacterCodingException + */ + public CharBackedInputStream(CharBuffer source, String encodingName) throws CharacterCodingException { + super(); + this.encoder = Charset.forName(encodingName).newEncoder(); + this.backers = new LinkedList<ByteBuffer>(); + if (source != null) { + addBackingSource(source); + } + } + + public CharBackedInputStream() throws CharacterCodingException { + this((CharBuffer) null, "UTF-8"); + } + + public CharBackedInputStream(CharSequence backingStr) throws CharacterCodingException { + this(backingStr, "UTF-8"); + } + + public CharBackedInputStream(char[] backingChars) throws CharacterCodingException { + this(backingChars, "UTF-8"); + } + + public CharBackedInputStream(char[] backingChars, String encodingName) throws CharacterCodingException { + this(CharBuffer.wrap(backingChars), encodingName); + } + + public CharBackedInputStream(CharSequence backingStr, String encodingName) throws CharacterCodingException { + this(CharBuffer.wrap(backingStr), encodingName); + } + + public void addBackingSource(CharSequence backingStr) throws CharacterCodingException { + addBackingSource(CharBuffer.wrap(backingStr)); + } + + public void addBackingSource(CharSequence backingStr, int off, int len) throws CharacterCodingException { + addBackingSource(CharBuffer.wrap(backingStr.subSequence(off, len + off))); + } + + public void addBackingSource(char[] chars, int off, int len) throws CharacterCodingException { + addBackingSource(CharBuffer.wrap(chars, off, len)); + } + + public void addBackingSource(char[] chars) throws CharacterCodingException { + addBackingSource(CharBuffer.wrap(chars)); + } + + public void addBackingSource(CharBuffer source) throws CharacterCodingException { + ByteBuffer buffer = encoder.encode(source); + if (currentBacker == null) { + currentBacker = buffer; + } else { + backers.add(buffer); + } + } + + /* + * (non-Javadoc) + * + * @see java.io.InputStream#read() + */ + public int read() throws IOException { + if (currentBacker == null) { + return -1; + } + try { + return currentBacker.get(); + } catch (BufferUnderflowException ex) { + currentBacker = backers.poll(); + return read(); + } + } + + /** + * @return Returns the writer. + */ + public Writer getWriter() { + if (writer == null) { + writer = new InputStreamWriter(); + } + return writer; + } + + /* (non-Javadoc) + * @see java.lang.Appendable#append(java.lang.CharSequence) + */ + public Appendable append(CharSequence csq) throws IOException { + addBackingSource(csq); + return this; + } + + /* (non-Javadoc) + * @see java.lang.Appendable#append(java.lang.CharSequence, int, int) + */ + public Appendable append(CharSequence csq, int start, int end) throws IOException { + addBackingSource(csq, start, end - start); + return this; + } + + /* (non-Javadoc) + * @see java.lang.Appendable#append(char) + */ + public Appendable append(char c) throws IOException { + throw new UnsupportedOperationException( + "doing this one character at a time would be so inefficient it would defeat the whole purpose of this class"); + } +}
\ No newline at end of file diff --git a/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/io/CsvReader.java b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/io/CsvReader.java new file mode 100644 index 00000000000..0260cf9e3ef --- /dev/null +++ b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/io/CsvReader.java @@ -0,0 +1,148 @@ +/******************************************************************************* + * 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.jdk.core.util.io; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; +import java.io.Reader; +import java.io.StreamTokenizer; +import java.util.Arrays; + +/** + * @author Ryan D. Brooks + */ +public class CsvReader { + private Reader reader; + private StreamTokenizer streamTokenizer; + private boolean[] fieldsUsed; + private int fieldCount; + private String[] nextRow; + + /** + * @param file a comma separate value file + * @param totalNumFields the largest number of fields on any row (whether they are used or not) + * @param enabled whether to enable or disable all the feilds initially + * @throws IOException + */ + public CsvReader(File file, int totalNumFields, boolean enabled) throws IOException { + this(new BufferedReader(new FileReader(file)), totalNumFields, enabled); + } + + /** + * All fields will be enabled initially + * + * @param file a comma separate value file + * @param totalNumFields the largest number of fields on any row (whether they are used or not) + * @throws IOException + */ + public CsvReader(File file, int totalNumFields) throws IOException { + this(new BufferedReader(new FileReader(file)), totalNumFields); + } + + public CsvReader(Reader reader, int totalNumFields) throws IOException { + this(reader, totalNumFields, true); + } + + public CsvReader(Reader reader, int totalNumFields, boolean enabled) throws IOException { + this.reader = reader; + this.streamTokenizer = new StreamTokenizer(reader); + this.fieldsUsed = new boolean[totalNumFields]; + Arrays.fill(fieldsUsed, enabled); + countFieldsUsed(); + + streamTokenizer.resetSyntax(); + streamTokenizer.eolIsSignificant(true); + streamTokenizer.whitespaceChars(0, ' ' - 1); + streamTokenizer.wordChars(' ', 255); // make all non-white space characters part of the returned string + streamTokenizer.ordinaryChar(','); // except the delimiter ',' + streamTokenizer.quoteChar('\"'); // and the quote char + + getRow(); //prime so hasNext might return true (and getRow will return the first row the next time it is called) + } + + private void countFieldsUsed() { + this.fieldCount = 0; + for (int i = 0; i < fieldsUsed.length; i++) { + if (fieldsUsed[i]) { + fieldCount++; + } + } + } + + /** + * inclusive range + * + * @param start + * @param end + * @param enable + */ + public void setFieldsEnabled(int start, int end, boolean enable) { + for (int i = start; i <= end; i++) { + setFieldEnabled(i, enable); + } + } + + public void setFieldEnabled(int index, boolean enable) { + fieldsUsed[index] = enable; + countFieldsUsed(); + } + + public String[] getRow() throws IOException { + String[] rowToReturn = nextRow; + this.nextRow = getRowInternal(); + return rowToReturn; + } + + public boolean hasNext() { + return nextRow != null; + } + + public void skipHeaderRow() throws IOException { + getRow(); + } + + /** + * @return an array + * @throws IOException + */ + private String[] getRowInternal() throws IOException { + String[] values = new String[fieldCount]; + int fieldIndex = 0; + int valuesIndex = 0; + while (streamTokenizer.nextToken() != StreamTokenizer.TT_EOL) { + if (streamTokenizer.ttype == ',') { + if (fieldsUsed[fieldIndex]) { + valuesIndex++; // accounts for fields that are used even if they are empty (i.e. two consecutive commas) + } + fieldIndex++; + } else if (streamTokenizer.ttype == StreamTokenizer.TT_WORD || streamTokenizer.ttype == '\"') { + if (fieldsUsed[fieldIndex]) { + values[valuesIndex] = streamTokenizer.sval; + } + } else if (streamTokenizer.ttype == StreamTokenizer.TT_EOF) { + return null; + } else { + throw new IllegalArgumentException("The token type was: " + streamTokenizer.ttype); + } + } + return values; + } + + public void close() { + try { + reader.close(); + } catch (IOException ex) { + ex.printStackTrace(); + } + } +}
\ No newline at end of file diff --git a/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/io/DriveType.java b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/io/DriveType.java new file mode 100644 index 00000000000..e1893f48c60 --- /dev/null +++ b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/io/DriveType.java @@ -0,0 +1,32 @@ +/******************************************************************************* + * 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.jdk.core.util.io; + +public enum DriveType { + Unknown((short) 0), NoRootDirectory((short) 1), Removable((short) 2), // Floppy, Zip, etc + Fixed((short) 3), // Hard disk + Remote((short) 4), // Network drive + CdRom((short) 5), + RamDrive((short) 6); + + private final short value; + + DriveType(short value) { + this.value = value; + } + + /** + * @return Returns the value. + */ + public short getValue() { + return value; + } +} diff --git a/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/io/EnumBaseBuilder.java b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/io/EnumBaseBuilder.java new file mode 100644 index 00000000000..f9ea4fef78c --- /dev/null +++ b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/io/EnumBaseBuilder.java @@ -0,0 +1,156 @@ +/******************************************************************************* + * 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.jdk.core.util.io; + +import java.util.Comparator; +import java.util.PriorityQueue; + +/** + * @author Robert A. Fisher + * @deprecated + */ +@Deprecated +public class EnumBaseBuilder extends JavaFileBuilder { + + protected PriorityQueue<EnumRecord> enums; + + private static final String stringTableMethod = "\tprotected String[] getStringTable() {\n" + "\t\treturn stringTable;\n" + "\t}"; + private static final String enumTableMethod = "\tprotected EnumSyntax[] getEnumValueTable() {\n" + "\t\treturn enumValueTable;\n" + "\t}"; + + public EnumBaseBuilder(String packageName, String className, String classJavaDoc) { + super(packageName, className, classJavaDoc, "EnumBase"); + + // Place the enums in a priority queue based on their number value + enums = new PriorityQueue<EnumRecord>(20, new Comparator<EnumRecord>() { + + public int compare(EnumRecord i, EnumRecord j) { + return i.number - j.number; + } + + }); + + addMethod(getGetEnum()); + addMethod(getToEnum1()); + addMethod(getToEnum2()); + addMethod(stringTableMethod); + addMethod(enumTableMethod); + } + + public void addEnum(String name, int enumNumber) { + addEnum(name, enumNumber, null); + } + + public void addEnum(String name, int enumNumber, String additionalValues) { + addField(new Field(className, name, true, true, true, getInitialValue(enumNumber, additionalValues))); + enums.offer(new EnumRecord(enumNumber, name)); + } + + protected String getBasicConstructor() { + return "\tprotected " + className + "(int value) {\n" + "\t\tsuper(value);\n" + "\t}"; + } + + private String getInitialValue(int enumNumber, String additionalValues) { + return "new " + className + "(" + enumNumber + ((additionalValues != null) ? "," + additionalValues : "") + ")"; + } + + private String getGetEnum() { + return "\tpublic static " + className + " getEnum(String str) {\n" + "\t\treturn (" + className + ") getEnum(str, stringTable, enumValueTable);\n" + "\t}"; + } + + private String getToEnum1() { + return "\tpublic static " + className + " toEnum(int value) {\n" + "\t\treturn (" + className + ") getEnum(value, enumValueTable);\n" + "\t}"; + } + + private String getToEnum2() { + return "\tpublic static " + className + " toEnum(EnumBase otherEnum) {\n" + "\t\treturn toEnum(otherEnum.getValue());\n" + "\t}"; + } + + /* + * Add the fields from the parent, along with fields that have to be generated dynamically + * based on what enums have been added over the lifetime of this builder. + * + * (non-Javadoc) + * @see org.eclipse.osee.framework.jdk.core.util.io.JavaFileBuilder#getFields(java.lang.StringBuilder) + */ + @Override + protected void getFields(StringBuilder string) { + super.getFields(string); + + // Get a copy of the priority queue, in case this is called many times + PriorityQueue<EnumRecord> records = new PriorityQueue<EnumRecord>(enums); + + StringBuilder stringTable = new StringBuilder(); + StringBuilder enumValueTable = new StringBuilder(); + + // This shoud start at one less than the first value since EnumBase accounts for non-zero based enums + int lastEnumVal = records.peek().number - 1; + + // Start the declarations for the two necessary fields + stringTable.append("\tprivate static final String[] stringTable = new String[] {"); + enumValueTable.append("\tprivate static final " + className + "[] enumValueTable = new " + className + "[] {"); + + EnumRecord record; + // Pop each of the records from the queue + while ((record = records.poll()) != null) { + + // Fill skipped values in the enum listing with null references + for (int x = lastEnumVal; x < (record.number - 1); x++) { + stringTable.append("null, "); + enumValueTable.append("null, "); + } + + stringTable.append("\"" + record.name + "\""); + enumValueTable.append(record.name); + + // If there are more items, then add a comma + if (!records.isEmpty()) { + stringTable.append(", "); + enumValueTable.append(", "); + } + + lastEnumVal = record.number; + } + + stringTable.append("};\n"); + enumValueTable.append("};\n"); + + string.append(stringTable.toString()); + string.append(enumValueTable.toString()); + } + + private class EnumRecord { + private int number; + private String name; + + /** + * @param number The ordinal value of the enumeration + * @param name The declarartion name of the enumeration + */ + public EnumRecord(int number, String name) { + this.number = number; + this.name = name; + } + + /** + * @return Returns the name. + */ + public String getName() { + return name; + } + + /** + * @return Returns the number. + */ + public int getNumber() { + return number; + } + } +} diff --git a/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/io/ExtensionFilter.java b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/io/ExtensionFilter.java new file mode 100644 index 00000000000..117ad3c5abf --- /dev/null +++ b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/io/ExtensionFilter.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.jdk.core.util.io; + +import java.io.File; +import java.io.FileFilter; + +/** + * Filter for filtering files that end with a specific string. + * + * @author Robert A. Fisher + */ +public class ExtensionFilter implements FileFilter { + private final String extension; + + /** + * @param extension The string to match the end of the filenames against. + * @throws IllegalArgumentException if <code>extension</code> is null. + */ + public ExtensionFilter(String extension) { + if (extension == null) throw new IllegalArgumentException("extension must not be null"); + this.extension = extension; + } + + public boolean accept(File file) { + return file.isFile() && file.getName().endsWith(extension); + } +} diff --git a/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/io/IEnumValueBuilder.java b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/io/IEnumValueBuilder.java new file mode 100644 index 00000000000..059504beb2e --- /dev/null +++ b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/io/IEnumValueBuilder.java @@ -0,0 +1,97 @@ +/******************************************************************************* + * 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.jdk.core.util.io; + +import java.util.Comparator; +import java.util.PriorityQueue; + +/** + * Started with EnumBaseBuilder and made modifications for IEnumValue + * + * @author Cindy Maher + */ +public class IEnumValueBuilder extends JavaFileBuilder { + + protected PriorityQueue<EnumRecord> enums; + + public IEnumValueBuilder(String packageName, String className, String classJavaDoc) { + super(packageName, className, classJavaDoc, null); + + // Place the enums in a priority queue based on their number value + enums = new PriorityQueue<EnumRecord>(20, new Comparator<EnumRecord>() { + + public int compare(EnumRecord i, EnumRecord j) { + return i.number - j.number; + } + + }); + + addMethod(getBasicConstructor()); + addMethod(getGetIntValue()); + addMethod(getToEnum()); + addMethod(getGetToEnum()); + } + + public void addEnum(String name, int enumNumber) { + addEnumField(new EnumRecord(enumNumber, name)); + } + + protected String getBasicConstructor() { + return "\tprivate int value;\n\n" + "\tprivate " + className + "(int value) {\n" + "\t\tthis.value = value;\n" + "\t}\n"; + } + + private String getGetIntValue() { + return "\tpublic int getIntValue() {\n" + "\t\treturn value;\n" + "\t}\n"; + } + + private String getToEnum() { + return "\tpublic static " + className + " toEnum(int value) {\n" + "\t\tfor (" + className + " myEnum : " + className + ".values()) {\n" + "\t\t\tif (myEnum.getIntValue() == value) {\n" + "\t\t\t\treturn myEnum;\n" + "\t\t\t}\n" + "\t\t}\n" + "\t\tthrow new IllegalArgumentException(\"Unable to find " + className + " with value \" + value + \".\");\n" + "\t}\n"; + } + + private String getGetToEnum() { + return "\tpublic static " + className + " getEnum(String enumString) {\n" + "\t\tfor (" + className + " myEnum : " + className + ".values()) {\n" + "\t\t\tif (" + className + ".valueOf(enumString) == myEnum) {\n" + "\t\t\t\treturn myEnum;\n" + "\t\t\t}\n" + "\t\t}\n" + "\t\tthrow new IllegalArgumentException(\"Unable to find " + className + " to match \" + enumString + \".\");\n" + "\t}\n"; + } + + public class EnumRecord { + private int number; + private String name; + + /** + * @param number The ordinal value of the enumeration + * @param name The declaration name of the enumeration + */ + public EnumRecord(int number, String name) { + this.number = number; + this.name = name; + } + + /** + * @return Returns the name. + */ + public String getName() { + return name; + } + + /** + * @return Returns the number. + */ + public int getNumber() { + return number; + } + + @Override + public String toString() { + String enumStr = name + "(" + number + ")"; + return enumStr; + } + + } +} diff --git a/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/io/IOInputThread.java b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/io/IOInputThread.java new file mode 100644 index 00000000000..e23eaa6e99c --- /dev/null +++ b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/io/IOInputThread.java @@ -0,0 +1,54 @@ +/******************************************************************************* + * 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.jdk.core.util.io; + +import java.io.BufferedWriter; +import java.io.IOException; +import java.io.Reader; + +/** + * @author Ryan D. Brooks + * @author Andrew M. Finkbeiner + */ +public class IOInputThread extends Thread { + + private Reader input; + private BufferedWriter output; + + /** + * + */ + public IOInputThread(Reader input, BufferedWriter output) { + super(); + this.output = output; + this.input = input; + } + + public void run() { + int character; + try { + //* + while ((character = input.read()) != -1) { + output.write(character); + output.flush(); + } + } catch (IOException ex) { + ex.printStackTrace(); + } finally { + try { + input.close(); + //output.flush(); + } catch (IOException ex) { + ex.printStackTrace(); + } + } + } +} diff --git a/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/io/IOOutputThread.java b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/io/IOOutputThread.java new file mode 100644 index 00000000000..ef3ecaa90f3 --- /dev/null +++ b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/io/IOOutputThread.java @@ -0,0 +1,65 @@ +/******************************************************************************* + * Copyright (c) 2004, 2007 Boeing. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Boeing - initial API and implementation + *******************************************************************************/ +package org.eclipse.osee.framework.jdk.core.util.io; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.Writer; + +/** + * @author Ryan D. Brooks + * @author Andrew M. Finkbeiner + */ +public class IOOutputThread extends Thread { + + private Writer output; + private BufferedReader input; + private boolean verbose; + + /** + * + */ + public IOOutputThread(Writer output, BufferedReader input, boolean verbose) { + super(); + this.output = output; + this.input = input; + this.verbose = verbose; + } + + public IOOutputThread(Writer output, BufferedReader input) { + this(output, input, true); + } + + public void run() { + String outLine = null; + try { + // * + while ((outLine = input.readLine()) != null) { + if (verbose) { + output.write(this.getName()); + output.write(": "); + } + output.write(outLine); + output.write('\n'); + output.flush(); + } + } catch (IOException ex) { + ex.printStackTrace(); + } finally { + try { + input.close(); + output.flush(); + } catch (IOException ex) { + ex.printStackTrace(); + } + } + } +} diff --git a/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/io/IZipEntryCompleteCallback.java b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/io/IZipEntryCompleteCallback.java new file mode 100644 index 00000000000..f5d6a7a247d --- /dev/null +++ b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/io/IZipEntryCompleteCallback.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.jdk.core.util.io; + +public interface IZipEntryCompleteCallback { + + void setValue(int i); + + void setMinimum(int i); + + void setMaximum(int i); + +} diff --git a/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/io/InputBufferThread.java b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/io/InputBufferThread.java new file mode 100644 index 00000000000..a25bdb012b9 --- /dev/null +++ b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/io/InputBufferThread.java @@ -0,0 +1,109 @@ +/******************************************************************************* + * 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.jdk.core.util.io; + +import java.io.BufferedReader; +import java.io.IOException; + +/** + * Sole purpose is to read input from a specified stream and save it into a buffer providing some access methods to the + * buffer. + * + * @author Michael P. Masterson + */ +public class InputBufferThread extends Thread { + + private BufferedReader input; + private StringBuffer buffer; + private boolean shouldStopRunning; + private long lastRead; + + /** + * @param input The stream to read from + */ + public InputBufferThread(BufferedReader input) { + super(); + shouldStopRunning = false; + this.input = input; + buffer = new StringBuffer(); + } + + /** + * Overridden Thread.run method. Reads from the input stream on character at a time until the end of available input + * or until the boold shouldStopRunning is set by an outside source. + */ + public void run() { + char character; + try { + while ((character = (char) input.read()) != -1) { + lastRead = System.currentTimeMillis(); + if (this.shouldStopRunning) { + break; + } + this.append(character); + } + + input.close(); + } catch (IOException ex) { + return; + } + } + + /** + * Appends one character to the buffer. + * + * @param line The character to append + */ + private synchronized void append(char line) { + buffer.append(line); + } + + /** + * Checks if the string passed is contained in the buffer so far + * + * @param matcher The string to look for + * @return True if the String passed is somewhere in the buffer at this point + */ + public synchronized boolean contains(String matcher, boolean remove) { + int index = buffer.lastIndexOf(matcher); + if (remove && index > 0) { + buffer.delete(0, index + matcher.length()); + } + return index >= 0; + } + + public boolean contains(String matcher) { + return contains(matcher, false); + } + + /** + * @return The entire buffered input. + */ + public synchronized String getBuffer() { + return buffer.toString(); + } + + /** + * Tells this thread whether to stop on the next cycle or not + * + * @param b True if the thread should stop on the next run cycle. + */ + public void stopOnNextRun(boolean b) { + this.shouldStopRunning = b; + } + + public long getLastRead() { + if (lastRead == 0) + return System.currentTimeMillis(); + else + return lastRead; + } +} diff --git a/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/io/JavaFileBuilder.java b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/io/JavaFileBuilder.java new file mode 100644 index 00000000000..f0193892af9 --- /dev/null +++ b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/io/JavaFileBuilder.java @@ -0,0 +1,286 @@ +/******************************************************************************* + * 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.jdk.core.util.io; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.PrintWriter; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Date; +import java.util.Iterator; +import java.util.LinkedList; +import java.util.List; +import org.eclipse.osee.framework.jdk.core.util.io.IEnumValueBuilder.EnumRecord; + +/** + * Allows java files to be built dynamically and written out to disk. + * + * @author Robert A. Fisher + */ +public class JavaFileBuilder { + protected String packageName; + protected String className; + protected String classJavaDoc; + protected String extendsClass; + private ArrayList<String> interfaces; + private List<Field> fields; + private List<String> imports; + private List<String> methods; + private List<EnumRecord> enumFields; + + /** + * Create a JavaFileBuilder for a class. + * + * @param className The class of the file. + */ + public JavaFileBuilder(String className) { + this(null, className, null, null); + } + + /** + * Constructor + */ + public JavaFileBuilder(String packageName, String className, String classJavaDoc, String extendsClass) { + this.packageName = packageName; + this.className = className; + this.classJavaDoc = classJavaDoc; + this.extendsClass = extendsClass; + interfaces = new ArrayList<String>(); + fields = new LinkedList<Field>(); + imports = new LinkedList<String>(); + methods = new LinkedList<String>(); + enumFields = new LinkedList<EnumRecord>(); + } + + public void addInterface(String interfaceName) { + interfaces.add(interfaceName); + } + + public void addField(Field field) { + fields.add(field); + } + + public void addEnumField(EnumRecord enumField) { + enumFields.add(enumField); + } + + public void addImport(String importName) { + imports.add(importName); + } + + public void addMethod(String method) { + methods.add(method); + } + + /** + * @param classJavaDoc The classJavaDoc to set. + */ + public void setClassJavaDoc(String classJavaDoc) { + this.classJavaDoc = classJavaDoc; + } + + /** + * @param className The className to set. + */ + public void setClassName(String className) { + this.className = className; + } + + /** + * @param extendsClass The extendsClass to set. + */ + public void setExtendsClass(String extendsClass) { + this.extendsClass = extendsClass; + } + + /** + * @param packageName The packageName to set. + */ + public void setPackageName(String packageName) { + this.packageName = packageName; + } + + /** + * Write the file out to disk. The file will be written to the specified directory. By virtue of Java, the filename + * will be the name of the class with .java as the extension. + * + * @throws FileNotFoundException + */ + public void write(File directory) throws FileNotFoundException { + if (!directory.isDirectory()) throw new IllegalArgumentException("Supplied file is not a directory"); + + PrintWriter out = new PrintWriter(new File(directory, className + ".java")); + + out.write(this.toString()); + + out.close(); + } + + public static class Field { + private boolean isPublic; + private boolean isFinal; + private boolean isStatic; + private String type; + private String name; + private String initialValue; + + public Field(String type, String name, boolean isFinal) { + this(type, name, false, false, isFinal); + } + + public Field(String type, String name, boolean isPublic, boolean isStatic, boolean isFinal) { + this(type, name, isPublic, isStatic, isFinal, null); + } + + /** + * @param type The type of the field + * @param name The name of the field + * @param isPublic Whether the field should be declared as public + * @param isStatic Whether the field should be declared as static + * @param isFinal Whether the field should be declared as final + * @param initialValue An initial value to set the field to. + */ + public Field(String type, String name, boolean isPublic, boolean isStatic, boolean isFinal, String initialValue) { + this.type = type; + this.name = name; + this.isPublic = isPublic; + this.isStatic = isStatic; + this.isFinal = isFinal; + this.initialValue = initialValue; + } + + @Override + public String toString() { + String declaration = "\t" + ((isPublic) ? "public " : "private ") + ((isStatic) ? "static " : "") + ((isFinal) ? "final " : "") + type + " " + name; + + if (initialValue != null) declaration += " = " + initialValue; + return declaration + ";"; + } + + /** + * @return Returns the isPublic. + */ + public boolean isPublic() { + return isPublic; + } + + /** + * @return Returns the isStatic. + */ + public boolean isStatic() { + return isStatic; + } + + /** + * @return Returns the isFinal. + */ + public boolean isFinal() { + return isFinal; + } + + /** + * @return Returns the name. + */ + public String getName() { + return name; + } + + /** + * @return Returns the type. + */ + public String getType() { + return type; + } + } + + /* + * (non-Javadoc) + * + * @see java.lang.Object#toString() + */ + @Override + public String toString() { + StringBuilder string = new StringBuilder(); + + SimpleDateFormat dateFormat = new SimpleDateFormat("MMMM d, yyyy"); + + // Add the head comment for the file + string.append("/*\n * Created on " + dateFormat.format(new Date()) + "\n *\n * PLACE_YOUR_DISTRIBUTION_STATEMENT_RIGHT_HERE\n */\n\n"); + string.append("package " + packageName + ";"); + string.append("\n\n"); + + // Add all of the imports + for (String importName : imports) { + string.append("import " + importName + ";\n"); + } + + string.append("\n"); + + // Add the class comment if it is available + if (classJavaDoc != null) { + string.append(stringToJavadoc(classJavaDoc)); + } + + // add the start of the class + // Check to see if this is an IEnumValue file + if (interfaces.size() != 0 && interfaces.get(0).equals("IEnumValue") && extendsClass == null) { + string.append("public enum " + className + " implements IEnumValue"); + string.append(" {\n"); + getEnumFields(string); + } else { + string.append("public class " + className + ((extendsClass == null) ? "" : " extends " + extendsClass.trim())); + for (int i = 0; i < interfaces.size(); i++) { + if (i == 0) + string.append(" implements " + interfaces.get(i)); + else + string.append(", " + interfaces.get(i)); + } + string.append(" {\n"); + getFields(string); + } + + getMethods(string); + + // add the end of the file + string.append("}"); + + return string.toString(); + } + + protected void getFields(StringBuilder string) { + for (Field field : fields) + string.append(field.toString() + "\n"); + } + + protected void getEnumFields(StringBuilder string) { + Iterator<EnumRecord> enumFieldsIter = enumFields.iterator(); + while (enumFieldsIter.hasNext()) { + EnumRecord eField = enumFieldsIter.next(); + string.append("\t" + eField); + if (!enumFieldsIter.hasNext()) + string.append(";\n\n"); + else + string.append(",\n"); + } + + } + + protected void getMethods(StringBuilder string) { + for (String method : methods) + string.append(method + "\n"); + } + + private String stringToJavadoc(String string) { + return "/**\n" + string.replaceAll("^", " * ").replaceAll("\n", "\n * ") + "\n */\n"; + } + +} diff --git a/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/io/LnkWriter.java b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/io/LnkWriter.java new file mode 100644 index 00000000000..b9c8331012b --- /dev/null +++ b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/io/LnkWriter.java @@ -0,0 +1,822 @@ +/******************************************************************************* + * 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.jdk.core.util.io; + +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; + +/** + * Provides a way to produce simple lnk files. + * + * @author Robert A. Fisher + */ +public class LnkWriter { + + private String description; + private String longName; + private String shortName; + private char shareDriveLetter; + private String shareName; + private String relativePath; + private String commandLineArguments; + private String iconFilename; + private String volumeLabel; + private String workingDirectory; + private String localPath; + private String finalPath; + private int iconNumber; + private int fileLength; + private int volumeSerialNumber; + private DriveType driveType; + + private static final int DWORD = 4; // A dword is 4 bytes + + private static byte MAGIC_VAL[] = new byte[] {0x4C, 0x00, 0x00, 0x00}; + private static byte GUID[] = new byte[] {0x01, 0x14, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, (byte) 0xC0, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x46}; + + public LnkWriter() { + this.description = null; + this.longName = null; + this.shortName = null; + this.shareName = null; + this.relativePath = null; + this.commandLineArguments = null; + this.iconFilename = null; + this.volumeLabel = null; + this.workingDirectory = null; + this.localPath = null; + this.finalPath = null; + this.iconNumber = 0; + this.fileLength = 0; + this.volumeSerialNumber = 0; + this.driveType = DriveType.Unknown; + } + + /** + * @param commandLineArguments The commandLineArguments to set. + */ + public void setCommandLineArguments(String commandLineArguments) { + this.commandLineArguments = commandLineArguments; + } + + /** + * @param description The description to set. + */ + public void setDescription(String description) { + this.description = description; + } + + /** + * @param driveType The driveType to set. + */ + public void setDriveType(DriveType driveType) { + this.driveType = driveType; + } + + /** + * @param fileLength The fileLength to set. + */ + public void setFileLength(int fileLength) { + this.fileLength = fileLength; + } + + /** + * @param finalPath The finalPath to set. + */ + public void setFinalPath(String finalPath) { + this.finalPath = finalPath; + } + + /** + * @param iconFilename The iconFilename to set. + */ + public void setIconFilename(String iconFilename) { + this.iconFilename = iconFilename; + } + + /** + * @param iconNumber The iconNumber to set. + */ + public void setIconNumber(int iconNumber) { + this.iconNumber = iconNumber; + } + + /** + * @param localPath The localPath to set. + */ + public void setLocalPath(String localPath) { + this.localPath = localPath; + } + + /** + * @param longName The longName to set. + */ + public void setLongName(String longName) { + this.longName = longName; + } + + /** + * @param shareName The networkShare to set. + */ + public void setShareName(String shareName, char driveLetter) { + this.shareName = shareName; + this.shareDriveLetter = driveLetter; + } + + /** + * @param relativePath The relativePath to set. + */ + public void setRelativePath(String relativePath) { + this.relativePath = relativePath; + } + + /** + * @param shortName The shortName to set. + */ + public void setShortName(String shortName) { + this.shortName = shortName; + } + + /** + * @param volumeLabel The volumeLabel to set. + */ + public void setVolumeLabel(String volumeLabel) { + this.volumeLabel = volumeLabel; + } + + /** + * @param volumeSerialNumber The volumeSerialNumber to set. + */ + public void setVolumeSerialNumber(int volumeSerialNumber) { + this.volumeSerialNumber = volumeSerialNumber; + } + + /** + * @param workingDirectory The workingDirectory to set. + */ + public void setWorkingDirectory(String workingDirectory) { + this.workingDirectory = workingDirectory; + } + + public static void writeOsee(String shortcutName) throws IOException { + writeFile(shortcutName, OSEE); + } + + public static void writeOseeMs(String shortcutName) throws IOException { + writeFile(shortcutName, OSEE_MS); + } + + private static void writeFile(String name, byte[] data) throws IOException { + File outfile = new File(name); + FileOutputStream out; + out = new FileOutputStream(outfile); + + ByteArrayOutputStream byteOut = new ByteArrayOutputStream(); + byteOut.write(data); + byteOut.writeTo(out); + out.close(); + } + + public void write(String shortcutName) { + + File outfile = new File(shortcutName); + FileOutputStream out; + try { + out = new FileOutputStream(outfile); + } catch (FileNotFoundException ex) { + ex.printStackTrace(); + return; + } + + ByteArrayOutputStream byteOut = new ByteArrayOutputStream(); + try { + byteOut.write(MAGIC_VAL); + byteOut.write(GUID); + byteOut.write(getTheFlags()); + byteOut.write(getFileAttributes()); + byteOut.write(getTimeFields()); + byteOut.write(getFileLength()); + byteOut.write(getIconNumber()); + byteOut.write(getShowWnd()); + byteOut.write(getHotKey()); + byteOut.write(new byte[2 * DWORD]); // There is a 2 DWORD bubble in the format + byteOut.write(getShellItemIdList()); + byteOut.write(getFileLocationInfo()); + if (description != null) byteOut.write(getStringByteData(description)); + if (relativePath != null) byteOut.write(getStringByteData(relativePath)); + if (workingDirectory != null) byteOut.write(getStringByteData(workingDirectory)); + if (commandLineArguments != null) byteOut.write(getStringByteData(commandLineArguments)); + if (iconFilename != null) byteOut.write(getStringByteData(iconFilename)); + byteOut.write(intToByteArray(0)); // End stuff ... + byteOut.writeTo(out); + out.close(); + } catch (IOException ex) { + ex.printStackTrace(); + return; + } + } + + private byte[] getTheFlags() { + // The flags field is one DWORD + byte data[] = new byte[DWORD]; + + // This will always be the case + data[0] |= 1 << 0; // Points to a file or directory + + if (description != null) data[0] |= 1 << 1; // Has a description string + if (relativePath != null) data[0] |= 1 << 2; // Has a relative path string + if (workingDirectory != null) data[0] |= 1 << 3; // Has a working directory string + if (commandLineArguments != null) data[0] |= 1 << 4; // Has command line arguments + if (iconFilename != null) data[0] |= 1 << 5; // Has a custom icon + return data; + } + + private byte[] getFileAttributes() { + // The file attributes field is one DWORD + byte data[] = new byte[DWORD]; + + // Nothing set here yet + + return data; + } + + private byte[] getTimeFields() { + // The 3 time fields are 64 bits each + byte data[] = new byte[3 * 8]; + + // Nothing to set here yet + + return data; + } + + private byte[] getFileLength() { + return intToByteArray(fileLength); + } + + private byte[] getIconNumber() { + return intToByteArray(iconNumber); + } + + private byte[] getShowWnd() { + + // SW_NORMAL = 1 + // SW_SHOWMINIMIZED = 2 + // SW_SHOWMAXIMIXED = 3 + return intToByteArray(1); + } + + private byte[] getHotKey() { + // No hot key setting yet + return intToByteArray(0); + } + + private byte[] getShellItemIdList() { + + // First must acquire all items that go within the table + byte shortNameString[] = getNullTerminatedBytes(shortName.getBytes()); + byte longNameString[] = getNullTerminatedBytes(longName.getBytes()); + + // The table has 4.5 dword's in addition to the two strings + byte data[] = new byte[(int) (4.5 * DWORD) + shortNameString.length + longNameString.length]; + + // Put the length of the list (everything except this 2 bytes + System.arraycopy(shortToByteArray((short) (data.length - 2)), 0, data, 0 * DWORD, 2); + + // Length of the first item (which is this whole block, minus one dword + System.arraycopy(shortToByteArray((short) (data.length - DWORD)), 0, data, (int) (0.5 * DWORD), 2); + + System.arraycopy(shortToByteArray((short) 0x32), 0, data, 1 * DWORD, 2); // Some mystical + // value + System.arraycopy(intToByteArray(fileLength), 0, data, (int) (1.5 * DWORD), 4); + System.arraycopy(intToByteArray(0x3E712576), 0, data, (int) (2.5 * DWORD), 4);// Some mystical + // value + System.arraycopy(shortToByteArray((short) (0x20)), 0, data, (int) (3.5 * DWORD), 2);// Some + // mystical + // value + + // Place the longname string in now + System.arraycopy(longNameString, 0, data, 4 * DWORD, longNameString.length); + + // Place the shortname string right after the longname + System.arraycopy(shortNameString, 0, data, 4 * DWORD + longNameString.length, shortNameString.length); + + return data; + } + + private byte[] getFileLocationInfo() { + // First must acquire all tables that follow this structure + byte localVolumeTable[] = getLocalVolumeTable(); + byte localPathString[] = (localPath != null) ? getNullTerminatedBytes(localPath.getBytes()) : new byte[0]; + byte networkVolumeTable[] = getNetworkVolumeTable(); + byte finalPathString[] = getNullTerminatedBytes(finalPath.getBytes()); + + // The file attributes field is seven DWORD's, plus the structures above + byte data[] = new byte[7 * DWORD + localVolumeTable.length + localPathString.length + networkVolumeTable.length + finalPathString.length]; + + // This flag specifies whether local volume, and/or network volume data is available + int flags = 0; + if (localVolumeTable.length > 0) flags |= 0x1; + if (networkVolumeTable.length > 0) flags |= 0x2; + + // Calculate the necessary offets + int localVolumeOffset = 7 * DWORD; + int localPathOffset = localVolumeOffset + localVolumeTable.length; + int networkVolumeOffset = localPathOffset + localPathString.length; + int finalPathOffset = networkVolumeOffset + networkVolumeTable.length; + + // Put the length value in the first dword + System.arraycopy(intToByteArray(data.length), 0, data, 0 * DWORD, 4); + + // Write the following words + System.arraycopy(intToByteArray(0x1C), 0, data, 1 * DWORD, 4); // First offset after this + // structure + System.arraycopy(intToByteArray(flags), 0, data, 2 * DWORD, 4); + System.arraycopy(intToByteArray(localVolumeOffset), 0, data, 3 * DWORD, 4); + System.arraycopy(intToByteArray(localPathOffset), 0, data, 4 * DWORD, 4); + System.arraycopy(intToByteArray(networkVolumeOffset), 0, data, 5 * DWORD, 4); + System.arraycopy(intToByteArray(finalPathOffset), 0, data, 6 * DWORD, 4); + + // Write the referenced blocks + System.arraycopy(localVolumeTable, 0, data, localVolumeOffset, localVolumeTable.length); + System.arraycopy(localPathString, 0, data, localPathOffset, localPathString.length); + System.arraycopy(networkVolumeTable, 0, data, networkVolumeOffset, networkVolumeTable.length); + System.arraycopy(finalPathString, 0, data, finalPathOffset, finalPathString.length); + + return data; + } + + private byte[] getLocalVolumeTable() { + // If missing the label then don't put it in + if (volumeLabel == null) return new byte[0]; + + byte volumeLabelString[] = getNullTerminatedBytes(volumeLabel.getBytes()); + + // The first 4 dword's are static, then there is the volume label string + byte data[] = new byte[(4 * DWORD) + volumeLabelString.length]; + + // Put the length value in the first dword + System.arraycopy(intToByteArray((short) data.length), 0, data, 0 * DWORD, 4); + + // Write the following words + System.arraycopy(intToByteArray(driveType.getValue()), 0, data, 1 * DWORD, 4); + System.arraycopy(intToByteArray(volumeSerialNumber), 0, data, 2 * DWORD, 4); + System.arraycopy(intToByteArray(0x10), 0, data, 3 * DWORD, 4); + + // Place the string right after that + System.arraycopy(volumeLabelString, 0, data, 4 * DWORD, volumeLabelString.length); + + return data; + } + + private byte[] getNetworkVolumeTable() { + // If the network share is null, then no table + if (shareName == null) return new byte[0]; + + byte networkShareString[] = getNullTerminatedBytes(shareName.getBytes()); + + // The first 5 dword's are static, then there is the network share name, and drive letter + byte data[] = new byte[(5 * DWORD) + networkShareString.length + 3]; + + // Put the length value in the first dword + System.arraycopy(intToByteArray(data.length), 0, data, 0 * DWORD, 4); + + // Write the following words + System.arraycopy(intToByteArray(0x2), 0, data, 1 * DWORD, 4); + System.arraycopy(intToByteArray(0x14), 0, data, 2 * DWORD, 4); + System.arraycopy(intToByteArray(0x0), 0, data, 3 * DWORD, 4); + System.arraycopy(intToByteArray(0x200), 0, data, 4 * DWORD, 4); + + // Place the string right after that, then drive letter + System.arraycopy(networkShareString, 0, data, 5 * DWORD, networkShareString.length); + System.arraycopy(new byte[] {(byte) shareDriveLetter, ':'}, 0, data, data.length - 3, 2); + + return data; + } + + private byte[] getStringByteData(String theString) { + byte data[] = null; + + if (theString != null) { + byte string[] = getNullTerminatedBytes(theString.getBytes()); + + // The first 2 bytes tell the size of the string + // The following space is the string itself + data = new byte[2 + string.length]; + + // Put the length value in the first 2 bytes + System.arraycopy(shortToByteArray((short) string.length), 0, data, 0, 2); + + // Place the string right after that + System.arraycopy(string, 0, data, 2, string.length); + } + + return data; + } + + private byte[] getNullTerminatedBytes(byte string[]) { + // Need an array one larger for the null terminator + byte data[] = new byte[string.length + 1]; + + // Place the string into the new array + System.arraycopy(string, 0, data, 0, string.length); + + return data; + } + + private byte[] shortToByteArray(short val) { + byte data[] = new byte[2]; + + for (int i = 0; i < 2; i++) + data[i] = (byte) (0xFF & (val >> i * 8)); + + return data; + } + + private byte[] intToByteArray(int val) { + byte data[] = new byte[4]; + + // 32 bit values seem to be in reverse order + for (int i = 0; i < 4; i++) + data[i] = (byte) (0xFF & (val >> i * 8)); + + return data; + } + + // This is the binary for the OSEE lnk ;-) + private static final byte OSEE[] = new byte[] {(byte) 0x4C, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x01, + (byte) 0x14, (byte) 0x02, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0xC0, + (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x46, (byte) 0xFB, + (byte) 0x02, (byte) 0x00, (byte) 0x00, (byte) 0x20, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x54, + (byte) 0x20, (byte) 0x6E, (byte) 0x73, (byte) 0x3B, (byte) 0xF8, (byte) 0xC4, (byte) 0x01, (byte) 0xEE, + (byte) 0xDF, (byte) 0x76, (byte) 0x9A, (byte) 0xD4, (byte) 0x83, (byte) 0xC5, (byte) 0x01, (byte) 0x7C, + (byte) 0xF6, (byte) 0xA1, (byte) 0x69, (byte) 0x3B, (byte) 0xF8, (byte) 0xC4, (byte) 0x01, (byte) 0x5F, + (byte) 0xC0, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x01, + (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, + (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x75, + (byte) 0x00, (byte) 0x14, (byte) 0x00, (byte) 0x1F, (byte) 0x50, (byte) 0xE0, (byte) 0x4F, (byte) 0xD0, + (byte) 0x20, (byte) 0xEA, (byte) 0x3A, (byte) 0x69, (byte) 0x10, (byte) 0xA2, (byte) 0xD8, (byte) 0x08, + (byte) 0x00, (byte) 0x2B, (byte) 0x30, (byte) 0x30, (byte) 0x9D, (byte) 0x19, (byte) 0x00, (byte) 0x23, + (byte) 0x43, (byte) 0x3A, (byte) 0x5C, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, + (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, + (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x91, (byte) 0x65, (byte) 0x15, (byte) 0x00, + (byte) 0x31, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0xF3, (byte) 0x32, + (byte) 0xCA, (byte) 0x7D, (byte) 0x30, (byte) 0x00, (byte) 0x57, (byte) 0x49, (byte) 0x4E, (byte) 0x4E, + (byte) 0x54, (byte) 0x00, (byte) 0x00, (byte) 0x18, (byte) 0x00, (byte) 0x31, (byte) 0x00, (byte) 0x00, + (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0xE8, (byte) 0x32, (byte) 0xE1, (byte) 0x6A, (byte) 0x30, + (byte) 0x00, (byte) 0x73, (byte) 0x79, (byte) 0x73, (byte) 0x74, (byte) 0x65, (byte) 0x6D, (byte) 0x33, + (byte) 0x32, (byte) 0x00, (byte) 0x00, (byte) 0x19, (byte) 0x00, (byte) 0x32, (byte) 0x00, (byte) 0x5F, + (byte) 0xC0, (byte) 0x00, (byte) 0x00, (byte) 0x2C, (byte) 0x32, (byte) 0x91, (byte) 0x01, (byte) 0x20, + (byte) 0x00, (byte) 0x6A, (byte) 0x61, (byte) 0x76, (byte) 0x61, (byte) 0x77, (byte) 0x2E, (byte) 0x65, + (byte) 0x78, (byte) 0x65, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x51, (byte) 0x00, + (byte) 0x00, (byte) 0x00, (byte) 0x1C, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x01, (byte) 0x00, + (byte) 0x00, (byte) 0x00, (byte) 0x1C, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x34, (byte) 0x00, + (byte) 0x00, (byte) 0x00, (byte) 0x1C, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x50, (byte) 0x00, + (byte) 0x00, (byte) 0x00, (byte) 0x18, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x03, (byte) 0x00, + (byte) 0x00, (byte) 0x00, (byte) 0xC9, (byte) 0x72, (byte) 0x53, (byte) 0xAC, (byte) 0x10, (byte) 0x00, + (byte) 0x00, (byte) 0x00, (byte) 0x45, (byte) 0x32, (byte) 0x38, (byte) 0x32, (byte) 0x32, (byte) 0x30, + (byte) 0x34, (byte) 0x00, (byte) 0x43, (byte) 0x3A, (byte) 0x5C, (byte) 0x57, (byte) 0x49, (byte) 0x4E, + (byte) 0x4E, (byte) 0x54, (byte) 0x5C, (byte) 0x73, (byte) 0x79, (byte) 0x73, (byte) 0x74, (byte) 0x65, + (byte) 0x6D, (byte) 0x33, (byte) 0x32, (byte) 0x5C, (byte) 0x6A, (byte) 0x61, (byte) 0x76, (byte) 0x61, + (byte) 0x77, (byte) 0x2E, (byte) 0x65, (byte) 0x78, (byte) 0x65, (byte) 0x00, (byte) 0x00, (byte) 0x21, + (byte) 0x00, (byte) 0x2E, (byte) 0x00, (byte) 0x2E, (byte) 0x00, (byte) 0x5C, (byte) 0x00, (byte) 0x2E, + (byte) 0x00, (byte) 0x2E, (byte) 0x00, (byte) 0x5C, (byte) 0x00, (byte) 0x2E, (byte) 0x00, (byte) 0x2E, + (byte) 0x00, (byte) 0x5C, (byte) 0x00, (byte) 0x57, (byte) 0x00, (byte) 0x49, (byte) 0x00, (byte) 0x4E, + (byte) 0x00, (byte) 0x4E, (byte) 0x00, (byte) 0x54, (byte) 0x00, (byte) 0x5C, (byte) 0x00, (byte) 0x73, + (byte) 0x00, (byte) 0x79, (byte) 0x00, (byte) 0x73, (byte) 0x00, (byte) 0x74, (byte) 0x00, (byte) 0x65, + (byte) 0x00, (byte) 0x6D, (byte) 0x00, (byte) 0x33, (byte) 0x00, (byte) 0x32, (byte) 0x00, (byte) 0x5C, + (byte) 0x00, (byte) 0x6A, (byte) 0x00, (byte) 0x61, (byte) 0x00, (byte) 0x76, (byte) 0x00, (byte) 0x61, + (byte) 0x00, (byte) 0x77, (byte) 0x00, (byte) 0x2E, (byte) 0x00, (byte) 0x65, (byte) 0x00, (byte) 0x78, + (byte) 0x00, (byte) 0x65, (byte) 0x00, (byte) 0x12, (byte) 0x00, (byte) 0x59, (byte) 0x00, (byte) 0x3A, + (byte) 0x00, (byte) 0x5C, (byte) 0x00, (byte) 0x4F, (byte) 0x00, (byte) 0x53, (byte) 0x00, (byte) 0x45, + (byte) 0x00, (byte) 0x45, (byte) 0x00, (byte) 0x5C, (byte) 0x00, (byte) 0x77, (byte) 0x00, (byte) 0x69, + (byte) 0x00, (byte) 0x6E, (byte) 0x00, (byte) 0x33, (byte) 0x00, (byte) 0x32, (byte) 0x00, (byte) 0x5C, + (byte) 0x00, (byte) 0x4F, (byte) 0x00, (byte) 0x53, (byte) 0x00, (byte) 0x45, (byte) 0x00, (byte) 0x45, + (byte) 0x00, (byte) 0x29, (byte) 0x00, (byte) 0x2D, (byte) 0x00, (byte) 0x58, (byte) 0x00, (byte) 0x6D, + (byte) 0x00, (byte) 0x78, (byte) 0x00, (byte) 0x35, (byte) 0x00, (byte) 0x31, (byte) 0x00, (byte) 0x32, + (byte) 0x00, (byte) 0x4D, (byte) 0x00, (byte) 0x20, (byte) 0x00, (byte) 0x2D, (byte) 0x00, (byte) 0x6A, + (byte) 0x00, (byte) 0x61, (byte) 0x00, (byte) 0x72, (byte) 0x00, (byte) 0x20, (byte) 0x00, (byte) 0x59, + (byte) 0x00, (byte) 0x3A, (byte) 0x00, (byte) 0x5C, (byte) 0x00, (byte) 0x4F, (byte) 0x00, (byte) 0x53, + (byte) 0x00, (byte) 0x45, (byte) 0x00, (byte) 0x45, (byte) 0x00, (byte) 0x5C, (byte) 0x00, (byte) 0x77, + (byte) 0x00, (byte) 0x69, (byte) 0x00, (byte) 0x6E, (byte) 0x00, (byte) 0x33, (byte) 0x00, (byte) 0x32, + (byte) 0x00, (byte) 0x5C, (byte) 0x00, (byte) 0x4F, (byte) 0x00, (byte) 0x53, (byte) 0x00, (byte) 0x45, + (byte) 0x00, (byte) 0x45, (byte) 0x00, (byte) 0x5C, (byte) 0x00, (byte) 0x4F, (byte) 0x00, (byte) 0x53, + (byte) 0x00, (byte) 0x45, (byte) 0x00, (byte) 0x45, (byte) 0x00, (byte) 0x2E, (byte) 0x00, (byte) 0x6A, + (byte) 0x00, (byte) 0x61, (byte) 0x00, (byte) 0x72, (byte) 0x00, (byte) 0x1B, (byte) 0x00, (byte) 0x59, + (byte) 0x00, (byte) 0x3A, (byte) 0x00, (byte) 0x5C, (byte) 0x00, (byte) 0x4F, (byte) 0x00, (byte) 0x53, + (byte) 0x00, (byte) 0x45, (byte) 0x00, (byte) 0x45, (byte) 0x00, (byte) 0x5C, (byte) 0x00, (byte) 0x77, + (byte) 0x00, (byte) 0x69, (byte) 0x00, (byte) 0x6E, (byte) 0x00, (byte) 0x33, (byte) 0x00, (byte) 0x32, + (byte) 0x00, (byte) 0x5C, (byte) 0x00, (byte) 0x4F, (byte) 0x00, (byte) 0x53, (byte) 0x00, (byte) 0x45, + (byte) 0x00, (byte) 0x45, (byte) 0x00, (byte) 0x5C, (byte) 0x00, (byte) 0x4F, (byte) 0x00, (byte) 0x53, + (byte) 0x00, (byte) 0x45, (byte) 0x00, (byte) 0x45, (byte) 0x00, (byte) 0x2E, (byte) 0x00, (byte) 0x69, + (byte) 0x00, (byte) 0x63, (byte) 0x00, (byte) 0x6F, (byte) 0x00, (byte) 0x14, (byte) 0x03, (byte) 0x00, + (byte) 0x00, (byte) 0x01, (byte) 0x00, (byte) 0x00, (byte) 0xA0, (byte) 0x25, (byte) 0x53, (byte) 0x79, + (byte) 0x73, (byte) 0x74, (byte) 0x65, (byte) 0x6D, (byte) 0x52, (byte) 0x6F, (byte) 0x6F, (byte) 0x74, + (byte) 0x25, (byte) 0x5C, (byte) 0x73, (byte) 0x79, (byte) 0x73, (byte) 0x74, (byte) 0x65, (byte) 0x6D, + (byte) 0x33, (byte) 0x32, (byte) 0x5C, (byte) 0x6A, (byte) 0x61, (byte) 0x76, (byte) 0x61, (byte) 0x77, + (byte) 0x2E, (byte) 0x65, (byte) 0x78, (byte) 0x65, (byte) 0x00, (byte) 0x4C, (byte) 0x82, (byte) 0x57, + (byte) 0x7C, (byte) 0x7B, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x33, (byte) 0x00, (byte) 0x00, + (byte) 0xC0, (byte) 0x78, (byte) 0x74, (byte) 0x58, (byte) 0x7C, (byte) 0x33, (byte) 0x00, (byte) 0x00, + (byte) 0xC0, (byte) 0xE8, (byte) 0xF1, (byte) 0xE3, (byte) 0x03, (byte) 0x00, (byte) 0x00, (byte) 0x00, + (byte) 0x00, (byte) 0xC3, (byte) 0x52, (byte) 0x58, (byte) 0x7C, (byte) 0x0D, (byte) 0x00, (byte) 0x00, + (byte) 0x00, (byte) 0x18, (byte) 0xEB, (byte) 0xE3, (byte) 0x03, (byte) 0xFC, (byte) 0x5F, (byte) 0xE4, + (byte) 0x77, (byte) 0x30, (byte) 0x75, (byte) 0x48, (byte) 0x00, (byte) 0x0D, (byte) 0x00, (byte) 0x00, + (byte) 0x00, (byte) 0x04, (byte) 0x01, (byte) 0x00, (byte) 0x00, (byte) 0xDC, (byte) 0xEF, (byte) 0xE3, + (byte) 0x03, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x01, (byte) 0x6C, (byte) 0x41, + (byte) 0xB9, (byte) 0xB3, (byte) 0x5F, (byte) 0xE4, (byte) 0x77, (byte) 0x18, (byte) 0x00, (byte) 0x00, + (byte) 0x00, (byte) 0xF0, (byte) 0x08, (byte) 0x00, (byte) 0x00, (byte) 0x3C, (byte) 0xEB, (byte) 0xE3, + (byte) 0x03, (byte) 0x40, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, + (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x92, (byte) 0x00, (byte) 0x92, + (byte) 0x00, (byte) 0xB6, (byte) 0xE8, (byte) 0x56, (byte) 0x04, (byte) 0xF0, (byte) 0x08, (byte) 0x00, + (byte) 0x00, (byte) 0x92, (byte) 0x00, (byte) 0x92, (byte) 0x00, (byte) 0xB6, (byte) 0xE8, (byte) 0x56, + (byte) 0x04, (byte) 0x64, (byte) 0xED, (byte) 0xE3, (byte) 0x03, (byte) 0x5B, (byte) 0xDA, (byte) 0xA9, + (byte) 0x70, (byte) 0xE8, (byte) 0xF1, (byte) 0xE3, (byte) 0x03, (byte) 0xDC, (byte) 0xEF, (byte) 0xE3, + (byte) 0x03, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0xD8, (byte) 0xEC, (byte) 0xE3, + (byte) 0x03, (byte) 0x7C, (byte) 0xEB, (byte) 0xE3, (byte) 0x03, (byte) 0x13, (byte) 0x50, (byte) 0xE2, + (byte) 0x77, (byte) 0xB3, (byte) 0x5F, (byte) 0xE4, (byte) 0x77, (byte) 0x7A, (byte) 0x03, (byte) 0x0D, + (byte) 0x00, (byte) 0x0D, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x04, (byte) 0x01, (byte) 0x00, + (byte) 0x00, (byte) 0xDC, (byte) 0xEF, (byte) 0xE3, (byte) 0x03, (byte) 0x00, (byte) 0x00, (byte) 0x00, + (byte) 0x00, (byte) 0x98, (byte) 0xEB, (byte) 0xE3, (byte) 0x03, (byte) 0xF0, (byte) 0x21, (byte) 0x75, + (byte) 0x71, (byte) 0xB3, (byte) 0x5F, (byte) 0xE4, (byte) 0x77, (byte) 0x7A, (byte) 0x03, (byte) 0x0D, + (byte) 0x00, (byte) 0x0D, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x04, (byte) 0x01, (byte) 0x00, + (byte) 0x00, (byte) 0xDC, (byte) 0xEF, (byte) 0xE3, (byte) 0x03, (byte) 0xF4, (byte) 0xEB, (byte) 0xE3, + (byte) 0x03, (byte) 0x6F, (byte) 0x27, (byte) 0x75, (byte) 0x71, (byte) 0x7A, (byte) 0x03, (byte) 0x0D, + (byte) 0x00, (byte) 0x0D, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x04, (byte) 0x01, (byte) 0x00, + (byte) 0x00, (byte) 0xDC, (byte) 0xEF, (byte) 0xE3, (byte) 0x03, (byte) 0x9B, (byte) 0x27, (byte) 0x75, + (byte) 0x71, (byte) 0x25, (byte) 0x00, (byte) 0x53, (byte) 0x00, (byte) 0x79, (byte) 0x00, (byte) 0x73, + (byte) 0x00, (byte) 0x74, (byte) 0x00, (byte) 0x65, (byte) 0x00, (byte) 0x6D, (byte) 0x00, (byte) 0x52, + (byte) 0x00, (byte) 0x6F, (byte) 0x00, (byte) 0x6F, (byte) 0x00, (byte) 0x74, (byte) 0x00, (byte) 0x25, + (byte) 0x00, (byte) 0x5C, (byte) 0x00, (byte) 0x73, (byte) 0x00, (byte) 0x79, (byte) 0x00, (byte) 0x73, + (byte) 0x00, (byte) 0x74, (byte) 0x00, (byte) 0x65, (byte) 0x00, (byte) 0x6D, (byte) 0x00, (byte) 0x33, + (byte) 0x00, (byte) 0x32, (byte) 0x00, (byte) 0x5C, (byte) 0x00, (byte) 0x6A, (byte) 0x00, (byte) 0x61, + (byte) 0x00, (byte) 0x76, (byte) 0x00, (byte) 0x61, (byte) 0x00, (byte) 0x77, (byte) 0x00, (byte) 0x2E, + (byte) 0x00, (byte) 0x65, (byte) 0x00, (byte) 0x78, (byte) 0x00, (byte) 0x65, (byte) 0x00, (byte) 0x00, + (byte) 0x00, (byte) 0x18, (byte) 0xEC, (byte) 0xE3, (byte) 0x03, (byte) 0x74, (byte) 0x25, (byte) 0x75, + (byte) 0x71, (byte) 0x20, (byte) 0xFC, (byte) 0x51, (byte) 0x04, (byte) 0x7A, (byte) 0xF2, (byte) 0xE3, + (byte) 0x03, (byte) 0x00, (byte) 0x00, (byte) 0x07, (byte) 0x00, (byte) 0x54, (byte) 0xEC, (byte) 0xE3, + (byte) 0x03, (byte) 0xD0, (byte) 0x57, (byte) 0xF8, (byte) 0x77, (byte) 0xEC, (byte) 0x57, (byte) 0xF8, + (byte) 0x77, (byte) 0x08, (byte) 0x06, (byte) 0x07, (byte) 0x00, (byte) 0x30, (byte) 0x00, (byte) 0x0D, + (byte) 0x01, (byte) 0x05, (byte) 0x96, (byte) 0x57, (byte) 0x7C, (byte) 0x00, (byte) 0x00, (byte) 0x07, + (byte) 0x00, (byte) 0x7A, (byte) 0xF2, (byte) 0xE3, (byte) 0x03, (byte) 0xE8, (byte) 0x3C, (byte) 0x0F, + (byte) 0x00, (byte) 0x49, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x30, (byte) 0x00, (byte) 0x0D, + (byte) 0x01, (byte) 0x30, (byte) 0x00, (byte) 0x0D, (byte) 0x01, (byte) 0x00, (byte) 0x00, (byte) 0x00, + (byte) 0x00, (byte) 0x24, (byte) 0xEC, (byte) 0xE3, (byte) 0x03, (byte) 0x00, (byte) 0x00, (byte) 0x00, + (byte) 0x00, (byte) 0xE0, (byte) 0xED, (byte) 0xE3, (byte) 0x03, (byte) 0x44, (byte) 0x1F, (byte) 0x5C, + (byte) 0x7C, (byte) 0x50, (byte) 0x24, (byte) 0x57, (byte) 0x7C, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, + (byte) 0xFF, (byte) 0x78, (byte) 0xEC, (byte) 0xE3, (byte) 0x03, (byte) 0x30, (byte) 0x77, (byte) 0xE1, + (byte) 0x77, (byte) 0x34, (byte) 0x00, (byte) 0x0D, (byte) 0x01, (byte) 0x87, (byte) 0x78, (byte) 0xE1, + (byte) 0x77, (byte) 0x34, (byte) 0x00, (byte) 0x0D, (byte) 0x01, (byte) 0x00, (byte) 0x00, (byte) 0x2F, + (byte) 0x78, (byte) 0xB2, (byte) 0xFC, (byte) 0x51, (byte) 0x04, (byte) 0x00, (byte) 0x00, (byte) 0x00, + (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x90, (byte) 0xEC, (byte) 0xE3, + (byte) 0x03, (byte) 0x0A, (byte) 0x78, (byte) 0xE1, (byte) 0x77, (byte) 0xE8, (byte) 0x3C, (byte) 0x0F, + (byte) 0x00, (byte) 0xE8, (byte) 0x3C, (byte) 0x0F, (byte) 0x00, (byte) 0x30, (byte) 0x75, (byte) 0x48, + (byte) 0x00, (byte) 0x7A, (byte) 0x03, (byte) 0x0D, (byte) 0x00, (byte) 0xCC, (byte) 0xEC, (byte) 0xE3, + (byte) 0x03, (byte) 0x05, (byte) 0x7B, (byte) 0xE1, (byte) 0x77, (byte) 0xE8, (byte) 0x3C, (byte) 0x0F, + (byte) 0x00, (byte) 0x04, (byte) 0x01, (byte) 0x00, (byte) 0x00, (byte) 0xE8, (byte) 0xF1, (byte) 0xE3, + (byte) 0x03, (byte) 0x01, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0xA8, (byte) 0x19, (byte) 0x2F, + (byte) 0x00, (byte) 0x30, (byte) 0x75, (byte) 0x48, (byte) 0x00, (byte) 0x7A, (byte) 0x03, (byte) 0x0D, + (byte) 0x00, (byte) 0x20, (byte) 0x34, (byte) 0xE1, (byte) 0x77, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, + (byte) 0xFF, (byte) 0x08, (byte) 0xED, (byte) 0xE3, (byte) 0x03, (byte) 0x76, (byte) 0x26, (byte) 0x75, + (byte) 0x71, (byte) 0x7A, (byte) 0x03, (byte) 0x0D, (byte) 0x00, (byte) 0x49, (byte) 0x00, (byte) 0x00, + (byte) 0x00, (byte) 0xF0, (byte) 0xEC, (byte) 0xE3, (byte) 0x03, (byte) 0xD7, (byte) 0x79, (byte) 0xE1, + (byte) 0x77, (byte) 0x30, (byte) 0x75, (byte) 0x48, (byte) 0x00, (byte) 0x0D, (byte) 0x00, (byte) 0x00, + (byte) 0x00, (byte) 0x04, (byte) 0x01, (byte) 0x00, (byte) 0x00, (byte) 0xE8, (byte) 0xF1, (byte) 0xE3, + (byte) 0x03, (byte) 0xA8, (byte) 0x19, (byte) 0x2F, (byte) 0x00, (byte) 0x30, (byte) 0x75, (byte) 0x48, + (byte) 0x00, (byte) 0x0D, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x14, (byte) 0xED, (byte) 0xE3, + (byte) 0x03, (byte) 0xFC, (byte) 0x5F, (byte) 0xE4, (byte) 0x77, (byte) 0x30, (byte) 0x75, (byte) 0x48, + (byte) 0x00, (byte) 0x0D, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x04, (byte) 0x01, (byte) 0x00, + (byte) 0x00, (byte) 0xE8, (byte) 0xF1, (byte) 0xE3, (byte) 0x03, (byte) 0x00, (byte) 0x00, (byte) 0x00, + (byte) 0x00, (byte) 0x0D, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0xB3, (byte) 0x5F, (byte) 0xE4, + (byte) 0x77, (byte) 0x34, (byte) 0xED, (byte) 0xE3, (byte) 0x03, (byte) 0xD0, (byte) 0xA3, (byte) 0xE3, + (byte) 0x77, (byte) 0x7A, (byte) 0x03, (byte) 0x0D, (byte) 0x00, (byte) 0x0D, (byte) 0x00, (byte) 0x00, + (byte) 0x00, (byte) 0x04, (byte) 0x01, (byte) 0x00, (byte) 0x00, (byte) 0xE8, (byte) 0xF1, (byte) 0xE3, + (byte) 0x03, (byte) 0xB3, (byte) 0x5F, (byte) 0xE4, (byte) 0x77, (byte) 0xCD, (byte) 0xAB, (byte) 0xBA, + (byte) 0xDC, (byte) 0x58, (byte) 0xED, (byte) 0xE3, (byte) 0x03, (byte) 0xA6, (byte) 0x52, (byte) 0x58, + (byte) 0x7C, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0x0C, (byte) 0x00, (byte) 0x00, + (byte) 0x00, (byte) 0x50, (byte) 0xED, (byte) 0xE3, (byte) 0x03, (byte) 0xEF, (byte) 0x52, (byte) 0x58, + (byte) 0x7C, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0x0C, (byte) 0x00, (byte) 0x00, + (byte) 0x00, (byte) 0x60, (byte) 0xED, (byte) 0xE3, (byte) 0x03, (byte) 0x04, (byte) 0x00, (byte) 0x00, + (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x80, (byte) 0x00, + (byte) 0x00, (byte) 0xA4, (byte) 0xEF, (byte) 0xE3, (byte) 0x03, (byte) 0x75, (byte) 0x4E, (byte) 0xAA, + (byte) 0x70, (byte) 0x01, (byte) 0x80, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, + (byte) 0x00, (byte) 0xE8, (byte) 0xF1, (byte) 0xE3, (byte) 0x03, (byte) 0xD8, (byte) 0x8F, (byte) 0x52, + (byte) 0x04, (byte) 0xF0, (byte) 0x21, (byte) 0x75, (byte) 0x71, (byte) 0xB3, (byte) 0x5F, (byte) 0xE4, + (byte) 0x77, (byte) 0x7A, (byte) 0x03, (byte) 0x0D, (byte) 0x00, (byte) 0x0D, (byte) 0x00, (byte) 0x00, + (byte) 0x00, (byte) 0x04, (byte) 0x01, (byte) 0x00, (byte) 0x00, (byte) 0xE8, (byte) 0xF1, (byte) 0xE3, + (byte) 0x03, (byte) 0xF0, (byte) 0xED, (byte) 0xE3, (byte) 0x03, (byte) 0x6F, (byte) 0x27, (byte) 0x75, + (byte) 0x71, (byte) 0x7A, (byte) 0x03, (byte) 0x0D, (byte) 0x00, (byte) 0x0D, (byte) 0x00, (byte) 0x00, + (byte) 0x00, (byte) 0x04, (byte) 0x01, (byte) 0x00, (byte) 0x00, (byte) 0xE8, (byte) 0xF1, (byte) 0xE3, + (byte) 0x03, (byte) 0x9B, (byte) 0x27, (byte) 0x75, (byte) 0x71, (byte) 0xD4, (byte) 0xEE, (byte) 0xE3, + (byte) 0x03, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x80, (byte) 0x04, (byte) 0x52, + (byte) 0x04, (byte) 0x60, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x03, (byte) 0x00, (byte) 0x00, + (byte) 0xA0, (byte) 0x58, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, + (byte) 0x00, (byte) 0x65, (byte) 0x32, (byte) 0x38, (byte) 0x32, (byte) 0x32, (byte) 0x30, (byte) 0x34, + (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, + (byte) 0x00, (byte) 0x06, (byte) 0xA0, (byte) 0x78, (byte) 0xF9, (byte) 0x08, (byte) 0x80, (byte) 0xFF, + (byte) 0x4E, (byte) 0x9C, (byte) 0x47, (byte) 0xF1, (byte) 0xD0, (byte) 0x77, (byte) 0xFE, (byte) 0x54, + (byte) 0xB6, (byte) 0x46, (byte) 0x18, (byte) 0x99, (byte) 0x1F, (byte) 0xA2, (byte) 0xE1, (byte) 0xD9, + (byte) 0x11, (byte) 0x86, (byte) 0xC3, (byte) 0x00, (byte) 0x0F, (byte) 0x1F, (byte) 0xD8, (byte) 0x1B, + (byte) 0x0F, (byte) 0x06, (byte) 0xA0, (byte) 0x78, (byte) 0xF9, (byte) 0x08, (byte) 0x80, (byte) 0xFF, + (byte) 0x4E, (byte) 0x9C, (byte) 0x47, (byte) 0xF1, (byte) 0xD0, (byte) 0x77, (byte) 0xFE, (byte) 0x54, + (byte) 0xB6, (byte) 0x46, (byte) 0x18, (byte) 0x99, (byte) 0x1F, (byte) 0xA2, (byte) 0xE1, (byte) 0xD9, + (byte) 0x11, (byte) 0x86, (byte) 0xC3, (byte) 0x00, (byte) 0x0F, (byte) 0x1F, (byte) 0xD8, (byte) 0x1B, + (byte) 0x0F, (byte) 0x10, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x05, (byte) 0x00, (byte) 0x00, + (byte) 0xA0, (byte) 0x24, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x42, (byte) 0x00, (byte) 0x00, + (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00}; + + // This is the binary for the OSEE_MS lnk ;-) + private static final byte[] OSEE_MS = new byte[] {(byte) 0x4C, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x01, + (byte) 0x14, (byte) 0x02, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0xC0, + (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x46, (byte) 0xFB, + (byte) 0x02, (byte) 0x00, (byte) 0x00, (byte) 0x20, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x54, + (byte) 0x20, (byte) 0x6E, (byte) 0x73, (byte) 0x3B, (byte) 0xF8, (byte) 0xC4, (byte) 0x01, (byte) 0xAB, + (byte) 0x00, (byte) 0xE4, (byte) 0x8F, (byte) 0xA2, (byte) 0x9E, (byte) 0xC5, (byte) 0x01, (byte) 0x7C, + (byte) 0xF6, (byte) 0xA1, (byte) 0x69, (byte) 0x3B, (byte) 0xF8, (byte) 0xC4, (byte) 0x01, (byte) 0x5F, + (byte) 0xC0, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x01, + (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, + (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x9E, + (byte) 0x00, (byte) 0x14, (byte) 0x00, (byte) 0x1F, (byte) 0x50, (byte) 0xE0, (byte) 0x4F, (byte) 0xD0, + (byte) 0x20, (byte) 0xEA, (byte) 0x3A, (byte) 0x69, (byte) 0x10, (byte) 0xA2, (byte) 0xD8, (byte) 0x08, + (byte) 0x00, (byte) 0x2B, (byte) 0x30, (byte) 0x30, (byte) 0x9D, (byte) 0x19, (byte) 0x00, (byte) 0x23, + (byte) 0x43, (byte) 0x3A, (byte) 0x5C, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, + (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, + (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x91, (byte) 0x65, (byte) 0x15, (byte) 0x00, + (byte) 0x31, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x17, (byte) 0x33, + (byte) 0xB5, (byte) 0xBB, (byte) 0x30, (byte) 0x00, (byte) 0x57, (byte) 0x49, (byte) 0x4E, (byte) 0x4E, + (byte) 0x54, (byte) 0x00, (byte) 0x00, (byte) 0x18, (byte) 0x00, (byte) 0x31, (byte) 0x00, (byte) 0x00, + (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x08, (byte) 0x33, (byte) 0x1D, (byte) 0x6E, (byte) 0x30, + (byte) 0x00, (byte) 0x73, (byte) 0x79, (byte) 0x73, (byte) 0x74, (byte) 0x65, (byte) 0x6D, (byte) 0x33, + (byte) 0x32, (byte) 0x00, (byte) 0x00, (byte) 0x42, (byte) 0x00, (byte) 0x32, (byte) 0x00, (byte) 0x5F, + (byte) 0xC0, (byte) 0x00, (byte) 0x00, (byte) 0xE5, (byte) 0x32, (byte) 0x10, (byte) 0x89, (byte) 0x20, + (byte) 0x00, (byte) 0x6A, (byte) 0x61, (byte) 0x76, (byte) 0x61, (byte) 0x77, (byte) 0x2E, (byte) 0x65, + (byte) 0x78, (byte) 0x65, (byte) 0x00, (byte) 0x2A, (byte) 0x00, (byte) 0x03, (byte) 0x00, (byte) 0x04, + (byte) 0x00, (byte) 0xEF, (byte) 0xBE, (byte) 0xE5, (byte) 0x32, (byte) 0x19, (byte) 0x89, (byte) 0x04, + (byte) 0x33, (byte) 0x60, (byte) 0x8D, (byte) 0x14, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x6A, + (byte) 0x00, (byte) 0x61, (byte) 0x00, (byte) 0x76, (byte) 0x00, (byte) 0x61, (byte) 0x00, (byte) 0x77, + (byte) 0x00, (byte) 0x2E, (byte) 0x00, (byte) 0x65, (byte) 0x00, (byte) 0x78, (byte) 0x00, (byte) 0x65, + (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x18, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x4C, + (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x1C, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x01, + (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x1C, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x2D, + (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x4B, + (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x11, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x03, + (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x34, (byte) 0xCC, (byte) 0xE0, (byte) 0x84, (byte) 0x10, + (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x43, (byte) 0x3A, (byte) 0x5C, (byte) 0x57, + (byte) 0x49, (byte) 0x4E, (byte) 0x44, (byte) 0x4F, (byte) 0x57, (byte) 0x53, (byte) 0x5C, (byte) 0x73, + (byte) 0x79, (byte) 0x73, (byte) 0x74, (byte) 0x65, (byte) 0x6D, (byte) 0x33, (byte) 0x32, (byte) 0x5C, + (byte) 0x6A, (byte) 0x61, (byte) 0x76, (byte) 0x61, (byte) 0x77, (byte) 0x2E, (byte) 0x65, (byte) 0x78, + (byte) 0x65, (byte) 0x00, (byte) 0x00, (byte) 0x1A, (byte) 0x00, (byte) 0x2E, (byte) 0x00, (byte) 0x5C, + (byte) 0x00, (byte) 0x57, (byte) 0x00, (byte) 0x49, (byte) 0x00, (byte) 0x4E, (byte) 0x00, (byte) 0x4E, + (byte) 0x00, (byte) 0x54, (byte) 0x00, (byte) 0x5C, (byte) 0x00, (byte) 0x73, (byte) 0x00, (byte) 0x79, + (byte) 0x00, (byte) 0x73, (byte) 0x00, (byte) 0x74, (byte) 0x00, (byte) 0x65, (byte) 0x00, (byte) 0x6D, + (byte) 0x00, (byte) 0x33, (byte) 0x00, (byte) 0x32, (byte) 0x00, (byte) 0x5C, (byte) 0x00, (byte) 0x6A, + (byte) 0x00, (byte) 0x61, (byte) 0x00, (byte) 0x76, (byte) 0x00, (byte) 0x61, (byte) 0x00, (byte) 0x77, + (byte) 0x00, (byte) 0x2E, (byte) 0x00, (byte) 0x65, (byte) 0x00, (byte) 0x78, (byte) 0x00, (byte) 0x65, + (byte) 0x00, (byte) 0x15, (byte) 0x00, (byte) 0x59, (byte) 0x00, (byte) 0x3A, (byte) 0x00, (byte) 0x5C, + (byte) 0x00, (byte) 0x4F, (byte) 0x00, (byte) 0x53, (byte) 0x00, (byte) 0x45, (byte) 0x00, (byte) 0x45, + (byte) 0x00, (byte) 0x5C, (byte) 0x00, (byte) 0x77, (byte) 0x00, (byte) 0x69, (byte) 0x00, (byte) 0x6E, + (byte) 0x00, (byte) 0x33, (byte) 0x00, (byte) 0x32, (byte) 0x00, (byte) 0x5C, (byte) 0x00, (byte) 0x4F, + (byte) 0x00, (byte) 0x53, (byte) 0x00, (byte) 0x45, (byte) 0x00, (byte) 0x45, (byte) 0x00, (byte) 0x5F, + (byte) 0x00, (byte) 0x4D, (byte) 0x00, (byte) 0x53, (byte) 0x00, (byte) 0x2C, (byte) 0x00, (byte) 0x2D, + (byte) 0x00, (byte) 0x58, (byte) 0x00, (byte) 0x6D, (byte) 0x00, (byte) 0x78, (byte) 0x00, (byte) 0x35, + (byte) 0x00, (byte) 0x31, (byte) 0x00, (byte) 0x32, (byte) 0x00, (byte) 0x4D, (byte) 0x00, (byte) 0x20, + (byte) 0x00, (byte) 0x2D, (byte) 0x00, (byte) 0x6A, (byte) 0x00, (byte) 0x61, (byte) 0x00, (byte) 0x72, + (byte) 0x00, (byte) 0x20, (byte) 0x00, (byte) 0x59, (byte) 0x00, (byte) 0x3A, (byte) 0x00, (byte) 0x5C, + (byte) 0x00, (byte) 0x4F, (byte) 0x00, (byte) 0x53, (byte) 0x00, (byte) 0x45, (byte) 0x00, (byte) 0x45, + (byte) 0x00, (byte) 0x5C, (byte) 0x00, (byte) 0x77, (byte) 0x00, (byte) 0x69, (byte) 0x00, (byte) 0x6E, + (byte) 0x00, (byte) 0x33, (byte) 0x00, (byte) 0x32, (byte) 0x00, (byte) 0x5C, (byte) 0x00, (byte) 0x4F, + (byte) 0x00, (byte) 0x53, (byte) 0x00, (byte) 0x45, (byte) 0x00, (byte) 0x45, (byte) 0x00, (byte) 0x5F, + (byte) 0x00, (byte) 0x4D, (byte) 0x00, (byte) 0x53, (byte) 0x00, (byte) 0x5C, (byte) 0x00, (byte) 0x4F, + (byte) 0x00, (byte) 0x53, (byte) 0x00, (byte) 0x45, (byte) 0x00, (byte) 0x45, (byte) 0x00, (byte) 0x2E, + (byte) 0x00, (byte) 0x6A, (byte) 0x00, (byte) 0x61, (byte) 0x00, (byte) 0x72, (byte) 0x00, (byte) 0x1B, + (byte) 0x00, (byte) 0x59, (byte) 0x00, (byte) 0x3A, (byte) 0x00, (byte) 0x5C, (byte) 0x00, (byte) 0x4F, + (byte) 0x00, (byte) 0x53, (byte) 0x00, (byte) 0x45, (byte) 0x00, (byte) 0x45, (byte) 0x00, (byte) 0x5C, + (byte) 0x00, (byte) 0x77, (byte) 0x00, (byte) 0x69, (byte) 0x00, (byte) 0x6E, (byte) 0x00, (byte) 0x33, + (byte) 0x00, (byte) 0x32, (byte) 0x00, (byte) 0x5C, (byte) 0x00, (byte) 0x4F, (byte) 0x00, (byte) 0x53, + (byte) 0x00, (byte) 0x45, (byte) 0x00, (byte) 0x45, (byte) 0x00, (byte) 0x5C, (byte) 0x00, (byte) 0x4F, + (byte) 0x00, (byte) 0x53, (byte) 0x00, (byte) 0x45, (byte) 0x00, (byte) 0x45, (byte) 0x00, (byte) 0x2E, + (byte) 0x00, (byte) 0x69, (byte) 0x00, (byte) 0x63, (byte) 0x00, (byte) 0x6F, (byte) 0x00, (byte) 0x14, + (byte) 0x03, (byte) 0x00, (byte) 0x00, (byte) 0x01, (byte) 0x00, (byte) 0x00, (byte) 0xA0, (byte) 0x25, + (byte) 0x53, (byte) 0x79, (byte) 0x73, (byte) 0x74, (byte) 0x65, (byte) 0x6D, (byte) 0x52, (byte) 0x6F, + (byte) 0x6F, (byte) 0x74, (byte) 0x25, (byte) 0x5C, (byte) 0x73, (byte) 0x79, (byte) 0x73, (byte) 0x74, + (byte) 0x65, (byte) 0x6D, (byte) 0x33, (byte) 0x32, (byte) 0x5C, (byte) 0x6A, (byte) 0x61, (byte) 0x76, + (byte) 0x61, (byte) 0x77, (byte) 0x2E, (byte) 0x65, (byte) 0x78, (byte) 0x65, (byte) 0x00, (byte) 0x4C, + (byte) 0x82, (byte) 0x57, (byte) 0x7C, (byte) 0x7B, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x33, + (byte) 0x00, (byte) 0x00, (byte) 0xC0, (byte) 0x78, (byte) 0x74, (byte) 0x58, (byte) 0x7C, (byte) 0x33, + (byte) 0x00, (byte) 0x00, (byte) 0xC0, (byte) 0xE8, (byte) 0xF1, (byte) 0xE3, (byte) 0x03, (byte) 0x00, + (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0xC3, (byte) 0x52, (byte) 0x58, (byte) 0x7C, (byte) 0x0D, + (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x18, (byte) 0xEB, (byte) 0xE3, (byte) 0x03, (byte) 0xFC, + (byte) 0x5F, (byte) 0xE4, (byte) 0x77, (byte) 0x30, (byte) 0x75, (byte) 0x48, (byte) 0x00, (byte) 0x0D, + (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x04, (byte) 0x01, (byte) 0x00, (byte) 0x00, (byte) 0xDC, + (byte) 0xEF, (byte) 0xE3, (byte) 0x03, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x01, + (byte) 0x6C, (byte) 0x41, (byte) 0xB9, (byte) 0xB3, (byte) 0x5F, (byte) 0xE4, (byte) 0x77, (byte) 0x18, + (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0xF0, (byte) 0x08, (byte) 0x00, (byte) 0x00, (byte) 0x3C, + (byte) 0xEB, (byte) 0xE3, (byte) 0x03, (byte) 0x40, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, + (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x92, + (byte) 0x00, (byte) 0x92, (byte) 0x00, (byte) 0xB6, (byte) 0xE8, (byte) 0x56, (byte) 0x04, (byte) 0xF0, + (byte) 0x08, (byte) 0x00, (byte) 0x00, (byte) 0x92, (byte) 0x00, (byte) 0x92, (byte) 0x00, (byte) 0xB6, + (byte) 0xE8, (byte) 0x56, (byte) 0x04, (byte) 0x64, (byte) 0xED, (byte) 0xE3, (byte) 0x03, (byte) 0x5B, + (byte) 0xDA, (byte) 0xA9, (byte) 0x70, (byte) 0xE8, (byte) 0xF1, (byte) 0xE3, (byte) 0x03, (byte) 0xDC, + (byte) 0xEF, (byte) 0xE3, (byte) 0x03, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0xD8, + (byte) 0xEC, (byte) 0xE3, (byte) 0x03, (byte) 0x7C, (byte) 0xEB, (byte) 0xE3, (byte) 0x03, (byte) 0x13, + (byte) 0x50, (byte) 0xE2, (byte) 0x77, (byte) 0xB3, (byte) 0x5F, (byte) 0xE4, (byte) 0x77, (byte) 0x7A, + (byte) 0x03, (byte) 0x0D, (byte) 0x00, (byte) 0x0D, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x04, + (byte) 0x01, (byte) 0x00, (byte) 0x00, (byte) 0xDC, (byte) 0xEF, (byte) 0xE3, (byte) 0x03, (byte) 0x00, + (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x98, (byte) 0xEB, (byte) 0xE3, (byte) 0x03, (byte) 0xF0, + (byte) 0x21, (byte) 0x75, (byte) 0x71, (byte) 0xB3, (byte) 0x5F, (byte) 0xE4, (byte) 0x77, (byte) 0x7A, + (byte) 0x03, (byte) 0x0D, (byte) 0x00, (byte) 0x0D, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x04, + (byte) 0x01, (byte) 0x00, (byte) 0x00, (byte) 0xDC, (byte) 0xEF, (byte) 0xE3, (byte) 0x03, (byte) 0xF4, + (byte) 0xEB, (byte) 0xE3, (byte) 0x03, (byte) 0x6F, (byte) 0x27, (byte) 0x75, (byte) 0x71, (byte) 0x7A, + (byte) 0x03, (byte) 0x0D, (byte) 0x00, (byte) 0x0D, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x04, + (byte) 0x01, (byte) 0x00, (byte) 0x00, (byte) 0xDC, (byte) 0xEF, (byte) 0xE3, (byte) 0x03, (byte) 0x9B, + (byte) 0x27, (byte) 0x75, (byte) 0x71, (byte) 0x25, (byte) 0x00, (byte) 0x53, (byte) 0x00, (byte) 0x79, + (byte) 0x00, (byte) 0x73, (byte) 0x00, (byte) 0x74, (byte) 0x00, (byte) 0x65, (byte) 0x00, (byte) 0x6D, + (byte) 0x00, (byte) 0x52, (byte) 0x00, (byte) 0x6F, (byte) 0x00, (byte) 0x6F, (byte) 0x00, (byte) 0x74, + (byte) 0x00, (byte) 0x25, (byte) 0x00, (byte) 0x5C, (byte) 0x00, (byte) 0x73, (byte) 0x00, (byte) 0x79, + (byte) 0x00, (byte) 0x73, (byte) 0x00, (byte) 0x74, (byte) 0x00, (byte) 0x65, (byte) 0x00, (byte) 0x6D, + (byte) 0x00, (byte) 0x33, (byte) 0x00, (byte) 0x32, (byte) 0x00, (byte) 0x5C, (byte) 0x00, (byte) 0x6A, + (byte) 0x00, (byte) 0x61, (byte) 0x00, (byte) 0x76, (byte) 0x00, (byte) 0x61, (byte) 0x00, (byte) 0x77, + (byte) 0x00, (byte) 0x2E, (byte) 0x00, (byte) 0x65, (byte) 0x00, (byte) 0x78, (byte) 0x00, (byte) 0x65, + (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x18, (byte) 0xEC, (byte) 0xE3, (byte) 0x03, (byte) 0x74, + (byte) 0x25, (byte) 0x75, (byte) 0x71, (byte) 0x20, (byte) 0xFC, (byte) 0x51, (byte) 0x04, (byte) 0x7A, + (byte) 0xF2, (byte) 0xE3, (byte) 0x03, (byte) 0x00, (byte) 0x00, (byte) 0x07, (byte) 0x00, (byte) 0x54, + (byte) 0xEC, (byte) 0xE3, (byte) 0x03, (byte) 0xD0, (byte) 0x57, (byte) 0xF8, (byte) 0x77, (byte) 0xEC, + (byte) 0x57, (byte) 0xF8, (byte) 0x77, (byte) 0x08, (byte) 0x06, (byte) 0x07, (byte) 0x00, (byte) 0x30, + (byte) 0x00, (byte) 0x0D, (byte) 0x01, (byte) 0x05, (byte) 0x96, (byte) 0x57, (byte) 0x7C, (byte) 0x00, + (byte) 0x00, (byte) 0x07, (byte) 0x00, (byte) 0x7A, (byte) 0xF2, (byte) 0xE3, (byte) 0x03, (byte) 0xE8, + (byte) 0x3C, (byte) 0x0F, (byte) 0x00, (byte) 0x49, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x30, + (byte) 0x00, (byte) 0x0D, (byte) 0x01, (byte) 0x30, (byte) 0x00, (byte) 0x0D, (byte) 0x01, (byte) 0x00, + (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x24, (byte) 0xEC, (byte) 0xE3, (byte) 0x03, (byte) 0x00, + (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0xE0, (byte) 0xED, (byte) 0xE3, (byte) 0x03, (byte) 0x44, + (byte) 0x1F, (byte) 0x5C, (byte) 0x7C, (byte) 0x50, (byte) 0x24, (byte) 0x57, (byte) 0x7C, (byte) 0xFF, + (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0x78, (byte) 0xEC, (byte) 0xE3, (byte) 0x03, (byte) 0x30, + (byte) 0x77, (byte) 0xE1, (byte) 0x77, (byte) 0x34, (byte) 0x00, (byte) 0x0D, (byte) 0x01, (byte) 0x87, + (byte) 0x78, (byte) 0xE1, (byte) 0x77, (byte) 0x34, (byte) 0x00, (byte) 0x0D, (byte) 0x01, (byte) 0x00, + (byte) 0x00, (byte) 0x2F, (byte) 0x78, (byte) 0xB2, (byte) 0xFC, (byte) 0x51, (byte) 0x04, (byte) 0x00, + (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x90, + (byte) 0xEC, (byte) 0xE3, (byte) 0x03, (byte) 0x0A, (byte) 0x78, (byte) 0xE1, (byte) 0x77, (byte) 0xE8, + (byte) 0x3C, (byte) 0x0F, (byte) 0x00, (byte) 0xE8, (byte) 0x3C, (byte) 0x0F, (byte) 0x00, (byte) 0x30, + (byte) 0x75, (byte) 0x48, (byte) 0x00, (byte) 0x7A, (byte) 0x03, (byte) 0x0D, (byte) 0x00, (byte) 0xCC, + (byte) 0xEC, (byte) 0xE3, (byte) 0x03, (byte) 0x05, (byte) 0x7B, (byte) 0xE1, (byte) 0x77, (byte) 0xE8, + (byte) 0x3C, (byte) 0x0F, (byte) 0x00, (byte) 0x04, (byte) 0x01, (byte) 0x00, (byte) 0x00, (byte) 0xE8, + (byte) 0xF1, (byte) 0xE3, (byte) 0x03, (byte) 0x01, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0xA8, + (byte) 0x19, (byte) 0x2F, (byte) 0x00, (byte) 0x30, (byte) 0x75, (byte) 0x48, (byte) 0x00, (byte) 0x7A, + (byte) 0x03, (byte) 0x0D, (byte) 0x00, (byte) 0x20, (byte) 0x34, (byte) 0xE1, (byte) 0x77, (byte) 0xFF, + (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0x08, (byte) 0xED, (byte) 0xE3, (byte) 0x03, (byte) 0x76, + (byte) 0x26, (byte) 0x75, (byte) 0x71, (byte) 0x7A, (byte) 0x03, (byte) 0x0D, (byte) 0x00, (byte) 0x49, + (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0xF0, (byte) 0xEC, (byte) 0xE3, (byte) 0x03, (byte) 0xD7, + (byte) 0x79, (byte) 0xE1, (byte) 0x77, (byte) 0x30, (byte) 0x75, (byte) 0x48, (byte) 0x00, (byte) 0x0D, + (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x04, (byte) 0x01, (byte) 0x00, (byte) 0x00, (byte) 0xE8, + (byte) 0xF1, (byte) 0xE3, (byte) 0x03, (byte) 0xA8, (byte) 0x19, (byte) 0x2F, (byte) 0x00, (byte) 0x30, + (byte) 0x75, (byte) 0x48, (byte) 0x00, (byte) 0x0D, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x14, + (byte) 0xED, (byte) 0xE3, (byte) 0x03, (byte) 0xFC, (byte) 0x5F, (byte) 0xE4, (byte) 0x77, (byte) 0x30, + (byte) 0x75, (byte) 0x48, (byte) 0x00, (byte) 0x0D, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x04, + (byte) 0x01, (byte) 0x00, (byte) 0x00, (byte) 0xE8, (byte) 0xF1, (byte) 0xE3, (byte) 0x03, (byte) 0x00, + (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x0D, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0xB3, + (byte) 0x5F, (byte) 0xE4, (byte) 0x77, (byte) 0x34, (byte) 0xED, (byte) 0xE3, (byte) 0x03, (byte) 0xD0, + (byte) 0xA3, (byte) 0xE3, (byte) 0x77, (byte) 0x7A, (byte) 0x03, (byte) 0x0D, (byte) 0x00, (byte) 0x0D, + (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x04, (byte) 0x01, (byte) 0x00, (byte) 0x00, (byte) 0xE8, + (byte) 0xF1, (byte) 0xE3, (byte) 0x03, (byte) 0xB3, (byte) 0x5F, (byte) 0xE4, (byte) 0x77, (byte) 0xCD, + (byte) 0xAB, (byte) 0xBA, (byte) 0xDC, (byte) 0x58, (byte) 0xED, (byte) 0xE3, (byte) 0x03, (byte) 0xA6, + (byte) 0x52, (byte) 0x58, (byte) 0x7C, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0x0C, + (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x50, (byte) 0xED, (byte) 0xE3, (byte) 0x03, (byte) 0xEF, + (byte) 0x52, (byte) 0x58, (byte) 0x7C, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0x0C, + (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x60, (byte) 0xED, (byte) 0xE3, (byte) 0x03, (byte) 0x04, + (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, + (byte) 0x80, (byte) 0x00, (byte) 0x00, (byte) 0xA4, (byte) 0xEF, (byte) 0xE3, (byte) 0x03, (byte) 0x75, + (byte) 0x4E, (byte) 0xAA, (byte) 0x70, (byte) 0x01, (byte) 0x80, (byte) 0x00, (byte) 0x00, (byte) 0x00, + (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0xE8, (byte) 0xF1, (byte) 0xE3, (byte) 0x03, (byte) 0xD8, + (byte) 0x8F, (byte) 0x52, (byte) 0x04, (byte) 0xF0, (byte) 0x21, (byte) 0x75, (byte) 0x71, (byte) 0xB3, + (byte) 0x5F, (byte) 0xE4, (byte) 0x77, (byte) 0x7A, (byte) 0x03, (byte) 0x0D, (byte) 0x00, (byte) 0x0D, + (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x04, (byte) 0x01, (byte) 0x00, (byte) 0x00, (byte) 0xE8, + (byte) 0xF1, (byte) 0xE3, (byte) 0x03, (byte) 0xF0, (byte) 0xED, (byte) 0xE3, (byte) 0x03, (byte) 0x6F, + (byte) 0x27, (byte) 0x75, (byte) 0x71, (byte) 0x7A, (byte) 0x03, (byte) 0x0D, (byte) 0x00, (byte) 0x0D, + (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x04, (byte) 0x01, (byte) 0x00, (byte) 0x00, (byte) 0xE8, + (byte) 0xF1, (byte) 0xE3, (byte) 0x03, (byte) 0x9B, (byte) 0x27, (byte) 0x75, (byte) 0x71, (byte) 0xD4, + (byte) 0xEE, (byte) 0xE3, (byte) 0x03, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x80, + (byte) 0x04, (byte) 0x52, (byte) 0x04, (byte) 0x60, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x03, + (byte) 0x00, (byte) 0x00, (byte) 0xA0, (byte) 0x58, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, + (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x65, (byte) 0x32, (byte) 0x38, (byte) 0x32, (byte) 0x32, + (byte) 0x30, (byte) 0x34, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, + (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x06, (byte) 0xA0, (byte) 0x78, (byte) 0xF9, (byte) 0x08, + (byte) 0x80, (byte) 0xFF, (byte) 0x4E, (byte) 0x9C, (byte) 0x47, (byte) 0xF1, (byte) 0xD0, (byte) 0x77, + (byte) 0xFE, (byte) 0x54, (byte) 0xB6, (byte) 0x46, (byte) 0x18, (byte) 0x99, (byte) 0x1F, (byte) 0xA2, + (byte) 0xE1, (byte) 0xD9, (byte) 0x11, (byte) 0x86, (byte) 0xC3, (byte) 0x00, (byte) 0x0F, (byte) 0x1F, + (byte) 0xD8, (byte) 0x1B, (byte) 0x0F, (byte) 0x06, (byte) 0xA0, (byte) 0x78, (byte) 0xF9, (byte) 0x08, + (byte) 0x80, (byte) 0xFF, (byte) 0x4E, (byte) 0x9C, (byte) 0x47, (byte) 0xF1, (byte) 0xD0, (byte) 0x77, + (byte) 0xFE, (byte) 0x54, (byte) 0xB6, (byte) 0x46, (byte) 0x18, (byte) 0x99, (byte) 0x1F, (byte) 0xA2, + (byte) 0xE1, (byte) 0xD9, (byte) 0x11, (byte) 0x86, (byte) 0xC3, (byte) 0x00, (byte) 0x0F, (byte) 0x1F, + (byte) 0xD8, (byte) 0x1B, (byte) 0x0F, (byte) 0x10, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x05, + (byte) 0x00, (byte) 0x00, (byte) 0xA0, (byte) 0x24, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x42, + (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00}; +} diff --git a/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/io/MatchFilter.java b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/io/MatchFilter.java new file mode 100644 index 00000000000..8e73837a59c --- /dev/null +++ b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/io/MatchFilter.java @@ -0,0 +1,32 @@ +/******************************************************************************* + * 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.jdk.core.util.io; + +import java.io.File; +import java.io.FilenameFilter; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * @author Ryan D. Brooks + */ +public class MatchFilter implements FilenameFilter { + protected Matcher matcher; + + public MatchFilter(String pattern) { + this.matcher = Pattern.compile(pattern).matcher(""); + } + + public boolean accept(File dir, String fileName) { + matcher.reset(fileName); + return matcher.matches(); + } +}
\ No newline at end of file diff --git a/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/io/MinicomConnection.java b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/io/MinicomConnection.java new file mode 100644 index 00000000000..e18fdb12910 --- /dev/null +++ b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/io/MinicomConnection.java @@ -0,0 +1,169 @@ +/******************************************************************************* + * 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.jdk.core.util.io; + +import java.io.IOException; +import java.io.PipedReader; +import java.io.PipedWriter; +import java.io.PrintWriter; +import org.eclipse.osee.framework.jdk.core.util.Lib; + +/** + * Specifically used for connecting to minicom via the serial port and setting up an input and output stream. + * + * @author Michael P. Masterson + */ +public class MinicomConnection { + private static final int MAX_RESPONSE_TIME = 100000; + private static final int ITERATION_TIME = 2000; + + private InputBufferThread inputBuffer; + private PrintWriter commandLine; + + /** + * saves input and output streams then waits for minicom to load completely + */ + public MinicomConnection() { + super(); + setupConnection(); + waitForWelcomeScreen(); + } + + public static void main(String[] args) { + for (int i = 0; i < 20; i++) { + System.out.println("i = " + i + ", Making Connection..."); + MinicomConnection connection = new MinicomConnection(); + System.out.println("Connection made"); + System.out.println("Restarting..."); + connection.resetPizzaBox(); + } + System.out.println("Done with main"); + + } + + /** + * Uses a process builder to set up the minicom process executable. Using this it will create a thread for inputting + * commands to minicom. + */ + private void setupConnection() { + try { + ProcessBuilder pb = new ProcessBuilder(); + + // the path to the minicom program through linux. + String[] minicomExe = new String[] {"/usr/bin/minicom"}; + + // sets up the operating system command + pb.command(minicomExe); + + // starts a new process based on the minicom command + Process minicomProc = pb.start(); + + // the following three writers and readers will be used to issue minicom commands and read its responses + PipedWriter pw = new PipedWriter(); + commandLine = new PrintWriter(pw); + PipedReader pr = new PipedReader(pw); + + // send the textual output of minicom to the trash + PrintWriter outputFromTheMinicom = new PrintWriter(System.out); + + // sets up the minicom thread and directs minicom output to the two streams passed + inputBuffer = (InputBufferThread) Lib.handleMinicomProcess(minicomProc, outputFromTheMinicom, pr)[1]; + } catch (IOException ex) { + ex.printStackTrace(); + } + + } + + /** + * @return The printWriter for issuing commands to minicom + */ + public PrintWriter getCommandLine() { + return this.commandLine; + } + + /** + * reads input from the minicom until it sees a common line singifying it has completely loaded + */ + private void waitForWelcomeScreen() { + waitFor("Press CTRL-A Z for help on special keys"); + } + + /** + * Waits to either read in the expected reset completion line OR for the run command to see the completion line + */ + public void waitForReset() { + waitFor("Decompression complete"); + } + + /** + * Waits for the parameter passed to appear in the minicom output. Uses the InputBufferThread that should have been + * started before this. + * + * @param matcher The string to look for in the minicom's output stream + */ + public synchronized void waitFor(String matcher) { + try { + int elapsedTime = 0; + while (elapsedTime <= MAX_RESPONSE_TIME) { + if (inputBuffer.contains(matcher)) break; + + System.out.println("Input buffer did not contain " + matcher + " after " + elapsedTime + " milisecs"); + this.wait(ITERATION_TIME); + elapsedTime += ITERATION_TIME; + } + if (elapsedTime > MAX_RESPONSE_TIME) { + throw new InterruptedException( + "Waiting for '" + matcher + "' took longer then " + MAX_RESPONSE_TIME + " miliseconds."); + } + wait(4000); + + } catch (InterruptedException ex) { + ex.printStackTrace(); + } + + } + + /** + * Stops the buffering thread from running and closes the commandLine + */ + public void disconnect() { + System.out.println("Disconnecting..."); + inputBuffer.stopOnNextRun(true); + commandLine.close(); + System.out.println("Disconnect Finished"); + } + + /** + * Runs through the commands given through minicom that will reset the pizzabox. Once the command/s are given, it + * waits for the reset to complete before exitting minicom. + */ + public void resetPizzaBox() { + System.out.println("Issuing rset Command"); + // Issues the reset command to the OFP + commandLine.println("rset"); + + System.out.println("Waiting for reset"); + waitForReset(); + System.out.println("Reset Finished"); + + System.out.println("Issuing CTRL-A Q command"); + // quits minicom + commandLine.println((char) 1 + "q"); + + System.out.println("hitting enter on 'you sure you want to quit'"); + // hit enter on the "Are you sure you want to quit?" popup + commandLine.println(); + + disconnect(); + System.out.println("Done with resetPizzaBox"); + } + +} diff --git a/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/io/MinicomOutputThread.java b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/io/MinicomOutputThread.java new file mode 100644 index 00000000000..487202bb8c8 --- /dev/null +++ b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/io/MinicomOutputThread.java @@ -0,0 +1,109 @@ +/******************************************************************************* + * 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.jdk.core.util.io; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.Writer; + +/** + * Thread specifically used for connecting to minicom via the serial port and setting up an input and output stream. + * + * @author Michael P. Masterson + */ +public class MinicomOutputThread extends Thread { + private Writer output; + private BufferedReader input; + private boolean resetFinished; + + /** + * saves input and output streams then waits for minicom to load completely + */ + public MinicomOutputThread(Writer output, BufferedReader input) { + super(); + this.output = output; + this.input = input; + waitForWelcomScreen(); + resetFinished = false; + } + + /** + * reads input from the minicom until it sees a common line singifying it has completely loaded + */ + private void waitForWelcomScreen() { + try { + String welcomeLine = "Press CTRL-A Z for help on special keys"; + String outLine = null; + while ((outLine = input.readLine()) != null) { + output.write("\nWELCOME: " + outLine); + if (outLine.contains(welcomeLine)) break; + + } + } catch (IOException ex) { + ex.printStackTrace(); + } + } + + /** + * @return True if the text for the completion of a reset has been seen on the line + */ + public boolean isResetFinished() { + return this.resetFinished; + } + + /** + * Common run command for the thread. Sits on the serial line reading input from the minicom and printing it to the + * the output stream. If the expected end of a reset is found, it sets that field to indicate the reset is finished. + */ + public void run() { + String outLine = null; + try { + while ((outLine = input.readLine()) != null) { + if (!outLine.contains("[")) output.write(outLine + "\n"); + + if (outLine.contains("Start of wp_periodic_task")) { + output.write("Found end of reset\n"); + this.resetFinished = true; + } + + } + } catch (IOException ex) { + ex.printStackTrace(); + } finally { + try { + input.close(); + output.flush(); + } catch (IOException ex) { + ex.printStackTrace(); + } + } + } + + /** + * Waits to either read in the expected reset completion line OR for the run command to see the completion line + */ + public void waitForReset() { + try { + String outLine; + while ((outLine = input.readLine()) != null && !isResetFinished()) { + if (!outLine.contains("[")) output.write(outLine + "\n"); + + if (outLine.contains("Start of wp_periodic_task")) { + output.write("Found end of reset\n"); + break; + } + } + } catch (IOException ex) { + ex.printStackTrace(); + } + } + +} diff --git a/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/io/MultipleLinks.java b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/io/MultipleLinks.java new file mode 100644 index 00000000000..7450729d804 --- /dev/null +++ b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/io/MultipleLinks.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.jdk.core.util.io; + +import java.io.File; +import java.io.IOException; +import org.eclipse.osee.framework.jdk.core.util.Lib; + +/** + * @author Ryan D. Brooks + */ +public class MultipleLinks { + + public static void main(String[] args) throws IOException { + if (args.length < 3) { + System.out.println("Usage: java tc.MultipleLinks <file to link> <directory for links> <# of links>"); + return; + } + link(new File(args[0]), new File(args[1]), Integer.parseInt(args[2])); + } + + public static void link(File fileToLink, File directory, int linkCount) throws IOException { + if (!fileToLink.isFile()) { + throw new IllegalArgumentException(fileToLink + " is not a file."); + } + + fileToLink = fileToLink.getCanonicalFile(); + directory = directory.getCanonicalFile(); + if (directory.mkdir()) { + System.out.println("Created " + directory); + } + + //separate exstension and file name + String fileName = fileToLink.getName(); + String extension = ""; + int pos = fileName.lastIndexOf('.'); + if (pos != -1) { + extension = fileName.substring(pos); + } + fileName = Lib.stripExtension(fileToLink.getName()); + + String command = "ln -s " + fileToLink.getPath() + " " + directory.getPath() + File.separator + fileName; + for (int i = 0; i < linkCount; i++) { + Lib.handleProcess(Runtime.getRuntime().exec(command + i + extension)); + } + } +}
\ No newline at end of file diff --git a/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/io/RenameFiles.java b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/io/RenameFiles.java new file mode 100644 index 00000000000..0e67bd2ac28 --- /dev/null +++ b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/io/RenameFiles.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.jdk.core.util.io; + +import java.io.File; +import java.io.IOException; +import java.util.List; +import java.util.regex.Pattern; +import org.eclipse.osee.framework.jdk.core.text.Rule; +import org.eclipse.osee.framework.jdk.core.text.change.ChangeSet; +import org.eclipse.osee.framework.jdk.core.text.rules.ReplaceAll; +import org.eclipse.osee.framework.jdk.core.util.Lib; + +/** + * @author Ryan D. Brooks + */ +public class RenameFiles { + + public static void main(String[] args) throws IOException { + if (args.length < 3) { + System.out.println("Usage: java library.RenameFiles <directory> <full path pattern> <replacement>\n"); + return; + } + + Rule rule = new ReplaceAll(Pattern.compile(args[1]), args[2]); + List<File> files = Lib.recursivelyListFiles(new File(args[0]).getCanonicalFile(), null); + int size = files.size(); + int renamedFileCount = 0; + + for (int i = 0; i < size; i++) { + File file = (File) files.get(i); + ChangeSet newName = rule.computeChanges(file.getPath()); + if (rule.ruleWasApplicable()) { + File newFile = new File(newName.toString()); + if (file.renameTo(newFile)) { + System.out.println(file.getPath() + " became " + newFile.getPath()); + renamedFileCount++; + } else { + System.out.println(file.getPath() + " failed to become " + newFile.getPath()); + } + } + } + System.out.println("Changed " + renamedFileCount + " files"); + } +} diff --git a/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/io/Streams.java b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/io/Streams.java new file mode 100644 index 00000000000..b36d98fce16 --- /dev/null +++ b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/io/Streams.java @@ -0,0 +1,77 @@ +/******************************************************************************* + * 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.jdk.core.util.io; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.UnsupportedEncodingException; +import java.util.LinkedList; + +/** + * Utility class for working with Streams. + * + * @author Jeff C. Phillips + */ +public class Streams { + + private final static int ORACLE_BUFF_LENGTH = 4 * 8192; + + /** + * Converts a String into a InputStream using specifiec charSet + * + * @param string + * @param charSet + * @return Return input stream reference + * @throws UnsupportedEncodingException + */ + public static InputStream convertStringToInputStream(String string, String charSet) throws UnsupportedEncodingException { + return new ByteArrayInputStream(string.getBytes(charSet)); + } + + public static byte[] getByteArray(InputStream stream) { + + if (stream == null) throw new IllegalStateException("stream can not be null"); + + int length = -1; + long read = 0; + byte[] data = new byte[ORACLE_BUFF_LENGTH]; + LinkedList<byte[]> linkedByteArrays = new LinkedList<byte[]>(); + + try { + while ((length = stream.read(data)) != -1) { + linkedByteArrays.add(data); + read += length; + + // Get another buffer for the next go around + data = new byte[ORACLE_BUFF_LENGTH]; + + if (read > Integer.MAX_VALUE) throw new UnsupportedOperationException("The data is too large."); + } + } catch (IOException e) { + throw new RuntimeException(e); + } + + // Get a contiguous buffer for all of the pieces to go into + data = new byte[(int) read]; + int writeSize; + int index = 0; + + for (byte[] chunk : linkedByteArrays) { + writeSize = Math.min((int) read, ORACLE_BUFF_LENGTH); + System.arraycopy(chunk, 0, data, index, writeSize); + + read -= writeSize; + index += writeSize; + } + return data; + } +} diff --git a/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/io/Zip.java b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/io/Zip.java new file mode 100644 index 00000000000..45c94af7dd1 --- /dev/null +++ b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/io/Zip.java @@ -0,0 +1,114 @@ +/******************************************************************************* + * 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.jdk.core.util.io; + +import java.io.BufferedInputStream; +import java.io.BufferedOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.util.Enumeration; +import java.util.zip.ZipEntry; +import java.util.zip.ZipFile; +import java.util.zip.ZipOutputStream; + +public class Zip { + + public static void zip(String[] filenames, String outFilename) { + // These are the files to include in the ZIP file + // String[] filenames = new String[]{"filename1", "filename2"}; + + // Create a buffer for reading the files + byte[] buf = new byte[1024]; + + try { + // Create the ZIP file + ZipOutputStream out = new ZipOutputStream(new FileOutputStream(outFilename)); + + // Compress the files + for (int i = 0; i < filenames.length; i++) { + FileInputStream in = new FileInputStream(filenames[i]); + + // Add ZIP entry to output stream. + out.putNextEntry(new ZipEntry(filenames[i])); + + // Transfer bytes from the file to the ZIP file + int len; + while ((len = in.read(buf)) > 0) { + out.write(buf, 0, len); + } + + // Complete the entry + out.closeEntry(); + in.close(); + } + + // Complete the ZIP file + out.close(); + } catch (IOException e) { + } + + } + + public static void unzip(File zipFile, File destinationDir, IZipEntryCompleteCallback progressBar) throws IOException { + int BUFFER = 2048; + BufferedOutputStream dest = null; + BufferedInputStream is = null; + ZipEntry entry = null; + + try { + ZipFile zipfile = new ZipFile(zipFile.getAbsolutePath()); + progressBar.setValue(0); + progressBar.setMinimum(0); + progressBar.setMaximum(zipfile.size()); + System.out.println(zipfile.size()); + Enumeration<? extends ZipEntry> e = zipfile.entries(); + int size = 0; + while (e.hasMoreElements()) { + entry = (ZipEntry) e.nextElement(); + is = new BufferedInputStream(zipfile.getInputStream(entry)); + int count; + byte data[] = new byte[BUFFER]; + File fileDir = new File(destinationDir.getAbsolutePath() + File.separator + entry.getName()); + if (entry.isDirectory()) { + fileDir.mkdirs(); + progressBar.setValue(++size); + continue; + } else { + fileDir.getParentFile().mkdirs(); + } + + if (!fileDir.exists() || (fileDir.exists() && fileDir.canWrite())) { + FileOutputStream fos = new FileOutputStream(fileDir.getAbsolutePath()); + dest = new BufferedOutputStream(fos, BUFFER); + while ((count = is.read(data, 0, BUFFER)) != -1) { + dest.write(data, 0, count); + } + dest.flush(); + dest.close(); + } + + is.close(); + + if (fileDir.getAbsolutePath().endsWith(".lnk")) { + if (fileDir.canWrite()) { + fileDir.setReadOnly(); + } + } + progressBar.setValue(++size); + } + } catch (Exception ex) { + String information = "ZipFile: " + (zipFile != null ? zipFile.getAbsolutePath() : "NULL") + "\n" + "DestinationDir: " + (destinationDir != null ? destinationDir.getAbsolutePath() : "NULL") + "\n" + "Entry Processed: " + (entry != null ? entry.toString() : "NULL") + "\n"; + throw new IOException(information + ex.getMessage()); + } + } +}
\ No newline at end of file diff --git a/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/io/streams/StreamCatcher.java b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/io/streams/StreamCatcher.java new file mode 100644 index 00000000000..c2e2b2efed7 --- /dev/null +++ b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/io/streams/StreamCatcher.java @@ -0,0 +1,60 @@ +/******************************************************************************* + * Copyright (c) 2004, 2007 Boeing. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Boeing - initial API and implementation + *******************************************************************************/ +package org.eclipse.osee.framework.jdk.core.util.io.streams; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.util.logging.Level; +import java.util.logging.Logger; + +/** + * @author Jeff C. Phillips + */ +public class StreamCatcher extends Thread { + private InputStream is; + private String type; + private Logger logger; + + public StreamCatcher(InputStream is, String type) { + this(is, type, null); + } + + public StreamCatcher(InputStream is, String type, Logger logger) { + this.is = is; + this.type = type; + this.logger = logger; + } + + public void run() { + try { + InputStreamReader isr = new InputStreamReader(is); + BufferedReader br = new BufferedReader(isr); + String line = null; + String loggerError = ""; + + while ((line = br.readLine()) != null) { + + if (logger == null) + System.out.println(type + ">" + line); + else + loggerError += line + "\n"; + + } + + if (logger != null && loggerError.length() > 0) logger.log(Level.SEVERE, loggerError); + + } catch (IOException ioe) { + ioe.printStackTrace(); + } + } +} diff --git a/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/io/xml/AbstractSaxHandler.java b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/io/xml/AbstractSaxHandler.java new file mode 100644 index 00000000000..f35d9535550 --- /dev/null +++ b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/io/xml/AbstractSaxHandler.java @@ -0,0 +1,75 @@ +/******************************************************************************* + * 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.jdk.core.util.io.xml; + +import java.io.IOException; +import org.xml.sax.Attributes; +import org.xml.sax.SAXException; +import org.xml.sax.helpers.DefaultHandler; + +/** + * @author Ryan D. Brooks + */ +public abstract class AbstractSaxHandler extends DefaultHandler { + // Buffer for collecting data from the "characters" SAX event. + private StringBuilder contents; + private final int maxContentLength; + + protected AbstractSaxHandler() { + this(0); + } + + protected AbstractSaxHandler(int maxContentLength) { + this.contents = new StringBuilder(2000); + this.maxContentLength = maxContentLength; + } + + /* (non-Javadoc) + * @see org.xml.sax.helpers.DefaultHandler#characters(char[], int, int) + */ + @Override + public void characters(char[] ch, int start, int length) throws SAXException { + if (maxContentLength > 0 && contents.length() + length > maxContentLength) { + return; // don't add more characters if doing so will make the content too long + } + contents.append(ch, start, length); + } + + /* (non-Javadoc) + * @see org.xml.sax.helpers.DefaultHandler#endElement(java.lang.String, java.lang.String, java.lang.String) + */ + @Override + public void endElement(String uri, String localName, String qName) throws SAXException { + endElementFound(uri, localName, qName); + contents.setLength(0); // efficiently reset the StringBuilder to be empty (but preserve its capacity) + } + + /* (non-Javadoc) + * @see org.xml.sax.helpers.DefaultHandler#startElement(java.lang.String, java.lang.String, java.lang.String, org.xml.sax.Attributes) + */ + @Override + public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { + startElementFound(uri, localName, qName, attributes); + contents.setLength(0); // efficiently reset the StringBuilder to be empty (but preserve its capacity) + } + + public abstract void startElementFound(String uri, String localName, String qName, Attributes attributes) throws SAXException; + + public abstract void endElementFound(String uri, String localName, String qName) throws SAXException; + + public String getContents() { + return contents.toString(); + } + + public void addContentsTo(Appendable appendable) throws IOException { + appendable.append(contents); + } +}
\ No newline at end of file diff --git a/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/io/xml/ExcelSaxHandler.java b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/io/xml/ExcelSaxHandler.java new file mode 100644 index 00000000000..01e71e0da56 --- /dev/null +++ b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/io/xml/ExcelSaxHandler.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.jdk.core.util.io.xml; + +import java.util.Arrays; +import org.eclipse.osee.framework.jdk.core.util.io.xml.excel.ExcelXmlWriter; +import org.xml.sax.Attributes; +import org.xml.sax.SAXException; + +/** + * @author Ryan D. Brooks + */ +public class ExcelSaxHandler extends AbstractSaxHandler { + private String[] row; + private int cellIndex; + private int rowIndex; + private final RowProcessor rowProcessor; + private boolean isRowHeader; + private final boolean firstRowIsHeader; + private final boolean multiTable; + private boolean rowEmpty; + + public ExcelSaxHandler(RowProcessor rowProcessor, boolean firstRowIsHeader, boolean enableMultiTableSupport) { + super(); + this.rowProcessor = rowProcessor; + this.firstRowIsHeader = firstRowIsHeader; + this.multiTable = enableMultiTableSupport; + rowIndex = 0; + } + + public ExcelSaxHandler(RowProcessor rowProcessor, boolean hasHeaderRow) { + this(rowProcessor, hasHeaderRow, false); + } + + /* + * (non-Javadoc) + * + * @see org.eclipse.osee.framework.jdk.core.util.io.xml.AbstractSaxHandler#startElementFound(java.lang.String, + * java.lang.String, java.lang.String, org.xml.sax.Attributes) + */ + @Override + public void startElementFound(String uri, String localName, String qName, Attributes attributes) throws SAXException { + if (localName.equalsIgnoreCase("Row")) { + cellIndex = -1; // so that upon finding the first cell start element the index becomes 0 + rowEmpty = true; + // null out because any empty cells would otherwise contain data from the previous row + Arrays.fill(row, 0, row.length, null); + + String indexStr = attributes.getValue("ss:Index"); + if (indexStr != null) { + int oldRowIndex = rowIndex; + rowIndex = Integer.parseInt(indexStr) - 1; // translate from Excel's 1-based index to + // our 0-based index + for (int i = oldRowIndex; i < rowIndex; i++) { + rowProcessor.processEmptyRow(); + } + } else { + rowIndex++; + } + } else if (localName.equalsIgnoreCase("Cell")) { + String indexStr = attributes.getValue("ss:Index"); + if (indexStr != null) { + cellIndex = Integer.parseInt(indexStr) - 1; // translate from Excel's 1-based index to + // our 0-based index + } else { + cellIndex++; + } + } else if (localName.equalsIgnoreCase("Table")) { + String columnCountStr = attributes.getValue("ss:ExpandedColumnCount"); + if (columnCountStr == null) { + throw new IllegalArgumentException("missing ss:ExpandedColumnCount attribute of Table element"); + } + row = new String[Integer.parseInt(columnCountStr)]; + + String rowCountStr = attributes.getValue("ss:ExpandedRowCount"); + if (rowCountStr == null) { + rowCountStr = "0"; + } + rowProcessor.detectedRowAndColumnCounts(Integer.parseInt(rowCountStr), row.length); + } else if (localName.equalsIgnoreCase("Worksheet")) { + isRowHeader = firstRowIsHeader; // next non-empty row will be considered a header (if + // applicable) + rowProcessor.foundStartOfWorksheet(attributes.getValue("ss:Name")); + // System.out.println("Worksheet =" +attributes.getValue("ss:Name")); + } + } + + /* + * (non-Javadoc) + * + * @see org.eclipse.osee.framework.jdk.core.util.io.xml.AbstractSaxHandler#endElementWithClearContents(java.lang.String, + * java.lang.String, java.lang.String) + */ + @Override + public void endElementFound(String uri, String localName, String qName) throws SAXException { + if (localName.equalsIgnoreCase("Data")) { + String contentStr = getContents(); + if (!contentStr.equals(ExcelXmlWriter.blobMessage)) { + if (contentStr.equals(ExcelXmlWriter.defaultEmptyString)) { + row[cellIndex] = ""; + } else { + row[cellIndex] = contentStr; + } + } + rowEmpty = false; + } else if (localName.equalsIgnoreCase("Row")) { + if (rowEmpty) { + rowProcessor.processEmptyRow(); + if (multiTable) { + isRowHeader = true; // next non-empty row will be considered a header + } + } else if (row[0] != null && row[0].startsWith("#")) { + rowProcessor.processCommentRow(row); + } else if (isRowHeader) { + isRowHeader = false; + rowProcessor.processHeaderRow(row); + } else { + rowProcessor.processRow(row); + } + } else if (localName.equalsIgnoreCase("Worksheet")) { + rowProcessor.reachedEndOfWorksheet(); + } else if (localName.equalsIgnoreCase("EmbeddedClob")) { + row[cellIndex] = getContents(); + } + } +}
\ No newline at end of file diff --git a/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/io/xml/RowProcessor.java b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/io/xml/RowProcessor.java new file mode 100644 index 00000000000..fd8553fc073 --- /dev/null +++ b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/io/xml/RowProcessor.java @@ -0,0 +1,30 @@ +/******************************************************************************* + * 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.jdk.core.util.io.xml; + +/** + * @author Ryan D. Brooks + */ +public interface RowProcessor { + public abstract void processRow(String[] row); + + public abstract void processHeaderRow(String[] row); + + public abstract void processEmptyRow(); + + public abstract void processCommentRow(String[] row); + + public abstract void reachedEndOfWorksheet(); + + public abstract void foundStartOfWorksheet(String sheetName); + + public abstract void detectedRowAndColumnCounts(int rowCount, int columnCount); +} diff --git a/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/io/xml/WordMlTableWriter.java b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/io/xml/WordMlTableWriter.java new file mode 100644 index 00000000000..7d2658b716a --- /dev/null +++ b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/io/xml/WordMlTableWriter.java @@ -0,0 +1,121 @@ +/******************************************************************************* + * 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.jdk.core.util.io.xml; + +import java.io.File; +import java.io.IOException; +import java.nio.charset.CharacterCodingException; +import org.eclipse.osee.framework.jdk.core.util.Lib; +import org.eclipse.osee.framework.jdk.core.util.io.CharBackedInputStream; +import org.eclipse.osee.framework.jdk.core.util.io.xml.excel.ISheetWriter; + +/** + * @author Jeff C. Phillips + */ +public class WordMlTableWriter implements ISheetWriter { + private static final String TABLE_START = "<w:tbl><w:tblPr><w:tblBorders><w:top w:val=\"single\" w:sz=\"1\" /><w:left w:val=\"single\" w:sz=\"1\" /><w:bottom w:val=\"single\" w:sz=\"1\" /><w:right w:val=\"single\" w:sz=\"1\" /><w:insideH w:val=\"single\" w:sz=\"1\" /><w:insideV w:val=\"single\" w:sz=\"1\" /></w:tblBorders></w:tblPr>"; + private static final String TABLE_END = "</w:tbl>"; + private static final String START_TABLE_GRID = "<w:tblGrid>"; + private static final String END_TABLE_GRID = "</w:tblGrid>"; + private static final String TABLE_GRID = "<w:gridCol w:w=\"1024\" />"; + private static final String CELL_STRART = "<w:tc><w:tcPr><w:tcW w:w=\"1024\" /></w:tcPr><w:p><w:r><w:t>"; + private static final String CELL_END = "</w:t></w:r></w:p></w:tc>"; + private static final String ROW_START = "<w:tr>"; + private static final String ROW_END = "</w:tr>"; + private final Appendable str; + private int columnSize; + private boolean startTable; + + public WordMlTableWriter(Appendable str) throws CharacterCodingException { + this.str = str; + } + + public void startSheet(String worksheetName) throws IOException { + startSheet(worksheetName, -1); + } + + public void startSheet(String worksheetName, int columnCount) throws IOException { + str.append(TABLE_START); + columnSize = columnCount; + startTable = true; + } + + public void endSheet() throws IOException { + str.append(TABLE_END); + } + + public void writeRow(String... row) throws IOException { + // column size is set when the first row is created. + if (startTable) { + if (columnSize < 0) { + columnSize = row.length; + writeTableGridData(); + } + } + + /* if (row.length != columnSize) { + throw new IllegalArgumentException("Table columns need to be the same size."); + }*/ + str.append(ROW_START); + + for (String data : row) { + writeTextCell(data); + } + str.append(ROW_END); + } + + private void writeTableGridData() throws IOException { + str.append(START_TABLE_GRID); + + for (int i = 0; i < columnSize; i++) { + str.append(TABLE_GRID); + } + str.append(END_TABLE_GRID); + } + + private void writeTextCell(String data) throws IOException { + str.append(CELL_STRART); + if (data != null) { + str.append(data); + } + str.append(CELL_END); + } + + /** + * @param args + */ + public static void main(String[] args) { + CharBackedInputStream charBak; + try { + charBak = new CharBackedInputStream(); + WordMlTableWriter wordMl = new WordMlTableWriter(charBak); + + wordMl.startSheet("hello"); + wordMl.writeRow("hi", "there"); + wordMl.writeRow("hi", "there"); + + wordMl.endSheet(); + + StringBuffer buffer = new StringBuffer(); + buffer.append(System.getProperty("user.home")); + buffer.append(File.separator); + buffer.append(WordMlTableWriter.class.getName()); + buffer.append(".test.xml"); + + Lib.inputStreamToFile(charBak, new File(buffer.toString())); + } catch (Exception ex) { + System.out.println(ex.getMessage()); + } + } + + public void endWorkbook() throws IOException { + } +} diff --git a/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/io/xml/WordSaxHandler.java b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/io/xml/WordSaxHandler.java new file mode 100644 index 00000000000..18a0f116a10 --- /dev/null +++ b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/io/xml/WordSaxHandler.java @@ -0,0 +1,85 @@ +/******************************************************************************* + * 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.jdk.core.util.io.xml; + +import java.io.IOException; +import org.xml.sax.Attributes; +import org.xml.sax.SAXException; + +/** + * @author Ryan D. Brooks + */ +public class WordSaxHandler extends AbstractSaxHandler { + private boolean inHeader; + private boolean inFooter; + private StringBuilder headerText; + private StringBuilder footerText; + + public WordSaxHandler() { + super(); + headerText = new StringBuilder(); + footerText = new StringBuilder(); + } + + public void reset() { + headerText.delete(0, 99999999); + footerText.delete(0, 99999999); + } + + /* (non-Javadoc) + * @see org.eclipse.osee.framework.jdk.core.util.io.xml.AbstractSaxHandler#startElementFound(java.lang.String, java.lang.String, java.lang.String, org.xml.sax.Attributes) + */ + @Override + public void startElementFound(String uri, String localName, String qName, Attributes attributes) throws SAXException { + if (localName.equalsIgnoreCase("hdr")) { + inHeader = true; + } else if (localName.equalsIgnoreCase("ftr")) { + inFooter = true; + } else if (localName.equalsIgnoreCase("Table")) { + + } else if (localName.equalsIgnoreCase("Worksheet")) { + + } + } + + /* + * (non-Javadoc) + * + * @see org.eclipse.osee.framework.jdk.core.util.io.xml.AbstractSaxHandler#endElementWithClearContents(java.lang.String, + * java.lang.String, java.lang.String) + */ + @Override + public void endElementFound(String uri, String localName, String qName) throws SAXException { + try { + if (localName.equalsIgnoreCase("t")) { + if (inHeader) { + addContentsTo(headerText); + } else if (inFooter) { + addContentsTo(footerText); + } + } else if (localName.equalsIgnoreCase("hdr")) { + inHeader = false; + } else if (localName.equalsIgnoreCase("ftr")) { + inFooter = false; + } + } catch (IOException ex) { + throw new SAXException(ex); + } + } + + public String getHeaderText() { + return headerText.toString(); + } + + public String getFooterText() { + return footerText.toString(); + } +}
\ No newline at end of file diff --git a/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/io/xml/XmlStraightener.java b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/io/xml/XmlStraightener.java new file mode 100644 index 00000000000..ae870a16540 --- /dev/null +++ b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/io/xml/XmlStraightener.java @@ -0,0 +1,47 @@ +/******************************************************************************* + * Copyright (c) 2004, 2007 Boeing. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Boeing - initial API and implementation + *******************************************************************************/ +package org.eclipse.osee.framework.jdk.core.util.io.xml; + +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import org.eclipse.osee.framework.jdk.core.text.Rule; +import org.eclipse.osee.framework.jdk.core.text.change.ChangeSet; +import org.eclipse.osee.framework.jdk.core.util.Lib; + +/** + * @author Ryan D. Brooks + */ +public class XmlStraightener extends Rule { + private static final Pattern tagPattern = Pattern.compile("<[^!][^>]*>"); + + /** + * @param outExtension + */ + public XmlStraightener(String outExtension) { + super(outExtension); + } + + /* (non-Javadoc) + * @see org.eclipse.osee.framework.jdk.core.text.Rule#computeChanges(java.lang.CharSequence) + */ + @Override + public ChangeSet computeChanges(CharSequence seq) { + ChangeSet changeSet = new ChangeSet(seq); + + Matcher tagMatcher = tagPattern.matcher(seq); + while (tagMatcher.find()) { + changeSet.insertBefore(tagMatcher.end(), Lib.lineSeparator); + ruleWasApplicable = true; + } + + return changeSet; + } +}
\ No newline at end of file diff --git a/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/io/xml/excel/ExcelXmlWriter.java b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/io/xml/excel/ExcelXmlWriter.java new file mode 100644 index 00000000000..96eb2e0a5c9 --- /dev/null +++ b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/io/xml/excel/ExcelXmlWriter.java @@ -0,0 +1,140 @@ +/******************************************************************************* + * 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.jdk.core.util.io.xml.excel; + +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileWriter; +import java.io.IOException; +import java.io.Writer; +import org.eclipse.osee.framework.jdk.core.util.xml.Xml; + +/** + * @author Ryan D. Brooks + */ +public class ExcelXmlWriter implements ISheetWriter { + private BufferedWriter out; + private boolean inSheet; + private boolean startTable; + private int columnCount; + private String emptyStringRepresentation; + public static final String defaultEmptyStringXmlRep = "ø"; + public static final String defaultEmptyString = "\u00F8"; + public static final String blobMessage = "data stored in EmbeddedClob since longer than 32767 chars"; + + public ExcelXmlWriter(Writer writer) throws IOException { + super(); + out = new BufferedWriter(writer); + emptyStringRepresentation = defaultEmptyStringXmlRep; + + out.write("<?xml version=\"1.0\"?>\n"); + out.write("<?mso-application progid=\"Excel.Sheet\"?>\n"); + out.write("<Workbook xmlns=\"urn:schemas-microsoft-com:office:spreadsheet\"\n"); + out.write(" xmlns:o=\"urn:schemas-microsoft-com:office:office\"\n"); + out.write(" xmlns:x=\"urn:schemas-microsoft-com:office:excel\"\n"); + out.write(" xmlns:ss=\"urn:schemas-microsoft-com:office:spreadsheet\"\n"); + out.write(" xmlns:html=\"http://www.w3.org/TR/REC-html40\">\n"); + } + + public ExcelXmlWriter(File file) throws IOException { + this(new FileWriter(file)); + } + + /* (non-Javadoc) + * @see org.eclipse.osee.framework.jdk.core.util.io.xml.excel.ISheetWriter#startSheet(java.lang.String) + */ + public void startSheet(String worksheetName) throws IOException { + startSheet(worksheetName, -1); + } + + public void startSheet(String worksheetName, int columnCount) throws IOException { + this.columnCount = columnCount; + if (worksheetName.length() > 31) { + worksheetName = worksheetName.substring(0, 31); + } + out.write(String.format(" <Worksheet ss:Name=\"%s\">\n", worksheetName)); + + inSheet = true; + startTable = true; + } + + /* (non-Javadoc) + * @see org.eclipse.osee.framework.jdk.core.util.io.xml.excel.ISheetWriter#endSheet() + */ + public void endSheet() throws IOException { + if (startTable) { + out.write(" <Table x:FullColumns=\"1\" x:FullRows=\"1\">\n"); + startTable = false; + } + out.write(" </Table>\n"); + out.write(" </Worksheet>\n"); + inSheet = false; + startTable = false; + } + + public void endWorkbook() throws IOException { + if (inSheet) { + endSheet(); + } + out.write("</Workbook>\n"); + out.close(); + } + + /* (non-Javadoc) + * @see org.eclipse.osee.framework.jdk.core.util.io.xml.excel.ISheetWriter#writeRow(java.lang.String) + */ + public void writeRow(String... row) throws IOException { + if (startTable) { + if (columnCount < 0) { + columnCount = row.length; + } + if (columnCount > 256) { + throw new IllegalArgumentException("Excel does not support more than 256 columns: " + columnCount); + } + out.write(" <Table x:FullColumns=\"1\" x:FullRows=\"1\" ss:ExpandedColumnCount=\"" + columnCount + "\">\n"); + startTable = false; + } + + out.write(" <Row>\n"); + boolean cellSkipped = false; + for (int cellIndex = 0; cellIndex < row.length; cellIndex++) { + String cellData = row[cellIndex]; + if (cellData == null) { + cellSkipped = true; + } else { + out.write(" <Cell"); + if (cellSkipped) { + out.write(" ss:Index=\"" + (cellIndex + 1) + "\""); + cellSkipped = false; + } + out.write(">"); + out.write("<Data ss:Type=\"String\">"); + if (cellData.equals("")) { + out.write(emptyStringRepresentation); + } else { + if (cellData.length() > 32767) { + out.write(blobMessage); + } else { + Xml.writeAsCdata(out, cellData); + } + } + out.write("</Data>"); + if (cellData.length() > 32767) { + out.write("<EmbeddedClob>"); + Xml.writeAsCdata(out, cellData); + out.write("</EmbeddedClob>"); + } + out.write("</Cell>\n"); + } + } + out.write(" </Row>\n"); + } +}
\ No newline at end of file diff --git a/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/io/xml/excel/ISheetWriter.java b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/io/xml/excel/ISheetWriter.java new file mode 100644 index 00000000000..579ce209e71 --- /dev/null +++ b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/io/xml/excel/ISheetWriter.java @@ -0,0 +1,30 @@ +/******************************************************************************* + * 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.jdk.core.util.io.xml.excel; + +import java.io.IOException; + +/** + * @author Robert A. Fisher + */ +public interface ISheetWriter { + + public void startSheet(String worksheetName) throws IOException; + + public void startSheet(String worksheetName, int columnCount) throws IOException; + + public void endSheet() throws IOException; + + public void writeRow(String... row) throws IOException; + + public void endWorkbook() throws IOException; + +}
\ No newline at end of file diff --git a/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/network/PortUtil.java b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/network/PortUtil.java new file mode 100644 index 00000000000..76d7a042113 --- /dev/null +++ b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/network/PortUtil.java @@ -0,0 +1,119 @@ +/******************************************************************************* + * 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.jdk.core.util.network; + +import java.io.IOException; +import java.net.DatagramSocket; +import java.net.InetAddress; +import java.net.ServerSocket; + +/** + * @author Andrew M. Finkbeiner + */ +public class PortUtil { + + private static PortUtil singleton; + @SuppressWarnings("unused") + private ServerSocket ss; + + public static PortUtil getInstance() { + if (singleton == null) { + singleton = new PortUtil(); + } + return singleton; + } + + int basePort = 18000; + int nextPort = 18000; + + private PortUtil() { + for (int j = nextPort; j < 64000; j += 250) { + if (checkIfPortIsTaken(j)) { + basePort = nextPort = j; + try { + ss = new ServerSocket(basePort); + } catch (IOException e) { + e.printStackTrace(); + } + break; + } + } + } + + public int getValidPort() throws IOException { + int port = getConsecutiveValidPorts(1); + return port; + } + + public int getConsecutiveValidPorts(int numberOfPorts) throws IOException { + try { + int returnVal = getConsecutiveLocalPorts(numberOfPorts); + nextPort = returnVal + numberOfPorts; + return returnVal; + } catch (Exception e) { + e.printStackTrace(); + IOException ioE = new IOException("Unable to get a valid port."); + ioE.initCause(e); + throw ioE; + } + } + + /** + * @param numberOfPorts The number of consecutive available ports to find + * @return The port of first number in the sequence of valid ports + * @throws Exception + */ + private int getConsecutiveLocalPorts(int numberOfPorts) throws Exception { + if (nextPort >= basePort + 250 - numberOfPorts) { + nextPort = basePort; + } + for (int i = nextPort, count = 1; i < basePort + 250; i++, count++) { + boolean passed = true; + for (int j = i; j < numberOfPorts + i; j++) { + if (!checkIfPortIsTaken(j)) { + passed = false; + break; + } + } + if (passed) { + return i; + } + } + throw new Exception("Unable to find valid port."); + } + + private boolean checkIfPortIsTaken(int port) { + return checkTcpIp(port) && checkUdpPort(port); + } + + private boolean checkTcpIp(int port) { + try { + ServerSocket socket; + socket = new ServerSocket(port); + socket.close(); + } catch (Exception e) { + return false; + } + return true; + } + + private boolean checkUdpPort(int port) { + try { + DatagramSocket ds = new DatagramSocket(port, InetAddress.getLocalHost()); + ds.close(); + ds.disconnect(); + } catch (Exception e) { + return false; + } + return true; + } +} diff --git a/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/requirement/RequirementId.java b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/requirement/RequirementId.java new file mode 100644 index 00000000000..585c385c79a --- /dev/null +++ b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/requirement/RequirementId.java @@ -0,0 +1,105 @@ +/******************************************************************************* + * 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.jdk.core.util.requirement; + +import java.util.Vector; +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 Ryan D. Brooks + * @author Robert A. Fisher + */ +public class RequirementId implements Xmlizable { + // TODO add requirement data + private String description; + private Vector<String> partialDescriptions; + private int timesVerified; + private boolean isPartial, isWhole, conflictExists; + + /** + * + */ + public RequirementId() { + this(""); + this.timesVerified = 0; + this.isPartial = false; + this.isWhole = false; + this.conflictExists = false; + } + + public RequirementId(String description) { + super(); + this.description = description; + } + + public String toString() { + return description; + } + + public Element toXml(Document doc) { + return Jaxp.createElement(doc, "RequirementId", description); + } + + public boolean conflictPresent() { + return conflictExists; + } + + /** + * Increments the count for how many times this requirement has been verified (which should only be once). If this + * requirement has already been marked as being previously verified (either partially or wholly) than a conflict flag + * will be set since a requirement can only be wholly verified once. + */ + public void verifiedHere() { + + // TODO add ability to store in what script this requirement is verified. + + if (isPartial || isWhole) { + conflictExists = true; + } else { + isWhole = true; + timesVerified++; + } + + } + + /** + * Adds a new description to the partial requirement description vector and increments the count for how many times + * this requirement has been verified. If this requirement has already been marked as being wholly verified than a + * conflict flag will be set since a partial verify is not needed. + * + * @param partialDesc - Helpful and concise description of what part of the requirement is being verified. + */ + public void partiallyVerifiedHere(String partialDesc) { + + // TODO add ability to store in what script or function this requirement is partially verified. + + if (isWhole) { + conflictExists = true; + } else { + if (!isPartial) { + isPartial = true; + } + + partialDescriptions.add(partialDesc); + timesVerified++; + } + + } + + public void usedHere() { + + // TODO add ability to store in what script or function this requirement is used. + + } +}
\ No newline at end of file diff --git a/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/time/GlobalTime.java b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/time/GlobalTime.java new file mode 100644 index 00000000000..d34556959ad --- /dev/null +++ b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/time/GlobalTime.java @@ -0,0 +1,30 @@ +/******************************************************************************* + * 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.jdk.core.util.time; + +import java.sql.Timestamp; +import java.util.Calendar; +import java.util.TimeZone; + +/** + * @author Jeff C. Phillips + */ +public class GlobalTime { + + public static Timestamp GreenwichMeanTimestamp() { + return new Timestamp(GreenwichMeanTimeMillis()); + } + + public static long GreenwichMeanTimeMillis() { + return Calendar.getInstance(TimeZone.getTimeZone("GMT")).getTimeInMillis(); + } + +} diff --git a/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/windows/OutlookCalendarEvent.java b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/windows/OutlookCalendarEvent.java new file mode 100644 index 00000000000..399b6bb5e7a --- /dev/null +++ b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/windows/OutlookCalendarEvent.java @@ -0,0 +1,47 @@ +/******************************************************************************* + * Copyright (c) 2004, 2007 Boeing. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Boeing - initial API and implementation + *******************************************************************************/ +package org.eclipse.osee.framework.jdk.core.util.windows; + +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.Date; + +public class OutlookCalendarEvent { + + private String location; + private String event; + private Date date; + private DateFormat myDateFormat; + private String startTime; + private String endTime; + + /** + * @param location - String the event location + * @param event - String the scheduled event + * @param date + * @param startTime + * @param endTime + */ + public OutlookCalendarEvent(String location, String event, Date date, String startTime, String endTime) { + super(); + this.location = location; + this.event = event; + this.date = date; + this.startTime = startTime; + this.endTime = endTime; + myDateFormat = new SimpleDateFormat("yyyyMMdd"); + } + + public String getEvent() { + return "\nBEGIN:VCALENDAR\n" + "PRODID:-//Microsoft Corporation//Outlook 10.0 MIMEDIR//EN\n" + "VERSION:1.0\n" + "BEGIN:VEVENT\n" + "DTSTART:" + myDateFormat.format(date) + "T" + startTime + "00\n" + "DTEND:" + myDateFormat.format(date) + "T" + endTime + "00\n" + "LOCATION;ENCODING=QUOTED-PRINTABLE:" + location + "\n" + "TRANSP:1\n" + "DESCRIPTION;ENCODING=QUOTED-PRINTABLE:=0D=0A\n" + "SUMMARY;ENCODING=QUOTED-PRINTABLE:Event:" + event + "\n" + "PRIORITY:3\n" + "END:VEVENT\n" + "END:VCALENDAR\n"; + } + +} diff --git a/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/windows/Registry.java b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/windows/Registry.java new file mode 100644 index 00000000000..9b953d46e81 --- /dev/null +++ b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/windows/Registry.java @@ -0,0 +1,214 @@ +/******************************************************************************* + * 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.jdk.core.util.windows; + +import java.io.File; +import java.io.IOException; +import java.io.StringWriter; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import org.eclipse.osee.framework.jdk.core.util.Lib; + +public class Registry { + + public static final String HKEY_LOCAL_MACHINE = "HKLM"; + public static final String HKEY_CURRENT_USER = "HKCU"; + public static final String REG_SZ = "REG_SZ"; + public static final String REG_HELP_CMD = "reg /?"; + + public abstract interface RegVersion { + abstract public String getQueryCmd(String root, String path, String key); + + abstract public String getQueryPattern(String key); + + abstract public String getUpdateCommand(String root, String path, String key, String value, String[] regArray); + + abstract public String isVersion(); + } + + public class RegVersion_1_00 implements RegVersion { + public String getQueryCmd(String root, String path, String key) { + return "reg query " + root + "\\" + path + "\\" + key; + } + + public String getQueryPattern(String key) { + return "out:\\s*(\\w*)\\s*" + key + "\\s*(.*)"; + } + + public String getUpdateCommand(String root, String path, String key, String value, String[] regArray) { + String cmd = ""; + if (regArray != null) { + value = value + File.pathSeparator + regArray[1]; + System.out.println("THE VALUE IS: " + value); + cmd = "reg update \"" + root + "\\" + path + "\\" + key + "=" + value + "\""; + } else { + cmd = "reg add \"" + root + "\\" + path + "\\" + key + "=" + value + "\""; + } + + System.out.println("THE CMD IS: " + cmd); + + return cmd; + } + + public String isVersion() { + return "1.00"; + } + } + + public class RegVersion_3_0 implements RegVersion { + + public String getQueryCmd(String root, String path, String key) { + return "reg query " + root + "\\" + path + " /v " + key; + } + + public String getQueryPattern(String key) { + return ".*?" + key + "\\s*(\\w*)\\s*(\\S*).*"; + } + + public String getUpdateCommand(String root, String path, String key, String value, String[] regArray) { + String type = Registry.REG_SZ; + if (regArray != null) { + value = value + File.pathSeparator + regArray[1]; + type = regArray[0]; + } + return "reg add " + root + "\\" + path + " /v " + key + " /t " + type + " /f /d \"" + value + "\""; + } + + public String isVersion() { + return "3.0"; + } + } + + public static boolean isRegVersion(double lowerBound, double upperBound) throws IOException { + boolean matched = false; + Process p = Runtime.getRuntime().exec(Registry.REG_HELP_CMD); + StringWriter stringWriter = new StringWriter(); + Lib.handleProcess(p, stringWriter); + + Pattern pattern = Pattern.compile(".*version\\s(\\d*\\.\\d+).*", Pattern.DOTALL); + Matcher matcher = pattern.matcher(stringWriter.toString()); + + System.out.println(matcher.groupCount()); + if (matcher.matches()) { + String regVersion = matcher.group(1).trim(); + System.out.println("Found Version: " + regVersion); + + double foundVersion = Double.parseDouble(regVersion); + if ((foundVersion >= lowerBound) && (foundVersion <= upperBound)) { + matched = true; + } + } + return matched; + } + + public static RegVersion getVersion() throws IOException { + Registry r = new Registry(); + RegVersion regVersion = null; + if (Registry.isRegVersion(1.00, 1.99)) { + regVersion = r.new RegVersion_1_00(); + } else { + regVersion = r.new RegVersion_3_0(); + } + return regVersion; + } + + public static String[] getValue(RegVersion version, String root, String path, String key) throws IOException { + String toReturn[] = null; + + Process p = Runtime.getRuntime().exec(version.getQueryCmd(root, path, key)); + StringWriter stringWriter = new StringWriter(); + Lib.handleProcess(p, stringWriter); + + Pattern pattern = Pattern.compile(version.getQueryPattern(key), Pattern.DOTALL); + Matcher matcher = pattern.matcher(stringWriter.toString()); + if (matcher.matches()) { + toReturn = new String[matcher.groupCount()]; + + for (int i = 1; i <= matcher.groupCount(); i++) { + toReturn[i - 1] = matcher.group(i).trim(); + } + } + + if (toReturn != null) { + for (String temp : toReturn) { + System.out.println("VAL: " + temp); + } + } + return toReturn; + } + + public static boolean prependRegistryValue(File updatedReg, String root, String path, String key, String value) throws IOException { + + RegVersion version = Registry.getVersion(); + + String[] regArray = Registry.getValue(version, root, path, key); + + if (regArray != null) { + if (regArray[1].contains(value)) { + System.out.println("Value is already there."); + return true; + } + } + + String command = version.getUpdateCommand(root, path, key, value, regArray); + + /* + * If we are using a 1.0 version then use a provided reg.exe executable to use commands. If + * not operation will fail. + */ + if (version.isVersion().equals("1.00")) { + if (updatedReg.exists() && updatedReg.isFile()) { + command = updatedReg.getAbsolutePath() + command.replaceAll("reg", ""); + ; + } + } + + Process p = Runtime.getRuntime().exec(command); + StringWriter stringWriter = new StringWriter(); + + Lib.handleProcess(p, stringWriter); + + System.out.println("The string: " + stringWriter); + + if (stringWriter.toString().contains("err:")) { + return false; + } + return true; + } + + public static boolean prependRegistryValue(String root, String path, String key, String value) throws IOException { + + RegVersion version = Registry.getVersion(); + + String[] regArray = Registry.getValue(version, root, path, key); + + Process p = Runtime.getRuntime().exec(version.getUpdateCommand(root, path, key, value, regArray)); + StringWriter stringWriter = new StringWriter(); + + Lib.handleProcess(p, stringWriter); + + System.out.println("The string: " + stringWriter); + + if (stringWriter.toString().contains("err:")) { + return false; + } + return true; + } + + public static void main(String[] args) { + try { + Registry.prependRegistryValue(Registry.HKEY_CURRENT_USER, "environment", "path", "HI THERE"); + } catch (IOException ex) { + ex.printStackTrace(); + } + } + +} diff --git a/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/xml/Jaxp.java b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/xml/Jaxp.java new file mode 100644 index 00000000000..ca40420c42d --- /dev/null +++ b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/xml/Jaxp.java @@ -0,0 +1,564 @@ +/******************************************************************************* + * 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.jdk.core.util.xml; + +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileWriter; +import java.io.IOException; +import java.io.InputStream; +import java.io.StringWriter; +import java.io.Writer; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.LinkedList; +import java.util.List; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.transform.Result; +import javax.xml.transform.Source; +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerConfigurationException; +import javax.xml.transform.TransformerException; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.dom.DOMSource; +import javax.xml.transform.stream.StreamResult; +import org.eclipse.osee.framework.jdk.core.util.io.CharBackedInputStream; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; +import org.w3c.dom.ProcessingInstruction; +import org.w3c.dom.Text; +import org.xml.sax.SAXException; +import com.sun.org.apache.xml.internal.serialize.OutputFormat; +import com.sun.org.apache.xml.internal.serialize.XMLSerializer; + +public class Jaxp { + private static final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + + /** + * Obtains a list of all direct descendants of element + * + * @param element the element to find the children of + * @return A list of elements that are direct children of element. If no children exist, an empty list is returned. + */ + public static List<Element> getChildDirects(Element element) { + NodeList nl = element.getChildNodes(); + List<Element> elementList = new ArrayList<Element>(nl.getLength()); // this may be oversized + for (int i = 0; i < nl.getLength(); i++) { + Node n = nl.item(i); + if (n.getNodeType() == Node.ELEMENT_NODE) elementList.add((Element) n); + } + return elementList; + } + + /** + * Obtains a list of all direct descendants of element with the matching tag. + * + * @param element the element to find the children of + * @param childTagName the tag name for the children + * @return A list of elements that are direct children of element whose tag names match childTagName. If no such + * children exist, an empty list is returned. + */ + public static List<Element> getChildDirects(Element element, String childTagName) { + List<Element> elementList = new ArrayList<Element>(); + NodeList nl = element.getChildNodes(); + for (int i = 0; i < nl.getLength(); i++) { + Node n = nl.item(i); + if (n.getNodeType() == Node.ELEMENT_NODE && ((Element) n).getTagName().equals(childTagName)) elementList.add((Element) n); + } + return elementList; + } + + /** + * Obtains the first child that is a direct descendant of element with the matching tag + * + * @param element the element to find the child of + * @param childTagName the tag name for the child + * @return the first child with the given tag one level deep from element, null if no such child exists. + */ + public static Element getChildDirect(Element element, String childTagName) { + NodeList nl = element.getChildNodes(); + for (int i = 0; i < nl.getLength(); i++) { + Node n = nl.item(i); + if (n.getNodeType() == Node.ELEMENT_NODE && ((Element) n).getTagName().equals(childTagName)) return ((Element) n); + } + return null; + } + + /** + * Obtains the first child that is a descendant of element with the matching tag + * + * @param element the element to find the child of + * @param childTagName the tag name for the child + * @return the first child with the given tag, or null if no such children exist + */ + public static Element getChild(Element element, String childTagName) { + NodeList elementList = element.getElementsByTagName(childTagName); + return (Element) elementList.item(0); + } + + public static Element createElement(Document d, String tag, String characterData) { + Element e = d.createElement(tag); + Text t = d.createTextNode(characterData); + e.appendChild(t); + // e.setTextContent(characterData); + // the above two lines do the same thing as this, but I trust them more so we'll go that + // route. + return e; + } + + /** + * Obtains the character data for the Element. Note this differs from the Node.getTextContext(); call, which returns + * the concatenation of the character data for all children of this Element. + * + * @param e The element go get the character data for + * @param trimWhitespace iff true, each segment will be trimmed. + * @return All of the character data for the Element e. This means if there are elements separating the character + * data, it will all be concatenated together. If trimWhitespace, each segment will be trimmed of whitespace, + * with a single space between segments; otherwise the segments will be concatenated without any space + * separation. If no character data is present, returns an empty string. + */ + public static String getElementCharacterData(Element e, boolean trimWhitespace) { + NodeList childNodes = e.getChildNodes(); + String resultString = ""; + boolean first = true; + + for (int i = 0; i < childNodes.getLength(); i++) { + Node n = childNodes.item(i); + if (n.getNodeType() == Node.TEXT_NODE) { + if (!first && trimWhitespace) resultString += " "; + resultString += trimWhitespace ? n.getNodeValue().trim() : n.getNodeValue(); + first = false; + } + } + return resultString; + } + + /** + * Obtains the character data for the Element. Note this differs from the Node.getTextContext(); call, which returns + * the concatenation of the character data for all children of this Element. + * + * @param e The element go get the character data for + * @return All of the character data for the Element e. This means if there are elements separating the character + * data, it will all be concatenated together. Each segment will be trimmed of whitespace, with a single + * space between segments. If no character data is present, returns an empty string. + */ + public static String getElementCharacterData(Element e) { + return getElementCharacterData(e, true); + } + + /** + * Obtains the character data for each element in the collection, return as a List. Each entry in the list + * corresponding to the character data for one of the elements in the collection. + * + * @param elements + * @return + */ + public static List<String> getElementsCharacterData(Collection<Element> elements) { + List<String> result = new ArrayList<String>(elements.size()); + for (Element e : elements) { + result.add(Jaxp.getElementCharacterData(e)); + } + return result; + } + + /** + * @param nodes The NodeList whose text we will return + * @return An ArrayList<String> of the text for all nodes + */ + public static ArrayList<String> getChildrenTexts(NodeList nodes) { + ArrayList<String> retVal = new ArrayList<String>(nodes.getLength()); + + for (int i = 0; i < nodes.getLength(); i++) { + Element element = (Element) nodes.item(i); + retVal.add(getElementCharacterData(element)); + } + return retVal; + } + + /** + * Obtains a list of Strings of the character data for all elements in the document whose tag name matches. + * + * @param document The document to be searched + * @param tagName The tagName for the children whose text we will obtain + * @return An ArrayList<String> of the text for all child nodes matching tagName + */ + public static ArrayList<String> getChildrenTexts(Document document, String tagName) { + return getChildrenTexts(document.getElementsByTagName(tagName)); + } + + /** + * Obtains a list of Strings of the character data for all descendants of element whose tag name matches. + * + * @param document The document to be searched + * @param tagName The tagName for the children whose text we will obtain + * @return An ArrayList<String> of the text for all child nodes matching tagName + */ + public static ArrayList<String> getChildrenTexts(Element element, String tagName) { + return getChildrenTexts(element.getElementsByTagName(tagName)); + } + + public static String getChildText(Element element, String childTagName, boolean trim) { + Element child = getChild(element, childTagName); + if (child != null) { + return getElementCharacterData(child, trim); + } + return null; + } + + public static String getChildText(Element element, String childTagName) { + return getChildText(element, childTagName, false); + } + + public static String getChildTextTrim(Element element, String childTagName) { + return getChildText(element, childTagName, true); + } + + private static void findElementsInternal(List<Element> source, LinkedList<String> path, List<Element> list) { + String tag = path.poll(); + LinkedList<String> childPath = new LinkedList<String>(path); + + for (Element e : source) { + List<Element> children = getChildDirects(e, tag); + if (!children.isEmpty()) { + if (path.size() == 0) // we're at the end of the path + list.addAll(children); + else { + findElementsInternal(children, childPath, list); + } + } + } + } + + /** + * Searches for all sub-elements found at the path provided. + * + * @param element The element underneath which we will search + * @param elementPath The path to follow. For example ["script","configuration","element_i_want"] + * @param firstIsRoot If true, the first item in elementPath must match element. That is, in the above example, e's + * tag name must be "script". This is useful when calling from the document level, that is where element is + * Document.getDocumentElement(), the first item in the path would be the first root element of the xml + * tree. + * @return All elements that match the specified path. + */ + public static List<Element> findElements(Element element, List<String> elementPath, boolean firstIsRoot) { + List<Element> result = new LinkedList<Element>(); + List<Element> source = new ArrayList<Element>(1); + source.add(element); + + LinkedList<String> path; + if (elementPath instanceof LinkedList) + path = (LinkedList<String>) (elementPath); + else + path = new LinkedList<String>(elementPath); + + // Strip off the first item of elementPath and make sure it matches 'element' + if (firstIsRoot) { + String firstTagName = path.poll(); + if (element.getTagName().equals(firstTagName)) return result; + } + + findElementsInternal(source, path, result); + return result; + } + + private static List<Element> findElementsSinglePath(Element e, String elementPath, boolean firstIsRoot) { + return findElements(e, Arrays.asList(elementPath.split("/")), firstIsRoot); + } + + private static List<Element> findElements(Element e, String elementPath, boolean firstIsRoot) { + List<Element> result = new LinkedList<Element>(); + String[] paths = elementPath.split("\\|"); + + for (String path : paths) { + result.addAll(findElementsSinglePath(e, path, firstIsRoot)); + } + return result; + } + + public static List<Element> findElements(Element element, String elementPath) { + return findElements(element, elementPath, false); + } + + public static List<Element> findElements(Document d, String elementPath) { + return findElements(d.getDocumentElement(), elementPath, true); + } + + /** + * Searches for a sub-element found at the path provided. Each list element indicates the tag name for the next + * sub-element. + * + * @param e The element underneath which we will search + * @param elementPath The path to follow. For example ["script","configuration","element_i_want"] + * @return The first element that matches the provided path, beneath the provided element e, or null if no such + * element exists. + */ + public static Element findElement(Element element, List<String> elementPath) { + + Element e = element; + for (String tag : elementPath) { + NodeList a = e.getChildNodes(); + Element nextElement = null; + for (int i = 0; i < a.getLength() && nextElement == null; i++) { + Node n = a.item(i); + if (n.getNodeType() == Node.ELEMENT_NODE && ((Element) n).getTagName().equals(tag)) nextElement = (Element) n; + } + if (nextElement == null) + return null; + else + e = nextElement; + } + return e; + } + + /** + * Searches the Document for the Element found at the '/' delimited path provided. The path should begin with the + * root node of the document. + * + * @param d The document to search + * @param elementPath The path to follow. For example "script/configuration/element_i_want" + * @return The first element that matches the provided path, or null if no such element exists. + */ + public static Element findElement(Document d, String elementPath) { + List<String> pathList = Arrays.asList(elementPath.split("/")); + String rootTagName = pathList.get(0); + // Remove the first item from the list, Arrays.asList List type doesn't support .remove() + if (pathList.size() > 1) + pathList = pathList.subList(1, pathList.size()); + else + pathList.clear(); + + Element root = d.getDocumentElement(); + if (!root.getTagName().equals(rootTagName)) return null; + return findElement(d.getDocumentElement(), pathList); + } + + /** + * Searches for a sub-element found at the '/' delimited path provided. The path should begin with the first node + * underneath the provided element. + * + * @param e The element underneath which we will search + * @param elementPath The path to follow. For example "script/configuration/element_i_want" + * @return The first element that matches the provided path, beneath the provided element e, or null if no such + * element exists. + */ + public static Element findElement(Element e, String elementPath) { + return findElement(e, Arrays.asList(elementPath.split("/"))); + } + + public static Document readXmlDocument(InputStream is) throws ParserConfigurationException, SAXException, IOException { + DocumentBuilder builder = factory.newDocumentBuilder(); + return builder.parse(is); + } + + public static Document readXmlDocument(String xmlString) throws ParserConfigurationException, SAXException, IOException { + DocumentBuilder builder = factory.newDocumentBuilder(); + CharBackedInputStream charBak = new CharBackedInputStream(); + charBak.addBackingSource(xmlString); + Document document = builder.parse(charBak); + return document; + } + + public static Document readXmlDocument(File xmlFile) throws ParserConfigurationException, SAXException, IOException { + DocumentBuilder builder = factory.newDocumentBuilder(); + Document document = builder.parse(xmlFile); + return document; + } + + public static Document readXmlDocumentFromResource(Class<?> base, String name) throws ParserConfigurationException, SAXException, IOException { + DocumentBuilder builder = factory.newDocumentBuilder(); + Document document = builder.parse(base.getResourceAsStream(name)); + return document; + } + + /** + * Adds the XSL style sheet processing instruction to the document. + * + * @param d + * @param xslPath + */ + public static void setXslProperty(Document d, String xslPath) { + ProcessingInstruction xsl = d.createProcessingInstruction("xml-stylesheet", // + "type=\"text/xsl\" href=\"" + xslPath + "\""); + d.appendChild(xsl); + } + + /** + * Writes the XML document 'document' to the 'file'. + * + * @param document The XML document to output + * @param file Where to put the output + * @throws TransformerException + * @throws IOException + */ + public static void writeXmlDocument(Document document, File file) throws TransformerException, IOException { + writeXmlDocument(document, file, getCompactFormat(document)); + } + + /** + * Writes the XML document 'document' to the 'file'. + * + * @param document The XML document to output + * @param file Where to put the output + * @param prettyOutput If true, turns on indention so the output is more easily readable, if False turns indention + * off to save space. + * @throws TransformerException + * @throws IOException + */ + public static void writeXmlDocument(Document document, File file, OutputFormat format) throws TransformerException, IOException { + BufferedWriter out = new BufferedWriter(new FileWriter(file)); + outputXmlDocument(document, out, format); + out.close(); + } + + /** + * Gets the XML document 'document' as a string + * + * @param document The XML document to output + * @param file Where to put the output + * @param prettyOutput If true, turns on indention so the output is more easily readable, if False turns indention + * off and is assumed to provide the XML as compactly as possible. + * @throws TransformerException + */ + public static String xmlToString(Document document, OutputFormat format) throws IOException { + StringWriter stringWriter = new StringWriter(); + outputXmlDocument(document, stringWriter, format); + return stringWriter.toString(); + } + + /** + * Sends the XML to the output + * + * @param document The source XML + * @param output Where the XML is 'printed' to + * @param format The format style to use + * @throws IOException + */ + private static void outputXmlDocument(Document document, Writer output, OutputFormat format) throws IOException { + XMLSerializer serializer = new XMLSerializer(output, format); + serializer.serialize(document); + } + + /** + * Generates an OutputFormat that is pleasing to look at (indention, newlines, etc) + * + * @param document the document to be formatted + * @return the OutputFormat object to use for XML Formatting + * @see XMLSerializer + */ + public static OutputFormat getPrettyFormat(Document document) { + OutputFormat format = new OutputFormat(document); + format.setIndenting(true); + format.setIndent(2); + return format; + } + + /** + * Generates an OutputFormat that is compact (no extra whitepsace) + * + * @param document the document to be formatted + * @return the OutputFormat object to use for XML Formatting + * @see XMLSerializer + */ + public static OutputFormat getCompactFormat(Document document) { + OutputFormat format = new OutputFormat(document); + format.setIndenting(false); + format.setLineSeparator(""); + return format; + } + + public static Document newDocument() throws ParserConfigurationException { + factory.setNamespaceAware(true); + DocumentBuilder builder = factory.newDocumentBuilder(); + return builder.newDocument(); + } + + public static String getDocumentXml(Document doc) { + try { + Source source = new DOMSource(doc); + StringWriter stringWriter = new StringWriter(); + Result result = new StreamResult(stringWriter); + TransformerFactory factory = TransformerFactory.newInstance(); + Transformer transformer = factory.newTransformer(); + transformer.transform(source, result); + return stringWriter.getBuffer().toString(); + } catch (TransformerConfigurationException e) { + e.printStackTrace(); + } catch (TransformerException e) { + e.printStackTrace(); + } + return null; + } + + public static void main(String args[]) { + try { + Document doc = readXmlDocument("<A name='george' type='level1'>" + " <B type='level2'>I'm at level 2</B>" // + + " <B type='level2'>I'm also at level 2</B>" // + + " <C type='level2'>" // + + " <D>likes to be C's child</D>" // + + "C has some more text here" // + + " <D>2nd round</D>"// + + "END of C" // + + " </C>" // + + "</A>"); + + Element e = (Element) getChild(doc.getDocumentElement(), "C"); + System.out.println("e.getTagName :" + e.getTagName()); + System.out.println("e.getLocalName :" + e.getLocalName()); + System.out.println("e.getNodeName :" + e.getNodeName()); + System.out.println("e.getNodeType :" + e.getNodeType()); + System.out.println("e.getNodeValue :" + e.getNodeValue()); + System.out.println("e.getPrefix :" + e.getPrefix()); + System.out.println("e.getTextContent :" + e.getTextContent()); + System.out.println(""); + System.out.println("e.getFirstChild().getNodeValue :" + e.getFirstChild().getNodeValue()); + System.out.println("e.getFirstChild().getTextContent :" + e.getFirstChild().getTextContent()); + System.out.println(""); + System.out.println(getElementCharacterData(e)); + + System.out.println(""); + System.out.println("Looking for the Top level item:"); + NodeList nl = doc.getElementsByTagName("A"); + for (int i = 0; i < nl.getLength(); i++) { + System.out.println(" Found: " + nl.item(i).getNodeName()); + } + System.out.println("Looking for the Top level item:"); + nl = doc.getDocumentElement().getElementsByTagName("A"); + for (int i = 0; i < nl.getLength(); i++) { + System.out.println("Found: " + nl.item(i).getNodeName()); + } + + System.out.println(""); + System.out.println("Searching For D:"); + Element em = findElement(doc, "A/C/D"); + System.out.println(em.getTagName() + ":" + getElementCharacterData(em)); + + List<Element> list = findElements(doc.getDocumentElement(), "C/D"); + for (Element te : list) + System.out.println(te.getTagName() + ":" + getElementCharacterData(te)); + + Element joe = Jaxp.createElement(doc, "f", "This is F's Data"); + em.appendChild(joe); + + System.out.println(Jaxp.getElementCharacterData(joe)); + + System.out.println("******"); + System.out.println(xmlToString(doc, getPrettyFormat(doc))); + + } catch (Exception ex) { + ex.printStackTrace(); + } + } +} diff --git a/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/xml/Xml.java b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/xml/Xml.java new file mode 100644 index 00000000000..ccaa5b3758e --- /dev/null +++ b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/xml/Xml.java @@ -0,0 +1,106 @@ +/******************************************************************************* + * 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.jdk.core.util.xml; + +import java.io.IOException; +import java.util.regex.Pattern; + +/** + * @author David Diepenbrock + */ +public class Xml { + private static final String[] XML_CHARS = new String[] {"[&]", "[<]", "[>]", "[\"]"}; + private static final String[] XML_ESCAPES = new String[] {"&", "<", ">", """}; + private static final Pattern squareBracket = Pattern.compile("\\]"); + + /** + * TODO Optimize algorithm + * + * @param text + * @return Returns a string with entity reference characters unescaped. + */ + public static String unescape(String text) { + StringBuffer stringBuffer = new StringBuffer(); + int startIndex, endIndex; + char chr; + + for (int index = 0; index < text.length(); index++) { + chr = text.charAt(index); + + if (chr == '&') { + startIndex = index; + endIndex = text.indexOf(';', startIndex) + 1; + + String entityReference = text.substring(startIndex, endIndex); + + if (entityReference.equals("&")) + stringBuffer.append('&'); + else if (entityReference.equals("<")) + stringBuffer.append('<'); + else if (entityReference.equals(">")) + stringBuffer.append('>'); + else if (entityReference.equals(" ")) + stringBuffer.append(' '); + else if (entityReference.equals(""")) + stringBuffer.append('"'); + else + throw new IllegalArgumentException("unknown entity reference: " + text.substring(startIndex, endIndex)); + + index = endIndex - 1; + } else { + stringBuffer.append(chr); + } + } + return stringBuffer.toString(); + } + + /** + * TODO Optimize algorithm + * + * @param text + * @return Returns a string with entity reference characters escaped. + */ + public static CharSequence escape(CharSequence text) { + String textString = text.toString(); + for (int x = 0; x < XML_CHARS.length; x++) { + textString = textString.replaceAll(XML_CHARS[x], XML_ESCAPES[x]); + } + + return textString; + } + + public static void writeAsCdata(Appendable appendable, String string) throws IOException { + if (string.indexOf('<') == -1 && string.indexOf('&') == -1 && string.indexOf("]]>") == -1) { + appendable.append(string); + } else { + if (string.indexOf(']') == -1) { + writeCdata(appendable, string); + } else { + // work around bug in excel xml parsing that thinks a single ] closes CDATA + String[] tokens = squareBracket.split(string); + for (int i = 0; i < tokens.length; i++) { + writeCdata(appendable, tokens[i]); + if (i != tokens.length - 1) { // the last token would not have been followed by ] + appendable.append(']'); + } + } + } + } + + } + + private static void writeCdata(Appendable appendable, String content) throws IOException { + appendable.append("<![CDATA["); + appendable.append(content); + appendable.append("]]>"); + } + +} diff --git a/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/xml/XmlOutputTransform.java b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/xml/XmlOutputTransform.java new file mode 100644 index 00000000000..19f4c277526 --- /dev/null +++ b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/xml/XmlOutputTransform.java @@ -0,0 +1,92 @@ +/******************************************************************************* + * 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.jdk.core.util.xml; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileWriter; +import java.io.InputStream; +import java.io.StringWriter; +import java.io.Writer; +import javax.xml.transform.Result; +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.stream.StreamResult; +import javax.xml.transform.stream.StreamSource; + +/** + * @author Roberto E. Escobar + */ +public final class XmlOutputTransform { + + // Prevent Instantiation + private XmlOutputTransform() { + } + + protected static void xmlToHtml(InputStream inputXML, InputStream inputXslt, Result result) throws Exception { + Transformer transformer = TransformerFactory.newInstance().newTransformer(new StreamSource(inputXslt)); + xmlToHtml(inputXML, transformer, result); + } + + private static void xmlToHtml(InputStream inputXML, Transformer transformer, Result result) throws Exception { + try { + transformer.transform(new StreamSource(inputXML), result); + } catch (Exception ex) { + throw new Exception("Error during Transform. " + ex.getLocalizedMessage(), ex); + } + } + + private static void xmlToHtml(InputStream inputXML, InputStream inputXslt, Writer result) throws Exception { + boolean isNetworked = false; + + if (true != isNetworked) { + // Perform Transform Directly + xmlToHtml(inputXML, inputXslt, new StreamResult(result)); + } else { + // Perform Transform as a Separate process by launching an XmlTransformServer. + XmlTransformAsProcess.getHtmlFromXml(inputXML, inputXslt, result); + } + } + + public static String xmlToHtmlString(String sourceFile, File transformToApply) { + return xmlToHtmlString(new File(sourceFile), transformToApply); + } + + public static String xmlToHtmlString(File sourceFile, String transformToApply) { + return xmlToHtmlString(sourceFile, new File(transformToApply)); + } + + public static String xmlToHtmlString(String sourceFile, String transformToApply) { + return xmlToHtmlString(new File(sourceFile), new File(transformToApply)); + } + + public static File xmlToHtmlFile(File sourceFile, File transformToApply) throws Exception { + File file = new File(sourceFile.getAbsolutePath().replace(".tmo", ".html")); + xmlToHtml(new FileInputStream(sourceFile), new FileInputStream(transformToApply), new FileWriter(file)); + return file; + } + + public static String xmlToHtmlString(File sourceFile, File transformToApply) { + StringWriter sWriter = new StringWriter(); + try { + xmlToHtml(new FileInputStream(sourceFile), new FileInputStream(transformToApply), sWriter); + } catch (Exception e) { + e.printStackTrace(); + } + return sWriter.toString(); + } + + public static String xmlToHtmlString(InputStream sourceXML, Transformer transformer) throws Exception { + StringWriter sWriter = new StringWriter(); + xmlToHtml(sourceXML, transformer, new StreamResult(sWriter)); + return sWriter.toString(); + } +}
\ No newline at end of file diff --git a/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/xml/XmlTransformAsProcess.java b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/xml/XmlTransformAsProcess.java new file mode 100644 index 00000000000..e6ddd6054a8 --- /dev/null +++ b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/xml/XmlTransformAsProcess.java @@ -0,0 +1,182 @@ +/******************************************************************************* + * 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.jdk.core.util.xml; + +import java.io.BufferedInputStream; +import java.io.BufferedOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.InputStream; +import java.io.OutputStream; +import java.io.PrintWriter; +import java.io.Writer; +import java.net.InetAddress; +import java.net.MalformedURLException; +import java.net.Socket; +import java.net.URISyntaxException; +import java.net.URL; +import java.security.CodeSource; +import java.security.ProtectionDomain; +import java.util.ArrayList; +import java.util.List; +import org.eclipse.osee.framework.jdk.core.util.network.PortUtil; + +/** + * @author Roberto E. Escobar + */ +public class XmlTransformAsProcess { + + private Socket clientSocket; + private InputStream inputFromNetwork; + private OutputStream outputFromNetwork; + private Process process; + + private XmlTransformAsProcess() { + process = null; + clientSocket = null; + inputFromNetwork = null; + outputFromNetwork = null; + } + + @SuppressWarnings("unchecked") + private URL getClassLocation(final Class classToFind) { + URL result = null; + if (classToFind == null) { + throw new IllegalArgumentException("Class is null"); + } + final String classAsResource = classToFind.getName().replace('.', '/').concat(".class"); + final ProtectionDomain pd = classToFind.getProtectionDomain(); + if (pd != null) { + final CodeSource cs = pd.getCodeSource(); + if (cs != null) { + result = cs.getLocation(); + } + if (result != null) { + // Convert a code source location into a full class file location + if (result.getProtocol().equals("file")) { + try { + if (result.toExternalForm().endsWith(".jar") || result.toExternalForm().endsWith(".zip")) + result = new URL("jar:".concat(result.toExternalForm()).concat("!/").concat(classAsResource)); + else if (new File(result.getFile()).isDirectory()) result = new URL(result, classAsResource); + } catch (MalformedURLException ignore) { + } + } + } + } + if (result == null) { + // Try to find class definition as a resource + final ClassLoader classLoader = classToFind.getClassLoader(); + result = classLoader != null ? classLoader.getResource(classAsResource) : ClassLoader.getSystemResource(classAsResource); + } + return result; + } + + private void connectToServer(InetAddress address, int port) throws Exception { + try { + for (int i = 0; i < 10; i++) { + try { + clientSocket = new Socket(address, port); + break; + } catch (Throwable th) { + Thread.sleep(1000); + } + } + System.out.println("Connected"); + inputFromNetwork = new BufferedInputStream(clientSocket.getInputStream()); + outputFromNetwork = new BufferedOutputStream(clientSocket.getOutputStream()); + } catch (Exception ex) { + throw new Exception("Unable to Connect to Transform Server. ", ex); + } + } + + private void launchServer(int port) throws Exception { + List<String> commands = new ArrayList<String>(); + try { + URL url = getClassLocation(XmlTransformServer.class); + String path = new File(url.toURI()).getAbsolutePath(); + int indexOf = path.indexOf("bin"); + path = path.substring(0, indexOf + 4); + File classFileLocation = new File(path); + + String className = XmlTransformServer.class.getName(); + + commands.add("java"); + commands.add("-Xmx1024M"); + commands.add(className); + commands.add(Integer.toString(port)); + + ProcessBuilder builder = new ProcessBuilder(); + builder.directory(classFileLocation); + builder.command(commands); + process = builder.start(); + Thread.sleep(800); + } catch (URISyntaxException ex) { + throw new Exception("Unable to find XmlTransformServer class in File System. ", ex); + } catch (Exception ex) { + throw new Exception("Unable to launch TransformServer. ", ex); + } + } + + public void processXml(InputStream xmlSource, InputStream xsltSource, Writer result) { + try { + XmlTransformServer.sendStream(clientSocket, xmlSource, outputFromNetwork); + Thread.sleep(2000); + System.gc(); + System.out.println("Sent Xml"); + XmlTransformServer.sendStream(clientSocket, xsltSource, outputFromNetwork); + System.gc(); + Thread.sleep(2000); + System.out.println("Sent Xslt"); + XmlTransformServer.receiveStream(clientSocket, inputFromNetwork, result); + System.gc(); + } catch (Exception ex) { + ex.printStackTrace(); + } + } + + private void clearResources() throws Exception { + if (inputFromNetwork != null) { + inputFromNetwork.close(); + } + if (outputFromNetwork != null) { + outputFromNetwork.close(); + } + if (clientSocket != null) { + clientSocket.close(); + } + if (process != null) { + process.destroy(); + } + } + + public static void getHtmlFromXml(InputStream xmlSource, InputStream xsltSource, Writer results) throws Exception { + XmlTransformAsProcess xmlTransformProcess = new XmlTransformAsProcess(); + try { + InetAddress address = InetAddress.getLocalHost(); + int port = PortUtil.getInstance().getValidPort(); + System.out.println("Transform Server at port: " + port); + System.gc(); + xmlTransformProcess.launchServer(port); + xmlTransformProcess.connectToServer(address, port); + xmlTransformProcess.processXml(xmlSource, xsltSource, results); + + } finally { + xmlTransformProcess.clearResources(); + System.gc(); + } + } + + public static void main(String[] args) throws Exception { + InputStream xmlInput = new FileInputStream(args[0]); + InputStream xsltInput = new FileInputStream(args[1]); + getHtmlFromXml(xmlInput, xsltInput, new PrintWriter(System.out)); + } +} diff --git a/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/xml/XmlTransformServer.java b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/xml/XmlTransformServer.java new file mode 100644 index 00000000000..673c78baece --- /dev/null +++ b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/xml/XmlTransformServer.java @@ -0,0 +1,203 @@ +/******************************************************************************* + * 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.jdk.core.util.xml; + +import java.io.BufferedInputStream; +import java.io.BufferedOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.InputStream; +import java.io.OutputStream; +import java.io.PrintStream; +import java.io.PrintWriter; +import java.io.Writer; +import java.net.ServerSocket; +import java.net.Socket; +import javax.xml.transform.ErrorListener; +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.stream.StreamResult; +import javax.xml.transform.stream.StreamSource; + +/** + * @author Roberto E. Escobar + */ +public class XmlTransformServer { + + private static int MAX_PACKET_SIZE = 65536; + private static int FINISH_PROCESSING_FLAG = -1; + private static int TIMEOUT = 60000 * 3; + + private InputStream inputFromNetwork; + private OutputStream outputToNetwork; + + private Socket clientSocket; + private ServerSocket server; + private int portNumber; + private String userHome; + + public XmlTransformServer() { + this.server = null; + this.portNumber = 0; + this.userHome = System.getProperty("user.home"); + } + + private void initializeServer(int portNumber) throws Exception { + this.portNumber = portNumber; + try { + server = new ServerSocket(portNumber); + clientSocket = server.accept(); + inputFromNetwork = new BufferedInputStream(clientSocket.getInputStream()); + outputToNetwork = new BufferedOutputStream(clientSocket.getOutputStream()); + } catch (Exception ex) { + throw new Exception("Unable to launch Server and get Connection. ", ex); + } + } + + public void process() throws Exception { + performRead("xml", ".xml"); + performRead("xslt", ".xsl"); + performWrite(); + } + + private void performRead(String prefix, String extension) throws Exception { + File file = new File(userHome + File.separator + prefix + portNumber + extension); + file.createNewFile(); + FileOutputStream fos = new FileOutputStream(file); + try { + receiveStream(clientSocket, inputFromNetwork, new PrintStream(fos)); + } catch (Exception ex) { + ex.printStackTrace(); + } finally { + fos.close(); + } + } + + private void performWrite() throws Exception { + File file = new File(userHome + File.separator + "html" + portNumber + ".html"); + file.createNewFile(); + FileOutputStream fos = new FileOutputStream(file); + + File fisXml = new File(userHome + File.separator + "xml" + portNumber + ".xml"); + File fisXslt = new File(userHome + File.separator + "xslt" + portNumber + ".xsl"); + ErrorListener listener = null; + try { + System.gc(); + Transformer transformer = TransformerFactory.newInstance().newTransformer(new StreamSource(fisXslt)); + listener = transformer.getErrorListener(); + transformer.transform(new StreamSource(fisXml), new StreamResult(fos)); + } catch (Exception ex) { + PrintWriter pw = new PrintWriter(fos); + pw.write("Error during Transform. " + listener.toString()); + ex.printStackTrace(pw); + } finally { + fos.close(); + fisXml.delete(); + fisXslt.delete(); + } + System.gc(); + + InputStream fis = new FileInputStream(file); + try { + sendStream(clientSocket, fis, outputToNetwork); + Thread.sleep(1000); + } catch (Exception ex) { + ex.printStackTrace(); + } finally { + fis.close(); + file.delete(); + } + } + + private void clearResources() throws Exception { + if (outputToNetwork != null) { + outputToNetwork.close(); + } + if (inputFromNetwork != null) { + inputFromNetwork.close(); + } + if (clientSocket != null) { + clientSocket.close(); + } + if (server != null) { + server.close(); + } + } + + static public void sendStream(Socket socket, InputStream in, OutputStream out) throws Exception { + socket.setSoTimeout(TIMEOUT); + try { + int numberOfBytes = 0; + byte[] buffer = new byte[MAX_PACKET_SIZE]; + while ((numberOfBytes = in.read(buffer, 0, buffer.length)) != -1) { + out.write(buffer, 0, numberOfBytes); + } + out.write(FINISH_PROCESSING_FLAG); + out.flush(); + } catch (Exception ex) { + throw new Exception("Error during send.", ex); + } + } + + static public void receiveStream(Socket socket, InputStream in, OutputStream out) throws Exception { + socket.setSoTimeout(TIMEOUT); + try { + int numberOfBytes = 0; + byte[] buffer = new byte[MAX_PACKET_SIZE]; + while ((numberOfBytes = in.read(buffer, 0, buffer.length)) != -1) { + if (buffer[numberOfBytes - 1] == -1) { + out.write(buffer, 0, numberOfBytes - 1); + break; + } + out.write(buffer, 0, numberOfBytes); + } + out.flush(); + } catch (Exception ex) { + throw new Exception("Error during receive.", ex); + } + } + + static public void receiveStream(Socket socket, InputStream in, Writer out) throws Exception { + socket.setSoTimeout(TIMEOUT); + try { + int numberOfBytes = 0; + byte[] buffer = new byte[MAX_PACKET_SIZE]; + while ((numberOfBytes = in.read(buffer, 0, buffer.length)) != -1) { + if (buffer[numberOfBytes - 1] == -1) { + out.write(new String(buffer, 0, numberOfBytes - 1)); + break; + } + out.write(new String(buffer, 0, numberOfBytes)); + } + out.flush(); + } catch (Exception ex) { + throw new Exception("Error during receive.", ex); + } + } + + public static void main(String args[]) { + XmlTransformServer xmlTransformServer = new XmlTransformServer(); + try { + int port = Integer.parseInt(args[0]); + xmlTransformServer.initializeServer(port); + xmlTransformServer.process(); + } catch (Exception ex) { + ex.printStackTrace(); + } finally { + try { + xmlTransformServer.clearResources(); + } catch (Exception ex) { + ex.printStackTrace(); + } + } + } +} diff --git a/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/xml/XmlTranslation.java b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/xml/XmlTranslation.java new file mode 100644 index 00000000000..c6bc2b14f3c --- /dev/null +++ b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/xml/XmlTranslation.java @@ -0,0 +1,61 @@ +/******************************************************************************* + * 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.jdk.core.util.xml; + +import java.io.CharArrayReader; +import java.io.CharArrayWriter; +import java.nio.CharBuffer; +import javax.xml.transform.Result; +import javax.xml.transform.Source; +import javax.xml.transform.Templates; +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerConfigurationException; +import javax.xml.transform.TransformerException; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.URIResolver; +import javax.xml.transform.stream.StreamResult; +import javax.xml.transform.stream.StreamSource; + +/** + * @author Ryan D. Brooks + */ +public class XmlTranslation { + /** + * applies the xslFilename to inFilename and writes the output to outFilename. + */ + public static CharBuffer applyXsl(CharBuffer xmlBuffer, CharBuffer xslBuffer, URIResolver uriResolver) { + return applyXsl(new StreamSource(new CharArrayReader(xmlBuffer.array())), xslBuffer, uriResolver); + } + + /** + * applies the xslFilename to inFilename and writes the output to outFilename. + */ + public static CharBuffer applyXsl(Source source, CharBuffer xslBuffer, URIResolver uriResolver) { + try { + TransformerFactory factory = TransformerFactory.newInstance(); + factory.setURIResolver(uriResolver); + + Templates template = factory.newTemplates(new StreamSource(new CharArrayReader(xslBuffer.array()))); + Transformer xformer = template.newTransformer(); + + CharArrayWriter resultWriter = new CharArrayWriter(10000); + Result result = new StreamResult(resultWriter); + + xformer.transform(source, result); + return CharBuffer.wrap(resultWriter.toCharArray()); + } catch (TransformerConfigurationException ex) { + ex.printStackTrace(); + } catch (TransformerException ex) { + ex.printStackTrace(); + } + return null; + } +} diff --git a/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/xml/excel/Cell.java b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/xml/excel/Cell.java new file mode 100644 index 00000000000..b14f7c953fa --- /dev/null +++ b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/xml/excel/Cell.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.jdk.core.util.xml.excel; + +import org.eclipse.osee.framework.jdk.core.persistence.Xmlizable; +import org.w3c.dom.Document; +import org.w3c.dom.Element; + +/** + * @author Ryan D. Brooks + */ +public class Cell implements Xmlizable { + + public Element toXml(Document doc) { + return null; + } + + public void initializeFromXml(Document doc) { + } +} diff --git a/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/xml/excel/Row.java b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/xml/excel/Row.java new file mode 100644 index 00000000000..4d7110bb656 --- /dev/null +++ b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/xml/excel/Row.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.jdk.core.util.xml.excel; + +import org.eclipse.osee.framework.jdk.core.persistence.Xmlizable; +import org.w3c.dom.Document; +import org.w3c.dom.Element; + +/** + * @author Ryan D. Brooks + */ +public class Row implements Xmlizable { + + public Element toXml(Document doc) { + return null; + } + + public void initializeFromXml(Document doc) { + } +} diff --git a/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/xml/excel/Style.java b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/xml/excel/Style.java new file mode 100644 index 00000000000..3a305bd5346 --- /dev/null +++ b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/xml/excel/Style.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.jdk.core.util.xml.excel; + +import org.eclipse.osee.framework.jdk.core.persistence.Xmlizable; +import org.w3c.dom.Document; +import org.w3c.dom.Element; + +/** + * @author Ryan D. Brooks + */ +public class Style implements Xmlizable { + + public Element toXml(Document doc) { + return null; + } + + public void initializeFromXml(Document doc) { + } +} diff --git a/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/xml/excel/Table.java b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/xml/excel/Table.java new file mode 100644 index 00000000000..818fa709607 --- /dev/null +++ b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/xml/excel/Table.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.jdk.core.util.xml.excel; + +import org.eclipse.osee.framework.jdk.core.persistence.Xmlizable; +import org.w3c.dom.Document; +import org.w3c.dom.Element; + +/** + * @author Ryan D. Brooks + */ +public class Table implements Xmlizable { + + public Element toXml(Document doc) { + return null; + } + + public void initializeFromXml(Document doc) { + } +} diff --git a/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/xml/excel/WorkBook.java b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/xml/excel/WorkBook.java new file mode 100644 index 00000000000..43b3c650610 --- /dev/null +++ b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/xml/excel/WorkBook.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.jdk.core.util.xml.excel; + +import org.eclipse.osee.framework.jdk.core.persistence.Xmlizable; +import org.w3c.dom.Document; +import org.w3c.dom.Element; + +/** + * @author Ryan D. Brooks + */ +public class WorkBook implements Xmlizable { + + public Element toXml(Document doc) { + return null; + } + + public void initializeFromXml(Document doc) { + } +} diff --git a/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/xml/excel/WorkSheet.java b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/xml/excel/WorkSheet.java new file mode 100644 index 00000000000..dca1df40aed --- /dev/null +++ b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/xml/excel/WorkSheet.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.jdk.core.util.xml.excel; + +import org.eclipse.osee.framework.jdk.core.persistence.Xmlizable; +import org.w3c.dom.Document; +import org.w3c.dom.Element; + +/** + * @author Ryan D. Brooks + */ +public class WorkSheet implements Xmlizable { + + public Element toXml(Document doc) { + return null; + } + + public void initializeFromXml(Document doc) { + } +} diff --git a/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/xml/parser/GenericParser.java b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/xml/parser/GenericParser.java new file mode 100644 index 00000000000..b52093dcd18 --- /dev/null +++ b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/xml/parser/GenericParser.java @@ -0,0 +1,173 @@ +/******************************************************************************* + * 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.jdk.core.util.xml.parser; + +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.util.HashSet; +import java.util.Set; +import org.eclipse.osee.framework.jdk.core.collection.tree.Tree; +import org.eclipse.osee.framework.jdk.core.collection.tree.TreeNode; +import org.eclipse.osee.framework.jdk.core.util.io.xml.AbstractSaxHandler; +import org.xml.sax.Attributes; +import org.xml.sax.ErrorHandler; +import org.xml.sax.InputSource; +import org.xml.sax.SAXException; +import org.xml.sax.SAXParseException; +import org.xml.sax.XMLReader; +import org.xml.sax.helpers.XMLReaderFactory; + +/** + * @author Roberto E. Escobar + */ +public class GenericParser extends AbstractSaxHandler { + + private String toFind; + private boolean startCollecting; + private Tree<XmlNode> collectedTree; + private TreeNode<XmlNode> currentNode; + private Set<IXmlNodeListener> listeners; + private Set<IProcessingInstructionsListener> instructionListeners; + + public GenericParser(String startTag) { + this.toFind = startTag; + this.listeners = new HashSet<IXmlNodeListener>(); + this.instructionListeners = new HashSet<IProcessingInstructionsListener>(); + } + + public void reset() { + this.startCollecting = false; + this.currentNode = null; + this.collectedTree = null; + } + + /* + * (non-Javadoc) + * + * @see org.eclipse.osee.framework.jdk.core.util.io.xml.AbstractSaxHandler#startElementFound(java.lang.String, + * java.lang.String, java.lang.String, org.xml.sax.Attributes) + */ + @Override + public void startElementFound(String uri, String localName, String qName, Attributes attributes) throws SAXException { + if (localName.equalsIgnoreCase(toFind)) { + startCollecting = true; + collectedTree = new Tree<XmlNode>(new XmlNode(localName, attributes)); + currentNode = null; + } + + if (startCollecting) { + XmlNode node = new XmlNode(localName, attributes); + if (currentNode == null) { + currentNode = collectedTree.getRoot(); + } else { + currentNode = currentNode.addChild(node); + } + } + } + + /* + * (non-Javadoc) + * + * @see org.eclipse.osee.framework.jdk.core.util.io.xml.AbstractSaxHandler#endElementFound(java.lang.String, + * java.lang.String, java.lang.String) + */ + @Override + public void endElementFound(String uri, String localName, String qName) throws SAXException { + if (localName.equalsIgnoreCase(toFind)) { + startCollecting = false; + notifyTreeCollected(collectedTree); + } + + if (startCollecting) { + if (currentNode != null) { + currentNode.getSelf().setTextContent(getContents()); + if (currentNode.getSelf().getName().equalsIgnoreCase(localName)) { + // Found End of current Node Stop appending Children + TreeNode<XmlNode> parent = currentNode.getParent(); + currentNode = parent; + } + } + } + } + + public void processingInstruction(String target, String data) throws SAXException { + super.processingInstruction(target, data); + notifyProcessingInstructionChanged(target, data); + } + + synchronized public void registerInstructionListener(IProcessingInstructionsListener listener) { + if (!instructionListeners.contains(listener)) { + instructionListeners.add(listener); + } + } + + synchronized public void deregisterInstructionListener(IProcessingInstructionsListener listener) { + if (instructionListeners.contains(listener)) { + instructionListeners.remove(listener); + } + } + + synchronized public void registerXmlNodeListener(IXmlNodeListener listener) { + if (!listeners.contains(listener)) { + listeners.add(listener); + } + } + + synchronized public void deregisterXmlNodeListener(IXmlNodeListener listener) { + if (listeners.contains(listener)) { + listeners.remove(listener); + } + } + + synchronized public void notifyTreeCollected(final Tree<XmlNode> tree) { + TreeNode<XmlNode> root = tree.getRoot(); + for (IXmlNodeListener listener : listeners) { + listener.collectionChanged(root); + } + } + + synchronized public void notifyProcessingInstructionChanged(String target, String data) { + for (IProcessingInstructionsListener listener : instructionListeners) { + listener.processingInstructionChanged(target, data); + } + } + + public void process(File xmlSource) throws SAXException, IOException { + this.reset(); + process(new FileInputStream(xmlSource)); + } + + public void process(InputStream xmlSource) throws SAXException, IOException { + this.reset(); + XMLReader xmlReader; + xmlReader = XMLReaderFactory.createXMLReader(); + xmlReader.setContentHandler(this); + xmlReader.setErrorHandler(new ErrorHandler() { + + public void warning(SAXParseException exception) throws SAXException { + exception.printStackTrace(); + } + + public void fatalError(SAXParseException exception) throws SAXException { + exception.printStackTrace(); + } + + public void error(SAXParseException exception) throws SAXException { + exception.printStackTrace(); + } + + }); + xmlReader.parse(new InputSource(xmlSource)); + System.out.println(); + } +} diff --git a/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/xml/parser/IProcessingInstructionsListener.java b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/xml/parser/IProcessingInstructionsListener.java new file mode 100644 index 00000000000..5ebb0297c16 --- /dev/null +++ b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/xml/parser/IProcessingInstructionsListener.java @@ -0,0 +1,19 @@ +/******************************************************************************* + * 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.jdk.core.util.xml.parser; + +/** + * @author Roberto E. Escobar + */ +public interface IProcessingInstructionsListener { + + public void processingInstructionChanged(String target, String data); +} diff --git a/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/xml/parser/IXmlNodeListener.java b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/xml/parser/IXmlNodeListener.java new file mode 100644 index 00000000000..054c77c9fdf --- /dev/null +++ b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/xml/parser/IXmlNodeListener.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.jdk.core.util.xml.parser; + +import org.eclipse.osee.framework.jdk.core.collection.tree.TreeNode; + +/** + * @author Roberto E. Escobar + */ +public interface IXmlNodeListener { + + public void collectionChanged(TreeNode<XmlNode> collected); +} diff --git a/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/xml/parser/XmlNode.java b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/xml/parser/XmlNode.java new file mode 100644 index 00000000000..6a3c79e9f84 --- /dev/null +++ b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/xml/parser/XmlNode.java @@ -0,0 +1,64 @@ +/******************************************************************************* + * 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.jdk.core.util.xml.parser; + +import java.util.HashMap; +import java.util.Map; +import org.xml.sax.Attributes; + +/** + * @author Roberto E. Escobar + */ +public class XmlNode { + + private String name; + private String textContent; + private Map<String, String> attributes; + + public XmlNode(String name, Attributes attributes) { + this.name = name; + this.attributes = new HashMap<String, String>(attributes.getLength()); + for (int i = 0; i < attributes.getLength(); i++) + this.attributes.put(attributes.getQName(i), attributes.getValue(i)); + this.textContent = ""; + } + + /** + * @return Returns the textContent. + */ + public String getTextContent() { + return textContent; + } + + /** + * @param textContent The textContent to set. + */ + public void setTextContent(String textContent) { + if (textContent != null && textContent.length() > 0) { + this.textContent = textContent; + } + } + + /** + * @param qname + * @return Returns the value of the attribute matching the qualified name. + */ + public String getAttributeValue(String qname) { + return attributes.get(qname); + } + + /** + * @return Returns the name. + */ + public String getName() { + return name; + } +} diff --git a/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/xml/parser/XmlTreeUtilities.java b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/xml/parser/XmlTreeUtilities.java new file mode 100644 index 00000000000..0ef3310a66a --- /dev/null +++ b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/util/xml/parser/XmlTreeUtilities.java @@ -0,0 +1,120 @@ +/******************************************************************************* + * 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.jdk.core.util.xml.parser; + +import java.util.ArrayList; +import java.util.List; +import java.util.Stack; +import org.eclipse.osee.framework.jdk.core.collection.tree.TreeNode; + +/** + * @author Roberto E. Escobar + */ +public class XmlTreeUtilities { + + private static XmlTreeUtilities instance = null; + + private XmlTreeUtilities() { + } + + public static XmlTreeUtilities getInstance() { + if (instance == null) { + instance = new XmlTreeUtilities(); + } + return instance; + } + + private Stack<String> processPath(String pattern) { + Stack<String> elementPath = new Stack<String>(); + String[] path = pattern.split("/"); + for (int index = path.length - 1; index >= 0; index--) { + String entry = path[index]; + entry = entry.trim(); + if (entry.length() > 0) { + elementPath.push(entry); + } + } + return elementPath; + } + + public List<TreeNode<XmlNode>> getXmlNodesAt(String path, TreeNode<XmlNode> root) { + Stack<String> elementPath = processPath(path); + List<TreeNode<XmlNode>> toReturn = new ArrayList<TreeNode<XmlNode>>(); + List<TreeNode<XmlNode>> nodes = root.getChildren(); + while (!elementPath.empty()) { + String token = elementPath.pop(); + nodes = collectNodesMatchingToken(token, nodes); + } + if (nodes != null && nodes.size() > 0) { + toReturn.addAll(nodes); + } + + return toReturn; + } + + private List<TreeNode<XmlNode>> collectNodesMatchingToken(String token, List<TreeNode<XmlNode>> nodes) { + List<TreeNode<XmlNode>> toReturn = new ArrayList<TreeNode<XmlNode>>(); + + for (TreeNode<XmlNode> node : nodes) { + if (token.equalsIgnoreCase("*")) { + if (node.getChildren().size() > 0) { + toReturn.addAll(node.getChildren()); + } + } + if (node.getSelf().getName().equalsIgnoreCase(token)) { + toReturn.add(node); + if (node.getChildren().size() > 0) { + toReturn.addAll(node.getChildren()); + } + } + } + return toReturn; + } + + public int countNodesMatchingText(List<TreeNode<XmlNode>> nodes, String toMatch) { + int result = 0; + for (TreeNode<XmlNode> node : nodes) { + if (node != null) { + String content = node.getSelf().getTextContent(); + if (content.equalsIgnoreCase(toMatch)) { + result++; + } + } + } + return result; + } + + public XmlNode getFirstXmlNode(List<TreeNode<XmlNode>> nodes) { + XmlNode toReturn = null; + if (nodes.size() > 0) { + toReturn = nodes.get(0).getSelf(); + } + return toReturn; + } + + public String getFirstXmlNodeText(List<TreeNode<XmlNode>> nodes) { + XmlNode node = getFirstXmlNode(nodes); + return node != null ? node.getTextContent() : ""; + } + + public boolean containsNode(String path, TreeNode<XmlNode> nodes) { + List<TreeNode<XmlNode>> searchResults = getXmlNodesAt("Location", nodes); + return searchResults.size() > 0; + } + + public String getTextAtPath(String path, TreeNode<XmlNode> nodes) { + return getFirstXmlNodeText(getXmlNodesAt(path, nodes)); + } + + public XmlNode getXmlNodeAtPath(String path, TreeNode<XmlNode> nodes) { + return getFirstXmlNode(getXmlNodesAt(path, nodes)); + } +} diff --git a/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/validate/ExpressionValidator.java b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/validate/ExpressionValidator.java new file mode 100644 index 00000000000..e528b18c61d --- /dev/null +++ b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/validate/ExpressionValidator.java @@ -0,0 +1,47 @@ +/******************************************************************************* + * Copyright (c) 2004, 2007 Boeing. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Boeing - initial API and implementation + *******************************************************************************/ +package org.eclipse.osee.framework.jdk.core.validate; + +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +public class ExpressionValidator extends FieldValidator { + + public ExpressionValidator(String fieldName) { + super(fieldName); + } + + public boolean isValid() { + Object object = this.paramMap.get(fieldName); + if (object instanceof String) { + String toValidate = (String) object; + + Object expression = this.paramMap.get("expression"); + if (expression instanceof String) { + String expressionString = (String) expression; + if (expressionString.contains("matches")) { + expressionString = expressionString.replaceAll("\\s*matches\\('", ""); + expressionString = expressionString.replaceAll("\\'\\)\\s*", ""); + return matcher(toValidate, expressionString); + //return true; + } + } + } + return false; + } + + private boolean matcher(String toValidate, String regularExpression) { + Pattern pattern = Pattern.compile(regularExpression); + Matcher matcher = pattern.matcher(toValidate); + return matcher.matches(); + } + +} diff --git a/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/validate/FieldValidator.java b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/validate/FieldValidator.java new file mode 100644 index 00000000000..70f0a1f988d --- /dev/null +++ b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/validate/FieldValidator.java @@ -0,0 +1,50 @@ +/******************************************************************************* + * 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.jdk.core.validate; + +import java.util.HashMap; +import java.util.Map; + +public abstract class FieldValidator implements IValidator { + + protected String fieldName; + private String message; + protected Map<String, Object> paramMap; + + FieldValidator(String fieldName) { + this.fieldName = fieldName; + this.message = ""; + this.paramMap = new HashMap<String, Object>(); + } + + public String getFieldName() { + return fieldName; + } + + public String getMessage() { + for (String key : paramMap.keySet()) { + message = message.replaceAll("\\$\\{" + key + "\\}", paramMap.get(key).toString()); + } + return message; + } + + void setMessage(String message) { + this.message = message; + } + + public void setItemToValidate(Object object) { + this.paramMap.put(fieldName, object); + } + + void addParam(String paramName, Object value) { + this.paramMap.put(paramName, value); + } +} diff --git a/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/validate/IValidator.java b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/validate/IValidator.java new file mode 100644 index 00000000000..840961970eb --- /dev/null +++ b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/validate/IValidator.java @@ -0,0 +1,22 @@ +/******************************************************************************* + * Copyright (c) 2004, 2007 Boeing. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Boeing - initial API and implementation + *******************************************************************************/ +package org.eclipse.osee.framework.jdk.core.validate; + +public interface IValidator { + + public String getFieldName(); + + public String getMessage(); + + public void setItemToValidate(Object object); + + public boolean isValid(); +} diff --git a/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/validate/RequiredStringValidator.java b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/validate/RequiredStringValidator.java new file mode 100644 index 00000000000..4c33a052e41 --- /dev/null +++ b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/validate/RequiredStringValidator.java @@ -0,0 +1,27 @@ +/******************************************************************************* + * Copyright (c) 2004, 2007 Boeing. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Boeing - initial API and implementation + *******************************************************************************/ +package org.eclipse.osee.framework.jdk.core.validate; + +public class RequiredStringValidator extends FieldValidator { + + public RequiredStringValidator(String fieldName) { + super(fieldName); + } + + public boolean isValid() { + Object object = paramMap.get(fieldName); + if (object != null && object instanceof String) { + String value = (String) object; + return (value != null && !value.equals("")); + } + return false; + } +} diff --git a/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/validate/RequiredValidator.java b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/validate/RequiredValidator.java new file mode 100644 index 00000000000..7370c844edc --- /dev/null +++ b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/validate/RequiredValidator.java @@ -0,0 +1,23 @@ +/******************************************************************************* + * 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.jdk.core.validate; + +public class RequiredValidator extends FieldValidator { + + public RequiredValidator(String fieldName) { + super(fieldName); + } + + public boolean isValid() { + return false; + } + +} diff --git a/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/validate/Validator.java b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/validate/Validator.java new file mode 100644 index 00000000000..492edbdf78c --- /dev/null +++ b/org.eclipse.osee.framework.jdk.core/src/org/eclipse/osee/framework/jdk/core/validate/Validator.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.jdk.core.validate; + +import java.io.InputStream; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; + +public class Validator { + + private InputStream fileToRead; + private Map<String, List<IValidator>> validatorMap; + + private enum EntryEnum { + field; + } + + private enum FieldAttributes { + name; + } + + private enum FieldEntries { + validator; + } + + private enum FieldValidatorAttributes { + type; + } + + private enum FieldValidatorEntries { + message, param; + } + + private enum ParamAttributes { + name; + } + + private enum ValidationTypes { + requiredstring, required, expression; + } + + public Validator(InputStream fileToRead) throws Exception { + this.fileToRead = fileToRead; + this.validatorMap = new HashMap<String, List<IValidator>>(); + parseFile(); + } + + private void storeValidator(String fieldName, IValidator validator) { + List<IValidator> list = null; + if (!validatorMap.containsKey(fieldName)) { + list = new ArrayList<IValidator>(); + validatorMap.put(fieldName, list); + } else { + list = validatorMap.get(fieldName); + } + list.add(validator); + } + + private void parseMessage(Element element, FieldValidator validator) { + NodeList messageList = element.getElementsByTagName(FieldValidatorEntries.message.name()); + if (messageList.getLength() == 1) { + Node node = messageList.item(0); + if (node != null) { + String message = node.getTextContent(); + if (message != null && !message.equals("")) { + validator.setMessage(message.trim()); + } + } + } + } + + private void parseParams(Element element, FieldValidator validator) { + NodeList paramList = element.getElementsByTagName(FieldValidatorEntries.param.name()); + for (int i = 0; i < paramList.getLength(); i++) { + Element paramElement = (Element) paramList.item(i); + String paramName = paramElement.getAttribute(ParamAttributes.name.name()); + if (paramName != null && !paramName.equals("")) { + String content = paramElement.getTextContent(); + if (content != null && !content.equals("")) { + validator.addParam(paramName.trim(), content.trim()); + } + } + } + } + + private void parseValidator(Element element, String fieldName, String validatorType) { + FieldValidator validator = validatorFactory(fieldName, validatorType); + if (validator != null) { + parseMessage(element, validator); + parseParams(element, validator); + storeValidator(fieldName, validator); + } + } + + private void parseFile() throws Exception { + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + DocumentBuilder builder = factory.newDocumentBuilder(); + Document document = builder.parse(fileToRead); + + NodeList fields = document.getElementsByTagName(EntryEnum.field.name()); + + for (int i = 0; i < fields.getLength(); i++) { + + Element fieldElement = (Element) fields.item(i); + String fieldName = fieldElement.getAttribute(FieldAttributes.name.name()); + if (fieldName != null && !fieldName.equals("")) { + + NodeList validators = fieldElement.getElementsByTagName(FieldEntries.validator.name()); + for (int j = 0; j < validators.getLength(); j++) { + Element validatorElement = (Element) validators.item(j); + + String validatorType = validatorElement.getAttribute(FieldValidatorAttributes.type.name()); + if (validatorType != null && !validatorType.equals("")) { + parseValidator(validatorElement, fieldName.trim(), validatorType.trim()); + } + } + } + } + } + + private FieldValidator validatorFactory(String name, String type) { + FieldValidator toReturn = null; + ValidationTypes validationType = ValidationTypes.valueOf(type); + switch (validationType) { + case requiredstring: + toReturn = new RequiredStringValidator(name); + break; + case required: + toReturn = new RequiredValidator(name); + break; + case expression: + toReturn = new ExpressionValidator(name); + default: + break; + } + return toReturn; + } + + public List<IValidator> getValidator(String fieldName) { + List<IValidator> list = validatorMap.get(fieldName); + return (list != null ? list : new ArrayList<IValidator>()); + } +} |