This commit was manufactured by cvs2svn to create branch 'R3_0_5_patches'.
diff --git a/features/org.eclipse.wst.common_core.feature.patch/buildnotes_org.eclipse.wst.common_core.feature.patch.html b/features/org.eclipse.wst.common_core.feature.patch/buildnotes_org.eclipse.wst.common_core.feature.patch.html
deleted file mode 100644
index 540cb68..0000000
--- a/features/org.eclipse.wst.common_core.feature.patch/buildnotes_org.eclipse.wst.common_core.feature.patch.html
+++ /dev/null
@@ -1,17 +0,0 @@
-<!doctype html public "-//w3c//dtd html 4.0 transitional//en">
-<html>
-
-<head>
- <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
- <meta name="Build" content="Build">
- <title>WTP 1.5.5 Patches</title>
-</head>
-
-<body>
-
-<h1>WTP 1.5.5 Patches</h1>
-
-<h2>org.eclipse.wst.common_core.feature</h2>
-
-<p>Bug <a href='https://bugs.eclipse.org/bugs/show_bug.cgi?id=203155'>203155</a>. ISynchronizerExtenders not invoked if ResourceDelta contains changes from >1 project</p>
-<p>Bug <a href='https://bugs.eclipse.org/bugs/show_bug.cgi?id=206463'>206463</a>. Threading issues with WebServicesNode Job</p>
diff --git a/features/org.eclipse.wst.common_ui.feature.patch/.cvsignore b/features/org.eclipse.wst.common_ui.feature.patch/.cvsignore
new file mode 100644
index 0000000..c14487c
--- /dev/null
+++ b/features/org.eclipse.wst.common_ui.feature.patch/.cvsignore
@@ -0,0 +1 @@
+build.xml
diff --git a/features/org.eclipse.wst.common_ui.feature.patch/.project b/features/org.eclipse.wst.common_ui.feature.patch/.project
new file mode 100644
index 0000000..0dbb12b
--- /dev/null
+++ b/features/org.eclipse.wst.common_ui.feature.patch/.project
@@ -0,0 +1,17 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<projectDescription>
+ <name>org.eclipse.wst.common_ui.feature.patch</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/features/org.eclipse.wst.common_ui.feature.patch/build.properties b/features/org.eclipse.wst.common_ui.feature.patch/build.properties
new file mode 100644
index 0000000..cb50260
--- /dev/null
+++ b/features/org.eclipse.wst.common_ui.feature.patch/build.properties
@@ -0,0 +1,5 @@
+bin.includes = feature.xml,\
+ license.html,\
+ feature.properties,\
+ epl-v10.html,\
+ eclipse_update_120.jpg
diff --git a/features/org.eclipse.wst.common_ui.feature.patch/buildnotes_org.eclipse.wst.common_ui.feature.patch.html b/features/org.eclipse.wst.common_ui.feature.patch/buildnotes_org.eclipse.wst.common_ui.feature.patch.html
new file mode 100644
index 0000000..82503c2
--- /dev/null
+++ b/features/org.eclipse.wst.common_ui.feature.patch/buildnotes_org.eclipse.wst.common_ui.feature.patch.html
@@ -0,0 +1,18 @@
+<!doctype html public "-//w3c//dtd html 4.0 transitional//en">
+<html>
+
+<head>
+<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
+<meta name="Build" content="Build">
+<title>WTP 3.0.4 Patches</title>
+</head>
+
+<body>
+
+<h1>WTP 3.0.4 Patches</h1>
+
+<h2>org.eclipse.wst.common_ui.feature</h2>
+
+<p>Bug <a href='https://bugs.eclipse.org/267144'>267144</a>. RuntimesPropertyPage needs ProgressMonitor</p>
+</body>
+</html>
\ No newline at end of file
diff --git a/features/org.eclipse.wst.common_ui.feature.patch/eclipse_update_120.jpg b/features/org.eclipse.wst.common_ui.feature.patch/eclipse_update_120.jpg
new file mode 100644
index 0000000..bfdf708
--- /dev/null
+++ b/features/org.eclipse.wst.common_ui.feature.patch/eclipse_update_120.jpg
Binary files differ
diff --git a/features/org.eclipse.wst.common_ui.feature.patch/epl-v10.html b/features/org.eclipse.wst.common_ui.feature.patch/epl-v10.html
new file mode 100644
index 0000000..ed4b196
--- /dev/null
+++ b/features/org.eclipse.wst.common_ui.feature.patch/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/features/org.eclipse.wst.common_core.feature.patch/feature.properties b/features/org.eclipse.wst.common_ui.feature.patch/feature.properties
similarity index 93%
rename from features/org.eclipse.wst.common_core.feature.patch/feature.properties
rename to features/org.eclipse.wst.common_ui.feature.patch/feature.properties
index e80208a..52e1b78 100644
--- a/features/org.eclipse.wst.common_core.feature.patch/feature.properties
+++ b/features/org.eclipse.wst.common_ui.feature.patch/feature.properties
@@ -1,5 +1,5 @@
###############################################################################
-# Copyright (c) 2007 IBM Corporation and others.
+# Copyright (c) 2008 IBM Corporation 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
@@ -15,7 +15,7 @@
# This file should be translated.
# "featureName" property - name of the feature
-featureName=WTP Patch for wst.common_core
+featureName=WTP Patches for org.eclipse.wst.common_ui.feature
# "providerName" property - name of the company that provides the feature
providerName=Eclipse.org
@@ -25,16 +25,14 @@
# "description" property - description of the feature
description=\
-A patch feature for common.emfworkbench.integration \n\
-This patch fixes problems as described in the bugzillas below.\n\
+Contains fixes described in the following bugillia(s):\n\
\n\
-Bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=203155 ISynchronizerExtenders not invoked if ResourceDelta contains changes from more than 1 project \n\
-Bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=206463 Threading issues with WebServicesNode Job \n\
+Bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=267144 RuntimesPropertyPage needs ProgressMonitor\n\
\n\
# "copyright" property - text of the "Feature Update Copyright"
copyright=\
-Copyright (c) 2007 IBM Corporation and others.\n\
+Copyright (c) 2008 IBM Corporation 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\
@@ -52,7 +50,7 @@
# should be plain text version of license agreement pointed to be "licenseURL"
license=\
ECLIPSE FOUNDATION SOFTWARE USER AGREEMENT\n\
-September 27, 2007\n\
+September, 2008\n\
\n\
Usage Of Content\n\
\n\
diff --git a/features/org.eclipse.wst.common_core.feature.patch/feature.xml b/features/org.eclipse.wst.common_ui.feature.patch/feature.xml
similarity index 61%
rename from features/org.eclipse.wst.common_core.feature.patch/feature.xml
rename to features/org.eclipse.wst.common_ui.feature.patch/feature.xml
index 58bd8a3..c6ed5b7 100644
--- a/features/org.eclipse.wst.common_core.feature.patch/feature.xml
+++ b/features/org.eclipse.wst.common_ui.feature.patch/feature.xml
@@ -1,8 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<feature
- id="org.eclipse.wst.common_core.feature.patch"
+ id="org.eclipse.wst.common_ui.feature.patch"
label="%featureName"
- version="1.5.5.qualifier"
+ version="3.0.4.qualifier"
provider-name="%providerName">
<description>
@@ -18,14 +18,14 @@
</license>
<requires>
- <import feature="org.eclipse.wst.common_core.feature" version="1.5.5.v200708010505--AXrVWgWbmEdPjw" patch="true"/>
+ <import feature="org.eclipse.wst.common_ui.feature" version="3.0.4.v200811200248-7C78ELhE8VrRVqtHp4iT8PuSwZ5W" patch="true"/>
</requires>
<plugin
- id="org.eclipse.wst.common.emfworkbench.integration"
+ id="org.eclipse.wst.common.project.facet.ui"
download-size="0"
install-size="0"
version="0.0.0"
unpack="false"/>
-
+
</feature>
diff --git a/features/org.eclipse.wst.common_ui.feature.patch/license.html b/features/org.eclipse.wst.common_ui.feature.patch/license.html
new file mode 100644
index 0000000..2347060
--- /dev/null
+++ b/features/org.eclipse.wst.common_ui.feature.patch/license.html
@@ -0,0 +1,93 @@
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3c.org/TR/1999/REC-html401-19991224/loose.dtd">
+<!-- saved from url=(0044)http://www.eclipse.org/legal/epl/notice.html -->
+<HTML><HEAD><TITLE>Eclipse.org Software User Agreement</TITLE>
+<META http-equiv=Content-Type content="text/html; charset=iso-8859-1">
+<META content="MSHTML 6.00.2800.1479" name=GENERATOR></HEAD>
+<BODY lang=EN-US vLink=purple link=blue>
+<H2>Eclipse Foundation Software User Agreement</H2>
+<P>January 28, 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>
+<P>Content may be apportioned into plug-ins ("Plug-ins"), plug-in fragments
+("Fragments"), and features ("Features"). A Feature is a bundle of one or more
+Plug-ins and/or Fragments and associated material. Files named "feature.xml" may
+contain a list of the names and version numbers of the Plug-ins and/or Fragments
+associated with a Feature. Plug-ins and Fragments are located in directories
+named "plugins" and Features are located in directories named "features".</P>
+<P>Features may also include other Features ("Included Features"). Files named
+"feature.xml" may contain a list of the names and version numbers of Included
+Features.</P>
+<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>Plug-in and Fragment directories
+ <LI>Subdirectories of the directory named "src" of certain Plug-ins
+ <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". 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>Apache Software License 1.1 (available at <A
+ href="http://www.apache.org/licenses/LICENSE">http://www.apache.org/licenses/LICENSE</A>)
+
+ <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>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>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>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></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></BODY></HTML>
diff --git a/plugins/org.eclipse.jem.util/.classpath b/plugins/org.eclipse.jem.util/.classpath
new file mode 100644
index 0000000..a988941
--- /dev/null
+++ b/plugins/org.eclipse.jem.util/.classpath
@@ -0,0 +1,9 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<classpath>
+ <classpathentry kind="src" path="jemutil"/>
+ <classpathentry kind="src" path="property_files"/>
+ <classpathentry kind="src" path="jemutil-nonworkbnech"/>
+ <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/J2SE-1.5"/>
+ <classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/>
+ <classpathentry kind="output" path="bin"/>
+</classpath>
diff --git a/plugins/org.eclipse.jem.util/.cvsignore b/plugins/org.eclipse.jem.util/.cvsignore
new file mode 100644
index 0000000..e043cc4
--- /dev/null
+++ b/plugins/org.eclipse.jem.util/.cvsignore
@@ -0,0 +1,3 @@
+bin
+build.xml
+javaCompiler...args
diff --git a/plugins/org.eclipse.jem.util/.options b/plugins/org.eclipse.jem.util/.options
new file mode 100644
index 0000000..0565417
--- /dev/null
+++ b/plugins/org.eclipse.jem.util/.options
@@ -0,0 +1,3 @@
+org.eclipse.jem.util/debug/logtrace=false
+org.eclipse.jem.util/debug/logtracefile=false
+org.eclipse.jem.util/debug/loglevel=WARNING
\ No newline at end of file
diff --git a/plugins/org.eclipse.jem.util/.project b/plugins/org.eclipse.jem.util/.project
new file mode 100644
index 0000000..e0e4120
--- /dev/null
+++ b/plugins/org.eclipse.jem.util/.project
@@ -0,0 +1,28 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<projectDescription>
+ <name>org.eclipse.jem.util</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/plugins/org.eclipse.jem.util/.settings/org.eclipse.core.resources.prefs b/plugins/org.eclipse.jem.util/.settings/org.eclipse.core.resources.prefs
new file mode 100644
index 0000000..02c2954
--- /dev/null
+++ b/plugins/org.eclipse.jem.util/.settings/org.eclipse.core.resources.prefs
@@ -0,0 +1,3 @@
+#Sun Apr 15 21:15:45 EDT 2007
+eclipse.preferences.version=1
+encoding/<project>=ISO-8859-1
diff --git a/plugins/org.eclipse.jem.util/.settings/org.eclipse.jdt.core.prefs b/plugins/org.eclipse.jem.util/.settings/org.eclipse.jdt.core.prefs
new file mode 100644
index 0000000..cb579cc
--- /dev/null
+++ b/plugins/org.eclipse.jem.util/.settings/org.eclipse.jdt.core.prefs
@@ -0,0 +1,292 @@
+#Tue Jul 31 20:39:48 EDT 2007
+eclipse.preferences.version=1
+org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.5
+org.eclipse.jdt.core.compiler.compliance=1.5
+org.eclipse.jdt.core.compiler.problem.annotationSuperInterface=warning
+org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
+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.emptyStatement=ignore
+org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
+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.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=error
+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.syntheticAccessEmulation=ignore
+org.eclipse.jdt.core.compiler.problem.typeParameterHiding=warning
+org.eclipse.jdt.core.compiler.problem.uncheckedTypeOperation=warning
+org.eclipse.jdt.core.compiler.problem.undocumentedEmptyBlock=ignore
+org.eclipse.jdt.core.compiler.problem.unnecessaryElse=ignore
+org.eclipse.jdt.core.compiler.problem.unnecessaryTypeCheck=error
+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=error
+org.eclipse.jdt.core.compiler.problem.unusedLocal=error
+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=error
+org.eclipse.jdt.core.compiler.problem.varargsArgumentNeedCast=warning
+org.eclipse.jdt.core.compiler.source=1.5
+org.eclipse.jdt.core.formatter.align_type_members_on_columns=false
+org.eclipse.jdt.core.formatter.alignment_for_arguments_in_allocation_expression=16
+org.eclipse.jdt.core.formatter.alignment_for_arguments_in_enum_constant=16
+org.eclipse.jdt.core.formatter.alignment_for_arguments_in_explicit_constructor_call=16
+org.eclipse.jdt.core.formatter.alignment_for_arguments_in_method_invocation=16
+org.eclipse.jdt.core.formatter.alignment_for_arguments_in_qualified_allocation_expression=16
+org.eclipse.jdt.core.formatter.alignment_for_assignment=0
+org.eclipse.jdt.core.formatter.alignment_for_binary_expression=16
+org.eclipse.jdt.core.formatter.alignment_for_compact_if=16
+org.eclipse.jdt.core.formatter.alignment_for_conditional_expression=80
+org.eclipse.jdt.core.formatter.alignment_for_enum_constants=0
+org.eclipse.jdt.core.formatter.alignment_for_expressions_in_array_initializer=16
+org.eclipse.jdt.core.formatter.alignment_for_multiple_fields=16
+org.eclipse.jdt.core.formatter.alignment_for_parameters_in_constructor_declaration=16
+org.eclipse.jdt.core.formatter.alignment_for_parameters_in_method_declaration=16
+org.eclipse.jdt.core.formatter.alignment_for_selector_in_method_invocation=16
+org.eclipse.jdt.core.formatter.alignment_for_superclass_in_type_declaration=16
+org.eclipse.jdt.core.formatter.alignment_for_superinterfaces_in_enum_declaration=16
+org.eclipse.jdt.core.formatter.alignment_for_superinterfaces_in_type_declaration=16
+org.eclipse.jdt.core.formatter.alignment_for_throws_clause_in_constructor_declaration=16
+org.eclipse.jdt.core.formatter.alignment_for_throws_clause_in_method_declaration=16
+org.eclipse.jdt.core.formatter.blank_lines_after_imports=1
+org.eclipse.jdt.core.formatter.blank_lines_after_package=1
+org.eclipse.jdt.core.formatter.blank_lines_before_field=1
+org.eclipse.jdt.core.formatter.blank_lines_before_first_class_body_declaration=1
+org.eclipse.jdt.core.formatter.blank_lines_before_imports=1
+org.eclipse.jdt.core.formatter.blank_lines_before_member_type=1
+org.eclipse.jdt.core.formatter.blank_lines_before_method=1
+org.eclipse.jdt.core.formatter.blank_lines_before_new_chunk=1
+org.eclipse.jdt.core.formatter.blank_lines_before_package=0
+org.eclipse.jdt.core.formatter.blank_lines_between_type_declarations=1
+org.eclipse.jdt.core.formatter.brace_position_for_annotation_type_declaration=end_of_line
+org.eclipse.jdt.core.formatter.brace_position_for_anonymous_type_declaration=end_of_line
+org.eclipse.jdt.core.formatter.brace_position_for_array_initializer=end_of_line
+org.eclipse.jdt.core.formatter.brace_position_for_block=end_of_line
+org.eclipse.jdt.core.formatter.brace_position_for_block_in_case=end_of_line
+org.eclipse.jdt.core.formatter.brace_position_for_constructor_declaration=end_of_line
+org.eclipse.jdt.core.formatter.brace_position_for_enum_constant=end_of_line
+org.eclipse.jdt.core.formatter.brace_position_for_enum_declaration=end_of_line
+org.eclipse.jdt.core.formatter.brace_position_for_method_declaration=end_of_line
+org.eclipse.jdt.core.formatter.brace_position_for_switch=end_of_line
+org.eclipse.jdt.core.formatter.brace_position_for_type_declaration=end_of_line
+org.eclipse.jdt.core.formatter.comment.format_header=false
+org.eclipse.jdt.core.formatter.comment.format_html=true
+org.eclipse.jdt.core.formatter.comment.format_source_code=true
+org.eclipse.jdt.core.formatter.comment.indent_parameter_description=true
+org.eclipse.jdt.core.formatter.comment.indent_root_tags=true
+org.eclipse.jdt.core.formatter.comment.insert_new_line_before_root_tags=insert
+org.eclipse.jdt.core.formatter.comment.insert_new_line_for_parameter=insert
+org.eclipse.jdt.core.formatter.comment.line_length=150
+org.eclipse.jdt.core.formatter.compact_else_if=true
+org.eclipse.jdt.core.formatter.continuation_indentation=2
+org.eclipse.jdt.core.formatter.continuation_indentation_for_array_initializer=2
+org.eclipse.jdt.core.formatter.format_guardian_clause_on_one_line=true
+org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_annotation_declaration_header=true
+org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_enum_constant_header=true
+org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_enum_declaration_header=true
+org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_type_header=true
+org.eclipse.jdt.core.formatter.indent_breaks_compare_to_cases=true
+org.eclipse.jdt.core.formatter.indent_empty_lines=false
+org.eclipse.jdt.core.formatter.indent_statements_compare_to_block=true
+org.eclipse.jdt.core.formatter.indent_statements_compare_to_body=true
+org.eclipse.jdt.core.formatter.indent_switchstatements_compare_to_cases=true
+org.eclipse.jdt.core.formatter.indent_switchstatements_compare_to_switch=true
+org.eclipse.jdt.core.formatter.indentation.size=4
+org.eclipse.jdt.core.formatter.insert_new_line_after_annotation=insert
+org.eclipse.jdt.core.formatter.insert_new_line_after_opening_brace_in_array_initializer=do not insert
+org.eclipse.jdt.core.formatter.insert_new_line_at_end_of_file_if_missing=do not insert
+org.eclipse.jdt.core.formatter.insert_new_line_before_catch_in_try_statement=do not insert
+org.eclipse.jdt.core.formatter.insert_new_line_before_closing_brace_in_array_initializer=do not insert
+org.eclipse.jdt.core.formatter.insert_new_line_before_else_in_if_statement=do not insert
+org.eclipse.jdt.core.formatter.insert_new_line_before_finally_in_try_statement=do not insert
+org.eclipse.jdt.core.formatter.insert_new_line_before_while_in_do_statement=do not insert
+org.eclipse.jdt.core.formatter.insert_new_line_in_empty_annotation_declaration=insert
+org.eclipse.jdt.core.formatter.insert_new_line_in_empty_anonymous_type_declaration=insert
+org.eclipse.jdt.core.formatter.insert_new_line_in_empty_block=insert
+org.eclipse.jdt.core.formatter.insert_new_line_in_empty_enum_constant=insert
+org.eclipse.jdt.core.formatter.insert_new_line_in_empty_enum_declaration=insert
+org.eclipse.jdt.core.formatter.insert_new_line_in_empty_method_body=insert
+org.eclipse.jdt.core.formatter.insert_new_line_in_empty_type_declaration=insert
+org.eclipse.jdt.core.formatter.insert_space_after_and_in_type_parameter=insert
+org.eclipse.jdt.core.formatter.insert_space_after_assignment_operator=insert
+org.eclipse.jdt.core.formatter.insert_space_after_at_in_annotation=do not insert
+org.eclipse.jdt.core.formatter.insert_space_after_at_in_annotation_type_declaration=do not insert
+org.eclipse.jdt.core.formatter.insert_space_after_binary_operator=insert
+org.eclipse.jdt.core.formatter.insert_space_after_closing_angle_bracket_in_type_arguments=insert
+org.eclipse.jdt.core.formatter.insert_space_after_closing_angle_bracket_in_type_parameters=insert
+org.eclipse.jdt.core.formatter.insert_space_after_closing_brace_in_block=insert
+org.eclipse.jdt.core.formatter.insert_space_after_closing_paren_in_cast=insert
+org.eclipse.jdt.core.formatter.insert_space_after_colon_in_assert=insert
+org.eclipse.jdt.core.formatter.insert_space_after_colon_in_case=insert
+org.eclipse.jdt.core.formatter.insert_space_after_colon_in_conditional=insert
+org.eclipse.jdt.core.formatter.insert_space_after_colon_in_for=insert
+org.eclipse.jdt.core.formatter.insert_space_after_colon_in_labeled_statement=insert
+org.eclipse.jdt.core.formatter.insert_space_after_comma_in_allocation_expression=insert
+org.eclipse.jdt.core.formatter.insert_space_after_comma_in_annotation=insert
+org.eclipse.jdt.core.formatter.insert_space_after_comma_in_array_initializer=insert
+org.eclipse.jdt.core.formatter.insert_space_after_comma_in_constructor_declaration_parameters=insert
+org.eclipse.jdt.core.formatter.insert_space_after_comma_in_constructor_declaration_throws=insert
+org.eclipse.jdt.core.formatter.insert_space_after_comma_in_enum_constant_arguments=insert
+org.eclipse.jdt.core.formatter.insert_space_after_comma_in_enum_declarations=insert
+org.eclipse.jdt.core.formatter.insert_space_after_comma_in_explicitconstructorcall_arguments=insert
+org.eclipse.jdt.core.formatter.insert_space_after_comma_in_for_increments=insert
+org.eclipse.jdt.core.formatter.insert_space_after_comma_in_for_inits=insert
+org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_declaration_parameters=insert
+org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_declaration_throws=insert
+org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_invocation_arguments=insert
+org.eclipse.jdt.core.formatter.insert_space_after_comma_in_multiple_field_declarations=insert
+org.eclipse.jdt.core.formatter.insert_space_after_comma_in_multiple_local_declarations=insert
+org.eclipse.jdt.core.formatter.insert_space_after_comma_in_parameterized_type_reference=insert
+org.eclipse.jdt.core.formatter.insert_space_after_comma_in_superinterfaces=insert
+org.eclipse.jdt.core.formatter.insert_space_after_comma_in_type_arguments=insert
+org.eclipse.jdt.core.formatter.insert_space_after_comma_in_type_parameters=insert
+org.eclipse.jdt.core.formatter.insert_space_after_ellipsis=insert
+org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_parameterized_type_reference=do not insert
+org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_type_arguments=do not insert
+org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_type_parameters=do not insert
+org.eclipse.jdt.core.formatter.insert_space_after_opening_brace_in_array_initializer=insert
+org.eclipse.jdt.core.formatter.insert_space_after_opening_bracket_in_array_allocation_expression=do not insert
+org.eclipse.jdt.core.formatter.insert_space_after_opening_bracket_in_array_reference=do not insert
+org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_annotation=do not insert
+org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_cast=do not insert
+org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_catch=do not insert
+org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_constructor_declaration=do not insert
+org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_enum_constant=do not insert
+org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_for=do not insert
+org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_if=do not insert
+org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_method_declaration=do not insert
+org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_method_invocation=do not insert
+org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_parenthesized_expression=do not insert
+org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_switch=do not insert
+org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_synchronized=do not insert
+org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_while=do not insert
+org.eclipse.jdt.core.formatter.insert_space_after_postfix_operator=do not insert
+org.eclipse.jdt.core.formatter.insert_space_after_prefix_operator=do not insert
+org.eclipse.jdt.core.formatter.insert_space_after_question_in_conditional=insert
+org.eclipse.jdt.core.formatter.insert_space_after_question_in_wildcard=do not insert
+org.eclipse.jdt.core.formatter.insert_space_after_semicolon_in_for=insert
+org.eclipse.jdt.core.formatter.insert_space_after_unary_operator=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_and_in_type_parameter=insert
+org.eclipse.jdt.core.formatter.insert_space_before_assignment_operator=insert
+org.eclipse.jdt.core.formatter.insert_space_before_at_in_annotation_type_declaration=insert
+org.eclipse.jdt.core.formatter.insert_space_before_binary_operator=insert
+org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_parameterized_type_reference=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_type_arguments=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_type_parameters=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_closing_brace_in_array_initializer=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_closing_bracket_in_array_allocation_expression=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_closing_bracket_in_array_reference=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_annotation=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_cast=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_catch=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_constructor_declaration=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_enum_constant=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_for=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_if=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_method_declaration=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_method_invocation=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_parenthesized_expression=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_switch=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_synchronized=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_while=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_colon_in_assert=insert
+org.eclipse.jdt.core.formatter.insert_space_before_colon_in_case=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_colon_in_conditional=insert
+org.eclipse.jdt.core.formatter.insert_space_before_colon_in_default=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_colon_in_for=insert
+org.eclipse.jdt.core.formatter.insert_space_before_colon_in_labeled_statement=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_comma_in_allocation_expression=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_comma_in_annotation=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_comma_in_array_initializer=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_comma_in_constructor_declaration_parameters=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_comma_in_constructor_declaration_throws=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_comma_in_enum_constant_arguments=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_comma_in_enum_declarations=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_comma_in_explicitconstructorcall_arguments=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_comma_in_for_increments=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_comma_in_for_inits=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_declaration_parameters=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_declaration_throws=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_invocation_arguments=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_comma_in_multiple_field_declarations=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_comma_in_multiple_local_declarations=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_comma_in_parameterized_type_reference=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_comma_in_superinterfaces=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_comma_in_type_arguments=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_comma_in_type_parameters=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_ellipsis=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_parameterized_type_reference=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_type_arguments=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_type_parameters=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_annotation_type_declaration=insert
+org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_anonymous_type_declaration=insert
+org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_array_initializer=insert
+org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_block=insert
+org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_constructor_declaration=insert
+org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_enum_constant=insert
+org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_enum_declaration=insert
+org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_method_declaration=insert
+org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_switch=insert
+org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_type_declaration=insert
+org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_allocation_expression=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_reference=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_type_reference=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_annotation=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_annotation_type_member_declaration=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_catch=insert
+org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_constructor_declaration=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_enum_constant=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_for=insert
+org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_if=insert
+org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_method_declaration=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_method_invocation=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_parenthesized_expression=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_switch=insert
+org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_synchronized=insert
+org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_while=insert
+org.eclipse.jdt.core.formatter.insert_space_before_parenthesized_expression_in_return=insert
+org.eclipse.jdt.core.formatter.insert_space_before_postfix_operator=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_prefix_operator=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_question_in_conditional=insert
+org.eclipse.jdt.core.formatter.insert_space_before_question_in_wildcard=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_semicolon=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_semicolon_in_for=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_unary_operator=do not insert
+org.eclipse.jdt.core.formatter.insert_space_between_brackets_in_array_type_reference=do not insert
+org.eclipse.jdt.core.formatter.insert_space_between_empty_braces_in_array_initializer=do not insert
+org.eclipse.jdt.core.formatter.insert_space_between_empty_brackets_in_array_allocation_expression=do not insert
+org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_annotation_type_member_declaration=do not insert
+org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_constructor_declaration=do not insert
+org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_enum_constant=do not insert
+org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_method_declaration=do not insert
+org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_method_invocation=do not insert
+org.eclipse.jdt.core.formatter.keep_else_statement_on_same_line=false
+org.eclipse.jdt.core.formatter.keep_empty_array_initializer_on_one_line=false
+org.eclipse.jdt.core.formatter.keep_imple_if_on_one_line=false
+org.eclipse.jdt.core.formatter.keep_then_statement_on_same_line=false
+org.eclipse.jdt.core.formatter.lineSplit=150
+org.eclipse.jdt.core.formatter.number_of_blank_lines_at_beginning_of_method_body=0
+org.eclipse.jdt.core.formatter.number_of_empty_lines_to_preserve=1
+org.eclipse.jdt.core.formatter.put_empty_statement_on_new_line=true
+org.eclipse.jdt.core.formatter.tabulation.char=tab
+org.eclipse.jdt.core.formatter.tabulation.size=4
+org.eclipse.jdt.core.formatter.use_tabs_only_for_leading_indentations=false
diff --git a/plugins/org.eclipse.jem.util/.settings/org.eclipse.jdt.ui.prefs b/plugins/org.eclipse.jem.util/.settings/org.eclipse.jdt.ui.prefs
new file mode 100644
index 0000000..6c8e1bc
--- /dev/null
+++ b/plugins/org.eclipse.jem.util/.settings/org.eclipse.jdt.ui.prefs
@@ -0,0 +1,8 @@
+#Tue Feb 21 10:09:19 EST 2006
+eclipse.preferences.version=1
+formatter_profile=_jve
+formatter_settings_version=10
+org.eclipse.jdt.ui.ignorelowercasenames=true
+org.eclipse.jdt.ui.importorder=java;javax;org;org.eclipse.wtp;org.eclipse.jem;org.eclipse.ve.internal.cdm;org.eclipse.ve.internal.cde;org.eclipse.ve.internal.jcm;org.eclipse.ve.internal.java;org.eclipse.ve;com;
+org.eclipse.jdt.ui.ondemandthreshold=3
+org.eclipse.jdt.ui.text.custom_code_templates=<?xml version\="1.0" encoding\="UTF-8"?><templates/>
diff --git a/plugins/org.eclipse.jem.util/.settings/org.eclipse.pde.prefs b/plugins/org.eclipse.jem.util/.settings/org.eclipse.pde.prefs
new file mode 100644
index 0000000..fb46b28
--- /dev/null
+++ b/plugins/org.eclipse.jem.util/.settings/org.eclipse.pde.prefs
@@ -0,0 +1,12 @@
+#Fri May 13 10:10:04 EDT 2005
+compilers.p.deprecated=1
+compilers.p.no-required-att=0
+compilers.p.not-externalized-att=2
+compilers.p.unknown-attribute=0
+compilers.p.unknown-class=2
+compilers.p.unknown-element=1
+compilers.p.unknown-resource=2
+compilers.p.unresolved-ex-points=0
+compilers.p.unresolved-import=2
+compilers.use-project=true
+eclipse.preferences.version=1
diff --git a/plugins/org.eclipse.jem.util/META-INF/MANIFEST.MF b/plugins/org.eclipse.jem.util/META-INF/MANIFEST.MF
new file mode 100644
index 0000000..9e05ebc
--- /dev/null
+++ b/plugins/org.eclipse.jem.util/META-INF/MANIFEST.MF
@@ -0,0 +1,26 @@
+Manifest-Version: 1.0
+Bundle-ManifestVersion: 2
+Bundle-Name: %pluginName
+Bundle-SymbolicName: org.eclipse.jem.util; singleton:=true
+Bundle-Version: 2.0.101.qualifier
+Bundle-Activator: org.eclipse.jem.util.plugin.JEMUtilPlugin
+Bundle-Vendor: %providerName
+Bundle-Localization: plugin
+Export-Package: org.eclipse.jem.internal.util.emf.workbench;x-friends:="org.eclipse.jem.beaninfo",
+ org.eclipse.jem.internal.util.emf.workbench.nature;x-internal:=true,
+ org.eclipse.jem.internal.util.emf.workbench.nls;x-internal:=true,
+ org.eclipse.jem.util,
+ org.eclipse.jem.util.emf.workbench,
+ org.eclipse.jem.util.emf.workbench.nature,
+ org.eclipse.jem.util.logger,
+ org.eclipse.jem.util.logger.proxy,
+ org.eclipse.jem.util.logger.proxyrender,
+ org.eclipse.jem.util.plugin
+Require-Bundle: org.eclipse.core.runtime;bundle-version="[3.4.0,4.0.0)",
+ org.eclipse.core.resources;bundle-version="[3.4.0,4.0.0)",
+ org.eclipse.emf.ecore;bundle-version="[2.4.0,3.0.0)",
+ org.eclipse.emf.ecore.xmi;bundle-version="[2.4.0,3.0.0)",
+ org.eclipse.perfmsr.core;bundle-version="1.0.0";resolution:=optional,
+ com.ibm.icu;bundle-version="[3.8.1.1,4.0.0)"
+Eclipse-LazyStart: true
+Bundle-RequiredExecutionEnvironment: J2SE-1.5
diff --git a/plugins/org.eclipse.jem.util/PERFMSR_README.txt b/plugins/org.eclipse.jem.util/PERFMSR_README.txt
new file mode 100644
index 0000000..ea51258
--- /dev/null
+++ b/plugins/org.eclipse.jem.util/PERFMSR_README.txt
@@ -0,0 +1,12 @@
+org.eclipse.perfmsr.core code can be found in the perfmsr.jar loaded as binary in this
+project. Since this is optional, we needed to be able to compile without the true
+plugin being available. So we created the stub jar containing just what we needed.
+
+If there is a need to change anything in the stub jar, you will need to checkout
+the folder org.eclipse.jem.util/org.eclipse.perfmsr.core.stub. This will then
+be a separate project. You can then make the changes there, and then following the
+README in that project to create and commit the changes.
+
+The jar is in this project's classpath, but it is not exported and is not in
+the plugin.xml or build.properties. This means it will be available for compilation
+but it won't show up in the runtime workbench.
\ No newline at end of file
diff --git "a/plugins/org.eclipse.jem.util/READ_ME_BEFORE_CHANGING_MANIFEST\041\041\041" "b/plugins/org.eclipse.jem.util/READ_ME_BEFORE_CHANGING_MANIFEST\041\041\041"
new file mode 100644
index 0000000..718e94a
--- /dev/null
+++ "b/plugins/org.eclipse.jem.util/READ_ME_BEFORE_CHANGING_MANIFEST\041\041\041"
@@ -0,0 +1,8 @@
+Do not include a new dependency plugin to the MANIFEST for this plugind!!!
+
+The reason for this is that this plugin is also executed outside of Eclipse framework, such IBM Websphere Application Server (c) IBM. We cannot add
+new dependencies to the plugin because the current set is considered to be API. Adding a new set without consulting those users would break
+them.
+
+The external API is anything in the jemutil-nonworkbench folder. If it is only for a class in the other source folder(s) it may be OK since they would not be
+using that code. But it would be best to consult with them first.
\ No newline at end of file
diff --git a/plugins/org.eclipse.jem.util/about.html b/plugins/org.eclipse.jem.util/about.html
new file mode 100644
index 0000000..5acea59
--- /dev/null
+++ b/plugins/org.eclipse.jem.util/about.html
@@ -0,0 +1,25 @@
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN">
+<html><head><title>About</title>
+
+
+
+<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"></head><body lang="EN-US">
+<h2>About This Content</h2>
+
+<P>June, 2008</P>
+<h3>License</h3>
+
+<p>The Eclipse Foundation makes available all content in this plug-in ("Content"). Unless otherwise
+indicated below, the Content is provided to you under the terms and conditions of the
+Eclipse Public License Version 1.0 ("EPL"). A copy of the EPL is 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>If you did not receive this Content directly from the Eclipse Foundation, the Content is
+being redistributed by another party ("Redistributor") and different terms and conditions may
+apply to your use of any object code in the Content. Check the Redistributor's license that was
+provided with the Content. If no such license exists, contact the Redistributor. Unless otherwise
+indicated below, the terms and conditions of the EPL still apply to any source code in the Content
+and such source code may be obtained at <a href="http://www.eclipse.org/">http://www.eclipse.org</a>.</p>
+
+</body></html>
\ No newline at end of file
diff --git a/plugins/org.eclipse.jem.util/build.properties b/plugins/org.eclipse.jem.util/build.properties
new file mode 100644
index 0000000..aa0d851
--- /dev/null
+++ b/plugins/org.eclipse.jem.util/build.properties
@@ -0,0 +1,24 @@
+###############################################################################
+# Copyright (c) 2003, 2005 IBM Corporation 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:
+# IBM Corporation - initial API and implementation
+###############################################################################
+bin.includes = plugin.xml,\
+ .options,\
+ about.html,\
+ plugin.properties,\
+ META-INF/,\
+ .
+src.includes = schema/,\
+ about.html
+output.. = bin/
+source.. = jemutil/,\
+ property_files/,\
+ jemutil-nonworkbnech/
+jars.compile.order = .
+extra.. = ./org.eclipse.perfmsr.core.stub/perfmsr.jar
diff --git a/plugins/org.eclipse.jem.util/jemutil-nonworkbnech/org/eclipse/jem/util/logger/LogEntry.java b/plugins/org.eclipse.jem.util/jemutil-nonworkbnech/org/eclipse/jem/util/logger/LogEntry.java
new file mode 100644
index 0000000..f50bae7
--- /dev/null
+++ b/plugins/org.eclipse.jem.util/jemutil-nonworkbnech/org/eclipse/jem/util/logger/LogEntry.java
@@ -0,0 +1,329 @@
+/*******************************************************************************
+ * Copyright (c) 2005, 2006 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+/*
+
+
+ */
+package org.eclipse.jem.util.logger;
+
+import java.io.ByteArrayOutputStream;
+import java.io.PrintWriter;
+
+/**
+ * This class should be used when logging information which should be grouped together. Instead of creating a new instance of this class every time it
+ * is needed, for performance reasons, create an instance and reuse it.
+ * <p>
+ * Currently the only fields that are logged are the {@link #getText()} and {@link #getTargetException()}.
+ *
+ * @since 1.0.0
+ */
+public class LogEntry {
+
+ private int _executionMap = 0;
+
+ private Throwable _caughtException = null;
+
+ private String _propertiesFileName = null;
+
+ private String localeOfOrigin = null;
+
+ private String sourceIdentifier;
+
+ private String elapsedTime;
+
+ private String text;
+
+ private String messageTypeIdentifier;
+
+ /**
+ * The file name parameter must be a name which can be used by ResourceBundle to load the string from the .properties file. The parameter must not
+ * be null or the empty string.
+ *
+ * @param propertiesFileName
+ *
+ * @since 1.0.0
+ */
+ public LogEntry(String propertiesFileName) {
+ setPropertiesFileName(propertiesFileName);
+ }
+
+ /**
+ * Default Constructor
+ */
+ public LogEntry() {
+ }
+
+ /**
+ * Get execution map
+ *
+ * @return execution map
+ *
+ * @since 1.0.0
+ */
+ public int getExecutionMap() {
+ return _executionMap;
+ }
+
+ /**
+ * Get the properties file name
+ *
+ * @return properties file name or <code>null</code> if not set.
+ *
+ * @since 1.0.0
+ */
+ public String getPropertiesFileName() {
+ return _propertiesFileName;
+ }
+
+ /**
+ * Get target exception
+ *
+ * @return target exception or <code>null</code> if not set.
+ *
+ * @since 1.0.0
+ */
+ public Throwable getTargetException() {
+ return _caughtException;
+ }
+
+ /**
+ * Get locale of origin
+ *
+ * @return locale of origin or <code>null</code> if not set.
+ *
+ * @since 1.0.0
+ */
+ public String getLocaleOfOrigin() {
+ return localeOfOrigin;
+ }
+
+ /**
+ * Get source identifier.
+ *
+ * @return source identifier or <code>null</code> if not set.
+ *
+ * @since 1.0.0
+ */
+ public String getSourceidentifier() {
+ return sourceIdentifier;
+ }
+
+ /**
+ * Get elapsed time
+ *
+ * @return elapsed time
+ *
+ * @since 1.0.0
+ */
+ public String getElapsedTime() {
+ return elapsedTime;
+ }
+
+ /**
+ * Get the message type identifier
+ *
+ * @return message type identifier or <code>null</code> if not set.
+ *
+ * @since 1.0.0
+ */
+ public String getMessageTypeIdentifier() {
+ return messageTypeIdentifier;
+ }
+
+ /**
+ * Set execution map
+ *
+ * @param map
+ *
+ * @since 1.0.0
+ */
+ public void setExecutionMap(int map) {
+ _executionMap = map;
+ }
+
+ /**
+ * Set properties file name
+ *
+ * @param fName
+ *
+ * @since 1.0.0
+ */
+ public void setPropertiesFileName(String fName) {
+ _propertiesFileName = fName;
+ }
+
+ /**
+ * Set target exception
+ *
+ * @param exc
+ *
+ * @since 1.0.0
+ */
+ public void setTargetException(Throwable exc) {
+ _caughtException = exc;
+ }
+
+ /**
+ * Append stacktrace of current stack (at the time of call to this method) to the text buffer.
+ *
+ *
+ * @since 1.0.0
+ */
+ public void appendStackTrace() {
+ // Grab the stack trace from the Thread ...
+ ByteArrayOutputStream byteOutput = new ByteArrayOutputStream();
+ PrintWriter printWriter = new PrintWriter(byteOutput);
+ // Can't call Thread.dumpStack() because it doesn't take a writer as input.
+ // Copy its mechanism instead.
+ new Exception("Stack trace").printStackTrace(printWriter); //$NON-NLS-1$
+ printWriter.flush();
+
+ // and update the text to the LogEntry's text.
+ StringBuffer buffer = new StringBuffer();
+ buffer.append(getText());
+ buffer.append("\n"); //$NON-NLS-1$
+ buffer.append(byteOutput.toString());
+ setText(buffer.toString());
+ }
+
+ /**
+ * Get the text.
+ *
+ * @return text or or <code>null</code> if not set.
+ *
+ * @since 1.0.0
+ */
+ public String getText() {
+ return text;
+ }
+
+ /**
+ * Set the text
+ *
+ * @param string
+ *
+ * @since 1.0.0
+ */
+ public void setText(String string) {
+ text = string;
+ }
+
+ /**
+ * Set every entry to the default value except the properties file name.
+ *
+ *
+ * @since 1.0.0
+ */
+ public void reset() {
+ setExecutionMap(0);
+ setTargetException(null);
+ localeOfOrigin = null;
+ sourceIdentifier = null;
+ elapsedTime = null;
+ setText(null);
+ }
+
+ /**
+ * Set locale of origin.
+ *
+ * @param origin
+ *
+ * @since 1.0.0
+ */
+ public void setLocaleOfOrigin(String origin) {
+ localeOfOrigin = origin;
+ }
+
+ /**
+ * Set source id.
+ *
+ * @param id
+ *
+ * @since 1.0.0
+ */
+ public void setSourceID(String id) {
+ sourceIdentifier = id;
+ }
+
+ /**
+ * Set elapsed time.
+ *
+ * @param time
+ *
+ * @since 1.0.0
+ */
+ public void setElapsedTime(long time) {
+ elapsedTime = String.valueOf(time);
+ }
+
+ /**
+ * Set source identifier.
+ *
+ * @param string
+ *
+ * @since 1.0.0
+ */
+ public void setSourceIdentifier(String string) {
+ setSourceID(string);
+ }
+
+ /**
+ * Set message type identifier.
+ *
+ * @param string
+ *
+ * @since 1.0.0
+ * @deprecated Use {@link #setText(String)} instead and calling it with the result of {@link java.text.MessageFormat#format(java.lang.String, java.lang.Object[])}
+ */
+ public void setMessageTypeIdentifier(String string) {
+ messageTypeIdentifier = string;
+ }
+
+ /**
+ * Set message type id. Same as <code>setMessageTypeIdentifier.</code>
+ * @param string
+ *
+ * @since 1.0.0
+ * @deprecated Use {@link #setText(String)} instead and calling it with the result of {@link java.text.MessageFormat#format(java.lang.String, java.lang.Object[])}
+ */
+ public void setMessageTypeID(String string) {
+ setMessageTypeIdentifier(string);
+ }
+
+ /**
+ * Set tokens. (Currently this is ignored).
+ *
+ * @param strings
+ *
+ * @since 1.0.0
+ * @deprecated Use {@link #setText(String)} instead and calling it with the result of {@link java.text.MessageFormat#format(java.lang.String, java.lang.Object[])}
+ */
+ public void setTokens(String[] strings) {
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see java.lang.Object#toString()
+ */
+ public String toString() {
+ ByteArrayOutputStream byteOutput = new ByteArrayOutputStream();
+ PrintWriter printWriter = new PrintWriter(byteOutput);
+ if (text != null)
+ printWriter.println(text);
+ if (_caughtException != null) {
+ _caughtException.printStackTrace(printWriter);
+ }
+ printWriter.flush();
+ return byteOutput.toString();
+ }
+
+}
diff --git a/plugins/org.eclipse.jem.util/jemutil-nonworkbnech/org/eclipse/jem/util/logger/proxy/ILogRenderer.java b/plugins/org.eclipse.jem.util/jemutil-nonworkbnech/org/eclipse/jem/util/logger/proxy/ILogRenderer.java
new file mode 100644
index 0000000..5d1e951
--- /dev/null
+++ b/plugins/org.eclipse.jem.util/jemutil-nonworkbnech/org/eclipse/jem/util/logger/proxy/ILogRenderer.java
@@ -0,0 +1,72 @@
+/*******************************************************************************
+ * Copyright (c) 2005 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+/*
+
+
+ */
+package org.eclipse.jem.util.logger.proxy;
+
+/**
+ * Basic log renderer interface. It is replaced by the extension <code>ILogRenderer2.</code>
+ *
+ * @since 1.0.0
+ */
+public interface ILogRenderer {
+
+ /**
+ * Logged to console.
+ */
+ final public static String CONSOLE_DESCRIPTION = "console"; //$NON-NLS-1$
+
+ /**
+ * Logged to workbench.
+ */
+ final public static String WORKBENCH_DESCRIPTION = "workbench log"; //$NON-NLS-1$
+
+ /**
+ * Not logged.
+ */
+ final public static String NOLOG_DESCRIPTION = ""; //$NON-NLS-1$
+
+ /**
+ * Log levels. These are deprecated, use <code>java.util.logging.Level</code> codes instead.
+ */
+ final public static int LOG_ERROR = 0;
+
+ final public static int LOG_TRACE = 1;
+
+ final public static int LOG_WARNING = 2;
+
+ final public static int LOG_INFO = 3;
+
+ final public static String DefaultPluginID = "org.eclipse.jem.util"; //$NON-NLS-1$
+
+ /**
+ * Log the string at the specified type.
+ *
+ * @param msg
+ * @param type
+ * @return how it was logged. See <code>CONSOLE_DESCRIPTION.</code>
+ *
+ * @since 1.0.0
+ */
+ public String log(String msg, int type);
+
+ /**
+ * Start or stop the tracing.
+ *
+ * @param Flag
+ * <code>true</code> to start the tracing.
+ *
+ * @since 1.0.0
+ */
+ public void setTraceMode(boolean Flag);
+}
\ No newline at end of file
diff --git a/plugins/org.eclipse.jem.util/jemutil-nonworkbnech/org/eclipse/jem/util/logger/proxy/ILogRenderer2.java b/plugins/org.eclipse.jem.util/jemutil-nonworkbnech/org/eclipse/jem/util/logger/proxy/ILogRenderer2.java
new file mode 100644
index 0000000..f5a670f
--- /dev/null
+++ b/plugins/org.eclipse.jem.util/jemutil-nonworkbnech/org/eclipse/jem/util/logger/proxy/ILogRenderer2.java
@@ -0,0 +1,151 @@
+/*******************************************************************************
+ * Copyright (c) 2004, 2005 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+/*
+
+
+ */
+package org.eclipse.jem.util.logger.proxy;
+
+import java.util.logging.Level;
+
+/**
+ * Log renderer that provides more function. Basically it can handle
+ * the logging of specific types in a different manner than the default
+ * conversion to string supplied by Logger.
+ *
+ * It also uses the Level classes from java.util.logging as the logging levels.
+ *
+ * @since 1.0.0
+ */
+public interface ILogRenderer2 extends ILogRenderer {
+
+ /**
+ * When Logger.setLevel(DEFAULT): restore to what the default level was.
+ * When log(...,DEFAULT): Log at the default level for the type of object.
+ */
+ static final Level DEFAULT = new Logger.LocalLevel("DEFAULT", Integer.MAX_VALUE-1); //$NON-NLS-1$
+
+ /**
+ * When log(...,TRACE) : Log only when in trace mode.
+ * Don't use in Logger.setLevel(). Has no meaning in that case.
+ */
+ static final Level TRACE = new Logger.LocalLevel("TRACE", Integer.MAX_VALUE-2); //$NON-NLS-1$
+
+ /**
+ * Log the throwable at the given level (if DEFAULT, use default level for a throwable).
+ *
+ * @param t
+ * @param level
+ * @return
+ *
+ * @since 1.0.0
+ */
+ String log(Throwable t, Level level);
+
+ /**
+ * Log the object at the given level (if DEFAULT, use default level for an object).
+ *
+ * @param o
+ * @param level
+ * @return
+ *
+ * @since 1.0.0
+ */
+ String log(Object o, Level level);
+
+ /**
+ * Log the boolean at the given level (if DEFAULT, use default level for a boolean).
+ *
+ * @param b
+ * @param level
+ * @return
+ *
+ * @since 1.0.0
+ */
+ String log(boolean b, Level level);
+
+ /**
+ * Log the char at the given level (if DEFAULT, use default level for a char).
+ *
+ * @param c
+ * @param level
+ * @return
+ *
+ * @since 1.0.0
+ */
+ String log(char c, Level level);
+
+ /**
+ * Log the byte at the given level (if DEFAULT, use default level for a byte).
+ *
+ * @param b
+ * @param level
+ * @return
+ *
+ * @since 1.0.0
+ */
+ String log(byte b, Level level);
+
+ /**
+ * Log the short at the given level (if DEFAULT, use default level for a short).
+ *
+ * @param s
+ * @param level
+ * @return
+ *
+ * @since 1.0.0
+ */
+ String log(short s, Level level);
+
+ /**
+ * Log the int at the given level (if DEFAULT, use default level for an int).
+ *
+ * @param i
+ * @param level
+ * @return
+ *
+ * @since 1.0.0
+ */
+ String log(int i, Level level);
+
+ /**
+ * Log the long at the given level (if DEFAULT, use default level for a long).
+ *
+ * @param l
+ * @param level
+ * @return
+ *
+ * @since 1.0.0
+ */
+ String log(long l, Level level);
+
+ /**
+ * Log the float at the given level (if DEFAULT, use default level for a float).
+ *
+ * @param f
+ * @param level
+ * @return
+ *
+ * @since 1.0.0
+ */
+ String log(float f, Level level);
+
+ /**
+ * Log the double at the given level (if DEFAULT, use default level for a double).
+ *
+ * @param d
+ * @param level
+ * @return
+ *
+ * @since 1.0.0
+ */
+ String log(double d, Level level);
+}
diff --git a/plugins/org.eclipse.jem.util/jemutil-nonworkbnech/org/eclipse/jem/util/logger/proxy/JDKConsoleRenderer.java b/plugins/org.eclipse.jem.util/jemutil-nonworkbnech/org/eclipse/jem/util/logger/proxy/JDKConsoleRenderer.java
new file mode 100644
index 0000000..c7c9d75
--- /dev/null
+++ b/plugins/org.eclipse.jem.util/jemutil-nonworkbnech/org/eclipse/jem/util/logger/proxy/JDKConsoleRenderer.java
@@ -0,0 +1,247 @@
+/*******************************************************************************
+ * Copyright (c) 2004, 2005 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+/*
+
+
+ */
+package org.eclipse.jem.util.logger.proxy;
+
+import java.util.logging.Level;
+
+/**
+ * Default log renderer to use when not running under Eclipse. It logs to sysout and syserr.
+ *
+ * @since 1.1.0
+ */
+
+public class JDKConsoleRenderer implements ILogRenderer2 {
+
+ private boolean fTraceMode = false; // will we actually punch trace messaged or not
+
+ private boolean fSettingTrace = false;
+
+ private Logger fMyLogger = null;
+
+ /**
+ * Constructer taking a logger.
+ *
+ * @param logger
+ *
+ * @since 1.1.0
+ */
+ public JDKConsoleRenderer(Logger logger) {
+ super();
+ fMyLogger = logger;
+ fTraceMode = fMyLogger.getTraceMode();
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.eclipse.jem.util.logger.proxy.ILogRenderer#log(java.lang.String, int)
+ */
+ public String log(String msg, int type) {
+
+ if (type == ILogRenderer.LOG_TRACE && !fTraceMode)
+ return null;
+
+ if (type == ILogRenderer.LOG_ERROR)
+ System.err.println(msg);
+ else
+ System.out.println(msg);
+ return ILogRenderer.CONSOLE_DESCRIPTION;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.eclipse.jem.util.logger.proxy.ILogRenderer#setTraceMode(boolean)
+ */
+ public void setTraceMode(boolean flag) {
+
+ if (fSettingTrace)
+ return;
+ fSettingTrace = true;
+ fTraceMode = flag;
+ fMyLogger.setTraceMode(flag);
+ fSettingTrace = false;
+ }
+
+ /**
+ * Log the string at the given level.
+ *
+ * @param msg
+ * @param level
+ * @return <code>CONSOLE_DESCRIPTION</code>
+ *
+ * @since 1.1.0
+ */
+ protected String log(String msg, Level level) {
+ if (level == Level.SEVERE)
+ System.err.println(msg);
+ else
+ System.out.println(msg);
+ return ILogRenderer.CONSOLE_DESCRIPTION;
+ }
+
+ /**
+ * Answer if logging at the given level
+ *
+ * @param logLevel
+ * @return <code>true</code> if logging at the given level.
+ *
+ * @since 1.1.0
+ */
+ protected boolean isLogging(Level logLevel) {
+ return fTraceMode || fMyLogger.isLoggingLevel(logLevel);
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.eclipse.jem.util.logger.proxy.ILogRenderer2#log(boolean, java.util.logging.Level)
+ */
+ public String log(boolean b, Level level) {
+ if (level == DEFAULT)
+ level = Level.FINEST;
+ if (isLogging(level))
+ return log(fMyLogger.getGenericMsg(String.valueOf(b), level), level);
+ else
+ return NOLOG_DESCRIPTION;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.eclipse.jem.util.logger.proxy.ILogRenderer2#log(byte, java.util.logging.Level)
+ */
+ public String log(byte b, Level level) {
+ if (level == DEFAULT)
+ level = Level.FINEST;
+ if (isLogging(level))
+ return log(fMyLogger.getGenericMsg(String.valueOf(b), level), level);
+ else
+ return NOLOG_DESCRIPTION;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.eclipse.jem.util.logger.proxy.ILogRenderer2#log(char, java.util.logging.Level)
+ */
+ public String log(char c, Level level) {
+ if (level == DEFAULT)
+ level = Level.FINEST;
+ if (isLogging(level))
+ return log(fMyLogger.getGenericMsg(String.valueOf(c), level), level);
+ else
+ return NOLOG_DESCRIPTION;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.eclipse.jem.util.logger.proxy.ILogRenderer2#log(double, java.util.logging.Level)
+ */
+ public String log(double d, Level level) {
+ if (level == DEFAULT)
+ level = Level.FINEST;
+ if (isLogging(level))
+ return log(fMyLogger.getGenericMsg(String.valueOf(d), level), level);
+ else
+ return NOLOG_DESCRIPTION;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.eclipse.jem.util.logger.proxy.ILogRenderer2#log(float, java.util.logging.Level)
+ */
+ public String log(float f, Level level) {
+ if (level == DEFAULT)
+ level = Level.FINEST;
+ if (isLogging(level))
+ return log(fMyLogger.getGenericMsg(String.valueOf(f), level), level);
+ else
+ return NOLOG_DESCRIPTION;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.eclipse.jem.util.logger.proxy.ILogRenderer2#log(int, java.util.logging.Level)
+ */
+ public String log(int i, Level level) {
+ if (level == DEFAULT)
+ level = Level.FINEST;
+ if (isLogging(level))
+ return log(fMyLogger.getGenericMsg(String.valueOf(i), level), level);
+ else
+ return NOLOG_DESCRIPTION;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.eclipse.jem.util.logger.proxy.ILogRenderer2#log(long, java.util.logging.Level)
+ */
+ public String log(long l, Level level) {
+ if (level == DEFAULT)
+ level = Level.FINEST;
+ if (isLogging(level))
+ return log(fMyLogger.getGenericMsg(String.valueOf(l), level), level);
+ else
+ return NOLOG_DESCRIPTION;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.eclipse.jem.util.logger.proxy.ILogRenderer2#log(java.lang.Object, java.util.logging.Level)
+ */
+ public String log(Object o, Level level) {
+ if (level == DEFAULT)
+ level = Level.FINEST;
+ if (isLogging(level))
+ return log(fMyLogger.getGenericMsg(String.valueOf(o), level), level);
+ else
+ return NOLOG_DESCRIPTION;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.eclipse.jem.util.logger.proxy.ILogRenderer2#log(short, java.util.logging.Level)
+ */
+ public String log(short s, Level level) {
+ if (level == DEFAULT)
+ level = Level.FINEST;
+ if (isLogging(level))
+ return log(fMyLogger.getGenericMsg(String.valueOf(s), level), level);
+ else
+ return NOLOG_DESCRIPTION;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.eclipse.jem.util.logger.proxy.ILogRenderer2#log(java.lang.Throwable, java.util.logging.Level)
+ */
+ public String log(Throwable t, Level level) {
+ if (level == DEFAULT)
+ level = Level.SEVERE;
+ if (isLogging(level))
+ return log(fMyLogger.getGenericMsg(fMyLogger.exceptionToString(t), level), level);
+ else
+ return NOLOG_DESCRIPTION;
+ }
+
+}
diff --git a/plugins/org.eclipse.jem.util/jemutil-nonworkbnech/org/eclipse/jem/util/logger/proxy/Logger.java b/plugins/org.eclipse.jem.util/jemutil-nonworkbnech/org/eclipse/jem/util/logger/proxy/Logger.java
new file mode 100644
index 0000000..b86ad05
--- /dev/null
+++ b/plugins/org.eclipse.jem.util/jemutil-nonworkbnech/org/eclipse/jem/util/logger/proxy/Logger.java
@@ -0,0 +1,843 @@
+/*******************************************************************************
+ * Copyright (c) 2004, 2006 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+/*
+
+
+ */
+package org.eclipse.jem.util.logger.proxy;
+
+import java.io.PrintWriter;
+import java.io.StringWriter;
+import java.util.*;
+import java.util.logging.Level;
+
+/**
+ * This is a base, UI independent logger. It will
+ * construct a consistent msg. body, and call an enfironment specific ILogRenderer.
+ * By default, this logger will use a console based ILogRenderer,
+ * and a J2EE Plugin identification.
+ *
+ * <p>
+ * When running outside of Eclipse, the trace and logging level come from the system properties
+ * <ul>
+ * <li>"debug" (="true") - The default is <code>false</code>.
+ * <li>"logLevel" (="level" where "level" is a level string, e.g. SEVERE, WARNING, etc. from the <code>java.util.logging.Level</code> class).
+ * The default is "WARNING".
+ * </ul>
+ *
+ *
+ * @since 1.0.0
+ */
+public class Logger {
+
+ // This is used by ILogRenderer2 to define the default level.
+ static class LocalLevel extends Level {
+ /**
+ * Comment for <code>serialVersionUID</code>
+ *
+ * @since 1.1.0
+ */
+ private static final long serialVersionUID = -6273357074767854883L;
+
+ public LocalLevel(String name, int level) {
+ super(name, level);
+ }
+ }
+
+ private boolean fTraceMode = false; // will we actually punch trace messaged or not
+ private String fPluginID;
+ private ILogRenderer fRenderer = null;
+ private ILogRenderer2 renderer2 = null;
+ public String fLineSeperator;
+ private Level level;
+ private Level defaultLevel = Level.SEVERE; // By default only severe or greater are logged.
+ private String logFileName;
+ private final static String DefaultLoggerPlugin = ILogRenderer.DefaultPluginID;
+ static private Hashtable Loggers = new Hashtable(); // Keep track of all the Loggers
+ final protected static String[] LogMark = { "*** ERROR *** ", //$NON-NLS-1$
+ "[Trace] ", //$NON-NLS-1$
+ "+++ Warning +++ ", //$NON-NLS-1$
+ "Info " }; //$NON-NLS-1$
+
+ final protected static String Filler = " "; // Use this to indent msg. body //$NON-NLS-1$
+
+ protected Logger() {
+ this(ILogRenderer.DefaultPluginID);
+ }
+
+ protected Logger(String pluginID) {
+ fPluginID = pluginID;
+ setRenderer(new JDKConsoleRenderer(this)); // Set up default to this. Someone can change it later.
+ }
+
+ /**
+ * Return the stacktrace as a print formatted string.
+ * @param e
+ * @return the stacktrace as a string.
+ *
+ * @since 1.0.0
+ */
+ public String exceptionToString(Throwable e) {
+ StringWriter stringWriter = new StringWriter();
+ e.printStackTrace(new PrintWriter(stringWriter));
+ return stringWriter.toString();
+ }
+
+ /**
+ * Get the system default logger. This is used for clients that don't know if they
+ * are running in Eclipse or outside of it. This way they have a common logger format
+ * which switch correctly.
+ * @return default logger.
+ *
+ * @since 1.0.0
+ */
+ static public Logger getLogger() {
+ Logger defaultLogger = (Logger) Loggers.get(DefaultLoggerPlugin);
+ if (defaultLogger == null) {
+ defaultLogger = new Logger();
+ defaultLogger.init();
+ Loggers.put(DefaultLoggerPlugin, defaultLogger);
+ }
+ return defaultLogger;
+ }
+
+ /**
+ * Get the logger for a specific plugin.
+ * @param pluginId
+ * @return logger for a specific pluggin.
+ *
+ * @since 1.0.0
+ */
+ static public Logger getLogger(String pluginId) {
+ if (pluginId == null)
+ return Logger.getLogger();
+ Logger Logger = (Logger) Loggers.get(pluginId);
+ if (Logger == null) {
+ Logger = new Logger(pluginId);
+ Logger.init();
+ Loggers.put(pluginId, Logger);
+ }
+ return Logger;
+ }
+
+ /**
+ * Used by subclass to get a logger if it exists, but not create one.
+ * @param pluginId
+ * @return logger.
+ *
+ * @since 1.0.0
+ */
+ static protected Logger getLoggerIfExists(String pluginId) {
+ if (pluginId == null)
+ return Logger.getLogger();
+ else
+ return (Logger) Loggers.get(pluginId);
+ }
+
+ /**
+ * Get the plugin id for this logger.
+ * @return pluginid
+ *
+ * @since 1.0.0
+ */
+ public String getPluginID() {
+ return fPluginID;
+ }
+
+ /**
+ * Get the trace mode for this logger
+ * @return <code>true</code> if tracing is going on.
+ *
+ * @since 1.0.0
+ */
+ public boolean getTraceMode() {
+ return fTraceMode;
+ }
+
+ /*
+ * Indent the Msg. Body to make it easier to read the log
+ */
+ private void indentMsg(String msg, StringBuffer logMsg) {
+ // Line seperator is different on different platform, unix = \n, windows \r\n and mac \r
+ String sep = fLineSeperator;
+ if (msg.indexOf("\r\n") != -1) //$NON-NLS-1$
+ sep = "\r\n"; //$NON-NLS-1$
+ else if (msg.indexOf("\n") != -1) //$NON-NLS-1$
+ sep = "\n"; //$NON-NLS-1$
+ else if (msg.indexOf("\r") != -1) //$NON-NLS-1$
+ sep = "\r"; //$NON-NLS-1$
+ StringTokenizer tokenizer = new StringTokenizer(msg, sep);
+ boolean first = true;
+ while (tokenizer.hasMoreTokens()) {
+ if (first) {
+ first = false;
+ logMsg.append(Filler + tokenizer.nextToken());
+ } else
+ logMsg.append(fLineSeperator + Filler + tokenizer.nextToken());
+ }
+ }
+ /*
+ * If Eclipse is started with the -XDebug or -debug turn traces on for this Logger
+ * Creation date: (8/23/2001 7:37:04 PM)
+ */
+ private void init() {
+ if (System.getProperty("debug") != null) //$NON-NLS-1$
+ fTraceMode = true;
+ level = defaultLevel = Level.parse(System.getProperty("logLevel", Level.WARNING.getName())); //$NON-NLS-1$
+
+ try {
+ fLineSeperator = System.getProperty("line.separator"); // Diff on Win/Unix/Mac //$NON-NLS-1$
+ } catch (Exception e) {
+ fLineSeperator = "\n"; //$NON-NLS-1$
+ }
+ }
+ /*
+ * Generic log.
+ * Creation date: (8/24/2001 1:55:34 PM)
+ * @return java.lang.String
+ * @param msg java.lang.String
+ * @param type int
+ */
+ private String logAny(String msg, int type) {
+ StringBuffer logMsg = new StringBuffer();
+ logMsg.append(fLineSeperator);
+ logMsg.append(LogMark[type]);
+ return punchLog(logRest(msg, logMsg), type);
+ }
+
+ /**
+ * This is to be used by renderers that want to put a msg out
+ * in a generic format. This just returns the string that
+ * should be logged. It puts things like headers on it.
+ *
+ * @param msg
+ * @param aLevel
+ * @return The generic message for the string and level.
+ *
+ * @since 1.0.0
+ */
+ public String getGenericMsg(String msg, Level aLevel) {
+ StringBuffer genMsg = new StringBuffer(msg.length()+16);
+ genMsg.append(fLineSeperator);
+ genMsg.append(getLevelHeader(aLevel));
+ genMsg.append(": "); //$NON-NLS-1$
+ genMsg.append(new Date());
+ indentMsg(msg, genMsg);
+ return genMsg.toString();
+ }
+
+ private static final Level[] LEVEL_SEARCH = new Level[] {
+ Level.SEVERE,
+ Level.WARNING,
+ Level.INFO,
+ ILogRenderer2.TRACE
+ };
+
+ private static final String[] LEVEL_MARK = new String[] {
+ "*** ERROR ***", //$NON-NLS-1$
+ "+++ Warning +++", //$NON-NLS-1$
+ "Info", //$NON-NLS-1$
+ "[Trace]" //$NON-NLS-1$
+ };
+
+ private String getLevelHeader(Level aLevel) {
+ for (int i=0; i<LEVEL_SEARCH.length; i++)
+ if (LEVEL_SEARCH[i] == aLevel)
+ return LEVEL_MARK[i];
+ return aLevel.getName(); // Not found, just use level string.
+ }
+
+ // The write's are here for history. Will implement using log(obj, Level) for all of the types.
+
+
+ /**
+ * deprecated use log(Level, Exception)
+ * @param aLevel
+ * @param ex
+ * @return
+ *
+ * @since 1.0.0
+ *
+ */
+ public String write(Level aLevel, Exception ex) {
+ return log(aLevel, ex);
+ }
+
+ /**
+ * deprecated use log(Throwable)
+ * @param ex
+ * @return
+ *
+ * @since 1.0.0
+ *
+ */
+ public String write(Throwable ex) {
+ return log(ex);
+ }
+
+ /**
+ * deprecated use log(Object, Level)
+ * @param aLevel
+ * @param logEntry
+ * @return
+ *
+ * @since 1.0.0
+ */
+ public String write(Level aLevel, Object logEntry) {
+ return log(logEntry, aLevel);
+ }
+
+ /**
+ * deprecated use log(String, Level)
+ * @param aLevel
+ * @param string
+ * @return
+ *
+ * @since 1.0.0
+ */
+ public String write(Level aLevel, String string) {
+ return log(string, aLevel);
+ }
+ /**
+ * deprecated use log(Throwable, Level)
+ * @param aLevel
+ * @param ex
+ * @return
+ *
+ * @since 1.0.0
+ */
+ public String write(Level aLevel, Throwable ex) {
+ return log(ex, aLevel);
+ }
+ /**
+ * deprecated use log(Throwable, Level)
+ * @param aLevel
+ * @param ex
+ * @return
+ *
+ * @since 1.0.0
+ */
+ public String log(Level aLevel, Exception ex) {
+ return log(ex, aLevel);
+ }
+ /**
+ * deprecated use log(Throwable, Level)
+ * @param aLevel
+ * @param ex
+ * @return
+ *
+ * @since 1.0.0
+ */
+ public String log(Level aLevel, Throwable ex) {
+ return log(ex, aLevel);
+ }
+
+ /**
+ * Get the logging level
+ * @return logging level
+ *
+ * @since 1.0.0
+ */
+ public Level getLevel() {
+ return level;
+ }
+
+ /**
+ * Check if the requested level is being logged. (e.g. if current level is SEVERE, then FINE will not be logged).
+ * @param requestlevel
+ * @return <code>true</code> if the level will be logged.
+ *
+ * @since 1.0.0
+ */
+ public boolean isLoggingLevel(Level requestlevel) {
+ if (requestlevel == ILogRenderer2.TRACE && !getTraceMode())
+ return false; // We aren't tracing but requested trace.
+
+ return !(requestlevel.intValue() < getLevel().intValue() || getLevel() == Level.OFF);
+ }
+
+ /**
+ * Log an error string.
+ * @param msg
+ * @return how it was logged. See <code>CONSOLE_DESCRIPTION.</code>
+ *
+ * @since 1.0.0
+ */
+ public String logError(String msg) {
+ return log(msg, Level.SEVERE);
+ }
+
+ /**
+ * Log an error throwable
+ * @param e
+ * @return how it was logged. See <code>CONSOLE_DESCRIPTION.</code>
+ *
+ * @since 1.0.0
+ */
+ public String logError(Throwable e) {
+ return log(e, Level.SEVERE);
+ }
+
+ /**
+ * Log an info message.
+ * @param msg
+ * @return how it was logged. See <code>CONSOLE_DESCRIPTION.</code>
+ *
+ * @since 1.0.0
+ */
+ public String logInfo(String msg) {
+ return log(msg, Level.INFO);
+ }
+
+/**
+ * Log a throwable as a warning.
+ * @param e
+ * @return how it was logged. See <code>CONSOLE_DESCRIPTION.</code>
+ *
+ * @since 1.0.0
+ */
+ public String logInfo(Throwable e) {
+ return log(e, Level.INFO);
+ }
+
+ /**
+ * Append the string to logMsg buffer passed in. Append the date and format the
+ * string with nice indentation.
+ *
+ * @param msg
+ * @param logMsg
+ * @return the string from the logMsg after logging the rest.
+ *
+ * @since 1.0.0
+ */
+ protected String logRest(String msg, StringBuffer logMsg) {
+ logMsg.append(new Date());
+ indentMsg(msg, logMsg);
+ return logMsg.toString();
+ }
+
+ /**
+ * Log the msg as trace only.
+ * @param msg
+ * @return how it was logged. See <code>CONSOLE_DESCRIPTION.</code>
+ *
+ * @since 1.0.0
+ */
+ public String logTrace(String msg) {
+ if (fTraceMode)
+ return log(msg, ILogRenderer2.TRACE);
+ else
+ return ILogRenderer.NOLOG_DESCRIPTION;
+ }
+
+ /**
+ * Log the throwable as trace only.
+ * @param e
+ * @return how it was logged. See <code>CONSOLE_DESCRIPTION.</code>
+ *
+ * @since 1.0.0
+ */
+ public String logTrace(Throwable e) {
+ return log(e, ILogRenderer2.TRACE);
+ }
+
+ /**
+ * Log the message as warning.
+ * @param msg
+ * @return how it was logged. See <code>CONSOLE_DESCRIPTION.</code>
+ *
+ * @since 1.0.0
+ */
+ public String logWarning(String msg) {
+ return log(msg, Level.WARNING);
+ }
+ /**
+ * Log the throwable as a warning.
+ * @param e
+ * @return how it was logged. See <code>CONSOLE_DESCRIPTION.</code>
+ *
+ * @since 1.0.0
+ */
+ public String logWarning(Throwable e) {
+ return log(e, Level.WARNING);
+ }
+
+ /**
+ * Ask the Renderer to punch the msg. in the log.. one
+ * caller at the time
+ * Creation date: (8/24/2001 9:19:17 AM)
+ * @return java.lang.String
+ * @param msg java.lang.String
+ * @param type int
+ */
+ protected synchronized String punchLog(String msg, int type) {
+ return fRenderer.log(msg, type);
+ }
+
+ /**
+ * Set the renderer to use.
+ * @param renderer
+ *
+ * @since 1.0.0
+ */
+ public void setRenderer(ILogRenderer renderer) {
+ fRenderer = renderer;
+ renderer2 = (renderer instanceof ILogRenderer2) ? (ILogRenderer2) renderer : null;
+ renderer.setTraceMode(getTraceMode());
+ }
+
+ /**
+ * Set the trace mode.
+ * @param flag <code>true</code> to turn on tracing.
+ *
+ * @since 1.0.0
+ */
+ public void setTraceMode(boolean flag) {
+ fTraceMode = flag;
+ if (fRenderer != null)
+ fRenderer.setTraceMode(flag);
+ }
+
+ /**
+ * Set the level cutoff for logging. Anything below this level will not log.
+ * Do not set level to <code>ILogRenderer2.TRACE</code>. It doesn't make sense.
+ *
+ * @param level (Use <code>ILogRenderer2.DEFAULT</code> to restore to default for this logger.
+ *
+ * @since 1.0.0
+ */
+ public void setLevel(Level level) {
+ this.level = level != ILogRenderer2.DEFAULT ? level : defaultLevel;
+ }
+
+ /**
+ * Set the default level for this logger. It won't touch the current level.
+ *
+ * @param level
+ *
+ * @since 1.0.0
+ */
+ public void setDefaultLevel(Level level) {
+ this.defaultLevel = level;
+ }
+
+ /**
+ * Get the log file name.
+ * @return Returns the logFileName.
+ */
+ public String getLogFileName() {
+ return logFileName;
+ }
+
+ /**
+ * Set the log file name.
+ * @param logFileName The logFileName to set.
+ */
+ public void setLogFileName(String logFileName) {
+ this.logFileName = logFileName;
+ }
+
+ // Now all of the log() types that use a Level.
+
+ /**
+ * Log the throwable at the default level for a throwable.
+ * @param e
+ * @return how it was logged. See <code>CONSOLE_DESCRIPTION.</code>
+ *
+ * @since 1.0.0
+ */
+ public String log(Throwable e) {
+ return log(e, ILogRenderer2.DEFAULT);
+ }
+
+ /**
+ * Log the throwable at the given level.
+ * @param e
+ * @param logLevel
+ * @return how it was logged. See <code>CONSOLE_DESCRIPTION.</code>
+ *
+ * @since 1.0.0
+ */
+ public String log(Throwable e, Level logLevel) {
+ if (renderer2 != null) {
+ return renderer2.log(e, logLevel);
+ } else {
+ // Do it the old way.
+ String stackTrace = exceptionToString(e);
+ return logAny(stackTrace, getOldType(logLevel != ILogRenderer2.DEFAULT ? level : Level.SEVERE));
+ }
+ }
+
+ public String log(Object o) {
+ return log(o, ILogRenderer2.DEFAULT);
+ }
+
+ /**
+ * Log the object at the given level.
+ * @param o
+ * @param logLevel
+ * @return how it was logged. See <code>CONSOLE_DESCRIPTION.</code>
+ *
+ * @since 1.0.0
+ */
+ public String log(Object o, Level logLevel) {
+ if (renderer2 != null) {
+ return renderer2.log(o, logLevel);
+ } else {
+ // Do it the old way.
+ return logAny(String.valueOf(o), getOldType(logLevel != ILogRenderer2.DEFAULT ? level : Level.FINEST));
+ }
+ }
+
+ // The following are added to match up with Hyades so that primitives can be logged too.
+
+ /**
+ * Log a boolean at the default level.
+ * @param b
+ * @return how it was logged. See <code>CONSOLE_DESCRIPTION.</code>
+ *
+ * @since 1.0.0
+ */
+ public String log(boolean b) {
+ return log(b, ILogRenderer2.DEFAULT);
+ }
+
+ /**
+ * Log a boolean at the given level.
+ * @param b
+ * @param logLevel
+ * @return how it was logged. See <code>CONSOLE_DESCRIPTION.</code>
+ *
+ * @since 1.0.0
+ */
+ public String log(boolean b, Level logLevel) {
+ if (renderer2 != null) {
+ return renderer2.log(b, logLevel);
+ } else {
+ // Do it the old way.
+ return logAny(String.valueOf(b), getOldType(logLevel != ILogRenderer2.DEFAULT ? level : Level.FINEST));
+ }
+ }
+
+ /**
+ * Log the character at the default level.
+ * @param c
+ * @return how it was logged. See <code>CONSOLE_DESCRIPTION.</code>
+ *
+ * @since 1.0.0
+ */
+ public String log(char c) {
+ return log(c, ILogRenderer2.DEFAULT);
+ }
+
+ /**
+ * Log the character at the given level.
+ * @param c
+ * @param logLevel
+ * @return how it was logged. See <code>CONSOLE_DESCRIPTION.</code>
+ *
+ * @since 1.0.0
+ */
+ public String log(char c, Level logLevel) {
+ if (renderer2 != null) {
+ return renderer2.log(c, logLevel);
+ } else {
+ // Do it the old way.
+ return logAny(String.valueOf(c), getOldType(logLevel != ILogRenderer2.DEFAULT ? level : Level.FINEST));
+ }
+ }
+
+ /**
+ * Log the byte at the default level.
+ * @param b
+ * @return how it was logged. See <code>CONSOLE_DESCRIPTION.</code>
+ *
+ * @since 1.0.0
+ */
+ public String log(byte b) {
+ return log(b, ILogRenderer2.DEFAULT);
+ }
+
+ /**
+ * Log the byte at the given level.
+ * @param b
+ * @param logLevel
+ * @return how it was logged. See <code>CONSOLE_DESCRIPTION.</code>
+ *
+ * @since 1.0.0
+ */
+ public String log(byte b, Level logLevel) {
+ if (renderer2 != null) {
+ return renderer2.log(b, logLevel);
+ } else {
+ // Do it the old way.
+ return logAny(String.valueOf(b), getOldType(logLevel != ILogRenderer2.DEFAULT ? level : Level.FINEST));
+ }
+ }
+
+ /**
+ * Log the short at the default level.
+ * @param s
+ * @return how it was logged. See <code>CONSOLE_DESCRIPTION.</code>
+ *
+ * @since 1.0.0
+ */
+ public String log(short s) {
+ return log(s, ILogRenderer2.DEFAULT);
+ }
+
+ /**
+ * Log the short at the given level.
+ * @param s
+ * @param logLevel
+ * @return how it was logged. See <code>CONSOLE_DESCRIPTION.</code>
+ *
+ * @since 1.0.0
+ */
+ public String log(short s, Level logLevel) {
+ if (renderer2 != null) {
+ return renderer2.log(s, logLevel);
+ } else {
+ // Do it the old way.
+ return logAny(String.valueOf(s), getOldType(logLevel != ILogRenderer2.DEFAULT ? level : Level.FINEST));
+ }
+ }
+
+ /**
+ * Log the int at the default level.
+ * @param i
+ * @return how it was logged. See <code>CONSOLE_DESCRIPTION.</code>
+ *
+ * @since 1.0.0
+ */
+ public String log(int i) {
+ return log(i, ILogRenderer2.DEFAULT);
+ }
+
+ /**
+ * Log the int at the default level.
+ * @param i
+ * @param logLevel
+ * @return how it was logged. See <code>CONSOLE_DESCRIPTION.</code>
+ *
+ * @since 1.0.0
+ */
+ public String log(int i, Level logLevel) {
+ if (renderer2 != null) {
+ return renderer2.log(i, logLevel);
+ } else {
+ // Do it the old way.
+ return logAny(String.valueOf(i), getOldType(logLevel != ILogRenderer2.DEFAULT ? level : Level.FINEST));
+ }
+ }
+
+ /**
+ * Log the long at the default level.
+ * @param l
+ * @return how it was logged. See <code>CONSOLE_DESCRIPTION.</code>
+ *
+ * @since 1.0.0
+ */
+ public String log(long l) {
+ return log(l, ILogRenderer2.DEFAULT);
+ }
+
+ /**
+ * Log the long at the given level.
+ * @param l
+ * @param logLevel
+ * @return how it was logged. See <code>CONSOLE_DESCRIPTION.</code>
+ *
+ * @since 1.0.0
+ */
+ public String log(long l, Level logLevel) {
+ if (renderer2 != null) {
+ return renderer2.log(l, logLevel);
+ } else {
+ // Do it the old way.
+ return logAny(String.valueOf(l), getOldType(logLevel != ILogRenderer2.DEFAULT ? level : Level.FINEST));
+ }
+ }
+
+ /**
+ * Log the float at the default level.
+ * @param f
+ * @return how it was logged. See <code>CONSOLE_DESCRIPTION.</code>
+ *
+ * @since 1.0.0
+ */
+ public String log(float f) {
+ return log(f, ILogRenderer2.DEFAULT);
+ }
+
+ /**
+ * Log the float at the given level.
+ * @param f
+ * @param logLevel
+ * @return how it was logged. See <code>CONSOLE_DESCRIPTION.</code>
+ *
+ * @since 1.0.0
+ */
+ public String log(float f, Level logLevel) {
+ if (renderer2 != null) {
+ return renderer2.log(f, logLevel);
+ } else {
+ // Do it the old way.
+ return logAny(String.valueOf(f), getOldType(logLevel != ILogRenderer2.DEFAULT ? level : Level.FINEST));
+ }
+ }
+
+ /**
+ * Log the double at the default level
+ * @param d
+ * @return how it was logged. See <code>CONSOLE_DESCRIPTION.</code>
+ *
+ * @since 1.0.0
+ */
+ public String log(double d) {
+ return log(d, ILogRenderer2.DEFAULT);
+ }
+
+ /**
+ * Log the double at the given level
+ *
+ * @param d
+ * @param logLevel
+ * @return how it was logged. See <code>CONSOLE_DESCRIPTION.</code>
+ *
+ * @since 1.0.0
+ */
+ public String log(double d, Level logLevel) {
+ if (renderer2 != null) {
+ return renderer2.log(d, logLevel);
+ } else {
+ // Do it the old way.
+ return logAny(String.valueOf(d), getOldType(logLevel != ILogRenderer2.DEFAULT ? level : Level.FINEST));
+ }
+ }
+
+ /*
+ * Turn new type into old type. The defaultLevel is the
+ * level to use if the incoming level is marked as default.
+ */
+ private int getOldType(Level aLevel) {
+ if (aLevel == Level.SEVERE)
+ return ILogRenderer.LOG_ERROR;
+ else if (aLevel == Level.WARNING)
+ return ILogRenderer.LOG_WARNING;
+ else if (aLevel == Level.INFO)
+ return ILogRenderer.LOG_INFO;
+ else if (aLevel == ILogRenderer2.TRACE)
+ return ILogRenderer.LOG_TRACE;
+ else
+ return ILogRenderer.LOG_INFO;
+ }
+}
diff --git a/plugins/org.eclipse.jem.util/jemutil/org/eclipse/jem/internal/util/emf/workbench/EMFWorkbenchContextFactory.java b/plugins/org.eclipse.jem.util/jemutil/org/eclipse/jem/internal/util/emf/workbench/EMFWorkbenchContextFactory.java
new file mode 100644
index 0000000..698a435
--- /dev/null
+++ b/plugins/org.eclipse.jem.util/jemutil/org/eclipse/jem/internal/util/emf/workbench/EMFWorkbenchContextFactory.java
@@ -0,0 +1,172 @@
+/*******************************************************************************
+ * Copyright (c) 2005 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+/*
+ * $$RCSfile: EMFWorkbenchContextFactory.java,v $$
+ * $$Revision: 1.4 $$ $$Date: 2005/06/16 20:14:27 $$
+ */
+package org.eclipse.jem.internal.util.emf.workbench;
+
+import java.util.*;
+
+import org.eclipse.core.resources.IProject;
+import org.eclipse.core.resources.IProjectNature;
+import org.eclipse.core.runtime.*;
+import org.eclipse.emf.ecore.resource.ResourceSet;
+
+import org.eclipse.jem.internal.util.emf.workbench.nls.EMFWorkbenchResourceHandler;
+import org.eclipse.jem.util.RegistryReader;
+import org.eclipse.jem.util.emf.workbench.*;
+import org.eclipse.jem.util.emf.workbench.nature.EMFNature;
+import org.eclipse.jem.util.logger.proxy.Logger;
+import org.eclipse.jem.util.plugin.JEMUtilPlugin;
+
+
+
+public class EMFWorkbenchContextFactory {
+ public static final EMFWorkbenchContextFactory INSTANCE;
+
+ static {
+ INSTANCE = createFactoryInstance();
+ }
+ private final Class CONTRIBUTOR_CLASS = IEMFContextContributor.class;
+ protected Map emfContextCache = new WeakHashMap();
+
+
+ private static EMFWorkbenchContextFactory createFactoryInstance() {
+ EMFWorkbenchContextFactory factory = createFactoryInstanceFromExtension();
+ if (factory == null)
+ factory = new EMFWorkbenchContextFactory();
+ return factory;
+ }
+
+ private static EMFWorkbenchContextFactory createFactoryInstanceFromExtension() {
+ final EMFWorkbenchContextFactory[] factoryHolder = new EMFWorkbenchContextFactory[1];
+ RegistryReader reader = new RegistryReader(JEMUtilPlugin.ID, "internalWorkbenchContextFactory") { //$NON-NLS-1$
+ public boolean readElement(IConfigurationElement element) {
+ if (element.getName().equals("factoryClass")) //$NON-NLS-1$
+ try {
+ factoryHolder[0] = (EMFWorkbenchContextFactory)element.createExecutableExtension("name"); //$NON-NLS-1$
+ return true;
+ } catch (CoreException e) {
+ Logger.getLogger().logError(e);
+ }
+ return false;
+ }
+ };
+ reader.readRegistry();
+ return factoryHolder[0];
+ }
+
+ /**
+ * Constructor for EMFNatureFactory.
+ */
+ protected EMFWorkbenchContextFactory() {
+ super();
+
+ }
+
+
+ protected void cacheEMFContext(IProject aProject, EMFWorkbenchContextBase emfContext) {
+ if (aProject != null && emfContext != null)
+ emfContextCache.put(aProject, emfContext);
+ }
+
+ protected EMFWorkbenchContextBase getCachedEMFContext(IProject aProject) {
+ if (aProject != null)
+ return (EMFWorkbenchContextBase) emfContextCache.get(aProject);
+ return null;
+ }
+
+ /**
+ * <code>aProject</code> is either being closed or deleted so we need to cleanup our cache.
+ */
+ public void removeCachedProject(IProject aProject) {
+ if (aProject != null)
+ emfContextCache.remove(aProject);
+
+ }
+ /**
+ * Return a new or existing EMFNature on <code>aProject</code>. Allow the <code>contributor</code>
+ * to contribute to the new or existing nature prior to returning.
+ */
+ public EMFWorkbenchContextBase createEMFContext(IProject aProject, IEMFContextContributor contributor) {
+ if (aProject == null)
+ throw new IllegalStateException("[EMFWorkbenchContextBase]" + EMFWorkbenchResourceHandler.getString("EMFWorkbenchContextFactory_UI_0")); //$NON-NLS-1$ //$NON-NLS-2$
+ if (!aProject.isAccessible())
+ throw new IllegalStateException("[EMFWorkbenchContextBase]" + EMFWorkbenchResourceHandler.getString("EMFWorkbenchContextFactory_UI_1", new Object[]{aProject.getName()})); //$NON-NLS-1$ //$NON-NLS-2$
+ EMFWorkbenchContextBase context = getCachedEMFContext(aProject);
+ boolean contributorFound = false;
+ if (context == null) {
+ context = primCreateEMFContext(aProject);
+ cacheEMFContext(aProject, context);
+ contributorFound = initializeEMFContextFromContributors(aProject, context, contributor);
+ }
+ if (contributor != null && context != null && !contributorFound)
+ contributor.primaryContributeToContext(context);
+ return context;
+ }
+
+ protected boolean initializeEMFContextFromContributors(IProject aProject, EMFWorkbenchContextBase emfContext, IEMFContextContributor contributor) {
+ boolean contributorFound = false;
+ if (aProject == null || emfContext == null)
+ return contributorFound;
+ List runtimes = EMFNature.getRegisteredRuntimes(aProject);
+ for (int i = 0; i < runtimes.size(); i++) {
+ IProjectNature nature = (IProjectNature) runtimes.get(i);
+ if (nature != null && CONTRIBUTOR_CLASS.isInstance(nature)) {
+ if (nature == contributor)
+ contributorFound = true;
+ ((IEMFContextContributor) nature).primaryContributeToContext(emfContext);
+ }
+ }
+ return contributorFound;
+ }
+
+ protected boolean isNatureEnabled(IProject aProject, String natureId) {
+ try {
+ return aProject.isNatureEnabled(natureId);
+ } catch (CoreException e) {
+ return false;
+ }
+ }
+
+ protected String[] getNatureIds(IProject aProject) {
+ try {
+ if (aProject.isAccessible())
+ return aProject.getDescription().getNatureIds();
+ } catch (CoreException e) {
+ }
+ return null;
+ }
+
+ protected IProjectNature getNature(IProject aProject, String natureId) {
+ try {
+ return aProject.getNature(natureId);
+ } catch (CoreException e) {
+ return null;
+ }
+ }
+
+ protected EMFWorkbenchContextBase primCreateEMFContext(IProject aProject) {
+ return new EMFWorkbenchContextBase(aProject);
+ }
+ /**
+ * Return an existing EMFNature on <code>aProject</code>.
+ */
+ public EMFWorkbenchContextBase getEMFContext(IProject aProject) {
+ return getCachedEMFContext(aProject);
+ }
+
+ public ResourceSetWorkbenchSynchronizer createSynchronizer(ResourceSet aResourceSet, IProject aProject) {
+ return new ResourceSetWorkbenchSynchronizer(aResourceSet, aProject);
+ }
+
+}
diff --git a/plugins/org.eclipse.jem.util/jemutil/org/eclipse/jem/internal/util/emf/workbench/ProjectResourceSetImpl.java b/plugins/org.eclipse.jem.util/jemutil/org/eclipse/jem/internal/util/emf/workbench/ProjectResourceSetImpl.java
new file mode 100644
index 0000000..d6473fc
--- /dev/null
+++ b/plugins/org.eclipse.jem.util/jemutil/org/eclipse/jem/internal/util/emf/workbench/ProjectResourceSetImpl.java
@@ -0,0 +1,784 @@
+/*******************************************************************************
+ * Copyright (c) 2005 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+/*
+ * $$RCSfile: ProjectResourceSetImpl.java,v $$
+ * $$Revision: 1.21.2.1 $$ $$Date: 2009/05/14 00:17:56 $$
+ */
+package org.eclipse.jem.internal.util.emf.workbench;
+
+import java.io.IOException;
+import java.util.*;
+
+import org.eclipse.core.resources.*;
+import org.eclipse.core.runtime.*;
+import org.eclipse.core.runtime.content.IContentDescription;
+import org.eclipse.emf.common.notify.Notification;
+import org.eclipse.emf.common.notify.impl.NotificationImpl;
+import org.eclipse.emf.common.util.EList;
+import org.eclipse.emf.common.util.URI;
+import org.eclipse.emf.ecore.EObject;
+import org.eclipse.emf.ecore.resource.*;
+import org.eclipse.emf.ecore.resource.Resource.Factory;
+import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl;
+import org.eclipse.emf.ecore.resource.impl.URIConverterImpl;
+import org.eclipse.emf.ecore.xmi.XMLResource;
+
+import org.eclipse.jem.util.emf.workbench.*;
+import org.eclipse.jem.util.emf.workbench.nature.EMFNature;
+import org.eclipse.jem.util.logger.proxy.Logger;
+import org.eclipse.jem.util.plugin.JEMUtilPlugin;
+
+public class ProjectResourceSetImpl extends ResourceSetImpl implements FlexibleProjectResourceSet {
+ public static interface ModuleURI {
+ public static final int SUB_PROTOCOL_INDX = 0;
+ public static final int PROJECT_NAME_INDX = 1;
+ public static final int MODULE_NAME_INDX = 2;
+ public static final int CONTENT_TYPE_INDX = 3;
+ }
+
+ public class SynchronizedResourcesEList<E extends Object & Resource> extends ResourcesEList<E> implements EList<E> {
+
+ /**
+ *
+ */
+ private static final long serialVersionUID = 1L;
+ private final Object lock = new Object();
+
+ public void move(int newPosition, E object) {
+
+ synchronized(lock) {
+ super.move(newPosition, object);
+ }
+
+ }
+
+ public E move(int newPosition, int oldPosition) {
+
+ synchronized(lock) {
+ return super.move(newPosition, oldPosition);
+ }
+ }
+
+ public boolean add(E o) {
+
+ synchronized(lock) {
+ return super.add(o);
+ }
+ }
+
+ public void add(int index, E element) {
+
+ synchronized(lock) {
+ super.add(index, element);
+ }
+
+ }
+
+ public boolean addAll(Collection<? extends E> c) {
+
+ synchronized(lock) {
+ return super.addAll(c);
+ }
+ }
+
+ public boolean addAll(int index, Collection<? extends E> c) {
+
+ synchronized(lock) {
+ return super.addAll(index, c);
+ }
+ }
+
+ public void clear() {
+
+ synchronized(lock) {
+ super.clear();
+ }
+
+ }
+
+ public boolean contains(Object o) {
+
+ synchronized(lock) {
+ return super.contains(o);
+ }
+ }
+
+ public boolean containsAll(Collection<?> c) {
+
+ synchronized(lock) {
+ return super.containsAll(c);
+ }
+ }
+
+ public boolean equals(Object o) {
+
+ synchronized(lock) {
+ return super.equals(o);
+ }
+ }
+
+ public E get(int index) {
+
+ synchronized(lock) {
+ return super.get(index);
+ }
+ }
+
+ public int hashCode() {
+
+ synchronized(lock) {
+ return super.hashCode();
+ }
+ }
+
+ public int indexOf(Object o) {
+
+ synchronized(lock) {
+ return super.indexOf(o);
+ }
+ }
+
+ public boolean isEmpty() {
+
+ synchronized(lock) {
+ return super.isEmpty();
+ }
+ }
+
+ public Iterator<E> iterator() {
+
+ synchronized(lock) {
+ return super.iterator();
+ }
+ }
+
+ public int lastIndexOf(Object o) {
+
+ synchronized(lock) {
+ return super.lastIndexOf(o);
+ }
+ }
+
+ public ListIterator<E> listIterator() {
+
+ synchronized(lock) {
+ return super.listIterator();
+ }
+ }
+
+ public ListIterator<E> listIterator(int index) {
+
+ synchronized(lock) {
+ return super.listIterator(index);
+ }
+ }
+
+ public boolean remove(Object o) {
+
+ synchronized(lock) {
+ return super.remove(o);
+ }
+ }
+
+ public E remove(int index) {
+
+ synchronized(lock) {
+ return super.remove(index);
+ }
+ }
+
+ public boolean removeAll(Collection<?> c) {
+
+ synchronized(lock) {
+ return super.removeAll(c);
+ }
+ }
+
+ public boolean retainAll(Collection<?> c) {
+
+ synchronized(lock) {
+ return super.retainAll(c);
+ }
+ }
+
+ public E set(int index, E element) {
+
+ synchronized(lock) {
+ return super.set(index, element);
+ }
+ }
+
+ public int size() {
+
+ synchronized(lock) {
+ return super.size();
+ }
+ }
+
+ public List<E> subList(int fromIndex, int toIndex) {
+
+ synchronized(lock) {
+ return super.subList(fromIndex, toIndex);
+ }
+ }
+
+ public Object[] toArray() {
+
+ synchronized(lock) {
+ return super.toArray();
+ }
+ }
+
+ public <T> T[] toArray(T[] a) {
+
+ synchronized(lock) {
+ return super.toArray(a);
+ }
+ }
+
+ }
+
+ private boolean isReleasing = false;
+ private IProject project;
+ protected List resourceHandlers = new ArrayList();
+ protected ResourceSetWorkbenchSynchronizer synchronizer;
+ protected ProjectResourceSetImpl() {
+ setURIResourceMap(new HashMap(10)); // Tell it to cache uri->resource access.
+ getLoadOptions().put(XMLResource.OPTION_USE_PARSER_POOL, EMFNature.SHARED_PARSER_POOL);
+ }
+ public ProjectResourceSetImpl(IProject aProject) {
+ this();
+ setProject(aProject);
+ initializeSharedCacheListener();
+ }
+ protected void initializeSharedCacheListener() {
+ JEMUtilPlugin.getSharedCache().beginListening(this);
+ }
+ protected boolean isReleasing() {
+ return isReleasing;
+ }
+ /**
+ * @see org.eclipse.emf.ecore.resource.impl.ResourceSetImpl#delegatedGetResource(URI, boolean)
+ */
+ protected Resource delegatedGetResource(URI uri, boolean loadOnDemand) {
+ Resource res = super.delegatedGetResource(uri, loadOnDemand);
+ if (res == null)
+ res = getResourceFromHandlers(uri);
+ return res;
+ }
+
+ public Resource createResource(URI uri, String contentType) {
+ if (isReleasing) return null;
+ //Check the map first when creating the resource and do not
+ //normalize if a value is found.
+ boolean isMapped = detectURIMapping(uri);
+ boolean hasContentType = (getContentTypeName(uri) != null);
+ URI converted = uri;
+ if (!isMapped)
+ converted = getURIConverter().normalize(uri);
+ else if (hasContentType)
+ converted = getURIConverter().normalize(uri);
+
+ Resource result = createResourceFromHandlers(converted);
+ if (result == null) {
+ Resource.Factory resourceFactory = getResourceFactoryRegistry().getFactory(uri);
+ if (resourceFactory != null)
+ {//We got the right factory, now use the right URI
+ result = resourceFactory.createResource(converted);
+ getResources().add(result);
+ }
+ }
+
+
+ return result;
+ }
+
+ public Resource createResource(URI uri) {
+ return createResource(uri, ContentHandler.UNSPECIFIED_CONTENT_TYPE);
+ }
+
+ private boolean detectURIMapping(URI uri) {
+ if (uri == null) return false;
+ return !(((URIConverterImpl.URIMap)getURIConverter().getURIMap()).getURI(uri).equals(uri));
+ }
+ /**
+ * Return the IFile for the <code>uri</code> within the Workspace. This URI is assumed to be
+ * absolute in the following format: platform:/resource/....
+ */
+ private IFile getPlatformFile(URI uri) {
+ if (WorkbenchResourceHelperBase.isPlatformResourceURI(uri)) {
+ String fileString = URI.decode(uri.path());
+ fileString = fileString.substring(JEMUtilPlugin.PLATFORM_RESOURCE.length() + 1);
+ return ResourcesPlugin.getWorkspace().getRoot().getFile(new Path(fileString));
+ }
+ return null;
+ }
+ public Resource createResource(URI uri, Resource.Factory resourceFactory) {
+ if (isReleasing) return null;
+ //Check the map first when creating the resource and do not
+ //normalize if a value is found.
+ boolean isMapped = detectURIMapping(uri);
+ boolean hasContentType = (getContentTypeName(uri) != null);
+ URI converted = uri;
+ if (!isMapped)
+ converted = getURIConverter().normalize(uri);
+ else if (hasContentType)
+ converted = getURIConverter().normalize(uri);
+ Resource result = createResourceFromHandlers(converted);
+ if (result == null) {
+
+ if (resourceFactory != null)
+ {
+ result = resourceFactory.createResource(converted);
+ getResources().add(result);
+ getURIResourceMap().put(uri, result);
+ return result;
+ }
+ else
+ {
+ return null;
+ }
+
+ }
+ return result;
+ }
+ /**
+ * @see org.eclipse.emf.ecore.resource.impl.ResourceSetImpl#demandLoad(Resource)
+ */
+ protected void demandLoad(Resource resource) throws IOException {
+ if (!isReleasing)
+ super.demandLoad(resource);
+ }
+
+ /**
+ * See if any resource handlers from the WorkbenchContext
+ * decide to create the Resource in another manner.
+ */
+ protected Resource createResourceFromHandlers(URI uri) {
+ Resource resource = null;
+ ResourceHandler handler = null;
+ for (int i = 0; i < resourceHandlers.size(); i++) {
+ handler = (ResourceHandler) resourceHandlers.get(i);
+ resource = handler.createResource(this, uri);
+ if (resource != null)
+ return resource;
+ }
+ return null;
+ }
+ /**
+ * See if any resource handlers from the WorkbenchContext
+ * can return a Resource from a <code>uri</code>.
+ */
+ protected Resource getResourceFromHandlers(URI uri) {
+ if (isReleasing) return null;
+ for (int i = 0; i < resourceHandlers.size(); i++) {
+ Resource resource = ((ResourceHandler) resourceHandlers.get(i)).getResource(this, uri);
+ if (resource != null)
+ return resource;
+ }
+ return null;
+ }
+
+ public void release() {
+ // Send out notification of release.
+ if (eNotificationRequired()) {
+ eNotify(new NotificationImpl(SPECIAL_NOTIFICATION_TYPE, null, null, Notification.NO_INDEX, false) {
+ /* (non-Javadoc)
+ * @see org.eclipse.emf.common.notify.impl.NotificationImpl#getFeatureID(java.lang.Class)
+ */
+ public int getFeatureID(Class expectedClass) {
+ return PROJECTRESOURCESET_ABOUT_TO_RELEASE_ID;
+ }
+
+ /* (non-Javadoc)
+ * @see org.eclipse.emf.common.notify.impl.NotificationImpl#getNotifier()
+ */
+ public Object getNotifier() {
+ return ProjectResourceSetImpl.this;
+ }
+ });
+ }
+ setIsReleasing(true);
+ if (synchronizer != null)
+ synchronizer.dispose();
+ synchronizer = null;
+ removeAndUnloadAllResources();
+ resourceHandlers = null;
+ eAdapters().clear();
+ setProject(null);
+ JEMUtilPlugin.getSharedCache().stopListening(this);
+ }
+ protected void removeAndUnloadAllResources() {
+ boolean caughtException = false;
+ if (getResources().isEmpty()) return;
+ List list = new ArrayList(getResources());
+ getResources().clear();
+ Resource res;
+ int size = list.size();
+ for (int i = 0; i < size; i++) {
+ res = (Resource) list.get(i);
+ try {
+ res.unload();
+ } catch (RuntimeException ex) {
+ Logger.getLogger().logError(ex);
+ caughtException = true;
+ }
+ }
+ if (caughtException)
+ throw new RuntimeException("Exception(s) unloading resources - check log files"); //$NON-NLS-1$
+ }
+ protected void setIsReleasing(boolean aBoolean) {
+ isReleasing = aBoolean;
+ }
+ /**
+ * Gets the project.
+ * @return Returns a IProject
+ */
+ public IProject getProject() {
+ return project;
+ }
+ /**
+ * Sets the project.
+ * @param project The project to set
+ */
+ protected void setProject(IProject project) {
+ this.project = project;
+ }
+ /*
+ * Javadoc copied from interface.
+ */
+ public EObject getEObject(URI uri, boolean loadOnDemand) {
+ if (isReleasing) return null;
+ Resource resource = getResource(uri.trimFragment(), loadOnDemand);
+ EObject result = null;
+ if (resource != null && resource.isLoaded())
+ result = resource.getEObject(uri.fragment());
+ if (result == null)
+ result = getEObjectFromHandlers(uri, loadOnDemand);
+ return result;
+ }
+ /**
+ * See if any resource handlers from the WorkbenchContext
+ * can return a EObject from a <code>uri</code> after
+ * failing to find it using the normal mechanisms.
+ */
+ protected EObject getEObjectFromHandlers(URI uri, boolean loadOnDemand) {
+ EObject obj = null;
+ ResourceHandler handler = null;
+ for (int i = 0; i < resourceHandlers.size(); i++) {
+ handler = (ResourceHandler) resourceHandlers.get(i);
+ obj = handler.getEObjectFailed(this, uri, loadOnDemand);
+ if (obj != null)
+ return obj;
+ }
+ return null;
+ }
+
+ public boolean add(ResourceHandler resourceHandler) {
+ return resourceHandlers.add(resourceHandler);
+ }
+ public void addFirst(ResourceHandler resourceHandler) {
+ resourceHandlers.add(0, resourceHandler);
+ }
+ public boolean remove(ResourceHandler resourceHandler) {
+ return resourceHandlers.remove(resourceHandler);
+ }
+ /**
+ * Returns the synchronizer.
+ * @return ResourceSetWorkbenchSynchronizer
+ */
+ public ResourceSetWorkbenchSynchronizer getSynchronizer() {
+ return synchronizer;
+ }
+ /**
+ * Sets the synchronizer.
+ * @param synchronizer The synchronizer to set
+ */
+ public void setSynchronizer(ResourceSetWorkbenchSynchronizer synchronizer) {
+ this.synchronizer = synchronizer;
+ }
+ /**
+ * @see org.eclipse.emf.ecore.resource.ResourceSet#setResourceFactoryRegistry(Resource.Factory.Registry)
+ */
+ public void setResourceFactoryRegistry(Resource.Factory.Registry factoryReg) {
+ if (resourceFactoryRegistry != null && factoryReg != null) {
+ preserveEntries(factoryReg.getExtensionToFactoryMap(), resourceFactoryRegistry.getExtensionToFactoryMap());
+ preserveEntries(factoryReg.getProtocolToFactoryMap(), resourceFactoryRegistry.getProtocolToFactoryMap());
+ }
+ super.setResourceFactoryRegistry(factoryReg);
+ }
+ /*
+ * Preserve the entries from map2 in map1 if no collision.
+ */
+ protected void preserveEntries(Map map1, Map map2) {
+ if (map2.isEmpty())
+ return;
+ Iterator it = map2.entrySet().iterator();
+ Map.Entry entry;
+ while (it.hasNext()) {
+ entry = (Map.Entry) it.next();
+ if (!map1.containsKey(entry.getKey()))
+ map1.put(entry.getKey(), entry.getValue());
+ }
+ }
+ /*
+ * Javadoc copied from interface.
+ */
+ public Resource getResource(URI uri, boolean loadOnDemand) {
+ if (isReleasing) return null;
+
+ Map<URI, Resource> map = getURIResourceMap();
+ if (map != null)
+ {
+ Resource resource = map.get(uri);
+ if (resource != null)
+ {
+ if (loadOnDemand && !resource.isLoaded())
+ {
+ demandLoadHelper(resource);
+ }
+ return resource;
+ }
+ }
+
+ URIConverter theURIConverter = getURIConverter();
+ URI normalizedURI = theURIConverter.normalize(uri);
+ List resourcesToRemove = new ArrayList();
+ for (Resource resource : getResources())
+ {
+ if (theURIConverter.normalize(resource.getURI()).equals(normalizedURI)) {
+
+ if (getContentTypeName(uri) == null) { // loading from legacy archive api or non-typed resource
+ if (loadOnDemand && !resource.isLoaded())
+ {
+ demandLoadHelper(resource);
+ }
+
+ if (map != null)
+ {
+ map.put(uri, resource);
+ }
+ return resource;
+ } else {// content type is known
+ boolean resourceExists = false;
+ IFile file = getPlatformFile(resource);
+ if (file != null)
+ resourceExists = file.exists();
+ String resourceContentTypeID = getContentTypeID(resource);
+ String uriContentTypeID = getContentTypeName(uri);
+ String existingMapKeyType = (findKey(resource) != null) ? getContentTypeName(findKey(resource)) : null;
+ if((!map.containsValue(resource) || ((map.get(uri) != null) && map.get(uri).equals(resource))) // existing resource with alternate mapping doesn't exist in map
+ || ((resourceContentTypeID != null && resourceContentTypeID.equals(uriContentTypeID)))) {
+ if (loadOnDemand && !resource.isLoaded()) {
+ demandLoadHelper(resource);
+ } // if embedded uri content type is different than resource content type, continue searching
+ if (resourceContentTypeID != null
+ && uriContentTypeID != null) {
+ if ((resourceContentTypeID.equals(uriContentTypeID)) && existingMapKeyType == null) continue;
+ if ((!resourceContentTypeID.equals(uriContentTypeID)) || (existingMapKeyType != null && !existingMapKeyType
+ .equals(uriContentTypeID)))
+ continue;
+ else if (existingMapKeyType == null && !resourceExists) {
+ resourcesToRemove.add(resource);
+ continue;
+ }
+ } else if (uriContentTypeID != null && resourceContentTypeID == null && !resourceExists) {
+ resourcesToRemove.add(resource);
+ continue;
+ }
+
+ if (map != null && (map.get(uri) == null)) {
+ map.put(uri, resource);
+ }
+ return resource;
+ }
+ }
+ }
+ }
+ // Cleanup invalid resources
+ getResources().removeAll(resourcesToRemove);
+ Resource delegatedResource = delegatedGetResource(uri, loadOnDemand);
+ if (delegatedResource != null)
+ {
+ if (map != null)
+ {
+ map.put(uri, delegatedResource);
+ }
+ return delegatedResource;
+ }
+
+ if (loadOnDemand)
+ {
+ Resource resource = demandCreateResource(uri);
+ if (resource == null)
+ {
+ throw new RuntimeException("Cannot create a resource for '" + uri + "'; a registered resource factory is needed");
+ }
+
+ if (map != null)
+ {
+ map.put(uri, resource);
+ }
+
+ demandLoadHelper(resource);
+
+
+ return resource;
+ }
+
+ return null;
+
+ }
+ private IFile getPlatformFile(Resource res) {
+ IFile file = null;
+ file = getPlatformFile(res.getURI());
+ if (file == null) {
+ if (res.getResourceSet() != null) {
+ URIConverter converter = res.getResourceSet().getURIConverter();
+ URI convertedUri = converter.normalize(res.getURI());
+ if (!res.getURI().equals(convertedUri))
+ file = getPlatformFile(convertedUri);
+ }
+ }
+ return file;
+ }
+
+ private String getContentTypeID(Resource resource) {
+ IFile file = getPlatformFile(resource);
+ IContentDescription desc = null;
+ try {
+ desc = file.getContentDescription();
+ } catch (CoreException e) {
+ }
+ if (desc != null && desc.getContentType() != null)
+ return desc.getContentType().getId();
+ return null;
+ }
+ private URI findKey(Resource resource) {
+ Map aMap = getURIResourceMap();
+ Set keys = aMap.keySet();
+ for (Iterator iterator = keys.iterator(); iterator.hasNext();) {
+ URI name = (URI) iterator.next();
+ if (aMap.get(name).equals(resource))
+ return name;
+ }
+ return null;
+ }
+ protected static String getContentTypeName(URI uri) {
+
+ if (WorkbenchResourceHelperBase.isPlatformResourceURI(uri) || !isValidFullyQualifiedModuleURI(uri))
+ return null;
+ String contentTypeIdentifier = (uri.segmentCount() > 3 ? uri.segment(ModuleURI.CONTENT_TYPE_INDX) : null);
+ if (contentTypeIdentifier != null && Platform.getContentTypeManager().getContentType(uri.segment(ModuleURI.CONTENT_TYPE_INDX)) != null)
+ return contentTypeIdentifier;
+ else
+ return null;
+ }
+ public static boolean isValidFullyQualifiedModuleURI(URI aModuleURI) {
+ if (aModuleURI.segmentCount() < 3) {
+ return false;
+ }
+ return true;
+ }
+ /*
+ * Javadoc copied from interface.
+ */
+ public Resource getResource(URI uri, boolean loadOnDemand, Resource.Factory resourceFactory) {
+ if (isReleasing) return null;
+
+
+ Map<URI, Resource> map = getURIResourceMap();
+ if (map != null)
+ {
+ Resource resource = map.get(uri);
+ if (resource != null)
+ {
+ if (loadOnDemand && !resource.isLoaded())
+ {
+ demandLoadHelper(resource);
+ }
+ return resource;
+ }
+ }
+
+ URIConverter theURIConverter = getURIConverter();
+ URI normalizedURI = theURIConverter.normalize(uri);
+ for (Resource resource : getResources())
+ {
+ if (theURIConverter.normalize(resource.getURI()).equals(normalizedURI))
+ {
+ if (loadOnDemand && !resource.isLoaded())
+ {
+ demandLoadHelper(resource);
+ }
+
+ if (map != null)
+ {
+ map.put(uri, resource);
+ }
+ return resource;
+ }
+ }
+
+ Resource delegatedResource = delegatedGetResource(uri, loadOnDemand);
+ if (delegatedResource != null)
+ {
+ if (map != null)
+ {
+ map.put(uri, delegatedResource);
+ }
+ return delegatedResource;
+ }
+
+ if (loadOnDemand)
+ {
+ Resource resource = demandCreateResource(uri,resourceFactory);
+ if (resource == null)
+ {
+ throw new RuntimeException("Cannot create a resource for '" + uri + "'; a registered resource factory is needed");
+ }
+
+ demandLoadHelper(resource);
+
+ if (map != null)
+ {
+ map.put(uri, resource);
+ }
+ return resource;
+ }
+
+ return null;
+
+ }
+
+
+ /* (non-Javadoc)
+ * @see org.eclipse.jem.util.emf.workbench.ProjectResourceSet#resetNormalizedURICache()
+ */
+ public void resetNormalizedURICache() {
+ if (getURIResourceMap() != null)
+ getURIResourceMap().clear();
+ }
+
+ protected Resource demandCreateResource(URI uri, Factory resourceFactory) {
+ // TODO Auto-generated method stub
+ return createResource(uri,resourceFactory);
+ }
+
+ public EList<Resource> getResources() {
+ if (resources == null)
+ {
+ resources = new SynchronizedResourcesEList<Resource>();
+ }
+ return resources;
+ }
+
+}
diff --git a/plugins/org.eclipse.jem.util/jemutil/org/eclipse/jem/internal/util/emf/workbench/WorkspaceResourceHandler.java b/plugins/org.eclipse.jem.util/jemutil/org/eclipse/jem/internal/util/emf/workbench/WorkspaceResourceHandler.java
new file mode 100644
index 0000000..9234123
--- /dev/null
+++ b/plugins/org.eclipse.jem.util/jemutil/org/eclipse/jem/internal/util/emf/workbench/WorkspaceResourceHandler.java
@@ -0,0 +1,147 @@
+/*******************************************************************************
+ * Copyright (c) 2005 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+/*
+ * $$RCSfile: WorkspaceResourceHandler.java,v $$
+ * $$Revision: 1.2 $$ $$Date: 2005/02/15 23:04:14 $$
+ */
+package org.eclipse.jem.internal.util.emf.workbench;
+
+import org.eclipse.core.resources.*;
+import org.eclipse.emf.common.util.URI;
+import org.eclipse.emf.ecore.EObject;
+import org.eclipse.emf.ecore.resource.Resource;
+import org.eclipse.emf.ecore.resource.ResourceSet;
+import org.eclipse.emf.ecore.resource.impl.URIConverterImpl;
+
+import org.eclipse.jem.util.emf.workbench.ResourceHandler;
+import org.eclipse.jem.util.emf.workbench.WorkbenchResourceHelperBase;
+import org.eclipse.jem.util.plugin.JEMUtilPlugin;
+
+/**
+ * The main purpose of this class is to redirect, if necessary, to another
+ * ResourceSet. This class should be used in conjunction with the WorkbenchURIConverter
+ * so that the URIs passed will use the platform protocol. Anything else will be considered
+ * to be ambiguous and we will not be able to redirect.
+ */
+public class WorkspaceResourceHandler implements ResourceHandler {
+ /**
+ * Constructor for WorkspaceResourceHandler.
+ */
+ public WorkspaceResourceHandler() {
+ super();
+ }
+ /*
+ * @see IResourceHandler#getResource(ResourceSet, URI)
+ */
+ public Resource getResource(ResourceSet originatingResourceSet, URI uri) {
+ if (WorkbenchResourceHelperBase.isPlatformResourceURI(uri))
+ return getResourceForPlatformProtocol(originatingResourceSet, uri);
+ URI mappedURI = ((URIConverterImpl.URIMap)originatingResourceSet.getURIConverter().getURIMap()).getURI(uri);
+ if (isGlobalPluginLoad(mappedURI))
+ return getResourceForPlatformPluginProtocol(originatingResourceSet, uri);
+ return null;
+ }
+ /**
+ * Redirect to the correct project based on the project name in the <code>uri</code>.
+ * The <code>uri</code> will be in the following format: platform:/resource/[project name].
+ */
+ protected Resource createResourceForPlatformProtocol(ResourceSet originatingResourceSet, URI uri) {
+ String projectName = uri.segment(1);
+ IProject project = getProject(projectName);
+ if (project != null && project.isAccessible()) {
+ ResourceSet set = WorkbenchResourceHelperBase.getResourceSet(project);
+ if (originatingResourceSet != set)
+ return createResource(uri, set);
+ }
+ return null;
+ }
+ /**
+ * Redirect to the correct project based on the project name in the <code>uri</code>.
+ * The <code>uri</code> will be in the following format: platform:/resource/[project name].
+ */
+ protected Resource createResourceForPlatformPluginProtocol(ResourceSet originatingResourceSet, URI uri) {
+
+ ResourceSet set = JEMUtilPlugin.getPluginResourceSet();
+ return createResource(uri, set);
+ }
+ protected Resource createResource(URI uri, ResourceSet redirectedResourceSet) {
+ return redirectedResourceSet.createResource(uri);
+ }
+ /**
+ * Redirect to the correct project based on the first segment in the file name.
+ * This is for compatability purposes for people using the platform:/resource protocol.
+ */
+ protected Resource getResourceForPlatformProtocol(ResourceSet originatingResourceSet, URI uri) {
+ String projectName = uri.segment(1);
+ IProject project = getProject(projectName);
+ if (project != null && project.isAccessible()) {
+ ResourceSet set = WorkbenchResourceHelperBase.getResourceSet(project);
+ if (originatingResourceSet != set)
+ return getResource(uri, set);
+ }
+ return null;
+ }
+ /**
+ * Redirect to the correct project based on the first segment in the file name.
+ * This is for compatability purposes for people using the platform:/resource protocol.
+ */
+ protected Resource getResourceForPlatformPluginProtocol(ResourceSet originatingResourceSet, URI uri) {
+
+ ResourceSet set = JEMUtilPlugin.getPluginResourceSet();
+ return getResource(uri, set);
+
+ }
+ protected Resource getResource(URI uri, ResourceSet redirectedResourceSet) {
+ return redirectedResourceSet.getResource(uri, false);
+ }
+
+ protected IWorkspace getWorkspace() {
+ return ResourcesPlugin.getWorkspace();
+ }
+ protected IProject getProject(String projectName) {
+ IWorkspace ws = getWorkspace();
+ if (ws == null)
+ return null;
+ return ws.getRoot().getProject(projectName);
+ }
+ protected IProject getProject(ResourceSet resourceSet) {
+ return WorkbenchResourceHelperBase.getProject(resourceSet);
+ }
+ /**
+ * @see org.eclipse.jem.util.ResourceHandler#createResource(ResourceSet, URI)
+ */
+ public Resource createResource(ResourceSet originatingResourceSet, URI uri) {
+ if (WorkbenchResourceHelperBase.isPlatformResourceURI(uri))
+ return createResourceForPlatformProtocol(originatingResourceSet, uri);
+ URI mappedURI = ((URIConverterImpl.URIMap)originatingResourceSet.getURIConverter().getURIMap()).getURI(uri);
+ if (isGlobalPluginLoad(mappedURI))
+ return createResourceForPlatformPluginProtocol(originatingResourceSet, uri);
+ return null;
+ }
+ /**
+ * @see org.eclipse.jem.util.ResourceHandler#getEObjectFailed(ResourceSet, URI, boolean)
+ * Subclasses may override.
+ */
+ public EObject getEObjectFailed(ResourceSet originatingResourceSet, URI uri, boolean loadOnDemand) {
+ return null;
+ }
+
+ protected boolean isGlobalPluginLoad(URI aURI) {
+ if (WorkbenchResourceHelperBase.isPlatformPluginResourceURI(aURI)) {
+ String[] globalPlugins = JEMUtilPlugin.getGlobalLoadingPluginNames();
+ for (int i=0;i<globalPlugins.length;i++) {
+ if (aURI.segment(1).startsWith(globalPlugins[i]))
+ return true;
+ }
+ }
+ return false;
+ }
+}
diff --git a/plugins/org.eclipse.jem.util/jemutil/org/eclipse/jem/internal/util/emf/workbench/WorkspaceResourceNotifier.java b/plugins/org.eclipse.jem.util/jemutil/org/eclipse/jem/internal/util/emf/workbench/WorkspaceResourceNotifier.java
new file mode 100644
index 0000000..6c10afe
--- /dev/null
+++ b/plugins/org.eclipse.jem.util/jemutil/org/eclipse/jem/internal/util/emf/workbench/WorkspaceResourceNotifier.java
@@ -0,0 +1,73 @@
+/*******************************************************************************
+ * Copyright (c) 2005 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+/*
+ * $$RCSfile: WorkspaceResourceNotifier.java,v $$
+ * $$Revision: 1.2 $$ $$Date: 2005/02/15 23:04:14 $$
+ */
+package org.eclipse.jem.internal.util.emf.workbench;
+
+
+import org.eclipse.emf.common.notify.Adapter;
+import org.eclipse.emf.common.notify.Notification;
+import org.eclipse.emf.common.notify.impl.AdapterImpl;
+import org.eclipse.emf.common.notify.impl.NotifierImpl;
+
+import org.eclipse.jem.util.emf.workbench.ProjectResourceSet;
+
+/**
+ * This class is used to capture all ADD and REMOVE notifications from each ProjectResourceSet
+ * and forward it on to any interrested listeners. This is to allow you to listen to one object
+ * to gain all ADD and REMOVE notifications for each ResourceSet within the system.
+ */
+public class WorkspaceResourceNotifier extends NotifierImpl {
+ protected Adapter projectAdapter = new WorkspaceResourceCacheAdapter();
+
+ class WorkspaceResourceCacheAdapter extends AdapterImpl {
+ /**
+ * Forward ADD and REMOVE notification.
+ */
+ public void notifyChanged(Notification msg) {
+ switch (msg.getEventType()) {
+ case Notification.ADD :
+ case Notification.ADD_MANY :
+ case Notification.REMOVE :
+ case Notification.REMOVE_MANY :
+ eNotify(msg);
+ break;
+ }
+ }
+ }
+
+ /**
+ * Constructor for WorkspaceResourceCache.
+ */
+ public WorkspaceResourceNotifier() {
+ super();
+ }
+
+ /**
+ * Begin listening to a ProjectResourceSet.
+ */
+ public void beginListening(ProjectResourceSet aResourceSet) {
+ if (aResourceSet != null) {
+ if (aResourceSet.eAdapters() == null ||
+ !aResourceSet.eAdapters().contains(projectAdapter))
+ aResourceSet.eAdapters().add(projectAdapter);
+ }
+ }
+ /**
+ * Stop listening to a ProjectResourceSet.
+ */
+ public void stopListening(ProjectResourceSet aResourceSet) {
+ if (aResourceSet != null)
+ aResourceSet.eAdapters().remove(projectAdapter);
+ }
+}
diff --git a/plugins/org.eclipse.jem.util/jemutil/org/eclipse/jem/internal/util/emf/workbench/nature/EMFNatureRegistry.java b/plugins/org.eclipse.jem.util/jemutil/org/eclipse/jem/internal/util/emf/workbench/nature/EMFNatureRegistry.java
new file mode 100644
index 0000000..f85f7b0
--- /dev/null
+++ b/plugins/org.eclipse.jem.util/jemutil/org/eclipse/jem/internal/util/emf/workbench/nature/EMFNatureRegistry.java
@@ -0,0 +1,74 @@
+/*******************************************************************************
+ * Copyright (c) 2005 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+/*
+ * $$RCSfile: EMFNatureRegistry.java,v $$
+ * $$Revision: 1.2 $$ $$Date: 2005/02/15 23:04:14 $$
+ */
+package org.eclipse.jem.internal.util.emf.workbench.nature;
+
+import java.util.HashSet;
+import java.util.Set;
+
+
+import org.eclipse.core.runtime.*;
+
+import org.eclipse.jem.internal.util.emf.workbench.nls.EMFWorkbenchResourceHandler;
+import org.eclipse.jem.util.logger.proxy.Logger;
+
+public class EMFNatureRegistry {
+
+ private static final String NATURE_REGISTRATION_POINT = "org.eclipse.jem.util.nature_registration"; //$NON-NLS-1$
+ private static final String NATURE = "nature"; //$NON-NLS-1$
+ private static final String STATIC_ID = "id"; //$NON-NLS-1$
+
+ /**
+ * Constructor
+ */
+ private EMFNatureRegistry() {
+ super();
+ readRegistry();
+ }
+
+ private static EMFNatureRegistry singleton;
+
+ public final Set REGISTERED_NATURE_IDS = new HashSet();
+
+ public static EMFNatureRegistry singleton() {
+ if (singleton == null)
+ singleton = new EMFNatureRegistry();
+ return singleton;
+ }
+
+ protected void readRegistry() {
+ // register Nature IDs for the J2EENatures
+ IExtensionRegistry r = Platform.getExtensionRegistry();
+ IConfigurationElement[] ce = r.getConfigurationElementsFor(NATURE_REGISTRATION_POINT);
+ String natureId;
+ for (int i=0; i<ce.length; i++) {
+ if (ce[i].getName().equals(NATURE)) {
+ natureId = ce[i].getAttribute(STATIC_ID);
+ if (natureId != null)
+ registerNatureID(natureId);
+ }
+ }
+ }
+
+ /**
+ * @param natureId
+ */
+ private void registerNatureID(String natureId) {
+ if (!REGISTERED_NATURE_IDS.contains(natureId))
+ REGISTERED_NATURE_IDS.add(natureId);
+ else
+ Logger.getLogger().logError(EMFWorkbenchResourceHandler.getString("EMFNatureRegistry_ERROR_0", new Object[] {natureId})); //$NON-NLS-1$
+ }
+
+}
diff --git a/plugins/org.eclipse.jem.util/jemutil/org/eclipse/jem/internal/util/emf/workbench/nls/EMFWorkbenchResourceHandler.java b/plugins/org.eclipse.jem.util/jemutil/org/eclipse/jem/internal/util/emf/workbench/nls/EMFWorkbenchResourceHandler.java
new file mode 100644
index 0000000..31a8e45
--- /dev/null
+++ b/plugins/org.eclipse.jem.util/jemutil/org/eclipse/jem/internal/util/emf/workbench/nls/EMFWorkbenchResourceHandler.java
@@ -0,0 +1,63 @@
+/*******************************************************************************
+ * Copyright (c) 2005 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+/*
+ * $$RCSfile: EMFWorkbenchResourceHandler.java,v $$
+ * $$Revision: 1.2 $$ $$Date: 2005/02/15 23:04:14 $$
+ */
+package org.eclipse.jem.internal.util.emf.workbench.nls;
+
+import java.text.MessageFormat;
+import java.util.MissingResourceException;
+import java.util.ResourceBundle;
+
+public class EMFWorkbenchResourceHandler {
+
+ private static ResourceBundle fgResourceBundle;
+
+ /**
+ * Returns the resource bundle used by all classes in this Project
+ */
+ public static ResourceBundle getResourceBundle() {
+ try {
+ return ResourceBundle.getBundle("emfworkbench");//$NON-NLS-1$
+ } catch (MissingResourceException e) {
+ // does nothing - this method will return null and
+ // getString(String, String) will return the key
+ // it was called with
+ }
+ return null;
+ }
+ public static String getString(String key) {
+ if (fgResourceBundle == null) {
+ fgResourceBundle= getResourceBundle();
+ }
+
+ if (fgResourceBundle != null) {
+ try {
+ return fgResourceBundle.getString(key);
+ } catch (MissingResourceException e) {
+ return "!" + key + "!";//$NON-NLS-2$//$NON-NLS-1$
+ }
+ } else {
+ return "!" + key + "!";//$NON-NLS-2$//$NON-NLS-1$
+ }
+ }
+public static String getString(String key, Object[] args) {
+
+ try {return MessageFormat.format(getString(key), args);}
+ catch (IllegalArgumentException e) {return getString(key);}
+
+}
+public static String getString(String key, Object[] args, int x) {
+
+ return getString(key);
+ }
+}
diff --git a/plugins/org.eclipse.jem.util/jemutil/org/eclipse/jem/util/CharacterUtil.java b/plugins/org.eclipse.jem.util/jemutil/org/eclipse/jem/util/CharacterUtil.java
new file mode 100644
index 0000000..d452b01
--- /dev/null
+++ b/plugins/org.eclipse.jem.util/jemutil/org/eclipse/jem/util/CharacterUtil.java
@@ -0,0 +1,279 @@
+/*******************************************************************************
+ * Copyright (c) 2006 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+/*
+
+
+ */
+package org.eclipse.jem.util;
+
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+
+import com.ibm.icu.text.UTF16;
+
+
+/**
+ * Static helper to handle characters in the new UTF multi-char format.
+ * It is needed because ICU4J currently doesn't handle some correctly yet that we
+ * need to have working. As ICU4J gets them working, the methods here will become
+ * deprecated.
+ *
+ * @since 1.2.0
+ */
+public class CharacterUtil {
+
+ private CharacterUtil() {
+
+ }
+
+
+ /**
+ * TODO So until ICU4J does work correctly this util will be needed. It will
+ * stay around because it is API, but at that time it will be marked deprecated. It should
+ * also then reroute to ICU4J instead of doing the method reflections.
+ */
+ private static Method METHOD_JAVA_IDENTIFIER_START, METHOD_JAVA_IDENTIFIER_PART;
+
+ static {
+ // Try to get the Character.isJavaIdentifier(int) method. If there, then we are in 1.5 or above. Else use the char form.
+ try {
+ METHOD_JAVA_IDENTIFIER_START = Character.class.getMethod("isJavaIdentifierStart", new Class[] {Integer.TYPE});
+ } catch (SecurityException e) {
+ // Default to use (char) type instead.
+ METHOD_JAVA_IDENTIFIER_START = null;
+ } catch (NoSuchMethodException e) {
+ // Default to use (char) type instead.
+ METHOD_JAVA_IDENTIFIER_START = null;
+ }
+ try {
+ METHOD_JAVA_IDENTIFIER_PART = Character.class.getMethod("isJavaIdentifierPart", new Class[] {Integer.TYPE});
+ } catch (SecurityException e) {
+ // Default to use (char) type instead.
+ METHOD_JAVA_IDENTIFIER_PART = null;
+ } catch (NoSuchMethodException e) {
+ // Default to use (char) type instead.
+ METHOD_JAVA_IDENTIFIER_PART = null;
+ }
+ }
+
+ /**
+ * Is start of java identifier
+ * @param intChar int character (UTF multi-char is valid)
+ * @return <code>true</code> if start of java identifier.
+ *
+ * @see Character#isJavaIdentifierStart(char)
+ * @since 1.2.0
+ */
+ public static boolean isJavaIdentifierStart(int intChar) {
+ if (METHOD_JAVA_IDENTIFIER_START != null) {
+ try {
+ return ((Boolean) METHOD_JAVA_IDENTIFIER_START.invoke(null, new Object[] {new Integer(intChar)})).booleanValue();
+ } catch (IllegalArgumentException e) {
+ } catch (IllegalAccessException e) {
+ } catch (InvocationTargetException e) {
+ }
+ }
+ return Character.isJavaIdentifierStart((char) intChar);
+ }
+
+ /**
+ * Is start of java identifier
+ * @param intChar int character (UTF multi-char is valid)
+ * @return <code>true</code> if start of java identifier.
+ *
+ * @see Character#isJavaIdentifierStart(char)
+ * @since 1.2.0
+ */
+ public static boolean isJavaIdentifierPart(int intChar) {
+ if (METHOD_JAVA_IDENTIFIER_PART != null) {
+ try {
+ return ((Boolean) METHOD_JAVA_IDENTIFIER_PART.invoke(null, new Object[] {new Integer(intChar)})).booleanValue();
+ } catch (IllegalArgumentException e) {
+ } catch (IllegalAccessException e) {
+ } catch (InvocationTargetException e) {
+ }
+ }
+ return Character.isJavaIdentifierPart((char) intChar);
+ }
+
+ public static abstract class AbstractCharIterator {
+
+
+ protected final CharSequence charSeq;
+ private int pos = 0;
+ private int lastCharIndex = 0;
+
+ /**
+ * Create with a string.
+ * @param charSeq
+ *
+ * @since 1.2.0
+ */
+ public AbstractCharIterator(CharSequence charSeq) {
+ this.charSeq = charSeq;
+ }
+
+ /**
+ * Set the next char index.
+ * @param index
+ *
+ * @since 1.2.0
+ */
+ public void setIndex(int index) {
+ pos = index;
+ }
+
+ /**
+ * Has another char.
+ * @return <code>true</code> if there is another char to return.
+ *
+ * @since 1.2.0
+ */
+ public boolean hasNext() {
+ return pos < charSeq.length();
+ }
+
+ /**
+ * Has another char before the current position. Doing previous
+ * will return the char that was just returned.
+ * @return
+ *
+ * @since 1.2.0
+ */
+ public boolean hasPrevious() {
+ return pos > 0;
+ }
+
+ /**
+ * Return next char from the one that was just returned.
+ * @return next char.
+ *
+ * @since 1.2.0
+ */
+ public int next() {
+ if (!hasNext())
+ throw new IllegalStateException();
+
+ int next = utfCharAt(pos);
+ lastCharIndex = pos;
+ pos += UTF16.getCharCount(next);
+ return next;
+ }
+
+ /**
+ * Return the UTF-32 char at the given position.
+ * @param pos
+ * @return
+ *
+ * @since 1.2.0
+ */
+ protected abstract int utfCharAt(int pos);
+
+ /**
+ * Return the previous character from the one that was just returned.
+ * @return
+ *
+ * @since 1.2.0
+ */
+ public int previous() {
+ if (!hasPrevious())
+ throw new IllegalStateException();
+
+ int next;
+ if (UTF16.isTrailSurrogate(charSeq.charAt(--pos))) {
+ if (pos > 0)
+ next = utfCharAt(--pos);
+ else
+ next = charSeq.charAt(pos);
+ } else {
+ next = charSeq.charAt(pos);
+ }
+ lastCharIndex = pos;
+ return next;
+ }
+
+ /**
+ * Return the UTF16 character position of the char that was just returned from either
+ * previous or next.
+ * This is the (char) position not the
+ * position of logical int chars returned. For example a standard string of
+ * <code>"abc"</code> the position of the char 'b' is 1. But take the string
+ * <code>"ab1b2c"</code> where "b1b2" is one UTF-32 char, then the position
+ * of 'c' is 3. It would not be 2, which is what the logical char position
+ * would be if taking UFT32 into account.
+ * @return
+ *
+ * @since 1.2.0
+ */
+ public int getPosition() {
+ return lastCharIndex;
+ }
+
+ }
+
+ /**
+ * Special char iterator that returns ints instead of chars for
+ * walking strings that can contain UTF multi-chars. This is
+ * a limited version of {@link java.text.CharacterIterator}.
+ *
+ * @since 1.2.0
+ */
+ public static class StringIterator extends AbstractCharIterator {
+
+
+ /**
+ * Create with a string.
+ * @param str
+ *
+ * @since 1.2.0
+ */
+ public StringIterator(String str) {
+ super(str);
+ }
+
+ /* (non-Javadoc)
+ * @see org.eclipse.jem.util.CharacterUtil.AbstractCharIterator#utfCharAt(int)
+ */
+ protected int utfCharAt(int pos) {
+ return UTF16.charAt((String) charSeq, pos);
+ }
+
+ }
+
+ /**
+ * Special char iterator that returns ints instead of chars for
+ * walking strings that can contain UTF multi-chars. This is
+ * a limited version of {@link java.text.CharacterIterator}.
+ *
+ * @since 1.2.0
+ */
+ public static class StringBufferIterator extends AbstractCharIterator {
+
+
+ /**
+ * Create with a string.
+ * @param strBuffer
+ *
+ * @since 1.2.0
+ */
+ public StringBufferIterator(StringBuffer strBuffer) {
+ super(strBuffer);
+ }
+
+ /* (non-Javadoc)
+ * @see org.eclipse.jem.util.CharacterUtil.AbstractCharIterator#utfCharAt(int)
+ */
+ protected int utfCharAt(int pos) {
+ return UTF16.charAt((StringBuffer) charSeq, pos);
+ }
+
+ }
+}
diff --git a/plugins/org.eclipse.jem.util/jemutil/org/eclipse/jem/util/NotPresentPerformanceMonitor.java b/plugins/org.eclipse.jem.util/jemutil/org/eclipse/jem/util/NotPresentPerformanceMonitor.java
new file mode 100644
index 0000000..54af2bd
--- /dev/null
+++ b/plugins/org.eclipse.jem.util/jemutil/org/eclipse/jem/util/NotPresentPerformanceMonitor.java
@@ -0,0 +1,55 @@
+package org.eclipse.jem.util;
+/*******************************************************************************
+ * Copyright (c) 2005 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+/*
+ * $$RCSfile: NotPresentPerformanceMonitor.java,v $$
+ * $$Revision: 1.3 $$ $$Date: 2005/02/15 23:04:14 $$
+ */
+/**
+ * This is the instantiation to use if the performance monitor plugin is not installed. It basically does nothing.
+ *
+ * <p>
+ * This class is not intended to be instantiated by clients.
+ * </p>
+ *
+ * @since 1.0.0
+ */
+public class NotPresentPerformanceMonitor extends PerformanceMonitorUtil {
+
+ /*
+ * Only instantiated from this package.
+ */
+ NotPresentPerformanceMonitor() {
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.eclipse.jem.util.PerformanceMonitorUtil#setVar(java.lang.String)
+ */
+ public void setVar(String var) {
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see org.eclipse.jem.util.PerformanceMonitorUtil#doSnapshot(int, int)
+ */
+ protected void doSnapshot(int step, int types) {
+ }
+
+
+ /*
+ * (non-Javadoc)
+ * @see org.eclipse.jem.util.PerformanceMonitorUtil#doSnapshot(int)
+ */
+ protected void doSnapshot(int step) {
+ }
+}
\ No newline at end of file
diff --git a/plugins/org.eclipse.jem.util/jemutil/org/eclipse/jem/util/PerformanceMonitorUtil.java b/plugins/org.eclipse.jem.util/jemutil/org/eclipse/jem/util/PerformanceMonitorUtil.java
new file mode 100644
index 0000000..e6f3a1b
--- /dev/null
+++ b/plugins/org.eclipse.jem.util/jemutil/org/eclipse/jem/util/PerformanceMonitorUtil.java
@@ -0,0 +1,280 @@
+/*******************************************************************************
+ * Copyright (c) 2004, 2005 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+/*
+
+
+ */
+package org.eclipse.jem.util;
+import java.util.EventObject;
+
+import org.eclipse.perfmsr.core.IPerformanceMonitor;
+
+/**
+ * This is a simplified wrapper to the IPerformanceMonitor that hides it so that the actual plugin can be optional and not required.
+ *
+ * <p>
+ * This class is not meant to be subclassed by clients.
+ * </p>
+ *
+ * @since 1.0.0
+ */
+public abstract class PerformanceMonitorUtil {
+ /**
+ * Event for PerformanceListener notification.
+ *
+ * @since 1.1.0
+ */
+ public static class PerformanceEvent extends EventObject {
+
+ /**
+ * Comment for <code>serialVersionUID</code>
+ *
+ * @since 1.1.0
+ */
+ private static final long serialVersionUID = -4680071462750180339L;
+
+ PerformanceEvent(Object source, int step) {
+ super(source);
+ snapshowWithTypes = false;
+ this.step = step;
+ this.types = 0; // Not set.
+ }
+
+ PerformanceEvent(Object source, int step, int types) {
+ super(source);
+ snapshowWithTypes = true;
+ this.step = step;
+ this.types = types;
+ }
+
+
+ /**
+ * Snapshot with types if <code>true</code>.
+ * @since 1.1.0
+ */
+ public final boolean snapshowWithTypes;
+
+ /**
+ * Step of snapshot
+ * @since 1.1.0
+ */
+ public final int step;
+
+ /**
+ * types of snapshot.
+ * @since 1.1.0
+ */
+ public final int types;
+ }
+
+ /**
+ * Performance Listener interface
+ *
+ * @since 1.1.0
+ */
+ public interface PerformanceListener {
+ /**
+ * Snapshot was called.
+ * @param event
+ *
+ * @since 1.1.0
+ */
+ public void snapshot(PerformanceEvent event);
+ }
+
+ private PerformanceListener[] listeners;
+
+ public interface Types {
+
+ /**
+ * 1 - Write out the performance counters from the operating system. These include working set, peak working set, elapsed time, user time, and
+ * kernel time.
+ */
+ int OperatingSystemCounters = IPerformanceMonitor.Types.OperatingSystemCounters;
+
+ /**
+ * 2 - Write out the global performance info. This includes things like the total committed memory for the entire system.
+ *
+ * This function depends on the GetPerformanceInfo() function being available in the Windows psapi.dll. This is available in XP but is usually
+ * not available in Win/2000. If it is not available then this function throws an UnsupportedOperationException.
+ */
+ int GlobalSystemCounters = IPerformanceMonitor.Types.GlobalSystemCounters;
+
+ /**
+ * 4 - Write out the size of the Java Heap.
+ */
+ int JavaHeapSize = IPerformanceMonitor.Types.JavaHeapSize;
+
+ /**
+ * 8 - Write out how much of the Java heap is being used. This calls the garbage collector so it may skew timing results.
+ */
+ int JavaHeapUsed = IPerformanceMonitor.Types.JavaHeapUsed;
+
+ /**
+ * 16 - The plugin startup and size information.
+ */
+ int PluginInfo = IPerformanceMonitor.Types.PluginInfo;
+
+ /** 0xffff - Everything. */
+ int All = IPerformanceMonitor.Types.All;
+ }
+
+ private static PerformanceMonitorUtil sharedMonitor;
+
+ public static PerformanceMonitorUtil getMonitor() {
+ if (sharedMonitor == null) {
+ try {
+ Class.forName("org.eclipse.perfmsr.core.PerfMsrCorePlugin"); // This just tests if the performance plugin is available. Throws //$NON-NLS-1$
+ // exception otherwise.
+ Class presentClass = Class.forName("org.eclipse.jem.util.PresentPerformanceMonitor"); // Get the class we use wrapper it. //$NON-NLS-1$
+ sharedMonitor = (PerformanceMonitorUtil) presentClass.newInstance();
+ if (!sharedMonitor.isValid())
+ sharedMonitor = null;
+ } catch (RuntimeException e) {
+ // If any runtime exception, just use the not present one.
+ } catch (ClassNotFoundException e) {
+ // If class not found, then plugin not available, so just use the not present one.
+ } catch (InstantiationException e) {
+ // Problem instantiating, so just use the not present one.
+ } catch (IllegalAccessException e) {
+ // Some illegal access, so just use the not present one.
+ }
+ if (sharedMonitor == null) {
+ // Couldn't get the performance one for some reason. Use not present one instead.
+ sharedMonitor = new NotPresentPerformanceMonitor();
+ }
+ }
+ return sharedMonitor;
+ }
+
+ protected boolean isValid() {
+ return true;
+ }
+
+ /**
+ * Set the variations that are in effect.
+ *
+ * @param var
+ * a comma delimited string of variation numbers
+ */
+ public abstract void setVar(String var);
+
+ /**
+ * Take a snapshot of some default performance measurements.
+ *
+ * @param step
+ * this identifies the step that the snapshot is for
+ */
+ public final void snapshot(int step) {
+ doSnapshot(step);
+ if (listeners != null)
+ notifySnapshot(new PerformanceEvent(this, step));
+ }
+
+ private void notifySnapshot(PerformanceEvent event) {
+ PerformanceListener[] list = listeners;
+ for (int i = 0; i < list.length; i++) {
+ list[i].snapshot(event);
+ }
+ }
+
+ /**
+ * Do the actual snapshot
+ * @param step
+ *
+ * @see #snapshot(int)
+ * @since 1.1.0
+ */
+ protected abstract void doSnapshot(int step);
+
+ /**
+ * Take a snapshot of the selected performance measurements.
+ *
+ * @param step
+ * this identifies the step that the snapshot is for
+ *
+ * @param types
+ * This controls which measurements are selected. It is an or'd together list of the IPerformanceMonitor.Types constants.
+ *
+ * @see IPerformanceMonitor.Types
+ */
+ public void snapshot(int step, int types) {
+ doSnapshot(step, types);
+ if (listeners != null)
+ notifySnapshot(new PerformanceEvent(this, step, types));
+ }
+
+ /**
+ * Do the actual snapshot
+ * @param step
+ *
+ * @see #snapshot(int, int)
+ * @since 1.1.0
+ */
+ protected abstract void doSnapshot(int step, int types);
+
+ /**
+ * Add listener to list.
+ * @param listener
+ *
+ * @since 1.1.0
+ */
+ public void addPerformanceListener(PerformanceListener listener) {
+ if (findListener(listener) != -1)
+ return;
+ PerformanceListener[] newList = new PerformanceListener[listeners != null ? listeners.length+1 : 1];
+ if (listeners != null)
+ System.arraycopy(listeners, 0, newList, 0, listeners.length);
+ newList[newList.length-1] = listener;
+ listeners = newList;
+ }
+
+ private int findListener(PerformanceListener listener) {
+ if (listeners != null) {
+ for (int i = 0; i < listeners.length; i++) {
+ if (listeners[i] == listener)
+ return i;
+ }
+ }
+ return -1;
+ }
+
+ /**
+ * Remove the listener from the list.
+ * @param listener
+ *
+ * @since 1.1.0
+ */
+ public void removePerformanceListener(PerformanceListener listener) {
+ int index = findListener(listener);
+ if (index != -1) {
+ if (listeners.length == 1) {
+ listeners = null;
+ return;
+ }
+ PerformanceListener[] newList = new PerformanceListener[listeners.length-1];
+ System.arraycopy(listeners, 0, newList, 0, index);
+ System.arraycopy(listeners, index+1, newList, index, newList.length-index);
+ listeners = newList;
+ }
+ }
+ /**
+ * Upload the results to the server. This causes the file to be
+ * closed, and the monitor to be placed into the finished state.
+ *
+ * This method can only be called if the uploadhost, uploadport and uploaduserid
+ * have been configured before hand.
+ *
+ * @param description an optional description (it can be null)
+ *
+ */
+ public boolean upload(String description){return false;}
+}
diff --git a/plugins/org.eclipse.jem.util/jemutil/org/eclipse/jem/util/PresentPerformanceMonitor.java b/plugins/org.eclipse.jem.util/jemutil/org/eclipse/jem/util/PresentPerformanceMonitor.java
new file mode 100644
index 0000000..d021cd5
--- /dev/null
+++ b/plugins/org.eclipse.jem.util/jemutil/org/eclipse/jem/util/PresentPerformanceMonitor.java
@@ -0,0 +1,79 @@
+/*******************************************************************************
+ * Copyright (c) 2004, 2005 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+/*
+
+
+ */
+package org.eclipse.jem.util;
+import org.eclipse.perfmsr.core.IPerformanceMonitor;
+import org.eclipse.perfmsr.core.PerfMsrCorePlugin;
+
+/**
+ * This is the version used when the performance plugin is available.
+ *
+ * <p>
+ * This class is not meant to be instantiated by clients.
+ * </p>
+ *
+ * @since 1.0.0
+ */
+public class PresentPerformanceMonitor extends PerformanceMonitorUtil {
+
+ /* (non-Javadoc)
+ * @see org.eclipse.jem.util.PerformanceMonitorUtil#upload(java.lang.String)
+ */
+ public boolean upload(String description) {
+ return monitor.upload(description).success;
+ }
+
+ private IPerformanceMonitor monitor;
+
+ /*
+ * So that only instantiated by this package.
+ */
+ PresentPerformanceMonitor() {
+ monitor = PerfMsrCorePlugin.getPerformanceMonitor(true);
+ }
+
+
+ /* (non-Javadoc)
+ * @see org.eclipse.jem.util.PerformanceMonitorUtil#isValid()
+ */
+ protected boolean isValid() {
+ return monitor != null;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.eclipse.jem.util.PerformanceMonitorUtil#setVar(java.lang.String)
+ */
+ public void setVar(String var) {
+ monitor.setVar(var);
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see org.eclipse.jem.util.PerformanceMonitorUtil#doSnapshot(int)
+ */
+ protected void doSnapshot(int step) {
+ monitor.snapshot(step);
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see org.eclipse.jem.util.PerformanceMonitorUtil#doSnapshot(int, int)
+ */
+ protected void doSnapshot(int step, int types) {
+ monitor.snapshot(step, types);
+ }
+
+}
diff --git a/plugins/org.eclipse.jem.util/jemutil/org/eclipse/jem/util/RegistryReader.java b/plugins/org.eclipse.jem.util/jemutil/org/eclipse/jem/util/RegistryReader.java
new file mode 100644
index 0000000..37e8277
--- /dev/null
+++ b/plugins/org.eclipse.jem.util/jemutil/org/eclipse/jem/util/RegistryReader.java
@@ -0,0 +1,156 @@
+/*******************************************************************************
+ * Copyright (c) 2005, 2006 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+/*
+ * $$RCSfile: RegistryReader.java,v $$
+ * $$Revision: 1.5 $$ $$Date: 2006/05/17 20:13:45 $$
+ */
+package org.eclipse.jem.util;
+import org.eclipse.core.runtime.*;
+import org.osgi.framework.Bundle;
+
+import org.eclipse.jem.util.logger.proxy.Logger;
+
+
+/**
+ * Class to read a registry. It is meant to be subclassed to provide specific function.
+ *
+ * @since 1.0.0
+ */
+public abstract class RegistryReader {
+
+ String pluginId;
+
+ String extensionPointId;
+
+ private static Bundle systemBundle;
+
+ /**
+ * Utility method to get the plugin id of a configuation element
+ *
+ * @param configurationElement
+ * @return plugin id of configuration element
+ * @since 1.0.0
+ */
+ public static String getPluginId(IConfigurationElement configurationElement) {
+ String pluginId = null;
+
+ if (configurationElement != null) {
+ IExtension extension = configurationElement.getDeclaringExtension();
+
+ if (extension != null)
+ pluginId = extension.getContributor().getName();
+ }
+
+ return pluginId;
+ }
+
+ /**
+ * Constructor for RegistryReader taking a registry, plugin id, and extension point id.
+ *
+ * @param registry
+ * @param pluginID
+ * @param extensionPoint
+ *
+ * @deprecated Use RegistryReader(plugin, extensionPoint) instead. The registry passed in is ignored.
+ * @since 1.0.0
+ */
+ public RegistryReader(IPluginRegistry registry, String pluginID, String extensionPoint) {
+ this(pluginID, extensionPoint);
+ }
+
+ /**
+ * Constructor for RegistryReader taking the plugin id and extension point id.
+ *
+ * @param pluginID
+ * @param extensionPoint
+ *
+ * @since 1.0.0
+ */
+ public RegistryReader(String pluginID, String extensionPoint) {
+ super();
+ this.pluginId = pluginID;
+ extensionPointId = extensionPoint;
+ }
+
+ private void internalReadElement(IConfigurationElement element) {
+ boolean recognized = this.readElement(element);
+ if (!recognized) {
+ logError(element, "Error processing extension: " + element); //$NON-NLS-1$
+ }
+ }
+
+ /*
+ * Logs the error in the desktop log using the provided text and the information in the configuration element.
+ */
+ protected void logError(IConfigurationElement element, String text) {
+ IExtension extension = element.getDeclaringExtension();
+ StringBuffer buf = new StringBuffer();
+ buf.append("Plugin " + extension.getContributor().getName() + ", extension " + extension.getExtensionPointUniqueIdentifier()); //$NON-NLS-1$ //$NON-NLS-2$
+ buf.append("\n" + text); //$NON-NLS-1$
+ Logger.getLogger().logError(buf.toString());
+ }
+
+ /*
+ * Logs a very common registry error when a required attribute is missing.
+ */
+ protected void logMissingAttribute(IConfigurationElement element, String attributeName) {
+ logError(element, "Required attribute '" + attributeName + "' not defined"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ /*
+ * Implement this method to read element attributes. If this element has subelements, the reader will recursively cycle through them and call this
+ * method so don't do it here.
+ */
+ public abstract boolean readElement(IConfigurationElement element);
+
+ /**
+ * Read the extension point and parse it.
+ *
+ * @since 1.0.0
+ */
+ public void readRegistry() {
+ IExtensionPoint point = Platform.getExtensionRegistry().getExtensionPoint(pluginId, extensionPointId);
+ if (point == null)
+ return;
+ IConfigurationElement[] elements = point.getConfigurationElements();
+ for (int i = 0; i < elements.length; i++) {
+ internalReadElement(elements[i]);
+ }
+ }
+
+ /**
+ * Tests to see if it is valid at this point in time to create an executable extension. A valid reason not to would be that the workspace is
+ * shutting donw.
+ *
+ * @param element
+ * @return <code>true</code> if it is valid point to create an executable extension.
+ *
+ * @since 1.0.0
+ */
+ public static boolean canCreateExecutableExtension(IConfigurationElement element) {
+ if (Platform.isRunning() && getSystemBundle().getState() != Bundle.STOPPING)
+ return true;
+ return false;
+ }
+
+ /**
+ * Get the system bundle
+ *
+ * @return system bundle.
+ *
+ * @since 1.0.0
+ */
+ protected static Bundle getSystemBundle() {
+ if (systemBundle == null)
+ systemBundle = Platform.getBundle("org.eclipse.osgi"); //$NON-NLS-1$
+ return systemBundle;
+ }
+}
diff --git a/plugins/org.eclipse.jem.util/jemutil/org/eclipse/jem/util/TimerTests.java b/plugins/org.eclipse.jem.util/jemutil/org/eclipse/jem/util/TimerTests.java
new file mode 100644
index 0000000..7524f78
--- /dev/null
+++ b/plugins/org.eclipse.jem.util/jemutil/org/eclipse/jem/util/TimerTests.java
@@ -0,0 +1,352 @@
+/*******************************************************************************
+ * Copyright (c) 2004, 2006 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+/*
+
+
+ */
+package org.eclipse.jem.util;
+
+import java.text.NumberFormat;
+import java.util.*;
+
+/**
+ *
+ * @since 1.0.2
+ */
+public class TimerTests {
+
+ /**
+ * Default TimerTests class to use when not using your own. It's a global.
+ */
+ public static TimerTests basicTest = new TimerTests();
+
+ public static final String CURRENT_PARENT_ID = "current parent"; //$NON-NLS-1$
+ protected String currentParentId = null;
+
+
+ protected static class TimerStep {
+ static final int START = 0;
+ static final int STOP = 1;
+ static final int START_CUMULATIVE = 2;
+ static final int STOP_CUMULATIVE = 3;
+ static final int START_ACCUMULATING = 4;
+ static final int STOP_ACCUMULATING = 5;
+ protected String id;
+ protected int type;
+ protected long currentTime;
+ protected int threadId;
+}
+
+ protected boolean testOn = false;
+ protected List steps;
+
+ public synchronized boolean startStep(String id) {
+ if (!testOn)
+ return true;
+
+ TimerStep step = createTimerStep(id, TimerStep.START);
+ return step != null;
+ }
+
+ protected TimerStep createTimerStep(String id, int stepType) {
+ TimerStep newStep = new TimerStep();
+ newStep.threadId = Thread.currentThread().hashCode();
+ newStep.id = id;
+ newStep.type = stepType;
+ newStep.currentTime = System.currentTimeMillis();
+ steps.add(newStep);
+
+ return newStep;
+ }
+
+ public synchronized boolean stopStep(String id) {
+ if (!testOn)
+ return true;
+ TimerStep step = createTimerStep(id, TimerStep.STOP);
+ return step != null;
+ }
+
+ public synchronized boolean startAccumulating(String id) {
+ if (!testOn)
+ return true;
+
+ return createTimerStep(id, TimerStep.START_ACCUMULATING) != null;
+ }
+
+ public synchronized boolean stopAccumulating(String id) {
+ if (!testOn)
+ return true;
+
+ return createTimerStep(id, TimerStep.STOP_ACCUMULATING) != null;
+ }
+ public synchronized boolean startCumulativeStep(String id) {
+ if (!testOn)
+ return true;
+
+ return createTimerStep(id, TimerStep.START_CUMULATIVE) != null;
+ }
+
+ public synchronized boolean stopCumulativeStep(String id) {
+ if (!testOn)
+ return true;
+ return createTimerStep(id, TimerStep.STOP_CUMULATIVE) != null;
+ }
+
+ /**
+ * Clear the tests so that you can restart and do some more tests.
+ *
+ *
+ * @since 1.0.2
+ */
+ public synchronized void clearTests() {
+ if (!testOn)
+ return;
+ steps.clear();
+ currentParentId = null;
+ }
+
+ /**
+ * Turn this test on. If not turned on then all calls will quickly return with no errors. This allows the code to stay in place even when not
+ * debugging.
+ * <p>
+ * When turned off, it will clear the test.
+ *
+ * @param on
+ *
+ * @since 1.0.2
+ */
+ public synchronized void testState(boolean on) {
+ if (on == testOn)
+ return;
+ if (on) {
+ testOn = true;
+ if (steps == null)
+ steps = new ArrayList();
+ } else {
+ testOn = false;
+ steps = null;
+ }
+ currentParentId = null;
+ }
+ private static class CumulativeInformation {
+ public TimerStep currentCumulativeStep;
+ public long cumTime;
+ public int cumCount;
+ public int cumCountNonZero;
+ public long maxTime;
+ public long minTime = Integer.MAX_VALUE;
+ public long minTimeNonZero = Integer.MAX_VALUE;
+ }
+ public synchronized void printIt() {
+ if (!testOn)
+ return;
+ if (steps == null)
+ return;
+ Map stepInfoByThreadId = new HashMap();
+ Map indentsByThreadId = new HashMap();
+ Map cumSteps;
+ TimerStep prevStep = null;
+ TimerStep startStep;
+ NumberFormat percentFormatter = NumberFormat.getPercentInstance();
+ double totalTime = 0;
+ StringBuffer strb = new StringBuffer(150);
+ if (steps.size() > 2){
+ totalTime = ((TimerStep)steps.get(steps.size()-1)).currentTime - ((TimerStep)steps.get(0)).currentTime;
+ }
+ for (int i = 0; i < steps.size(); i++) {
+ TimerStep step = (TimerStep) steps.get(i);
+ Integer threadId = new Integer(step.threadId);
+ switch (step.type) {
+ case TimerStep.START:
+ case TimerStep.STOP:
+ Integer threadIndent = (Integer) indentsByThreadId.get(threadId);
+ int indent = 0;
+ if (step.type == TimerStep.START) {
+ if (threadIndent != null)
+ indent = threadIndent.intValue() + 1;
+ indentsByThreadId.put(threadId, new Integer(indent));
+ } else {
+ if (threadIndent != null)
+ indent = threadIndent.intValue();
+ if (indent > 0)
+ indentsByThreadId.put(threadId, new Integer(indent - 1));
+ else {
+ indentsByThreadId.remove(threadId);
+ indent = 0;
+ }
+ }
+ strb.setLength(0);
+ strb.append(step.currentTime);
+ strb.append("\t"); //$NON-NLS-1$
+ for (int j = 0; j < indent; j++) {
+ strb.append(" "); //$NON-NLS-1$
+ }
+ switch (step.type) {
+ case TimerStep.START:
+ strb.append("Start"); //$NON-NLS-1$
+ break;
+
+ case TimerStep.STOP:
+ strb.append("Stop "); //$NON-NLS-1$
+ break;
+ default:
+ break;
+ }
+ ;
+ strb.append(" \""); //$NON-NLS-1$
+ strb.append(step.id);
+ strb.append("\" id("); //$NON-NLS-1$
+ strb.append(step.threadId);
+ strb.append(")"); //$NON-NLS-1$
+ Map startSteps = (Map) stepInfoByThreadId.get(threadId);
+ if (startSteps == null)
+ stepInfoByThreadId.put(threadId, startSteps = new HashMap());
+ if (step.type == TimerStep.START) {
+ // Store the start step for later lookup when calulating the total time
+ startSteps.put(step.id, step);
+ } else {
+ // This is the stop time for a step. We need to find
+ // the corresponding start time and calculate the total time.
+ Object item = startSteps.remove(step.id);
+ if (item instanceof TimerStep) {
+ startStep = (TimerStep) item;
+ if (startStep != null) {
+ int addchars = 100 - strb.length();
+ for (int j = 0; j < addchars; j++) {
+ strb.append(" "); //$NON-NLS-1$
+ }
+ long delta = step.currentTime - startStep.currentTime;
+ strb.append(" Total = " + delta + " ms"); //$NON-NLS-1$ //$NON-NLS-2$
+ if (totalTime > 0)
+ strb.append(" " + percentFormatter.format(delta/totalTime)); //$NON-NLS-1$
+ }
+ } else
+ strb.append(" ---> Couldn't find Starting point for \"" + step.id + "\""); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+ if (i > 0 && (step.currentTime - prevStep.currentTime) > 0)
+ System.out.println("-- " + (step.currentTime - prevStep.currentTime) + " ms --"); //$NON-NLS-1$ //$NON-NLS-2$
+ prevStep = step;
+ System.out.println(strb);
+ break;
+
+ case TimerStep.START_ACCUMULATING:
+ cumSteps = (Map) stepInfoByThreadId.get(threadId);
+ if (cumSteps == null)
+ stepInfoByThreadId.put(threadId, cumSteps = new HashMap());
+ cumSteps.put(step.id, new CumulativeInformation());
+ threadIndent = (Integer) indentsByThreadId.get(threadId);
+ indent = 0;
+ if (threadIndent != null)
+ indent = threadIndent.intValue();
+ strb.setLength(0);
+ strb.append(step.currentTime);
+ strb.append("\t"); //$NON-NLS-1$
+ for (int j = 0; j < indent; j++) {
+ strb.append(" "); //$NON-NLS-1$
+ }
+ strb.append("Start Accumulating"); //$NON-NLS-1$
+ strb.append(" \""); //$NON-NLS-1$
+ strb.append(step.id);
+ strb.append("\" id("); //$NON-NLS-1$
+ strb.append(step.threadId);
+ strb.append(")"); //$NON-NLS-1$
+ if (i > 0 && (step.currentTime - prevStep.currentTime) > 0)
+ System.out.println("-- " + (step.currentTime - prevStep.currentTime) + " ms --"); //$NON-NLS-1$ //$NON-NLS-2$
+ prevStep = step;
+ System.out.println(strb);
+ break;
+
+ case TimerStep.START_CUMULATIVE:
+ cumSteps = (Map) stepInfoByThreadId.get(threadId);
+ if (cumSteps != null) {
+ Object info = cumSteps.get(step.id);
+ if (info instanceof CumulativeInformation)
+ ((CumulativeInformation) info).currentCumulativeStep = step;
+ }
+ break;
+
+ case TimerStep.STOP_CUMULATIVE:
+ cumSteps = (Map) stepInfoByThreadId.get(threadId);
+ if (cumSteps != null) {
+ Object info = cumSteps.get(step.id);
+ if (info instanceof CumulativeInformation) {
+ CumulativeInformation cumInfo = (CumulativeInformation) info;
+ if (cumInfo.currentCumulativeStep != null) {
+ cumInfo.cumCount++;
+ long delta = step.currentTime - cumInfo.currentCumulativeStep.currentTime;
+ cumInfo.cumTime += delta;
+ if (cumInfo.maxTime < delta)
+ cumInfo.maxTime = delta;
+ if (delta < cumInfo.minTime)
+ cumInfo.minTime = delta;
+ if (delta != 0) {
+ cumInfo.cumCountNonZero++;
+ if (delta < cumInfo.minTimeNonZero)
+ cumInfo.minTimeNonZero = delta;
+ }
+ }
+ }
+ }
+ break;
+
+ case TimerStep.STOP_ACCUMULATING:
+ threadIndent = (Integer) indentsByThreadId.get(threadId);
+ indent = 0;
+ if (threadIndent != null)
+ indent = threadIndent.intValue();
+ strb.setLength(0);
+ strb.append(step.currentTime);
+ strb.append("\t"); //$NON-NLS-1$
+ for (int j = 0; j < indent; j++) {
+ strb.append(" "); //$NON-NLS-1$
+ }
+ strb.append("Stop Accumulating"); //$NON-NLS-1$
+ strb.append(" \""); //$NON-NLS-1$
+ strb.append(step.id);
+ strb.append("\" id("); //$NON-NLS-1$
+ strb.append(step.threadId);
+ strb.append(")"); //$NON-NLS-1$
+ cumSteps = (Map) stepInfoByThreadId.get(threadId);
+ if (cumSteps != null) {
+ Object info = cumSteps.get(step.id);
+ if (info instanceof CumulativeInformation) {
+ CumulativeInformation cumInfo = (CumulativeInformation) info;
+ if (cumInfo.currentCumulativeStep != null) {
+ strb.append(" cumulative time="); //$NON-NLS-1$
+ strb.append(cumInfo.cumTime);
+ strb.append(" cumulative count="); //$NON-NLS-1$
+ strb.append(cumInfo.cumCount);
+ strb.append(" max time="); //$NON-NLS-1$
+ strb.append(cumInfo.maxTime);
+ strb.append(" min time="); //$NON-NLS-1$
+ strb.append(cumInfo.minTime);
+ strb.append(" avg time="); //$NON-NLS-1$
+ strb.append(((double) cumInfo.cumTime)/cumInfo.cumCount);
+ strb.append(" NonZero times: cumulative ~0 count="); //$NON-NLS-1$
+ strb.append(cumInfo.cumCountNonZero);
+ if (cumInfo.cumCountNonZero != 0) {
+ strb.append(" min ~0 time="); //$NON-NLS-1$
+ strb.append(cumInfo.minTimeNonZero);
+ strb.append(" avg ~0 time="); //$NON-NLS-1$
+ strb.append(((double) cumInfo.cumTime) / cumInfo.cumCountNonZero);
+ }
+ }
+ }
+ }
+ if (i > 0 && (step.currentTime - prevStep.currentTime) > 0)
+ System.out.println("-- " + (step.currentTime - prevStep.currentTime) + " ms --"); //$NON-NLS-1$ //$NON-NLS-2$
+ prevStep = step;
+ System.out.println(strb);
+ break;
+ }
+ }
+ }
+}
diff --git a/plugins/org.eclipse.jem.util/jemutil/org/eclipse/jem/util/UIContextDetermination.java b/plugins/org.eclipse.jem.util/jemutil/org/eclipse/jem/util/UIContextDetermination.java
new file mode 100644
index 0000000..8955882
--- /dev/null
+++ b/plugins/org.eclipse.jem.util/jemutil/org/eclipse/jem/util/UIContextDetermination.java
@@ -0,0 +1,190 @@
+/*******************************************************************************
+ * Copyright (c) 2005 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+/*
+ * $$RCSfile: UIContextDetermination.java,v $$
+ * $$Revision: 1.5 $$ $$Date: 2007/04/10 01:09:36 $$
+ */
+package org.eclipse.jem.util;
+import java.util.HashMap;
+import java.util.Map;
+
+import org.eclipse.core.runtime.*;
+
+import org.eclipse.jem.util.logger.proxy.Logger;
+import org.eclipse.jem.util.plugin.JEMUtilPlugin;
+
+
+/**
+ * Static utility class for UIContext determination.
+ *
+ * @since 1.0.0
+ */
+public class UIContextDetermination {
+
+ private static final int UNKNOWN = 100;
+
+ public static final String HEADLESS_CONTEXT_LITERAL = "Headless"; //$NON-NLS-1$
+
+ public static final String UI_CONTEXT_LITERAL = "UI"; //$NON-NLS-1$
+
+ public static final int HEADLESS_CONTEXT = 102;
+
+ public static final int UI_CONTEXT = 101;
+
+ private static Map cachedExtensions = null;
+
+ private static int currentContext = UNKNOWN;
+
+ private UIContextDetermination() {
+ }
+
+ /**
+ * Returns an instance of a given class based on the UI or Headless context.
+ *
+ * @param key
+ * @return new class instance for the given key.
+ * @throws IllegalArgumentException
+ * If the key is invalid (e.g. no extension is found for the key)
+ */
+ public static Object createInstance(String key) {
+ Object result = null;
+ if (cachedExtensions == null)
+ initExtensions();
+ IConfigurationElement contextSensitiveClass = (IConfigurationElement) cachedExtensions.get(key);
+ try {
+ if (contextSensitiveClass != null)
+ result = contextSensitiveClass
+ .createExecutableExtension(UIContextDeterminationRegistryReader.UI_CONTEXT_SENSTIVE_CLASS_CLASSNAME_ATTR);
+ } catch (CoreException e) {
+ Logger.getLogger().logError("Problem loading extension not found for key \"" + key + "\"."); //$NON-NLS-1$ //$NON-NLS-2$
+ Logger.getLogger().logError(e);
+ }
+ if (result == null)
+ Logger.getLogger().logError("Extension not found for key \"" + key + "\"."); //$NON-NLS-1$ //$NON-NLS-2$
+ return result;
+ }
+
+ /**
+ * Returns the current context -- determines the value if necessary.
+ *
+ * @return current context
+ * @see #HEADLESS_CONTEXT
+ * @see #UI_CONTEXT
+ */
+ public static int getCurrentContext() {
+ if (currentContext == UNKNOWN) {
+ currentContext = HEADLESS_CONTEXT;
+ new UITesterRegistryReader().readRegistry();
+ }
+ return currentContext;
+ }
+
+ /*
+ * Invokes the UIContextDeterminationRegistryReader to cache all of the extensions, if necessary.
+ *
+ */
+ private static void initExtensions() {
+ if (cachedExtensions == null) {
+ cachedExtensions = new HashMap();
+ new UIContextDeterminationRegistryReader().readRegistry();
+ }
+ }
+
+ /*
+ * Converts the input to one of UI_CONTEXT or HEADLESS_CONTEXT. Defaults to HEADLESS on invalid input
+ *
+ * @param literal @return
+ */
+ private static int convertLiteral(String literal) {
+ return (UI_CONTEXT_LITERAL.equals(literal)) ? UI_CONTEXT : HEADLESS_CONTEXT;
+ }
+
+ /*
+ * Reads the registration of UI Context-sensitive class extensions and initializes the cache of the UIContextDetermination object.
+ *
+ * @author mdelder
+ */
+ private static class UIContextDeterminationRegistryReader extends RegistryReader {
+
+ public static final String UI_CONTEXT_SENSTIVE_CLASS_ELEMENT = "uiContextSensitiveClass"; //$NON-NLS-1$
+
+ public static final String UI_CONTEXT_SENSTIVE_CLASS_KEY_ATTR = "key"; //$NON-NLS-1$
+
+ public static final String UI_CONTEXT_SENSTIVE_CLASS_CLASSNAME_ATTR = "className"; //$NON-NLS-1$
+
+ public static final String UI_CONTEXT_SENSTIVE_CLASS_CONTEXT_ATTR = "context"; //$NON-NLS-1$
+
+ public UIContextDeterminationRegistryReader() {
+ super(JEMUtilPlugin.PLUGIN_ID, JEMUtilPlugin.UI_CONTEXT_EXTENSION_POINT);
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.eclipse.jem.util.RegistryReader#readElement(org.eclipse.core.runtime.IConfigurationElement)
+ */
+ public boolean readElement(IConfigurationElement element) {
+ boolean result = false;
+ if (element.getName().equals(UI_CONTEXT_SENSTIVE_CLASS_ELEMENT)) {
+
+ String key = element.getAttribute(UI_CONTEXT_SENSTIVE_CLASS_KEY_ATTR);
+ String context = element.getAttribute(UI_CONTEXT_SENSTIVE_CLASS_CONTEXT_ATTR);
+
+ if (!cachedExtensions.containsKey(key) || getCurrentContext() == convertLiteral(context))
+ cachedExtensions.put(key, element);
+ result = true;
+ }
+ return result;
+ }
+ }
+
+ /*
+ * Reads the uiTester extension and instantiate the any of the UITester classes it finds.
+ *
+ * The implementation has the side effect that if multiple UITesters are registered, any of them can trip the currentContext into the UI_CONTEXT
+ * state.
+ *
+ * @author mdelder
+ */
+ private static class UITesterRegistryReader extends RegistryReader {
+
+ public static final String UI_TESTER_ELEMENT = "uiTester"; //$NON-NLS-1$
+
+ public static final String UI_TESTER_CLASSNAME_ATTR = "className"; //$NON-NLS-1$
+
+ public UITesterRegistryReader() {
+ super(JEMUtilPlugin.PLUGIN_ID, JEMUtilPlugin.UI_TESTER_EXTENSION_POINT);
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see com.ibm.etools.emf.workbench.RegistryReader#readElement(org.eclipse.core.runtime.IConfigurationElement)
+ */
+ public boolean readElement(IConfigurationElement element) {
+ boolean result = false;
+ if (element.getName().equals(UI_TESTER_ELEMENT)) {
+ result = true;
+ try {
+ // Don't bother running tester it if we already processed one extension that returned true.
+ if (currentContext != UI_CONTEXT && canCreateExecutableExtension(element)) {
+ UITester tester = (UITester) element.createExecutableExtension(UI_TESTER_CLASSNAME_ATTR);
+ if (tester.isCurrentContextUI())
+ currentContext = UI_CONTEXT;
+ }
+ } catch (Exception t) {
+ Logger.getLogger().log("UIContextDetermination is proceeding in HEADLESS mode"); //$NON-NLS-1$
+ }
+ }
+ return result;
+ }
+ }
+}
\ No newline at end of file
diff --git a/plugins/org.eclipse.jem.util/jemutil/org/eclipse/jem/util/UITester.java b/plugins/org.eclipse.jem.util/jemutil/org/eclipse/jem/util/UITester.java
new file mode 100644
index 0000000..54517e8
--- /dev/null
+++ b/plugins/org.eclipse.jem.util/jemutil/org/eclipse/jem/util/UITester.java
@@ -0,0 +1,31 @@
+package org.eclipse.jem.util;
+/*******************************************************************************
+ * Copyright (c) 2005 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+/*
+ * $$RCSfile: UITester.java,v $$
+ * $$Revision: 1.2 $$ $$Date: 2005/02/15 23:04:14 $$
+ */
+/**
+ * Interface for a UITester. The "classname" attribute on the "uiTester" extension point should implement this class.
+ *
+ * @since 1.0.0
+ */
+public interface UITester {
+
+ /**
+ * Answer if the current context is an UI context.
+ *
+ * @return <code>true</code> if an UI context.
+ *
+ * @since 1.0.0
+ */
+ public boolean isCurrentContextUI();
+}
\ No newline at end of file
diff --git a/plugins/org.eclipse.jem.util/jemutil/org/eclipse/jem/util/emf/workbench/EMFWorkbenchContextBase.java b/plugins/org.eclipse.jem.util/jemutil/org/eclipse/jem/util/emf/workbench/EMFWorkbenchContextBase.java
new file mode 100644
index 0000000..bedff60
--- /dev/null
+++ b/plugins/org.eclipse.jem.util/jemutil/org/eclipse/jem/util/emf/workbench/EMFWorkbenchContextBase.java
@@ -0,0 +1,193 @@
+/*******************************************************************************
+ * Copyright (c) 2005 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+/*
+ * $$RCSfile: EMFWorkbenchContextBase.java,v $$
+ * $$Revision: 1.2 $$ $$Date: 2005/02/15 23:04:14 $$
+ */
+package org.eclipse.jem.util.emf.workbench;
+
+import org.eclipse.core.resources.IProject;
+import org.eclipse.core.runtime.CoreException;
+import org.eclipse.emf.common.util.URI;
+import org.eclipse.emf.ecore.resource.Resource;
+
+import org.eclipse.jem.internal.util.emf.workbench.*;
+import org.eclipse.jem.internal.util.emf.workbench.nls.EMFWorkbenchResourceHandler;
+import org.eclipse.jem.util.plugin.JEMUtilPlugin;
+
+
+/**
+ * ContextBase for EMFWorkbench.
+ *
+ * <p>
+ * This is meant to be subclassed as needed for additional or override function. It will be instantiated by default.
+ * </p>
+ *
+ * @since 1.0.0
+ */
+public class EMFWorkbenchContextBase {
+
+ protected IProject project;
+
+ protected ProjectResourceSet resourceSet;
+
+ /**
+ * Construct with a project.
+ *
+ * @param aProject
+ *
+ * @since 1.0.0
+ */
+ public EMFWorkbenchContextBase(IProject aProject) {
+ if (aProject == null)
+ throw new IllegalArgumentException(EMFWorkbenchResourceHandler.getString("EMFWorkbenchContextBase_ERROR_1")); //$NON-NLS-1$
+ project = aProject;
+ }
+
+ /**
+ * Dispose of the context base.
+ *
+ *
+ * @since 1.0.0
+ */
+ public void dispose() {
+ if (resourceSet != null)
+ resourceSet.release();
+ resourceSet = null;
+ project = null;
+ }
+
+ /**
+ * Get the project this context is associated with.
+ *
+ * @return project
+ *
+ * @since 1.0.0
+ */
+ public IProject getProject() {
+ return project;
+ }
+
+ /**
+ * Return the resource set (creating if needed) for context.
+ *
+ * @return resource set
+ *
+ * @since 1.0.0
+ */
+ public ProjectResourceSet getResourceSet() {
+ if (resourceSet == null) {
+ resourceSet = createResourceSet();
+ initializeResourceSet(resourceSet);
+ }
+ return resourceSet;
+ }
+
+ /**
+ * Used for optimization; answer whether a resourceSet has been created
+ *
+ * @return <code>true</code> if a resource set has been created.
+ *
+ * @since 1.0.0
+ */
+ public boolean hasResourceSet() {
+ return resourceSet != null;
+ }
+
+ /**
+ * Initialize the resource set.
+ *
+ * @param aResourceSet
+ *
+ * @since 1.0.0
+ */
+ protected void initializeResourceSet(ProjectResourceSet aResourceSet) {
+ createResourceSetSynchronizer(aResourceSet);
+ aResourceSet.setURIConverter(createURIConverter(aResourceSet));
+ aResourceSet.add(new WorkspaceResourceHandler());
+ JEMUtilPlugin.getDefault().addExtendedResourceHandlers(aResourceSet);
+
+ }
+
+ /**
+ * Create the resource set. By default it is a ProjectResourceSetImpl.
+ *
+ * @return project's new resource set.
+ *
+ * @since 1.0.0
+ */
+ protected ProjectResourceSet createResourceSet() {
+ if (project == null)
+ throw new IllegalStateException(EMFWorkbenchResourceHandler.getString("EMFWorkbenchContextBase_ERROR_2")); //$NON-NLS-1$
+ return new ProjectResourceSetImpl(project);
+ }
+
+ /**
+ * Create a URIConverter for the resource set.
+ *
+ * @param aResourceSet
+ * @return a uri converter.
+ *
+ * @since 1.0.0
+ */
+ protected WorkbenchURIConverter createURIConverter(ProjectResourceSet aResourceSet) {
+ return new WorkbenchURIConverterImpl(getProject(), aResourceSet.getSynchronizer());
+ }
+
+ /**
+ * Create a resource set workbench synchronizer.
+ *
+ * @param aResourceSet
+ * @return a resource set workbench synchronizer.
+ *
+ * @since 1.0.0
+ */
+ protected ResourceSetWorkbenchSynchronizer createResourceSetSynchronizer(ProjectResourceSet aResourceSet) {
+ return EMFWorkbenchContextFactory.INSTANCE.createSynchronizer(aResourceSet, getProject());
+ }
+
+ /**
+ * Delete the resource from the workspace.
+ *
+ * @param aResource
+ * @throws CoreException
+ *
+ * @since 1.0.0
+ */
+ public void deleteResource(Resource aResource) throws CoreException {
+ if (aResource != null)
+ deleteFile(aResource);
+ }
+
+ /**
+ * Delete the file associated with the resource.
+ *
+ * @param resource
+ *
+ * @since 1.0.0
+ */
+ public void deleteFile(Resource resource) {
+ throw new UnsupportedOperationException(EMFWorkbenchResourceHandler.getString("EMFWorkbenchContextBase_ERROR_0")); //$NON-NLS-1$
+ }
+
+ /**
+ * Get resource (with the given URI) from the project resource set. Load it if not already loaded.
+ *
+ * @param uri
+ * @return resource for the uri, or <code>null</code> if not found.
+ *
+ * @since 1.0.0
+ */
+ public Resource getResource(URI uri) {
+ return this.resourceSet.getResource(uri, true);
+ }
+
+}
\ No newline at end of file
diff --git a/plugins/org.eclipse.jem.util/jemutil/org/eclipse/jem/util/emf/workbench/FlexibleProjectResourceSet.java b/plugins/org.eclipse.jem.util/jemutil/org/eclipse/jem/util/emf/workbench/FlexibleProjectResourceSet.java
new file mode 100644
index 0000000..1e231f0
--- /dev/null
+++ b/plugins/org.eclipse.jem.util/jemutil/org/eclipse/jem/util/emf/workbench/FlexibleProjectResourceSet.java
@@ -0,0 +1,68 @@
+package org.eclipse.jem.util.emf.workbench;
+
+import org.eclipse.emf.common.util.URI;
+import org.eclipse.emf.ecore.resource.Resource;
+import org.eclipse.emf.ecore.resource.Resource.Factory;
+
+
+public interface FlexibleProjectResourceSet extends ProjectResourceSet {
+
+
+ /**
+ * Returns the resource resolved by the URI.
+ * <p>
+ * A resource set is expected to implement the following strategy
+ * in order to resolve the given URI to a resource.
+ * First it uses it's {@link #getURIConverter URI converter} to {@link URIConverter#normalize normalize} the URI
+ * and then to compare it with the normalized URI of each resource;
+ * if it finds a match,
+ * that resource becomes the result.
+ * Failing that,
+ * it {@link org.eclipse.emf.ecore.resource.impl.ResourceSetImpl#delegatedGetResource delegates}
+ * to allow the URI to be resolved elsewhere.
+ * For example,
+ * the {@link org.eclipse.emf.ecore.EPackage.Registry#INSTANCE package registry}
+ * is used to {@link org.eclipse.emf.ecore.EPackage.Registry#getEPackage resolve}
+ * the {@link org.eclipse.emf.ecore.EPackage namespace URI} of a package
+ * to the static instance of that package.
+ * So the important point is that an arbitrary implementation may resolve the URI to any resource,
+ * not necessarily to one contained by this particular resource set.
+ * If the delegation step fails to provide a result,
+ * and if <code>loadOnDemand</code> is <code>true</code>,
+ * a resource is {@link org.eclipse.emf.ecore.resource.impl.ResourceSetImpl#demandCreateResource created}
+ * and that resource becomes the result.
+ * If <code>loadOnDemand</code> is <code>true</code>
+ * and the result resource is not {@link Resource#isLoaded loaded},
+ * it will be {@link org.eclipse.emf.ecore.resource.impl.ResourceSetImpl#demandLoad loaded} before it is returned.
+ * </p>
+ * @param uri the URI to resolve.
+ * @param loadOnDemand whether to create and load the resource, if it doesn't already exists.
+ * @param registeredFactory that is used to create resource if needed
+ * @return the resource resolved by the URI, or <code>null</code> if there isn't one and it's not being demand loaded.
+ * @throws RuntimeException if a resource can't be demand created.
+ * @throws org.eclipse.emf.common.util.WrappedException if a problem occurs during demand load.
+ * @since 2.1
+ */
+
+ Resource getResource(URI uri, boolean loadOnDemand, Factory registeredFactory);
+
+ /**
+ * Creates a new resource, of the appropriate type, and returns it.
+ * <p>
+ * It delegates to the resource factory {@link #getResourceFactoryRegistry registry}
+ * to determine the {@link Resource.Factory.Registry#getFactory correct} factory,
+ * and then it uses that factory to {@link Resource.Factory#createResource create} the resource
+ * and add it to the {@link #getResources contents}.
+ * If there is no registered factory, <code>null</code> will be returned;
+ * when running within Eclipse,
+ * a default XMI factory will be registered,
+ * and this will never return <code>null</code>.
+ * </p>
+ * @param uri the URI of the resource to create.
+ * @param resourceFactory
+ * @return a new resource, or <code>null</code> if no factory is registered.
+ */
+
+ public Resource createResource(URI uri, Resource.Factory resourceFactory);
+
+}
diff --git a/plugins/org.eclipse.jem.util/jemutil/org/eclipse/jem/util/emf/workbench/IEMFContextContributor.java b/plugins/org.eclipse.jem.util/jemutil/org/eclipse/jem/util/emf/workbench/IEMFContextContributor.java
new file mode 100644
index 0000000..465d7fa
--- /dev/null
+++ b/plugins/org.eclipse.jem.util/jemutil/org/eclipse/jem/util/emf/workbench/IEMFContextContributor.java
@@ -0,0 +1,46 @@
+/*******************************************************************************
+ * Copyright (c) 2005 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+/*
+ * $$RCSfile: IEMFContextContributor.java,v $$
+ * $$Revision: 1.2 $$ $$Date: 2005/02/15 23:04:14 $$
+ */
+
+package org.eclipse.jem.util.emf.workbench;
+
+/**
+ * EMF Context Contributor interface. Implimenters are called to contribute to the context.
+ *
+ * @see org.eclipse.jem.util.emf.workbench.WorkbenchResourceHelperBase#createEMFContext(IProject, IEMFContextContributor)
+ * @since 1.0.0
+ */
+public interface IEMFContextContributor {
+
+ /**
+ * This is your opportunity to add a primary EMFNature. Typically you would add to the WorkbenchContext held by <code>aNature</code> in order to
+ * change the container for the WorkbenchURIConverter or add adapter factories to the ResourceSet or anything else that is needed.
+ *
+ * @param aNature
+ *
+ * @since 1.0.0
+ */
+ void primaryContributeToContext(EMFWorkbenchContextBase aNature);
+
+ /**
+ * This is your opportunity to add a secondary EMFNature. Typically you would add to the WorkbenchContext held by <code>aNature</code> in order
+ * to change the container for the WorkbenchURIConverter or add adapter factories to the ResourceSet or anything else that is needed.
+ *
+ * @param aNature
+ *
+ * @since 1.0.0
+ */
+ void secondaryContributeToContext(EMFWorkbenchContextBase aNature);
+
+}
\ No newline at end of file
diff --git a/plugins/org.eclipse.jem.util/jemutil/org/eclipse/jem/util/emf/workbench/ISynchronizerExtender.java b/plugins/org.eclipse.jem.util/jemutil/org/eclipse/jem/util/emf/workbench/ISynchronizerExtender.java
new file mode 100644
index 0000000..f70dd1e
--- /dev/null
+++ b/plugins/org.eclipse.jem.util/jemutil/org/eclipse/jem/util/emf/workbench/ISynchronizerExtender.java
@@ -0,0 +1,44 @@
+/*******************************************************************************
+ * Copyright (c) 2005 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+/*
+ * $$RCSfile: ISynchronizerExtender.java,v $$
+ * $$Revision: 1.2 $$ $$Date: 2005/02/15 23:04:14 $$
+ */
+package org.eclipse.jem.util.emf.workbench;
+
+import org.eclipse.core.resources.IResourceDelta;
+
+/**
+ * Implimenters allows clients, eg {@link org.eclipse.jem.util.emf.workbench.EMFNatureContributor}, to extend the behavior of the
+ * ResourceSetWorkbenchSynchronizer.
+ *
+ * @see org.eclipse.jem.util.emf.workbench.ResourceSetWorkbenchSynchronizer#addExtender(ISynchronizerExtender)
+ * @since 1.0.0
+ */
+public interface ISynchronizerExtender {
+
+ /**
+ * Notification that project has changed.
+ *
+ * @param delta
+ *
+ * @since 1.0.0
+ */
+ void projectChanged(IResourceDelta delta);
+
+ /**
+ * Notification that project has been closed.
+ *
+ *
+ * @since 1.0.0
+ */
+ void projectClosed();
+}
\ No newline at end of file
diff --git a/plugins/org.eclipse.jem.util/jemutil/org/eclipse/jem/util/emf/workbench/ProjectResourceSet.java b/plugins/org.eclipse.jem.util/jemutil/org/eclipse/jem/util/emf/workbench/ProjectResourceSet.java
new file mode 100644
index 0000000..2c97699
--- /dev/null
+++ b/plugins/org.eclipse.jem.util/jemutil/org/eclipse/jem/util/emf/workbench/ProjectResourceSet.java
@@ -0,0 +1,119 @@
+/*******************************************************************************
+ * Copyright (c) 2005 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+/*
+ * $$RCSfile: ProjectResourceSet.java,v $$
+ * $$Revision: 1.5 $$ $$Date: 2007/08/30 02:37:05 $$
+ */
+package org.eclipse.jem.util.emf.workbench;
+
+import org.eclipse.core.resources.IProject;
+import org.eclipse.emf.common.notify.Notification;
+import org.eclipse.emf.ecore.resource.ResourceSet;
+
+/**
+ * A ResourceSet for an entire project. It allows sharing of resources from multiple editors/viewers for a project.
+ * <p>
+ * An additional Notification type is sent out by ProjectResourceSet's of project resource set about to be released. A release is
+ * called when projects are about to be closed. They release all of the resources and unload them. This notification can be used
+ * to know that this is about to happen and to do something before the resources become invalid. It will be sent out just before the
+ * resource set will be released.
+ *
+ * @see ProjectResourceSet#SPECIAL_NOTIFICATION_TYPE
+ * @see ProjectResourceSet#PROJECTRESOURCESET_ABOUT_TO_RELEASE_ID
+ * @since 1.0.0
+ */
+
+public interface ProjectResourceSet extends ResourceSet {
+
+ IProject getProject();
+
+ /**
+ * Notification type in notifications from the ProjectResourceSet for
+ * special notifications, and not the standard ones from ResourceSet.
+ *
+ * @see org.eclipse.emf.common.notify.Notification#getEventType()
+ * @since 1.1.0
+ */
+ static int SPECIAL_NOTIFICATION_TYPE = Notification.EVENT_TYPE_COUNT+4;
+
+ /**
+ * Notification Feature ID for resource set about to be released.
+ * Use {@link org.eclipse.emf.common.notify.Notification#getFeatureID(java.lang.Class)} to
+ * get this id. The getFeature() on notification will return null.
+ *
+ * @since 1.1.0
+ */
+ static int PROJECTRESOURCESET_ABOUT_TO_RELEASE_ID = 1000;
+
+ /**
+ * Call when the ResourceSet is no longer to be used.
+ *
+ *
+ * @since 1.0.0
+ */
+ void release();
+
+ /**
+ * Add the <code>resourceHandler</code> to the end of the list of resourceHandlers.
+ *
+ * @param resourceHandler
+ * IResourceHandler
+ * @return boolean Return <code>true</code> if it was added.
+ * @since 1.0.0
+ */
+ boolean add(ResourceHandler resourceHandler);
+
+ /**
+ * Add the <code>resourceHandler</code> to the front of the list of resourceHandlers.
+ *
+ * @param resourceHandler
+ * IResourceHandler
+ * @since 1.0.0
+ */
+ void addFirst(ResourceHandler resourceHandler);
+
+ /**
+ * Remove the <code>resourceHandler</code> from the list of resourceHandlers.
+ *
+ * @param resourceHandler
+ * IResourceHandler
+ * @return boolean Return true if it was removed.
+ * @since 1.0.0
+ */
+ boolean remove(ResourceHandler resourceHandler);
+
+ /**
+ * Return the ResourceSet synchronizer that will synchronize the ResourceSet with changes from the Workbench.
+ *
+ * @return ResourceSetWorkbenchSynchronizer
+ * @since 1.0.0
+ */
+ ResourceSetWorkbenchSynchronizer getSynchronizer();
+
+ /**
+ * Set the ResourceSet synchronizer that will synchronize the ResourceSet with changes from the Workbench.
+ *
+ * @param aSynchronizer
+ * @return ResourceSetWorkbenchSynchronizer
+ * @since 1.0.0
+ */
+ void setSynchronizer(ResourceSetWorkbenchSynchronizer aSynchronizer);
+
+ /**
+ * This should be called by clients whenever the structure of the project changes such that any cached URIs will be invalid. For example, if the
+ * source folders within the URIConverter change.
+ *
+ * @since 1.0.0
+ */
+ void resetNormalizedURICache();
+
+
+}
\ No newline at end of file
diff --git a/plugins/org.eclipse.jem.util/jemutil/org/eclipse/jem/util/emf/workbench/ProjectUtilities.java b/plugins/org.eclipse.jem.util/jemutil/org/eclipse/jem/util/emf/workbench/ProjectUtilities.java
new file mode 100644
index 0000000..eae2e81
--- /dev/null
+++ b/plugins/org.eclipse.jem.util/jemutil/org/eclipse/jem/util/emf/workbench/ProjectUtilities.java
@@ -0,0 +1,775 @@
+/*******************************************************************************
+ * Copyright (c) 2005 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+/*
+ * $$RCSfile: ProjectUtilities.java,v $$
+ * $$Revision: 1.6 $$ $$Date: 2008/03/05 19:43:18 $$
+ */
+
+package org.eclipse.jem.util.emf.workbench;
+
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.logging.Level;
+
+import org.eclipse.core.resources.*;
+import org.eclipse.core.runtime.*;
+import org.eclipse.emf.common.util.URI;
+import org.eclipse.emf.ecore.EObject;
+import org.eclipse.emf.ecore.resource.*;
+
+import org.eclipse.jem.util.logger.proxy.Logger;
+import org.eclipse.jem.util.plugin.JEMUtilPlugin;
+
+
+/**
+ * EMF Workbench Project Utilities.
+ *
+ * @since 1.0.0
+ */
+
+public class ProjectUtilities {
+
+ /**
+ * Project control file name in project.
+ *
+ * @since 1.0.0
+ */
+ public final static String DOT_PROJECT = ".project"; //$NON-NLS-1$
+
+ /**
+ * Classpath control file name in project.
+ *
+ * @since 1.0.0
+ */
+ public final static String DOT_CLASSPATH = ".classpath"; //$NON-NLS-1$
+
+ public ProjectUtilities() {
+ }
+
+ /**
+ * Add the nature id to the project ahead of all other nature ids.
+ *
+ * @param proj
+ * @param natureId
+ * @throws CoreException
+ *
+ * @since 1.0.0
+ */
+ public static void addNatureToProject(IProject proj, String natureId) throws CoreException {
+ IProjectDescription description = proj.getDescription();
+ String[] prevNatures = description.getNatureIds();
+ String[] newNatures = new String[prevNatures.length + 1];
+ System.arraycopy(prevNatures, 0, newNatures, 1, prevNatures.length);
+ newNatures[0] = natureId;
+ description.setNatureIds(newNatures);
+ proj.setDescription(description, null);
+ }
+
+ /**
+ * Add the nature id after all of the other nature ids for the project.
+ *
+ * @param proj
+ * @param natureId
+ * @throws CoreException
+ *
+ * @since 1.0.0
+ */
+ public static void addNatureToProjectLast(IProject proj, String natureId) throws CoreException {
+ IProjectDescription description = proj.getDescription();
+ String[] prevNatures = description.getNatureIds();
+ String[] newNatures = new String[prevNatures.length + 1];
+ System.arraycopy(prevNatures, 0, newNatures, 0, prevNatures.length);
+ newNatures[prevNatures.length] = natureId;
+ description.setNatureIds(newNatures);
+ proj.setDescription(description, null);
+ }
+
+ /**
+ * Remove the nature id from the project.
+ *
+ * @param project
+ * @param natureId
+ * @throws CoreException
+ *
+ * @since 1.0.0
+ */
+ public static void removeNatureFromProject(IProject project, String natureId) throws CoreException {
+ IProjectDescription description = project.getDescription();
+ String[] prevNatures = description.getNatureIds();
+ int size = prevNatures.length;
+ int newsize = 0;
+ String[] newNatures = new String[size];
+ boolean matchfound = false;
+ for (int i = 0; i < size; i++) {
+ if (prevNatures[i].equals(natureId)) {
+ matchfound = true;
+ continue;
+ } else
+ newNatures[newsize++] = prevNatures[i];
+ }
+ if (!matchfound)
+ throw new CoreException(new Status(IStatus.ERROR, JEMUtilPlugin.ID, 0,
+ "The nature id " + natureId + " does not exist on the project " + project.getName(), null)); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ else {
+ String[] temp = newNatures;
+ newNatures = new String[newsize];
+ System.arraycopy(temp, 0, newNatures, 0, newsize);
+ description.setNatureIds(newNatures);
+ project.setDescription(description, null);
+ }
+ }
+
+ /**
+ * Add the list of projects to end of the "referenced projects" list from the project's description.
+ *
+ * @param project
+ * @param toBeAddedProjectsList
+ * @throws CoreException
+ *
+ * @since 1.0.0
+ */
+ public static void addReferenceProjects(IProject project, List toBeAddedProjectsList) throws CoreException {
+
+ IProjectDescription description = project.getDescription();
+ IProject[] projects = description.getReferencedProjects();
+
+ ArrayList projectsList = new ArrayList();
+
+ for (int i = 0; i < projects.length; i++) {
+ projectsList.add(projects[i]);
+ }
+
+ for (int i = 0; i < toBeAddedProjectsList.size(); i++) {
+ projectsList.add(toBeAddedProjectsList.get(i));
+ }
+
+ IProject[] refProjects = new IProject[projectsList.size()];
+
+ for (int i = 0; i < refProjects.length; i++) {
+ refProjects[i] = (IProject) (projectsList.get(i));
+ }
+
+ description.setReferencedProjects(refProjects);
+ project.setDescription(description, null);
+ }
+
+ /**
+ * Add the single project to the end of the "referenced projects" list from the project's description.
+ *
+ * @param project
+ * @param projectToBeAdded
+ * @throws CoreException
+ *
+ * @since 1.0.0
+ */
+ public static void addReferenceProjects(IProject project, IProject projectToBeAdded) throws CoreException {
+ IProjectDescription description = project.getDescription();
+ IProject[] projects = description.getReferencedProjects();
+
+ ArrayList projectsList = new ArrayList();
+
+ for (int i = 0; i < projects.length; i++) {
+ projectsList.add(projects[i]);
+ }
+
+ projectsList.add(projectToBeAdded);
+
+ IProject[] refProjects = new IProject[projectsList.size()];
+
+ for (int i = 0; i < refProjects.length; i++) {
+ refProjects[i] = (IProject) (projectsList.get(i));
+ }
+
+ description.setReferencedProjects(refProjects);
+ project.setDescription(description, null);
+ }
+
+ /**
+ * Force a an immediate build of the project.
+ *
+ * @param project
+ * @param progressMonitor
+ *
+ * @since 1.0.0
+ */
+ public static void forceAutoBuild(IProject project, IProgressMonitor progressMonitor) {
+ try {
+ project.build(IncrementalProjectBuilder.FULL_BUILD, progressMonitor);
+ } catch (CoreException ce) {
+ //Revisit: Need to use a Logger
+ //Logger.getLogger().logError(ce);
+ }
+ }
+
+ /**
+ * Return if auto build is turned on.
+ *
+ * @return <code>true</code> if auto build is turned on.
+ *
+ * @since 1.0.0
+ */
+ public static boolean getCurrentAutoBuildSetting() {
+
+ IWorkspace workspace = ResourcesPlugin.getWorkspace();
+ IWorkspaceDescription wd = workspace.getDescription();
+ return wd.isAutoBuilding();
+ }
+
+ /**
+ * Get the project associated with the given object.
+ *
+ * @param object
+ * may be an <code>IProject, IResource, IAdaptable (to an IProject), EObject (gets IProject if object is in a ProjectResourceSet</code>.
+ * @param natureId
+ * if <code>null</code> then returns project. If not <code>null</code> then returns project only if project has this nature id.
+ * @return project associated with the object or <code>null</code> if not found.
+ *
+ * @since 1.0.0
+ */
+ public static IProject getProject(Object object, String natureId) {
+ IProject result = getProject(object);
+ if (natureId == null)
+ return result;
+ if (result != null && result.isAccessible() && natureId != null)
+ try {
+ if (result.hasNature(natureId))
+ return result;
+ } catch (CoreException e) {
+ Logger.getLogger().logError(e);
+ }
+ return null;
+ }
+
+ /**
+ * Get the project associated with the given object.
+ *
+ * @param object
+ * may be an <code>IProject, IResource, IAdaptable (to an IProject), EObject (gets IProject if object is in a ProjectResourceSet</code>.
+ * @return project associated with the object or <code>null</code> if not found.
+ *
+ * @since 1.0.0
+ */
+ public static IProject getProject(Object object) {
+ IProject result = null;
+
+ if (object instanceof IProject)
+ result = (IProject) object;
+ else if (object instanceof IResource)
+ result = ((IResource) object).getProject();
+ else if (object instanceof IAdaptable)
+ result = (IProject) ((IAdaptable) object).getAdapter(IProject.class);
+ else if (object instanceof EObject)
+ result = getProject((EObject) object);
+
+ return result;
+ }
+
+ /**
+ * Get the project associated with the given EObject. (If in a ProjectResourceSet, then the project from that resource set).
+ *
+ * @param aRefObject
+ * @return project if associated or <code>null</code> if not found.
+ *
+ * @since 1.0.0
+ */
+ public static IProject getProject(EObject aRefObject) {
+ if (aRefObject != null) {
+ Resource resource = aRefObject.eResource();
+ if (resource != null)
+ return getProject(resource);
+ }
+ return null;
+ }
+
+ public static IFile getPlatformFile(URI uri) {
+ if (WorkbenchResourceHelperBase.isPlatformResourceURI(uri)) {
+ String fileString = URI.decode(uri.path());
+ fileString = fileString.substring(JEMUtilPlugin.PLATFORM_RESOURCE.length() + 1);
+ return WorkbenchResourceHelperBase.getWorkspace().getRoot().getFile(new Path(fileString));
+ }
+ return null;
+ }
+
+ /**
+ * Get the project associated with the given Resource. (If in a ProjectResourceSet, then the project from that resource set).
+ *
+ * @param resource
+ * @return project if associated or <code>null</code> if not found.
+ *
+ * @since 1.0.0
+ */
+ public static IProject getProject(Resource resource) {
+ ResourceSet set = resource == null ? null : resource.getResourceSet();
+ if (set == null) {
+ URI uri = resource.getURI();
+ if (uri == null) return null;
+ IFile file = getPlatformFile(resource.getURI());
+ if (file == null)
+ return null;
+ return file.getProject();
+ }
+
+ if (set instanceof ProjectResourceSet)
+ return ((ProjectResourceSet) set).getProject();
+ URIConverter converter = set == null ? null : set.getURIConverter();
+ if (converter != null && converter instanceof WorkbenchURIConverter && ((WorkbenchURIConverter) converter).getOutputContainer() != null)
+ return ((WorkbenchURIConverter) converter).getOutputContainer().getProject();
+ else
+ return null;
+ }
+
+ /**
+ * Remove the list of projects from the list of "referenced projects" in the project's description.
+ *
+ * @param project
+ * @param toBeRemovedProjectList
+ * @throws org.eclipse.core.runtime.CoreException
+ *
+ * @since 1.0.0
+ */
+ public static void removeReferenceProjects(IProject project, List toBeRemovedProjectList) throws org.eclipse.core.runtime.CoreException {
+ IProjectDescription description = project.getDescription();
+ IProject[] projects = description.getReferencedProjects();
+
+ ArrayList projectsList = new ArrayList();
+
+ for (int i = 0; i < projects.length; i++) {
+ projectsList.add(projects[i]);
+ }
+
+ for (int i = 0; i < toBeRemovedProjectList.size(); i++) {
+ projectsList.remove(toBeRemovedProjectList.get(i));
+ }
+
+ IProject[] refProjects = new IProject[projectsList.size()];
+
+ for (int i = 0; i < refProjects.length; i++) {
+ refProjects[i] = (IProject) (projectsList.get(i));
+ }
+
+ description.setReferencedProjects(refProjects);
+ project.setDescription(description, null);
+ }
+
+ /**
+ * Remove the project from the list of "referenced projects" in the description for the given project.
+ *
+ * @param project
+ * @param toBeRemovedProject
+ * @throws org.eclipse.core.runtime.CoreException
+ *
+ * @since 1.0.0
+ */
+ public static void removeReferenceProjects(IProject project, IProject toBeRemovedProject) throws org.eclipse.core.runtime.CoreException {
+ IProjectDescription description = project.getDescription();
+ IProject[] projects = description.getReferencedProjects();
+
+ ArrayList projectsList = new ArrayList();
+
+ for (int i = 0; i < projects.length; i++) {
+ projectsList.add((projects[i]));
+ }
+
+ projectsList.remove(toBeRemovedProject);
+
+ IProject[] refProjects = new IProject[projectsList.size()];
+
+ for (int i = 0; i < refProjects.length; i++) {
+ refProjects[i] = (IProject) (projectsList.get(i));
+ }
+
+ description.setReferencedProjects(refProjects);
+ project.setDescription(description, null);
+ }
+
+ /**
+ * Turn auto-building off.
+ *
+ *
+ * @since 1.0.0
+ */
+ public static void turnAutoBuildOff() {
+ try {
+ IWorkspace workspace = ResourcesPlugin.getWorkspace();
+ IWorkspaceDescription wd = workspace.getDescription();
+ wd.setAutoBuilding(false);
+ workspace.setDescription(wd);
+ } catch (CoreException ce) {
+ //Logger.getLogger().logError(ce);
+ }
+ }
+
+ /**
+ * Turn auto-building on.
+ *
+ *
+ * @since 1.0.0
+ */
+ public static void turnAutoBuildOn() {
+ try {
+ IWorkspace workspace = ResourcesPlugin.getWorkspace();
+ IWorkspaceDescription wd = workspace.getDescription();
+ wd.setAutoBuilding(true);
+ workspace.setDescription(wd);
+ } catch (CoreException ce) {
+ //Logger.getLogger().logError(ce);
+ }
+ }
+
+ /**
+ * Set the auto-building state.
+ *
+ * @param aBoolean
+ * <code>true</code> to turn auto-building on.
+ *
+ * @since 1.0.0
+ */
+ public static void turnAutoBuildOn(boolean aBoolean) {
+ try {
+ IWorkspace workspace = ResourcesPlugin.getWorkspace();
+ IWorkspaceDescription wd = workspace.getDescription();
+ wd.setAutoBuilding(aBoolean);
+ workspace.setDescription(wd);
+ } catch (CoreException ce) {
+ //Logger.getLogger().logError(ce);
+
+ }
+ }
+
+ /**
+ * Adds a builder to the build spec for the given project.
+ *
+ * @param builderID
+ * The id of the builder.
+ * @param project
+ * Project to add to.
+ * @return whether the builder id was actually added (it may have already existed)
+ * @throws CoreException
+ * @since 1.0.0
+ */
+ public static boolean addToBuildSpec(String builderID, IProject project) throws CoreException {
+ return addToBuildSpecBefore(builderID, null, project);
+ }
+
+ /**
+ * Adds a builder to the build spec for the given project, immediately before the specified successor builder.
+ *
+ * @param builderID
+ * The id of the builder.
+ * @param successorID
+ * The id to put the builder before.
+ * @return whether the builder id was actually added (it may have already existed)
+ * @throws CoreException
+ * @since 1.0.0
+ */
+ public static boolean addToBuildSpecBefore(String builderID, String successorID, IProject project) throws CoreException {
+ IProjectDescription description = project.getDescription();
+ ICommand[] commands = description.getBuildSpec();
+ boolean found = false;
+ for (int i = 0; i < commands.length; ++i) {
+ if (commands[i].getBuilderName().equals(builderID)) {
+ found = true;
+ break;
+ }
+ }
+ if (!found) {
+ boolean successorFound = false;
+ ICommand command = description.newCommand();
+ command.setBuilderName(builderID);
+ ICommand[] newCommands = new ICommand[commands.length + 1];
+ for (int j = 0, index = 0; j < commands.length; j++, index++) {
+ if (successorID != null && commands[j].getBuilderName().equals(successorID)) {
+ successorFound = true;
+ newCommands[index++] = command;
+ }
+ newCommands[index] = commands[j];
+ }
+ if (!successorFound)
+ newCommands[newCommands.length - 1] = command;
+ description.setBuildSpec(newCommands);
+ project.setDescription(description, null);
+ }
+ return !found;
+ }
+
+ /**
+ * Remove the builder from the build spec.
+ *
+ * @param builderID
+ * The id of the builder.
+ * @param project
+ * Project to remove from.
+ * @return boolean if the builder id was found and removed
+ * @throws CoreException
+ * @since 1.0.0
+ */
+ public static boolean removeFromBuildSpec(String builderID, IProject project) throws CoreException {
+ IProjectDescription description = project.getDescription();
+ ICommand[] commands = description.getBuildSpec();
+ boolean found = false;
+ for (int i = 0; i < commands.length; ++i) {
+ if (commands[i].getBuilderName().equals(builderID)) {
+ found = true;
+ break;
+ }
+ }
+ if (found) {
+ ICommand[] newCommands = new ICommand[commands.length - 1];
+ int newCount = 0;
+ for (int i = 0; i < commands.length; ++i) {
+ if (!(commands[i].getBuilderName().equals(builderID))) {
+ //Add the existng to the new array
+ newCommands[newCount] = commands[i];
+ newCount++;
+ }
+ }
+
+ description.setBuildSpec(newCommands);
+ project.setDescription(description, null);
+
+ }
+ return found;
+
+ }
+
+ /**
+ * Ensure the container is not read-only.
+ * <p>
+ * For Linux, a Resource cannot be created in a ReadOnly folder. This is only necessary for new files.
+ *
+ * @param resource
+ * workspace resource to make read/write
+ * @since 1.0.0
+ */
+ public static void ensureContainerNotReadOnly(IResource resource) {
+ if (resource != null && !resource.exists()) { //it must be new
+ IContainer container = resource.getParent();
+ ResourceAttributes attr = container.getResourceAttributes();
+ while (attr != null && !attr.isReadOnly()) {
+ container = container.getParent();
+ if (container == null)
+ break;
+ attr = container.getResourceAttributes();
+ }
+ if (container != null && attr != null)
+ attr.setReadOnly(false);
+ }
+ }
+
+ /**
+ * Get projects from primary nature.
+ *
+ * @param natureID
+ * @return All projects that have the given nature id as the first nature id.
+ *
+ * @since 1.0.0
+ */
+ public static IProject[] getProjectsForPrimaryNature(String natureID) {
+ IProject[] projectsWithNature = new IProject[] {};
+ List result = new ArrayList();
+ IProject[] projects = getAllProjects();
+ for (int i = 0; i < projects.length; i++) {
+ if (isProjectPrimaryNature(projects[i], natureID))
+ result.add(projects[i]);
+ }
+ return (IProject[]) result.toArray(projectsWithNature);
+ }
+
+ /**
+ * Get all projects in the workspace
+ *
+ * @return all workspace projects
+ *
+ * @since 1.0.0
+ */
+ public static IProject[] getAllProjects() {
+ return ResourcesPlugin.getWorkspace().getRoot().getProjects();
+ }
+
+ /**
+ * Is this nature id the primary nature id for the project
+ *
+ * @param project
+ * @param natureID
+ * @return <code>true</code> if first nature id for the project.
+ *
+ * @since 1.0.0
+ */
+ public static boolean isProjectPrimaryNature(IProject project, String natureID) {
+ String[] natures = null;
+ try {
+ natures = project.getDescription().getNatureIds();
+ } catch (Exception e1) {
+ }
+ return (natures != null && natures.length > 0 && natures[0].equals(natureID));
+ }
+
+ protected static IPath createPath(IProject p, String defaultSourceName) {
+ IPath path = new Path(p.getName());
+ path = path.append(defaultSourceName);
+ path = path.makeAbsolute();
+ return path;
+ }
+
+ /**
+ * Returns a list of existing files which will be modified if the classpath changes for the given proeject.
+ *
+ * @param p
+ * project
+ * @return list of affected files.
+ *
+ * @since 1.0.0
+ */
+ public static List getFilesAffectedByClasspathChange(IProject p) {
+ List result = new ArrayList(2);
+ addFileIfExists(p, result, DOT_CLASSPATH);
+ addFileIfExists(p, result, DOT_PROJECT);
+ return result;
+ }
+
+ protected static void addFileIfExists(IProject p, List aList, String filename) {
+ IFile aFile = p.getFile(filename);
+ if (aFile != null && aFile.exists())
+ aList.add(aFile);
+ }
+
+ /**
+ * Strip off a leading "/" from each project name in the array, if it has one.
+ *
+ * @param projecNames
+ * @return array of project names with all leading '/' removed.
+ *
+ * @since 1.0.0
+ */
+ public static String[] getProjectNamesWithoutForwardSlash(String[] projecNames) {
+ String[] projNames = new String[projecNames.length];
+ List temp = java.util.Arrays.asList(projecNames);
+ for (int i = 0; i < temp.size(); i++) {
+ String name = (String) (temp.get(i));
+ if (name.startsWith("/")) { //$NON-NLS-1$
+ projNames[i] = name.substring(1, name.length());
+ } else {
+ projNames[i] = name;
+ }
+ }
+ return projNames;
+ }
+
+ protected static URL createFileURL(IPath path) {
+ try {
+ return path.toFile().toURL();
+ } catch (MalformedURLException e) {
+ Logger.getLogger().log(e, Level.WARNING);
+ return null;
+ }
+ }
+
+ /**
+ * Find first newObject that is not in the oldObjects array (using "==").
+ *
+ * @param oldObjects
+ * @param newObjects
+ * @return first newObject not found in oldObjects, or <code>null</code> if all found.
+ *
+ * @since 1.0.0
+ */
+ public static Object getNewObject(Object[] oldObjects, Object[] newObjects) {
+ if (oldObjects != null && newObjects != null && oldObjects.length < newObjects.length) {
+ for (int i = 0; i < newObjects.length; i++) {
+ boolean found = false;
+ Object object = newObjects[i];
+ for (int j = 0; j < oldObjects.length; j++) {
+ if (oldObjects[j] == object) {
+ found = true;
+ break;
+ }
+ }
+ if (!found)
+ return object;
+ }
+ }
+ if (oldObjects == null && newObjects != null && newObjects.length == 1)
+ return newObjects[0];
+ return null;
+ }
+
+ /**
+ * List of all files in the project.
+ * <p>
+ * Note: A more efficient way to do this is to use {@link IResource#accept(org.eclipse.core.resources.IResourceProxyVisitor, int)}
+ *
+ * @param 1.0.0
+ * @return list of files in the project
+ *
+ * @see IResource#accept(org.eclipse.core.resources.IResourceProxyVisitor, int)
+ * @since 1.0.0
+ */
+ public static List getAllProjectFiles(IProject project) {
+ List result = new ArrayList();
+ if (project == null)
+ return result;
+ try {
+ result = collectFiles(project.members(), result);
+ } catch (CoreException e) {
+ }
+ return result;
+ }
+
+ private static List collectFiles(IResource[] members, List result) throws CoreException {
+ // recursively collect files for the given members
+ for (int i = 0; i < members.length; i++) {
+ IResource res = members[i];
+ if (res instanceof IFolder) {
+ collectFiles(((IFolder) res).members(), result);
+ } else if (res instanceof IFile) {
+ result.add(res);
+ }
+ }
+ return result;
+ }
+
+ /**
+ * Get the project.
+ *
+ * @param projectName
+ * @return a IProject given the projectName
+ * @since 1.0.0
+ */
+ public static IProject getProject(String projectName) {
+ return ResourcesPlugin.getWorkspace().getRoot().getProject(projectName);
+ }
+
+ /**
+ * Return whether the given builder name is attached to the project.
+ *
+ * @param project
+ * @param builderName
+ * @return <code>true</code> if builder name is attached to the project.
+ *
+ * @since 1.0.0
+ */
+ public static boolean hasBuilder(IProject project, String builderName) {
+ try {
+ ICommand[] builders = project.getDescription().getBuildSpec();
+ for (int i = 0; i < builders.length; i++) {
+ ICommand builder = builders[i];
+ if (builder != null) {
+ if (builder.getBuilderName().equals(builderName))
+ return true;
+ }
+ }
+ } catch (Exception e) {
+ }
+ return false;
+ }
+}
\ No newline at end of file
diff --git a/plugins/org.eclipse.jem.util/jemutil/org/eclipse/jem/util/emf/workbench/ResourceHandler.java b/plugins/org.eclipse.jem.util/jemutil/org/eclipse/jem/util/emf/workbench/ResourceHandler.java
new file mode 100644
index 0000000..0170780
--- /dev/null
+++ b/plugins/org.eclipse.jem.util/jemutil/org/eclipse/jem/util/emf/workbench/ResourceHandler.java
@@ -0,0 +1,65 @@
+/*******************************************************************************
+ * Copyright (c) 2005 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+/*
+ * $$RCSfile: ResourceHandler.java,v $$
+ * $$Revision: 1.2 $$ $$Date: 2005/02/15 23:04:14 $$
+ */
+package org.eclipse.jem.util.emf.workbench;
+
+import org.eclipse.emf.common.util.URI;
+import org.eclipse.emf.ecore.EObject;
+import org.eclipse.emf.ecore.resource.Resource;
+import org.eclipse.emf.ecore.resource.ResourceSet;
+
+/**
+ * Implementers of this interface are provide extension capabilities on resource set. Such as looking or creating in other resource sets for a
+ * resource or an EObject.
+ *
+ * @see org.eclipse.jem.util.emf.workbench.ProjectResourceSet#add(ResourceHandler)
+ * @since 1.0.0
+ */
+public interface ResourceHandler {
+
+ /**
+ * Each ResourceHandler for a WorkbenchContext (which holds a ProjectResourceSet) will get an oportunity to get the Resource given the uriString
+ * prior to the originatingResourceSet getting it in the normal manner.
+ *
+ * If this handler loaded a Resource in its create(ResourceSet, uriString) then this method should be able to return it as well.
+ *
+ * @param originatingResourceSet
+ * @param uri
+ * @return resource if found or <code>nulll/code> if this handler didn't find it.
+ *
+ * @since 1.0.0
+ */
+ Resource getResource(ResourceSet originatingResourceSet, URI uri);
+
+ /**
+ * Get the EObject for the given URI, if it can. Load the resource if loadOnDemand is <code>true</code>.
+ *
+ * @param originatingResourceSet
+ * @param uri
+ * uri of EObject being requested
+ * @param loadOnDemand
+ * <code>true</code> if resource should be loaded
+ * @return eobject if found or <code>null</code> if not.
+ */
+ EObject getEObjectFailed(ResourceSet originatingResourceSet, URI uri, boolean loadOnDemand);
+
+ /**
+ * Create the resource pointed to be the URI if this handler will handle it.
+ *
+ * @param originatingResourceSet
+ * @param uri
+ * @return resource if created, or <code>null</code> if handler doesn't handle this type.
+ */
+ Resource createResource(ResourceSet originatingResourceSet, URI uri);
+}
\ No newline at end of file
diff --git a/plugins/org.eclipse.jem.util/jemutil/org/eclipse/jem/util/emf/workbench/ResourceSetWorkbenchSynchronizer.java b/plugins/org.eclipse.jem.util/jemutil/org/eclipse/jem/util/emf/workbench/ResourceSetWorkbenchSynchronizer.java
new file mode 100644
index 0000000..1cec597
--- /dev/null
+++ b/plugins/org.eclipse.jem.util/jemutil/org/eclipse/jem/util/emf/workbench/ResourceSetWorkbenchSynchronizer.java
@@ -0,0 +1,192 @@
+/*******************************************************************************
+ * Copyright (c) 2005, 2006 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+/*
+ * $$RCSfile: ResourceSetWorkbenchSynchronizer.java,v $$
+ * $$Revision: 1.4 $$ $$Date: 2006/05/17 20:13:45 $$
+ */
+
+package org.eclipse.jem.util.emf.workbench;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.eclipse.core.resources.*;
+import org.eclipse.emf.ecore.resource.ResourceSet;
+
+import org.eclipse.jem.internal.util.emf.workbench.EMFWorkbenchContextFactory;
+import org.eclipse.jem.util.plugin.JEMUtilPlugin;
+
+
+/**
+ * Synchronizer on the workbench. It listens for the project to see if it is closed or deleted. If it does it notifies this out.
+ *
+ * @since 1.0.0
+ */
+public class ResourceSetWorkbenchSynchronizer implements IResourceChangeListener {
+
+ protected IProject project;
+
+ protected ResourceSet resourceSet;
+
+ /** Extenders that will be notified after a pre build resource change */
+ protected List extenders;
+
+ /** The delta for this project that will be broadcast to the extenders */
+ protected IResourceDelta currentProjectDelta;
+
+ private int currentEventType = -1;
+
+ /**
+ * Constructor taking a resource set and project.
+ *
+ * @param aResourceSet
+ * @param aProject
+ *
+ * @since 1.0.0
+ */
+ public ResourceSetWorkbenchSynchronizer(ResourceSet aResourceSet, IProject aProject) {
+ resourceSet = aResourceSet;
+ project = aProject;
+ if (aResourceSet != null && aResourceSet instanceof ProjectResourceSet)
+ ((ProjectResourceSet) aResourceSet).setSynchronizer(this);
+ initialize();
+ }
+
+ /**
+ * Get the project for this synchronizer
+ *
+ * @return project
+ *
+ * @since 1.0.0
+ */
+ public IProject getProject() {
+ return project;
+ }
+
+ /*
+ * @see IResourceChangeListener#resourceChanged(IResourceChangeEvent)
+ */
+ public void resourceChanged(IResourceChangeEvent event) {
+ currentEventType = event.getType();
+ currentProjectDelta = null;
+ if ((currentEventType == IResourceChangeEvent.PRE_CLOSE || currentEventType == IResourceChangeEvent.PRE_DELETE)
+ && event.getResource().equals(getProject())) {
+ notifyExtendersOfClose();
+ release();
+ }
+ }
+
+
+ protected void notifyExtendersIfNecessary() {
+ if (currentEventType != IResourceChangeEvent.POST_CHANGE || extenders == null || currentProjectDelta == null)
+ return;
+ for (int i = 0; i < extenders.size(); i++) {
+ ISynchronizerExtender extender = (ISynchronizerExtender) extenders.get(i);
+ extender.projectChanged(currentProjectDelta);
+ }
+ }
+
+ protected void notifyExtendersOfClose() {
+ if (extenders != null && !extenders.isEmpty()) {
+ for (int i = 0; i < extenders.size(); i++) {
+ ISynchronizerExtender extender = (ISynchronizerExtender) extenders.get(i);
+ extender.projectClosed();
+ }
+ }
+ }
+
+ protected IWorkspace getWorkspace() {
+ if (getProject() == null)
+ return ResourcesPlugin.getWorkspace();
+ return getProject().getWorkspace();
+ }
+
+ protected void initialize() {
+ getWorkspace().addResourceChangeListener(this,
+ IResourceChangeEvent.PRE_CLOSE | IResourceChangeEvent.PRE_DELETE | IResourceChangeEvent.POST_CHANGE | IResourceChangeEvent.PRE_BUILD);
+ }
+
+ /**
+ * Dispose of the synchronizer. Called when no longer needed.
+ *
+ *
+ * @since 1.0.0
+ */
+ public void dispose() {
+ getWorkspace().removeResourceChangeListener(this);
+ }
+
+ /**
+ * The project is going away so we need to cleanup ourself and the ResourceSet.
+ */
+ protected void release() {
+ if (JEMUtilPlugin.isActivated()) {
+ try {
+ if (resourceSet instanceof ProjectResourceSet)
+ ((ProjectResourceSet) resourceSet).release();
+ } finally {
+ EMFWorkbenchContextFactory.INSTANCE.removeCachedProject(getProject());
+ dispose();
+ }
+ }
+ }
+
+ /**
+ * Add an extender to be notified of events.
+ *
+ * @param extender
+ *
+ * @since 1.0.0
+ */
+ public void addExtender(ISynchronizerExtender extender) {
+ if (extenders == null)
+ extenders = new ArrayList(3);
+ extenders.add(extender);
+ }
+
+ /**
+ * Remove extender from notification of events.
+ *
+ * @param extender
+ *
+ * @since 1.0.0
+ */
+ public void removeExtender(ISynchronizerExtender extender) {
+ if (extenders == null)
+ return;
+ extenders.remove(extender);
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see java.lang.Object#toString()
+ */
+ public String toString() {
+ return getClass().getName() + '(' + ((getProject() != null) ? getProject().getName() : "null") + ')'; //$NON-NLS-1$
+ }
+
+ /**
+ * Tell Synchronizer that a file is about to be saved. This method should be called prior to writing to an IFile from an EMF resource.
+ * <p>
+ * Default does nothing, but subclasses can do something.
+ * </p>
+ *
+ * @param aFile
+ * file about to be saved.
+ *
+ * @since 1.0.0
+ */
+ public void preSave(IFile aFile) {
+ //Default is do nothing
+ }
+
+}
diff --git a/plugins/org.eclipse.jem.util/jemutil/org/eclipse/jem/util/emf/workbench/WorkbenchByteArrayOutputStream.java b/plugins/org.eclipse.jem.util/jemutil/org/eclipse/jem/util/emf/workbench/WorkbenchByteArrayOutputStream.java
new file mode 100644
index 0000000..9d72f51
--- /dev/null
+++ b/plugins/org.eclipse.jem.util/jemutil/org/eclipse/jem/util/emf/workbench/WorkbenchByteArrayOutputStream.java
@@ -0,0 +1,148 @@
+/*******************************************************************************
+ * Copyright (c) 2005 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+/*
+ * $$RCSfile: WorkbenchByteArrayOutputStream.java,v $$
+ * $$Revision: 1.2 $$ $$Date: 2005/02/15 23:04:14 $$
+ */
+package org.eclipse.jem.util.emf.workbench;
+
+import java.io.IOException;
+
+import org.eclipse.core.resources.IFile;
+import org.eclipse.emf.ecore.resource.impl.URIConverterImpl;
+
+/**
+ * ByteArray OutputStream for the Workbench. It works with the synchronizer {@link org.eclipse.jem.util.emf.workbench.ResourceSetWorkbenchSynchronizer}to
+ * notify of a save. It also changes all of the line separators to the current system line separator, i.e. if there are some '\r' and we are on
+ * Windows(R) then they will be converted to '\n\r'), if the setting for the stream is to do eol conversion.
+ *
+ * @since 1.0.0
+ */
+public class WorkbenchByteArrayOutputStream extends URIConverterImpl.PlatformResourceOutputStream {
+
+ private boolean fConvertEOL = false;
+
+ protected ResourceSetWorkbenchSynchronizer synchronizer;
+
+ /**
+ * Construct with an IFile
+ *
+ * @param aFile
+ *
+ * @since 1.0.0
+ */
+ public WorkbenchByteArrayOutputStream(IFile aFile) {
+ this(aFile, null);
+ }
+
+ /**
+ * Construct with a IFile and a synchronizer. This way synchronizer will know when file is about to be saved.
+ *
+ * @param aFile
+ * @param aSynchronizer
+ *
+ * @since 1.0.0
+ */
+ public WorkbenchByteArrayOutputStream(IFile aFile, ResourceSetWorkbenchSynchronizer aSynchronizer) {
+ super(aFile, false, true, null);
+ synchronizer = aSynchronizer;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see java.io.OutputStream#close()
+ */
+ public void close() throws IOException {
+ if (synchronizer != null)
+ synchronizer.preSave(file);
+ super.close();
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.eclipse.emf.ecore.resource.impl.URIConverterImpl.PlatformResourceOutputStream#flush()
+ */
+ public void flush() throws IOException {
+ if (synchronizer != null)
+ synchronizer.preSave(file);
+ super.flush();
+ }
+
+ /*
+ * Convert the end of line characters.
+ */
+ private int convertEOL(byte[] data) {
+ // Algorithm:
+ // Remove all '\r' chars
+ // Replace all '\n' chars with line seperator chars
+
+ String EOL = System.getProperties().getProperty("line.separator"); //$NON-NLS-1$
+ byte[] EOLBytes = EOL.getBytes();
+
+ int out = 0;
+
+ for (int in = 0; in < data.length; in++) {
+ if (data[in] == '\r') {
+ // don't output (ie, throw the char away)
+ } else if (data[in] == '\n') {
+ // The code does not currently handle expanding the array
+ if ((in - out + 1) < EOLBytes.length)
+ throw new UnsupportedOperationException("WorkbenchByteArrayOutputStream: Expanding EOL chars not implemented"); //$NON-NLS-1$
+
+ for (int i = 0; i < EOLBytes.length; i++) {
+ data[out++] = EOLBytes[i];
+ }
+ } else {
+ // Just copy the data
+ data[out++] = data[in];
+ }
+ }
+
+ return out;
+ }
+
+ /**
+ * Is EOL conversion turned on.
+ *
+ * @return <code>true</code> if EOL conversion is turned on.
+ *
+ * @since 1.0.0
+ */
+ public boolean isConvertEOLChars() {
+ return fConvertEOL;
+ }
+
+ /**
+ * Set the EOL conversion flag.
+ *
+ * @param set
+ * <code>true</code> if EOL should be converted to current line separator.
+ *
+ * @since 1.0.0
+ */
+ public void setConvertEOLChars(boolean set) {
+ fConvertEOL = set;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see java.io.ByteArrayOutputStream#toByteArray()
+ */
+ public synchronized byte[] toByteArray() {
+ byte[] contents = super.toByteArray();
+ if (isConvertEOLChars())
+ convertEOL(contents);
+ return contents;
+ }
+}
\ No newline at end of file
diff --git a/plugins/org.eclipse.jem.util/jemutil/org/eclipse/jem/util/emf/workbench/WorkbenchResourceHelperBase.java b/plugins/org.eclipse.jem.util/jemutil/org/eclipse/jem/util/emf/workbench/WorkbenchResourceHelperBase.java
new file mode 100644
index 0000000..f526237
--- /dev/null
+++ b/plugins/org.eclipse.jem.util/jemutil/org/eclipse/jem/util/emf/workbench/WorkbenchResourceHelperBase.java
@@ -0,0 +1,695 @@
+/*******************************************************************************
+ * Copyright (c) 2005 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+/*
+ * $$RCSfile: WorkbenchResourceHelperBase.java,v $$
+ * $$Revision: 1.6 $$ $$Date: 2008/03/12 14:21:39 $$
+ */
+package org.eclipse.jem.util.emf.workbench;
+
+import java.util.*;
+
+import org.eclipse.core.resources.*;
+import org.eclipse.core.runtime.*;
+import org.eclipse.emf.common.util.URI;
+import org.eclipse.emf.common.util.WrappedException;
+import org.eclipse.emf.ecore.*;
+import org.eclipse.emf.ecore.resource.*;
+import org.eclipse.emf.ecore.util.InternalEList;
+
+import org.eclipse.jem.internal.util.emf.workbench.EMFWorkbenchContextFactory;
+import org.eclipse.jem.internal.util.emf.workbench.WorkspaceResourceHandler;
+import org.eclipse.jem.util.plugin.JEMUtilPlugin;
+
+
+/**
+ * Workbench resource helper
+ *
+ * @since 1.0.0
+ */
+public class WorkbenchResourceHelperBase {
+
+ /**
+ * Everything is static, don't know why there is an instance here.
+ */
+ public static final WorkbenchResourceHelperBase INSTANCE = new WorkbenchResourceHelperBase();
+
+ protected static WorkspaceResourceHandler workspaceURILoader = new WorkspaceResourceHandler();
+
+ protected static void resolveContainedProxies(EObject refObject) {
+ List contained = refObject.eContents();
+ EObject mofObject;
+ for (int i = 0; i < contained.size(); i++) {
+ mofObject = (EObject) contained.get(i);
+ resolveProxies(mofObject);
+ }
+ }
+
+ protected static void resolveNonContainedProxies(EObject refObject) {
+ List references = refObject.eClass().getEAllReferences();
+ EReference reference;
+ for (int i = 0; i < references.size(); i++) {
+ reference = (EReference) references.get(i);
+ if (!reference.isContainment()) {
+ if (reference.isMany()) {
+ List value = (List) refObject.eGet(reference);
+ for (int j = 0; j < value.size(); j++)
+ value.get(j);
+ } else {
+ refObject.eGet(reference);
+ }
+ }
+ }
+ }
+
+ /**
+ * Force all of the proxies with <code>resource</code> to be resolved.
+ *
+ * @param resource
+ *
+ * @since 1.0.0
+ */
+ public static void resolveProxies(Resource resource) {
+ if (resource != null) {
+ List topLevels = resource.getContents();
+ EObject mofObject;
+ for (int i = 0; i < topLevels.size(); i++) {
+ mofObject = (EObject) topLevels.get(i);
+ resolveProxies(mofObject);
+ }
+ }
+ }
+
+ /**
+ * Return a List of proxies that are contained by the <code>resource</code>.
+ *
+ * @param resource
+ * @return list of proxies.
+ *
+ * @since 1.0.0
+ */
+ public static List gatherProxies(Resource resource) {
+ if (resource == null)
+ return Collections.EMPTY_LIST;
+ List list = new ArrayList();
+ List topLevels = resource.getContents();
+ int size = topLevels.size();
+ EObject mofObject;
+ for (int i = 0; i < size; i++) {
+ mofObject = (EObject) topLevels.get(i);
+ gatherProxies((InternalEObject) mofObject, list);
+ }
+ return list;
+ }
+
+ protected static void gatherProxies(InternalEObject refObject, List proxies) {
+ if (refObject == null)
+ return;
+ List contains = refObject.eClass().getEAllContainments();
+ if (contains != null) {
+ int size = contains.size();
+ EStructuralFeature sf = null;
+ for (int i = 0; i < size; i++) {
+ sf = (EStructuralFeature) contains.get(i);
+ gatherProxies(refObject, sf, proxies);
+ }
+ }
+ }
+
+ protected static void gatherProxies(InternalEObject refObject, EStructuralFeature sf, List proxies) {
+ Object value = null;
+ InternalEObject proxy = null;
+ if (sf.isMany() || refObject.eIsSet(sf)) {
+ value = refObject.eGet(sf, false);
+ if (value != null) {
+ if (sf.isMany()) {
+ Iterator j = ((InternalEList) value).basicIterator();
+ while (j.hasNext()) {
+ proxy = (InternalEObject) j.next();
+ if (proxy.eIsProxy())
+ proxies.add(proxy);
+ }
+ } else if (((InternalEObject) value).eIsProxy())
+ proxies.add(value);
+ }
+ }
+ }
+
+ protected static void resolveProxies(EObject refObject) {
+ if (refObject != null) {
+ resolveNonContainedProxies(refObject);
+ resolveContainedProxies(refObject);
+ }
+ }
+
+ /**
+ * Return an existing context base on <code>aProject</code>.
+ *
+ * @param aProject
+ * @return the context base for the project or <code>null</code> if none.
+ *
+ * @since 1.0.0
+ */
+ public static EMFWorkbenchContextBase getEMFContext(IProject aProject) {
+ return EMFWorkbenchContextFactory.INSTANCE.getEMFContext(aProject);
+ }
+
+ /**
+ * Create a resource from the URI. The URI must contain the project name, either as the first segment, or if in platform resource url protocol.
+ * {@link #getResourceSet(URI)}
+ *
+ * @param uri
+ * @return a new resource for the uri or <code>null</code> if not a project uri
+ *
+ * @since 1.0.0
+ */
+ public static Resource createResource(URI uri) {
+ ResourceSet set = getResourceSet(uri);
+ if (set != null)
+ return set.createResource(uri);
+ return null;
+ }
+
+ /**
+ * Check for a cached Resource for the given URI, if none is found, create a new Resource for with the URI against the proper ResourceSet.
+ *
+ * @param uri The URI MUST be either a "<b>platform:/resource/</b>project-name/...." type URI or it
+ * must be of type "project-name/...". This method will only return resources that are workbench project resources.
+ * Any other type of URI will cause <code>null</code> to be returned.
+ * @return resource or <code>null</code> if not a project uri.
+ *
+ * @since 1.0.0
+ */
+ public static Resource getExistingOrCreateResource(URI uri) {
+ return getExistingOrCreateResource(uri, getResourceSet(uri));
+ }
+
+ /**
+ * Get the IFile for the URI. The URI must be a workbench project style URI.
+ * @param uri The URI MUST be either a "<b>platform:/resource/</b>project-name/...." type URI or it
+ * must be of type "project-name/...". This method will only return resources that are workbench project resources.
+ * Any other type of URI will cause <code>null</code> to be returned.
+ * @return the IFile if the URI is a project form, <code>null</code> if not a project form, OR the project doesn't exist. The IFile returned doesn't necessarily exist. Use {@link IFile#exists()} to test that.
+ *
+ * @since 1.2.0
+ */
+ public static IFile getIFile(URI uri) {
+ IProject project = getProject(uri);
+ if (project != null) {
+ IPath path;
+ if (isPlatformResourceURI(uri)) {
+ // Need to get the path and remove the first two segments (/resource/project name/).
+ path = new Path(URI.decode(uri.path())).removeFirstSegments(2);
+ } else {
+ // Need to get the path and remove the first segment (/project name/).
+ path = new Path(URI.decode(uri.path())).removeFirstSegments(1);
+ }
+ return project.getFile(path);
+ } else
+ return null;
+ }
+
+ /**
+ * Check for a cached Resource for the given URI, if none is found, create a new Resource for with the URI against the given ResourceSet.
+ *
+ * @param uri
+ * @param set
+ * @return resource or <code>null</code> if set was <code>null</code>.
+ *
+ * @since 1.0.0
+ */
+ public static Resource getExistingOrCreateResource(URI uri, ResourceSet set) {
+ if (set != null) {
+ Resource res = set.getResource(uri, false);
+ if (res == null)
+ res = set.createResource(uri);
+ return res;
+ } else
+ return null;
+ }
+
+ /**
+ * Return a new or existing context base on <code>aProject</code>. Allow the <code>contributor</code> to contribute to the new or existing
+ * nature prior to returning.
+ *
+ * @param aProject
+ * @param contributor
+ * @return the context base for the project.
+ *
+ * @since 1.0.0
+ */
+ public static EMFWorkbenchContextBase createEMFContext(IProject aProject, IEMFContextContributor contributor) {
+ return EMFWorkbenchContextFactory.INSTANCE.createEMFContext(aProject, contributor);
+ }
+
+ /**
+ * Does the passed URI have the form platform:/resource/... ?
+ *
+ * @param uri
+ * @return <code>true</code> if it is a platform resource protocol.
+ *
+ * @since 1.0.0
+ */
+ public static boolean isPlatformResourceURI(URI uri) {
+ return JEMUtilPlugin.PLATFORM_PROTOCOL.equals(uri.scheme()) && JEMUtilPlugin.PLATFORM_RESOURCE.equals(uri.segment(0));
+ }
+
+ /**
+ * This api may be used to cache a Resource if it has a URI that is Workspace relative. Return true if it is cached.
+ *
+ * @param aResource
+ * @return <code>true</code> if it was successful to cache.
+ *
+ * @since 1.0.0
+ */
+ public static boolean cacheResource(Resource aResource) {
+ if (aResource != null) {
+ ResourceSet set = getResourceSet(aResource.getURI());
+ if (set != null)
+ return set.getResources().add(aResource);
+ }
+ return false;
+ }
+
+ /**
+ * This api is used if you create a new MOF resource and you want to add it to the correct ResourceSet. In order to do that, we need the IProject
+ * that you want aResource to be cached within as well as the IPath which is the full path of the location of the new Resource.
+ *
+ * @param aProject
+ * @param aResource
+ * @param fullPath
+ * @return <code>true</code> if resource was cached.
+ *
+ * @since 1.0.0
+ */
+ public static boolean cacheResource(IProject aProject, Resource aResource, IPath fullPath) {
+ if (aProject == null || aResource == null || !aProject.isAccessible())
+ return false;
+ ResourceSet set = getResourceSet(aProject);
+ if (set != null) {
+ URI converted = set.getURIConverter().normalize(aResource.getURI());
+ if (converted != aResource.getURI())
+ aResource.setURI(converted);
+ return set.getResources().add(aResource);
+ }
+ return false;
+ }
+
+ /**
+ * Get the path of the project resource relative to the workspace or relative to the list of containers in this project.
+ *
+ * @param aResource
+ * @return path
+ *
+ * @since 1.0.0
+ */
+ public static String getActualProjectRelativeURI(IResource aResource) {
+ if (aResource == null || !aResource.isAccessible())
+ return null;
+ IProject project = aResource.getProject();
+ IPath path = getPathInProject(project, aResource.getFullPath());
+ return path.makeRelative().toString();
+ }
+
+ /**
+ * Return an IPath that can be used to load a Resource using the <code>fullPath</code>. This will be a project relative path.
+ *
+ * @param project
+ * @param fullPath
+ * @return path
+ *
+ * @since 1.0.0
+ */
+ public static IPath getPathInProject(IProject project, IPath fullPath) {
+ List containers = getProjectURIConverterContainers(project);
+ if (!containers.isEmpty())
+ return getPathFromContainers(containers, fullPath);
+ return fullPath;
+ }
+
+ protected static List getProjectURIConverterContainers(IProject project) {
+ EMFWorkbenchContextBase nature = createEMFContext(project, null);
+ if (nature != null) {
+ WorkbenchURIConverter conv = (WorkbenchURIConverter) nature.getResourceSet().getURIConverter();
+ if (conv != null)
+ return conv.getInputContainers();
+ }
+ return Collections.EMPTY_LIST;
+ }
+
+ /**
+ * If this path is contained within one of the listed containers, then return the path relative to the container.
+ *
+ * @param containers
+ * @param fullPath
+ * @return path relative to a container, or unchanged path if not in a container.
+ *
+ * @since 1.0.0
+ */
+ public static IPath getPathFromContainers(List containers, IPath fullPath) {
+ IContainer container = null;
+ IPath result;
+ int size = containers.size();
+ int matching = -1;
+ IPath containerPath;
+ for (int i = 0; i < size; i++) {
+ container = (IContainer) containers.get(i);
+ containerPath = container.getFullPath();
+ matching = fullPath.matchingFirstSegments(containerPath);
+ if (matching > 0 && matching == containerPath.segmentCount()) {
+ result = fullPath.removeFirstSegments(matching);
+ result = result.makeRelative();
+ return result;
+ }
+ }
+ return fullPath;
+ }
+
+ /**
+ * Return true if the <code>uri</code> has its container segments visible from the input containers for the <code>project</code>.
+ *
+ * @param project
+ * @param uri
+ * @return <code>true</code> if the uri is visible from the input containers.
+ *
+ * @since 1.0.0
+ */
+ public static boolean hasContainerStructure(IProject project, URI uri) {
+ if (project != null && uri != null) {
+ IPath path = new Path(uri.toString());
+ List containers = getProjectURIConverterContainers(project);
+ int segmentCount = path.segmentCount();
+ IPath containerPath = segmentCount > 1 ? path.removeLastSegments(1) : null;
+ IContainer container = null;
+ for (int i = 0; i < containers.size(); i++) {
+ container = (IContainer) containers.get(i);
+ if (!container.isAccessible())
+ continue;
+ if (segmentCount == 1) {
+ if (container == project)
+ return true;
+ } else if (containerPath != null) {
+ IFolder folder = container.getFolder(containerPath);
+ if (folder != null && folder.isAccessible())
+ return true;
+ }
+ }
+ }
+ return false;
+ }
+
+ /**
+ * Get the resource for the uri. The URI MUST be either a "<b>platform:/resource/</b>project-name/...." type URI or it
+ * must be of type "project-name/...". This method will only return resources that are workbench project resources.
+ * Any other type of URI will cause <code>null</code> to be returned. It will be loaded if not already loaded. If it is not to
+ * be loaded if not loaded use {@link #getResource(URI, boolean)} instead.
+ *
+ * @param uri must be either a "<b>platform:/resource/</b>project-name/..." form or it must be "project-name/...". Any other form will be invalid.
+ * @return resource if uri is for a valid workbench project resource or <code>null</code> if project not found or not a valid project resource.
+ *
+ * @throws WrappedException if valid project format URI but file not found or some other error on load.
+ * @since 1.0.0
+ */
+ public static Resource getResource(URI uri) {
+ return getResource(uri, true);
+ }
+
+ /**
+ * Return the Resource for the passed IFile without forcing a load.
+ *
+ * @param aFile
+ * @return
+ *
+ * @since 1.0.0
+ */
+ public static Resource getResource(IFile aFile) {
+ return getResource(aFile, false);
+ }
+
+ /**
+ * Return the Resource for the passed IFile, forcing a load if <code>loadOnDemand</code> says so.
+ *
+ * @param aFile
+ * @param loadOnDemand
+ * <code>true</code> will force a load of resource if not loaded.
+ * @return
+ *
+ * @since 1.0.0
+ */
+ public static Resource getResource(IFile aFile, boolean loadOnDemand) {
+ if (aFile != null)
+ return getResource(URI.createPlatformResourceURI(aFile.getFullPath().toString()), loadOnDemand);
+ return null;
+ }
+
+ /**
+ * Return the Resource for the passed IFile without a load if not loaded.
+ *
+ * @param aFile
+ * @return
+ *
+ * @since 1.0.0
+ */
+ public static Resource load(IFile aFile) {
+ return getResource(aFile, true);
+ }
+
+ /**
+ * Get the resource for the uri. The URI MUST be either a "<b>platform:/resource/</b>project-name/...." type URI or it
+ * must be of type "project-name/...". This method will only return resources that are workbench project resources.
+ * Any other type of URI will cause <code>null</code> to be returned.
+ *
+ * @param uri must be either a "<b>platform:/resource/</b>project-name/..." form or it must be "project-name/...". Any other form will be invalid.
+ * @param loadOnDemand <code>true</code> will cause resource to be loaded if not already loaded.
+ * @return resource if uri is for a valid workbench project resource, or <code>null</code> if project not found, or not a valid project resource uri.
+ *
+ * @throws WrappedException if valid project format URI but file not found or some other error on load if loadOnDemand is true.
+ * @since 1.0.0
+ */
+ public static Resource getResource(URI uri, boolean loadOnDemand) {
+ ResourceSet set = getResourceSet(uri);
+ if (set != null)
+ return set.getResource(uri, loadOnDemand);
+ return null;
+ }
+
+ /**
+ * Return a ResourceSet for the passed URI. The URI should be in the format platform:/resource/{project name}/... or {project name}/... for this
+ * api to work.
+ *
+ * @param uri
+ * @return the resource set or <code>null</code> if not of correct form or project doesn't have a resource set.
+ *
+ * @since 1.0.0
+ */
+ public static ResourceSet getResourceSet(URI uri) {
+ IProject project = getProject(uri);
+ if (project != null && project.isAccessible())
+ return getResourceSet(project);
+ else
+ return null;
+ }
+
+ /*
+ * Get the project for the uri if the uri is a valid workbench project format uri. null otherwise.
+ */
+ private static IProject getProject(URI uri) {
+ String projectName;
+ if (isPlatformResourceURI(uri))
+ projectName = uri.segment(1);
+ else if (uri.scheme() == null) {
+ projectName = new Path(uri.path()).segment(0); //assume project name is first in the URI
+ } else
+ return null;
+ IProject project = getWorkspace().getRoot().getProject(URI.decode(projectName));
+ if (project != null && project.isAccessible())
+ return project;
+ else
+ return null;
+ }
+
+ /**
+ * Return the ResourceSet for the passed IProject.
+ *
+ * @param project
+ * @return resource set
+ */
+ public static ResourceSet getResourceSet(IProject project) {
+ EMFWorkbenchContextBase nat = createEMFContext(project, null);
+ if (nat != null)
+ return nat.getResourceSet();
+ return null;
+ }
+
+ /**
+ * Get the workspace. (just use {@link ResourcesPlugin#getWorkspace()}).
+ *
+ * @return
+ *
+ * @since 1.0.0
+ */
+ public static IWorkspace getWorkspace() {
+ return ResourcesPlugin.getWorkspace();
+ }
+
+ /**
+ * Get the project associated with the resource set.
+ *
+ * @param set
+ * @return project or <code>null</code> if resource set not associated with a project.
+ *
+ * @since 1.0.0
+ */
+ public static IProject getProject(ResourceSet set) {
+ if (set != null) {
+ if (set instanceof ProjectResourceSet) {
+ ProjectResourceSet pset = (ProjectResourceSet) set;
+ return pset.getProject();
+ }
+ }
+ return null;
+ }
+
+ protected static boolean isRegisteredURIMapping(String href) {
+ if (href != null) {
+ String file = href;
+ int index = href.indexOf('#');
+ if (index > -1)
+ file = href.substring(0, index);
+ return URIConverter.URI_MAP.get(file) != null;
+ }
+ return false;
+ }
+
+ /**
+ * Remove all of the resources from the resource set and then unload them. Unload forces all of the objects to become proxies so next resolve will
+ * reload the resource.
+ *
+ * @param resources
+ * @param aSet
+ *
+ * @since 1.0.0
+ */
+ public static void removeAndUnloadAll(List resources, ResourceSet aSet) {
+ if (aSet == null || resources == null || resources.isEmpty())
+ return;
+ aSet.getResources().removeAll(resources);
+ Resource res;
+ for (int i = 0; i < resources.size(); i++) {
+ res = (Resource) resources.get(i);
+ res.unload();
+ }
+ }
+
+ /**
+ * Turn object into a proxy.
+ *
+ * @param anObject
+ * @return <code>true</code> if object was able to become a proxy.
+ *
+ * @since 1.0.0
+ */
+ public static boolean becomeProxy(EObject anObject) {
+ if (anObject != null) {
+ Resource res = anObject.eResource();
+ if (res != null) {
+ URI uri = res.getURI();
+ ((InternalEObject) anObject).eSetProxyURI(uri.appendFragment(res.getURIFragment(anObject)));
+ //anObject.eAdapters().clear();
+ return true;
+ }
+ }
+ return false;
+ }
+
+ /**
+ * Return true if the WrappedException is actually a Resource Not Found.
+ *
+ * @param wrappedEx
+ * @return <code>true</code> is exception wrappers a resource not found.
+ * @since 1.0.0
+ */
+ public static boolean isResourceNotFound(WrappedException wrappedEx) {
+ Exception excep = wrappedEx.exception();
+ while (excep instanceof WrappedException) {
+ excep = ((WrappedException) excep).exception();
+ }
+ return primIsResourceNotFound(excep);
+ }
+
+ private static boolean primIsResourceNotFound(Throwable excep) {
+ if (excep instanceof CoreException) {
+ IStatus status = ((CoreException) excep).getStatus();
+ return status.getCode() == IResourceStatus.RESOURCE_NOT_FOUND && ResourcesPlugin.PI_RESOURCES.equals(status.getPlugin());
+ }
+ return false;
+ }
+
+ /**
+ * Return true if the WrappedException is actually a Resource Not Found.
+ *
+ * @param wrappedEx
+ * @return <code>true</code> is exception wrappers a resource not found.
+ * @since 1.0.0
+ */
+ public static boolean isResourceNotFound(Resource.IOWrappedException wrappedEx) {
+ return primIsResourceNotFound(wrappedEx.getCause());
+ }
+
+ /**
+ * Return a URI represenation of the platformURI without the leading "platform:/resource/" if present.
+ *
+ * @param platformURI
+ * @return uri
+ * @since 1.0.0
+ */
+ public static URI getNonPlatformURI(URI platformURI) {
+ if (isPlatformResourceURI(platformURI)) {
+ String uriString = primGetNonPlatformURIString(platformURI);
+ return URI.createURI(uriString);
+ }
+ return platformURI;
+ }
+
+ /**
+ * Return a String represenation of the platformURI without the leading "platform:/resource/" if present.
+ *
+ * @param platformURI
+ * @return
+ * @since 1.0.0
+ */
+ public static String getNonPlatformURIString(URI platformURI) {
+ if (isPlatformResourceURI(platformURI)) { return primGetNonPlatformURIString(platformURI); }
+ return platformURI.toString();
+ }
+
+ /*
+ * Remove "platform:/resource/" from the front of the platformURI and return the remaining String.
+ */
+ private static String primGetNonPlatformURIString(URI platformURI) {
+ String uriString = platformURI.toString();
+ //"platform:/resource/" is 19 characters.
+ return uriString.substring(19, uriString.length());
+ }
+
+ /**
+ * Does the passed URI have the form platform:/plugin/... ?
+ *
+ * @param uri
+ * @return <code>true</code> if uri is platform plugin protocol.
+ *
+ * @since 1.0.0
+ */
+ public static boolean isPlatformPluginResourceURI(URI uri) {
+ if (uri == null) return false;
+ return JEMUtilPlugin.PLATFORM_PROTOCOL.equals(uri.scheme()) && JEMUtilPlugin.PLATFORM_PLUGIN.equals(uri.segment(0));
+ }
+
+}
\ No newline at end of file
diff --git a/plugins/org.eclipse.jem.util/jemutil/org/eclipse/jem/util/emf/workbench/WorkbenchURIConverter.java b/plugins/org.eclipse.jem.util/jemutil/org/eclipse/jem/util/emf/workbench/WorkbenchURIConverter.java
new file mode 100644
index 0000000..e556851
--- /dev/null
+++ b/plugins/org.eclipse.jem.util/jemutil/org/eclipse/jem/util/emf/workbench/WorkbenchURIConverter.java
@@ -0,0 +1,154 @@
+/*******************************************************************************
+ * Copyright (c) 2005 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+/*
+ * $$RCSfile: WorkbenchURIConverter.java,v $$
+ * $$Revision: 1.2 $$ $$Date: 2005/02/15 23:04:14 $$
+ */
+package org.eclipse.jem.util.emf.workbench;
+
+import java.util.List;
+
+import org.eclipse.core.resources.IContainer;
+import org.eclipse.core.resources.IFile;
+import org.eclipse.core.runtime.IPath;
+import org.eclipse.emf.ecore.resource.URIConverter;
+
+/**
+ * Implementers of this interface are WorkbenchURI converters. Workbench URI converters handle references to files in the project's containers.
+ * This converter is only necessary to resolve old ambiguous workbench URIs.
+ * @since 1.0.0
+ */
+public interface WorkbenchURIConverter extends URIConverter {
+
+ /**
+ * Add input container to to the converter.
+ *
+ * @param aContainer
+ *
+ * @since 1.0.0
+ */
+ void addInputContainer(IContainer aContainer);
+
+ /**
+ * Add list of containers to the converter.
+ *
+ * @param containers
+ * list of <code>IContainer</code>
+ *
+ * @since 1.0.0
+ */
+ void addInputContainers(List containers);
+
+ /**
+ * Get the file relative to a container.
+ *
+ * @param uri
+ * @return file relative to a container or <code>null</code> if not.
+ *
+ * @since 1.0.0
+ */
+ IFile getFile(String uri);
+
+ /**
+ * Get first input container
+ *
+ * @return first input container or <code>null</code> if none set.
+ *
+ * @since 1.0.0
+ */
+ IContainer getInputContainer();
+
+ /**
+ * Get all input containers.
+ *
+ * @return all input containers.
+ *
+ * @since 1.0.0
+ */
+ List getInputContainers();
+
+ /**
+ * Get the output container if set.
+ *
+ * @return output container or <code>null</code> if not set.
+ *
+ * @since 1.0.0
+ */
+ IContainer getOutputContainer();
+
+ /**
+ * Set the output container.
+ *
+ * @param container
+ *
+ * @since 1.0.0
+ */
+ void setOutputContainer(IContainer container);
+
+ /**
+ * Return an IFile for
+ *
+ * @aPath. If we have a parent and we do not contain the first segment of the aPath, forward to the parent to retrieve the file.
+ * @param aPath
+ * @return
+ *
+ * @since 1.0.0
+ */
+ IFile getOutputFile(IPath aPath);
+
+ /**
+ * Get output file with mapping applied.
+ *
+ * @param uri
+ * @return
+ *
+ * @since 1.0.0
+ */
+ IFile getOutputFileWithMappingApplied(String uri);
+
+ /**
+ * Remove input container from list.
+ *
+ * @param aContainer
+ * @return <code>true</code> if removed.
+ *
+ * @since 1.0.0
+ */
+ boolean removeInputContainer(IContainer aContainer);
+
+ /**
+ * Return true if we can retrieve the resource used to open an input stream on.
+ *
+ * @param aFileName
+ * @return <code>true</code> if filename is valid for file stream access.
+ * @since 1.0.0
+ *
+ */
+ boolean canGetUnderlyingResource(String aFileName);
+
+ /**
+ * Is force save relative flag turned on.
+ *
+ * @return <code>true</code> if force save relative is turned on.
+ *
+ * @since 1.0.0
+ */
+ boolean isForceSaveRelative();
+
+ /**
+ * Set to true if you do not want any path manipulation when creating the output stream..
+ *
+ * @param forceSaveRelative
+ * <code>true</code> to force saves as relative.
+ */
+ void setForceSaveRelative(boolean forceSaveRelative);
+
+}
\ No newline at end of file
diff --git a/plugins/org.eclipse.jem.util/jemutil/org/eclipse/jem/util/emf/workbench/WorkbenchURIConverterImpl.java b/plugins/org.eclipse.jem.util/jemutil/org/eclipse/jem/util/emf/workbench/WorkbenchURIConverterImpl.java
new file mode 100644
index 0000000..6365551
--- /dev/null
+++ b/plugins/org.eclipse.jem.util/jemutil/org/eclipse/jem/util/emf/workbench/WorkbenchURIConverterImpl.java
@@ -0,0 +1,514 @@
+/*******************************************************************************
+ * Copyright (c) 2005, 2006 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+/*
+ * $$RCSfile: WorkbenchURIConverterImpl.java,v $$
+ * $$Revision: 1.6 $$ $$Date: 2006/05/17 20:13:45 $$
+ */
+package org.eclipse.jem.util.emf.workbench;
+
+import java.io.*;
+import java.util.ArrayList;
+import java.util.List;
+
+import org.eclipse.core.resources.*;
+import org.eclipse.core.runtime.*;
+import org.eclipse.emf.common.util.URI;
+import org.eclipse.emf.ecore.resource.Resource;
+import org.eclipse.emf.ecore.resource.impl.URIConverterImpl;
+
+import org.eclipse.jem.util.plugin.JEMUtilPlugin;
+
+
+/**
+ * A default implementation of the WorkbenchURIConverter interface.
+ *
+ * @since 1.0.0
+ */
+public class WorkbenchURIConverterImpl extends URIConverterImpl implements WorkbenchURIConverter {
+
+ private final static IWorkspaceRoot WORKSPACE_ROOT = URIConverterImpl.workspaceRoot;
+ private final static String WORKSPACE_ROOT_LOCATION = WORKSPACE_ROOT.getLocation().toString();
+
+ private static final String FILE_PROTOCOL = "file"; //$NON-NLS-1$
+
+ private static final IPath INVALID_PATH = new Path("!!!!~!!!!"); //$NON-NLS-1$
+
+ private static final IFile INVALID_FILE = WORKSPACE_ROOT.getFile(INVALID_PATH.append(INVALID_PATH));
+
+ //Used to avoid trying to fixup the URI when getting the
+ //OutputStream
+ protected boolean forceSaveRelative = false;
+
+ protected List inputContainers;
+
+ protected IContainer outputContainer;
+
+ protected ResourceSetWorkbenchSynchronizer resourceSetSynchronizer;
+
+ /*
+ * KLUDGE: We need to know the meta data area. This is so that any uri that starts with the metadata directory
+ * is considered a file uri and NOT a workspace uri. The metadata is where plugin's store their working data.
+ * It is not part of the workspace root.
+ *
+ * There is no request for simply the metadata area. The log file is in the metadata directory. So we will
+ * get the log file location and just remove the log file name. That should leave us with the metadata directory
+ * only. If Eclipse ever decides to move it from here, this will no longer work. But it hasn't moved in three
+ * versions.
+ *
+ * @since 1.1.0
+ */
+ static protected final String METADATA_LOCATION = Platform.getLogFileLocation().removeLastSegments(1).toString();
+
+ /**
+ * Default converter constructor, no containers.
+ *
+ *
+ * @since 1.0.0
+ */
+ public WorkbenchURIConverterImpl() {
+ super();
+ }
+
+ /**
+ * Construct with an input container.
+ *
+ * @param anInputContainer
+ *
+ * @since 1.0.0
+ */
+ public WorkbenchURIConverterImpl(IContainer anInputContainer) {
+ this(anInputContainer, (ResourceSetWorkbenchSynchronizer) null);
+ }
+
+ /**
+ * Construct with an input container and a synchronzier.
+ *
+ * @param aContainer
+ * @param aSynchronizer
+ *
+ * @since 1.0.0
+ */
+ public WorkbenchURIConverterImpl(IContainer aContainer, ResourceSetWorkbenchSynchronizer aSynchronizer) {
+ this(aContainer, null, aSynchronizer);
+ }
+
+ /**
+ * Construct with an input container and an output container.
+ *
+ * @param anInputContainer
+ * @param anOutputContainer
+ *
+ * @since 1.0.0
+ */
+ public WorkbenchURIConverterImpl(IContainer anInputContainer, IContainer anOutputContainer) {
+ this(anInputContainer, anOutputContainer, null);
+ }
+
+ /**
+ * Construct with an input container, output container, and a synchronizer.
+ *
+ * @param anInputContainer
+ * @param anOutputContainer
+ * @param aSynchronizer
+ *
+ * @since 1.0.0
+ */
+ public WorkbenchURIConverterImpl(IContainer anInputContainer, IContainer anOutputContainer, ResourceSetWorkbenchSynchronizer aSynchronizer) {
+ addInputContainer(anInputContainer);
+ setOutputContainer(anOutputContainer);
+ resourceSetSynchronizer = aSynchronizer;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.eclipse.jem.util.emf.workbench.WorkbenchURIConverter#addInputContainer(org.eclipse.core.resources.IContainer)
+ */
+ public void addInputContainer(IContainer aContainer) {
+ if (aContainer != null && !getInputContainers().contains(aContainer))
+ getInputContainers().add(aContainer);
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.eclipse.jem.util.emf.workbench.WorkbenchURIConverter#addInputContainers(java.util.List)
+ */
+ public void addInputContainers(List containers) {
+ for (int i = 0; i < containers.size(); i++) {
+ addInputContainer((IContainer) containers.get(i));
+ }
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.eclipse.jem.util.emf.workbench.WorkbenchURIConverter#removeInputContainer(org.eclipse.core.resources.IContainer)
+ */
+ public boolean removeInputContainer(IContainer aContainer) {
+ return getInputContainers().remove(aContainer);
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.eclipse.jem.util.emf.workbench.WorkbenchURIConverter#getInputContainers()
+ */
+ public List getInputContainers() {
+ if (inputContainers == null)
+ inputContainers = new ArrayList();
+ return inputContainers;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.eclipse.jem.util.emf.workbench.WorkbenchURIConverter#getInputContainer()
+ */
+ public IContainer getInputContainer() {
+ if (!getInputContainers().isEmpty())
+ return (IContainer) getInputContainers().get(0);
+ else
+ return null;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.eclipse.jem.util.emf.workbench.WorkbenchURIConverter#getOutputContainer()
+ */
+ public IContainer getOutputContainer() {
+ if (outputContainer == null)
+ outputContainer = getInputContainer();
+ return outputContainer;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.eclipse.jem.util.emf.workbench.WorkbenchURIConverter#setOutputContainer(org.eclipse.core.resources.IContainer)
+ */
+ public void setOutputContainer(IContainer newOutputContainer) {
+ outputContainer = newOutputContainer;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.eclipse.jem.util.emf.workbench.WorkbenchURIConverter#getOutputFile(org.eclipse.core.runtime.IPath)
+ */
+ public IFile getOutputFile(IPath aPath) {
+ IFile file = null;
+ if (getOutputContainer() != null) {
+ if (forceSaveRelative)
+ return primGetOutputFile(aPath);
+ file = getOutputFileForPathWithContainerSegments(aPath);
+ if (file != null)
+ return file;
+ else
+ return primGetOutputFile(aPath);
+ }
+ return file;
+ }
+
+ protected IFile primGetOutputFile(IPath aPath) {
+ return primGetFile(getOutputContainer(), aPath);
+ }
+
+ protected IFile getOutputFileForPathWithContainerSegments(IPath aPath) {
+ IContainer out = getOutputContainer();
+ return getFileForPathWithContainerSegments(aPath, out, false);
+ }
+
+ protected IFile getFileForPathWithContainerSegments(IPath aPath, IContainer container, boolean testExists) {
+ IPath containerPath = null;
+ IFile file = null;
+ if (testExists) {
+ containerPath = container.getProjectRelativePath();
+ if (!containerPath.isEmpty()) {
+ file = getFileForMatchingPath(aPath, containerPath, container);
+ if (file != null && file.exists())
+ return file;
+ }
+ }
+ containerPath = container.getFullPath();
+ file = getFileForMatchingPath(aPath, containerPath, container);
+ return file;
+ }
+
+ protected IFile getFileForMatchingPath(IPath containerPath, IPath sourcePath, IContainer container) {
+ int matches = 0;
+ matches = containerPath.matchingFirstSegments(sourcePath);
+ if (matches > 0 && matches == sourcePath.segmentCount()) {
+ IPath loadPath = containerPath.removeFirstSegments(matches);
+ return primGetFile(container, loadPath);
+ }
+ return null;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.eclipse.jem.util.emf.workbench.WorkbenchURIConverter#getFile(java.lang.String)
+ */
+ public IFile getFile(String uri) {
+ return getFile(new Path(uri));
+ }
+
+ /**
+ * Get the file from the path.
+ *
+ * @param path
+ * @return
+ * @see WorkbenchURIConverter#getFile(String)
+ * @since 1.0.0
+ */
+ public IFile getFile(IPath path) {
+ IFile file = null;
+ if (getInputContainer() != null) {
+ path = path.makeRelative();
+ java.util.Iterator it = getInputContainers().iterator();
+ while (it.hasNext()) {
+ IContainer con = (IContainer) it.next();
+ file = getInputFile(con, path);
+ if (file != null && file.exists())
+ return file;
+ }
+ }
+ if (file == null)
+ return INVALID_FILE;
+ return file;
+ }
+
+ /**
+ * Get output file from string path.
+ *
+ * @param uri
+ * @return
+ *
+ * @see WorkbenchURIConverter#getOutputFile(IPath)
+ * @since 1.0.0
+ */
+ public IFile getOutputFile(String uri) {
+ return getOutputFile(new Path(uri));
+ }
+
+ /**
+ * Get the input file from the container and path.
+ *
+ * @param con
+ * @param path
+ * @return
+ *
+ * @since 1.0.0
+ */
+ public IFile getInputFile(IContainer con, IPath path) {
+ IFile file = null;
+ if (WORKSPACE_ROOT.equals(con) && path.segmentCount() < 2)
+ path = INVALID_PATH.append(path);
+ file = primGetFile(con, path);
+ if (file == null || !file.exists())
+ file = getFileForPathWithContainerSegments(path, con, true);
+ return file;
+ }
+
+ protected IFile primGetFile(IContainer container, IPath path) {
+ try {
+ return container.getFile(path);
+ } catch (IllegalArgumentException ex) {
+ }
+ return null;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.eclipse.jem.util.emf.workbench.WorkbenchURIConverter#canGetUnderlyingResource(java.lang.String)
+ */
+ public boolean canGetUnderlyingResource(String aFileName) {
+ IFile file = getFile(aFileName);
+ return file != null && file.exists();
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.eclipse.jem.util.emf.workbench.WorkbenchURIConverter#isForceSaveRelative()
+ */
+ public boolean isForceSaveRelative() {
+ return forceSaveRelative;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.eclipse.jem.util.emf.workbench.WorkbenchURIConverter#setForceSaveRelative(boolean)
+ */
+ public void setForceSaveRelative(boolean forceSaveRelative) {
+ this.forceSaveRelative = forceSaveRelative;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.eclipse.emf.ecore.resource.URIConverter#normalize(org.eclipse.emf.common.util.URI)
+ */public URI normalize(URI uri) {
+ URI result = uri;
+ String fragment = null;
+ if (uri.hasFragment()) {
+ fragment = uri.fragment();
+ result = uri.trimFragment();
+ }
+ result = getInternalURIMap().getURI(result);
+ if (WorkbenchResourceHelperBase.isPlatformResourceURI(result))
+ return appendFragment(result, fragment);
+ if (WorkbenchResourceHelperBase.isPlatformPluginResourceURI(result)) {
+ URI normalized = normalizePluginURI(result, fragment);
+ return (normalized != null) ? normalized : uri;
+ }
+ String protocol = result.scheme();
+ URI fileSearchURI = null;
+ if (protocol == null) {
+ fileSearchURI = normalizeEmptyProtocol(result, fragment);
+ if (fileSearchURI != null)
+ return fileSearchURI;
+ } else if (FILE_PROTOCOL.equals(protocol)) {
+ fileSearchURI = normalizeFileProtocol(result, fragment);
+ if (fileSearchURI != null)
+ return fileSearchURI;
+ } else if (JEMUtilPlugin.WORKSPACE_PROTOCOL.equals(protocol))
+ return normalizeWorkspaceProtocol(result, fragment);
+ return super.normalize(uri);
+ }
+
+ /*
+ * Resolves a plugin format into the actual.
+ */
+ protected URI normalizePluginURI(URI uri, String fragment) {
+ if (uri.segmentCount() < 2)
+ return uri; // Invalid, just let it go on.
+ // See if already normalized.
+ int u_scoreNdx = uri.segment(1).lastIndexOf('_');
+ if (u_scoreNdx != -1) {
+ // Not normalized. Remove the version to make it normalized.
+ String[] segments = uri.segments();
+ segments[1] = segments[1].substring(0, u_scoreNdx);
+ return URI.createHierarchicalURI(uri.scheme(), uri.authority(), uri.device(), segments, uri.query(), fragment);
+ } else
+ return uri;
+ }
+
+ protected URI normalizeWorkspaceProtocol(URI aWorkspaceURI, String fragment) {
+ URI result;
+ String uriString = aWorkspaceURI.toString();
+ uriString = uriString.substring(JEMUtilPlugin.WORKSPACE_PROTOCOL.length() + 1);
+ result = URI.createPlatformResourceURI(uriString);
+ if (fragment != null)
+ result = appendFragment(aWorkspaceURI, fragment);
+ return result;
+ }
+
+ protected URI normalizeEmptyProtocol(URI aFileUri, String fragment) {
+ //Make the relative path absolute and return a platform URI.
+ IPath path = new Path(aFileUri.toString());
+ return normalizeToWorkspaceURI(path, fragment);
+ }
+
+ private URI normalizeToWorkspaceURI(IPath path, String fragment) {
+ URI result = null;
+ IFile file = getFile(path);
+ if (file == null || !file.exists())
+ file = getOutputFile(path);
+ if (file != null) {
+ result = URI.createPlatformResourceURI(file.getFullPath().toString());
+ result = appendFragment(result, fragment);
+ }
+ return result;
+ }
+
+ protected URI normalizeFileProtocol(URI aFileUri, String fragment) {
+ URI result = null;
+ //Make the relative path absolute and return a platform URI.
+ String devicePath = aFileUri.devicePath();
+ //Test for workspace location.
+ if (!devicePath.startsWith(METADATA_LOCATION) &&
+ devicePath.startsWith(WORKSPACE_ROOT_LOCATION) && devicePath.length() > WORKSPACE_ROOT_LOCATION.length()) {
+ //test for workspace location
+ result = normalizeToWorkspaceURI(new Path(devicePath.substring(WORKSPACE_ROOT_LOCATION.length())), fragment);
+ } else if (aFileUri.isRelative()) {
+ result = normalizeToWorkspaceURI(new Path(aFileUri.toString()), fragment);
+ } else {
+ result = aFileUri;
+ }
+ return result;
+ }
+
+ protected URI appendFragment(URI result, String fragment) {
+ if (fragment != null)
+ return result.appendFragment(fragment);
+ else
+ return result;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.eclipse.jem.util.emf.workbench.WorkbenchURIConverter#getOutputFileWithMappingApplied(java.lang.String)
+ */
+ public IFile getOutputFileWithMappingApplied(String uri) {
+ URI converted = getInternalURIMap().getURI(URI.createURI(uri));
+ return getOutputFile(new Path(converted.toString()));
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.eclipse.emf.ecore.resource.impl.URIConverterImpl#createPlatformResourceOutputStream(java.lang.String)
+ */
+ public OutputStream createPlatformResourceOutputStream(String platformResourcePath) throws IOException {
+ IFile file = WORKSPACE_ROOT.getFile(new Path(platformResourcePath));
+ ProjectUtilities.ensureContainerNotReadOnly(file);
+ return new WorkbenchByteArrayOutputStream(file, resourceSetSynchronizer);
+ }
+
+ protected URI getContainerRelativeURI(IFile aFile) {
+ IPath path = WorkbenchResourceHelperBase.getPathFromContainers(inputContainers, aFile.getFullPath());
+ if (path != null)
+ return URI.createURI(path.toString());
+ return null;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.eclipse.emf.ecore.resource.impl.URIConverterImpl#createPlatformResourceInputStream(java.lang.String)
+ */
+ public InputStream createPlatformResourceInputStream(String platformResourcePath) throws IOException {
+ IFile file = WORKSPACE_ROOT.getFile(new Path(platformResourcePath));
+ try {
+ if (!file.isSynchronized(IResource.DEPTH_ONE)) {
+ try {
+ File iofile = file.getFullPath().toFile();
+ if (iofile.exists() || file.exists())
+ file.refreshLocal(IResource.DEPTH_ONE, null);
+ } catch (CoreException ce) {
+ if (ce.getStatus().getCode() != IResourceStatus.WORKSPACE_LOCKED)
+ throw ce;
+ }
+ }
+ // CHANGED from <no-args> to <true> [94015]
+ return file.getContents(true);
+ } catch (CoreException exception) {
+ throw new Resource.IOWrappedException(exception);
+ }
+ }
+
+}
diff --git a/plugins/org.eclipse.jem.util/jemutil/org/eclipse/jem/util/emf/workbench/nature/EMFNature.java b/plugins/org.eclipse.jem.util/jemutil/org/eclipse/jem/util/emf/workbench/nature/EMFNature.java
new file mode 100644
index 0000000..f7f288a
--- /dev/null
+++ b/plugins/org.eclipse.jem.util/jemutil/org/eclipse/jem/util/emf/workbench/nature/EMFNature.java
@@ -0,0 +1,554 @@
+/*******************************************************************************
+ * Copyright (c) 2005 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+/*
+ * $$RCSfile: EMFNature.java,v $$
+ * $$Revision: 1.4 $$ $$Date: 2005/02/15 23:04:14 $$
+ */
+package org.eclipse.jem.util.emf.workbench.nature;
+
+import java.util.*;
+
+import org.eclipse.core.resources.*;
+import org.eclipse.core.runtime.*;
+import org.eclipse.emf.common.util.*;
+import org.eclipse.emf.ecore.resource.Resource;
+import org.eclipse.emf.ecore.resource.ResourceSet;
+import org.eclipse.emf.ecore.xmi.XMLParserPool;
+import org.eclipse.emf.ecore.xmi.impl.XMLParserPoolImpl;
+
+import org.eclipse.jem.internal.util.emf.workbench.nature.EMFNatureRegistry;
+import org.eclipse.jem.util.emf.workbench.*;
+import org.eclipse.jem.util.logger.proxy.Logger;
+
+
+/**
+ * The base EMFNature.
+ * <p>
+ * This is expected to be subclassed by clients, but there are default subclasses available.
+ * </p>
+ *
+ * @since 1.0.0
+ */
+public abstract class EMFNature implements IProjectNature, IEMFContextContributor {
+
+ protected IProject project;
+
+ protected EMFWorkbenchContextBase emfContext;
+
+ protected boolean hasConfigured = false;
+
+ public static XMLParserPool SHARED_PARSER_POOL = new XMLParserPoolImpl();
+
+ public EMFNature() {
+ super();
+ }
+
+ /**
+ * Add the nature id to the project.
+ *
+ * @param proj
+ * @param natureId
+ * @throws CoreException
+ *
+ * @since 1.0.0
+ */
+ protected static void addNatureToProject(IProject proj, String natureId) throws CoreException {
+ ProjectUtilities.addNatureToProject(proj, natureId);
+ }
+
+ /**
+ * Configures the project with this nature. This is called by <code>IProject.addNature</code> and should not be called directly by clients. The
+ * nature extension id is added to the list of natures on the project by <code>IProject.addNature</code>, and need not be added here.
+ *
+ * <p>
+ * All subtypes must call super. The better way for subtypes is to override primConfigure instead.
+ * </p>
+ *
+ * @throws CoreException
+ * @since 1.0.0
+ */
+ public void configure() throws org.eclipse.core.runtime.CoreException {
+ if (!hasConfigured) {
+ hasConfigured = true;
+ primConfigure();
+ }
+ }
+
+ /**
+ * Called from configure the first time configure is called on the nature. Default is do nothing. Subclasses should override and add in their own
+ * configuration.
+ *
+ * @throws org.eclipse.core.runtime.CoreException
+ *
+ * @since 1.0.0
+ */
+ protected void primConfigure() throws org.eclipse.core.runtime.CoreException {
+
+ }
+
+ /**
+ * Create an EMF context for the project.
+ *
+ * @throws CoreException
+ *
+ * @since 1.0.0
+ */
+ protected void createEmfContext() throws CoreException {
+ WorkbenchResourceHelperBase.createEMFContext(getProject(), this);
+ }
+
+ /**
+ * Create a folder relative to the project based on aProjectRelativePathString.
+ *
+ * @param aProjectRelativePathString
+ * @return
+ * @throws CoreException
+ *
+ * @since 1.0.0
+ */
+ public IFolder createFolder(String aProjectRelativePathString) throws CoreException {
+ if (aProjectRelativePathString != null && aProjectRelativePathString.length() > 0)
+ return createFolder(new Path(aProjectRelativePathString));
+ return null;
+ }
+
+ /**
+ * Create a folder relative to the project based on aProjectRelativePathString.
+ *
+ * @param aProjectRelativePath
+ * @return
+ * @throws CoreException
+ *
+ * @since 1.0.0
+ */
+ public IFolder createFolder(IPath aProjectRelativePath) throws CoreException {
+ if (aProjectRelativePath != null && !aProjectRelativePath.isEmpty()) {
+ IFolder folder = getWorkspace().getRoot().getFolder(getProjectPath().append(aProjectRelativePath));
+ if (!folder.exists()) {
+ ProjectUtilities.ensureContainerNotReadOnly(folder);
+ folder.create(true, true, null);
+ }
+ return folder;
+ }
+ return null;
+ }
+
+ /**
+ * Removes this nature from the project, performing any required deconfiguration. This is called by <code>IProject.removeNature</code> and
+ * should not be called directly by clients. The nature id is removed from the list of natures on the project by
+ * <code>IProject.removeNature</code>, and need not be removed here.
+ *
+ * @throws CoreException
+ * @since 1.0.0
+ */
+ public void deconfigure() throws org.eclipse.core.runtime.CoreException {
+ emfContext = null;
+ }
+
+ /**
+ * Return true if the IFile with the given name exists in this project.
+ *
+ * @param aFileName
+ * filename can be relative to one of the input file paths for the WorkbenchURIConverter.
+ * @return <code>true</code> if filename exists in this project
+ *
+ * @since 1.0.0
+ */
+ public boolean fileExists(String aFileName) {
+ if (aFileName == null)
+ return false;
+
+ IPath path = new Path(aFileName);
+ if (path.isAbsolute())
+ return ResourcesPlugin.getWorkspace().getRoot().getFile(path).exists();
+ else
+ return getWorkbenchURIConverter().canGetUnderlyingResource(aFileName);
+ }
+
+ /**
+ * Get the resource set for the project
+ *
+ * @return
+ *
+ * @since 1.0.0
+ */
+ public ResourceSet getResourceSet() {
+ return getEmfContextBase().getResourceSet();
+ }
+
+ /**
+ * Returns the EMF root folder for the project. Defaults to the project. Subclasses can override.
+ *
+ * @return EMF root folder for the project.
+ *
+ * @since 1.0.0
+ */
+ public IContainer getEMFRoot() {
+ return getProject();
+ }
+
+ /**
+ * Used for optimizations; answers whether a mof context for this nature has exists yet
+ *
+ * @deprecated use hasResourceSet();
+ * @since 1.0.0
+ */
+ public boolean hasContext() {
+ return hasResourceSet();
+ }
+
+ /**
+ * Is there a resource set yet for the project.
+ *
+ * @return <code>true</code> if there is a resource set for the project.
+ *
+ * @since 1.0.0
+ */
+ public boolean hasResourceSet() {
+ return emfContext != null && emfContext.hasResourceSet();
+ }
+
+ /**
+ * Lazy initializer; for migration of existing workspaces where configure will never get called.
+ *
+ * @return context base for the project.
+ *
+ * @since 1.0.0
+ */
+ protected EMFWorkbenchContextBase getEmfContextBase() {
+ if (emfContext == null) {
+ try {
+ createEmfContext();
+ } catch (CoreException ex) {
+ Logger.getLogger().logError(ex);
+ }
+ }
+ return emfContext;
+ }
+
+ /**
+ * Get the IFile with the given name if it is in this project.
+ *
+ * @param aFileName
+ * filename can be relative to one of the input file paths for the WorkbenchURIConverter.
+ * @return file it it is in this project, or <code>null</code> if it doesn't.
+ *
+ * @since 1.0.0
+ */
+ public IFile getFile(String aFileName) {
+ return getWorkbenchURIConverter().getFile(aFileName);
+ }
+
+ /**
+ * Return the nature's ID.
+ *
+ * @return nature id
+ *
+ * @since 1.0.0
+ */
+ public abstract String getNatureID();
+
+ /**
+ * Return the ID of the plugin that this nature is contained within.
+ *
+ * @return
+ *
+ * @since 1.0.0
+ */
+ protected abstract String getPluginID();
+
+ /**
+ * Returns the project to which this project nature applies.
+ *
+ * @return the project handle
+ * @since 1.0.0
+ */
+ public org.eclipse.core.resources.IProject getProject() {
+ return project;
+ }
+
+ /**
+ * Return the full path of the project.
+ *
+ * @return full project path (relative to workspace)
+ * @since 1.0.0
+ */
+ public IPath getProjectPath() {
+ return getProject().getFullPath();
+ }
+
+ /**
+ * Get the server property of the project from the supplied key
+ *
+ * @param key
+ * java.lang.String
+ * @deprecated we cannont use persistent properties because they are not stored in the repository
+ * @since 1.0.0
+ */
+ protected String getProjectServerValue(String key) {
+ if (key == null)
+ return null;
+ try {
+ QualifiedName wholeName = qualifiedKey(key);
+ return getProject().getPersistentProperty(wholeName);
+ } catch (CoreException exception) {
+ //If we can't find it assume it is null
+ exception.printStackTrace();
+ return null;
+ }
+ }
+
+ /**
+ * Get WorkbenchURIConverter for this project.
+ * <p>
+ * This method assumes the URIConverter on the ResourceSet is the one that was created for the ResourceSet on behalf of this nature runtime.
+ * </p>
+ *
+ * @return
+ *
+ * @since 1.0.0
+ */
+ protected WorkbenchURIConverter getWorkbenchURIConverter() {
+ return (WorkbenchURIConverter) getResourceSet().getURIConverter();
+ }
+
+ public IWorkspace getWorkspace() {
+ return getProject().getWorkspace();
+ }
+
+ /**
+ * @deprecated use getResource(URI)
+ */
+ public Resource getXmiResource(String uri) {
+ return getResource(URI.createURI(uri));
+ }
+
+ /**
+ * Get the resource for this uri. It will use the resource set of the project to find it. It will load if not already loaded.
+ *
+ * @param uri
+ * @return resource or <code>null</code> if resource is not found.
+ *
+ * @since 1.0.0
+ */
+ public Resource getResource(URI uri) {
+ try {
+ return getResourceSet().getResource(uri, true);
+ } catch (WrappedException ex) {
+ if (!WorkbenchResourceHelperBase.isResourceNotFound(ex))
+ throw ex;
+ }
+ return null;
+ }
+
+ /**
+ * @deprecated use getResourceSet()
+ */
+ public ResourceSet getXmiResourceSet() {
+ return getResourceSet();
+ }
+
+ /**
+ * Make sure that all dependent components are initialized before creating the ResourceSet.
+ */
+ protected void initializeDependentComponents() {
+ //com.ibm.etools.java.init.JavaInit.init();
+ }
+
+ /**
+ * @deprecated use createResource(URI)
+ */
+ public Resource makeXmiResource(String uri) {
+ return createResource(URI.createURI(uri));
+ }
+
+ /**
+ * @deprecated use createResource(URI)
+ */
+ public Resource makeXmiResource(String uri, EList anExtent) {
+ Resource res = makeXmiResource(uri);
+ if (res != null)
+ res.getContents().addAll(anExtent);
+ return res;
+ }
+
+ /**
+ * Create the resource for this uri. It will use the resource set of the project to create it.
+ *
+ * @param uri
+ * @return resource
+ *
+ * @since 1.0.0
+ */
+ public Resource createResource(URI uri) {
+ return getResourceSet().createResource(uri);
+ }
+
+ /*
+ * Return the QualifedValue for key for storage in the repository. The key is qualifed with the package name to avoid collision. @return
+ * QualifedName @param key java.lang.String
+ */
+ private QualifiedName qualifiedKey(String key) {
+ return new QualifiedName(getPluginID(), key);
+ }
+
+ /**
+ * Register the given nature id as an EMFNature.
+ *
+ * @param natureID
+ *
+ * @since 1.0.0
+ */
+ public static void registerNatureID(String natureID) {
+ EMFNatureRegistry.singleton().REGISTERED_NATURE_IDS.add(natureID);
+ }
+
+ /**
+ * Sets the project to which this nature applies. Used when instantiating this project nature runtime. This is called by
+ * <code>IProject.addNature</code> and should not be called directly by clients.
+ *
+ * @param project
+ * the project to which this nature applies
+ *
+ * @since 1.0.0
+ */
+ public void setProject(org.eclipse.core.resources.IProject newProject) {
+ project = newProject;
+ }
+
+ /**
+ * Set the server property of the project from the supplied value
+ *
+ * @param key
+ * java.lang.String
+ * @param value
+ * String
+ * @deprecated we cannont use persistent properties because they are not stored in the repository
+ */
+ protected void setProjectServerValue(String key, String value) {
+ if (key != null) {
+ try {
+ QualifiedName wholeName = qualifiedKey(key);
+ getProject().setPersistentProperty(wholeName, value);
+ } catch (CoreException exception) {
+ //If we can't find it assume it is null
+ exception.printStackTrace();
+ return;
+ }
+ }
+ }
+
+ /**
+ * Shutdown the EMF nature
+ *
+ *
+ * @since 1.0.0
+ */
+ public void shutdown() {
+ if (getResourceSet() != null)
+ ((ProjectResourceSet) getResourceSet()).release();
+ }
+
+ /**
+ * Return a list of EMFNatures based on the natures that have been configured for this project.
+ *
+ * @return List of EMFNatures
+ * @param project
+ * @return list of natures configured for the project.
+ * @since 1.0.0
+ */
+ public static List getRegisteredRuntimes(IProject project) {
+ List result = null;
+ EMFNature nature = null;
+ if (project != null && project.isAccessible()) {
+ String natureID;
+ Iterator it = EMFNatureRegistry.singleton().REGISTERED_NATURE_IDS.iterator();
+ while (it.hasNext()) {
+ natureID = (String) it.next();
+ try {
+ nature = (EMFNature) project.getNature(natureID);
+ } catch (CoreException e) {
+ }
+ if (nature != null) {
+ if (result == null)
+ result = new ArrayList(2);
+ result.add(nature);
+ }
+ }
+ }
+ return result == null ? Collections.EMPTY_LIST : result;
+ }
+
+ /**
+ * Return a list of nature ids based on the natures that have been configured for this project.
+ *
+ * @return list of configured nature ids.
+ * @param project
+ */
+ public static List getRegisteredRuntimeIDs(IProject project) {
+ List result = null;
+ String natureID = null;
+ if (project != null && project.isAccessible()) {
+ Iterator it = EMFNatureRegistry.singleton().REGISTERED_NATURE_IDS.iterator();
+ while (it.hasNext()) {
+ natureID = (String) it.next();
+ try {
+ if (project.hasNature(natureID)) {
+ if (result == null)
+ result = new ArrayList(2);
+ result.add(natureID);
+ }
+ } catch (CoreException e) {
+ }
+ }
+ }
+ return result == null ? Collections.EMPTY_LIST : result;
+ }
+
+ /**
+ * Return if the project has the given nature.
+ *
+ * @param project
+ * @param natureId
+ * @return <code>true</code> if project has given nature
+ *
+ * @since 1.0.0
+ */
+ public static boolean hasRuntime(IProject project, String natureId) {
+ if (project == null || !project.isAccessible())
+ return false;
+ try {
+ return project.hasNature(natureId);
+ } catch (CoreException e) {
+ return false;
+ }
+ }
+
+ /**
+ * Return if the project has any one of the possible given nature ids.
+ *
+ * @param project
+ * @param possibleNatureIds
+ * @return <code>true</code> if at least one of the possible natures id is configured for the project.
+ *
+ * @since 1.0.0
+ */
+ public static boolean hasRuntime(IProject project, String[] possibleNatureIds) {
+ if (project != null) {
+ for (int i = 0; i < possibleNatureIds.length; i++) {
+ if (hasRuntime(project, possibleNatureIds[i]))
+ return true;
+ }
+ }
+ return false;
+ }
+
+}
\ No newline at end of file
diff --git a/plugins/org.eclipse.jem.util/jemutil/org/eclipse/jem/util/logger/proxyrender/AbstractWorkBenchRenderer.java b/plugins/org.eclipse.jem.util/jemutil/org/eclipse/jem/util/logger/proxyrender/AbstractWorkBenchRenderer.java
new file mode 100644
index 0000000..b2c1473
--- /dev/null
+++ b/plugins/org.eclipse.jem.util/jemutil/org/eclipse/jem/util/logger/proxyrender/AbstractWorkBenchRenderer.java
@@ -0,0 +1,472 @@
+/*******************************************************************************
+ * Copyright (c) 2005 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+/*
+
+
+ */
+package org.eclipse.jem.util.logger.proxyrender;
+
+import java.lang.reflect.Field;
+import java.util.logging.Level;
+
+import org.eclipse.core.runtime.*;
+import org.osgi.framework.Bundle;
+
+import org.eclipse.jem.util.logger.proxy.*;
+
+
+/**
+ * Base log renderer that logs to the workbench.
+ *
+ * @since 1.1.0
+ */
+public abstract class AbstractWorkBenchRenderer implements ILogRenderer2 {
+
+ private boolean fTraceMode = false; // will we actually punch trace messaged or not
+
+ private boolean fSettingTrace = false;
+
+ protected Bundle fMyBundle = null;
+
+ protected Logger fMyLogger = null;
+
+ protected ILog fWorkBenchLogger = null;
+
+ /**
+ * Constructer taking a logger.
+ *
+ * @param logger
+ *
+ * @since 1.1.0
+ */
+ public AbstractWorkBenchRenderer(Logger logger) {
+ super();
+ fMyLogger = logger;
+ fTraceMode = fMyLogger.getTraceMode();
+
+ String pluginID = fMyLogger.getPluginID();
+ fMyBundle = Platform.getBundle(pluginID);
+ if (fMyBundle == null)
+ throw new RuntimeException("Invalid Plugin ID"); //$NON-NLS-1$
+
+ fWorkBenchLogger = Platform.getLog(fMyBundle);
+ setTraceMode(fMyLogger.getTraceMode() || isDebugging(fMyBundle));
+ fMyLogger.setRenderer(this);
+ }
+
+ /*
+ * This used to come from the Plugin instance. But in new OSGi, there is not necessarily a Plugin instance. So use the same logic they use.
+ */
+ private boolean isDebugging(Bundle bundle) {
+ String symbolicName = bundle.getSymbolicName();
+ if (symbolicName != null) {
+ String key = symbolicName + "/debug"; //$NON-NLS-1$
+ String value = Platform.getDebugOption(key);
+ return value == null ? false : value.equalsIgnoreCase("true"); //$NON-NLS-1$
+ }
+ return false;
+ }
+
+ /**
+ * Is the console log for eclipse turned on to sysout. If true, then we shouldn't log to console anything already logged because Eclipse would of
+ * logged it for us. This comes from the -Declipse.consoleLog="true" which is the default when starting eclipse from PDE.
+ */
+ protected static final boolean consoleLogOn;
+ static {
+ String consologPropertyName = null;
+ try {
+ // Accessing an internal field, so using reflection. This way if changes in future we won't crash.
+ Class eclipseStarter = Class.forName("org.eclipse.core.runtime.adaptor.EclipseStarter"); //$NON-NLS-1$
+ Field consolelog = eclipseStarter.getDeclaredField("PROP_CONSOLE_LOG"); //$NON-NLS-1$
+ consologPropertyName = (String) consolelog.get(null);
+ } catch (SecurityException e) {
+ } catch (IllegalArgumentException e) {
+ } catch (ClassNotFoundException e) {
+ } catch (NoSuchFieldException e) {
+ } catch (IllegalAccessException e) {
+ }
+ consoleLogOn = consologPropertyName != null && "true".equals(System.getProperty(consologPropertyName)) ; //$NON-NLS-1$
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.eclipse.jem.util.logger.proxy.ILogRenderer#setTraceMode(boolean)
+ */
+ public void setTraceMode(boolean flag) {
+ if (fSettingTrace)
+ return; // Do not allow cycles
+
+ fSettingTrace = true;
+ fTraceMode = flag;
+ fMyLogger.setTraceMode(flag);
+ fSettingTrace = false;
+ }
+
+ // The following methods are for historical renderers in case this has been subclassed outside
+ // of util.
+
+ /**
+ * Log a string to the trace.
+ *
+ * @param param
+ * @return
+ *
+ * @since 1.0.0
+ */
+ public abstract String log(String param);
+
+ /**
+ * Default one that log a string to the trace given a level. Default simply passes it to log(String) so that we don't break old subclasses.
+ * <p>
+ * If loggedToWorkbench is true, then it shouldn't be logged to console if consoleLogOn is true because workbench already logged to console.
+ *
+ * @param msg
+ * @param l
+ *
+ * @since 1.0.0
+ */
+ protected void log(String msg, Level l, boolean loggedToWorkbench) {
+ log(msg);
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.eclipse.jem.util.logger.proxy.ILogRenderer#log(java.lang.String, int)
+ */
+ public String log(String msg, int type) {
+
+ String target = logWorkBench(msg, type);
+ if (fTraceMode || target.equals(NOLOG_DESCRIPTION))
+ return log(msg);
+ else
+ return target;
+ }
+
+ /**
+ * Log to workbench, a string of the given level <code>ILogRenderer.LOG_</code>. levels.
+ *
+ * @param msg
+ * @param type
+ * @return description of the log's destination e.g., <code>CONSOLE_DESCRIPTION</code>
+ *
+ * @see ILogRenderer#LOG_ERROR and all of the other log types.
+ * @see ILogRenderer#CONSOLE_DESCRIPTION
+ * @since 1.0.0
+ */
+ public String logWorkBench(String msg, int type) {
+
+ try {
+ int ErrCode;
+ if (fWorkBenchLogger != null) {
+ switch (type) {
+ case (ILogRenderer.LOG_ERROR):
+ ErrCode = IStatus.ERROR;
+ break;
+ case (ILogRenderer.LOG_WARNING):
+ ErrCode = IStatus.WARNING;
+ break;
+ case (ILogRenderer.LOG_INFO):
+ ErrCode = IStatus.INFO;
+ break;
+ case (ILogRenderer.LOG_TRACE):
+ ErrCode = IStatus.OK;
+ break;
+ default:
+ throw new RuntimeException("Invalid Log Type"); //$NON-NLS-1$
+ }
+ Status status = new Status(ErrCode, fMyBundle.getSymbolicName(), IStatus.OK, msg, null);
+ fWorkBenchLogger.log(status);
+ return WORKBENCH_DESCRIPTION;
+ } else
+ return NOLOG_DESCRIPTION;
+ } catch (Exception t) {
+ return NOLOG_DESCRIPTION;
+ }
+ }
+
+ // Default implentation of the ILogRenderer2 interface.
+ protected boolean isLogging(Level level) {
+ return fTraceMode || fMyLogger.isLoggingLevel(level);
+ }
+
+ private static final int[] STATUS_LEVEL;
+
+ private static final Level[] STATUS_LEVEL_LOOKUP;
+
+ private static final Level[] LEVEL_STATUS;
+
+ static {
+ // Status levels that correspond to the log levels, from finest to none, same indexes as from STATUS_LEVEL_LOOKUP.
+ STATUS_LEVEL_LOOKUP = new Level[] { Level.INFO, Level.WARNING, Level.SEVERE};
+ STATUS_LEVEL = new int[] { IStatus.INFO, IStatus.WARNING, IStatus.ERROR};
+
+ // Levels that correspond to the IStatus levels.
+ int maxID = Math.max(IStatus.OK, Math.max(IStatus.INFO, Math.max(IStatus.WARNING, IStatus.ERROR)));
+ LEVEL_STATUS = new Level[maxID + 1];
+ LEVEL_STATUS[IStatus.OK] = Level.FINE;
+ LEVEL_STATUS[IStatus.INFO] = Level.INFO;
+ LEVEL_STATUS[IStatus.WARNING] = Level.WARNING;
+ LEVEL_STATUS[IStatus.ERROR] = Level.SEVERE;
+ }
+
+ /**
+ * Return the Java Level for the status code from the given IStatus.
+ *
+ * @param status
+ * @return the Java Level
+ *
+ * @since 1.0.0
+ */
+ protected Level getLogLevel(IStatus status) {
+ return LEVEL_STATUS[status.getSeverity()];
+ }
+
+ /**
+ * Return the IStatus status code for the given Java Level.
+ *
+ * @param logLevel
+ * @return the IStatus status code.
+ *
+ * @since 1.0.0
+ */
+ protected int getStatusSeverity(Level logLevel) {
+ for (int i = 0; i < STATUS_LEVEL_LOOKUP.length; i++) {
+ if (STATUS_LEVEL_LOOKUP[i] == logLevel)
+ return STATUS_LEVEL[i];
+ }
+ return IStatus.OK; // Default to ok.
+ }
+
+ /**
+ * Log the string to the workbench for the given level
+ *
+ * @param msg
+ * @param level
+ * @return description of the log's destination e.g., <code>CONSOLE_DESCRIPTION</code>
+ *
+ * @since 1.1.0
+ */
+ protected String logWorkbench(String msg, Level level) {
+ String result = NOLOG_DESCRIPTION;
+ // Test again because we could be here simply due to trace mode, in which case we
+ // don't want to workbench log it.
+ if (fMyLogger.isLoggingLevel(level)) {
+ Platform.getLog(fMyBundle).log(new Status(getStatusSeverity(level), fMyBundle.getSymbolicName(), 0, msg, null));
+ result = WORKBENCH_DESCRIPTION;
+ if (fTraceMode)
+ log(msg, level, true);
+ } else if (fTraceMode)
+ log(msg, level, false);
+ return result;
+ }
+
+ private String getStatusMsg(IStatus s, Level l) {
+ if (s.getException() != null)
+ return fMyLogger.getGenericMsg(s.toString() + fMyLogger.fLineSeperator + fMyLogger.exceptionToString(s.getException()), l);
+ else
+ return fMyLogger.getGenericMsg(s.toString(), l);
+ }
+
+ /**
+ * Log the IStatus to the workbench at the given level.
+ *
+ * @param s
+ * @param level
+ * @return description of the log's destination e.g., <code>CONSOLE_DESCRIPTION</code>
+ *
+ * @since 1.0.0
+ */
+ protected String logWorkbench(IStatus s, Level level) {
+ if (level == DEFAULT)
+ level = getLogLevel(s);
+ String result = NOLOG_DESCRIPTION;
+ // Test again because we could be here simply due to trace mode, in which case we
+ // don't want to workbench log it.
+ if (fMyLogger.isLoggingLevel(level)) {
+ Platform.getLog(fMyBundle).log(s);
+ result = WORKBENCH_DESCRIPTION;
+ if (fTraceMode)
+ log(getStatusMsg(s, level), level, true);
+ } else if (fTraceMode)
+ log(getStatusMsg(s, level), level, false);
+ return result;
+ }
+
+ /**
+ * Log to the workbench the Throwable at the given level.
+ *
+ * @param t
+ * @param level
+ * @return description of the log's destination e.g., <code>CONSOLE_DESCRIPTION</code>
+ *
+ * @since 1.0.0
+ */
+ protected String logWorkbench(Throwable t, Level level) {
+ String result = NOLOG_DESCRIPTION;
+ // Test again because we could be here simply due to trace mode, in which case we
+ // don't want to workbench log it.
+ if (fMyLogger.isLoggingLevel(level)) {
+ Platform.getLog(fMyBundle).log(new Status(getStatusSeverity(level), fMyBundle.getSymbolicName(), 0, "Exception thrown.", t)); //$NON-NLS-1$
+ result = WORKBENCH_DESCRIPTION;
+ if (fTraceMode)
+ log(fMyLogger.getGenericMsg(fMyLogger.exceptionToString(t), level), level, true);
+ } else if (fTraceMode)
+ log(fMyLogger.getGenericMsg(fMyLogger.exceptionToString(t), level), level, false);
+ return result;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.eclipse.jem.util.logger.proxy.ILogRenderer2#log(byte, java.util.logging.Level)
+ */
+ public String log(boolean b, Level level) {
+ if (level == DEFAULT)
+ level = Level.FINEST;
+ if (isLogging(level))
+ return logWorkbench(fMyLogger.getGenericMsg(String.valueOf(b), level), level);
+ else
+ return NOLOG_DESCRIPTION;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.eclipse.jem.util.logger.proxy.ILogRenderer2#log(byte, java.util.logging.Level)
+ */
+ public String log(byte b, Level level) {
+ if (level == DEFAULT)
+ level = Level.FINEST;
+ if (isLogging(level))
+ return logWorkbench(fMyLogger.getGenericMsg(String.valueOf(b), level), level);
+ else
+ return NOLOG_DESCRIPTION;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.eclipse.jem.util.logger.proxy.ILogRenderer2#log(char, java.util.logging.Level)
+ */
+ public String log(char c, Level level) {
+ if (level == DEFAULT)
+ level = Level.FINEST;
+ if (isLogging(level))
+ return logWorkbench(fMyLogger.getGenericMsg(String.valueOf(c), level), level);
+ else
+ return NOLOG_DESCRIPTION;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.eclipse.jem.util.logger.proxy.ILogRenderer2#log(double, java.util.logging.Level)
+ */
+ public String log(double d, Level level) {
+ if (level == DEFAULT)
+ level = Level.FINEST;
+ if (isLogging(level))
+ return logWorkbench(fMyLogger.getGenericMsg(String.valueOf(d), level), level);
+ else
+ return NOLOG_DESCRIPTION;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.eclipse.jem.util.logger.proxy.ILogRenderer2#log(float, java.util.logging.Level)
+ */
+ public String log(float f, Level level) {
+ if (level == DEFAULT)
+ level = Level.FINEST;
+ if (isLogging(level))
+ return logWorkbench(fMyLogger.getGenericMsg(String.valueOf(f), level), level);
+ else
+ return NOLOG_DESCRIPTION;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.eclipse.jem.util.logger.proxy.ILogRenderer2#log(int, java.util.logging.Level)
+ */
+ public String log(int i, Level level) {
+ if (level == DEFAULT)
+ level = Level.FINEST;
+ if (isLogging(level))
+ return logWorkbench(fMyLogger.getGenericMsg(String.valueOf(i), level), level);
+ else
+ return NOLOG_DESCRIPTION;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.eclipse.jem.util.logger.proxy.ILogRenderer2#log(long, java.util.logging.Level)
+ */
+ public String log(long l, Level level) {
+ if (level == DEFAULT)
+ level = Level.FINEST;
+ if (isLogging(level))
+ return logWorkbench(fMyLogger.getGenericMsg(String.valueOf(l), level), level);
+ else
+ return NOLOG_DESCRIPTION;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.eclipse.jem.util.logger.proxy.ILogRenderer2#log(java.lang.Object, java.util.logging.Level)
+ */
+ public String log(Object o, Level level) {
+ if (o instanceof IStatus)
+ return logWorkbench((IStatus) o, level);
+ if (level == DEFAULT)
+ level = Level.FINEST;
+ if (isLogging(level))
+ return logWorkbench(fMyLogger.getGenericMsg(String.valueOf(o), level), level);
+ else
+ return NOLOG_DESCRIPTION;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.eclipse.jem.util.logger.proxy.ILogRenderer2#log(short, java.util.logging.Level)
+ */
+ public String log(short s, Level level) {
+ if (level == DEFAULT)
+ level = Level.FINEST;
+ if (isLogging(level))
+ return logWorkbench(fMyLogger.getGenericMsg(String.valueOf(s), level), level);
+ else
+ return NOLOG_DESCRIPTION;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.eclipse.jem.util.logger.proxy.ILogRenderer2#log(java.lang.Throwable, java.util.logging.Level)
+ */
+ public String log(Throwable t, Level level) {
+ if (t instanceof CoreException)
+ return logWorkbench(((CoreException) t).getStatus(), level);
+ if (level == DEFAULT)
+ level = Level.SEVERE;
+ if (isLogging(level)) {
+ return logWorkbench(t, level);
+ } else
+ return NOLOG_DESCRIPTION;
+ }
+
+}
\ No newline at end of file
diff --git a/plugins/org.eclipse.jem.util/jemutil/org/eclipse/jem/util/logger/proxyrender/ConsoleLogRenderer.java b/plugins/org.eclipse.jem.util/jemutil/org/eclipse/jem/util/logger/proxyrender/ConsoleLogRenderer.java
new file mode 100644
index 0000000..0810e2d
--- /dev/null
+++ b/plugins/org.eclipse.jem.util/jemutil/org/eclipse/jem/util/logger/proxyrender/ConsoleLogRenderer.java
@@ -0,0 +1,67 @@
+/*******************************************************************************
+ * Copyright (c) 2005 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+/*
+
+
+ */
+package org.eclipse.jem.util.logger.proxyrender;
+
+import java.util.logging.Level;
+
+import org.eclipse.jem.util.logger.proxy.ILogRenderer;
+import org.eclipse.jem.util.logger.proxy.Logger;
+
+
+/**
+ * Log renderer to the console.
+ *
+ * @since 1.0.0
+ */
+public class ConsoleLogRenderer extends AbstractWorkBenchRenderer {
+
+ /**
+ * Constructor taking a logger.
+ *
+ * @param logger
+ *
+ * @since 1.0.0
+ */
+ public ConsoleLogRenderer(Logger logger) {
+ super(logger);
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.eclipse.jem.util.logger.proxyrender.AbstractWorkBenchRenderer#log(java.lang.String)
+ */
+ public String log(String msg) {
+
+ System.out.println(msg);
+ return ILogRenderer.CONSOLE_DESCRIPTION;
+
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.eclipse.jem.util.logger.proxyrender.AbstractWorkBenchRenderer#log(java.lang.String, java.util.logging.Level, boolean)
+ */
+ protected void log(String msg, Level l, boolean loggedToWorkbench) {
+ if (!loggedToWorkbench || !consoleLogOn) {
+ if (l == Level.SEVERE)
+ System.err.println(msg);
+ else
+ System.out.println(msg);
+ }
+ }
+
+}
\ No newline at end of file
diff --git a/plugins/org.eclipse.jem.util/jemutil/org/eclipse/jem/util/logger/proxyrender/DefaultPluginTraceRenderer.java b/plugins/org.eclipse.jem.util/jemutil/org/eclipse/jem/util/logger/proxyrender/DefaultPluginTraceRenderer.java
new file mode 100644
index 0000000..0473318
--- /dev/null
+++ b/plugins/org.eclipse.jem.util/jemutil/org/eclipse/jem/util/logger/proxyrender/DefaultPluginTraceRenderer.java
@@ -0,0 +1,113 @@
+/*******************************************************************************
+ * Copyright (c) 2005 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+/*
+
+
+ */
+package org.eclipse.jem.util.logger.proxyrender;
+
+import java.io.*;
+import java.util.logging.Level;
+
+import org.eclipse.core.runtime.Platform;
+
+import org.eclipse.jem.util.logger.proxy.Logger;
+
+
+/**
+ * Logger that also logs to a trace file in the plugin's metadata area.
+ *
+ * @since 1.0.0
+ */
+public class DefaultPluginTraceRenderer extends AbstractWorkBenchRenderer {
+
+ /**
+ * Name of the trace file in the metadata area.
+ *
+ * @since 1.0.0
+ */
+ public static final String PluginTraceFileName = "/.log"; //$NON-NLS-1$
+
+ private String fTraceFile = null;
+
+ private PrintWriter traceFile = null;
+
+ /**
+ * DefaultUILogRenderer constructor.
+ *
+ * @param logger
+ */
+ public DefaultPluginTraceRenderer(Logger logger) {
+ super(logger);
+
+ fTraceFile = Platform.getStateLocation(fMyBundle).toString() + PluginTraceFileName;
+ (new File(fTraceFile)).delete(); // Start from fresh ... do not want to leak on disk space
+
+ }
+
+ private void closeTraceFile() {
+ if (traceFile == null)
+ return;
+ try {
+ traceFile.flush();
+ traceFile.close();
+ } finally {
+ traceFile = null;
+ }
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.eclipse.jem.util.logger.proxyrender.AbstractWorkBenchRenderer#log(java.lang.String)
+ */
+ public String log(String msg) {
+
+ System.out.println(msg);
+
+ openTraceFile();
+ if (traceFile != null) {
+ traceFile.println(msg);
+ closeTraceFile();
+ }
+ return fTraceFile;
+
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.eclipse.jem.util.logger.proxyrender.AbstractWorkBenchRenderer#log(java.lang.String, java.util.logging.Level, boolean)
+ */
+ protected void log(String msg, Level l, boolean loggedToWorkbench) {
+ if (!loggedToWorkbench || !consoleLogOn) {
+ if (l == Level.SEVERE)
+ System.err.println(msg);
+ else
+ System.out.println(msg);
+ }
+
+ openTraceFile();
+ if (traceFile != null) {
+ traceFile.println(msg);
+ closeTraceFile();
+ }
+ }
+
+ private void openTraceFile() {
+ try {
+ traceFile = new PrintWriter(new FileOutputStream(fTraceFile, true));
+ } catch (IOException e) {
+ // there was a problem opening the log file so log to the console
+ traceFile = null;
+ }
+ }
+}
\ No newline at end of file
diff --git a/plugins/org.eclipse.jem.util/jemutil/org/eclipse/jem/util/logger/proxyrender/EclipseLogger.java b/plugins/org.eclipse.jem.util/jemutil/org/eclipse/jem/util/logger/proxyrender/EclipseLogger.java
new file mode 100644
index 0000000..8591267
--- /dev/null
+++ b/plugins/org.eclipse.jem.util/jemutil/org/eclipse/jem/util/logger/proxyrender/EclipseLogger.java
@@ -0,0 +1,123 @@
+/*******************************************************************************
+ * Copyright (c) 2004, 2005 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+/*
+
+
+ */
+package org.eclipse.jem.util.logger.proxyrender;
+
+import java.util.logging.Level;
+
+import org.eclipse.core.runtime.Platform;
+import org.eclipse.core.runtime.Plugin;
+import org.osgi.framework.Bundle;
+
+import org.eclipse.jem.util.logger.proxy.Logger;
+import org.eclipse.jem.util.plugin.JEMUtilPlugin;
+
+
+/**
+ * Get an Eclipse logger. This gets a logger that knows it is for a plugin.
+ *
+ * For each plugin, the following can be specified in the .option file:
+ * {plugin-id}/debug/logTrace
+ * The values valid for this are "true", "false", or "default". If true then loggers will be set into
+ * trace mode. This means everything logged (even those that are filtered out due to not meeting log level)
+ * will be traced out. If the value is "true" they will be traced to the system console.
+ * If it is "default" or not set at all, then it will be the value in the "org.eclipse.jem.util/debug/logTrace" .options setting.
+ * If not set there, then default value will be false.
+ *
+ * {plugin-id}/debug/logTraceFile
+ * The values valid for this are "true", "false", or "default". If true then loggers will trace to
+ * the system console AND to the ".log" file in the plugins work area in the metadata section of the workspace.
+ * If "false" then not traced to a trace file.
+ * If it is "default" or not set at all, then it will be the value in the "org.eclipse.jem.util/debug/logTraceFile" .options setting.
+ * If not set there, then default value will be false.
+ *
+ * {plugin-id}.debug/logLevel
+ * The values valid for this are the names from <code>java.util.logging.Level</code>, and "default". These
+ * are the trace cutoff levels to use. For instance, if the level was SEVERE, then only level SEVERE msgs
+ * are logged. The rest are skipped. Or if the level was WARNING, then only level SEVERE and WARNING are
+ * logged.
+ * If it is "default" or not set at all, then it will be the value in the "org.eclipse.jem.util/debug/logLevel" .options setting.
+ * If not set there, then default value will be WARNING.
+ *
+ *
+ * @since 1.0.0
+ */
+public class EclipseLogger extends Logger {
+
+ public static final String DEBUG_TRACE_OPTION = "/debug/logtrace"; //$NON-NLS-1$
+ public static final String DEBUG_TRACE_FILE_OPTION = "/debug/logtracefile"; //$NON-NLS-1$
+ public static final String DEBUG_LOG_LEVEL_OPTION = "/debug/loglevel"; // The logging level to use when no Hyaedes. (which we don't support at this time). //$NON-NLS-1$
+ public static final String DEFAULT_OPTION = "default"; // If option value is this, then the value from WTP Common plugin options will be used for both logTrace and logLevel. //$NON-NLS-1$
+
+ /**
+ * Return a logger based upon the Plugin.
+ * @param plugin
+ * @return
+ *
+ * @since 1.0.0
+ */
+ public static Logger getEclipseLogger(Plugin plugin) {
+ return getEclipseLogger(plugin.getBundle());
+ }
+
+ /**
+ * Return a logger based upon the bundle.
+ *
+ * @param bundle
+ * @return
+ *
+ * @since 1.0.0
+ */
+ public static Logger getEclipseLogger(Bundle bundle) {
+ String id = bundle.getSymbolicName();
+ Logger logger = getLoggerIfExists(id);
+ if (logger != null)
+ return logger;
+
+ logger = getLogger(id); // Create one, we will now customize it.
+
+ String pluginOption = Platform.getDebugOption(id + DEBUG_TRACE_OPTION);
+ if (pluginOption == null || "default".equalsIgnoreCase(pluginOption)) //$NON-NLS-1$
+ pluginOption = Platform.getDebugOption(JEMUtilPlugin.getDefault().getBundle().getSymbolicName() + DEBUG_TRACE_OPTION);
+ boolean logTrace = "true".equalsIgnoreCase(pluginOption); //$NON-NLS-1$
+
+ pluginOption = Platform.getDebugOption(id + DEBUG_TRACE_FILE_OPTION);
+ if (pluginOption == null || "default".equalsIgnoreCase(pluginOption)) //$NON-NLS-1$
+ pluginOption = Platform.getDebugOption(JEMUtilPlugin.getDefault().getBundle().getSymbolicName() + DEBUG_TRACE_FILE_OPTION);
+ boolean logTraceFile = "true".equalsIgnoreCase(pluginOption); //$NON-NLS-1$
+
+ pluginOption = Platform.getDebugOption(id + DEBUG_LOG_LEVEL_OPTION);
+ if (pluginOption == null || "default".equalsIgnoreCase(pluginOption)) //$NON-NLS-1$
+ pluginOption = Platform.getDebugOption(JEMUtilPlugin.getDefault().getBundle().getSymbolicName() + DEBUG_LOG_LEVEL_OPTION);
+
+ Level logLevel = Level.WARNING;
+ if (pluginOption != null) {
+ try {
+ logLevel = Level.parse(pluginOption);
+ } catch (IllegalArgumentException e) {
+ }
+ }
+
+ if (logTrace)
+ logger.setTraceMode(true);
+ logger.setLevel(logLevel);
+ if (!logTraceFile)
+ logger.setRenderer(new ConsoleLogRenderer(logger));
+ else
+ logger.setRenderer(new DefaultPluginTraceRenderer(logger));
+
+ return logger;
+ }
+
+}
diff --git a/plugins/org.eclipse.jem.util/jemutil/org/eclipse/jem/util/logger/proxyrender/IMsgLogger.java b/plugins/org.eclipse.jem.util/jemutil/org/eclipse/jem/util/logger/proxyrender/IMsgLogger.java
new file mode 100644
index 0000000..58f45d5
--- /dev/null
+++ b/plugins/org.eclipse.jem.util/jemutil/org/eclipse/jem/util/logger/proxyrender/IMsgLogger.java
@@ -0,0 +1,26 @@
+/*******************************************************************************
+ * Copyright (c) 2005 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+/*
+
+
+ */
+package org.eclipse.jem.util.logger.proxyrender;
+
+import org.eclipse.jem.util.logger.proxy.Logger;
+
+/**
+ * Interface for a message logger.
+ *
+ * @since 1.0.0
+ */
+public interface IMsgLogger {
+ public Logger getMsgLogger();
+}
diff --git a/plugins/org.eclipse.jem.util/jemutil/org/eclipse/jem/util/plugin/JEMUtilPlugin.java b/plugins/org.eclipse.jem.util/jemutil/org/eclipse/jem/util/plugin/JEMUtilPlugin.java
new file mode 100644
index 0000000..a7b9b8f
--- /dev/null
+++ b/plugins/org.eclipse.jem.util/jemutil/org/eclipse/jem/util/plugin/JEMUtilPlugin.java
@@ -0,0 +1,399 @@
+/*******************************************************************************
+ * Copyright (c) 2005, 2006 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+/*
+ * $$RCSfile: JEMUtilPlugin.java,v $$
+ * $$Revision: 1.5 $$ $$Date: 2006/05/17 20:13:45 $$
+ */
+package org.eclipse.jem.util.plugin;
+
+import java.io.File;
+import java.text.MessageFormat;
+
+import org.eclipse.core.resources.*;
+import org.eclipse.core.runtime.*;
+import org.eclipse.emf.common.notify.Adapter;
+import org.eclipse.emf.ecore.resource.ResourceSet;
+import org.osgi.framework.Bundle;
+
+import org.eclipse.jem.internal.util.emf.workbench.ProjectResourceSetImpl;
+import org.eclipse.jem.internal.util.emf.workbench.WorkspaceResourceNotifier;
+import org.eclipse.jem.internal.util.emf.workbench.nls.EMFWorkbenchResourceHandler;
+import org.eclipse.jem.util.emf.workbench.ProjectResourceSet;
+import org.eclipse.jem.util.emf.workbench.ResourceHandler;
+import org.eclipse.jem.util.logger.proxy.Logger;
+
+
+/**
+ * Plugin for EMFWorkbench utils.
+ *
+ * @since 1.0.0
+ */
+public class JEMUtilPlugin extends Plugin {
+
+ public static final String ID = "org.eclipse.jem.util"; //$NON-NLS-1$
+
+ /**
+ * Plugin id of this plugin.
+ *
+ * @since 1.0.0
+ */
+ public static final String PLUGIN_ID = ID;
+
+ /**
+ * UI Context extension point.
+ *
+ * @since 1.0.0
+ */
+ public static final String UI_CONTEXT_EXTENSION_POINT = "uiContextSensitiveClass"; //$NON-NLS-1$
+
+ /**
+ * UITester element name.
+ *
+ * @since 1.0.0
+ */
+ public static final String UI_TESTER_EXTENSION_POINT = "uiTester"; //$NON-NLS-1$
+
+ /**
+ * Protocol for workspace
+ *
+ * @since 1.0.0
+ */
+ public static final String WORKSPACE_PROTOCOL = "workspace"; //$NON-NLS-1$
+
+ /**
+ * Protocol for platform uri's. i.e. "platform:/..."
+ *
+ * @since 1.0.0
+ *
+ */
+ public static final String PLATFORM_PROTOCOL = "platform"; //$NON-NLS-1$
+
+ /**
+ * Resource indication in platform protocol. Indicates url is for a resource in the workspace. i.e. "platform:/resource/projectname/..."
+ *
+ * @since 1.0.0
+ */
+ public static final String PLATFORM_RESOURCE = "resource"; //$NON-NLS-1$
+
+ /**
+ * Plugin indication in platform protocol. Indicates url is for a file/directory in the plugins area. i.e. "platform:/plugin/pluginid/..."
+ *
+ * @since 1.0.0
+ */
+ public static final String PLATFORM_PLUGIN = "plugin"; //$NON-NLS-1$
+
+ private static WorkspaceResourceNotifier sharedCache;
+
+ private static ResourceSet pluginResourceSet;
+
+ private static String[] GLOBAL_LOADING_PLUGIN_NAMES;
+
+ private static JEMUtilPlugin DEFAULT;
+
+ public JEMUtilPlugin() {
+ super();
+ DEFAULT = this;
+ }
+
+ /**
+ * Get the workspace. Just use ResourcePlugin.getWorkspace() instead.
+ *
+ * @return
+ *
+ * @since 1.0.0
+ */
+ public static IWorkspace getWorkspace() {
+ return ResourcesPlugin.getWorkspace();
+ }
+
+ /**
+ * Get the plugin instance.
+ *
+ * @return plugin instance.
+ *
+ * @since 1.0.0
+ */
+ public static JEMUtilPlugin getDefault() {
+ return DEFAULT;
+ }
+
+ /**
+ * Gets the sharedCache.
+ * <p>
+ * This is not meant to be called by clients.
+ * </p>
+ *
+ * @return a WorkspaceResourceNotifier
+ * @since 1.0.0
+ */
+ public static WorkspaceResourceNotifier getSharedCache() {
+ if (sharedCache == null)
+ sharedCache = new WorkspaceResourceNotifier();
+ return sharedCache;
+ }
+
+ /**
+ * Sets the sharedCache.
+ * <p>
+ * This is not meant to be called by clients.
+ * </p>
+ *
+ * @param sharedCache
+ * The sharedCache to set
+ * @since 1.0.0
+ */
+ public static void setSharedCache(WorkspaceResourceNotifier aSharedCache) {
+ sharedCache = aSharedCache;
+ }
+
+ /**
+ * @deprecated use createIsolatedResourceSet(IProject)
+ */
+ public static ResourceSet createIsolatedResourceSet() {
+ return null;
+ }
+
+ /**
+ * Add an Adapter. You can use this api to listen for any shared resource being loaded or removed from any ProjectResourceSet in the Workbench
+ * instead of trying to listen to each individual ProjectResourceSet.
+ *
+ * @param adapter
+ *
+ * @since 1.0.0
+ */
+ public static void addWorkspaceEMFResourceListener(Adapter adapter) {
+ if (adapter != null && !getSharedCache().eAdapters().contains(adapter))
+ getSharedCache().eAdapters().add(adapter);
+ }
+
+ /**
+ * Removes the adapter.
+ *
+ * @param adapter
+ *
+ * @see #addWorkspaceEMFResourceListener(Adapter)
+ * @since 1.0.0
+ */
+ public static void removeWorkspaceEMFResourceListener(Adapter adapter) {
+ if (adapter != null)
+ getSharedCache().eAdapters().remove(adapter);
+ }
+
+ /**
+ * Is this plugin active.
+ *
+ * @return <code>true</code> if active
+ *
+ * @since 1.0.0
+ */
+ public static boolean isActivated() {
+ Bundle bundle = Platform.getBundle(ID);
+ if (bundle != null)
+ return bundle.getState() == Bundle.ACTIVE;
+ return false;
+ }
+
+ /**
+ * This method will be called when a WorkbenchContext is instantiated on an EMFNature.
+ * <p>
+ * This not meant to be called by clients.
+ * </p>
+ *
+ * @param aResourceSet
+ *
+ * @see plugin.xml#ResourceHandlerExtension extension point.
+ * @since 1.0.0
+ */
+ public void addExtendedResourceHandlers(ProjectResourceSet aResourceSet) {
+ if (aResourceSet == null)
+ return;
+ IExtensionRegistry registry = Platform.getExtensionRegistry();
+ IExtensionPoint pct = registry.getExtensionPoint(getBundle().getSymbolicName(), "ResourceHandlerExtension"); //$NON-NLS-1$
+ IExtension[] extension = pct.getExtensions();
+ IExtension config;
+ for (int l = 0; l < extension.length; ++l) {
+ config = extension[l];
+ IConfigurationElement[] cElems = config.getConfigurationElements();
+ ResourceHandler handler = null;
+ for (int i = 0; i < cElems.length; i++) {
+ try {
+ handler = (ResourceHandler) cElems[i].createExecutableExtension("run"); //$NON-NLS-1$
+
+ } catch (Exception ex) {
+ handler = null;
+ }
+ if (handler != null)
+ aResourceSet.add(handler);
+ }
+ }
+ }
+
+ /**
+ * Delete the contents of the directory (and the directory if deleteRoot is true).
+ * @param root
+ * @param deleteRoot <code>true</code> to delete the root directory too.
+ * @param monitor
+ * @return <code>true</code> if there was an error deleting anything.
+ *
+ * @since 1.1.0
+ */
+ public static boolean deleteDirectoryContent(File root, boolean deleteRoot, IProgressMonitor monitor) {
+ boolean error = false;
+ if (root.canRead()) {
+ if (root.isDirectory()) {
+ File[] files = root.listFiles();
+ monitor.beginTask(MessageFormat.format(EMFWorkbenchResourceHandler.getString("ProjectUtil_Delete_1"), new Object[] {root.getName()}), files.length+(deleteRoot ? 1 : 0)); //$NON-NLS-1$
+ for (int i = 0; i < files.length; i++) {
+ if (files[i].isDirectory())
+ error |= deleteDirectoryContent(files[i], true, new SubProgressMonitor(monitor, 1));
+ else {
+ error |= !files[i].delete();
+ }
+ monitor.worked(1);
+ }
+ } else {
+ monitor.beginTask(MessageFormat.format(EMFWorkbenchResourceHandler.getString("ProjectUtil_Delete_1"), new Object[] {root.getName()}), 1); //$NON-NLS-1$
+ }
+ if (deleteRoot) {
+ error |= !root.delete();
+ monitor.worked(1);
+ }
+ monitor.done();
+ } else {
+ error = true;
+ }
+ return error;
+ }
+
+ /**
+ * Add a clean resource changelistener.
+ * @param listener
+ * @param eventMask mask of event types to listen for in addition to ones that are necessary for clean. Use 0 if no additional ones.
+ *
+ * @since 1.1.0
+ */
+ public static void addCleanResourceChangeListener(CleanResourceChangeListener listener, int eventMask) {
+ // PRE_BUILD: Handle Clean.
+ // TODO Until https://bugs.eclipse.org/bugs/show_bug.cgi?id=101942 is fixed, we must do POST_BUILD, that will probably be sent because a clean will cause a build to occur which should cause a delta.
+ ResourcesPlugin.getWorkspace().addResourceChangeListener(listener, eventMask | IResourceChangeEvent.POST_BUILD);
+ }
+
+ /**
+ * A resource listener that can be used in addition to listen for Clean requests and process them.
+ * <p>
+ * Use <code>{@link IResourceChangeEvent#PRE_BUILD}</code> when adding as listener to get the
+ * clean events.
+ * <p>
+ * <b>Note</b> : TODO Until https://bugs.eclipse.org/bugs/show_bug.cgi?id=101942 is fixed, you must do POST_BUILD, that will probably be sent because a clean will cause a build to occur which should cause a delta.
+ * @since 1.1.0
+ */
+ public abstract static class CleanResourceChangeListener implements IResourceChangeListener {
+
+ public void resourceChanged(IResourceChangeEvent event) {
+ // Subclasses can override this to handle more events than just clean.
+ if (event.getBuildKind() == IncrementalProjectBuilder.CLEAN_BUILD) {
+ if (event.getSource() instanceof IProject)
+ cleanProject((IProject) event.getSource());
+ else if (event.getSource() instanceof IWorkspace)
+ cleanAll();
+ }
+ }
+
+ /**
+ * Clear out the project.
+ * @param project
+ *
+ * @since 1.1.0
+ */
+ protected abstract void cleanProject(IProject project);
+
+ /**
+ * Clean all.
+ * <p>
+ * By default this will simply call a clean project on each open project. Subclasses should override and either
+ * add more function to clear out non-project data and then call super. Or if they can handle all of the projects
+ * in a faster way, then can completely handle this.
+ *
+ * @since 1.1.0
+ */
+ protected void cleanAll() {
+ IProject[] projects = ResourcesPlugin.getWorkspace().getRoot().getProjects();
+ for (int i = 0; i < projects.length; i++) {
+ IProject project = projects[i];
+ if (project.isOpen()) {
+ cleanProject(project);
+ }
+ }
+ }
+ }
+
+ /**
+ * Get the project resource set for the plugin (there is one for the whole system).
+ *
+ * @return system-wide resource set.
+ * @since 1.0.0
+ */
+ public static ResourceSet getPluginResourceSet() {
+ if (pluginResourceSet == null)
+ pluginResourceSet = new ProjectResourceSetImpl(null);
+ return pluginResourceSet;
+ }
+
+ /**
+ * Set the system-wide resource set.
+ *
+ * @param set
+ * @since 1.0.0
+ */
+ public static void setPluginResourceSet(ResourceSet set) {
+ pluginResourceSet = set;
+ }
+
+ /**
+ * Get the global loading plugin names.
+ * <p>
+ * This is not meant to be called by clients.
+ * </p>
+ *
+ * @return
+ *
+ * @since 1.0.0
+ */
+ public static String[] getGlobalLoadingPluginNames() {
+ if (GLOBAL_LOADING_PLUGIN_NAMES == null)
+ GLOBAL_LOADING_PLUGIN_NAMES = readGlobalLoadingPluginNames();
+ return GLOBAL_LOADING_PLUGIN_NAMES;
+ }
+
+ /**
+ * Get the Logger for this plugin.
+ *
+ * @return logger for this plugin.
+ *
+ * @since 1.0.0
+ */
+ public static Logger getLogger() {
+ return Logger.getLogger(ID);
+ }
+
+ private static String[] readGlobalLoadingPluginNames() {
+ IExtensionRegistry reg = Platform.getExtensionRegistry();
+ IExtensionPoint exPoint = reg.getExtensionPoint(ID, "globalPluginResourceLoad"); //$NON-NLS-1$
+ IExtension[] extensions = exPoint.getExtensions();
+ String[] names = new String[extensions.length];
+ if (extensions.length > 0) {
+ for (int i = 0; i < extensions.length; i++)
+ names[i] = extensions[i].getContributor().getName();
+ }
+ return names;
+ }
+
+}
diff --git a/plugins/org.eclipse.jem.util/org.eclipse.perfmsr.core.stub/.classpath b/plugins/org.eclipse.jem.util/org.eclipse.perfmsr.core.stub/.classpath
new file mode 100644
index 0000000..065ac06
--- /dev/null
+++ b/plugins/org.eclipse.jem.util/org.eclipse.perfmsr.core.stub/.classpath
@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<classpath>
+ <classpathentry kind="src" path="src"/>
+ <classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/>
+ <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
+ <classpathentry kind="output" path="bin"/>
+</classpath>
diff --git a/plugins/org.eclipse.jem.util/org.eclipse.perfmsr.core.stub/.cvsignore b/plugins/org.eclipse.jem.util/org.eclipse.perfmsr.core.stub/.cvsignore
new file mode 100644
index 0000000..c5e82d7
--- /dev/null
+++ b/plugins/org.eclipse.jem.util/org.eclipse.perfmsr.core.stub/.cvsignore
@@ -0,0 +1 @@
+bin
\ No newline at end of file
diff --git a/plugins/org.eclipse.jem.util/org.eclipse.perfmsr.core.stub/.project b/plugins/org.eclipse.jem.util/org.eclipse.perfmsr.core.stub/.project
new file mode 100644
index 0000000..5e29c82
--- /dev/null
+++ b/plugins/org.eclipse.jem.util/org.eclipse.perfmsr.core.stub/.project
@@ -0,0 +1,28 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<projectDescription>
+ <name>org.eclipse.perfmsr.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/plugins/org.eclipse.jem.util/org.eclipse.perfmsr.core.stub/PERFMSR.README.txt b/plugins/org.eclipse.jem.util/org.eclipse.perfmsr.core.stub/PERFMSR.README.txt
new file mode 100644
index 0000000..3186a36
--- /dev/null
+++ b/plugins/org.eclipse.jem.util/org.eclipse.perfmsr.core.stub/PERFMSR.README.txt
@@ -0,0 +1,14 @@
+This is a stub plugin for perfmsr. It is here just so that org.eclipse.jem.util can compile.
+
+It should not be an open project during normal usage. Whenever any of the files in this project
+are changed, "perfmsr.jardesc" should be used to create the new changed appropriate jar. Do this by:
+
+1) Select perfmsr.jardesc
+2) On popup menu select "Create JAR"
+3) Hit "Finish"
+4) Commit all changes to CVS.
+5) Go to org.eclipse.jem.util project, select the org.eclipse.perfmsr.core.stub folder
+ and select Replace->Latest from HEAD. This will cause your just committed changes
+ from step 4 to be put into org.eclipse.jem.util and will be picked up for that
+ plugin to compile against.
+6) Either close or delete the org.eclipse.perfmsr.core.stuf project from the workspace.
\ No newline at end of file
diff --git a/plugins/org.eclipse.jem.util/org.eclipse.perfmsr.core.stub/about.html b/plugins/org.eclipse.jem.util/org.eclipse.perfmsr.core.stub/about.html
new file mode 100644
index 0000000..f9f238e
--- /dev/null
+++ b/plugins/org.eclipse.jem.util/org.eclipse.perfmsr.core.stub/about.html
@@ -0,0 +1,32 @@
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN">
+<html>
+<head>
+<title>About</title>
+<meta http-equiv=Content-Type content="text/html; charset=ISO-8859-1">
+</head>
+<body lang="EN-US">
+<h2>About This Content</h2>
+
+<p>30th March, 2004</p>
+<h3>License</h3>
+<p>Eclipse.org makes available all content in this plug-in ("Content"). Unless otherwise indicated below, the Content is provided to you under the terms and conditions of the
+Eclipse Public License Version 1.0 ("EPL"). A copy of the EPL is 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>
+
+<h3>Contributions</h3>
+
+<p>If this Content is licensed to you under the terms and conditions of the EPL, any Contributions, as defined in the EPL, uploaded, submitted, or otherwise
+made available to Eclipse.org, members of Eclipse.org and/or the host of Eclipse.org web site, by you that relate to such
+Content are provided under the terms and conditions of the EPL and can be made available to others under the terms of the EPL.</p>
+
+<p>If this Content is licensed to you under license terms and conditions other than the EPL ("Other License"), any modifications, enhancements and/or
+other code and/or documentation ("Modifications") uploaded, submitted, or otherwise made available to Eclipse.org, members of Eclipse.org and/or the
+host of Eclipse.org, by you that relate to such Content are provided under terms and conditions of the Other License and can be made available
+to others under the terms of the Other License. In addition, with regard to Modifications for which you are the copyright holder, you are also
+providing the Modifications under the terms and conditions of the EPL and such Modifications can be made available to others under the terms of
+the EPL.</p>
+
+<p><b>Version:</b> v20040624a
+
+</body>
+</html>
\ No newline at end of file
diff --git a/plugins/org.eclipse.jem.util/org.eclipse.perfmsr.core.stub/build.properties b/plugins/org.eclipse.jem.util/org.eclipse.perfmsr.core.stub/build.properties
new file mode 100644
index 0000000..3a4db57
--- /dev/null
+++ b/plugins/org.eclipse.jem.util/org.eclipse.perfmsr.core.stub/build.properties
@@ -0,0 +1,14 @@
+###############################################################################
+# Copyright (c) 2003, 2005 IBM Corporation 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:
+# IBM Corporation - initial API and implementation
+###############################################################################
+bin.includes = plugin.xml,\
+ plugin.properties,\
+ *.jar
+source.perfmsr.jar = src/
diff --git a/plugins/org.eclipse.jem.util/org.eclipse.perfmsr.core.stub/perfmsr.jar b/plugins/org.eclipse.jem.util/org.eclipse.perfmsr.core.stub/perfmsr.jar
new file mode 100644
index 0000000..1ebba8f
--- /dev/null
+++ b/plugins/org.eclipse.jem.util/org.eclipse.perfmsr.core.stub/perfmsr.jar
Binary files differ
diff --git a/plugins/org.eclipse.jem.util/org.eclipse.perfmsr.core.stub/perfmsr.jardesc b/plugins/org.eclipse.jem.util/org.eclipse.perfmsr.core.stub/perfmsr.jardesc
new file mode 100644
index 0000000..d48e223
--- /dev/null
+++ b/plugins/org.eclipse.jem.util/org.eclipse.perfmsr.core.stub/perfmsr.jardesc
@@ -0,0 +1,14 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<jardesc>
+ <jar path="org.eclipse.perfmsr.core.stub/perfmsr.jar"/>
+ <options buildIfNeeded="true" compress="true" descriptionLocation="/org.eclipse.perfmsr.core.stub/perfmsr.jardesc" exportErrors="true" exportWarnings="true" overwrite="false" saveDescription="true" useSourceFolders="false"/>
+ <manifest generateManifest="true" manifestLocation="/VEScrapProject/MANIFEST.mf" manifestVersion="1.0" reuseManifest="false" saveManifest="false" usesManifest="true">
+ <sealing sealJar="false">
+ <packagesToSeal/>
+ <packagesToUnSeal/>
+ </sealing>
+ </manifest>
+ <selectedElements exportClassFiles="true" exportJavaFiles="true" exportOutputFolder="false">
+ <javaElement handleIdentifier="=org.eclipse.perfmsr.core.stub/src"/>
+ </selectedElements>
+</jardesc>
diff --git a/plugins/org.eclipse.jem.util/org.eclipse.perfmsr.core.stub/plugin.properties b/plugins/org.eclipse.jem.util/org.eclipse.perfmsr.core.stub/plugin.properties
new file mode 100644
index 0000000..5720eeb
--- /dev/null
+++ b/plugins/org.eclipse.jem.util/org.eclipse.perfmsr.core.stub/plugin.properties
@@ -0,0 +1,12 @@
+###############################################################################
+# Copyright (c) 2003, 2005 IBM Corporation 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:
+# IBM Corporation - initial API and implementation
+###############################################################################
+Plugin.name=Performance Monitor
+
diff --git a/plugins/org.eclipse.jem.util/org.eclipse.perfmsr.core.stub/plugin.xml b/plugins/org.eclipse.jem.util/org.eclipse.perfmsr.core.stub/plugin.xml
new file mode 100644
index 0000000..596926d
--- /dev/null
+++ b/plugins/org.eclipse.jem.util/org.eclipse.perfmsr.core.stub/plugin.xml
@@ -0,0 +1,17 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<?eclipse version="3.0"?>
+<plugin
+ id="org.eclipse.perfmsr.core"
+ name="%Plugin.name"
+ version="3.0.0"
+ provider-name="Eclipse.org"
+ class="org.eclipse.perfmsr.core.PerfMsrCorePlugin">
+
+ <runtime>
+ <library name="perfmsr.jar"><export name="*"/></library>
+ </runtime>
+
+ <requires>
+ <import plugin="org.eclipse.core.runtime"/>
+ </requires>
+</plugin>
diff --git a/plugins/org.eclipse.jem.util/org.eclipse.perfmsr.core.stub/src/org/eclipse/perfmsr/core/IPerformanceMonitor.java b/plugins/org.eclipse.jem.util/org.eclipse.perfmsr.core.stub/src/org/eclipse/perfmsr/core/IPerformanceMonitor.java
new file mode 100644
index 0000000..bd992c7
--- /dev/null
+++ b/plugins/org.eclipse.jem.util/org.eclipse.perfmsr.core.stub/src/org/eclipse/perfmsr/core/IPerformanceMonitor.java
@@ -0,0 +1,195 @@
+/*******************************************************************************
+ * Copyright (c) 2003, 2005 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.perfmsr.core;
+
+/**
+ * Take snapshots of the various performance counters.
+ * ************* This is just a stub of the real interface to get org.eclipse.jem.util
+ * to compile. It is not usable by itself. ****************************
+ */
+public interface IPerformanceMonitor
+{
+ /**
+ * These constants control how much information is gathered for a particular snapshot.
+ * They are or'ed together and passed into the snapshot method.
+ */
+ interface Types
+ {
+ /**
+ * 1 - Write out the performance counters from the operating system. These
+ * include working set, peak working set, elapsed time, user time, and
+ * kernel time.
+ */
+ int OperatingSystemCounters = 1;
+
+ /**
+ * 2 - Write out the global performance info. This includes things like the total
+ * committed memory for the entire system.
+ *
+ * This function depends on the GetPerformanceInfo() function being available in
+ * the Windows psapi.dll. This is available in XP but is usually not available
+ * in Win/2000. If it is not available then this function throws an UnsupportedOperationException.
+ */
+ int GlobalSystemCounters = 2;
+
+ /**
+ * 4 - Write out the size of the Java Heap.
+ */
+ int JavaHeapSize = 4;
+
+ /**
+ * 8 - Write out how much of the Java heap is being used. This calls the
+ * garbage collector so it may skew timing results.
+ */
+ int JavaHeapUsed = 8;
+
+ /**
+ * 16 - The plugin startup and size information.
+ */
+ int PluginInfo = 16;
+
+ /** 0xffff - Everything. */
+ int All = 0xffff;
+ }
+
+ /**
+ * Add some more "extra" variations.
+ *
+ * The variations that are in effect are made up of these extra variations plus any variations
+ * that may have been set with the setVar() method.
+ *
+ * @param varList a comma separated list of variations
+ */
+ public void addVarAppend(String varList);
+
+ /**
+ * Set the driver name.
+ *
+ * @param driver a label that identifies the driver that is being tested. If it is a WSAD
+ * driver, this will usually be set by the extension.
+ */
+ public void setDriver(String driver);
+
+ /**
+ * Set the location of the performance measurement file, that is the place where
+ * the measurements are stored.
+ *
+ * @param logFile the file name of where the log should be written. Usually this is fully qualified
+ * path name. For example "x:\logs\timer.xml".
+ */
+ public void setLogFile(String logFile);
+
+ /**
+ * Set the performance monitor to be on or off. If it is off then most of the other
+ * operations will no-op.
+ *
+ * The default is for the performance monitor to be off unless it's special environment variable is set.
+ * When called from the UI, the UI should call this to make sure that it is on.
+ */
+ public void setIsOn(boolean isOn);
+
+ /**
+ * Sets the test case number for this measurement run.
+ *
+ * @param testd test case identifier
+ */
+ public void setTestd(int testd);
+
+ /**
+ * Sets the test case name. If will cause a new test case to be created if it does not already exist.
+ *
+ * @param testName a simple (short) test case name. In the case of JUnit test cases, it would usually
+ * be the JUnit name.
+ */
+ public void setTestName(String testName);
+
+ /**
+ * Set the variations that are in effect.
+ *
+ * @param var a comma delimited string of variation numbers
+ */
+ public void setVar(String var);
+
+ /**
+ * Set the upload host
+ *
+ * @param host DNS name of the upload host
+ */
+ public void setUploadHost(String host);
+
+ /**
+ * Set the upload port
+ *
+ * @param port upload port
+ */
+ public void setUploadPort(int port);
+
+ /**
+ * Set the upload userid
+ *
+ * @param userid
+ */
+ public void setUploadUserid(String userid);
+
+ /**
+ * Take a snapshot of some default performance measurements.
+ *
+ * @param step this identifies the step that the snapshot is for
+ */
+ void snapshot(int step);
+
+ /**
+ * Take a snapshot of the selected performance measurements.
+ *
+ * @param step this identifies the step that the snapshot is for
+ *
+ * @param types This controls which measurements are selected. It is an or'd together
+ * list of the IPerformanceMonitor.Types constants.
+ *
+ * @see IPerformanceMonitor.Types
+ */
+ void snapshot(int step, int types);
+
+ /**
+ * Write the comment to the performance measurement file.
+ *
+ * @param comment
+ */
+ void writeComment(String comment);
+
+ /**
+ * Upload the results to the server. This causes the file to be
+ * closed, and the monitor to be placed into the finished state.
+ *
+ * This method can only be called if the uploadhost, uploadport and uploaduserid
+ * have been configured before hand.
+ *
+ * @param description an optional description (it can be null)
+ *
+ * @return some status information
+ */
+ public Upload.Status upload(String description);
+//
+// /**
+// * Upload the results to the server. This causes the file to be
+// * closed, and the monitor to be placed into the finished state.
+// *
+// * @param host the host name that the file is being sent to
+// * @param port the port on the host
+// * @param userid the userid that is doing the upload
+// * @param description an optional description (it can be null)
+// *
+// * @return some status information
+// */
+// Upload.Status upload(String host, int port, String userid, String description);
+
+
+}
diff --git a/plugins/org.eclipse.jem.util/org.eclipse.perfmsr.core.stub/src/org/eclipse/perfmsr/core/PerfMsrCorePlugin.java b/plugins/org.eclipse.jem.util/org.eclipse.perfmsr.core.stub/src/org/eclipse/perfmsr/core/PerfMsrCorePlugin.java
new file mode 100644
index 0000000..655ba2a
--- /dev/null
+++ b/plugins/org.eclipse.jem.util/org.eclipse.perfmsr.core.stub/src/org/eclipse/perfmsr/core/PerfMsrCorePlugin.java
@@ -0,0 +1,31 @@
+/*******************************************************************************
+ * Copyright (c) 2005 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+/*
+
+
+ */
+package org.eclipse.perfmsr.core;
+
+import org.eclipse.core.runtime.Plugin;
+
+
+/**
+ * ************* This is just a stub of the real class to get org.eclipse.jem.util
+ * to compile. It is not usable by itself. ****************************
+ * @since 1.0.0
+ */
+public class PerfMsrCorePlugin extends Plugin {
+
+ public static IPerformanceMonitor getPerformanceMonitor(boolean bool) {
+ return null;
+ }
+
+}
diff --git a/plugins/org.eclipse.jem.util/org.eclipse.perfmsr.core.stub/src/org/eclipse/perfmsr/core/Upload.java b/plugins/org.eclipse.jem.util/org.eclipse.perfmsr.core.stub/src/org/eclipse/perfmsr/core/Upload.java
new file mode 100644
index 0000000..65fa677
--- /dev/null
+++ b/plugins/org.eclipse.jem.util/org.eclipse.perfmsr.core.stub/src/org/eclipse/perfmsr/core/Upload.java
@@ -0,0 +1,27 @@
+/*******************************************************************************
+ * Copyright (c) 2005 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+/*
+
+
+ */
+package org.eclipse.perfmsr.core;
+
+
+/**
+ * Upload.
+ * ************* This is just a stub of the real interface to get org.eclipse.jem.util
+ * to compile. It is not usable by itself. ****************************
+ */
+public interface Upload {
+ public static class Status {
+ public boolean success;
+ }
+}
diff --git a/plugins/org.eclipse.jem.util/plugin.properties b/plugins/org.eclipse.jem.util/plugin.properties
new file mode 100644
index 0000000..a53db6a
--- /dev/null
+++ b/plugins/org.eclipse.jem.util/plugin.properties
@@ -0,0 +1,18 @@
+###############################################################################
+# Copyright (c) 2005 IBM Corporation 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:
+# IBM Corporation - initial API and implementation
+###############################################################################
+#
+# $Source: /cvsroot/webtools/common.move/webtools.common.git/plugins/org.eclipse.jem.util/plugin.properties,v $
+# $Revision: 1.2 $ $Date: 2005/02/15 23:07:45 $
+#
+
+
+pluginName=Java EMF Model Utilities
+providerName = Eclipse.org
diff --git a/plugins/org.eclipse.jem.util/plugin.xml b/plugins/org.eclipse.jem.util/plugin.xml
new file mode 100644
index 0000000..591be42
--- /dev/null
+++ b/plugins/org.eclipse.jem.util/plugin.xml
@@ -0,0 +1,15 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<?eclipse version="3.0"?>
+<plugin>
+
+
+<!-- Extension point to register ResourceHandlers that will always be added to
+ new WorkbenchContexts -->
+ <extension-point id="ResourceHandlerExtension" name="ResourceHandlerExtension"/>
+ <extension-point id="globalPluginResourceLoad" name="Global Plugin Resource Load"/>
+ <extension-point id="nature_registration" name="EMF Nature registration"/>
+ <extension-point id="internalWorkbenchContextFactory" name="Internal Workbench Context Factory"/>
+ <extension-point id="uiContextSensitiveClass" name="UI Context Sensitive Class" schema="schema/uiContextSensitiveClass.exsd"/>
+ <extension-point id="uiTester" name="UI Tester" schema="schema/uiTester.exsd"/>
+
+</plugin>
diff --git a/plugins/org.eclipse.jem.util/property_files/emfworkbench.properties b/plugins/org.eclipse.jem.util/property_files/emfworkbench.properties
new file mode 100644
index 0000000..cad9483
--- /dev/null
+++ b/plugins/org.eclipse.jem.util/property_files/emfworkbench.properties
@@ -0,0 +1,18 @@
+###############################################################################
+# Copyright (c) 2005 IBM Corporation 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:
+# IBM Corporation - initial API and implementation
+###############################################################################
+EMFWorkbenchContextBase_ERROR_0=IWAE0003E Method not yet implemented.
+EMFWorkbenchContextBase_ERROR_1=IWAE0005E Project can not be null.
+EMFWorkbenchContextBase_ERROR_2=IWAE0006E Attempt to create resource set with null project
+EMFNatureRegistry_ERROR_0=IWAE0007E Duplicate EMF nature registration for id: {0}
+EMFWorkbenchContextFactory_UI_0=The project should not be null.
+EMFWorkbenchContextFactory_UI_1=The project \"{0}\" is not accessible.
+
+ProjectUtil_Delete_1=Deleting \"{0}\".
\ No newline at end of file
diff --git a/plugins/org.eclipse.jem.util/schema/uiContextSensitiveClass.exsd b/plugins/org.eclipse.jem.util/schema/uiContextSensitiveClass.exsd
new file mode 100644
index 0000000..df70e98
--- /dev/null
+++ b/plugins/org.eclipse.jem.util/schema/uiContextSensitiveClass.exsd
@@ -0,0 +1,169 @@
+<?xml version='1.0' encoding='UTF-8'?>
+<!-- Schema file written by PDE -->
+<schema targetNamespace="org.eclipse.jem.util">
+<annotation>
+ <appInfo>
+ <meta.schema plugin="org.eclipse.jem.util" id="uiContextSensitiveClass" name="UI Context Sensitive Class"/>
+ </appInfo>
+ <documentation>
+ Components are often designed in such a way that the "Headless" or non-graphical portions are separate from the Graphical User Interface (GUI) portions. Sometimes this is done to follow good design principles, other times there is a specific use case for doing so. When plugins follow this practice because they must vary their behavior based on whether they are running in a headless environment or a graphical environment, they often need to choose the correct implementation of a particular type. The org.eclipse.jem.util.uiContextSensitiveClass extension point provided by the JEM component solves exactly this problem.
+<p>
+To use the extension point, you must provide two extensions that are linked by a key. The key is a unique String-based value that you will later use to instanitate your class.
+<p>
+The first usage of the extension specifies your key, and the Headless context, and the class that should be instantiated for this (key, context) pair. This means in the headless environment this class will be instantiated when requested.
+<p>
+The second extension specifies the UI context and the same key, but a different implementation designed for graphical environments. This means in the UI environment this other class will be instantiated when requested.
+<p>
+The actual request is done in your code via:
+<pre>
+IMyInterface instance = (IMyInterface) UIContextDetermination.createInstance("myKey");
+</pre>
+where <code>"myKey"</code> is the key used on both extensions. It will then choose either the UI or the Headless extension depending upon the context.
+ </documentation>
+ </annotation>
+
+ <element name="extension">
+ <complexType>
+ <sequence>
+ <element ref="uiContextSensitiveClass" minOccurs="1" maxOccurs="unbounded"/>
+ </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>
+ </annotation>
+ </attribute>
+ </complexType>
+ </element>
+
+ <element name="uiContextSensitiveClass">
+ <annotation>
+ <documentation>
+ An extension point that defines an instance of a class and its appropriate context (UI or Headless)
+ </documentation>
+ </annotation>
+ <complexType>
+ <attribute name="key" type="string" use="required">
+ <annotation>
+ <documentation>
+ The key that should be used to create an instance of the Context Sensitive super class/interface.
+ </documentation>
+ </annotation>
+ </attribute>
+ <attribute name="className" type="string" use="required">
+ <annotation>
+ <documentation>
+ A concrete implementation for either a UI or Headless context.
+ </documentation>
+ </annotation>
+ </attribute>
+ <attribute name="context" use="required">
+ <annotation>
+ <documentation>
+ One of "UI" or "Headless" This is case-sensitive. It must match exactly as shown here.
+ </documentation>
+ </annotation>
+ <simpleType>
+ <restriction base="string">
+ <enumeration value="UI">
+ </enumeration>
+ <enumeration value="Headless">
+ </enumeration>
+ </restriction>
+ </simpleType>
+ </attribute>
+ </complexType>
+ </element>
+
+ <annotation>
+ <appInfo>
+ <meta.section type="since"/>
+ </appInfo>
+ <documentation>
+ 6.0
+ </documentation>
+ </annotation>
+
+ <annotation>
+ <appInfo>
+ <meta.section type="examples"/>
+ </appInfo>
+ <documentation>
+ Usage for the UI context:
+<pre>
+ <extension
+ id="context.Sensitive.Class.workingCopyManager"
+ name="Working Copy Manager - UI Context Class"
+ point="org.eclipse.jem.util.ContextSensitiveClass">
+ <uiContextSensitiveClass
+ context="UI"
+ key="workingCopyManager"
+ className="com.ibm.wtp.common.ui.WTPUIWorkingCopyManager"/>
+ </extension>
+</pre>
+<br>
+Usage for the Headless context:
+<pre>
+ <extension
+ id="context.Sensitive.Class.workingCopyManager"
+ name="Working Copy Manager - Headless Context Class"
+ point="org.eclipse.jem.util.ContextSensitiveClass">
+ <uiContextSensitiveClass
+ context="Headless"
+ key="workingCopyManager"
+ className="com.ibm.wtp.common.ui.WTPHeadlessWorkingCopyManager"/>
+ </extension>
+</pre>
+<br>
+And finally the retrieval of the class for the current context:
+
+<pre>
+IWorkingCopyManager manager = (IWorkingCopyManager) UIContextDetermination.createInstance("workingCopyManager");
+</pre>
+
+ </documentation>
+ </annotation>
+
+ <annotation>
+ <appInfo>
+ <meta.section type="apiInfo"/>
+ </appInfo>
+ <documentation>
+ See <code>org.eclipse.jem.util.UIContextDetermination</code>
+ </documentation>
+ </annotation>
+
+ <annotation>
+ <appInfo>
+ <meta.section type="implementation"/>
+ </appInfo>
+ <documentation>
+
+ </documentation>
+ </annotation>
+
+ <annotation>
+ <appInfo>
+ <meta.section type="copyright"/>
+ </appInfo>
+ <documentation>
+ Copyright (c) IBM 2003.
+ </documentation>
+ </annotation>
+
+</schema>
diff --git a/plugins/org.eclipse.jem.util/schema/uiTester.exsd b/plugins/org.eclipse.jem.util/schema/uiTester.exsd
new file mode 100644
index 0000000..729ab32
--- /dev/null
+++ b/plugins/org.eclipse.jem.util/schema/uiTester.exsd
@@ -0,0 +1,128 @@
+<?xml version='1.0' encoding='UTF-8'?>
+<!-- Schema file written by PDE -->
+<schema targetNamespace="org.eclipse.jem.util">
+<annotation>
+ <appInfo>
+ <meta.schema plugin="org.eclipse.jem.util" id="uiTester" name="UI Tester"/>
+ </appInfo>
+ <documentation>
+ This is used to tell JEM that it is running in a non-HEADLESS environment. Typically UI environment is non-HEADLESS. The default if there are no implementers of this extension point that return true is HEADLESS.
+<p>
+A HEADLESS environment is typically a batch situation where there is no UI and the workspace is used for one operation and then terminated. Most headless tasks are done under one operation and the JavaReflectionSynchronizer may not have a chance to flush a bad reflection before the real type needs to be found and can be found. So what would happen is if a class was created during this one operation it would not be found because the notifications had not yet gone out.
+<p>
+In a UI environment the operations are typically short and do only a few things and the results aren't needed until after the operation has completed. In that case it is more efficient to not keep checking if a class has appeared everytime a request is made, instead it will wait for the notification of the added class to appear before resetting the definition to allow checking again later.
+<p>
+If there is more than one implementer of this interface in the application, then it will go through each of them once until one returns true. As soon as one returns true it will stop and mark the application as being non-HEADLESS. This will be done only once for the application. It will not be again until the next session of the application.
+<p>
+This is typically an internal extension point only. The JEM UI plugin will provide an implementation that will return true if the Platform UI is active. So this will normally not be needed to be implemented by most customers.
+ </documentation>
+ </annotation>
+
+ <element name="extension">
+ <complexType>
+ <sequence>
+ <element ref="uiTester"/>
+ </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>
+ </annotation>
+ </attribute>
+ </complexType>
+ </element>
+
+ <element name="uiTester">
+ <annotation>
+ <documentation>
+ The uiTester definition element.
+ </documentation>
+ </annotation>
+ <complexType>
+ <attribute name="className" type="string" use="required">
+ <annotation>
+ <documentation>
+ The class name of the UITester for this extension. It must implement <samp>org.eclipse.jem.util.UITester</samp>.
+ </documentation>
+ <appInfo>
+ <meta.attribute kind="java" basedOn="org.eclipse.jem.util.UITester"/>
+ </appInfo>
+ </annotation>
+ </attribute>
+ </complexType>
+ </element>
+
+ <annotation>
+ <appInfo>
+ <meta.section type="since"/>
+ </appInfo>
+ <documentation>
+ 1.0.0
+ </documentation>
+ </annotation>
+
+ <annotation>
+ <appInfo>
+ <meta.section type="examples"/>
+ </appInfo>
+ <documentation>
+ The following is an example of an implementer:
+
+<p>
+<pre>
+ <extension point="org.eclipse.jem.util.uiTester">
+ <uiTester
+ className="com.example.UITesterImplementation"/>
+ </extension>
+</pre>
+</p>
+ </documentation>
+ </annotation>
+
+ <annotation>
+ <appInfo>
+ <meta.section type="apiInfo"/>
+ </appInfo>
+ <documentation>
+ The <samp>className</samp> attribute must be a fully-qualified class that implements the <samp>org.eclipse.jem.util.UITester</samp> interface for the tester.
+ </documentation>
+ </annotation>
+
+ <annotation>
+ <appInfo>
+ <meta.section type="implementation"/>
+ </appInfo>
+ <documentation>
+ There is no default implementation for this class.
+ </documentation>
+ </annotation>
+
+ <annotation>
+ <appInfo>
+ <meta.section type="copyright"/>
+ </appInfo>
+ <documentation>
+ Copyright (c) 2004, 2006 IBM Corporation and others.<br>
+All rights reserved. This program and the accompanying materials are made
+available under the terms of the Eclipse Public License v1.0 which accompanies
+this distribution, and is available at
+<a href="http://www.eclipse.org/legal/epl-v10.html">http://www.eclipse.org/legal/epl-v10.html</a>
+ </documentation>
+ </annotation>
+
+</schema>
diff --git a/plugins/org.eclipse.wst.common.emf/.classpath b/plugins/org.eclipse.wst.common.emf/.classpath
new file mode 100644
index 0000000..96202d8
--- /dev/null
+++ b/plugins/org.eclipse.wst.common.emf/.classpath
@@ -0,0 +1,12 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<classpath>
+ <classpathentry kind="src" path="wtpemf/"/>
+ <classpathentry kind="src" path="workbench/"/>
+ <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/J2SE-1.4"/>
+ <classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins">
+ <accessrules>
+ <accessrule kind="accessible" pattern="org/eclipse/wst/common/**"/>
+ </accessrules>
+ </classpathentry>
+ <classpathentry kind="output" path="bin"/>
+</classpath>
diff --git a/plugins/org.eclipse.wst.common.emf/.cvsignore b/plugins/org.eclipse.wst.common.emf/.cvsignore
new file mode 100644
index 0000000..26458b4
--- /dev/null
+++ b/plugins/org.eclipse.wst.common.emf/.cvsignore
@@ -0,0 +1,8 @@
+bin
+runtime
+temp.folder
+build.xml
+org.eclipse.wst.common.emf_1.0.0.zip
+src.zip
+@dot
+javaCompiler...args
diff --git a/plugins/org.eclipse.wst.common.emf/.project b/plugins/org.eclipse.wst.common.emf/.project
new file mode 100644
index 0000000..5b5f0fe
--- /dev/null
+++ b/plugins/org.eclipse.wst.common.emf/.project
@@ -0,0 +1,28 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<projectDescription>
+ <name>org.eclipse.wst.common.emf</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.jdt.core.javanature</nature>
+ <nature>org.eclipse.pde.PluginNature</nature>
+ </natures>
+</projectDescription>
diff --git a/plugins/org.eclipse.wst.common.emf/.settings/org.eclipse.jdt.core.prefs b/plugins/org.eclipse.wst.common.emf/.settings/org.eclipse.jdt.core.prefs
new file mode 100644
index 0000000..6c7418f
--- /dev/null
+++ b/plugins/org.eclipse.wst.common.emf/.settings/org.eclipse.jdt.core.prefs
@@ -0,0 +1,63 @@
+#Sat Mar 24 02:06:02 EDT 2007
+eclipse.preferences.version=1
+org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
+org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.2
+org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve
+org.eclipse.jdt.core.compiler.compliance=1.4
+org.eclipse.jdt.core.compiler.debug.lineNumber=generate
+org.eclipse.jdt.core.compiler.debug.localVariable=generate
+org.eclipse.jdt.core.compiler.debug.sourceFile=generate
+org.eclipse.jdt.core.compiler.problem.annotationSuperInterface=ignore
+org.eclipse.jdt.core.compiler.problem.assertIdentifier=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=error
+org.eclipse.jdt.core.compiler.problem.emptyStatement=ignore
+org.eclipse.jdt.core.compiler.problem.enumIdentifier=warning
+org.eclipse.jdt.core.compiler.problem.fallthroughCase=ignore
+org.eclipse.jdt.core.compiler.problem.fieldHiding=ignore
+org.eclipse.jdt.core.compiler.problem.finalParameterBound=ignore
+org.eclipse.jdt.core.compiler.problem.finallyBlockNotCompletingNormally=error
+org.eclipse.jdt.core.compiler.problem.forbiddenReference=error
+org.eclipse.jdt.core.compiler.problem.hiddenCatchBlock=error
+org.eclipse.jdt.core.compiler.problem.incompatibleNonInheritedInterfaceMethod=error
+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=error
+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=error
+org.eclipse.jdt.core.compiler.problem.nonExternalizedStringLiteral=ignore
+org.eclipse.jdt.core.compiler.problem.nullReference=ignore
+org.eclipse.jdt.core.compiler.problem.overridingPackageDefaultMethod=error
+org.eclipse.jdt.core.compiler.problem.parameterAssignment=ignore
+org.eclipse.jdt.core.compiler.problem.possibleAccidentalBooleanAssignment=ignore
+org.eclipse.jdt.core.compiler.problem.rawTypeReference=ignore
+org.eclipse.jdt.core.compiler.problem.redundantNullCheck=ignore
+org.eclipse.jdt.core.compiler.problem.specialParameterHidingField=disabled
+org.eclipse.jdt.core.compiler.problem.staticAccessReceiver=error
+org.eclipse.jdt.core.compiler.problem.suppressWarnings=enabled
+org.eclipse.jdt.core.compiler.problem.syntheticAccessEmulation=ignore
+org.eclipse.jdt.core.compiler.problem.typeParameterHiding=error
+org.eclipse.jdt.core.compiler.problem.uncheckedTypeOperation=ignore
+org.eclipse.jdt.core.compiler.problem.undocumentedEmptyBlock=ignore
+org.eclipse.jdt.core.compiler.problem.unhandledWarningToken=ignore
+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=error
+org.eclipse.jdt.core.compiler.problem.unusedLabel=error
+org.eclipse.jdt.core.compiler.problem.unusedLocal=ignore
+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=error
+org.eclipse.jdt.core.compiler.problem.varargsArgumentNeedCast=ignore
+org.eclipse.jdt.core.compiler.source=1.3
diff --git a/plugins/org.eclipse.wst.common.emf/META-INF/MANIFEST.MF b/plugins/org.eclipse.wst.common.emf/META-INF/MANIFEST.MF
new file mode 100644
index 0000000..9328000
--- /dev/null
+++ b/plugins/org.eclipse.wst.common.emf/META-INF/MANIFEST.MF
@@ -0,0 +1,19 @@
+Manifest-Version: 1.0
+Bundle-ManifestVersion: 2
+Bundle-Name: %pluginName
+Bundle-SymbolicName: org.eclipse.wst.common.emf; singleton:=true
+Bundle-Version: 1.1.204.qualifier
+Bundle-Activator: org.eclipse.wst.common.internal.emf.plugin.EcoreUtilitiesPlugin
+Bundle-Vendor: %pluginProvider
+Bundle-Localization: plugin
+Export-Package: org.eclipse.wst.common.internal.emf.plugin;x-internal:=true,
+ org.eclipse.wst.common.internal.emf.resource;x-friends:="org.eclipse.wst.common.modulecore",
+ org.eclipse.wst.common.internal.emf.utilities;x-internal:=true
+Require-Bundle: org.eclipse.emf.ecore.xmi;bundle-version="[2.4.0,3.0.0)",
+ org.eclipse.wst.common.frameworks;bundle-version="[1.1.200,2.0.0)",
+ org.eclipse.core.runtime;bundle-version="[3.4.0,4.0.0)",
+ org.eclipse.core.resources;bundle-version="[3.4.0,4.0.0)",
+ org.eclipse.jem.util;bundle-version="[2.0.100,3.0.0)"
+Eclipse-LazyStart: true
+Bundle-RequiredExecutionEnvironment: J2SE-1.4
+Bundle-ActivationPolicy: lazy
diff --git a/plugins/org.eclipse.wst.common.emf/about.html b/plugins/org.eclipse.wst.common.emf/about.html
new file mode 100644
index 0000000..2199df3
--- /dev/null
+++ b/plugins/org.eclipse.wst.common.emf/about.html
@@ -0,0 +1,34 @@
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN">
+<HTML>
+
+<head>
+<title>About</title>
+<meta http-equiv=Content-Type content="text/html; charset=ISO-8859-1">
+</head>
+
+<BODY lang="EN-US">
+
+<H3>About This Content</H3>
+
+<P>June, 2008</P>
+
+<H3>License</H3>
+
+<P>The Eclipse Foundation makes available all content in this plug-in
+("Content"). Unless otherwise indicated below, the Content is provided to you
+under the terms and conditions of the Eclipse Public License Version 1.0
+("EPL"). A copy of the EPL is available at
+<A href="http://www.eclipse.org/org/documents/epl-v10.php">http://www.eclipse.org/org/documents/epl-v10.php</A>.
+For purposes of the EPL, "Program" will mean the Content.</P>
+
+<P>If you did not receive this Content directly from the Eclipse Foundation, the
+Content is being redistributed by another party ("Redistributor") and different
+terms and conditions may apply to your use of any object code in the Content.
+Check the RedistributorÂ’s license that was provided with the Content. If no such
+license exists, contact the Redistributor. Unless otherwise indicated below, the
+terms and conditions of the EPL still apply to any source code in the Content
+and such source code may be obtained at
+<A href="http://www.eclipse.org/">http://www.eclipse.org/</A>.</P>
+
+</BODY>
+</HTML>
diff --git a/plugins/org.eclipse.wst.common.emf/build.properties b/plugins/org.eclipse.wst.common.emf/build.properties
new file mode 100644
index 0000000..ed37cff
--- /dev/null
+++ b/plugins/org.eclipse.wst.common.emf/build.properties
@@ -0,0 +1,22 @@
+###############################################################################
+# Copyright (c) 2003, 2006 IBM Corporation 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:
+# IBM Corporation - initial API and implementation
+###############################################################################
+bin.includes = plugin.xml,\
+ META-INF/,\
+ about.html,\
+ plugin.properties,\
+ .,\
+ schema/
+jars.compile.order = .
+src.includes = component.xml,\
+ schema/
+output.. = bin/
+source.. = wtpemf/,\
+ workbench/
diff --git a/plugins/org.eclipse.wst.common.emf/component.xml b/plugins/org.eclipse.wst.common.emf/component.xml
new file mode 100644
index 0000000..9530d33
--- /dev/null
+++ b/plugins/org.eclipse.wst.common.emf/component.xml
@@ -0,0 +1 @@
+<?xml version="1.0" encoding="UTF-8"?><component xmlns="http://eclipse.org/wtp/releng/tools/component-model" name="org.eclipse.wst.common.emf"><component-depends unrestricted="true"></component-depends><plugin id="org.eclipse.wst.common.emf" fragment="false"/><plugin id="org.eclipse.wst.common.emfworkbench.integration" fragment="false"/></component>
\ No newline at end of file
diff --git a/plugins/org.eclipse.wst.common.emf/plugin.properties b/plugins/org.eclipse.wst.common.emf/plugin.properties
new file mode 100644
index 0000000..fc83d04
--- /dev/null
+++ b/plugins/org.eclipse.wst.common.emf/plugin.properties
@@ -0,0 +1,13 @@
+###############################################################################
+# Copyright (c) 2005, 2006 IBM Corporation 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:
+# IBM Corporation - initial API and implementation
+###############################################################################
+PackageURIMap=PackageURIMap
+pluginName=EMF Utilities
+pluginProvider=Eclipse.org
\ No newline at end of file
diff --git a/plugins/org.eclipse.wst.common.emf/plugin.xml b/plugins/org.eclipse.wst.common.emf/plugin.xml
new file mode 100644
index 0000000..dde6ad8
--- /dev/null
+++ b/plugins/org.eclipse.wst.common.emf/plugin.xml
@@ -0,0 +1,35 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<?eclipse version="3.0"?>
+<plugin>
+
+ <extension-point id="packageURIMap" name="%PackageURIMap" schema="schema/packageURIMap.exsd"/>
+ <extension-point id="translatorExtension" name="translatorExtension" schema="schema/translatorExtension.exsd"/>
+
+<!-- Need to register the Ecore specific package mappings -->
+ <extension
+ point="org.eclipse.wst.common.emf.packageURIMap">
+ <map
+ uri="http://www.eclipse.org/emf/2002/Ecore"
+ prefix="ecore">
+ </map>
+ <map
+ uri="http://www.eclipse.org/emf/2002/Mapping"
+ prefix="mapping">
+ </map>
+<!-- Trick to get Mapping.xmi for MOF5 serialization -->
+ <map
+ uri="http://www.eclipse.org/emf/2002/Mapping"
+ prefix="Mapping">
+ </map>
+ </extension>
+
+ <extension
+ point="org.eclipse.jem.util.uiContextSensitiveClass">
+ <uiContextSensitiveClass
+ context="Headless"
+ key="rendererFactory"
+ className="org.eclipse.wst.common.internal.emf.resource.EMF2DOMRendererFactory">
+ </uiContextSensitiveClass>
+ </extension>
+
+</plugin>
diff --git a/plugins/org.eclipse.wst.validation/prepareforpii.xml b/plugins/org.eclipse.wst.common.emf/prepareforpii.xml
similarity index 79%
rename from plugins/org.eclipse.wst.validation/prepareforpii.xml
rename to plugins/org.eclipse.wst.common.emf/prepareforpii.xml
index 1aad5fe..8007604 100644
--- a/plugins/org.eclipse.wst.validation/prepareforpii.xml
+++ b/plugins/org.eclipse.wst.common.emf/prepareforpii.xml
@@ -3,7 +3,7 @@
<!-- Setup temp variables -->
<target name="init">
<property name="nlsDir" value="d:/NLS/Corona/0526"/>
- <property name="plugin" value="com.ibm.etools.validation"/>
+ <property name="plugin" value="com.ibm.wtp.emf"/>
<property name="plugindir" value="d:/workspaceCorona/${plugin}"/>
<property name="outputDir" value="${nlsDir}/${plugin}"/>
@@ -26,13 +26,12 @@
<messageIdGen folderPath = "${plugindir}" componentId = "E" />
- <copy todir = "${outputDir}/property_files" >
- <fileset dir="${plugindir}/property_files">
+ <copy todir = "${outputDir}/wtpemf" >
+ <fileset dir="${plugindir}/wtpemf">
<include name="**/*.properties"/>
</fileset>
</copy>
- <copy file="${plugindir}/plugin.properties" todir="${outputDir}"/>
</target>
</project>
diff --git a/plugins/org.eclipse.wst.common.emf/schema/packageURIMap.exsd b/plugins/org.eclipse.wst.common.emf/schema/packageURIMap.exsd
new file mode 100644
index 0000000..4f9d955
--- /dev/null
+++ b/plugins/org.eclipse.wst.common.emf/schema/packageURIMap.exsd
@@ -0,0 +1,113 @@
+<?xml version='1.0' encoding='UTF-8'?>
+<!-- Schema file written by PDE -->
+<schema targetNamespace="org.eclipse.wst.common.emf">
+<annotation>
+ <appInfo>
+ <meta.schema plugin="org.eclipse.wst.common.emf" id="packageURIMap" name="%PackageURIMap"/>
+ </appInfo>
+ <documentation>
+ This extension point is used to register package mappings.
+ </documentation>
+ </annotation>
+
+ <element name="extension">
+ <complexType>
+ <sequence>
+ <element ref="map" minOccurs="1" maxOccurs="unbounded"/>
+ </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="map">
+ <complexType>
+ <attribute name="uri" type="string" use="required">
+ <annotation>
+ <documentation>
+
+ </documentation>
+ </annotation>
+ </attribute>
+ <attribute name="prefix" type="string" use="required">
+ <annotation>
+ <documentation>
+
+ </documentation>
+ </annotation>
+ </attribute>
+ </complexType>
+ </element>
+
+ <annotation>
+ <appInfo>
+ <meta.section type="since"/>
+ </appInfo>
+ <documentation>
+ <b>This extension point is part of an interim API that is still under development and expected to change significantly before reaching stability. It is being made available at this early stage to solicit feedback from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken (repeatedly) as the API evolves.</b>
+ </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>
+ Copyright (c) 2005 IBM Corporation and others.<br>
+All rights reserved. This program and the accompanying materials are made
+available under the terms of the Eclipse Public License v1.0 which accompanies
+this distribution, and is available at <a
+href="http://www.eclipse.org/legal/epl-v10.html">http://www.eclipse.org/legal/epl-v10.html</a>
+ </documentation>
+ </annotation>
+
+</schema>
diff --git a/plugins/org.eclipse.wst.common.emf/schema/translatorExtension.exsd b/plugins/org.eclipse.wst.common.emf/schema/translatorExtension.exsd
new file mode 100644
index 0000000..5aa9669
--- /dev/null
+++ b/plugins/org.eclipse.wst.common.emf/schema/translatorExtension.exsd
@@ -0,0 +1,103 @@
+<?xml version='1.0' encoding='UTF-8'?>
+<!-- Schema file written by PDE -->
+<schema targetNamespace="org.eclipse.wst.common.emf">
+<annotation>
+ <appInfo>
+ <meta.schema plugin="org.eclipse.wst.common.emf" id="translatorExtension" name="translatorExtension"/>
+ </appInfo>
+ <documentation>
+ This is used to contribute child translators to the default translators in EMF2DOMAdapterImpl.
+ </documentation>
+ </annotation>
+
+ <element name="extension">
+ <complexType>
+ <sequence>
+ <element ref="translator"/>
+ </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="translator">
+ <complexType>
+ <attribute name="className" type="string" use="required">
+ <annotation>
+ <documentation>
+ This is the fully qualified classname of the child translator.
+ </documentation>
+ </annotation>
+ </attribute>
+ </complexType>
+ </element>
+
+ <annotation>
+ <appInfo>
+ <meta.section type="since"/>
+ </appInfo>
+ <documentation>
+ This extension point is part of an interim API that is still under development and expected to change significantly before reaching stability. It is being made available at this early stage to solicit feedback from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken (repeatedly) as the API evolves.
+ </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>
+ Copyright (c) 2005 IBM Corporation 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
+ </documentation>
+ </annotation>
+
+</schema>
diff --git a/plugins/org.eclipse.wst.common.emf/workbench/org/eclipse/wst/common/internal/emf/ResourceSynchronizedIsLoadingAdapter.java b/plugins/org.eclipse.wst.common.emf/workbench/org/eclipse/wst/common/internal/emf/ResourceSynchronizedIsLoadingAdapter.java
new file mode 100644
index 0000000..5034c7a
--- /dev/null
+++ b/plugins/org.eclipse.wst.common.emf/workbench/org/eclipse/wst/common/internal/emf/ResourceSynchronizedIsLoadingAdapter.java
@@ -0,0 +1,127 @@
+/*******************************************************************************
+ * Copyright (c) 2005, 2007 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+/*
+ * Created on Oct 26, 2004
+ *
+ * TODO To change the template for this generated file go to
+ * Window - Preferences - Java - Code Style - Code Templates
+ */
+package org.eclipse.wst.common.internal.emf;
+
+import org.eclipse.core.runtime.Platform;
+import org.eclipse.core.runtime.jobs.ILock;
+import org.eclipse.emf.common.notify.Notification;
+import org.eclipse.emf.common.notify.Notifier;
+import org.eclipse.emf.ecore.resource.Resource;
+import org.eclipse.wst.common.internal.emf.utilities.ResourceIsLoadingAdapter;
+
+
+
+/**
+ * The ResourceSynchronizedIsLoadingAdapter is used to synchronize the loading
+ * of EMF resources. This is the Eclipse version of ResourceIsLoadingAdapter,
+ * and uses the Eclipse ILock technology to acquire a semaphore until the
+ * Resource is loaded. the waitForResourceToLoad() method will pause until
+ * either (a) the Resource has loaded, the Adapter is notified, and the
+ * semaphore is released or (b) the DELAY timeout is exceeded, which prevents
+ * full deadlock.
+ *
+ * @author mdelder
+ */
+public class ResourceSynchronizedIsLoadingAdapter extends ResourceIsLoadingAdapter {
+
+ private final ILock loadingLock;
+
+ /**
+ * The delay is default to 5 minutes. This is the upward threshhold. The
+ * lock will wait up to DELAY milliseconds to acquire the lock, and bail
+ * if not. It does not mean that it will wait DELAY milliseconds always.
+ * In general, the wait should be almost instanteous -- just as long as
+ * document loading remains speedy.
+ */
+ private static final long DELAY = 300000;
+
+ public ResourceSynchronizedIsLoadingAdapter() {
+ loadingLock = Platform.getJobManager().newLock();
+ if (loadingLock != null)
+ loadingLock.acquire();
+ }
+
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see com.ibm.wtp.internal.emf.utilities.ResourceIsLoadingAdapter#waitForResourceToLoad()
+ */
+ public void waitForResourceToLoad() {
+
+ if (loadingLock == null)
+ return;
+
+ boolean lockAcquired = false;
+ try {
+ if (loadingLock != null)
+ if (!(lockAcquired = loadingLock.acquire(DELAY)))
+ logWarning();
+ }
+ catch (InterruptedException e) {
+ // ignore, just continue
+ }
+ finally {
+ if (lockAcquired)
+ loadingLock.release();
+ }
+
+ }
+
+
+ /**
+ *
+ */
+ private void logWarning() {
+ Notifier target = getTarget();
+ if (target == null || !(target instanceof Resource)) {
+ Resource resource = (Resource) target;
+ System.err.println("[WARNING] Could not acquire Semaphore Lock for Resource: \"" + resource.getURI() + "\" in " + getClass());
+ }
+
+ }
+
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see com.ibm.wtp.internal.emf.utilities.ResourceIsLoadingAdapter#notifyChanged(org.eclipse.emf.common.notify.Notification)
+ */
+ public void notifyChanged(Notification notification) {
+
+ if (notification.getNotifier() != null) {
+ // listen for the remove of the loading adapter
+ if (isSetLoadedResourceNotification(notification)) {
+ if (loadingLock != null)
+ loadingLock.release();
+ removeIsLoadingSupport();
+ }
+ }
+ }
+
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see com.ibm.wtp.internal.emf.utilities.ResourceIsLoadingAdapter#forceRelease()
+ */
+ public void forceRelease() {
+ if (loadingLock != null && loadingLock.getDepth() > 0)
+ loadingLock.release();
+ }
+
+}
diff --git a/plugins/org.eclipse.wst.common.emf/workbench/org/eclipse/wst/common/internal/emf/ResourceSynchronizedIsLoadingAdapterFactory.java b/plugins/org.eclipse.wst.common.emf/workbench/org/eclipse/wst/common/internal/emf/ResourceSynchronizedIsLoadingAdapterFactory.java
new file mode 100644
index 0000000..1990e8a
--- /dev/null
+++ b/plugins/org.eclipse.wst.common.emf/workbench/org/eclipse/wst/common/internal/emf/ResourceSynchronizedIsLoadingAdapterFactory.java
@@ -0,0 +1,38 @@
+/*******************************************************************************
+ * Copyright (c) 2005, 2006 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+/*
+ * Created on Oct 26, 2004
+ *
+ * TODO To change the template for this generated file go to
+ * Window - Preferences - Java - Code Style - Code Templates
+ */
+package org.eclipse.wst.common.internal.emf;
+
+import org.eclipse.wst.common.internal.emf.utilities.ResourceIsLoadingAdapter;
+import org.eclipse.wst.common.internal.emf.utilities.ResourceIsLoadingAdapterFactory;
+
+
+/**
+ * @author mdelder
+ *
+ * TODO To change the template for this generated type comment go to
+ * Window - Preferences - Java - Code Style - Code Templates
+ */
+public class ResourceSynchronizedIsLoadingAdapterFactory extends ResourceIsLoadingAdapterFactory {
+
+
+ /* (non-Javadoc)
+ * @see com.ibm.wtp.internal.emf.utilities.ResourceIsLoadingAdapterFactory#createResourceIsLoadingAdapter()
+ */
+ public ResourceIsLoadingAdapter createResourceIsLoadingAdapter() {
+ return new ResourceSynchronizedIsLoadingAdapter();
+ }
+}
diff --git a/plugins/org.eclipse.wst.common.emf/workbench/org/eclipse/wst/common/internal/emf/plugin/EcoreUtilitiesPlugin.java b/plugins/org.eclipse.wst.common.emf/workbench/org/eclipse/wst/common/internal/emf/plugin/EcoreUtilitiesPlugin.java
new file mode 100644
index 0000000..1c24c05
--- /dev/null
+++ b/plugins/org.eclipse.wst.common.emf/workbench/org/eclipse/wst/common/internal/emf/plugin/EcoreUtilitiesPlugin.java
@@ -0,0 +1,55 @@
+/*******************************************************************************
+ * Copyright (c) 2003, 2006 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+/*
+ * Created on Jun 9, 2003
+ *
+ * To change the template for this generated file go to
+ * Window>Preferences>Java>Code Generation>Code and Comments
+ */
+package org.eclipse.wst.common.internal.emf.plugin;
+
+import org.eclipse.core.runtime.Plugin;
+import org.eclipse.wst.common.internal.emf.ResourceSynchronizedIsLoadingAdapterFactory;
+import org.eclipse.wst.common.internal.emf.resource.RendererFactory;
+import org.eclipse.wst.common.internal.emf.utilities.ResourceIsLoadingAdapterFactory;
+import org.osgi.framework.BundleContext;
+
+/**
+ * @author DABERG
+ *
+ * To change the template for this generated type comment go to Window>Preferences>Java>Code
+ * Generation>Code and Comments
+ */
+public class EcoreUtilitiesPlugin extends Plugin {
+ public static final String ID = "org.eclipse.wst.common.emf"; //$NON-NLS-1$
+ public static final String TRANSLATOR_EXTENSTION_POINT = "translatorExtension"; //$NON-NLS-1$
+
+ /**
+ * @param descriptor
+ */
+ public EcoreUtilitiesPlugin() {
+ super();
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.eclipse.core.runtime.Plugin#startup()
+ */
+ public void start(BundleContext context) throws Exception {
+ super.start(context);
+ RendererFactory.setDefaultHandler(PluginRendererFactoryDefaultHandler.INSTANCE);
+ PackageURIMapReader reader = new PackageURIMapReader();
+ reader.processExtensions();
+ //use a synchronized loading adapter factory
+ ResourceIsLoadingAdapterFactory.INSTANCE = new ResourceSynchronizedIsLoadingAdapterFactory();
+ }
+}
diff --git a/plugins/org.eclipse.wst.common.emf/workbench/org/eclipse/wst/common/internal/emf/plugin/PackageURIMapReader.java b/plugins/org.eclipse.wst.common.emf/workbench/org/eclipse/wst/common/internal/emf/plugin/PackageURIMapReader.java
new file mode 100644
index 0000000..d1c39b0
--- /dev/null
+++ b/plugins/org.eclipse.wst.common.emf/workbench/org/eclipse/wst/common/internal/emf/plugin/PackageURIMapReader.java
@@ -0,0 +1,71 @@
+/*******************************************************************************
+ * Copyright (c) 2003, 2005 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.wst.common.internal.emf.plugin;
+
+import org.eclipse.core.runtime.IConfigurationElement;
+import org.eclipse.core.runtime.IExtension;
+import org.eclipse.core.runtime.IExtensionPoint;
+import org.eclipse.core.runtime.Platform;
+import org.eclipse.wst.common.internal.emf.resource.CompatibilityPackageMappingRegistry;
+
+/**
+ * This reader will read the packageURIMap extension point and populate the
+ * CompatibilityPackageMappingRegistry.
+ *
+ * The packageURIMap will have the following configuration element.
+ *
+ * <map prefix="somePackagePrefix" uri="somePackageURI"/>
+ *
+ */
+public class PackageURIMapReader {
+ private static final String URI_ATT_NAME = "uri"; //$NON-NLS-1$
+ private static final String PREFIX_ATT_NAME = "prefix"; //$NON-NLS-1$
+ private static final String EXTENSION_POINT_NAME = "packageURIMap"; //$NON-NLS-1$
+
+ /**
+ *
+ */
+ public PackageURIMapReader() {
+ super();
+ }
+
+ private IExtensionPoint getExtensionPoint() {
+ return Platform.getExtensionRegistry().getExtensionPoint(EcoreUtilitiesPlugin.ID, EXTENSION_POINT_NAME);
+ }
+
+ /**
+ * Call this method to read and process all of the packageURIMap extensions. *
+ */
+ public void processExtensions() {
+ CompatibilityPackageMappingRegistry reg = CompatibilityPackageMappingRegistry.INSTANCE;
+ IExtension[] extensions = getExtensionPoint().getExtensions();
+ for (int i = 0; i < extensions.length; i++)
+ processExtension(extensions[i], reg);
+ }
+
+ /**
+ * @param extension
+ */
+ private void processExtension(IExtension extension, CompatibilityPackageMappingRegistry reg) {
+ IConfigurationElement[] configs = extension.getConfigurationElements();
+ for (int i = 0; i < configs.length; i++)
+ processConfiguration(configs[i], reg);
+ }
+
+ /**
+ * @param element
+ */
+ private void processConfiguration(IConfigurationElement element, CompatibilityPackageMappingRegistry reg) {
+ String prefix = element.getAttribute(PREFIX_ATT_NAME);
+ String uri = element.getAttribute(URI_ATT_NAME);
+ reg.registerPrefixToPackageURI(prefix, uri);
+ }
+}
diff --git a/plugins/org.eclipse.wst.common.emf/workbench/org/eclipse/wst/common/internal/emf/plugin/PluginRendererFactoryDefaultHandler.java b/plugins/org.eclipse.wst.common.emf/workbench/org/eclipse/wst/common/internal/emf/plugin/PluginRendererFactoryDefaultHandler.java
new file mode 100644
index 0000000..ee80757
--- /dev/null
+++ b/plugins/org.eclipse.wst.common.emf/workbench/org/eclipse/wst/common/internal/emf/plugin/PluginRendererFactoryDefaultHandler.java
@@ -0,0 +1,52 @@
+/*******************************************************************************
+ * Copyright (c) 2003, 2005 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+/*
+ * Created on Dec 1, 2003
+ *
+ * To change the template for this generated file go to
+ * Window>Preferences>Java>Code Generation>Code and Comments
+ */
+package org.eclipse.wst.common.internal.emf.plugin;
+
+import org.eclipse.jem.util.UIContextDetermination;
+import org.eclipse.wst.common.internal.emf.resource.EMF2DOMRendererFactoryDefaultHandler;
+import org.eclipse.wst.common.internal.emf.resource.RendererFactory;
+
+/**
+ * @author schacher
+ *
+ * To change the template for this generated type comment go to
+ * Window>Preferences>Java>Code Generation>Code and Comments
+ */
+public class PluginRendererFactoryDefaultHandler extends EMF2DOMRendererFactoryDefaultHandler {
+
+ static final PluginRendererFactoryDefaultHandler INSTANCE = new PluginRendererFactoryDefaultHandler();
+ static final String EXT_POINT_NAME = "rendererFactory"; //$NON-NLS-1$
+
+ /**
+ *
+ */
+ protected PluginRendererFactoryDefaultHandler() {
+
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see com.ibm.etools.emf2xml.EMF2DOMRendererFactoryDefaultHandler#getDefaultRendererFactory()
+ */
+ public RendererFactory getDefaultRendererFactory() {
+ RendererFactory aFactory = (RendererFactory) UIContextDetermination.createInstance(EXT_POINT_NAME);
+ return aFactory == null ? super.getDefaultRendererFactory() : aFactory;
+ }
+
+
+}
diff --git a/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/resource/AbstractRendererImpl.java b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/resource/AbstractRendererImpl.java
new file mode 100644
index 0000000..cff83b7
--- /dev/null
+++ b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/resource/AbstractRendererImpl.java
@@ -0,0 +1,154 @@
+/*******************************************************************************
+ * Copyright (c) 2003, 2005 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.wst.common.internal.emf.resource;
+
+
+public abstract class AbstractRendererImpl implements Renderer {
+
+
+ protected TranslatorResource resource;
+ private int versionId;
+ private boolean validating = true;
+
+ /**
+ * Constructor for AbstractRendererImpl.
+ */
+ public AbstractRendererImpl() {
+ super();
+ }
+
+ /**
+ * @see com.ibm.etools.emf2xml.Renderer#setResource(TranslatorResource)
+ */
+ public void setResource(TranslatorResource aResource) {
+ resource = aResource;
+ }
+
+ /**
+ * @see com.ibm.etools.emf2xml.Renderer#getResource()
+ */
+ public TranslatorResource getResource() {
+ return resource;
+ }
+
+ public int getVersionId() {
+ return this.versionId;
+ }
+
+ public void setVersionId(int versionId) {
+ this.versionId = versionId;
+ }
+
+ /**
+ * @return
+ */
+ public boolean isValidating() {
+ return validating;
+ }
+
+ /**
+ * @param b
+ */
+ public void setValidating(boolean b) {
+ validating = b;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see com.ibm.etools.emf2xml.Renderer#accessForRead()
+ */
+ public void accessForRead() {
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see com.ibm.etools.emf2xml.Renderer#accessForWrite()
+ */
+ public void accessForWrite() {
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see com.ibm.etools.emf2xml.Renderer#isModified()
+ */
+ public boolean isModified() {
+ return false;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see com.ibm.etools.emf2xml.Renderer#isShared()
+ */
+ public boolean isShared() {
+ return false;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see com.ibm.etools.emf2xml.Renderer#isSharedForWrite()
+ */
+ public boolean isSharedForWrite() {
+ return false;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see com.ibm.etools.emf2xml.Renderer#preDelete()
+ */
+ public void preDelete() {
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see com.ibm.etools.emf2xml.Renderer#preUnload()
+ */
+ public void preUnload() {
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see com.ibm.etools.emf2xml.Renderer#releaseFromRead()
+ */
+ public void releaseFromRead() {
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see com.ibm.etools.emf2xml.Renderer#releaseFromWrite()
+ */
+ public void releaseFromWrite() {
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see com.ibm.etools.emf2xml.Renderer#setBatchMode(boolean)
+ */
+ public void setBatchMode(boolean isBatch) {
+ }
+
+ public boolean useStreamsForIO() {
+ return true;
+ }
+
+ public boolean isBatchMode() {
+ return false;
+ }
+}
diff --git a/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/resource/AttributeTranslatorFilter.java b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/resource/AttributeTranslatorFilter.java
new file mode 100644
index 0000000..b0d0869
--- /dev/null
+++ b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/resource/AttributeTranslatorFilter.java
@@ -0,0 +1,35 @@
+/***************************************************************************************************
+ * Copyright (c) 2003, 2004 IBM Corporation 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: IBM Corporation - initial API and implementation
+ **************************************************************************************************/
+/*
+ * Created on Sep 21, 2003
+ *
+ */
+package org.eclipse.wst.common.internal.emf.resource;
+
+
+public final class AttributeTranslatorFilter extends TranslatorFilter {
+
+ public AttributeTranslatorFilter() {
+ super(null, -1);
+ }
+
+ public AttributeTranslatorFilter(Translator trans, int version) {
+ super(trans, version);
+ }
+
+ public final int scanNextTranslator(Translator[] children, int start) {
+ int found = start + 1;
+ for (; found < children.length; ++found) {
+ if (children[found].isDOMAttribute())
+ break;
+ }
+ found = (found < children.length) ? found : -1;
+ return found;
+ }
+}
\ No newline at end of file
diff --git a/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/resource/CacheEventNode.java b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/resource/CacheEventNode.java
new file mode 100644
index 0000000..e575833
--- /dev/null
+++ b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/resource/CacheEventNode.java
@@ -0,0 +1,585 @@
+/*******************************************************************************
+ * Copyright (c) 2003, 2004 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.wst.common.internal.emf.resource;
+
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.eclipse.emf.common.notify.Notifier;
+import org.eclipse.emf.ecore.EObject;
+import org.xml.sax.Attributes;
+
+
+/**
+ * CacheEventNodes (CENOs) store information collected from SAX Events. This information can then be
+ * used once all necessary SAX Events have been generated to create and/or set values on EMF model
+ * objects.
+ *
+ * CacheEventNodes (CENOs) have a simple lifecycle: initialize, collect data, commit, discard. When
+ * initialized, CENOs will attempt to find the appropriate translator for a given XML element name,
+ * and also create/set any necessary EMF model values. Data is collected as SAX character() events
+ * are generated. On the SAX endElement event, the CENO is committed(), which is where it will
+ * complete its processing to create EMF model features. In those cases where it cannot complete its
+ * processing, it will defer its processing to the updateEMF() method of its parent. Defered
+ * processing is necessary to handle EMF features that require read ahead cues from the XML. CENOs
+ * will add themselves to their parents as children in a tree data structure. When an CENO
+ * determines it is the golden piece of information required to instantiate its parent feature, it
+ * will trigger its parent CENO to process the rest of the cached CENO tree. As mentioned, the
+ * building of a CENO tree will only occur for nodes with read ahead cues.
+ *
+ * discard() is invoked by init() to ensure that no junk state is left from a previous use of the
+ * CENO. commit() will call discard as needed. Because of the use of discard, CENOs can be pooled
+ * and reused. If a CENO determines that it is contained in a pool, it will manage its own release
+ * from that pool. Self- management is necessary because of the way in which CENOs might cache
+ * certain children while waiting to create the parent EMF feature.
+ *
+ * @author mdelder
+ */
+public class CacheEventNode {
+
+ public static final String ROOT_NODE = "EMF_ROOT_NODE"; //$NON-NLS-1$
+
+ private String nodeName = null;
+ private Translator translator = null;
+ private Notifier emfOwner = null;
+ private StringBuffer buffer = null;
+ private List children = null;
+ private int versionID;
+
+ /*
+ * The internal data structure used to store the attributes is a String[]. The choice was made
+ * to use an array to avoid the creation of another object (probably a Hashtable) and to exploit
+ * array-access times to get the name and value of the attributes (opposed to full fledged
+ * method invocations).
+ *
+ */
+ private String[] attributes = null;
+ private CacheEventNode parent = null;
+ private CacheEventPool containingPool = null;
+ private Boolean ignorable = null;
+
+ public CacheEventNode(CacheEventPool containingPool) {
+ this.containingPool = containingPool;
+ }
+
+ /**
+ * Lifecycle method. init(TranslatorResource) will configure this Adapter as a ROOT node.
+ *
+ * This method will invoke discard() before completing its tasks.
+ */
+ public void init(TranslatorResource resource) {
+ this.discard();
+ this.setEmfOwner(resource);
+ this.setTranslator(resource.getRootTranslator());
+ this.setVersionID(resource.getVersionID());
+ this.nodeName = CacheEventNode.ROOT_NODE;
+ }
+
+ /**
+ * Lifecycle method. init(CacheEventNode, String, Attributes) will configure this Adapter to be
+ * a non-ROOT node of the Adapter data structure
+ *
+ * This method will invoke discard() before completing its tasks.
+ */
+ public void init(CacheEventNode parentArg, String nodeNameArg, Attributes attributesArg) {
+ this.discard();
+ this.nodeName = nodeNameArg;
+ init(parentArg, attributesArg);
+ }
+
+ private void init(CacheEventNode parentRecord, Attributes attributesArg) {
+ setParent(parentRecord);
+
+ setAttributes(attributesArg);
+ if (parent != null) {
+ /* I am not the root */
+
+ /*
+ * If the parent is part of the DOM Path, then we ignore it and interact with the grand
+ * parent
+ */
+ if (parent.translator != null && parent.isInDOMPath()) {
+ setParent(parent.getParent());
+ }
+
+ setVersionID(parent.getVersionID());
+ if (parent.getEmfOwner() != null && parent.getTranslator() != null) {
+
+ /* My parent had enough information to create themself */
+
+ if (parent.getParent() != null) {
+ setTranslator(parent.getTranslator().findChild(nodeName, parent.getEmfOwner(), getVersionID()));
+
+ } else {
+ setTranslator(parent.getTranslator());
+ }
+
+ if (this.translator == null) {
+ /* Our translator is null! Ahh! Run! */
+ throw new IllegalStateException("Parent Translator (" + parent.getTranslator() + //$NON-NLS-1$
+ ") did not find a Child Translator for \"" + //$NON-NLS-1$
+ nodeName + "\"."); //$NON-NLS-1$
+ }
+
+ if (this.translator.getReadAheadHelper(nodeName) == null && !this.translator.isManagedByParent()) {
+ /*
+ * I do not require a read ahead cue, and I am not managed by my parent so I can
+ * create an instance of my EMF object
+ */
+
+ Notifier myEmfOwner = this.translator.createEMFObject(getNodeName(), null);
+ setEmfOwner(myEmfOwner);
+ this.translator.setMOFValue(parent.getEmfOwner(), myEmfOwner);
+ }
+ /*
+ * Else I require a read ahead value or I am being managed by my parent, so I have
+ * no need to create an EMF object
+ */
+ }
+ /*
+ * Else I am not mapped to the EMF stack (XML Elements found in the DOMPath are ignored)
+ */
+ }
+ /* processAttributes is guarded and will not execute unless ready */
+ processAttributes();
+
+ }
+
+ /**
+ * commit() is invoked only if the CacheEventNode (CENO) has all the information they need and
+ * should be able to determine what to do to the EMF feature.
+ *
+ * The commit() method will invoke discard() when it has completed its tasks, if needed. Thus,
+ * after invoking this method, the CENO may have no meaningful state. If discard() is invoked,
+ * all previously held reference will be released in order to be made eligible for Garbage
+ * Collection.
+ *
+ */
+ public void commit() {
+
+ if (parent == null || this.isIgnorable()) {
+ discard();
+ releaseFromContainingPool();
+ return;
+ }
+
+ ReadAheadHelper helper = null;
+ Translator activeTranslator = getTranslator();
+ Translator parentTranslator = getParent().getTranslator();
+
+ if (parent != null && parent.getEmfOwner() == null) {
+
+ /*
+ * Not enough information yet, add the CacheEventNode to the DOM Cache tree
+ */
+
+ parent.appendToBuffer(this);
+ if ((helper = getParent().getReadAheadHelper()) != null) {
+ /*
+ * If the parentRecord's emfOwner is null, then it must not be initialized therefore
+ * it or one of its ancestors must require read ahead clues
+ *
+ * The following if statement checks if the parent is the node waiting for a
+ * readAhead cue
+ */
+ EObject parentOwner = null;
+ if (helper.nodeValueIsReadAheadName(getNodeName())) {
+ /* The readAheadName is the value of the qName child node */
+
+ /* We have enough information to create the EmfOwner in the parent! */
+ parentOwner = parentTranslator.createEMFObject(getParent().getNodeName(), getBuffer());
+
+ /*
+ * Now we need to parse the cached DOM tree and update the emfOwner of the
+ * parent
+ */
+ getParent().updateEMF(parentOwner);
+
+ } else if (helper.nodeNameIsReadAheadName(getNodeName())) {
+ /* The readAheadName is the actual name of the child node (qName) */
+
+ /* We have enough information to create the EmfOwner in the parent! */
+ parentOwner = parentTranslator.createEMFObject(getParent().getNodeName(), getNodeName());
+
+ /*
+ * Now we need to parse the cached DOM tree and update the emfOwner of the
+ * parent
+ */
+ getParent().updateEMF(parentOwner);
+ }
+
+ } /* Else an ancestor of the parent is waiting */
+
+ } else {
+ if (activeTranslator != null) {
+ if (activeTranslator.isManagedByParent()) {
+
+ Object value = activeTranslator.convertStringToValue(getNodeName(), null, getBuffer(), getParent().getEmfOwner());
+ activeTranslator.setMOFValue(getParent().getEmfOwner(), value);
+ processAttributes();
+ } else {
+
+ activeTranslator.setTextValueIfNecessary(getBuffer(), getEmfOwner(), getVersionID());
+ }
+
+ }
+ discard();
+ releaseFromContainingPool();
+ }
+ }
+
+ /**
+ * Instruct the CacheEventNode to discard all references to make everything eligible for garbage
+ * collection. This should ONLY be called after commit has succeeded. In the case of EMF
+ * features that require a readAheadName, process not be completed in commit(), but rather will
+ * be defered to the updateEMF() method. This method was made private specifically because it
+ * could erase all information contained in the CacheEventNode before it has been processed.
+ *
+ */
+ private void discard() {
+ translator = null;
+ emfOwner = null;
+ buffer = null;
+ if (children != null)
+ children.clear();
+ children = null;
+ attributes = null;
+ parent = null;
+ }
+
+ private void releaseFromContainingPool() {
+ if (containingPool != null)
+ containingPool.releaseNode(this);
+ }
+
+ public boolean isIgnorable() {
+ if (ignorable == null) {
+ boolean result = false;
+ if (this.translator != null) {
+ if (this.translator.isEmptyContentSignificant()) {
+ result = false;
+ } else {
+ String domPath = this.translator.getDOMPath();
+ result = (domPath != null) ? domPath.indexOf(this.nodeName) >= 0 : false;
+ }
+ }
+ ignorable = result ? Boolean.TRUE : Boolean.FALSE;
+ }
+ return ignorable.booleanValue();
+ }
+
+ /**
+ * Determines if a given child has a translator.
+ *
+ * @param childNodeName
+ * the name of the current XML child node
+ * @return true only if the childNodeName can be ignored (e.g. it is part of the DOM Path)
+ */
+ public boolean isChildIgnorable(String childNodeName) {
+ boolean result = false;
+
+ Translator childTranslator = null;
+ if (this.getTranslator() != null) {
+ childTranslator = this.getTranslator().findChild(childNodeName, this.getEmfOwner(), this.getVersionID());
+
+ if (childTranslator != null) {
+ if (childTranslator.isEmptyContentSignificant()) {
+ result = false;
+ } else {
+ String temp = null;
+ result = ((temp = childTranslator.getDOMPath()) != null) ? temp.indexOf(childNodeName) >= 0 : false;
+ }
+ }
+ }
+
+ return result;
+ }
+
+ public boolean isInDOMPath() {
+ boolean result = false;
+
+ if (this.getTranslator() != null) {
+
+ result = this.getNodeName().equals(this.getTranslator().getDOMPath());
+ }
+
+ return result;
+ }
+
+ public String toString() {
+ StringBuffer output = new StringBuffer("CacheEventNode[");//$NON-NLS-1$
+ output.append("nodeName=");//$NON-NLS-1$
+ output.append(nodeName);
+ output.append("; translator=");//$NON-NLS-1$
+ output.append(translator);
+ output.append("; emfOwner=");//$NON-NLS-1$
+ try {
+ output.append(emfOwner);
+ } catch (RuntimeException re) {
+ output.append("Could not render as string!");//$NON-NLS-1$
+ }
+ output.append("; buffer=");//$NON-NLS-1$
+ output.append(this.buffer);
+ output.append("; hasChildren=");//$NON-NLS-1$
+ output.append((children != null && children.size() > 0));
+ if (children != null) {
+ for (int i = 0; i < this.children.size(); i++) {
+ output.append("\n\tchildren(");//$NON-NLS-1$
+ output.append(i);
+ output.append("): ");//$NON-NLS-1$
+ output.append(this.children.get(i));
+ }
+ }
+ output.append("]");//$NON-NLS-1$
+ return output.toString();
+ }
+
+ /**
+ * Updates the EMF model by creating EMF Features as necessary from the DOM Tree Cache
+ *
+ * @param owner
+ */
+ public void updateEMF(EObject owner) {
+ this.setEmfOwner(owner);
+ if (this.parent != null) {
+ this.translator.setMOFValue((EObject) this.parent.getEmfOwner(), owner);
+ this.processAttributes();
+ }
+
+ this.updateEMF();
+ }
+
+ /**
+ * The translator and the owner of the parent CENO passed to this method should be nonnull
+ */
+ public void updateEMF() {
+ if (this.children == null)
+ return;
+
+ CacheEventNode child = null;
+ Translator childTranslator = null;
+ Object value = null;
+ if (this.getEmfOwner() != null) {
+ Notifier parentOwner = this.getEmfOwner();
+ Translator parentTranslator = this.getTranslator();
+ for (int i = 0; i < this.children.size(); i++) {
+
+ child = (CacheEventNode) this.children.get(i); /* Create the EMF feature */
+ if (this.isChildIgnorable(child.getNodeName())) {
+ this.addChildren(child.getChildren());
+ } else {
+ childTranslator = parentTranslator.findChild(child.getNodeName(), parentOwner, child.getVersionID());
+ child.setTranslator(childTranslator);
+
+ value = childTranslator.convertStringToValue(child.getNodeName(), null, child.getBuffer(), parentOwner);
+ childTranslator.setMOFValue(parentOwner, value);
+
+ if (childTranslator.isObjectMap()) {
+ child.setEmfOwner((Notifier) value);
+ childTranslator.setTextValueIfNecessary(child.getBuffer(), child.getEmfOwner(), getVersionID());
+ }
+
+ child.processAttributes();
+ child.updateEMF(); /* update the EMF of the child */
+
+ }
+ child.discard();
+ child.releaseFromContainingPool();
+ }
+ this.children = null;
+ }
+ }
+
+ public void addChild(CacheEventNode child) {
+ if (this.children == null) {
+ this.children = new ArrayList();
+ }
+ if (parent != null && this.isIgnorable()) {
+ parent.addChild(child);
+ } else {
+ this.children.add(child);
+ }
+ }
+
+ protected void addChildren(List childrenArg) {
+ if (this.children == null) {
+ this.children = new ArrayList();
+ }
+ this.children.addAll(childrenArg);
+ }
+
+ public boolean removeChild(CacheEventNode child) {
+ if (this.children == null) {
+ return false;
+ }
+ return this.children.remove(child);
+ }
+
+ public List getChildren() {
+ return this.children;
+ }
+
+ public ReadAheadHelper getReadAheadHelper() {
+ if (this.translator != null && this.translator.hasReadAheadNames()) {
+ return translator.getReadAheadHelper(nodeName);
+ }
+ return null;
+ }
+
+
+ /* See the documentation for the attributes field for info on how it is structured */
+ public void setAttributes(Attributes attr) {
+
+ /*
+ * The attributes returned from the parser may be stored by reference, so we must copy them
+ * over to a local data store
+ */
+ if (attr != null && attr.getLength() > 0) {
+
+ if (this.attributes == null) {
+ this.attributes = new String[attr.getLength() * 2];
+ }
+ for (int i = 0; i < attr.getLength(); i++) {
+ this.attributes[i] = attr.getQName(i);
+ this.attributes[i + attr.getLength()] = attr.getValue(i);
+ }
+
+ }
+ }
+
+ /**
+ * processAttributes may be invoked multiple times. It is configured to only carry out the
+ * processing one time. After it successfully completes the construction of Translators and
+ * values it will discard the value of the attributes field by setting it to null.
+ *
+ */
+ public void processAttributes() {
+ /* See the documentation for the attributes field for info on how it is structured */
+ if (this.attributes != null && this.attributes.length > 0) {
+
+ if (this.emfOwner != null && this.translator != null) {
+ Translator attrTranslator = null;
+ final int limit = this.attributes.length / 2;
+ Object value = null;
+ for (int i = 0; i < limit; i++) {
+
+ /* Find the attribute translator by using the attribute name (attributes[i]) */
+ attrTranslator = this.translator.findChild(this.attributes[i], this.emfOwner, this.versionID);
+
+ if (attrTranslator != null) {
+
+ /*
+ * Convert the value of corresponding attribute value (attributes[i+limit])
+ * to a meaningful value
+ */
+ value = attrTranslator.convertStringToValue(this.attributes[i + limit], (EObject) this.emfOwner);
+ attrTranslator.setMOFValue((EObject) this.emfOwner, value);
+ }
+ }
+
+ /* Forget the attributes so we do not process them again */
+ this.attributes = null;
+ }
+ }
+ }
+
+ /**
+ * Appends data to the buffer stored by this CENO. Text will be extracted from the data array
+ * begining at positiong <i>start </i> and ending at position <i>start+length </i>.
+ *
+ * @param data
+ * @param start
+ * @param length
+ */
+ public void appendToBuffer(char[] data, int start, int length) {
+
+ if (parent != null && this.isIgnorable()) {
+ parent.appendToBuffer(data, start, length);
+ return;
+ }
+
+ if (buffer == null) {
+ this.buffer = new StringBuffer();
+ }
+
+ /*
+ * acts as a more efficient form of "append". Using this method avoids the need to copy the
+ * data into its own data structure (e.g. String) before being added to the buffer
+ */
+ this.buffer.insert(buffer.length(), data, start, length);
+
+ }
+
+ /**
+ * Add the given CENO as a child of this CENO.
+ *
+ * @param record
+ */
+ public void appendToBuffer(CacheEventNode record) {
+
+ this.addChild(record);
+ }
+
+ public String getBuffer() {
+ if (this.buffer == null) {
+ return null;
+ }
+ return this.buffer.toString();
+ }
+
+ public Notifier getEmfOwner() {
+ return emfOwner;
+ }
+
+ public CacheEventNode getParent() {
+ return parent;
+ }
+
+ private void setParent(CacheEventNode record) {
+ this.parent = record;
+ }
+
+ public Translator getTranslator() {
+ return this.translator;
+ }
+
+ public void setEmfOwner(Notifier notifier) {
+
+ this.emfOwner = notifier;
+ }
+
+ public void setTranslator(Translator translator) {
+ this.translator = translator;
+ }
+
+ public String getNodeName() {
+ return nodeName;
+ }
+
+ public int getVersionID() {
+
+ if (this.parent == null) {
+ try {
+ return ((TranslatorResource) this.getEmfOwner()).getVersionID();
+
+ } catch (RuntimeException re) {
+ }
+ }
+ return this.versionID;
+ }
+
+ public void setVersionID(int i) {
+ versionID = i;
+ }
+
+
+}
\ No newline at end of file
diff --git a/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/resource/CacheEventPool.java b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/resource/CacheEventPool.java
new file mode 100644
index 0000000..55799e2
--- /dev/null
+++ b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/resource/CacheEventPool.java
@@ -0,0 +1,149 @@
+/*******************************************************************************
+ * Copyright (c) 2003, 2004 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.wst.common.internal.emf.resource;
+
+
+import java.util.ArrayList;
+import java.util.Collection;
+
+import org.xml.sax.Attributes;
+
+/**
+ * Provides an instance pool of reusable CacheEventNodes. The pool will default to 10 live
+ * instances. When its available instances reach five times its initial capacity, it will shrink
+ * itself down to the initial capacity.
+ *
+ * @author mdelder
+ */
+public class CacheEventPool {
+
+ public static final int DEFAULT_CAPACITY = 10;
+ public static final int DEFAULT_CAPACITY_INCREMENT = 25;
+
+ private int poolCapacity = DEFAULT_CAPACITY;
+ private CacheEventStack availablePool = null;
+ private Collection inusePool = null;
+
+ public CacheEventPool() {
+ this(DEFAULT_CAPACITY);
+ }
+
+ /**
+ * Create a CacheEventPOol with the given initial capacity
+ *
+ * @param initialCapacity
+ * The number of available instances to create.
+ */
+ public CacheEventPool(int initialCapacity) {
+ poolCapacity = (initialCapacity > 0) ? initialCapacity : DEFAULT_CAPACITY;
+ availablePool = new CacheEventStack();
+ inusePool = new ArrayList(poolCapacity);
+ }
+
+ /**
+ * Create a CacheEventNode (CENO) initialized to use the given resource as its EMF Owner.
+ *
+ * THIS METHOD SHOULD ONLY BE USED TO CREATE ROOT NODES.
+ *
+ * @param resource
+ * the resource that will be populated
+ * @return a CacheEventNode to serve as the root.
+ */
+ public CacheEventNode createCacheEventNode(TranslatorResource resource) {
+ CacheEventNode adapter = fetchFreeNode();
+ adapter.init(resource);
+ return adapter;
+ }
+
+ /**
+ * Create child CacheEventNodes (CENOs) that will branch from the given parent.
+ *
+ * @param parent
+ * the containing CENO
+ * @param nodeName
+ * The value of the XML element node name
+ * @param attributes
+ * The attributes that were part of the given XML element
+ * @return A CENO that has been properly initialized.
+ */
+ public CacheEventNode createCacheEventNode(CacheEventNode parent, String nodeName, Attributes attributes) {
+ CacheEventNode adapter = fetchFreeNode();
+ adapter.init(parent, nodeName, attributes);
+ return adapter;
+ }
+
+ /**
+ * Release the CacheEventNode CENO back to the pool of availabe instances. This method should
+ * not be invoked directly. CENOs which are acquired from a given pool will automatically
+ * release themselves when necessary.
+ *
+ * @param adapter
+ */
+ public void releaseNode(CacheEventNode adapter) {
+ freeNode(adapter);
+ }
+
+ /**
+ * freezePool() should be invoked to free any unused resources. After freezePool has been
+ * invoked, warmPool() will need to be invoked before the pool can be used again.
+ *
+ */
+ public void freezePool() {
+ availablePool.clear();
+ availablePool = null;
+ }
+
+ /**
+ * warmPool() must be invoked to notify the pool it is about to be used. This should occur only
+ * once per document rendering. Until the pool is in use, it contains no available
+ * CacheEventNodes (CENOs) in order to limit the size of the in-memory footprint of the
+ * EMF2SAXWriter.
+ *
+ */
+ public void warmPool() {
+ ensureMinimumCapacity();
+ }
+
+ private CacheEventNode fetchFreeNode() {
+ CacheEventNode result = null;
+
+ if (availablePool == null || availablePool.isEmpty())
+ warmPool();
+
+ result = availablePool.pop();
+ inusePool.add(result);
+
+ return result;
+ }
+
+ private void freeNode(CacheEventNode adapter) {
+ if (inusePool.remove(adapter))
+ availablePool.push(adapter);
+ //else
+ // throw new IllegalStateException("Adapter not contained in pool!");
+ if (availablePool.size() > (5 * poolCapacity)) {
+ availablePool.clear();
+ ensureMinimumCapacity();
+ }
+ }
+
+ private void ensureMinimumCapacity() {
+ if (availablePool == null) {
+ availablePool = new CacheEventStack();
+ }
+ if (availablePool.size() < poolCapacity) {
+ final int minimumCapacity = poolCapacity - availablePool.size();
+ for (int i = 0; i < minimumCapacity; i++)
+ availablePool.push(new CacheEventNode(this));
+ }
+ }
+
+}
\ No newline at end of file
diff --git a/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/resource/CacheEventStack.java b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/resource/CacheEventStack.java
new file mode 100644
index 0000000..03f4198
--- /dev/null
+++ b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/resource/CacheEventStack.java
@@ -0,0 +1,59 @@
+/*******************************************************************************
+ * Copyright (c) 2003, 2004 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+/*
+ * Created on Sep 24, 2003
+ *
+ */
+package org.eclipse.wst.common.internal.emf.resource;
+
+import java.util.ArrayList;
+import java.util.EmptyStackException;
+
+/**
+ * An unsynchronized implementation of a Stack (LIFO) data structure. No casting is required when
+ * using this data structure.
+ *
+ * @author mdelder
+ */
+public class CacheEventStack extends ArrayList {
+
+ /**
+ *
+ * @return the top of the stack without removing it
+ */
+ public CacheEventNode peek() {
+ if (size() == 0)
+ throw new EmptyStackException();
+
+ return (CacheEventNode) get(size() - 1);
+ }
+
+ /**
+ *
+ * @return the top of the stack and removing it
+ */
+ public CacheEventNode pop() {
+ if (size() == 0)
+ throw new EmptyStackException();
+
+ return (CacheEventNode) remove(size() - 1);
+ }
+
+ /**
+ *
+ * @param adapter
+ * A CENO to push onto the top of the stack
+ */
+ public void push(CacheEventNode adapter) {
+ add(adapter);
+ }
+
+}
\ No newline at end of file
diff --git a/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/resource/CompatibilityPackageMappingRegistry.java b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/resource/CompatibilityPackageMappingRegistry.java
new file mode 100644
index 0000000..25367c8
--- /dev/null
+++ b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/resource/CompatibilityPackageMappingRegistry.java
@@ -0,0 +1,53 @@
+/*******************************************************************************
+ * Copyright (c) 2003, 2004 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.wst.common.internal.emf.resource;
+
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * This class is used to register mappings for a package prefix to its current namespace URI. Also,
+ * this registry is used to map the package
+ */
+public class CompatibilityPackageMappingRegistry {
+ public static CompatibilityPackageMappingRegistry INSTANCE = new CompatibilityPackageMappingRegistry();
+ private Map prefixToPackageURIs = new HashMap();
+ private Map packageURIsToPrefixes = new HashMap();
+
+ /**
+ *
+ */
+ private CompatibilityPackageMappingRegistry() {
+ super();
+ }
+
+ /**
+ * @return
+ */
+ public Map getPackageURIsToPrefixes() {
+ return packageURIsToPrefixes;
+ }
+
+ /**
+ * @return
+ */
+ public Map getPrefixToPackageURIs() {
+ return prefixToPackageURIs;
+ }
+
+ public void registerPrefixToPackageURI(String prefix, String uri) {
+ if (prefix != null && uri != null) {
+ prefixToPackageURIs.put(prefix, uri);
+ packageURIsToPrefixes.put(uri, prefix);
+ }
+ }
+
+}
\ No newline at end of file
diff --git a/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/resource/CompatibilityResourceFactory.java b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/resource/CompatibilityResourceFactory.java
new file mode 100644
index 0000000..f824de3
--- /dev/null
+++ b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/resource/CompatibilityResourceFactory.java
@@ -0,0 +1,61 @@
+/*******************************************************************************
+ * Copyright (c) 2003, 2004 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+/*
+ * Created on Apr 23, 2003
+ *
+ * To change the template for this generated file go to
+ * Window>Preferences>Java>Code Generation>Code and Comments
+ */
+package org.eclipse.wst.common.internal.emf.resource;
+
+import java.util.Map;
+
+import org.eclipse.emf.common.util.URI;
+import org.eclipse.emf.ecore.resource.Resource;
+import org.eclipse.emf.ecore.xmi.impl.XMIResourceFactoryImpl;
+
+/**
+ * @author DABERG
+ *
+ * To change the template for this generated type comment go to Window>Preferences>Java>Code
+ * Generation>Code and Comments
+ */
+public class CompatibilityResourceFactory extends XMIResourceFactoryImpl {
+ /**
+ *
+ */
+ public CompatibilityResourceFactory() {
+ super();
+ }
+
+ protected Map prefixToPackageURIs;
+
+ protected Map packageURIsToPrefixes;
+
+ public Map getPrefixToPackageURI() {
+ return CompatibilityPackageMappingRegistry.INSTANCE.getPrefixToPackageURIs();
+ }
+
+ public Map getPackageURIsToPrefixes() {
+ return CompatibilityPackageMappingRegistry.INSTANCE.getPackageURIsToPrefixes();
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.eclipse.emf.ecore.xmi.impl.XMIResourceFactoryImpl#createResource(org.eclipse.emf.common.util.URI)
+ */
+ public Resource createResource(URI uri) {
+ return new CompatibilityXMIResourceImpl(uri);
+ }
+
+
+}
\ No newline at end of file
diff --git a/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/resource/CompatibilitySAXXMIHandler.java b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/resource/CompatibilitySAXXMIHandler.java
new file mode 100644
index 0000000..ee6ff3e
--- /dev/null
+++ b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/resource/CompatibilitySAXXMIHandler.java
@@ -0,0 +1,55 @@
+/*******************************************************************************
+ * Copyright (c) 2003, 2004 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+/*
+ * Created on Apr 30, 2003
+ *
+ * To change the template for this generated file go to
+ * Window>Preferences>Java>Code Generation>Code and Comments
+ */
+package org.eclipse.wst.common.internal.emf.resource;
+
+import java.util.Map;
+
+import org.eclipse.emf.ecore.xmi.XMLHelper;
+import org.eclipse.emf.ecore.xmi.XMLResource;
+import org.eclipse.emf.ecore.xmi.impl.SAXXMIHandler;
+
+/**
+ * @author DABERG
+ *
+ * To change the template for this generated type comment go to Window>Preferences>Java>Code
+ * Generation>Code and Comments
+ */
+public class CompatibilitySAXXMIHandler extends SAXXMIHandler {
+ protected final static String NULL_ATTRIB = XMLResource.XSI_NS + ":null"; //$NON-NLS-1$
+
+ /**
+ * @param xmiResource
+ * @param helper
+ * @param options
+ */
+ public CompatibilitySAXXMIHandler(XMLResource xmiResource, XMLHelper helper, Map options) {
+ super(xmiResource, helper, options);
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.eclipse.emf.ecore.xmi.impl.XMLHandler#isNull()
+ */
+ protected boolean isNull() {
+ boolean isnull = super.isNull();
+ if (!isnull)
+ isnull = attribs.getValue(NULL_ATTRIB) != null;
+ return isnull;
+ }
+
+}
\ No newline at end of file
diff --git a/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/resource/CompatibilityURIConverter.java b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/resource/CompatibilityURIConverter.java
new file mode 100644
index 0000000..ba135f5
--- /dev/null
+++ b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/resource/CompatibilityURIConverter.java
@@ -0,0 +1,17 @@
+/***************************************************************************************************
+ * Copyright (c) 2003, 2004 IBM Corporation 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: IBM Corporation - initial API and implementation
+ **************************************************************************************************/
+package org.eclipse.wst.common.internal.emf.resource;
+
+import org.eclipse.emf.common.util.URI;
+import org.eclipse.emf.ecore.resource.URIConverter;
+
+public interface CompatibilityURIConverter extends URIConverter {
+ URI deNormalize(URI uri);
+
+}
\ No newline at end of file
diff --git a/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/resource/CompatibilityXMILoadImpl.java b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/resource/CompatibilityXMILoadImpl.java
new file mode 100644
index 0000000..5f17a46
--- /dev/null
+++ b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/resource/CompatibilityXMILoadImpl.java
@@ -0,0 +1,48 @@
+/*******************************************************************************
+ * Copyright (c) 2003, 2004 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+/*
+ * Created on Apr 30, 2003
+ *
+ * To change the template for this generated file go to
+ * Window>Preferences>Java>Code Generation>Code and Comments
+ */
+package org.eclipse.wst.common.internal.emf.resource;
+
+import org.eclipse.emf.ecore.xmi.XMLHelper;
+import org.eclipse.emf.ecore.xmi.impl.SAXWrapper;
+import org.eclipse.emf.ecore.xmi.impl.XMILoadImpl;
+import org.xml.sax.helpers.DefaultHandler;
+
+/**
+ * @author DABERG
+ *
+ * To change the template for this generated type comment go to Window>Preferences>Java>Code
+ * Generation>Code and Comments
+ */
+public class CompatibilityXMILoadImpl extends XMILoadImpl {
+
+ /**
+ * @param helper
+ */
+ public CompatibilityXMILoadImpl(XMLHelper helper) {
+ super(helper);
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.eclipse.emf.ecore.xmi.impl.XMLLoadImpl#makeDefaultHandler()
+ */
+ protected DefaultHandler makeDefaultHandler() {
+ return new SAXWrapper(new CompatibilitySAXXMIHandler(resource, helper, options));
+ }
+
+}
\ No newline at end of file
diff --git a/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/resource/CompatibilityXMIResource.java b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/resource/CompatibilityXMIResource.java
new file mode 100644
index 0000000..a954f5f
--- /dev/null
+++ b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/resource/CompatibilityXMIResource.java
@@ -0,0 +1,41 @@
+/***************************************************************************************************
+ * Copyright (c) 2003, 2004 IBM Corporation 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: IBM Corporation - initial API and implementation
+ **************************************************************************************************/
+package org.eclipse.wst.common.internal.emf.resource;
+
+import org.eclipse.emf.ecore.EObject;
+import org.eclipse.emf.ecore.xmi.XMIResource;
+
+public interface CompatibilityXMIResource extends XMIResource {
+ int FORMAT_EMF1 = 0;
+ /**
+ * format for MOF5 compatibility; note that this can NOT be used with resources usings the
+ * "platform:/plugin" protocol"
+ */
+ int FORMAT_MOF5 = 1;
+
+ void addOriginalPackageURI(String packageUri, String originalUri);
+
+ int getFormat();
+
+ /**
+ * Set the serialization format. By default it is FORMAT_EMF1.
+ *
+ * @see CompatibilityXMIResource#FORMAT_EMF1
+ * @see CompatibilityXMIResource#FORMAT_MOF5
+ */
+ void setFormat(int format);
+
+ boolean usesDefaultFormat();
+
+ /**
+ * @param rootObject
+ */
+ void removePreservingIds(EObject rootObject);
+
+}
\ No newline at end of file
diff --git a/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/resource/CompatibilityXMIResourceImpl.java b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/resource/CompatibilityXMIResourceImpl.java
new file mode 100644
index 0000000..db9fe94
--- /dev/null
+++ b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/resource/CompatibilityXMIResourceImpl.java
@@ -0,0 +1,374 @@
+/*******************************************************************************
+ * Copyright (c) 2003, 2006 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.wst.common.internal.emf.resource;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.util.HashMap;
+import java.util.Map;
+
+import org.eclipse.emf.common.util.EList;
+import org.eclipse.emf.common.util.URI;
+import org.eclipse.emf.ecore.EObject;
+import org.eclipse.emf.ecore.InternalEObject;
+import org.eclipse.emf.ecore.xmi.XMLHelper;
+import org.eclipse.emf.ecore.xmi.XMLLoad;
+import org.eclipse.emf.ecore.xmi.XMLSave;
+import org.eclipse.emf.ecore.xmi.impl.XMIResourceImpl;
+import org.eclipse.wst.common.internal.emf.utilities.IDUtil;
+import org.eclipse.wst.common.internal.emf.utilities.ResourceIsLoadingAdapter;
+import org.eclipse.wst.common.internal.emf.utilities.ResourceIsLoadingAdapterFactory;
+
+
+public class CompatibilityXMIResourceImpl extends XMIResourceImpl implements CompatibilityXMIResource {
+ protected static final String DEFAULT_ENCODING = "UTF-8"; //$NON-NLS-1$
+ protected int format = FORMAT_EMF1;
+ protected Map originalPackageURIs = new HashMap();
+ private boolean preserveIDs = false;
+
+ private static final String PLATFORM_PROTOCOL = "platform"; //$NON-NLS-1$
+ private static final String PLATFORM_PLUGIN = "plugin"; //$NON-NLS-1$
+
+ /**
+ * Constructor for MappableXMIResourceImpl.
+ */
+ public CompatibilityXMIResourceImpl() {
+ super();
+ initDefaultSaveOptions();
+ }
+
+ public CompatibilityXMIResourceImpl(URI uri) {
+ super(uri);
+ initDefaultSaveOptions();
+ }
+
+ /**
+ * @see org.eclipse.emf.ecore.xmi.impl.XMIResourceImpl#createXMLHelper()
+ */
+ protected final XMLHelper createXMLHelper() {
+ MappedXMIHelper helper = doCreateXMLHelper();
+ helper.setPackageURIsToPrefixes(getPackageURIsToPrefixes());
+ return helper;
+ }
+
+ protected MappedXMIHelper doCreateXMLHelper() {
+ return new MappedXMIHelper(this, getPrefixToPackageURIs());
+ }
+
+ /**
+ * Subclasses should not need to override this method.
+ *
+ * @see CompatibilityPackageMappingRegistry#getPrefixToPackageURIs()
+ */
+ protected Map getPrefixToPackageURIs() {
+ return CompatibilityPackageMappingRegistry.INSTANCE.getPrefixToPackageURIs();
+ }
+
+ /**
+ * Subclasses should not need to override this method.
+ *
+ * @see CompatibilityPackageMappingRegistry#getPrefixToPackageURIs()
+ */
+ protected Map getPackageURIsToPrefixes() {
+ return CompatibilityPackageMappingRegistry.INSTANCE.getPackageURIsToPrefixes();
+ }
+
+ public void addOriginalPackageURI(String packageUri, String originalUri) {
+ originalPackageURIs.put(packageUri, originalUri);
+ }
+
+ public int getFormat() {
+ return format;
+ }
+
+ public void setFormat(int format) {
+ if (!isPlatformPluginResourceURI())
+ this.format = format;
+ }
+
+ private boolean isPlatformPluginResourceURI() {
+ URI aURI = getURI();
+
+ return aURI != null && PLATFORM_PROTOCOL.equals(uri.scheme()) && PLATFORM_PLUGIN.equals(uri.segment(0));
+ }
+
+ /**
+ * @see org.eclipse.emf.ecore.resource.Resource#getURIFragment(EObject)
+ */
+ public String getURIFragment(EObject eObject) {
+ if (usesDefaultFormat())
+ return super.getURIFragment(eObject);
+ return IDUtil.getOrAssignID(eObject, this);
+ }
+
+ public boolean usesDefaultFormat() {
+ return format == CompatibilityXMIResource.FORMAT_EMF1;
+ }
+
+ /**
+ * @see org.eclipse.emf.ecore.xmi.impl.XMIResourceImpl#createXMLSave()
+ */
+ protected XMLSave createXMLSave() {
+ if (usesDefaultFormat())
+ return super.createXMLSave();
+ return new CompatibilityXMISaveImpl(createXMLHelper());
+ }
+
+ /**
+ * @see org.eclipse.emf.ecore.xmi.impl.XMLResourceImpl#doSave(OutputStream, Map)
+ */
+ public void doSave(OutputStream outputStream, Map options) throws IOException {
+ super.doSave(outputStream, options);
+ }
+
+ /**
+ * Method initDefaultOptions.
+ */
+ protected void initDefaultSaveOptions() {
+ if (defaultSaveOptions == null) {
+ getDefaultSaveOptions();
+ }
+ }
+
+ /**
+ * @see org.eclipse.emf.ecore.resource.impl.ResourceImpl#getEObjectByID(String)
+ */
+ protected EObject getEObjectByID(String id) {
+ if (idToEObjectMap != null) {
+ EObject eObject = (EObject) idToEObjectMap.get(id);
+ if (eObject != null) {
+ return eObject;
+ }
+ }
+ return null;
+ }
+
+ /**
+ * Called when the object is unloaded. This implementation
+ * {@link InternalEObject#eSetProxyURI sets}the object to be a proxy and clears the
+ * {@link #eAdapters adapters}.
+ */
+ protected void unloaded(InternalEObject internalEObject) {
+ //overridden from the super class; call super.getURIFragment instead of the implementation
+ //at this level, to avoid ID generation during unload
+ //internalEObject.eSetProxyURI(uri.appendFragment(getURIFragment(internalEObject)));
+ internalEObject.eSetProxyURI(uri.appendFragment(super.getURIFragment(internalEObject)));
+ internalEObject.eAdapters().clear();
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.eclipse.emf.ecore.xmi.impl.XMLResourceImpl#doLoad(java.io.InputStream,
+ * java.util.Map)
+ */
+ public final void doLoad(InputStream inputStream, Map options) throws IOException {
+ basicDoLoad(inputStream, options);
+ }
+
+ /**
+ * @deprecated Use {@link #doLoad(InputStream, Map)} instead.
+ */
+ protected void basicDoLoad(InputStream inputStream, Map options) throws IOException {
+ super.doLoad(inputStream, options);
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.eclipse.emf.ecore.xmi.impl.XMLResourceImpl#init()
+ */
+ protected void init() {
+ super.init();
+ setEncoding(DEFAULT_ENCODING);
+ }
+
+ protected XMLLoad createXMLLoad() {
+ return new CompatibilityXMILoadImpl(createXMLHelper());
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.eclipse.wst.common.internal.emf.resource.CompatibilityXMIResource#removePreservingIds(org.eclipse.emf.ecore.EObject)
+ */
+ public void removePreservingIds(EObject rootObject) {
+ setPreserveIDs(true);
+ getContents().remove(rootObject);
+ }
+
+ /**
+ * @return Returns the preserveIDs.
+ */
+ public boolean isPreserveIDs() {
+ return preserveIDs;
+ }
+
+ /**
+ * @param preserveIDs
+ * The preserveIDs to set.
+ */
+ public void setPreserveIDs(boolean preserveIDs) {
+ this.preserveIDs = preserveIDs;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.eclipse.emf.ecore.xmi.impl.XMLResourceImpl#detachedHelper(org.eclipse.emf.ecore.EObject)
+ */
+ protected void detachedHelper(EObject eObject) {
+ if (modificationTrackingAdapter != null) {
+ eObject.eAdapters().remove(modificationTrackingAdapter);
+ }
+
+ if (useUUIDs()) {
+ DETACHED_EOBJECT_TO_ID_MAP.put(eObject, getID(eObject));
+ }
+
+ if (!isPreserveIDs() && idToEObjectMap != null && eObjectToIDMap != null) {
+ idToEObjectMap.remove(eObjectToIDMap.remove(eObject));
+ }
+ }
+
+ public void load(Map options) throws IOException {
+
+ ResourceIsLoadingAdapter adapter = null;
+ if (isLoaded) {
+ adapter = ResourceIsLoadingAdapter.findAdapter(this);
+ if (adapter != null)
+ adapter.waitForResourceToLoad();
+ return;
+ }
+ synchronized (this) {
+ adapter = ResourceIsLoadingAdapter.findAdapter(this);
+ if (adapter == null && !isLoaded)
+ addSynchronizationLoadingAdapter();
+ }
+ if(adapter != null)
+ adapter.waitForResourceToLoad();
+ else {
+ try {
+ super.load(options);
+ } catch(IOException ioe) {
+ removeLoadingSynchronizationAdapter();
+ throw ioe;
+ } catch(RuntimeException re) {
+ removeLoadingSynchronizationAdapter();
+ throw re;
+ } catch(Error e) {
+ removeLoadingSynchronizationAdapter();
+ throw e;
+ }
+ }
+ }
+ public void loadExisting(Map options) throws IOException {
+
+
+ ResourceIsLoadingAdapter adapter = null;
+ if (isLoaded) {
+ adapter = ResourceIsLoadingAdapter.findAdapter(this);
+ if (adapter != null)
+ adapter.waitForResourceToLoad();
+ return;
+ }
+ synchronized (this) {
+ adapter = ResourceIsLoadingAdapter.findAdapter(this);
+ if (adapter == null && !isLoaded)
+ addSynchronizationLoadingAdapter();
+ }
+ if(adapter != null)
+ adapter.waitForResourceToLoad();
+ else {
+ try {
+ load((InputStream) null, options);
+ } catch(IOException ioe) {
+ removeLoadingSynchronizationAdapter();
+ throw ioe;
+ } catch(RuntimeException re) {
+ removeLoadingSynchronizationAdapter();
+ throw re;
+ } catch(Error e) {
+ removeLoadingSynchronizationAdapter();
+ throw e;
+ }
+ }
+ }
+
+ /**
+ *
+ */
+ protected void addSynchronizationLoadingAdapter() {
+ synchronized (eAdapters()) {
+ if (ResourceIsLoadingAdapter.findAdapter(this) == null)
+ eAdapters().add(ResourceIsLoadingAdapterFactory.INSTANCE.createResourceIsLoadingAdapter());
+ }
+ }
+
+ /**
+ *
+ */
+ protected void removeLoadingSynchronizationAdapter() {
+ ResourceIsLoadingAdapter adapter = ResourceIsLoadingAdapter.findAdapter(this);
+ if (adapter != null) {
+ adapter.forceRelease();
+ eAdapters().remove(adapter);
+ }
+ }
+
+ /**
+ * Case 1: LOAD RESOURCE FROM DISK this.isLoaded == false AND isLoaded ==
+ * true (which means we entered the load() method, but have not completed
+ * the load), and we're loading from a resource on disk, then we add the
+ * adapter Case 2: RESOURCE CREATION (NOT A LOAD) Case 4: RESOURCE CREATION,
+ * UNLOADED, NEW CONTENTS (NOT A LOAD) Resource is created but not from a
+ * resource on disk, so contents is null AND not empty, so no adapter: THIS
+ * IS NOT A LOAD Case 3: RESOURCE HAS BEEN UNLOADED, BEING RELOADED FROM
+ * DISK Contents is NOT null, but it is Empty and the resource is being
+ * loaded from disk. We must add the adapter.
+ *
+ */
+ public boolean isResourceBeingLoaded(boolean isLoaded) {
+ return (!this.isLoaded && isLoaded) && (contents == null || contents.isEmpty());
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.eclipse.emf.ecore.resource.Resource#getContents()
+ */
+ public EList getContents() {
+ waitForResourceToLoadIfNecessary();
+ return super.getContents();
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.eclipse.emf.ecore.resource.impl.ResourceImpl#isLoaded()
+ */
+ public boolean isLoaded() {
+ waitForResourceToLoadIfNecessary();
+ return super.isLoaded();
+ }
+
+ /**
+ *
+ */
+ protected final void waitForResourceToLoadIfNecessary() {
+ ResourceIsLoadingAdapter loadingAdapter = ResourceIsLoadingAdapter.findAdapter(this);
+ if (loadingAdapter != null) loadingAdapter.waitForResourceToLoad();
+ }
+
+
+
+}
diff --git a/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/resource/CompatibilityXMISaveImpl.java b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/resource/CompatibilityXMISaveImpl.java
new file mode 100644
index 0000000..c1a7bf2
--- /dev/null
+++ b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/resource/CompatibilityXMISaveImpl.java
@@ -0,0 +1,127 @@
+/***************************************************************************************************
+ * Copyright (c) 2003, 2004 IBM Corporation 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: IBM Corporation - initial API and implementation
+ **************************************************************************************************/
+package org.eclipse.wst.common.internal.emf.resource;
+
+import java.util.Map;
+
+import org.eclipse.emf.common.util.URI;
+import org.eclipse.emf.ecore.EClass;
+import org.eclipse.emf.ecore.EObject;
+import org.eclipse.emf.ecore.EPackage;
+import org.eclipse.emf.ecore.EStructuralFeature;
+import org.eclipse.emf.ecore.resource.Resource;
+import org.eclipse.emf.ecore.util.EcoreUtil;
+import org.eclipse.emf.ecore.xmi.XMIResource;
+import org.eclipse.emf.ecore.xmi.XMLHelper;
+import org.eclipse.emf.ecore.xmi.XMLResource;
+import org.eclipse.emf.ecore.xmi.impl.XMISaveImpl;
+
+public class CompatibilityXMISaveImpl extends XMISaveImpl {
+
+ /**
+ * Constructor for CompatibilityXMISaveImpl.
+ *
+ * @param helper
+ */
+ public CompatibilityXMISaveImpl(XMLHelper helper) {
+ super(helper);
+ }
+
+ /**
+ * Constructor for CompatibilityXMISaveImpl.
+ *
+ * @param options
+ * @param helper
+ * @param encoding
+ */
+ public CompatibilityXMISaveImpl(Map options, XMLHelper helper, String encoding) {
+ super(options, helper, encoding);
+ }
+
+ /**
+ * @see org.eclipse.emf.ecore.xmi.impl.XMISaveImpl#init(XMLResource, Map)
+ */
+ protected void init(XMLResource resource, Map options) {
+ super.init(resource, options);
+ xmiType = true;
+ }
+
+ /**
+ * @see org.eclipse.emf.ecore.xmi.impl.XMISaveImpl#addNamespaceDeclarations()
+ */
+ public void addNamespaceDeclarations() {
+ doc.addAttribute(XMI_VER_NS, XMIResource.VERSION_VALUE);
+ doc.addAttribute(XMI_XMLNS, XMIResource.XMI_URI);
+ EPackage[] packages = helper.packages();
+ StringBuffer xsiSchemaLocation = null;
+ if (declareSchemaLocation) {
+ for (int i = 0; i < packages.length; i++) {
+ EPackage ePackage = packages[i];
+
+ EObject root = EcoreUtil.getRootContainer(ePackage);
+ if (root instanceof EPackage) {
+ EPackage rootEPackage = (EPackage) root;
+ Resource resource = rootEPackage.eResource();
+ if (resource != null) {
+ URI uri = resource.getURI();
+ String rootNsURI = rootEPackage.getNsURI();
+ if (uri == null ? rootNsURI != null : !uri.toString().equals(rootNsURI)) {
+ declareXSI = true;
+ if (xsiSchemaLocation == null) {
+ xsiSchemaLocation = new StringBuffer();
+ } else {
+ xsiSchemaLocation.append(' ');
+ }
+ xsiSchemaLocation.append(rootNsURI);
+ xsiSchemaLocation.append(' ');
+ xsiSchemaLocation.append(helper.getHREF(rootEPackage));
+ }
+ }
+ }
+ }
+ }
+
+ if (declareXSI) {
+ doc.addAttribute(XSI_XMLNS, XMLResource.XSI_URI);
+ }
+
+ for (int i = 0; i < packages.length; i++) {
+ EPackage ePackage = packages[i];
+ //Modified from superclass - dispatch back to helper for compatibility
+ //String nsURI = ePackage.getNsURI();
+ //String nsPrefix = ePackage.getNsPrefix();
+ String[] nsInfo = ((MappedXMIHelper) helper).getNSInfo(ePackage);
+ doc.addAttributeNS(XMLResource.XML_NS, nsInfo[0], nsInfo[1]);
+ }
+
+ if (xsiSchemaLocation != null) {
+ doc.addAttribute(XSI_SCHEMA_LOCATION, xsiSchemaLocation.toString());
+ }
+ }
+
+ protected void saveHref(EObject remote, EStructuralFeature f) {
+ String name = helper.getQName(f);
+ String href = helper.getHREF(remote);
+ if (href != null) {
+ doc.startElement(name);
+ EClass eClass = remote.eClass();
+
+ EClass expectedType = (EClass) f.getEType();
+ //Changed next line to always write type if expectedType
+ //is different from eClass
+ if (eClass != expectedType) {
+ saveTypeAttribute(eClass);
+ }
+
+ doc.addAttribute(XMLResource.HREF, href);
+ doc.endEmptyElement();
+ }
+ }
+
+}
\ No newline at end of file
diff --git a/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/resource/ConstantAttributeTranslator.java b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/resource/ConstantAttributeTranslator.java
new file mode 100644
index 0000000..356f102
--- /dev/null
+++ b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/resource/ConstantAttributeTranslator.java
@@ -0,0 +1,54 @@
+/*******************************************************************************
+ * Copyright (c) 2003, 2004 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+/*
+ * Created on Apr 15, 2003
+ *
+ */
+package org.eclipse.wst.common.internal.emf.resource;
+
+import org.eclipse.emf.ecore.EObject;
+
+/**
+ * @author schacher
+ */
+public class ConstantAttributeTranslator extends Translator {
+
+ protected String attributeValue;
+
+ /**
+ * @param domNameAndPath
+ * @param eClass
+ */
+ public ConstantAttributeTranslator(String domNameAndPath, String attributeValue) {
+ super(domNameAndPath, null, DOM_ATTRIBUTE);
+ this.attributeValue = attributeValue;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see com.ibm.etools.emf2xml.impl.Translator#getMOFValue(org.eclipse.emf.ecore.EObject)
+ */
+ public Object getMOFValue(EObject mofObject) {
+ return attributeValue;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see com.ibm.etools.emf2xml.impl.Translator#isSetMOFValue(org.eclipse.emf.ecore.EObject)
+ */
+ public boolean isSetMOFValue(EObject emfObject) {
+ return true;
+ }
+
+
+}
\ No newline at end of file
diff --git a/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/resource/DefaultTranslatorFactory.java b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/resource/DefaultTranslatorFactory.java
new file mode 100644
index 0000000..06abce5
--- /dev/null
+++ b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/resource/DefaultTranslatorFactory.java
@@ -0,0 +1,101 @@
+/*******************************************************************************
+ * Copyright (c) 2003, 2005 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+/*
+ * Created on Aug 20, 2003
+ *
+ */
+package org.eclipse.wst.common.internal.emf.resource;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.eclipse.emf.common.notify.Notification;
+import org.eclipse.emf.common.notify.Notifier;
+import org.eclipse.emf.ecore.EObject;
+import org.eclipse.wst.common.internal.emf.utilities.Namespace;
+import org.eclipse.wst.common.internal.emf.utilities.NamespaceAdapter;
+
+
+/**
+ * @author schacher
+ */
+public class DefaultTranslatorFactory implements VariableTranslatorFactory {
+
+ public static final String XMLNS = "xmlns:"; //$NON-NLS-1$
+ public static final DefaultTranslatorFactory INSTANCE = new DefaultTranslatorFactory();
+
+ public DefaultTranslatorFactory() {
+ super();
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see com.ibm.etools.emf2xml.impl.VariableTranslatorFactory#accepts(java.lang.String)
+ */
+ public boolean accepts(String domName) {
+ return domName != null && domName.startsWith(XMLNS);
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see com.ibm.etools.emf2xml.impl.VariableTranslatorFactory#accepts(org.eclipse.emf.common.notify.Notification)
+ */
+ public boolean accepts(Notification notif) {
+ return notif.getFeature() == NamespaceAdapter.NOTIFICATION_FEATURE;
+ }
+
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see com.ibm.etools.emf2xml.impl.VariableTranslatorFactory#create(java.lang.String)
+ */
+ public Translator create(String domName) {
+ return new NamespaceTranslator(domName);
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see com.ibm.etools.emf2xml.impl.VariableTranslatorFactory#create(org.eclipse.emf.ecore.EObject)
+ */
+ public List create(Notifier target) {
+ if (!(target instanceof EObject))
+ return null;
+ List namespaces = NamespaceAdapter.getNamespaces((EObject) target);
+ if (namespaces == null || namespaces.isEmpty())
+ return null;
+ List result = new ArrayList(namespaces.size());
+ for (int i = 0; i < namespaces.size(); i++) {
+ result.add(create((Namespace) namespaces.get(i)));
+ }
+ return result;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see com.ibm.etools.emf2xml.impl.VariableTranslatorFactory#create(org.eclipse.emf.common.notify.Notification)
+ */
+ public Translator create(Notification notif) {
+ Namespace ns = (Namespace) notif.getNewValue();
+ return create(ns);
+ }
+
+ private Translator create(Namespace ns) {
+ return new NamespaceTranslator(XMLNS + ns.getPrefix());
+ }
+
+
+
+}
diff --git a/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/resource/DependencyTranslator.java b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/resource/DependencyTranslator.java
new file mode 100644
index 0000000..c7d1c62
--- /dev/null
+++ b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/resource/DependencyTranslator.java
@@ -0,0 +1,95 @@
+/*******************************************************************************
+ * Copyright (c) 2003, 2004 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+/*
+ * Created on Mar 25, 2003
+ *
+ */
+package org.eclipse.wst.common.internal.emf.resource;
+
+import java.util.List;
+
+import org.eclipse.emf.common.notify.Notifier;
+import org.eclipse.emf.ecore.EObject;
+import org.eclipse.emf.ecore.EStructuralFeature;
+
+/**
+ * @author schacher
+ */
+public class DependencyTranslator extends Translator {
+
+ /**
+ * @param domNameAndPath
+ * @param aFeature
+ */
+ public DependencyTranslator(String domNameAndPath, EStructuralFeature aFeature, EStructuralFeature aDependentFeature) {
+ super(domNameAndPath, aFeature);
+ dependencyFeature = aDependentFeature;
+ }
+
+ public EObject getChild(EObject parent) {
+ EObject child = basicGetDependencyObject(parent);
+ if (child == null)
+ return createChild(parent);
+ return child;
+ }
+
+
+ protected EObject createChild(EObject parent) {
+ EObject child = createEMFObject(dependencyFeature);
+ parent.eSet(dependencyFeature, child);
+ return child;
+ }
+
+ public List getMOFChildren(EObject mofObject) {
+ //return super.getMOFChildren(getChild(mofObject));
+ return super.getMOFChildren(mofObject);
+ }
+
+ public Object getMOFValue(EObject mofObject) {
+ return super.getMOFValue(getChild(mofObject));
+ }
+
+ public void setMOFValue(EObject emfObject, Object value) {
+ //super.setMOFValue(getChild(emfObject), value);
+ super.setMOFValue(getChild(emfObject), value, -1);
+ }
+
+ public void setMOFValue(Notifier owner, Object value, int newIndex) {
+ super.setMOFValue(getChild((EObject) owner), value, newIndex);
+ }
+
+ public void removeMOFValue(Notifier owner, Object value) {
+ super.removeMOFValue(getChild((EObject) owner), value);
+ }
+
+ public boolean isSetMOFValue(EObject emfObject) {
+ return super.isSetMOFValue(getChild(emfObject));
+ }
+
+ public void unSetMOFValue(EObject emfObject) {
+ super.unSetMOFValue(getChild(emfObject));
+ }
+
+
+ public boolean isDependencyChild() {
+ return true;
+ }
+
+ public boolean featureExists(EObject emfObject) {
+ return super.featureExists(getChild(emfObject));
+ }
+
+ public void clearList(EObject mofObject) {
+ super.clearList(getChild(mofObject));
+ }
+
+
+}
\ No newline at end of file
diff --git a/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/resource/EMF2DOMAdapter.java b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/resource/EMF2DOMAdapter.java
new file mode 100644
index 0000000..9782ea1
--- /dev/null
+++ b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/resource/EMF2DOMAdapter.java
@@ -0,0 +1,68 @@
+/***************************************************************************************************
+ * Copyright (c) 2003, 2004 IBM Corporation 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: IBM Corporation - initial API and implementation
+ **************************************************************************************************/
+package org.eclipse.wst.common.internal.emf.resource;
+
+
+import org.eclipse.emf.common.notify.Adapter;
+import org.eclipse.emf.ecore.EObject;
+import org.w3c.dom.Node;
+
+public interface EMF2DOMAdapter extends Adapter {
+
+
+ Class ADAPTER_CLASS = EMF2DOMAdapter.class;
+
+ /**
+ * Return the DOM node that the target of this adapter maps to. If the target MOF object maps to
+ * more than one DOM node, this node is the top-most node.
+ */
+ Node getNode();
+
+ void setNode(Node aNode);
+
+ /**
+ * Set to false and notification of changes from both the DOM node and the MOF object will be
+ * ignored.
+ */
+ boolean isNotificationEnabled();
+
+ /**
+ * Set to false and notification of changes from both the DOM node and the MOF object will be
+ * ignored.
+ */
+ void setNotificationEnabled(boolean isEnabled);
+
+ /**
+ * Updates the DOM tree for this adapter from the current values of the MOF Object. This method
+ * updates ALL the DOM nodes from all the MOF attributes.
+ */
+ void updateDOM();
+
+ /**
+ * Updates the MOF Object from the DOM tree. All the children of the DOM tree are updated into
+ * the MOF object.
+ */
+ void updateMOF();
+
+ public void updateDOMFeature(Translator map, Node node, EObject mofObject);
+
+ public void updateMOFFeature(Translator map, Node node, EObject mofObject);
+
+ EObject getEObject();
+
+ /**
+ * Return true if MOF object is a proxy.
+ */
+ boolean isMOFProxy();
+
+ /**
+ * Remove the DOM adapters from the node AND all its child nodes, recursively.
+ */
+ void removeAdapters(Node node);
+}
\ No newline at end of file
diff --git a/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/resource/EMF2DOMAdapterImpl.java b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/resource/EMF2DOMAdapterImpl.java
new file mode 100644
index 0000000..124c727
--- /dev/null
+++ b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/resource/EMF2DOMAdapterImpl.java
@@ -0,0 +1,1802 @@
+/*******************************************************************************
+ * Copyright (c) 2003, 2007 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.wst.common.internal.emf.resource;
+
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashSet;
+import java.util.Hashtable;
+import java.util.Iterator;
+import java.util.List;
+
+import org.eclipse.emf.common.notify.Adapter;
+import org.eclipse.emf.common.notify.Notification;
+import org.eclipse.emf.common.notify.Notifier;
+import org.eclipse.emf.common.notify.impl.AdapterImpl;
+import org.eclipse.emf.common.util.EList;
+import org.eclipse.emf.ecore.EObject;
+import org.eclipse.emf.ecore.EReference;
+import org.eclipse.emf.ecore.EStructuralFeature;
+import org.eclipse.emf.ecore.InternalEObject;
+import org.eclipse.emf.ecore.resource.Resource;
+import org.eclipse.emf.ecore.util.EcoreUtil;
+import org.eclipse.wst.common.internal.emf.utilities.Assert;
+import org.eclipse.wst.common.internal.emf.utilities.DOMUtilities;
+import org.eclipse.wst.common.internal.emf.utilities.EtoolsCopySession;
+import org.eclipse.wst.common.internal.emf.utilities.ExtendedEcoreUtil;
+import org.eclipse.wst.common.internal.emf.utilities.FeatureValueConversionException;
+import org.eclipse.wst.common.internal.emf.utilities.Revisit;
+import org.eclipse.wst.common.internal.emf.utilities.StringUtil;
+import org.eclipse.wst.common.internal.emf.utilities.TranslatorService;
+import org.eclipse.wst.common.internal.emf.utilities.WFTUtilsResourceHandler;
+import org.w3c.dom.Attr;
+import org.w3c.dom.Document;
+import org.w3c.dom.DocumentType;
+import org.w3c.dom.Element;
+import org.w3c.dom.NamedNodeMap;
+import org.w3c.dom.Node;
+import org.w3c.dom.NodeList;
+import org.w3c.dom.Text;
+
+
+public class EMF2DOMAdapterImpl extends AdapterImpl implements EMF2DOMAdapter {
+
+ final protected static boolean fDebug = false;
+
+ protected boolean fNotificationEnabled = true;
+
+ protected Node fNode;
+
+ protected Translator fTranslator;
+
+ protected EMF2DOMRenderer fRenderer;
+
+ protected Translator[] childTranslators;
+
+ protected boolean isRoot = false;
+
+ private static final String PLATFORM = "org.eclipse.core.runtime.Platform"; //$NON-NLS-1$
+ private static final String ISRUNNING = "isRunning"; //$NON-NLS-1$
+
+ private class DependencyAdapter extends org.eclipse.emf.common.notify.impl.AdapterImpl {
+
+ static final String KEY = "EMF2DOMDependencyAdapter"; //$NON-NLS-1$
+
+ public void notifyChanged(Notification msg) {
+ EMF2DOMAdapterImpl.this.notifyChanged(msg);
+ }
+
+ /**
+ * @see org.eclipse.emf.common.notify.impl.AdapterImpl#isAdapterForType(Object)
+ */
+ public boolean isAdapterForType(Object type) {
+ return KEY.equals(type);
+ }
+ }
+
+ /**
+ * Constructor for root adapters.
+ */
+ public EMF2DOMAdapterImpl(TranslatorResource resource, Document document, EMF2DOMRenderer renderer, Translator translator) {
+ this((Notifier) resource, (Node) document, renderer, translator);
+ isRoot = true;
+ }
+
+ /**
+ * Construct an Adapter given an EObject and a node
+ */
+ public EMF2DOMAdapterImpl(Notifier object, Node node, EMF2DOMRenderer renderer, Translator translator) {
+ super();
+ setTarget(object);
+ fNode = node;
+ fRenderer = renderer;
+ fTranslator = translator;
+ initChildTranslators();
+ addEMFAdapter();
+ addDOMAdapter();
+ addDependencyAdapterIfNecessary();
+ }
+
+ /**
+ * Construct an adapter from a DOM Node. The EObject will be created
+ */
+ public EMF2DOMAdapterImpl(Node node, EMF2DOMRenderer renderer, Translator translator) {
+ fNode = node;
+ fRenderer = renderer;
+ fTranslator = translator;
+ setTargetFromNode();
+ initChildTranslators();
+ addEMFAdapter();
+ addDOMAdapter();
+ addDependencyAdapterIfNecessary();
+
+ }
+
+ protected void addDependencyAdapterIfNecessary() {
+ if (!fTranslator.isDependencyParent())
+ return;
+ EObject child = fTranslator.basicGetDependencyObject(getEObject());
+ if (child != null)
+ addDependencyAdapter(child);
+ }
+
+ protected void initChildTranslators() {
+ List children = new ArrayList();
+ boolean isRunning = false; //is the OSGI platform running ?
+ try {
+ // If the Platform class can be found, then continue to check if the OSGI platform is running
+ Class clazz = Class.forName(PLATFORM);
+ Method m = clazz.getMethod(ISRUNNING, null);
+ isRunning = ((Boolean)m.invoke(clazz, null)).booleanValue();
+ } catch (ClassNotFoundException e) {
+ // Ignore because this must be in a non_OSGI environment
+ } catch (SecurityException e) {
+ // Ignore because this must be in a non_OSGI environment
+ } catch (NoSuchMethodException e) {
+ // Ignore because this must be in a non_OSGI environment
+ } catch (IllegalArgumentException e) {
+ // Ignore because this must be in a non_OSGI environment
+ } catch (IllegalAccessException e) {
+ // Ignore because this must be in a non_OSGI environment
+ } catch (InvocationTargetException e) {
+ // Ignore because this must be in a non_OSGI environment
+ }
+ //Check for extended child translators because we are in OSGI mode
+ if (isRunning) {
+ Translator[] extendedChildren = TranslatorService.getInstance().getTranslators();
+ for (int i = 0; i < extendedChildren.length; i++) {
+ if (extendedChildren[i] != null)
+ children.add(extendedChildren[i]);
+ }
+ }
+
+
+ children.addAll(Arrays.asList(fTranslator.getChildren(getTarget(), fRenderer.getVersionID())));
+
+ VariableTranslatorFactory factory = fTranslator.getVariableTranslatorFactory();
+ if (factory != null) {
+ String domName = null;
+ NamedNodeMap map = fNode.getAttributes();
+
+ if (map != null) {
+ int length = map.getLength();
+ for (int i = 0; i < length; i++) {
+ Node attrNode = map.item(i);
+ domName = attrNode.getNodeName();
+ //Handle variable translators
+ Translator t = fTranslator.findChild(domName, getTarget(), fRenderer.getVersionID());
+ if (t != null && !children.contains(t))
+ children.add(t);
+ }
+ }
+ List childrenFromEMF = factory.create(getTarget());
+ if (childrenFromEMF != null)
+ children.addAll(childrenFromEMF);
+ }
+
+ childTranslators = (Translator[]) children.toArray(new Translator[children.size()]);
+ }
+
+ /**
+ * Set to false and notification of changes from both the DOM node and the MOF object will be
+ * ignored.
+ */
+ public boolean isNotificationEnabled() {
+ return fNotificationEnabled;
+ }
+
+ /**
+ * Set to false and notification of changes from both the DOM node and the MOF object will be
+ * ignored.
+ */
+ public void setNotificationEnabled(boolean isEnabled) {
+ fNotificationEnabled = isEnabled;
+ }
+
+ public boolean isAdapterForType(Object type) {
+ return EMF2DOMAdapter.ADAPTER_CLASS == type;
+ }
+
+ protected void addEMFAdapter() {
+ target.eAdapters().add(this);
+ }
+
+ public String toString() {
+ StringBuffer sb = new StringBuffer();
+ sb.append(shortClassName(this));
+ sb.append('(');
+ sb.append(getNode().getNodeName());
+ sb.append(',');
+ sb.append(shortClassName(getTarget()));
+ sb.append(')');
+ return sb.toString();
+ }
+
+ protected String shortClassName(Object o) {
+ if (o != null) {
+ String cn = o.getClass().getName();
+ int i = cn.lastIndexOf('.');
+ return cn.substring(i + 1, cn.length());
+ }
+ return null;
+ }
+
+ /*
+ * Prints out a MOF notification for debugging
+ */
+ protected void debugMOFNotify(Notification msg) {
+ if (fDebug) {
+ String notifType = ""; //$NON-NLS-1$
+ switch (msg.getEventType()) {
+ case Notification.ADD :
+ notifType = "ADD"; //$NON-NLS-1$
+ break;
+ case Notification.REMOVE :
+ notifType = "REMOVE"; //$NON-NLS-1$
+ break;
+ case Notification.ADD_MANY :
+ notifType = "ADD_MANY"; //$NON-NLS-1$
+ break;
+ case Notification.REMOVE_MANY :
+ notifType = "REMOVE_MANY"; //$NON-NLS-1$
+ break;
+ case Notification.SET : {
+ if (msg.getPosition() == Notification.NO_INDEX)
+ notifType = "REPLACE"; //$NON-NLS-1$
+ else
+ notifType = "SET"; //$NON-NLS-1$
+ break;
+ }
+ case Notification.UNSET :
+ notifType = "UNSET"; //$NON-NLS-1$
+ break;
+ }
+
+ org.eclipse.jem.util.logger.proxy.Logger.getLogger().logError("MOF Change: " + notifType); //$NON-NLS-1$
+ org.eclipse.jem.util.logger.proxy.Logger.getLogger().logError("\tnotifier : " + msg.getNotifier()); //$NON-NLS-1$
+ org.eclipse.jem.util.logger.proxy.Logger.getLogger().logError("\tchangedFeature: " + msg.getFeature()); //$NON-NLS-1$
+ org.eclipse.jem.util.logger.proxy.Logger.getLogger().logError("\toldValue : " + msg.getOldValue()); //$NON-NLS-1$
+ org.eclipse.jem.util.logger.proxy.Logger.getLogger().logError("\tnewValue : " + msg.getNewValue()); //$NON-NLS-1$
+ }
+ }
+
+ /*
+ * Override this method to create the feature maps for the adapter.
+ */
+ protected Translator[] getChildTranslators() {
+ return childTranslators;
+ }
+
+ protected Translator findTranslator(Notification not) {
+ if (not.getFeature() == null)
+ return null;
+ Translator[] maps = getChildTranslators();
+ for (int i = 0; i < maps.length; i++) {
+ if (maps[i].isMapFor(not.getFeature(), not.getOldValue(), not.getNewValue()))
+ return maps[i];
+ }
+ return null;
+ }
+
+ /**
+ * Update all the children of the target MOF object in the relationship described by
+ *
+ * @map.
+ *
+ * @param map
+ * com.ibm.etools.mof2dom.AttributeTranslator Describes the mapping from the MOF
+ * attribute name to the DOM node name
+ */
+ protected void primUpdateDOMMultiFeature(Translator map, Node node, List mofChildren, List domChildren, Notifier owner) {
+
+ //Used for inserting primitives
+ List inorderDOMChildren = null;
+ if (!map.isObjectMap() || map.isManagedByParent()) {
+ inorderDOMChildren = new ArrayList();
+ inorderDOMChildren.addAll(domChildren);
+ }
+ Node parent = findDOMPath(node, map, false);
+
+ // Go though the MOF children checking to see if the corresponding
+ // MOF Adapter children exists. If not, create the adapter.
+ // Also handles reordering children that have moved.
+ int i = 0;
+ for (; i < mofChildren.size(); i++) {
+ Object child = mofChildren.get(i);
+ EObject mofChild = null;
+
+ EMF2DOMAdapter adapter = null;
+
+ // Check to see if the child is a MOF Object.
+ if (!map.isManagedByParent() && child instanceof EObject) {
+ mofChild = (EObject) mofChildren.get(i);
+ adapter = getExistingAdapter(mofChild);
+ }
+
+ if (adapter != null && i < domChildren.size() && domChildren.get(i) == adapter.getNode())
+ continue;
+ if (adapter != null) {
+ if (domChildren.isEmpty())
+ continue;
+ // A node has been reordered in the list
+ Node reorderNode = adapter.getNode();
+ Node insertBeforeNode = reorderNode;
+ if (i < domChildren.size() && domChildren.get(i) != reorderNode) {
+ insertBeforeNode = (Node) domChildren.get(i);
+ }
+ domChildren.remove(reorderNode);
+ domChildren.add(i, reorderNode);
+ if (reorderNode != insertBeforeNode) {
+ reorderDOMChild(parent, reorderNode, insertBeforeNode, map);
+ }
+ } else {
+ // A new node has been added, create it
+ parent = createDOMPath(node, map);
+ if (mofChild != null) {
+ adapter = createAdapter(mofChild, map);
+ Node newNode = adapter.getNode();
+ Node insertBeforeNode = findInsertBeforeNode(parent, map, mofChildren, i, domChildren);
+ DOMUtilities.insertBeforeNodeAndWhitespace(parent, newNode, insertBeforeNode);
+ domChildren.add(i, newNode);
+ boolean notificationFlag = adapter.isNotificationEnabled();
+ adapter.setNotificationEnabled(false);
+ try {
+ indent(newNode, map);
+ } finally {
+ adapter.setNotificationEnabled(notificationFlag);
+ }
+ adapter.updateDOM();
+ } else {
+ // The mof feature is a collection of primitives.
+ // create a new dom node and listen to it.
+ Element newNode = createNewNode(null, map);
+ Node insertBeforeNode = findInsertBeforeNode(parent, map, mofChildren, i, inorderDOMChildren);
+ DOMUtilities.insertBeforeNodeAndWhitespace(parent, newNode, insertBeforeNode);
+ indent(newNode, map);
+ addDOMAdapter(newNode); // Hook up listeners
+ domChildren.add(i, newNode);
+ inorderDOMChildren.add(newNode);
+ Text newText = parent.getOwnerDocument().createTextNode(map.convertValueToString(child, (EObject) owner));
+ DOMUtilities.insertBeforeNode(newNode, newText, null);
+ }
+ }
+ }
+
+ // Remove any remaining adapters.
+ for (; i < domChildren.size(); i++) {
+ removeDOMChild(parent, (Element) domChildren.get(i));
+ }
+
+ // If there are no MOF children, remove any unnecessary DOM node paths
+ if (mofChildren.size() == 0 && map.hasDOMPath()) {
+ if (map.shouldRenderEmptyDOMPath((EObject) owner))
+ createDOMPath(node, map);
+ else
+ removeDOMPath(node, map);
+ }
+
+ }
+
+ /**
+ * Update all the children of the target MOF object in the relationship described by
+ *
+ * @map.
+ *
+ * @param map
+ * com.ibm.etools.mof2dom.AttributeTranslator Describes the mapping from the MOF
+ * attribute name to the DOM node name
+ */
+ protected void primUpdateMOFMultiFeature(Translator map, Node node, List mofChildren, List domChilren) {
+
+ Hashtable nodeToAdapter = new Hashtable();
+
+ for (int i = 0; i < mofChildren.size(); i++) {
+ EMF2DOMAdapter adapter = getExistingAdapter((EObject) mofChildren.get(i));
+ if (adapter != null)
+ nodeToAdapter.put(adapter.getNode(), adapter);
+ }
+
+ // Go though the DOM children checking to see if the corresponding
+ // MOF Adapter children exists. If not, create the adapter.
+ // Also handles reordering children that have moved.
+ int i = 0;
+ int mofIndex = 0;
+ List adaptersToUpdate = new ArrayList();
+ for (; i < domChilren.size(); i++) {
+ Element childNode = (Element) domChilren.get(i);
+ EMF2DOMAdapter adapter = i < mofChildren.size() ? getExistingAdapter((EObject) mofChildren.get(i)) : null;
+ if (adapter != null && !adapter.isMOFProxy() && adapter.getNode() == childNode) {
+ // Because the adapter is processing STRUCTURE_CHANGED from the
+ // DOM, we
+ // must update all the way down the tree since anything under
+ // the notifying
+ // DOM node could have changed.
+ adapter.updateMOF();
+ mofIndex++;
+ continue;
+ }
+
+ adapter = (EMF2DOMAdapter) nodeToAdapter.get(childNode);
+ if (adapter != null) {
+ reorderIfNecessary((EList) mofChildren, adapter.getEObject(), mofIndex);
+ mofIndex++;
+ } else {
+ adapter = createAdapter(childNode, map);
+ if (adapter != null) {
+ try {
+ //We don't want to push anything back to the child dom
+ adapter.setNotificationEnabled(false);
+ map.setMOFValue(getTarget(), adapter.getTarget(), mofIndex);
+ } finally {
+ adapter.setNotificationEnabled(true);
+ }
+
+ adaptersToUpdate.add(adapter);
+ mofIndex++;
+ }
+ }
+ }
+
+ // Remove any remaining adapters.
+ //make a copy so we remove all items - bug 192468
+ Object[] childrenArray = mofChildren.toArray();
+ for (; i < childrenArray.length; i++) {
+ removeMOFValue((EObject) childrenArray[i], map);
+ }
+
+ // The adapters cannot be updated as they created. We must wait until
+ // all of the adapters are created and removed before updating,
+ // otherwise
+ // we can get in a state where there are adapters fighting with
+ // eachother
+ // (one for the old node and one for the new node).
+ for (int j = 0; j < adaptersToUpdate.size(); j++) {
+ ((EMF2DOMAdapter) adaptersToUpdate.get(j)).updateMOF();
+ }
+ }
+
+ /**
+ * Removes a feature's value.
+ *
+ * @param childAdapter
+ * com.ibm.etools.mof2dom.EMF2DOMAdapter The child to remove
+ * @param mofAttributeName
+ * String The name of the mofAttribute to remove the child from.
+ */
+ protected void removeMOFValue(EObject value, Translator translator) {
+
+ if (value == null)
+ return;
+
+ EMF2DOMAdapter adapter = (EMF2DOMAdapter) EcoreUtil.getExistingAdapter(value, EMF2DOMAdapter.ADAPTER_CLASS);
+ if (adapter != null) {
+ // Remove the adapter from BOTH the MOF Object and the DOM Nodes
+ removeAdapters(adapter.getNode());
+ value.eAdapters().remove(adapter);
+ }
+
+ EStructuralFeature feature = translator.getFeature();
+ boolean doUnload = feature == null || (translator.isObjectMap() && ((EReference) feature).isContainment());
+
+ // translator.removeMOFValue() was here originally
+
+ // Unload the objects.
+ if (doUnload)
+ ExtendedEcoreUtil.unload(value);
+
+ // Remove the MOF value
+ translator.removeMOFValue(getTarget(), value);
+ }
+
+ protected void reorderIfNecessary(EList emfChildren, EObject eObj, int emfIndex) {
+ int currIndex = emfChildren.indexOf(eObj);
+ if (currIndex > -1 && currIndex != emfIndex)
+ emfChildren.move(emfIndex, eObj);
+ }
+
+ /**
+ * default is to do nothing; subclasses can override
+ */
+ protected void indent(Node newNode, Translator map) {
+
+ }
+
+ protected Node findInsertBeforeNode(Node parentNode, Translator map, List mofList, int mofInx, List domList) {
+ Node insertBeforeNode = null;
+
+ // If there are no current dom children for this map, find the initial
+ // insert pos.
+ if (domList.size() == 0)
+ return findInitialInsertBeforeNode(parentNode, map);
+
+ // If some dom nodes then find the correct one to insert before.
+ int i = mofInx + 1;
+ while (i < mofList.size() && insertBeforeNode == null) {
+ // Start at the mofInx passed in and look forward for the first
+ // adapted
+ // MOF object. Use that node as the insert before node.
+ Object o = mofList.get(i);
+ if (!map.isObjectMap() || map.isManagedByParent())
+ break;
+ EObject tMOFObject = (EObject) o;
+ EMF2DOMAdapter tAdapter = (EMF2DOMAdapter) EcoreUtil.getExistingAdapter(tMOFObject, EMF2DOMAdapter.ADAPTER_CLASS);
+ if (tAdapter != null) {
+ insertBeforeNode = tAdapter.getNode();
+ }
+ i++;
+ }
+
+ // Handle inserting at the end of the list
+ if (insertBeforeNode == null)
+ insertBeforeNode = DOMUtilities.getNextNodeSibling((Node) domList.get(domList.size() - 1));
+ if (insertBeforeNode == null)
+ insertBeforeNode = ((Node) domList.get(domList.size() - 1)).getNextSibling();
+
+ return insertBeforeNode;
+ }
+
+ protected Node findInitialInsertBeforeNode(Node parentNode, Translator mapNode) {
+ Translator[] maps = getChildTranslators();
+
+ // First, skip past all the maps in the ordered collection
+ // of maps. We want to begin the search with this node.
+ int i = 0;
+ for (; i < maps.length; i++) {
+ if (maps[i] == mapNode)
+ break;
+ }
+
+ // Now search go through each map node until a child node matching
+ // its DOM name is found.
+ Node insertBeforeNode = null;
+ for (int j = i; j < maps.length && insertBeforeNode == null; j++) {
+ NodeList childNodes = parentNode.getChildNodes();
+ Translator nodeToFindMap = maps[j];
+ for (int k = 0; k < childNodes.getLength(); k++) {
+ Node node = childNodes.item(k);
+ if (nodeToFindMap.isMapFor(node.getNodeName())) {
+ insertBeforeNode = node;
+ break;
+ }
+ }
+ }
+ return insertBeforeNode;
+ }
+
+ /*
+ * Traverses the path that <map> specifies. Returns the last node of the path that was able to
+ * be traversed or null if the path could not be traversed. The <addAdapters> boolean is used to
+ * determine if the receiver is added as an adapter to every node found on the path.
+ */
+ protected Node findDOMPath(Node parent, Translator map, boolean addAdapters) {
+
+ String path = map.getDOMPath();
+ Node curNode = parent;
+ Iterator iter = DOMUtilities.createPathIterator(path);
+
+ while (curNode != null && iter.hasNext()) {
+ String nodeName = (String) iter.next();
+ curNode = DOMUtilities.getNodeChild(curNode, nodeName);
+ if (addAdapters && curNode != null) {
+ addDOMAdapter(curNode);
+ }
+ }
+ return curNode;
+ }
+
+ /**
+ * Return the list of DOM node children that currently exist with the specified tagname.
+ */
+ protected List getDOMChildren(Node node, Translator map) {
+ Node parent = findDOMPath(node, map, true);
+ if (parent != null)
+ return DOMUtilities.getNodeChildren(parent, map.getDOMNames());
+ return new ArrayList();
+ }
+
+ protected EMF2DOMAdapter getExistingAdapter(EObject refObject) {
+ EMF2DOMAdapter adapter = (EMF2DOMAdapter) EcoreUtil.getExistingAdapter(refObject, EMF2DOMAdapter.ADAPTER_CLASS);
+ if (adapter != null && adapter.isMOFProxy()) {
+ removeDOMAdapter(adapter.getNode(), adapter);
+ refObject.eAdapters().remove(adapter);
+ adapter = null;
+ }
+ return adapter;
+ }
+
+ protected void primAddDOMAdapter(Node aNode, EMF2DOMAdapter anAdapter) {
+ fRenderer.registerDOMAdapter(aNode, anAdapter);
+ }
+
+ protected EMF2DOMAdapter primGetExistingAdapter(Node aNode) {
+ return fRenderer.getExistingDOMAdapter(aNode);
+ }
+
+ protected void removeDOMAdapter(Node aNode, EMF2DOMAdapter anAdapter) {
+ fRenderer.removeDOMAdapter(aNode, anAdapter);
+ }
+
+ protected void addDOMAdapter(Node childNode) {
+
+ // Only add the adapter if this is an child node that will not be
+ // adapted. For instance a subtree that maps to a MOF attribute
+ // setting.
+ if (childNode.getNodeType() == Node.ELEMENT_NODE) {
+ EMF2DOMAdapter attrAdapter = primGetExistingAdapter(childNode);
+
+ if (attrAdapter == null || attrAdapter.getNode() != getNode()) {
+ // If the node is adapted, but not by this adapter then remove
+ // it. This happens to non-object children when the parent tag
+ // name is changed.
+ removeDOMAdapter(childNode, attrAdapter);
+
+ if (fDebug) {
+ org.eclipse.jem.util.logger.proxy.Logger.getLogger().logError("\tCHILD: Adding DOM adapter: " + this); //$NON-NLS-1$
+ org.eclipse.jem.util.logger.proxy.Logger.getLogger().logError("\t\tto: " + childNode); //$NON-NLS-1$
+ }
+ primAddDOMAdapter(childNode, this);
+ }
+ }
+ }
+
+ /**
+ * Reorder a child before a given node
+ */
+ protected void reorderDOMChild(Node parentNode, Node childNode, Node insertBeforeNode, Translator map) {
+ try {
+ removeDOMChild(parentNode, childNode, false);
+ parentNode.insertBefore(childNode, insertBeforeNode);
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ }
+
+ protected String getNewlineString(Node node) {
+ return DOMUtilities.NEWLINE_STRING;
+ }
+
+ protected String primGetIndentString(Node node) {
+ return DOMUtilities.getIndentString(node);
+ }
+
+ /**
+ * Remove a child node
+ */
+ protected void removeDOMChild(Node parentNode, Node childNode) {
+ removeDOMChild(parentNode, childNode, true);
+ }
+
+ /**
+ * Remove a child node
+ */
+ protected void removeDOMChild(Node parentNode, Node childNode, boolean removeAdapter) {
+ try {
+ if (childNode == null)
+ return;
+ // Look for any whitespace preceeding the node being
+ // removed and remove it as well.
+ Text prevText = DOMUtilities.getPreviousTextSibling(childNode);
+ if (prevText != null && DOMUtilities.isWhitespace(prevText)) {
+ parentNode.removeChild(prevText);
+ }
+ // Remove the node.
+ if (removeAdapter)
+ removeAdapters(childNode);
+ parentNode.removeChild(childNode);
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ }
+
+ /**
+ * Remove the DOM adapters from the node AND all its child nodes, recursively.
+ */
+ public void removeAdapters(Node node) {
+ EMF2DOMAdapter adapter = primGetExistingAdapter(node);
+ if (adapter != null) {
+ // Remove the adapter from both the DOM node and the MOF Object.
+ removeDOMAdapter(node, adapter);
+ if (adapter.getNode() == node) {
+ Notifier localTarget = adapter.getTarget();
+ if (localTarget != null)
+ localTarget.eAdapters().remove(adapter);
+ }
+ }
+ NodeList nl = node.getChildNodes();
+ for (int i = 0; i < nl.getLength(); i++) {
+ Node n = nl.item(i);
+ removeAdapters(n);
+ }
+ }
+
+ /**
+ * Creates the path specified by <map>under <node>. Only the portion of the path that does not
+ * exist (if any) is created
+ *
+ * @param node
+ * org.w3c.dom.Node
+ * @param map
+ * com.ibm.etools.mof2dom.Translator
+ */
+ protected Node createDOMPath(Node node, Translator map) {
+ Iterator i = DOMUtilities.createPathIterator(map.getDOMPath());
+ Node curNode = node;
+ while (i.hasNext()) {
+ String nodeName = (String) i.next();
+ curNode = findOrCreateNode(node, map, nodeName);
+ }
+ return curNode;
+ }
+
+ protected Element findOrCreateNode(Node parent, Translator map, String segment) {
+ Node node = DOMUtilities.getNodeChild(parent, segment);
+ if (node == null) {
+ // The node did not already exist, create it.
+ Document doc = parent.getOwnerDocument();
+ node = doc.createElement(segment);
+ if (map.isEmptyTag())
+ setEmptyTag((Element) node);
+
+ Node insertBeforeNode = findInitialInsertBeforeNode(parent, map);
+ DOMUtilities.insertBeforeNodeAndWhitespace(parent, node, insertBeforeNode);
+ indent(node, map);
+ addDOMAdapter(node); // Hook up listeners
+ }
+ return (Element) node;
+ }
+
+ /**
+ * Remove the node passed in if it has only whitespace nodes as children
+ *
+ * @param node
+ * org.w3c.dom.Node The node to check
+ */
+ protected void removeIfEmpty(Node node) {
+ NodeList nl = node.getChildNodes();
+
+ // Run through all the nodes children. If a non-whitespace node
+ // pis found, bail.
+ for (int i = 0; i < nl.getLength(); i++) {
+ Node childNode = nl.item(i);
+ if (!DOMUtilities.isWhitespace(childNode))
+ return;
+ }
+
+ // We only get here if there are no non-whitespace chars, so
+ // simply remove the node.
+ removeDOMChild(node.getParentNode(), node);
+ }
+
+ /**
+ * Remove the DOM path specified by <map>from <node>
+ */
+ protected void removeDOMPath(Node node, Translator map) {
+ Node childNode = findDOMPath(node, map, false);
+ while (childNode != null && childNode != node) {
+ removeIfEmpty(childNode);
+ childNode = childNode.getParentNode();
+ }
+ }
+
+ /**
+ * Create an adapter for a child DOM node
+ *
+ * @param node
+ * org.w3c.dom.Node The node to create the adapter for.
+ */
+ protected EMF2DOMAdapter createAdapter(EObject mofObject, Translator childMap) {
+ // Assert.isNotNull(childMap.getChildAdapterClass());
+ Assert.isNotNull(mofObject);
+
+ EMF2DOMAdapter adapter = (EMF2DOMAdapter) EcoreUtil.getAdapter(mofObject.eAdapters(), EMF2DOMAdapter.ADAPTER_CLASS);
+
+ if (adapter != null && adapter.isMOFProxy()) {
+ removeAdapters(adapter.getNode());
+ mofObject.eAdapters().remove(adapter);
+ adapter = null;
+ }
+ if (adapter == null)
+ adapter = primCreateAdapter(mofObject, childMap);
+ return adapter;
+ }
+
+ /**
+ * Create an adapter for a child DOM node
+ *
+ * @param node
+ * org.w3c.dom.Node The node to create the adapter for.
+ */
+ protected EMF2DOMAdapter primCreateAdapter(EObject mofObject, Translator childMap) {
+
+ Element newNode = createNewNode(mofObject, childMap);
+ return new EMF2DOMAdapterImpl(mofObject, newNode, fRenderer, childMap);
+ }
+
+ /**
+ * Create an adapter for a child DOM node
+ *
+ * @param node
+ * org.w3c.dom.Node The node to create the adapter for.
+ */
+ protected EMF2DOMAdapter primCreateAdapter(Node node, Translator childMap) {
+ return new EMF2DOMAdapterImpl(node, fRenderer, childMap);
+ }
+
+ /**
+ * Create an adapter for a child DOM node
+ *
+ * @param node
+ * org.w3c.dom.Node The node to create the adapter for.
+ */
+ protected EMF2DOMAdapter createAdapter(Node node, Translator childMap) {
+
+ //Assert.isNotNull(childMap.getChildAdapterClass());
+ Assert.isNotNull(node);
+
+ EMF2DOMAdapter adapter = primGetExistingAdapter(node);
+
+ if (adapter != null) {
+ if (adapter.isMOFProxy() || adapter.getTarget() == null) {
+ removeDOMAdapter(node, adapter);
+ if (adapter.getTarget() != null) {
+ adapter.getTarget().eAdapters().remove(adapter);
+ }
+ adapter = null;
+ }
+ } else {
+ adapter = primCreateAdapter(node, childMap);
+ }
+ return adapter;
+ }
+
+ protected Element createNewNode(EObject mofObject, Translator childMap) {
+ Node node = getNode();
+ Document doc = (node instanceof Document) ? (Document) node : node.getOwnerDocument();
+
+ Element element = doc.createElement(childMap.getDOMName(mofObject));
+ if (childMap.isEmptyTag())
+ setEmptyTag(element);
+
+ return element;
+ }
+
+ protected void setEmptyTag(Element element) {
+ Revisit.toDo();
+ //Need to figure out how to do this with pure DOM apis, if it is
+ // possible
+ }
+
+ /*
+ * Return true if MOF object is a proxy.
+ */
+ public boolean isMOFProxy() {
+ if (isRoot || target == null)
+ return false;
+ return ((InternalEObject) target).eIsProxy();
+ }
+
+ public EObject getEObject() {
+ if (isRoot)
+ return null;
+ return (EObject) target;
+ }
+
+ /**
+ * Return the DOM node that the target of this adapter maps to. If the target MOF object maps to
+ * more than one DOM node, this node is the top-most node.
+ */
+ public Node getNode() {
+ return fNode;
+ }
+
+ public void setNode(Node aNode) {
+ fNode = aNode;
+ }
+
+ public void updateDOM() {
+ if (!isNotificationEnabled())
+ return;
+ primUpdateDOM();
+ }
+
+ public void updateMOF() {
+ if (!isNotificationEnabled())
+ return;
+ primUpdateMOF();
+ }
+
+ protected void primUpdateDOM() {
+ if (isRoot)
+ updateDOMRootFeature();
+ else {
+ Translator[] maps = getChildTranslators();
+ for (int i = 0; i < maps.length; i++) {
+ updateDOMFeature(maps[i], getNode(), getEObject());
+ }
+ }
+ }
+
+ public void primUpdateMOF() {
+ if (isRoot)
+ updateMOFRootFeature();
+ else {
+ Translator[] maps = getChildTranslators();
+ for (int i = 0; i < maps.length; i++) {
+ updateMOFFeature(maps[i], getNode(), getEObject());
+ }
+ }
+ }
+
+ protected void updateDOMRootFeature() {
+ boolean notificationFlag = isNotificationEnabled();
+ try {
+ setNotificationEnabled(false);
+ primUpdateDOMMultiFeature(fTranslator, fNode, getResourceContents(), getDOMChildren(fNode, fTranslator), null);
+ updateDOMDocumentType();
+ } finally {
+ setNotificationEnabled(notificationFlag);
+ }
+ }
+
+ protected void updateMOFRootFeature() {
+ boolean notificationFlag = isNotificationEnabled();
+ try {
+ setNotificationEnabled(false);
+ updateMOFDocumentType();
+ primUpdateMOFMultiFeature(fTranslator, fNode, getResourceContents(), getDOMChildren(fNode, fTranslator));
+ } finally {
+ setNotificationEnabled(notificationFlag);
+ }
+ }
+
+ protected DocumentType getDocumentType() {
+ return ((Document) fNode).getDoctype();
+ }
+
+ protected TranslatorResource getResource() {
+ return (TranslatorResource) getTarget();
+ }
+
+ protected EList getResourceContents() {
+ if (!isRoot)
+ throw new IllegalStateException();
+ return ((Resource) getTarget()).getContents();
+ }
+
+ protected void updateDOMDocumentType() {
+
+ DocumentType docType = getDocumentType();
+ String publicId = null, systemId = null, oldPublicId, oldSystemId;
+ oldPublicId = docType == null ? null : docType.getPublicId();
+ oldSystemId = docType == null ? null : docType.getSystemId();
+ TranslatorResource resource = getResource();
+ if (resource != null) {
+ publicId = resource.getPublicId();
+ systemId = resource.getSystemId();
+ }
+ if (!(StringUtil.stringsEqual(publicId, oldPublicId) && StringUtil.stringsEqual(systemId, oldSystemId)))
+ fRenderer.replaceDocumentType(resource.getDoctype(), publicId, systemId);
+ }
+
+ protected void updateDOMDocumentType(Notification msg) {
+ if (msg.getFeature() == TranslatorResource.DOC_TYPE_FEATURE)
+ updateDOMDocumentType();
+ }
+
+ protected void updateMOFDocumentType() {
+
+ TranslatorResource resource = getResource();
+ if (resource == null)
+ return;
+
+ String publicId = null, systemId = null;
+ DocumentType docType = getDocumentType();
+
+ if (docType != null) {
+ publicId = docType.getPublicId();
+ systemId = docType.getSystemId();
+ }
+ if ((!(StringUtil.stringsEqual(publicId, resource.getPublicId()) && StringUtil.stringsEqual(systemId, resource.getSystemId()))) ||
+ ((resource.getPublicId() == null) || resource.getSystemId() == null))
+ resource.setDoctypeValues(publicId, systemId);
+ }
+
+ public void notifyChanged(Notification msg) {
+
+ if (isRoot) {
+ notifyChangedForRoot(msg);
+ return;
+ }
+ if (isDependencyFeature(msg))
+ handleDependencyFeature(msg);
+
+ if (!isNotificationEnabled())
+ return;
+
+ debugMOFNotify(msg);
+
+ switch (msg.getEventType()) {
+ case Notification.ADD :
+ case Notification.REMOVE :
+ case Notification.ADD_MANY :
+ case Notification.REMOVE_MANY :
+ case Notification.SET :
+ case Notification.UNSET :
+ case Notification.MOVE :
+ Translator translator = findTranslator(msg);
+ if (translator == null)
+ translator = addVariableTranslatorIfNecessary(msg);
+ if (translator != null)
+ updateDOMFeature(translator, getNode(), getEObject());
+ break;
+ }
+ }
+
+ protected void notifyChangedForRoot(Notification msg) {
+ if (!isNotificationEnabled())
+ return;
+
+ debugMOFNotify(msg);
+
+ switch (msg.getEventType()) {
+ case Notification.ADD :
+ case Notification.REMOVE :
+ case Notification.ADD_MANY :
+ case Notification.REMOVE_MANY :
+ primUpdateDOM();
+ break;
+ case Notification.SET :
+ updateDOMDocumentType(msg);
+ break;
+ case EtoolsCopySession.RESOURCE_COPIED :
+ updateDOM();
+ break;
+ }
+ }
+
+ protected void addDependencyAdapter(EObject child) {
+ Adapter existing = EcoreUtil.getExistingAdapter(child, DependencyAdapter.KEY);
+ if (existing != null)
+ return;
+ DependencyAdapter forwarder = new DependencyAdapter();
+ child.eAdapters().add(forwarder);
+ forwarder.setTarget(child);
+ }
+
+ protected void addDOMAdapter() {
+
+ primAddDOMAdapter(fNode, this);
+ if (fDebug) {
+ org.eclipse.jem.util.logger.proxy.Logger.getLogger().logError("Adding DOM adapter: " + this); //$NON-NLS-1$
+ org.eclipse.jem.util.logger.proxy.Logger.getLogger().logError("\tto: " + fNode); //$NON-NLS-1$
+ }
+
+ // Go through the maps. All of the DOM nodes that are not listened
+ // to by another DOM Node adapter, must be listened to by this adapter.
+ NodeList childNodes = fNode.getChildNodes();
+ for (int j = 0; j < childNodes.getLength(); j++) {
+ Node childNode = childNodes.item(j);
+ int nodeType = childNode.getNodeType();
+ if (!DOMUtilities.isTextNode(childNode) && nodeType != Node.COMMENT_NODE) {
+ Translator map = findTranslator(childNode.getNodeName(), false);
+ if (map != null && map.isManagedByParent())
+ addDOMAdapter(childNode);
+ }
+ }
+ }
+
+ protected Translator addVariableTranslatorIfNecessary(Notification msg) {
+ VariableTranslatorFactory fact = fTranslator.getVariableTranslatorFactory();
+ Translator trans = null;
+ if (fact != null && fact.accepts(msg)) {
+ trans = fact.create(msg);
+ if (trans != null)
+ childTranslators = (Translator[]) Translator.concat(childTranslators, trans);
+ }
+ return trans;
+ }
+
+ protected Text createTextNode(Document doc, Translator map, String text) {
+ String nonnulltext = (text != null) ? text : ""; //$NON-NLS-1$
+ return map.isCDATAContent() ? doc.createCDATASection(nonnulltext) : doc.createTextNode(nonnulltext);
+ }
+
+ protected String extractReadAheadName() {
+ if (!fTranslator.hasReadAheadNames())
+ return null;
+ String readAheadName = null;
+
+ ReadAheadHelper helper = fTranslator.getReadAheadHelper(fNode.getNodeName());
+ if (helper == null)
+ return null;
+
+ Node child = null;
+ String[] names = helper.getValues();
+ if (helper.getChildDOMName() == null) {
+ for (int i = 0; i < names.length; i++) {
+ child = DOMUtilities.getNodeChild(fNode, names[i]);
+ if (child != null) {
+ readAheadName = names[i];
+ break;
+ }
+ }
+ } else {
+ child = DOMUtilities.getNodeChild(fNode, helper.getChildDOMName());
+ if (child != null)
+ readAheadName = DOMUtilities.getChildText(child);
+ }
+ if (readAheadName == null)
+ readAheadName = names[0];
+ return readAheadName;
+ }
+
+ /**
+ * Extracts the text from <node>and converts it to an object suitable for setting into <feature>
+ */
+ protected Object extractValue(Node node, Translator map, EObject emfObject) {
+
+ // Extract the value from the text child
+ Node textNode = DOMUtilities.getChildTextNode(node);
+ String trimmedValue = null;
+ if (textNode != null)
+ trimmedValue = textNode.getNodeValue();
+ try {
+ return map.convertStringToValue(trimmedValue, emfObject);
+ } catch (FeatureValueConversionException ex) {
+ handleFeatureValueConversionException(ex);
+ return null;
+ }
+ }
+
+ /**
+ * @param ex
+ */
+ protected void handleFeatureValueConversionException(FeatureValueConversionException ex) {
+ throw ex;
+
+ }
+
+ /*
+ * Finds the child node that <map> specifies. If there is more than one child that satisfies
+ * <map> then the first one is returned.
+ *
+ * This method traverses past the domPath if one is specified in the <map>.
+ */
+ protected Node findDOMNode(Node parent, Translator map) {
+ return findDOMNode(parent, map, false);
+ }
+
+ /*
+ * Finds the child node that <map> specifies. If there is more than one child that satisfies
+ * <map> then the first one is returned. The <addAdapters> boolean is used to determine if the
+ * receiver is added as an adapter to every node found on the path.
+ *
+ * This method traverses past the domPath if one is specified in the <map>.
+ */
+ protected Node findDOMNode(Node parent, Translator map, boolean addAdapters) {
+
+ // First, trace down the path
+ Node curNode = findDOMPath(parent, map, addAdapters);
+ if (map.isDOMTextValue() || map.isDOMAttribute() || curNode == null)
+ return curNode;
+
+ // Now look for the first DOM name we can find
+ String[] domNames = map.getDOMNames();
+ Node node = null;
+ for (int i = 0; i < domNames.length; i++) {
+ String nodeName = domNames[i];
+ List nodes = DOMUtilities.getNodeChildren(curNode, nodeName);
+ if (nodes != null && !nodes.isEmpty()) {
+ if (nodes.size() > 1)
+ handleInvalidMultiNodes(nodeName);
+ node = (Node) nodes.get(0);
+ if (node != null) {
+ if (addAdapters && (map != null || map.isManagedByParent()))
+ addDOMAdapter(curNode);
+ break;
+ }
+ }
+ }
+ return node;
+ }
+
+ protected void handleInvalidMultiNodes(String nodeName) {
+ throw new IllegalStateException(WFTUtilsResourceHandler.getString(WFTUtilsResourceHandler.EMF2DOMAdapterImpl_ERROR_0, new Object[]{nodeName}));
+ }
+
+ /**
+ * Creates the path specified by <map>under <node>. Only the portion of the path that does not
+ * exist (if any) is created
+ *
+ * @param node
+ * org.w3c.dom.Node
+ * @param map
+ * com.ibm.etools.mof2dom.Translator
+ */
+ protected Text findOrCreateTextNode(Node parent, Translator map, String text) {
+ Text textNode = DOMUtilities.getChildTextNode(parent);
+ if (textNode != null) {
+ textNode.setData(text);
+ } else {
+ if (!isEmptyTag((Element) parent)) {
+ Text newNode = createTextNode(parent.getOwnerDocument(), map, text);
+ DOMUtilities.insertBeforeNode(parent, newNode, null);
+ return newNode;
+ }
+ }
+ return textNode;
+ }
+
+ protected Translator findTranslator(String tagName, boolean attributeMap) {
+ Translator[] maps = getChildTranslators();
+ for (int i = 0; i < maps.length; i++) {
+ Translator map = maps[i];
+ if (map.isMapFor(tagName) && attributeMap == map.isDOMAttribute())
+ return maps[i];
+ }
+
+ return null;
+ }
+
+ protected EMF2DOMAdapter getExistingAdapter(Node aNode) {
+ EMF2DOMAdapter adapter = primGetExistingAdapter(aNode);
+ if (adapter != null && adapter.isMOFProxy()) {
+ removeDOMAdapter(aNode, adapter);
+ adapter.getTarget().eAdapters().remove(adapter);
+ adapter = null;
+ }
+ return adapter;
+ }
+
+ protected void handleDependencyFeature(Notification msg) {
+ if (msg.getOldValue() != null)
+ removeDependencyAdapter((EObject) msg.getOldValue());
+ if (msg.getNewValue() != null)
+ addDependencyAdapter((EObject) msg.getNewValue());
+ }
+
+ protected boolean isDependencyFeature(Notification msg) {
+ switch (msg.getEventType()) {
+ case Notification.SET :
+ return fTranslator.isDependencyParent() && fTranslator.getDependencyFeature() == msg.getFeature();
+ default :
+ return false;
+ }
+ }
+
+ protected boolean isEmptyTag(Element parent) {
+ Revisit.toDo();
+ //Determine how to implement this with pure DOM apis, if possible.
+ return false;
+ }
+
+ protected void postUpdateDOMFeature(Translator map, Node node, EObject mofObject) {
+ }
+
+ protected void preUpdateDOMFeature(Translator map, Node node, EObject mofObject) {
+ }
+
+ /**
+ * Update an attribute of the target DOM object from with the values currently stored in the MOF
+ * object. The
+ *
+ * @map specifies the name of the MOF attribute to update and the name of the DOM node.
+ *
+ * @param map
+ * com.ibm.etools.mof2dom.AttributeTranslator
+ */
+ protected void primUpdateDOMFeature(Translator map, Node node, EObject mofObject) {
+ Object attrValue = null;
+ boolean isSet = false;
+ if (map.isIDMap()) {
+ try {
+ attrValue = map.getMOFValue(mofObject);
+ } catch (IDTranslator.NoResourceException ex) {
+ //If the object has been removed from the resource,
+ //No need to update
+ return;
+ }
+ isSet = attrValue != null;
+ } else {
+ attrValue = map.getMOFValue(mofObject);
+ isSet = map.isSetMOFValue(mofObject);
+ }
+
+ if (map.isDOMAttribute()) {
+ // An attribute of the MOF object maps to an attribute of the
+ // DOM node. Get the value of the MOF attribute and set it
+ // into DOM node.
+ Element e = (Element) createDOMPath(node, map);
+ if (attrValue != null && isSet)
+ e.setAttribute(map.getDOMName(mofObject), map.convertValueToString(attrValue, mofObject));
+ else
+ e.removeAttribute(map.getDOMName(mofObject));
+ } else {
+ updateDOMSubtree(map, node, mofObject, attrValue);
+ }
+ }
+
+ /**
+ * Update an attribute of the target DOM object from with the values currently stored in the MOF
+ * object. The
+ *
+ * @map specifies the name of the MOF attribute to update and the name of the DOM node.
+ */
+ protected void primUpdateDOMLinkFeature(Translator map, Node node, EObject mofObject) {
+ LinkUpdaterTarget.INSTANCE.updateDOM(map, node, mofObject);
+
+ }
+
+ /**
+ * Update all the children of the target MOF object in the relationship described by
+ *
+ * @map.
+ */
+ protected void primUpdateDOMMultiFeature(Translator map, Node node, EObject mofObject) {
+
+ List mofChildren = map.getMOFChildren(mofObject);
+ List domChildren = getDOMChildren(node, map);
+
+ primUpdateDOMMultiFeature(map, node, mofChildren, domChildren, mofObject);
+ }
+
+ /**
+ * Update an attribute of the target MOF object from the DOM node subtree. The
+ *
+ * @map specifies the name of the MOF attribute to update and the name of the DOM node.
+ */
+ protected boolean primUpdateMOFFeature(Translator map, Node node, EObject mofObject) {
+ if (!map.featureExists(mofObject))
+ return false;
+ Object domValue = null;
+ boolean updateMOFAttAdapter = false;
+ boolean isUnset = false;
+ EMF2DOMAdapter attrAdapter = null;
+
+ Node child = findDOMNode(node, map, true);
+
+ if (map.isDOMAttribute() && child != null) {
+ // An attribute of the MOF object maps to an attribute of the
+ // DOM node. Get the value of the DOM attribute and set it
+ // into the MOF object.
+
+ Attr domAttr = (Attr) child.getAttributes().getNamedItem(map.getDOMName(mofObject));
+ if (domAttr != null) {
+ domValue = domAttr.getValue();
+ domValue = map.convertStringToValue((String) domValue, mofObject);
+ } else
+ isUnset = true;
+ } else {
+ // An attribute of the MOF object is actually a sub-element
+ // of the DOM node. Search for the first sub-element with
+ // the correct name to use as an attribute.
+ if (child != null) {
+ // Check to see if this is a single valued attribute that has
+ // a MOF object as its value
+ if (!map.isManagedByParent()) {
+ attrAdapter = createAdapter(child, map);
+ updateMOFAttAdapter = true;
+ domValue = attrAdapter.getTarget();
+ } else {
+ // Check to make sure the child is adapted. If not, adapt
+ // it.
+ addDOMAdapter(child);
+
+ // Extract the value from the text child
+ domValue = extractValue(child, map, mofObject);
+ }
+ } else
+ isUnset = true;
+ }
+
+ // Set the attribute extracted from the DOM to the MOF object.
+ boolean hasChanged = true;
+ try {
+ if (map.isIDMap())
+ map.setMOFValue(mofObject, domValue);
+ else {
+ Object oldValue = null;
+ oldValue = map.getMOFValue(mofObject);
+ boolean isSet = map.isSetMOFValue(mofObject);
+ //In the case of enums with default values, we need to trip
+ // the attribute from
+ //default to a set value
+ if (oldValue == domValue) {
+ if (oldValue == null || isSet)
+ hasChanged = false;
+ } else if (domValue == null && !isSet)
+ //If the domValue is null and the feature is not set, then
+ // we don't need
+ //to do anything
+ hasChanged = false;
+ else if (oldValue != null && oldValue.equals(domValue) && isSet)
+ hasChanged = false;
+ if (oldValue == null && domValue == null && map.isSetMOFValue(mofObject) == isUnset)
+ hasChanged = true;
+ if (hasChanged) {
+ if (!(map.isDataType()) && !map.isShared())
+ removeMOFValue((EObject) oldValue, map);
+ if (domValue == null)
+ map.unSetMOFValue(mofObject);
+ else
+ map.setMOFValue(mofObject, domValue);
+
+ if ((domValue == null && !(map.isEnumFeature())) || isUnset)
+ map.unSetMOFValue(mofObject); //unset
+ // null
+ // for
+ // non
+ // enum
+ // features
+
+ if (updateMOFAttAdapter)
+ attrAdapter.updateMOF();
+ }
+ }
+ } catch (FeatureValueConversionException ex) {
+ handleFeatureValueConversionException(ex);
+ map.unSetMOFValue(mofObject);
+ }
+ return hasChanged;
+ }
+
+ /**
+ * Update an attribute of the target MOF object from the DOM node subtree. This method is only
+ * called if the DOM node changes and the map is an object link map. The
+ *
+ * @map specifies the name of the MOF attribute to update and the name of the DOM node.
+ *
+ * @param map
+ * com.ibm.etools.mof2dom.AttributeTranslator
+ * @return Return true if the MOF feature was updated, false if no update was done.
+ */
+ protected void primUpdateMOFLinkFeature(Translator map, Node node, EObject mofObject) {
+ LinkUpdaterTarget.INSTANCE.updateMOF(map, node, mofObject);
+ }
+
+ /**
+ * Update all the children of the target MOF object in the relationship described by
+ *
+ * @map.
+ *
+ * @param map
+ * com.ibm.etools.mof2dom.AttributeTranslator Describes the mapping from the MOF
+ * attribute name to the DOM node name
+ */
+ protected void primUpdateMOFMultiFeature(Translator map, Node node, EObject mofObject) {
+ // If the feature is a collection of strings or ints, call a special
+ // method
+ // that handles this.
+ if (map.isManagedByParent()) {
+ updateMOFMultiPrimitiveFeature(map, node, mofObject);
+ return;
+ }
+
+ List nodeChildren = getDOMChildren(node, map);
+ List mofChildren = map.getMOFChildren(mofObject);
+
+ primUpdateMOFMultiFeature(map, node, mofChildren, nodeChildren);
+ }
+
+ protected void removeDependencyAdapter(EObject obj) {
+ Adapter existing = EcoreUtil.getExistingAdapter(obj, DependencyAdapter.KEY);
+ if (existing != null)
+ obj.eAdapters().remove(existing);
+ }
+
+ /**
+ * Removes all the DOM children from <parent>that are represented by <map>.
+ */
+ protected void removeDOMChildren(Node parent, Translator map) {
+ String[] domNames = map.getDOMNames();
+ HashSet domNamesSet = new HashSet(domNames.length);
+ for (int i = 0; i < domNames.length; i++)
+ domNamesSet.add(domNames[i]);
+
+ // Walk through all the children and find any that match the map.
+ NodeList nl = parent.getChildNodes();
+ List toRemove = new ArrayList();
+ for (int i = 0; i < nl.getLength(); i++) {
+ Node childNode = nl.item(i);
+ if (domNamesSet.contains(childNode.getNodeName()))
+ toRemove.add(childNode);
+ }
+
+ // Remove any children that were found.
+ for (int i = 0; i < toRemove.size(); i++) {
+ Node childNode = (Node) toRemove.get(i);
+ removeDOMChild(parent, childNode, true);
+ }
+ }
+
+ protected void setTargetFromNode() {
+ setTarget(fTranslator.createEMFObject(fNode.getNodeName(), extractReadAheadName()));
+ }
+
+ /**
+ * Update an attribute of the target DOM object from with the values currently stored in the MOF
+ * object. The
+ *
+ * @map specifies the name of the MOF attribute to update and the name of the DOM node.
+ *
+ * @param map
+ * com.ibm.etools.mof2dom.AttributeTranslator
+ */
+ final public void updateDOMFeature(Translator map, Node node, EObject mofObject) {
+ if (!isNotificationEnabled())
+ return;
+ try {
+ preUpdateDOMFeature(map, node, mofObject);
+ if (map.isMultiValued()) {
+ updateDOMMultiFeature(map, node, mofObject);
+ return;
+ }
+
+ if (fDebug) {
+ org.eclipse.jem.util.logger.proxy.Logger.getLogger().logError("Updating DOM Node: " + node); //$NON-NLS-1$
+ org.eclipse.jem.util.logger.proxy.Logger.getLogger().logError("\tfrom: " + mofObject); //$NON-NLS-1$
+ org.eclipse.jem.util.logger.proxy.Logger.getLogger().logError("\tmap : " + map); //$NON-NLS-1$
+ }
+ boolean notificationFlag = isNotificationEnabled();
+ try {
+ setNotificationEnabled(false);
+ primUpdateDOMFeature(map, node, mofObject);
+ } finally {
+ setNotificationEnabled(notificationFlag);
+ }
+
+ if (map.isTargetLinkMap()) {
+ updateDOMLinkFeature(map, node, mofObject);
+ }
+ } finally {
+ postUpdateDOMFeature(map, node, mofObject);
+ }
+ }
+
+ /**
+ * Update an attribute of the target DOM object from the values currently stored in the MOF
+ * object. The
+ *
+ * @map specifies the name of the MOF attribute to update and the name of the DOM node.
+ *
+ * @param map
+ * com.ibm.etools.mof2dom.AttributeTranslator
+ */
+ final protected void updateDOMLinkFeature(Translator map, Node node, EObject mofObject) {
+ if (fDebug) {
+ org.eclipse.jem.util.logger.proxy.Logger.getLogger().logError("Updating DOM Node (link): " + node); //$NON-NLS-1$
+ org.eclipse.jem.util.logger.proxy.Logger.getLogger().logError("\tfrom: " + mofObject); //$NON-NLS-1$
+ org.eclipse.jem.util.logger.proxy.Logger.getLogger().logError("\tmap : " + map); //$NON-NLS-1$
+ }
+ primUpdateDOMLinkFeature(map, node, mofObject);
+ }
+
+ /**
+ * Update all the children of the target MOF object in the relationship described by
+ *
+ * @map.
+ *
+ * @param map
+ * com.ibm.etools.mof2dom.AttributeTranslator Describes the mapping from the MOF
+ * attribute name to the DOM node name
+ */
+ final protected void updateDOMMultiFeature(Translator map, Node node, EObject mofObject) {
+ if (fDebug) {
+ org.eclipse.jem.util.logger.proxy.Logger.getLogger().logError("Updating DOM Node (multi): " + node); //$NON-NLS-1$
+ org.eclipse.jem.util.logger.proxy.Logger.getLogger().logError("\tfrom: " + mofObject); //$NON-NLS-1$
+ org.eclipse.jem.util.logger.proxy.Logger.getLogger().logError("\tmap : " + map); //$NON-NLS-1$
+ }
+ boolean notificationFlag = isNotificationEnabled();
+ try {
+ setNotificationEnabled(false);
+ primUpdateDOMMultiFeature(map, node, mofObject);
+ } finally {
+ setNotificationEnabled(notificationFlag);
+ }
+ }
+
+ /**
+ * Update a DOM subtree to reflect the mofObject and map passed in. The subtree is of <node>is
+ * updated.
+ */
+ protected void updateDOMSubtree(Translator map, Node node, EObject mofObject, Object attrValue) {
+
+ if (map.featureExists(mofObject)) {
+ if ((map.isEnumFeature() || map.isBooleanFeature()) && (map.isUnsettable() && !map.isSetMOFValue(mofObject)))
+ attrValue = null;
+ } else
+ attrValue = map.extractStringValue(mofObject);
+
+ // Create and/or update the DOM subtree
+ if (attrValue != null) {
+ Node parent = createDOMPath(node, map);
+ if (map.isManagedByParent()) {
+ // Handle the case where the mof value is not another
+ // mof object (primitive)
+ if (map.getDOMName(mofObject) != null && map.getDOMName(mofObject).startsWith("#")) //$NON-NLS-1$
+ return;
+
+ Element child = map.isDOMTextValue() ? (Element) parent : findOrCreateNode(parent, map, map.getDOMName(mofObject));
+
+ findOrCreateTextNode(child, map, map.convertValueToString(attrValue, mofObject));
+ } else {
+ // Handle the case were the mof value is a mof object.
+ EObject mofValue = (EObject) attrValue;
+ EMF2DOMAdapter valueAdapter = (EMF2DOMAdapter) EcoreUtil.getExistingAdapter(mofValue, EMF2DOMAdapter.ADAPTER_CLASS);
+ if (valueAdapter != null)
+ valueAdapter.updateDOM();
+ else {
+ removeDOMChildren(parent, map);
+ EMF2DOMAdapter adapter = createAdapter(mofValue, map);
+ List mofChildren = map.getMOFChildren(mofObject);
+ List domChildren = getDOMChildren(parent, map);
+
+ Node insertBeforeNode = findInsertBeforeNode(parent, map, mofChildren, 0, domChildren);
+ DOMUtilities.insertBeforeNodeAndWhitespace(parent, adapter.getNode(), insertBeforeNode);
+ boolean notificationFlag = adapter.isNotificationEnabled();
+ adapter.setNotificationEnabled(false);
+ try {
+ indent(adapter.getNode(), map);
+ } finally {
+ adapter.setNotificationEnabled(notificationFlag);
+ }
+ adapter.updateDOM();
+ }
+ }
+ } else {
+ // The attribute value was set to null or unset. Remove any
+ // existing DOM nodes.
+ Node child = findDOMNode(node, map);
+ if (child != null)
+ removeDOMChild(child.getParentNode(), child);
+ }
+ }
+
+ /**
+ * Update a feature that is set by linking to another existing object. This method is called
+ * when the MOF object is updated in order to update DOM nodes.
+ */
+ final protected void updateMOFLinkFeature(Translator map, Node node, EObject mofObject) {
+ if (fDebug) {
+ org.eclipse.jem.util.logger.proxy.Logger.getLogger().logError("Updating MOFObject (link): " + mofObject); //$NON-NLS-1$
+ org.eclipse.jem.util.logger.proxy.Logger.getLogger().logError("\tfrom: " + node); //$NON-NLS-1$
+ org.eclipse.jem.util.logger.proxy.Logger.getLogger().logError("\tmap : " + map); //$NON-NLS-1$
+ }
+ boolean notificationFlag = isNotificationEnabled();
+ try {
+ setNotificationEnabled(false);
+ primUpdateMOFLinkFeature(map, node, mofObject);
+ } finally {
+ setNotificationEnabled(notificationFlag);
+ }
+ }
+
+ /**
+ * Update all the children of the target MOF object in the relationship described by
+ *
+ * @map.
+ *
+ * @param map
+ * com.ibm.etools.mof2dom.AttributeTranslator Describes the mapping from the MOF
+ * attribute name to the DOM node name
+ */
+ final protected void updateMOFMultiFeature(Translator map, Node node, EObject mofObject) {
+ if (fDebug) {
+ org.eclipse.jem.util.logger.proxy.Logger.getLogger().logError("Updating MOFObject (multi): " + mofObject); //$NON-NLS-1$
+ org.eclipse.jem.util.logger.proxy.Logger.getLogger().logError("\tfrom: " + node); //$NON-NLS-1$
+ org.eclipse.jem.util.logger.proxy.Logger.getLogger().logError("\tmap : " + map); //$NON-NLS-1$
+ }
+ boolean notificationFlag = isNotificationEnabled();
+ try {
+ setNotificationEnabled(false);
+ primUpdateMOFMultiFeature(map, node, mofObject);
+ } finally {
+ setNotificationEnabled(notificationFlag);
+ }
+ }
+
+ /**
+ * Update all the children of the target MOF object in the relationship described by
+ *
+ * @map. The relationship MUST BE a collection of string for this method to work.
+ */
+ protected void updateMOFMultiPrimitiveFeature(Translator map, Node node, EObject mofObject) {
+ List nodeChildren = getDOMChildren(node, map);
+
+ map.clearList(mofObject);
+
+ // Go through the list of nodes and update the MOF collection
+ int addIndex = 0;
+ for (int i = 0; i < nodeChildren.size(); i++) {
+ Node child = (Node) nodeChildren.get(i);
+ Object attributeValue = extractValue(child, map, mofObject);
+ boolean advanceAddIndex = true;
+ if (attributeValue != null){
+ if(map.getFeature() != null && map.getFeature().isUnique() && mofObject.eGet(map.getFeature()) != null && mofObject.eGet(map.getFeature()) instanceof List && ((List) mofObject.eGet(map.getFeature())).contains(attributeValue)){
+ advanceAddIndex = false;
+ String domName = map.domNameAndPath != null ? map.domNameAndPath : "attribute"; //$NON-NLS-1$
+ org.eclipse.jem.util.logger.proxy.Logger.getLogger().logError(new IllegalArgumentException("The 'no duplicates' constraint is violated by "+domName+" = "+attributeValue));
+ handleInvalidMultiNodes(child.getNodeName());
+ } else {
+ map.setMOFValue(mofObject, attributeValue, addIndex);
+ }
+ if(advanceAddIndex){
+ addIndex ++;
+ }
+ }
+
+ // Adapt the node so update will occur.
+ addDOMAdapter(child);
+ }
+ if (map.hasDOMPath() && nodeChildren.isEmpty() && findDOMPath(node, map, false) != null)
+ map.setMOFValueFromEmptyDOMPath(mofObject);
+ }
+
+ /**
+ * Update an attribute of the target MOF object from the DOM node subtree. The
+ *
+ * @map specifies the name of the MOF attribute to update and the name of the DOM node.
+ *
+ * @param map
+ * com.ibm.etools.mof2dom.AttributeTranslator
+ */
+ public void updateMOFFeature(Translator map, Node node, EObject mofObject) {
+ if (!isNotificationEnabled())
+ return;
+ if (map.isMultiValued()) {
+ updateMOFMultiFeature(map, node, mofObject);
+ return;
+ } else if (map.isComment()) {
+ updateMOFCommentFeature(map, node, mofObject);
+ return;
+ }
+
+ // TODO MDE Add a map.isComment() and updateMOFCommentFeature(map, node, mofObject);
+
+ if (fDebug) {
+ org.eclipse.jem.util.logger.proxy.Logger.getLogger().logError("Updating MOFObject: " + mofObject); //$NON-NLS-1$
+ org.eclipse.jem.util.logger.proxy.Logger.getLogger().logError("\tfrom: " + node); //$NON-NLS-1$
+ org.eclipse.jem.util.logger.proxy.Logger.getLogger().logError("\tmap : " + map); //$NON-NLS-1$
+ }
+ boolean notificationFlag = isNotificationEnabled();
+ boolean hasChanged = false;
+ try {
+ setNotificationEnabled(false);
+ hasChanged = primUpdateMOFFeature(map, node, mofObject);
+ } finally {
+ setNotificationEnabled(notificationFlag);
+ }
+
+ if (map.isTargetLinkMap() && hasChanged)
+ updateMOFLinkFeature(map, node, mofObject);
+ }
+
+ /**
+ * @param map
+ * @param node
+ * @param mofObject
+ */
+ public void updateMOFCommentFeature(Translator map, Node node, EObject mofObject) {
+ Node commentNode = node;
+ /* scan up the dom to find the first comment node before this node */
+ while ((commentNode = commentNode.getPreviousSibling()) != null && commentNode.getNodeType() != Node.COMMENT_NODE) {
+ /* no comment available */
+ if (commentNode.getNodeType() == Node.ELEMENT_NODE)
+ return;
+ }
+ if (commentNode != null)
+ map.setMOFValue(mofObject, commentNode.getNodeValue());
+
+ }
+
+}
diff --git a/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/resource/EMF2DOMRenderer.java b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/resource/EMF2DOMRenderer.java
new file mode 100644
index 0000000..53fbdc7
--- /dev/null
+++ b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/resource/EMF2DOMRenderer.java
@@ -0,0 +1,266 @@
+/*******************************************************************************
+ * Copyright (c) 2003, 2005 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.wst.common.internal.emf.resource;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.util.HashMap;
+import java.util.Map;
+
+import javax.xml.parsers.ParserConfigurationException;
+import javax.xml.transform.OutputKeys;
+import javax.xml.transform.Transformer;
+import javax.xml.transform.TransformerConfigurationException;
+import javax.xml.transform.TransformerException;
+import javax.xml.transform.TransformerFactory;
+import javax.xml.transform.TransformerFactoryConfigurationError;
+import javax.xml.transform.dom.DOMSource;
+import javax.xml.transform.stream.StreamResult;
+
+import org.eclipse.emf.common.util.WrappedException;
+import org.eclipse.emf.ecore.util.EcoreUtil;
+import org.eclipse.jem.util.logger.proxy.Logger;
+import org.eclipse.wst.common.internal.emf.utilities.DOMLoadOptions;
+import org.eclipse.wst.common.internal.emf.utilities.DOMUtilities;
+import org.eclipse.wst.common.internal.emf.utilities.Revisit;
+import org.w3c.dom.Document;
+import org.w3c.dom.Node;
+import org.w3c.dom.NodeList;
+import org.xml.sax.SAXException;
+
+
+
+public class EMF2DOMRenderer extends AbstractRendererImpl implements Renderer {
+
+ protected Map domAdapterRegistry;
+ protected boolean needsToCreateDOM = true;
+ protected Document document;
+
+ /**
+ * Constructor for DOMRendererImpl.
+ */
+ public EMF2DOMRenderer() {
+ super();
+ if (managesDOMAdapters())
+ initDOMAdapterRegistry();
+ }
+
+ /**
+ * @see com.ibm.etools.emf2xml.Renderer#doLoad(InputStream, Map)
+ */
+ public void doLoad(InputStream in, Map options) throws IOException {
+ if ((in != null) || !useStreamsForIO()) {
+ loadDocument(in, options);
+ EMF2DOMAdapter adapter = createRootDOMAdapter();
+ adapter.updateMOF();
+ }
+ }
+
+ protected void loadDocument(InputStream in, Map options) throws IOException {
+ try {
+ DOMLoadOptions domOpts = new DOMLoadOptions();
+ domOpts.setAllowJavaEncodings(true);
+ domOpts.setExpandEntityRefererences(true);
+ domOpts.setValidate(isValidating());
+ document = DOMUtilities.loadDocument(in, domOpts, getResource().getEntityResolver());
+ needsToCreateDOM = false;
+ } catch (RuntimeException t_rex) {
+ throw t_rex;
+ } catch (IOException iox) {
+ throw iox;
+ } catch (Exception ex) {
+ throw new WrappedException(ex);
+ }
+ }
+
+
+ /**
+ * @see com.ibm.etools.emf2xml.Renderer#doSave(OutputStream, Map)
+ */
+ public void doSave(OutputStream outputStream, Map options) throws IOException {
+ createDOMTreeIfNecessary();
+ serializeDocument(outputStream);
+ }
+
+ /**
+ * Subclasses should override if adapters are not cached within this renderer, e.g., they are
+ * stored in notifying Nodes
+ */
+ protected boolean managesDOMAdapters() {
+ return true;
+ }
+
+ protected void initDOMAdapterRegistry() {
+ if (domAdapterRegistry == null)
+ domAdapterRegistry = new HashMap();
+ }
+
+ public void registerDOMAdapter(Node node, EMF2DOMAdapter adapter) {
+ domAdapterRegistry.put(node, adapter);
+ }
+
+ public EMF2DOMAdapter getExistingDOMAdapter(Node node) {
+ return (EMF2DOMAdapter) domAdapterRegistry.get(node);
+ }
+
+ public void removeDOMAdapter(Node aNode, EMF2DOMAdapter anAdapter) {
+ domAdapterRegistry.remove(aNode);
+ }
+
+ /**
+ * @see com.ibm.etools.emf2xml.Renderer#prepareToAddContents()
+ */
+ public void prepareToAddContents() {
+ // createDOMTreeIfNecessary();
+ }
+
+ protected Node createDOMTree() {
+ createDocument();
+ EMF2DOMAdapter adapter = createRootDOMAdapter();
+ adapter.updateDOM();
+ needsToCreateDOM = false;
+ return document;
+ }
+
+
+ protected EMF2DOMAdapter createRootDOMAdapter() {
+ EMF2DOMAdapter root = new EMF2DOMAdapterImpl(getResource(), document, this, getResource().getRootTranslator());
+ registerDOMAdapter(document, root);
+ return root;
+ }
+
+
+ protected void createDOMTreeIfNecessary() {
+ if (needsToCreateDOM)
+ createDOMTree();
+ }
+
+ /**
+ * Create a new Document given
+ *
+ * @aResource.
+ */
+ protected void createDocument() {
+ TranslatorResource res = getResource();
+ res.setDefaults();
+ try {
+ document = DOMUtilities.createNewDocument(res.getDoctype(), res.getPublicId(), res.getSystemId());
+ } catch (ParserConfigurationException e) {
+ throw new WrappedException(e);
+ } catch (SAXException e) {
+ throw new WrappedException(e);
+ } catch (IOException e) {
+ throw new WrappedException(e);
+ }
+ }
+
+ public void serializeDocument(OutputStream out) throws IOException {
+ /*
+ * OutputFormat format = createOutputFormat(); Serializer serializer =
+ * SerializerFactory.getSerializerFactory(Method.XML).makeSerializer(out, format);
+ * serializer.asDOMSerializer().serialize(document);
+ */
+ try {
+ TransformerFactory factory = TransformerFactory.newInstance();
+ /*
+ * try { factory.setAttribute(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA); } catch
+ * (IllegalArgumentException x) { }
+ */
+ Transformer transformer = factory.newTransformer();
+
+ transformer.setOutputProperty(OutputKeys.ENCODING, getResource().getEncoding());
+ transformer.setOutputProperty(OutputKeys.VERSION, getResource().getXMLVersion());
+ transformer.setOutputProperty(OutputKeys.METHOD, "xml"); //$NON-NLS-1$
+ transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no"); //$NON-NLS-1$
+ if (getResource().getPublicId() != null)
+ transformer.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, getResource().getPublicId());
+ if (getResource().getSystemId() != null)
+ transformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, getResource().getSystemId());
+ transformer.setOutputProperty(OutputKeys.INDENT, "yes"); //$NON-NLS-1$
+ transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4"); //$NON-NLS-1$ //$NON-NLS-2$
+ DOMSource source = new DOMSource(document.getDocumentElement());
+ /* source.setSystemId(getResource().getSystemId()); */
+ transformer.transform(source, new StreamResult(out));
+ } catch (TransformerConfigurationException e) {
+ Logger.getLogger().logError(e);
+ } catch (TransformerFactoryConfigurationError e) {
+ Logger.getLogger().logError(e);
+ } catch (TransformerException e) {
+ Logger.getLogger().logError(e);
+ } finally {
+ }
+ }
+
+ /*
+ * protected OutputFormat createOutputFormat() { OutputFormat format = new OutputFormat();
+ * format.setIndenting(true); format.setLineSeparator(DOMUtilities.NEWLINE_STRING);
+ * //$NON-NLS-1$ format.setEncoding(getResource().getEncoding());
+ * format.setVersion(getResource().getXMLVersion()); return format; }
+ */
+
+ public void replaceDocumentType(String docTypeName, String publicId, String systemId) {
+ Revisit.revisit();
+ Document newDoc = null;
+ // Need be able to update the doctype directly on the existing document; right now can't
+ // because
+ // of limitations on parser neutral apis
+
+ try {
+ newDoc = DOMUtilities.createNewDocument(docTypeName, publicId, systemId);
+ } catch (ParserConfigurationException e) {
+ throw new WrappedException(e);
+ } catch (SAXException e) {
+ throw new WrappedException(e);
+ } catch (IOException e) {
+ throw new WrappedException(e);
+ }
+
+
+ replaceNode(document.getDocumentElement(), newDoc, newDoc);
+ readapt(document, newDoc);
+ document = newDoc;
+ }
+
+ protected void replaceNode(Node oldChild, Node newParent, Document newDoc) {
+ Node newChild = newDoc.importNode(oldChild, false);
+ newParent.appendChild(newChild);
+ readapt(oldChild, newChild);
+ NodeList children = oldChild.getChildNodes();
+ int length = children.getLength();
+ for (int i = 0; i < length; i++) {
+ replaceNode(children.item(i), newChild, newDoc);
+ }
+ }
+
+ public void preUnload() {
+ EMF2DOMAdapter adapter = (EMF2DOMAdapter) EcoreUtil.getAdapter(resource.eAdapters(), EMF2DOMAdapter.ADAPTER_CLASS);
+ if (adapter != null) {
+ adapter.removeAdapters(adapter.getNode());
+ }
+ }
+
+ protected void readapt(Node oldChild, Node newChild) {
+ EMF2DOMAdapter adapter = getExistingDOMAdapter(oldChild);
+ if (adapter != null) {
+ registerDOMAdapter(newChild, adapter);
+ // Some nodes are managed by the parent and thus the
+ // node should not be set on the parent adapter
+ if (adapter.getNode() == oldChild)
+ adapter.setNode(newChild);
+ }
+ }
+
+ public int getVersionID() {
+ return getResource().getVersionID();
+ }
+
+}
diff --git a/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/resource/EMF2DOMRendererFactory.java b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/resource/EMF2DOMRendererFactory.java
new file mode 100644
index 0000000..fce5603
--- /dev/null
+++ b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/resource/EMF2DOMRendererFactory.java
@@ -0,0 +1,29 @@
+/***************************************************************************************************
+ * Copyright (c) 2003, 2004 IBM Corporation 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: IBM Corporation - initial API and implementation
+ **************************************************************************************************/
+package org.eclipse.wst.common.internal.emf.resource;
+
+
+public class EMF2DOMRendererFactory extends RendererFactory {
+
+ public static final EMF2DOMRendererFactory INSTANCE = new EMF2DOMRendererFactory();
+
+ public EMF2DOMRendererFactory() {
+ super();
+ }
+
+ /**
+ * @see com.ibm.etools.emf2xml.RendererFactory#createRenderer()
+ */
+ public Renderer createRenderer() {
+ EMF2DOMRenderer renderer = new EMF2DOMRenderer();
+ renderer.setValidating(isValidating());
+ return renderer;
+ }
+
+}
\ No newline at end of file
diff --git a/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/resource/EMF2DOMRendererFactoryDefaultHandler.java b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/resource/EMF2DOMRendererFactoryDefaultHandler.java
new file mode 100644
index 0000000..1257a06
--- /dev/null
+++ b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/resource/EMF2DOMRendererFactoryDefaultHandler.java
@@ -0,0 +1,46 @@
+/*******************************************************************************
+ * Copyright (c) 2003, 2004 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+/*
+ * Created on Dec 1, 2003
+ *
+ * To change the template for this generated file go to
+ * Window>Preferences>Java>Code Generation>Code and Comments
+ */
+package org.eclipse.wst.common.internal.emf.resource;
+
+
+/**
+ * @author schacher
+ *
+ * To change the template for this generated type comment go to
+ * Window>Preferences>Java>Code Generation>Code and Comments
+ */
+public class EMF2DOMRendererFactoryDefaultHandler implements RendererFactoryDefaultHandler {
+
+ public static final EMF2DOMRendererFactoryDefaultHandler INSTANCE = new EMF2DOMRendererFactoryDefaultHandler();
+
+ /**
+ *
+ */
+ protected EMF2DOMRendererFactoryDefaultHandler() {
+ super();
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see com.ibm.etools.emf2xml.RendererFactoryDefaultHandler#getDefaultRendererFactory()
+ */
+ public RendererFactory getDefaultRendererFactory() {
+ return EMF2DOMRendererFactory.INSTANCE;
+ }
+
+}
\ No newline at end of file
diff --git a/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/resource/EMF2SAXDocumentHandler.java b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/resource/EMF2SAXDocumentHandler.java
new file mode 100644
index 0000000..a25bb63
--- /dev/null
+++ b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/resource/EMF2SAXDocumentHandler.java
@@ -0,0 +1,210 @@
+/*******************************************************************************
+ * Copyright (c) 2003, 2005 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.wst.common.internal.emf.resource;
+
+
+import java.io.IOException;
+
+import org.eclipse.jem.util.logger.proxy.Logger;
+import org.xml.sax.Attributes;
+import org.xml.sax.EntityResolver;
+import org.xml.sax.InputSource;
+import org.xml.sax.SAXException;
+import org.xml.sax.SAXParseException;
+import org.xml.sax.helpers.DefaultHandler;
+
+/**
+ * The EMF2SAXDocumentHandler is utilized by the SAX parser to announce XML Events, such as
+ * beginning and end of XML elements and the contents of those elements.
+ *
+ * @author mdelder
+ */
+public class EMF2SAXDocumentHandler extends DefaultHandler {
+
+ private TranslatorResource resource = null;
+ private final CacheEventStack eventStack = new CacheEventStack();
+ private CacheEventPool availableEventPool = new CacheEventPool();
+
+ /**
+ * Create an EMF2SAXDocumentHandler to populate the given resource.
+ *
+ */
+ public EMF2SAXDocumentHandler(TranslatorResource resource) {
+ this.resource = resource;
+ }
+
+ /**
+ * @see org.xml.sax.helpers.DefaultHandler#resolveEntity(java.lang.String, java.lang.String)
+ */
+ public InputSource resolveEntity(String publicId, String systemId) throws SAXException {
+ InputSource result = null;
+ this.resource.setDoctypeValues(publicId, systemId);
+
+ try {
+ EntityResolver entityResolver = this.resource.getEntityResolver();
+
+ if (entityResolver != null)
+ result = entityResolver.resolveEntity(publicId, systemId);
+ else
+ result = super.resolveEntity(publicId, systemId);
+ } catch (IOException ioe) {
+ throw new SAXException(ioe);
+ }
+
+ return result;
+ }
+
+ /**
+ * @see org.xml.sax.ContentHandler#startDocument()
+ */
+ public void startDocument() throws SAXException {
+ /*
+ * The endDocument() method should have frozen the pool, or it may not be warmed yet. In
+ * either case, this method call will do as little work as necessary
+ */
+ availableEventPool.warmPool();
+
+ /* This line should not be necessary, but is left for safty */
+ eventStack.clear();
+ this.createRoot(this.resource);
+
+ }
+
+ /**
+ * @see org.xml.sax.ContentHandler#startElement(java.lang.String, java.lang.String,
+ * java.lang.String, org.xml.sax.Attributes)
+ */
+ public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
+ addToStack(qName, attributes);
+ }
+
+ /**
+ * @see org.xml.sax.ContentHandler#characters(char[], int, int)
+ */
+ public void characters(char[] data, int start, int length) throws SAXException {
+
+ CacheEventNode currentRecord = getCurrentRecord();
+ if (currentRecord != null) {
+ currentRecord.appendToBuffer(data, start, length);
+ }
+ }
+
+ /**
+ * @see org.xml.sax.ContentHandler#endElement(java.lang.String, java.lang.String,
+ * java.lang.String)
+ */
+ public void endElement(String uri, String localName, String qName) throws SAXException {
+
+ CacheEventNode currentRecord = null;
+
+ /*
+ * This should only happen in the case where the DOMPath was ignored so the stack does not
+ * quite match with the XML data structure. In this case we do nothing
+ */
+ if (qName.equals(this.getCurrentRecord().getNodeName())) {
+ currentRecord = this.removeCurrentRecord();
+ if (currentRecord != null) {
+ currentRecord.commit();
+ }
+ }
+ }
+
+ /**
+ * @see org.xml.sax.ContentHandler#endDocument()
+ */
+ public void endDocument() throws SAXException {
+ CacheEventNode lastRecord = this.removeCurrentRecord();
+ lastRecord.commit();
+ availableEventPool.freezePool();
+ }
+
+ /**
+ * @see org.xml.sax.ErrorHandler#error(org.xml.sax.SAXParseException)
+ */
+ public void error(SAXParseException ex) throws SAXException {
+ throw ex;
+ }
+
+ /**
+ * @see org.xml.sax.ErrorHandler#fatalError(org.xml.sax.SAXParseException)
+ */
+ public void fatalError(SAXParseException ex) throws SAXException {
+ throw ex;
+ }
+
+ /**
+ * @see org.xml.sax.ErrorHandler#warning(org.xml.sax.SAXParseException)
+ */
+ public void warning(SAXParseException ex) throws SAXException {
+ Logger.getLogger().logWarning(ex);
+ }
+
+ /**
+ * @return
+ */
+ public TranslatorResource getResource() {
+ return resource;
+ }
+
+ protected void createRoot(TranslatorResource resourceArg) {
+ this.eventStack.push(availableEventPool.createCacheEventNode(resourceArg));
+ }
+
+ protected void addToStack(String nodeName, Attributes attributes) {
+ CacheEventNode parent = this.getCurrentRecord();
+ if (!parent.isChildIgnorable(nodeName)) {
+ this.eventStack.push(availableEventPool.createCacheEventNode(parent, nodeName, attributes));
+ }
+ }
+
+ /**
+ * Return the current CENO without removing it from the event stack.
+ *
+ * @return the current CENO without removing it
+ */
+ protected CacheEventNode getCurrentRecord() {
+ CacheEventNode result = null;
+ if (!this.eventStack.isEmpty()) {
+ result = this.eventStack.peek();
+ }
+ return result;
+ }
+
+ /**
+ * Return the current CENO and remove it from the event stack.
+ *
+ * @return the current CENO and remove it
+ */
+ protected CacheEventNode removeCurrentRecord() {
+ CacheEventNode result = null;
+ if (!this.eventStack.isEmpty()) {
+ result = this.eventStack.pop();
+ }
+ return result;
+ }
+
+ // private final void printStack() {
+ // // System.out.println("Printing stack ...");
+ // // for (int i = 0; i < this.eventStack.size(); i++) {
+ // // debug("stack[" + i + "]: " + eventStack.get(i));
+ // // }
+ // // System.out.println("... Printed stack");
+ // }
+ //
+ // private final static void debug(Object obj) {
+ // // System.out.println(obj);
+ // }
+ //
+ // private final static void warn(Object obj) {
+ // //System.err.println(obj);
+ // }
+
+}
diff --git a/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/resource/EMF2SAXRenderer.java b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/resource/EMF2SAXRenderer.java
new file mode 100644
index 0000000..86f721f
--- /dev/null
+++ b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/resource/EMF2SAXRenderer.java
@@ -0,0 +1,175 @@
+/*******************************************************************************
+ * Copyright (c) 2003, 2005 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.wst.common.internal.emf.resource;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.util.Map;
+
+import javax.xml.parsers.SAXParser;
+import javax.xml.parsers.SAXParserFactory;
+import javax.xml.transform.OutputKeys;
+import javax.xml.transform.Transformer;
+import javax.xml.transform.TransformerConfigurationException;
+import javax.xml.transform.TransformerFactory;
+import javax.xml.transform.TransformerFactoryConfigurationError;
+import javax.xml.transform.sax.SAXTransformerFactory;
+import javax.xml.transform.sax.TransformerHandler;
+import javax.xml.transform.stream.StreamResult;
+
+import org.eclipse.emf.common.util.WrappedException;
+import org.eclipse.jem.util.logger.proxy.Logger;
+import org.xml.sax.InputSource;
+import org.xml.sax.SAXException;
+import org.xml.sax.SAXNotRecognizedException;
+import org.xml.sax.XMLReader;
+
+/**
+ * @author mdelder
+ */
+public class EMF2SAXRenderer extends AbstractRendererImpl {
+
+ /**
+ *
+ */
+ public EMF2SAXRenderer() {
+ super();
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see com.ibm.etools.emf2xml.Renderer#doLoad(java.io.InputStream, java.util.Map)
+ */
+ public void doLoad(InputStream in, Map options) {
+ try {
+ SAXParserFactory factory = SAXParserFactory.newInstance();
+ factory.setValidating(isValidating());
+ factory.setNamespaceAware(true);
+ /*
+ * Causes errors in IBM JDK try { factory.setAttribute(JAXP_SCHEMA_LANGUAGE,
+ * W3C_XML_SCHEMA); } catch (IllegalArgumentException x) { }
+ */
+ SAXParser parser = factory.newSAXParser();
+ XMLReader reader = parser.getXMLReader();
+ EMF2SAXDocumentHandler handler = new EMF2SAXDocumentHandler(this.getResource());
+ try {
+ reader.setFeature("http://xml.org/sax/features/validation", isValidating()); //$NON-NLS-1$
+ } catch (SAXNotRecognizedException snre) {
+ }
+ try {
+ reader.setFeature("http://xml.org/sax/features/namespace-prefixes", true); //$NON-NLS-1$
+ } catch (SAXNotRecognizedException snre) {
+ }
+ try {
+ reader.setFeature("http://apache.org/xml/features/validation/schema", isValidating()); //$NON-NLS-1$
+ } catch (SAXNotRecognizedException e) {
+ reader.setFeature("http://xml.org/sax/features/validation", false); //$NON-NLS-1$
+ Logger.getLogger().log("Warning: Parser does not support \"http://apache.org/xml/features/validation/schema\". Validation will be disabled."); //$NON-NLS-1$
+ }
+ try {
+ reader.setFeature("http://apache.org/xml/features/allow-java-encodings", true); //$NON-NLS-1$
+ } catch (SAXNotRecognizedException e) {
+ Logger.getLogger().log("Warning: Parser does not support \"http://apache.org/xml/features/allow-java-encodings\"."); //$NON-NLS-1$
+ }
+ /*
+ * try { reader.setProperty("http://xml.org/sax/properties/lexical-handler", handler); }
+ * catch (SAXNotRecognizedException e) { }
+ */
+ reader.setContentHandler(handler);
+ reader.setErrorHandler(handler);
+ //reader.setDTDHandler(handler);
+ reader.setEntityResolver(handler);
+ InputSource testsource = new InputSource(in);
+ reader.parse(testsource);
+ } catch (RuntimeException t_rex) {
+ throw t_rex;
+ } catch (Exception ex) {
+ throw new WrappedException(ex);
+ }
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see com.ibm.etools.emf2xml.Renderer#doSave(java.io.OutputStream, java.util.Map)
+ */
+ public void doSave(OutputStream outputStream, Map options) throws IOException {
+
+ /*
+ * try { Serializer serializer =
+ * SerializerFactory.getSerializerFactory(Method.XML).makeSerializer(outputStream,
+ * createOutputFormat()); serializer.setOutputByteStream(outputStream); ContentHandler
+ * handler = serializer.asContentHandler();
+ */
+
+ TransformerHandler handler = null;
+ try {
+ try {
+ SAXTransformerFactory factory = (SAXTransformerFactory) TransformerFactory.newInstance();
+ handler = factory.newTransformerHandler();
+
+ handler.setResult(new StreamResult(outputStream));
+ Transformer transformer = handler.getTransformer();
+ transformer.setOutputProperty(OutputKeys.INDENT, "yes"); //$NON-NLS-1$
+ transformer.setOutputProperty(OutputKeys.ENCODING, getResource().getEncoding());
+ transformer.setOutputProperty(OutputKeys.VERSION, getResource().getXMLVersion());
+ transformer.setOutputProperty(OutputKeys.METHOD, "xml"); //$NON-NLS-1$
+ transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no"); //$NON-NLS-1$
+ transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4"); //$NON-NLS-1$ //$NON-NLS-2$
+
+ if (getResource().getPublicId() != null)
+ transformer.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, getResource().getPublicId());
+ if (getResource().getSystemId() != null)
+ transformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, getResource().getSystemId());
+
+ } catch (TransformerConfigurationException e) {
+ Logger.getLogger().logError(e);
+ } catch (TransformerFactoryConfigurationError e) {
+ Logger.getLogger().logError(e);
+ }
+ if (handler == null) {
+ Logger.getLogger("SAX Writer is null"); //$NON-NLS-1$
+ return;
+ }
+ EMF2SAXWriter writer = new EMF2SAXWriter();
+ writer.serialize(this.resource, handler);
+ } catch (SAXException saxe) {
+ throw new WrappedException(saxe);
+ }
+ }
+
+ /*
+ * protected OutputFormat createOutputFormat() { OutputFormat format = new OutputFormat();
+ * format.setIndenting(true); format.setLineSeparator(DOMUtilities.NEWLINE_STRING);
+ * //$NON-NLS-1$ format.setEncoding(getResource().getEncoding());
+ * format.setVersion(getResource().getXMLVersion()); if (this.resource != null)
+ * format.setDoctype(this.resource.getPublicId(), this.resource.getSystemId()); return format; }
+ */
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see com.ibm.etools.emf2xml.Renderer#prepareToAddContents()
+ */
+ public void prepareToAddContents() {
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see com.ibm.etools.emf2xml.Renderer#getVersionID()
+ */
+ public int getVersionID() {
+ return getResource().getVersionID();
+ }
+}
diff --git a/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/resource/EMF2SAXRendererFactory.java b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/resource/EMF2SAXRendererFactory.java
new file mode 100644
index 0000000..d3fd5d9
--- /dev/null
+++ b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/resource/EMF2SAXRendererFactory.java
@@ -0,0 +1,42 @@
+/*******************************************************************************
+ * Copyright (c) 2003, 2004 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+/*
+ * Created on Aug 19, 2003
+ *
+ */
+package org.eclipse.wst.common.internal.emf.resource;
+
+
+/**
+ * Used to create instances of the EMF2SAXRenderer
+ *
+ * @author mdelder
+ */
+public class EMF2SAXRendererFactory extends RendererFactory {
+
+ public static final EMF2SAXRendererFactory INSTANCE = new EMF2SAXRendererFactory();
+
+ protected EMF2SAXRendererFactory() {
+ super();
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see com.ibm.etools.emf2xml.RendererFactory#createRenderer()
+ */
+ public Renderer createRenderer() {
+ EMF2SAXRenderer renderer = new EMF2SAXRenderer();
+ renderer.setValidating(isValidating());
+ return renderer;
+ }
+
+}
\ No newline at end of file
diff --git a/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/resource/EMF2SAXWriter.java b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/resource/EMF2SAXWriter.java
new file mode 100644
index 0000000..6955734
--- /dev/null
+++ b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/resource/EMF2SAXWriter.java
@@ -0,0 +1,387 @@
+/*******************************************************************************
+ * Copyright (c) 2003, 2004 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.wst.common.internal.emf.resource;
+
+
+import java.util.List;
+import java.util.Stack;
+
+import org.eclipse.emf.common.util.EList;
+import org.eclipse.emf.ecore.EObject;
+import org.xml.sax.Attributes;
+import org.xml.sax.ContentHandler;
+import org.xml.sax.SAXException;
+import org.xml.sax.helpers.AttributesImpl;
+
+/**
+ * The EMF2SAXWriter handles the serialization of EMF Resources using SAX events. SAX events are
+ * triggered to the content handler as the tree is being parsed. These events can then be written
+ * into any stream wrapped by the ContentHandler.
+ *
+ * @author mdelder
+ */
+public class EMF2SAXWriter {
+
+ public static final String NAMESPACE = "";//"http://java.sun.com/xml/ns/j2ee"; //$NON-NLS-1$
+
+ /* Used in those cases where no Attributes are necessary */
+ private static final Attributes EMPTY_ATTRIBUTES = new AttributesImpl();
+
+ /**
+ * Serialize an EMF resource into an XML Stream using the given ContentHandler. Note that this
+ * method can also be used to copy a given EMF Resource if the EMF2SAXDocumentHandler is used as
+ * the given ContentHandler.
+ *
+ * @param resource
+ * @param handler
+ */
+ public void serialize(TranslatorResource resource, ContentHandler handler) throws SAXException {
+
+ Translator rootTranslator = resource.getRootTranslator();
+ EList contents = resource.getContents();
+
+ if (contents.size() != 1) {
+ throw new IllegalStateException("The contents of a resource may only contain one EMF Model Object."); //$NON-NLS-1$
+ }
+ handler.startDocument();
+ EObject element = (EObject) contents.get(0);
+ serialize(handler, element, rootTranslator, new WriterHints(resource));
+ handler.endDocument();
+
+ }
+
+ private void serialize(ContentHandler handler, EObject target, Translator translator, WriterHints hints) throws SAXException {
+
+ List mofChildren = null;
+ Object rawValue = null;
+ EObject newTarget = null;
+ Translator currentChildTranslator = null;
+ Translator nextTranslator = null;
+ char[] characterData = null;
+ String convertedValue = null;
+ Attributes attributes = null;
+ String childDomName = null;
+ final int version = hints.getVersion();
+
+ /*
+ * Processing hints are used to remember where are in the iteration of the translator's
+ * children. see the TranslatorFilter for more information on how this array is used.
+ */
+ int[] processingHints = TranslatorFilter.createProcessingHints();
+
+ String targetDomName = translator.getDOMName(target);
+
+ attributes = getAttributes(translator, target, hints);
+
+ handler.startElement(NAMESPACE, targetDomName, targetDomName, attributes);
+
+ currentChildTranslator = TranslatorFilter.getNextObjectTranslator(translator, processingHints[TranslatorFilter.NEXT_START_HINT_INDX], processingHints, target, version);
+ while (currentChildTranslator != null) {
+ /* For each Child Translator of the Translator parameter passed into the method */
+
+ /* Does the Translator have any MOF Children? */
+ mofChildren = currentChildTranslator.getMOFChildren(target);
+ openDomPathIfNecessary(handler, hints, currentChildTranslator, target, mofChildren);
+
+ if (currentChildTranslator.isManagedByParent()) {
+ /*
+ * Translators which are managed by their parents require less processing -- just
+ * convert their value to a string and write it out as the content of an XML element
+ */
+ childDomName = currentChildTranslator.getDOMName(target);
+ if (!currentChildTranslator.isEmptyTag()) {
+ /* The Translator is not an Empty tag. Its text content is significant */
+
+ if (mofChildren.size() > 0) {
+ for (int j = 0; j < mofChildren.size(); j++) {
+
+ /* Text only translators will not have open and close XML elements */
+ if (!currentChildTranslator.isDOMTextValue())
+ handler.startElement(NAMESPACE, childDomName, childDomName, EMPTY_ATTRIBUTES);
+
+ rawValue = mofChildren.get(j);
+ /* convertValueToString should always return a non-null String */
+ convertedValue = currentChildTranslator.convertValueToString(rawValue, target);
+ characterData = XMLEncoderDecoder.escape(convertedValue).toCharArray();
+ handler.characters(characterData, 0, characterData.length);
+
+ if (!currentChildTranslator.isDOMTextValue())
+ handler.endElement(NAMESPACE, childDomName, childDomName);
+ }
+ }
+ } else {
+ /*
+ * The Translator is an Empty Element (its mere presence has significance) (e.g.
+ * <cascade-delete/>
+ */
+
+ if (currentChildTranslator.isBooleanFeature()) {
+ /* Boolean features may or may not be rendered */
+ rawValue = mofChildren.get(0);
+ if (rawValue != null && ((Boolean) rawValue).booleanValue()) {
+ handler.startElement(NAMESPACE, childDomName, childDomName, EMPTY_ATTRIBUTES);
+ handler.endElement(NAMESPACE, childDomName, childDomName);
+ }
+
+ } else {
+ /* Always render any other Empty elements */
+ handler.startElement(NAMESPACE, childDomName, childDomName, EMPTY_ATTRIBUTES);
+ handler.endElement(NAMESPACE, childDomName, childDomName);
+ }
+ }
+ } else {
+
+ /* The Translator is a more complex feature, handle its processing recursively */
+ for (int j = 0; j < mofChildren.size(); j++) {
+ newTarget = (EObject) mofChildren.get(j);
+ serialize(handler, newTarget, currentChildTranslator, hints);
+ }
+ }
+
+ /* Fetch the next peer translator */
+ nextTranslator = TranslatorFilter.getNextObjectTranslator(translator, processingHints[TranslatorFilter.NEXT_START_HINT_INDX], processingHints, target, version);
+
+ closeDomPathIfNecessary(handler, hints, currentChildTranslator, nextTranslator, target, mofChildren);
+
+ /*
+ * We needed to invoke closeDomPathIfNecessary() with the peer, now we move on to
+ * process that peer
+ */
+ currentChildTranslator = nextTranslator;
+
+ }
+ handler.endElement(NAMESPACE, targetDomName, targetDomName);
+ }
+
+ /**
+ * Determines whether or not a DOM Path should be rendered. This method is particularly useful
+ * for determining whether Empty XML elements are relevant and should be written to the XML
+ * stream.
+ *
+ * @param target
+ * The EMF Target of the Translation
+ * @param currentChildTranslator
+ * The current Translator
+ * @param mofChildren
+ * The mofChildren that were found for the Translator on the Target
+ * @return
+ */
+ private boolean shouldRenderDomPath(EObject target, Translator currentChildTranslator, List mofChildren) {
+ return (currentChildTranslator.shouldRenderEmptyDOMPath(target) || mofChildren.size() > 0);
+ }
+
+ /**
+ * openDomPathIfNecessary will write the current DOM Path to the serialization stream if it has
+ * not been written by a previous peer translator. The processing results in the collapse of
+ * Peer Translators with matching DOM Paths into a single XML parent element.
+ *
+ * @param handler
+ * The ContentHandler which is writing the XML result
+ * @param hints
+ * A Global container for information specific to a single XML document
+ * @param currentChildTranslator
+ * The active Translator being processed
+ * @param target
+ * The EMF Target of the Translation
+ * @throws SAXException
+ */
+ private void openDomPathIfNecessary(ContentHandler handler, WriterHints hints, Translator currentChildTranslator, EObject target, List mofChildren) throws SAXException {
+
+ /* If the translator does not have a DOM Path, then we do nothing */
+ if (currentChildTranslator.hasDOMPath() && shouldRenderDomPath(target, currentChildTranslator, mofChildren)) {
+
+ String childDomPath = currentChildTranslator.getDOMPath();
+
+ /*
+ * IsDomPathActive() will verify whether this DOM Path has already been written to the
+ * XML stream
+ */
+ if (!hints.isDomPathActive(childDomPath)) {
+
+ /*
+ * Write an open element for the DOM Path and "remember" that we have written it
+ */
+ handler.startElement(NAMESPACE, childDomPath, childDomPath, EMPTY_ATTRIBUTES);
+ hints.pushDomPath(childDomPath);
+ }
+
+ }
+ }
+
+ /**
+ * closeDomPathIfNecessary will determine whether the next peer Translator shares the active DOM
+ * Path of the current Translator. If the next peer Translator has the same DOM Path, no action
+ * will be taken (hence condensing the elements into a single XML parent). However, if the DOM
+ * Path differs (including the Next Peer Translator has no DOM Path) then the current DOM Path
+ * will be closed (a close XML element is generated.
+ *
+ * @param handler
+ * The ContentHandler which is writing the XML result
+ * @param hints
+ * A Global container for information specific to a single XML document
+ * @param currentChildTranslator
+ * The last Translator to have completed processing
+ * @param nextTranslator
+ * The next peer Translator that will become active
+ * @param target
+ * The EMF Target of the Translation
+ * @throws SAXException
+ */
+ private void closeDomPathIfNecessary(ContentHandler handler, WriterHints hints, Translator currentChildTranslator, Translator nextTranslator, EObject target, List mofChildren) throws SAXException {
+
+ if (currentChildTranslator.hasDOMPath() && shouldRenderDomPath(target, currentChildTranslator, mofChildren)) {
+ String childDomPath = currentChildTranslator.getDOMPath();
+ if (nextTranslator != null) { /*
+ * There are more peers after this element, we can peek
+ * ahead
+ */
+ String nextPeerDomPath = nextTranslator.getDOMPath();
+ if (nextPeerDomPath == null || !nextPeerDomPath.equals(childDomPath)) {
+ handler.endElement(NAMESPACE, childDomPath, childDomPath);
+ hints.popDomPath();
+ }
+
+ } else { /* This was the last child element, we must close the dompath */
+ handler.endElement(NAMESPACE, childDomPath, childDomPath);
+ hints.popDomPath();
+ }
+ }
+ }
+
+ /**
+ * Aggregate the Attribute translator children from a given translator. This method will request
+ * the AttributesImpl object from the WriterHints object. The WriterHints maintains this
+ * reusable collection to limit the requirement for new object creation.
+ *
+ * @param translator
+ * @param target
+ * @param hints
+ * @return an initialized set of Attributes for the given Translator and EMF Target
+ */
+ private Attributes getAttributes(Translator translator, EObject target, WriterHints hints) {
+
+ AttributesImpl attributes = hints.getAttributeHolder();
+ int version = hints.getVersion();
+ Object rawValue = null;
+ String convertedValue = null;
+ String childDomName = null;
+ Translator attributeTranslator = null;
+ int[] processingHints = TranslatorFilter.createProcessingHints();
+
+ while ((attributeTranslator = TranslatorFilter.getNextAttributeTranslator(translator, processingHints[TranslatorFilter.NEXT_START_HINT_INDX], processingHints, target, version)) != null) {
+
+ List mofChildren = attributeTranslator.getMOFChildren(target);
+ if (mofChildren.size() > 0) {
+ for (int j = 0; j < mofChildren.size(); j++) {
+
+ childDomName = attributeTranslator.getDOMName(target);
+ rawValue = mofChildren.get(j);
+ convertedValue = attributeTranslator.convertValueToString(rawValue, target);
+ convertedValue = XMLEncoderDecoder.escape(convertedValue);
+ attributes.addAttribute(NAMESPACE, childDomName, childDomName, "String", convertedValue); //$NON-NLS-1$
+ }
+
+ } else {
+ childDomName = attributeTranslator.getDOMName(target);
+ convertedValue = (String) attributeTranslator.getMOFValue(target);
+ if (convertedValue != null)
+ attributes.addAttribute(NAMESPACE, childDomName, childDomName, "String", convertedValue); //$NON-NLS-1$
+ }
+ }
+ return attributes;
+ }
+
+ /**
+ * WriterHints is used to "remember" certain pieces of information while the writer is
+ * processing. Of particular interest are the version and the state of the DOM Path output.
+ * Consecutive elements with consistent (identical) DOM Paths are collapsed under a single XML
+ * element.
+ *
+ * The WriterHints provides global state between recursive invocations of serialize(). It should
+ * be not be used to store local data (e.g. data that is only relevant to a single Translator in
+ * a given context).
+ *
+ * The WriterHints also stores an AttributesImpl object that is re-used to store attributes. The
+ * getAttributes() method will request the Attributes Holder.
+ *
+ * @author mdelder
+ */
+ public final class WriterHints {
+ private final TranslatorResource resource;
+ private final Stack domStack = new Stack();
+ private final AttributesImpl attributesImpl = new AttributesImpl();
+
+ public WriterHints(TranslatorResource res) {
+ this.resource = res;
+ }
+
+ /**
+ * Push a new domPath onto the stack
+ *
+ * @param domPath
+ * a DOMPath which has been written to the XML stream
+ */
+ public void pushDomPath(String domPath) {
+
+ if (domPath != null && domPath.length() > 0)
+ domStack.push(domPath);
+ }
+
+ /**
+ * Pop the current domPath from the Array
+ */
+ public void popDomPath() {
+
+ if (!domStack.isEmpty())
+ domStack.pop();
+ }
+
+ /**
+ * Determines if the given DOMPath has already been written to the XML stream
+ *
+ * @param domPath
+ * @return true if the given DOMPath has already been written to the XML stream
+ */
+ public boolean isDomPathActive(String domPath) {
+ boolean result = false;
+ if (!domStack.isEmpty()) {
+
+ String currentDomPath = (String) domStack.peek();
+ if (currentDomPath != null && domPath != null)
+ result = currentDomPath.equals(domPath);
+ else if (!(currentDomPath == null ^ domPath == null))
+ result = true;
+ }
+
+ return result;
+ }
+
+ /**
+ * @return the version of the EMF Resource
+ */
+ public int getVersion() {
+ return this.resource.getVersionID();
+ }
+
+ /**
+ * Returns an empty AttributesImpl object to store attributes. Within the context of a given
+ * WriterHints object (and hence single XML document), the object returned is a singleton.
+ * The same AttributesImpl object is cleared and reused for each invocation.
+ *
+ * @return an empty AttributesImpl object to store attributes
+ */
+ public AttributesImpl getAttributeHolder() {
+ this.attributesImpl.clear();
+ return this.attributesImpl;
+ }
+
+ }
+}
\ No newline at end of file
diff --git a/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/resource/FileNameResourceFactoryRegistry.java b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/resource/FileNameResourceFactoryRegistry.java
new file mode 100644
index 0000000..41b3dab
--- /dev/null
+++ b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/resource/FileNameResourceFactoryRegistry.java
@@ -0,0 +1,97 @@
+/*******************************************************************************
+ * Copyright (c) 2003, 2007 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.wst.common.internal.emf.resource;
+
+import java.util.HashMap;
+import java.util.Map;
+
+import org.eclipse.emf.common.util.URI;
+import org.eclipse.emf.ecore.resource.Resource;
+import org.eclipse.emf.ecore.resource.Resource.Factory;
+import org.eclipse.wst.common.internal.emf.utilities.DefaultOverridableResourceFactoryRegistry;
+
+
+public abstract class FileNameResourceFactoryRegistry extends DefaultOverridableResourceFactoryRegistry {
+
+ private Map/*<String shortName, ResourceFactoryDescriptor>*/ descriptors = new HashMap();
+ private Map/*<ResourceFactoryDescriptor, Resource.Factory>*/ factories = new HashMap();
+
+ public FileNameResourceFactoryRegistry() {
+ super();
+ }
+
+ /**
+ * Return a Resource.Factory that is registered with the last segment of the URI's file name.
+ *
+ * @see org.eclipse.emf.ecore.resource.impl.ResourceFactoryRegistryImpl#getFactory(URI)
+ */
+ protected Object getFileNameFactory(URI uri) {
+
+ if(uri != null) {
+ ResourceFactoryDescriptor descriptor = getDescriptor(uri);
+
+ if(descriptor != null) {
+ return getFactory(descriptor);
+ }
+ }
+ return null;
+
+ }
+
+ public synchronized Resource.Factory getFactory(URI uri) {
+ return getFactory(uri, null);
+ }
+
+ public Resource.Factory getFactory(URI uri, String contentType)
+ {
+ Resource.Factory resourceFactory = null;
+ if(uri != null && uri.lastSegment() != null) {
+ ResourceFactoryDescriptor descriptor = getDescriptor(uri);
+
+ if(descriptor != null) {
+ resourceFactory = getFactory(descriptor);
+ }
+ }
+ if(resourceFactory == null)
+ resourceFactory = super.getFactory(uri, contentType);
+ return resourceFactory;
+ }
+
+ /**
+ * Register a file name representing the last segment of a URI with the corresponding
+ * Resource.Factory.
+ */
+ public synchronized void registerLastFileSegment(String aSimpleFileName, Resource.Factory aFactory) {
+ URI uri = URI.createURI(aSimpleFileName);
+ String lastSegment = uri.lastSegment();
+ addDescriptor(new StaticResourceFactoryDescriptor(lastSegment, aFactory));
+ }
+
+ protected synchronized ResourceFactoryDescriptor getDescriptor(URI uri) {
+ return (ResourceFactoryDescriptor) descriptors.get(uri.lastSegment());
+ }
+ protected synchronized Map getDescriptors() {
+ return descriptors;
+ }
+
+ protected final synchronized Resource.Factory getFactory(ResourceFactoryDescriptor descriptor) {
+ Resource.Factory factory = (Factory) factories.get(descriptor);
+ if(factory == null) {
+ factories.put(descriptor, (factory = descriptor.createFactory()));
+ }
+ return factory;
+ }
+
+ protected void addDescriptor(ResourceFactoryDescriptor descriptor) {
+ descriptors.put(descriptor.getShortSegment(), descriptor);
+ }
+
+}
diff --git a/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/resource/GenericTranslator.java b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/resource/GenericTranslator.java
new file mode 100644
index 0000000..eafe09f
--- /dev/null
+++ b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/resource/GenericTranslator.java
@@ -0,0 +1,110 @@
+/*******************************************************************************
+ * Copyright (c) 2003, 2004 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+/*
+ * Created on Mar 20, 2003
+ *
+ */
+package org.eclipse.wst.common.internal.emf.resource;
+
+import org.eclipse.emf.ecore.EClass;
+import org.eclipse.emf.ecore.EStructuralFeature;
+
+/**
+ * Specialized translator for objects that contain simple mappings with no specialized behavior.
+ */
+public class GenericTranslator extends Translator {
+
+ protected Translator[] children;
+
+ /**
+ * @param domNameAndPath
+ * @param eClass
+ */
+ public GenericTranslator(String domNameAndPath, EClass eClass) {
+ super(domNameAndPath, eClass);
+ }
+
+ /**
+ * @param domNameAndPath
+ * @param aFeature
+ */
+ public GenericTranslator(String domNameAndPath, EStructuralFeature aFeature) {
+ super(domNameAndPath, aFeature);
+ }
+
+ /**
+ * @param domNameAndPath
+ * @param aFeature
+ * @param path
+ */
+ public GenericTranslator(String domNameAndPath, EStructuralFeature aFeature, TranslatorPath path) {
+ super(domNameAndPath, aFeature, path);
+ }
+
+ /**
+ * @param domNameAndPath
+ * @param aFeature
+ * @param paths
+ */
+ public GenericTranslator(String domNameAndPath, EStructuralFeature aFeature, TranslatorPath[] paths) {
+ super(domNameAndPath, aFeature, paths);
+ }
+
+ /**
+ * @param domNameAndPath
+ * @param aFeature
+ * @param eClass
+ */
+ public GenericTranslator(String domNameAndPath, EStructuralFeature aFeature, EClass eClass) {
+ super(domNameAndPath, aFeature, eClass);
+ }
+
+ /**
+ * @param domNameAndPath
+ * @param aFeature
+ * @param style
+ */
+ public GenericTranslator(String domNameAndPath, EStructuralFeature aFeature, int style) {
+ super(domNameAndPath, aFeature, style);
+ }
+
+ /**
+ * @return Translator[]
+ */
+ public Translator[] getChildren() {
+ return children;
+ }
+
+ /**
+ * Sets the children.
+ *
+ * @param children
+ * The children to set
+ */
+ public void setChildren(Translator[] children) {
+ this.children = children;
+ }
+
+
+ public static Translator appendChildren(GenericTranslator tran, Translator[] child) {
+ Translator[] orgChild = tran.getChildren();
+ Translator[] newChildren = (Translator[]) concat(orgChild, child);
+ tran.setChildren(newChildren);
+ return tran;
+ }
+
+ public static Translator appendChild(GenericTranslator tran, Translator child) {
+ Object[] orgChild = tran.getChildren();
+ Translator[] newChildren = (Translator[]) concat(orgChild, child);
+ tran.setChildren(newChildren);
+ return tran;
+ }
+}
\ No newline at end of file
diff --git a/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/resource/IDTranslator.java b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/resource/IDTranslator.java
new file mode 100644
index 0000000..64bf6a0
--- /dev/null
+++ b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/resource/IDTranslator.java
@@ -0,0 +1,75 @@
+/*******************************************************************************
+ * Copyright (c) 2003, 2005 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+/*
+ * Created on Mar 19, 2003
+ *
+ */
+package org.eclipse.wst.common.internal.emf.resource;
+
+import org.eclipse.emf.ecore.EObject;
+import org.eclipse.emf.ecore.EStructuralFeature;
+import org.eclipse.emf.ecore.EcorePackage;
+import org.eclipse.emf.ecore.xmi.XMIResource;
+
+/**
+ * @author schacher
+ */
+public class IDTranslator extends Translator {
+ public class NoResourceException extends RuntimeException {
+
+ public NoResourceException() {
+ super();
+ }
+
+ public NoResourceException(String s) {
+ super(s);
+ }
+ }
+
+ static final public EStructuralFeature ID_FEATURE = EcorePackage.eINSTANCE.getEClass_EIDAttribute();
+ static final public IDTranslator INSTANCE = new IDTranslator();
+
+ public IDTranslator() {
+ super("id", ID_FEATURE, DOM_ATTRIBUTE); //$NON-NLS-1$
+ }
+
+ public void setMOFValue(EObject emfObject, Object value) {
+ XMIResource res = (XMIResource) emfObject.eResource();
+ if (res == null)
+ throw new NoResourceException();
+ String id = res.getID(emfObject);
+ if (id == null && value == null)
+ return;
+ if ((id != null && !id.equals(value)) || (value != null && !value.equals(id)))
+ res.setID(emfObject, (String) value);
+ }
+
+ public Object getMOFValue(EObject emfObject) {
+ if (emfObject == null)
+ throw new NoResourceException();
+ XMIResource res = (XMIResource) emfObject.eResource();
+ if (res == null)
+ throw new NoResourceException();
+ return res.getID(emfObject);
+ }
+
+
+ public boolean featureExists(EObject emfObject) {
+ return true;
+ }
+
+ public boolean isIDMap() {
+ return true;
+ }
+
+
+
+}
diff --git a/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/resource/IRootObjectResource.java b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/resource/IRootObjectResource.java
new file mode 100644
index 0000000..7048136
--- /dev/null
+++ b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/resource/IRootObjectResource.java
@@ -0,0 +1,19 @@
+/*******************************************************************************
+ * Copyright (c) 2005, 2007 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.wst.common.internal.emf.resource;
+
+import org.eclipse.emf.ecore.EObject;
+
+public interface IRootObjectResource {
+
+ public EObject getRootObject();
+
+}
diff --git a/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/resource/LinkUpdaterTarget.java b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/resource/LinkUpdaterTarget.java
new file mode 100644
index 0000000..f5cd1f9
--- /dev/null
+++ b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/resource/LinkUpdaterTarget.java
@@ -0,0 +1,59 @@
+/***************************************************************************************************
+ * Copyright (c) 2003, 2004 IBM Corporation 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: IBM Corporation - initial API and implementation
+ **************************************************************************************************/
+package org.eclipse.wst.common.internal.emf.resource;
+
+
+import java.util.Iterator;
+import java.util.List;
+
+import org.eclipse.emf.ecore.EObject;
+import org.eclipse.emf.ecore.util.EcoreUtil;
+import org.w3c.dom.Node;
+
+
+public class LinkUpdaterTarget extends Object {
+
+ public static final LinkUpdaterTarget INSTANCE = new LinkUpdaterTarget();
+
+ /**
+ * Constructor for LinkUpdaterMultiTarget.
+ *
+ * @param adapter
+ */
+ private LinkUpdaterTarget() {
+ super();
+ }
+
+
+ public void updateDOM(Translator map, Node node, EObject mofObject) {
+ refreshSourceObjects(map, node, mofObject, true);
+ }
+
+ public void updateMOF(Translator map, Node node, EObject mofObject) {
+ refreshSourceObjects(map, node, mofObject, false);
+ }
+
+ protected void refreshSourceObjects(Translator map, Node node, EObject mofObject, boolean domUpdate) {
+ TranslatorPath[] paths = map.getTranslatorPaths();
+ for (int i = 0; i < paths.length; i++) {
+ TranslatorPath path = paths[i];
+ List allSourceObjects = path.findObjects(mofObject);
+ for (Iterator iter = allSourceObjects.iterator(); iter.hasNext();) {
+ EObject curObject = (EObject) iter.next();
+ EMF2DOMAdapter curAdapter = (EMF2DOMAdapter) EcoreUtil.getAdapter(curObject.eAdapters(), EMF2DOMAdapter.class);
+ if (curAdapter != null) {
+ if (domUpdate)
+ curAdapter.updateDOM();
+ else
+ curAdapter.updateMOF();
+ }
+ }
+ }
+ }
+}
\ No newline at end of file
diff --git a/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/resource/MappedXMIHelper.java b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/resource/MappedXMIHelper.java
new file mode 100644
index 0000000..f0939a2
--- /dev/null
+++ b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/resource/MappedXMIHelper.java
@@ -0,0 +1,297 @@
+/*******************************************************************************
+ * Copyright (c) 2003, 2005 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.wst.common.internal.emf.resource;
+
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.Set;
+
+import org.eclipse.emf.common.util.URI;
+import org.eclipse.emf.ecore.EClass;
+import org.eclipse.emf.ecore.EObject;
+import org.eclipse.emf.ecore.EPackage;
+import org.eclipse.emf.ecore.EStructuralFeature;
+import org.eclipse.emf.ecore.InternalEObject;
+import org.eclipse.emf.ecore.resource.Resource;
+import org.eclipse.emf.ecore.resource.ResourceSet;
+import org.eclipse.emf.ecore.resource.URIConverter;
+import org.eclipse.emf.ecore.resource.impl.URIConverterImpl;
+import org.eclipse.emf.ecore.xmi.XMLHelper;
+import org.eclipse.emf.ecore.xmi.XMLResource;
+import org.eclipse.emf.ecore.xmi.impl.XMLHelperImpl;
+import org.eclipse.wst.common.internal.emf.utilities.IDUtil;
+
+public class MappedXMIHelper extends XMLHelperImpl {
+
+ private static final String WORKSPACE_PROTOCOL = "workspace:/"; //$NON-NLS-1$
+ private static final String PLATFORM_RESOURCE_PROTOCOL = "platform:/resource/"; //$NON-NLS-1$
+ private static final EStructuralFeature NULL_FEATURE = new UnsupportedFeature();
+ protected boolean usingMaps = true;
+ protected Map cachedRelativeURIs;
+ protected Map packageURIsToPrefixes;
+
+ /**
+ * Constructor for MappedXMLHelper.
+ *
+ * @param resource
+ */
+ public MappedXMIHelper(XMLResource resource, Map prefixesToURIs) {
+ super(resource);
+ this.prefixesToURIs.putAll(prefixesToURIs);
+ pushContext(); //Needed to initialize the context to zero
+ Set keys = prefixesToURIs.keySet();
+ for (Iterator iter = keys.iterator(); iter.hasNext();) {
+ String prefix = (String) iter.next();
+ String uri = (String) prefixesToURIs.get(prefix);
+ namespaceSupport.declarePrefix(prefix, uri);
+ }
+
+ }
+
+ public URI resolve(URI relative, URI base) {
+ URI resolved = null;
+ boolean isMapped = false;
+ ResourceSet set = getResource().getResourceSet();
+ if (set != null) {
+ URI localresourceURI = null;
+ if (relative.hasFragment())
+ localresourceURI = relative.trimFragment();
+ else
+ localresourceURI = relative;
+ isMapped = !(((URIConverterImpl.URIMap) set.getURIConverter().getURIMap()).getURI(localresourceURI).equals(localresourceURI));
+ }
+ if (!isMapped) {
+ if (isUsingContainerRelativePaths() && set != null)
+ resolved = set.getURIConverter().normalize(relative);
+ } else {
+ resolved = relative;
+ }
+ return resolved == null ? super.resolve(relative, base) : resolved;
+ }
+
+ /**
+ * Method isUsingContainerRelativePaths.
+ *
+ * @return boolean
+ */
+ private boolean isUsingContainerRelativePaths() {
+ return ((CompatibilityXMIResource) resource).getFormat() == CompatibilityXMIResource.FORMAT_MOF5 || usingMaps;
+ }
+
+ public void addPrefix(String prefix, String uri) {
+ /*
+ * problem - the incoming key value pair is ejbbnd->ejbbnd.xmi; however, the map already has
+ * a key value pair of ejbbnd->http:///ejbbnd.ecore
+ */
+ if (uri.endsWith(".ecore")) { //$NON-NLS-1$
+ usingMaps = false;
+ }
+ String existing = (String) prefixesToURIs.get(prefix);
+ if (existing == null) {
+ prefixesToURIs.put(prefix, uri);
+ namespaceSupport.declarePrefix(prefix, uri);
+ } else if (!existing.equals(uri)) {
+ getCompatibilityResource().addOriginalPackageURI(existing, uri);
+ getCompatibilityResource().setFormat(CompatibilityXMIResource.FORMAT_MOF5);
+ }
+ }
+
+ protected CompatibilityXMIResource getCompatibilityResource() {
+ return (CompatibilityXMIResource) getResource();
+ }
+
+ /**
+ * @see org.eclipse.emf.ecore.xmi.impl.XMLHelperImpl#getHREF(EObject)
+ */
+ public String getHREF(EObject obj) {
+ if (!getCompatibilityResource().usesDefaultFormat()) {
+ URIConverter conv = getURIConverter();
+ if (conv != null && conv instanceof CompatibilityURIConverter) {
+ String href = getCompatibliltyHREF(obj, (CompatibilityURIConverter) conv);
+ return useWorkspaceProtocolIfNecessary(href);
+ }
+ }
+ return super.getHREF(obj);
+ }
+
+
+ /**
+ * @param href
+ * @return
+ */
+ protected String useWorkspaceProtocolIfNecessary(String href) {
+ if (href != null && href.startsWith(PLATFORM_RESOURCE_PROTOCOL))
+ return WORKSPACE_PROTOCOL + href.substring(19);
+ return href;
+ }
+
+ private String getCompatibliltyHREF(EObject obj, CompatibilityURIConverter conv) {
+ //Implementation copied from super.getHREF(EObject)
+ InternalEObject o = (InternalEObject) obj;
+
+ URI objectURI = o.eProxyURI();
+ if (objectURI == null) {
+ Resource otherResource = obj.eResource();
+ if (otherResource == null) {
+ objectURI = handleDanglingHREF(obj);
+ if (objectURI == null) {
+ return null;
+ }
+ } else
+ objectURI = otherResource.getURI().appendFragment(otherResource.getURIFragment(obj));
+ }
+
+ //Modified to dispatch back to URI Converter
+ if (!objectURI.isRelative()) {
+ objectURI = makeRelative(objectURI, conv);
+ }
+ return objectURI.toString();
+ }
+
+ protected URI makeRelative(URI objectURI, CompatibilityURIConverter conv) {
+ String fragment = objectURI.fragment();
+ objectURI = objectURI.trimFragment();
+ URI relative = (URI) getCachedRelativeURIs().get(objectURI);
+ if (relative == null) {
+ relative = conv.deNormalize(objectURI);
+ if (relative.isRelative())
+ cachedRelativeURIs.put(objectURI, relative);
+ }
+ return relative.appendFragment(fragment);
+ }
+
+ protected URIConverter getURIConverter() {
+ ResourceSet set = getResource().getResourceSet();
+ if (set != null)
+ return set.getURIConverter();
+ return null;
+ }
+
+ protected Map getCachedRelativeURIs() {
+ if (cachedRelativeURIs == null)
+ cachedRelativeURIs = new HashMap();
+ return cachedRelativeURIs;
+ }
+
+ /**
+ * @see org.eclipse.emf.ecore.xmi.impl.XMLHelperImpl#getID(EObject)
+ */
+ public String getID(EObject obj) {
+ if (getCompatibilityResource().usesDefaultFormat())
+ return super.getID(obj);
+ return IDUtil.getOrAssignID(obj, resource);
+ }
+
+ public String[] getNSInfo(EPackage pkg) {
+ String prefix = getMappedPrefix(pkg);
+ if (prefix == null)
+ return new String[]{pkg.getNsPrefix(), pkg.getNsURI()};
+ return new String[]{prefix, prefix + ".xmi"}; //$NON-NLS-1$
+ }
+
+ protected String getMappedPrefix(EPackage pkg) {
+ String nsURI = pkg.getNsURI();
+ if (usingMaps || !getCompatibilityResource().usesDefaultFormat())
+ return (String) packageURIsToPrefixes.get(nsURI);
+ return null;
+ }
+
+ protected String getMappedPrefixOrDefault(EPackage pkg) {
+ String prefix = getMappedPrefix(pkg);
+ return prefix == null ? pkg.getNsPrefix() : prefix;
+ }
+
+
+ /**
+ * Returns the packageURIsToPrefixes.
+ *
+ * @return Map
+ */
+ public Map getPackageURIsToPrefixes() {
+ return packageURIsToPrefixes;
+ }
+
+ /**
+ * Sets the packageURIsToPrefixes.
+ *
+ * @param packageURIsToPrefixes
+ * The packageURIsToPrefixes to set
+ */
+ public void setPackageURIsToPrefixes(Map packageURIsToPrefixes) {
+ this.packageURIsToPrefixes = packageURIsToPrefixes;
+ }
+
+ public String getQName(EClass c) {
+ String name = getName(c);
+
+ if (xmlMap != null) {
+ XMLResource.XMLInfo clsInfo = xmlMap.getInfo(c);
+
+ if (clsInfo != null) {
+ String targetNamespace = clsInfo.getTargetNamespace();
+ return getQName(targetNamespace, name);
+ }
+ }
+
+ EPackage p = c.getEPackage();
+ packages.put(p, null);
+
+ if (p.getNsPrefix().equals("")) //$NON-NLS-1$
+ return name;
+
+ //Modified from superclass
+ //return p.getNsPrefix() + ":" + name;
+ return getMappedPrefixOrDefault(p) + ":" + name; //$NON-NLS-1$
+ }
+
+ /**
+ * @see org.eclipse.emf.ecore.xmi.impl.XMLHelperImpl#setValue(EObject, EStructuralFeature,
+ * Object, int)
+ */
+ public void setValue(EObject object, EStructuralFeature feature, Object value, int position) {
+ if (feature == NULL_FEATURE)
+ return;
+ if (!feature.isTransient()) {
+ if (value == null && feature.getEType().getInstanceClass() != null && feature.getEType().getInstanceClass().isPrimitive())
+ //For compatibility with MOF5 where types like Integer might have been set
+ //and serialized as "xsi:nil"
+ return;
+
+ super.setValue(object, feature, value, position);
+ }
+ }
+
+
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.eclipse.emf.ecore.xmi.XMLHelper#getFeature(org.eclipse.emf.ecore.EClass,
+ * java.lang.String, java.lang.String, boolean)
+ */
+ public EStructuralFeature getFeature(EClass eClass, String namespaceURI, String name, boolean isElement) {
+ if (UnsupportedFeature.isUnsupported(eClass, name))
+ return NULL_FEATURE;
+ return super.getFeature(eClass, namespaceURI, name, isElement);
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.eclipse.emf.ecore.xmi.XMLHelper#getFeatureKind(org.eclipse.emf.ecore.EStructuralFeature)
+ */
+ public int getFeatureKind(EStructuralFeature feature) {
+ if (feature == NULL_FEATURE)
+ return XMLHelper.DATATYPE_SINGLE;
+ return super.getFeatureKind(feature);
+ }
+}
diff --git a/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/resource/MultiObjectTranslator.java b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/resource/MultiObjectTranslator.java
new file mode 100644
index 0000000..91ed5bc
--- /dev/null
+++ b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/resource/MultiObjectTranslator.java
@@ -0,0 +1,93 @@
+/*******************************************************************************
+ * Copyright (c) 2003, 2004 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+/*
+ * Created on Mar 31, 2003
+ *
+ */
+package org.eclipse.wst.common.internal.emf.resource;
+
+import org.eclipse.emf.ecore.EObject;
+import org.eclipse.emf.ecore.EStructuralFeature;
+import org.w3c.dom.Node;
+
+/**
+ * @author schacher
+ */
+public abstract class MultiObjectTranslator extends Translator {
+ private static final Translator[] EMPTY_TRANSLATORS = new Translator[]{};
+
+ /**
+ * @param domNameAndPath
+ * @param aFeature
+ * @param style
+ */
+ public MultiObjectTranslator(String domNameAndPath, EStructuralFeature aFeature) {
+ super(domNameAndPath, aFeature);
+ }
+
+ public abstract Translator getDelegateFor(EObject o);
+
+ public abstract Translator getDelegateFor(String domName, String readAheadName);
+
+
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see com.ibm.etools.emf2xml.impl.Translator#createEMFObject(java.lang.String,
+ * java.lang.String)
+ */
+ public EObject createEMFObject(String nodeName, String readAheadName) {
+ return getDelegateFor(nodeName, readAheadName).createEMFObject(nodeName, readAheadName);
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see com.ibm.etools.emf2xml.impl.Translator#getChildren(java.lang.Object)
+ */
+ public Translator[] getChildren(Object o, int version) {
+ if (o == null)
+ return EMPTY_TRANSLATORS;
+ return getDelegateFor((EObject) o).getChildren(o, version);
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see com.ibm.etools.emf2xml.impl.Translator#getDOMName(java.lang.Object)
+ */
+ public String getDOMName(Object value) {
+ return getDelegateFor((EObject) value).getDOMName(value);
+ }
+
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see com.ibm.etools.emf2xml.impl.Translator#isManagedByParent()
+ */
+ public boolean isManagedByParent() {
+ return false;
+ }
+
+ public boolean shouldIndentEndTag(Node node) {
+ if (node.getNodeName().equals(getDOMPath())) {
+ return super.shouldIndentEndTag(node);
+ }
+ Translator delegate = getDelegateFor(node.getNodeName(), null);
+ if (delegate != null) {
+ return delegate.shouldIndentEndTag(node);
+ }
+ return super.shouldIndentEndTag(node);
+ }
+
+}
\ No newline at end of file
diff --git a/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/resource/NamespaceTranslator.java b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/resource/NamespaceTranslator.java
new file mode 100644
index 0000000..3c23ed4
--- /dev/null
+++ b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/resource/NamespaceTranslator.java
@@ -0,0 +1,112 @@
+/*******************************************************************************
+ * Copyright (c) 2003, 2005 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+/*
+ * Created on Aug 14, 2003
+ *
+ */
+package org.eclipse.wst.common.internal.emf.resource;
+
+import org.eclipse.emf.ecore.EObject;
+import org.eclipse.wst.common.internal.emf.utilities.Namespace;
+import org.eclipse.wst.common.internal.emf.utilities.NamespaceAdapter;
+
+
+/**
+ * @author schacher
+ */
+public class NamespaceTranslator extends Translator {
+
+ protected String prefix;
+
+ /**
+ * @param domNameAndPath
+ * @param aFeature
+ */
+ public NamespaceTranslator(String domName) {
+ super(domName, NamespaceAdapter.NOTIFICATION_FEATURE, DOM_ATTRIBUTE);
+ initPrefix();
+ }
+
+ private void initPrefix() {
+ String dName = getDOMName(null);
+ prefix = dName.substring(DefaultTranslatorFactory.XMLNS.length());
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see com.ibm.etools.emf2xml.impl.Translator#setMOFValue(org.eclipse.emf.ecore.EObject,
+ * java.lang.Object)
+ */
+ public void setMOFValue(EObject emfObject, Object value) {
+ NamespaceAdapter.addNamespace(prefix, (String) value, emfObject);
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see com.ibm.etools.emf2xml.impl.Translator#isSetMOFValue(org.eclipse.emf.ecore.EObject)
+ */
+ public boolean isSetMOFValue(EObject emfObject) {
+ return getMOFValue(emfObject) != null;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see com.ibm.etools.emf2xml.impl.Translator#getMOFValue(org.eclipse.emf.ecore.EObject)
+ */
+ public Object getMOFValue(EObject mofObject) {
+ return NamespaceAdapter.getNamespaceURIAtThisLevel(prefix, mofObject);
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see com.ibm.etools.emf2xml.impl.Translator#unSetMOFValue(org.eclipse.emf.ecore.EObject)
+ */
+ public void unSetMOFValue(EObject emfObject) {
+ NamespaceAdapter.removeNamespace(prefix, emfObject);
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see com.ibm.etools.emf2xml.impl.Translator#featureExists(org.eclipse.emf.ecore.EObject)
+ */
+ public boolean featureExists(EObject emfObject) {
+ return true;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see com.ibm.etools.emf2xml.impl.Translator#isDataType()
+ */
+ public boolean isDataType() {
+ return true;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see com.ibm.etools.emf2xml.impl.Translator#isMapFor(java.lang.Object, java.lang.Object,
+ * java.lang.Object)
+ */
+ public boolean isMapFor(Object aFeature, Object oldValue, Object newValue) {
+ if (aFeature == feature) {
+ Namespace namespace = (Namespace) (oldValue == null ? newValue : oldValue);
+ if (namespace != null)
+ return prefix.equals(namespace.getPrefix());
+ }
+ return false;
+ }
+}
diff --git a/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/resource/ObjectTranslatorFilter.java b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/resource/ObjectTranslatorFilter.java
new file mode 100644
index 0000000..918b9ce
--- /dev/null
+++ b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/resource/ObjectTranslatorFilter.java
@@ -0,0 +1,35 @@
+/***************************************************************************************************
+ * Copyright (c) 2003, 2004 IBM Corporation 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: IBM Corporation - initial API and implementation
+ **************************************************************************************************/
+/*
+ * Created on Sep 21, 2003
+ *
+ */
+package org.eclipse.wst.common.internal.emf.resource;
+
+
+public final class ObjectTranslatorFilter extends TranslatorFilter {
+
+ public ObjectTranslatorFilter() {
+ super(null, -1);
+ }
+
+ public ObjectTranslatorFilter(Translator trans, int version) {
+ super(trans, version);
+ }
+
+ public final int scanNextTranslator(Translator[] children, int start) {
+ int found = start + 1;
+ for (; found < children.length; ++found) {
+ if (!children[found].isDOMAttribute())
+ break;
+ }
+ found = (found < children.length) ? found : -1;
+ return found;
+ }
+}
\ No newline at end of file
diff --git a/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/resource/ReadAheadHelper.java b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/resource/ReadAheadHelper.java
new file mode 100644
index 0000000..a7d1a23
--- /dev/null
+++ b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/resource/ReadAheadHelper.java
@@ -0,0 +1,92 @@
+/*******************************************************************************
+ * Copyright (c) 2003, 2004 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+/*
+ * Created on Apr 2, 2003
+ *
+ */
+package org.eclipse.wst.common.internal.emf.resource;
+
+/**
+ * @author schacher
+ */
+public class ReadAheadHelper {
+
+ protected String parentDOMName;
+ protected String[] values;
+ protected String childDOMName;
+
+ public ReadAheadHelper(String parentDOMName, String[] values, String childDOMName) {
+ super();
+ this.parentDOMName = parentDOMName;
+ this.values = values;
+ this.childDOMName = childDOMName;
+ }
+
+ /**
+ * @return
+ */
+ public String getChildDOMName() {
+ return childDOMName;
+ }
+
+ /**
+ * @return
+ */
+ public String getParentDOMName() {
+ return parentDOMName;
+ }
+
+ /**
+ * @return
+ */
+ public String[] getValues() {
+ return values;
+ }
+
+ /**
+ * @param string
+ */
+ public void setChildDOMName(String string) {
+ childDOMName = string;
+ }
+
+ /**
+ * @param string
+ */
+ public void setParentDOMName(String string) {
+ parentDOMName = string;
+ }
+
+ /**
+ * @param strings
+ */
+ public void setValues(String[] strings) {
+ values = strings;
+ }
+
+
+ public boolean nodeValueIsReadAheadName(String nodeName) {
+
+ return (childDOMName != null) ? childDOMName.equals(nodeName) : false;
+ }
+
+ public boolean nodeNameIsReadAheadName(String nodeName) {
+ boolean result = false;
+ for (int i = 0; i < values.length; i++) {
+ if (nodeName.equals(values[i])) {
+ result = true;
+ break;
+ }
+ }
+ return result;
+ }
+
+}
\ No newline at end of file
diff --git a/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/resource/ReferencedResource.java b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/resource/ReferencedResource.java
new file mode 100644
index 0000000..45faf2b
--- /dev/null
+++ b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/resource/ReferencedResource.java
@@ -0,0 +1,130 @@
+/*******************************************************************************
+ * Copyright (c) 2003, 2006 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.wst.common.internal.emf.resource;
+
+
+
+import org.eclipse.emf.ecore.resource.Resource;
+
+public interface ReferencedResource extends Resource, CompatibilityXMIResource {
+ //TODO - rename packaged
+
+ public static final String DELETED_ERROR_MSG = "This resource has been deleted and can no longer be used."; //$NON-NLS-1$
+
+ public static final int RESOURCE_WAS_SAVED = 601;
+
+ /**
+ * A flag used to indicate a ReferencedResource is about
+ * to save.
+ */
+ public static final int RESOURCE_ABOUT_TO_SAVE = 602;
+
+ /**
+ * A flag used to indicate a ReferencedResource has failed
+ * to save.
+ */
+ public static final int RESOURCE_SAVE_FAILED = 603;
+
+ /**
+ * Access this resource for read only. This call increments the use read count of this resource.
+ * Clients should call this method before they use the resource. They should call
+ * releaseFromRead() after they are done modifying this resource.
+ */
+ void accessForRead();
+
+ /**
+ * Access this resource for write only. This call increments the use write count of this
+ * resource. Clients should call this method before they modify the resource. They should call
+ * releaseFromWrite() after they are done modifying this resource.
+ */
+ void accessForWrite();
+
+ /**
+ * Return true if this resource has just been loaded and not yet accessed for read or write.
+ */
+ boolean isNew();
+
+ /**
+ * Return true if this resource does not have any write references.
+ */
+ boolean isReadOnly();
+
+ /**
+ * Return true if this resource is shared for read or write by more than one accessor.
+ */
+ boolean isShared();
+
+ /**
+ * Return true if this resource is shared for write by more than one accessor.
+ */
+ boolean isSharedForWrite();
+
+ /**
+ * Release read the access to this resource. This call decrements the use count of this resource
+ * and will remove the resource from its resource set if the use count goes to 0. Clients should
+ * call this method when they are done accessing the resource and only after they have called
+ * accessForRead() to obtain access.
+ */
+ void releaseFromRead();
+
+ /**
+ * Release write the access to this resource. This call decrements the write count of this
+ * resource and will remove the resource from its resource set if the use count goes to 0.
+ * Clients should call this method when they are done accessing the resource and only after they
+ * have called accessForWrite() to obtain access.
+ */
+ void releaseFromWrite();
+
+ /**
+ * Saves this resource only if the write count is equal to 1.
+ */
+ void saveIfNecessary() throws Exception;
+
+ /**
+ * Return true if this resource is dirty and is not shared for write.
+ */
+ boolean needsToSave();
+
+
+
+ /**
+ * Set whether we should allow a refresh to take place even when this resource is dirty.
+ *
+ * @param b
+ */
+ void setForceRefresh(boolean b);
+
+ /**
+ * Return whether we should allow a refresh to take place even when this resource is dirty.
+ */
+ boolean shouldForceRefresh();
+
+ boolean wasReverted();
+
+ /**
+ * Returns the number of open read accesses on this resource
+ *
+ * @return
+ */
+ int getReadCount();
+
+ /**
+ * Returns the number of open write accesses on this resource
+ *
+ * @return
+ */
+ int getWriteCount();
+
+ /**
+ * If the resource is no longer being accessed, then remove it from the resource set.
+ */
+ void unloadIfNecessary();
+}
diff --git a/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/resource/ReferencedXMIFactoryImpl.java b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/resource/ReferencedXMIFactoryImpl.java
new file mode 100644
index 0000000..d891c2c
--- /dev/null
+++ b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/resource/ReferencedXMIFactoryImpl.java
@@ -0,0 +1,100 @@
+/***************************************************************************************************
+ * Copyright (c) 2003, 2004 IBM Corporation 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: IBM Corporation - initial API and implementation
+ **************************************************************************************************/
+package org.eclipse.wst.common.internal.emf.resource;
+
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.eclipse.emf.common.notify.AdapterFactory;
+import org.eclipse.emf.common.util.URI;
+import org.eclipse.emf.ecore.resource.Resource;
+import org.eclipse.emf.ecore.resource.impl.ResourceFactoryImpl;
+
+public class ReferencedXMIFactoryImpl extends ResourceFactoryImpl {
+
+ protected static List globalAdapterFactories;
+ protected List localAdapterFactories;
+
+ /**
+ * ReferencedXMIFactoryImpl constructor comment.
+ */
+ public ReferencedXMIFactoryImpl() {
+ super();
+ }
+
+ /**
+ * This is the method that subclasses can override to actually instantiate a new Resource
+ *
+ * @param uri
+ * @return
+ */
+ protected Resource doCreateResource(URI uri) {
+ return new ReferencedXMIResourceImpl(uri);
+ }
+
+ /**
+ * @see org.eclipse.emf.ecore.resource.impl.ResourceFactoryImpl#createResource(URI)
+ */
+ public final Resource createResource(URI uri) {
+ Resource res = doCreateResource(uri);
+ adaptNew(res);
+ return res;
+ }
+
+ protected void adaptNew(Resource res) {
+ if (globalAdapterFactories != null) {
+ for (int i = 0; i < globalAdapterFactories.size(); i++) {
+ AdapterFactory factory = (AdapterFactory) globalAdapterFactories.get(i);
+ factory.adaptAllNew(res);
+ }
+ }
+ if (localAdapterFactories != null) {
+ for (int i = 0; i < localAdapterFactories.size(); i++) {
+ AdapterFactory factory = (AdapterFactory) localAdapterFactories.get(i);
+ factory.adaptAllNew(res);
+ }
+ }
+ }
+
+ /**
+ * The local adapter factory is an adapter factory that you use to only adapt the resource
+ * specific to the ResourceFactory instance.
+ *
+ * @param factory
+ */
+ public void addLocalAdapterFactory(AdapterFactory factory) {
+ if (localAdapterFactories == null)
+ localAdapterFactories = new ArrayList(3);
+ localAdapterFactories.add(factory);
+ }
+
+ public void removeLocalAdapterFactory(AdapterFactory factory) {
+ if (localAdapterFactories != null)
+ localAdapterFactories.remove(factory);
+ }
+
+ /**
+ * A global adapter factory will be used to adapt any resource created by any ResourceFactory
+ * instance.
+ *
+ * @param factory
+ */
+ public static void addGlobalAdapterFactory(AdapterFactory factory) {
+ if (globalAdapterFactories == null)
+ globalAdapterFactories = new ArrayList(3);
+ globalAdapterFactories.add(factory);
+ }
+
+ public static void removeGlobalAdapterFactory(AdapterFactory factory) {
+ if (globalAdapterFactories != null)
+ globalAdapterFactories.remove(factory);
+ }
+}
+
diff --git a/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/resource/ReferencedXMIResourceImpl.java b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/resource/ReferencedXMIResourceImpl.java
new file mode 100644
index 0000000..64b9a5c
--- /dev/null
+++ b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/resource/ReferencedXMIResourceImpl.java
@@ -0,0 +1,416 @@
+/*******************************************************************************
+ * Copyright (c) 2003, 2006 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.wst.common.internal.emf.resource;
+
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+
+import org.eclipse.emf.common.notify.Notification;
+import org.eclipse.emf.common.notify.Notifier;
+import org.eclipse.emf.common.notify.impl.NotificationImpl;
+import org.eclipse.emf.common.util.EList;
+import org.eclipse.emf.common.util.URI;
+import org.eclipse.emf.ecore.EObject;
+import org.eclipse.jem.util.logger.proxy.Logger;
+import org.eclipse.wst.common.internal.emf.utilities.IDUtil;
+
+public class ReferencedXMIResourceImpl extends CompatibilityXMIResourceImpl implements ReferencedResource {
+ //TODO Add toString hook
+ private static final String TO_STRING = "ReferencedXMIResource, file = "; //$NON-NLS-1$
+ private static final String READ_COUNT_TO_STRING = " R= "; //$NON-NLS-1$
+ private static final String WRITE_COUNT_TO_STRING = " W= "; //$NON-NLS-1$
+
+ private int readReferenceCount = 1;
+ private int editReferenceCount = 0;
+ protected boolean isNew = true;
+ protected boolean forceRefresh;
+
+ public static class ESynchronizedAdapterList extends EAdapterList
+ {
+
+ public ESynchronizedAdapterList(Notifier notifier) {
+ super(notifier);
+ }
+
+ public synchronized boolean add(Object object)
+ {
+ return super.add(object);
+ }
+
+ public synchronized void add(int index, Object object)
+ {
+ super.add(index, object);
+ }
+
+ public synchronized boolean addAll(Collection collection)
+ {
+ return super.addAll(collection);
+ }
+
+ public synchronized boolean remove(Object object)
+ {
+ return super.remove(object);
+ }
+
+ public synchronized Object remove(int index)
+ {
+ return super.remove(index);
+ }
+
+ public synchronized boolean removeAll(Collection collection)
+ {
+ return super.removeAll(collection);
+ }
+
+ public synchronized void clear()
+ {
+ super.clear();
+ }
+
+
+ public synchronized Object set(int index, Object object)
+ {
+ return super.set(index, object);
+ }
+
+ public synchronized void move(int newPosition, Object object)
+ {
+ super.move(newPosition, object);
+ }
+
+ public synchronized Object move(int newPosition, int oldPosition)
+ {
+ return super.move(newPosition, oldPosition);
+ }
+ }
+
+
+ /**
+ * ReferencableXMIResourceImpl constructor comment.
+ */
+ public ReferencedXMIResourceImpl() {
+ super();
+ }
+
+ public ReferencedXMIResourceImpl(URI uri) {
+ super(uri);
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.eclipse.wst.common.internal.emf.resource.ReferencedResource#getReadCount()
+ */
+ public int getReadCount() {
+ return readReferenceCount;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.eclipse.wst.common.internal.emf.resource.ReferencedResource#getWriteCount()
+ */
+ public int getWriteCount() {
+ return editReferenceCount;
+ }
+
+
+
+ /*
+ * @see ReferencedResource#accessForRead
+ */
+ public void accessForRead() {
+ checkDeleted();
+ if (!isNew())
+ readReferenceCount++;
+ isNew = false;
+ }
+
+ /*
+ * @see ReferencedResource#accessForWrite
+ */
+ public void accessForWrite() {
+ checkDeleted();
+ editReferenceCount++;
+ if (isNew)
+ releaseFromRead();
+ isNew = false;
+ if (!isTrackingModification())
+ setTrackingModification(true);
+ }
+
+ /*
+ * Check if this resource has been removed and throw an exception if it does not have a
+ * ResourceSet.
+ */
+ protected void checkDeleted() {
+ if (getResourceSet() == null)
+ throw new RuntimeException(DELETED_ERROR_MSG);
+ }
+
+ /**
+ *
+ */
+ public void collectContainedObjects(java.util.List collecting, EObject parentObject) {
+
+ java.util.Iterator children = parentObject.eContents().iterator();
+ while (children.hasNext()) {
+ EObject child = (EObject) children.next();
+ collecting.add(child);
+ collectContainedObjects(collecting, child);
+ }
+ }
+
+ /**
+ *
+ */
+ public void ensureFullIDHydration() {
+ List allRefObjects = new ArrayList();
+ Iterator rootObjects = getContents().iterator();
+ while (rootObjects.hasNext()) {
+ EObject child = (EObject) rootObjects.next();
+ allRefObjects.add(child);
+ collectContainedObjects(allRefObjects, child);
+ }
+
+ Iterator iter = allRefObjects.iterator();
+ while (iter.hasNext())
+ IDUtil.assignID((EObject) iter.next(), this);
+ }
+
+ /**
+ * If the resource is no longer being accessed, then remove it from the resource set.
+ */
+ public void unloadIfNecessary() {
+ if ((getTotalReferenceCount() <= 0) || (editReferenceCount <= 0 && isModified()))
+ unload();
+ }
+
+ /**
+ * Return the number of write accesses to this resource.
+ *
+ * @return int The number of references.
+ */
+ protected int getTotalReferenceCount() {
+ return editReferenceCount + readReferenceCount;
+ }
+
+ /*
+ * @see ReferencedResource#isNew
+ */
+ public boolean isNew() {
+ return isNew;
+ }
+
+ /*
+ * @see ReferencedResource#isReadOnly
+ */
+ public boolean isReadOnly() {
+ return editReferenceCount <= 0;
+ }
+
+ /*
+ * @see ReferencedResource#isShared
+ */
+ public boolean isShared() {
+ return getTotalReferenceCount() > 1;
+ }
+
+ /*
+ * @see ReferencedResource#isSharedForWrite
+ */
+ public boolean isSharedForWrite() {
+ return editReferenceCount > 1;
+ }
+
+ /**
+ * @see ReferencedResource#preDelete
+ */
+ public void preDelete() {
+ }
+
+ /*
+ * @see ReferencedResource#releaseFromRead
+ */
+ public void releaseFromRead() {
+ readReferenceCount--;
+ if (readReferenceCount < 0)
+ throw new RuntimeException("Read reference count error: " + this.toString()); //$NON-NLS-1$
+ unloadIfNecessary();
+ }
+
+ /*
+ * @see ReferencedResource#releaseFromWrite
+ */
+ public void releaseFromWrite() {
+ editReferenceCount--;
+ if (editReferenceCount < 0)
+ throw new RuntimeException("Write reference count error: " + this.toString()); //$NON-NLS-1$
+ unloadIfNecessary();
+ }
+
+ /*
+ * @see ReferencedResource#saveIfNecessary
+ */
+ public void saveIfNecessary() throws Exception {
+ if (!isSharedForWrite()) // caller is the only referencer
+ save(Collections.EMPTY_MAP);
+ }
+
+ public String toString() {
+ return TO_STRING + getURI().toString() + READ_COUNT_TO_STRING + new Integer(readReferenceCount) + WRITE_COUNT_TO_STRING + new Integer(editReferenceCount);
+ }
+
+ /*
+ * @see ReferencedResource#needsToSave()
+ */
+ public boolean needsToSave() {
+ return isModified() && !isSharedForWrite();
+ }
+
+
+ /**
+ * @see ReferencedResource#setForceRefresh(boolean)
+ */
+ public void setForceRefresh(boolean b) {
+ forceRefresh = b;
+ }
+
+ /**
+ * @see ReferencedResource#shouldForceRefresh()
+ */
+ public boolean shouldForceRefresh() {
+ return forceRefresh;
+ }
+
+ protected void basicDoLoad(InputStream arg0, Map arg1) throws IOException {
+ boolean isTrackingMods = isTrackingModification();
+ try {
+ if (isTrackingMods)
+ setTrackingModification(false);
+ super.basicDoLoad(arg0, arg1);
+ } finally {
+ if (isTrackingMods)
+ setTrackingModification(true);
+ }
+ }
+
+ /**
+ * @see org.eclipse.emf.ecore.xmi.impl.XMLResourceImpl#doUnload()
+ */
+ protected void doUnload() {
+
+ try {
+ // Using load lock to ensure no other threads will attempt a load during the unload process
+ addSynchronizationLoadingAdapter();
+ waitForResourceToLoadIfNecessary();
+
+ if (isTrackingModification() && editReferenceCount < 1) //do not turn off modification if
+ // we still have a write count
+ setTrackingModification(false);
+ super.doUnload();
+ setForceRefresh(false);
+ setModified(false); //dcb - this is required to ensure that resources without files are
+ // marked as not modified.
+ if (readReferenceCount == 0 && editReferenceCount == 0 && getResourceSet() != null) {
+ getResourceSet().getResources().remove(this);
+ }
+
+ } finally {
+ //Removing the load lock
+ removeLoadingSynchronizationAdapter();
+ }
+
+ }
+
+
+ /**
+ * The resource has been unloaded, and there are no references. Treat the resource like a new
+ * Resource
+ */
+ // never used
+// private void resetAsNew() {
+// readReferenceCount = 1;
+// isNew = true;
+// }
+
+ /**
+ * @see org.eclipse.emf.ecore.resource.Resource#save(Object)
+ */
+ public void save(Map options) throws IOException {
+ notifyAboutToSave();
+ try {
+ super.save(options);
+ } catch (Exception e) {
+ notifySaveFailed();
+ if (e instanceof IOException)
+ throw (IOException) e;
+ else
+ Logger.getLogger().write(e);
+ }
+ notifySaved();
+ }
+
+ protected void notifySaved() {
+ notifySaveEvent(RESOURCE_WAS_SAVED);
+ }
+
+ protected void notifyAboutToSave() {
+ notifySaveEvent(RESOURCE_ABOUT_TO_SAVE);
+ }
+
+ protected void notifySaveFailed() {
+ notifySaveEvent(RESOURCE_SAVE_FAILED);
+ }
+
+ private void notifySaveEvent(int eventType) {
+ if (eNotificationRequired()) {
+ Notification notification =
+ new NotificationImpl(eventType, this, this)
+ {
+ public Object getNotifier()
+ {
+ return ReferencedXMIResourceImpl.this;
+ }
+ public int getFeatureID(Class expectedClass)
+ {
+ return eventType;
+ }
+ };
+ eNotify(notification);
+ }
+ }
+
+ /**
+ * @see com.ibm.etools.emf.workbench.ReferencedResource#wasReverted()
+ */
+ public boolean wasReverted() {
+ return false;
+ }
+
+ public EList eAdapters()
+ {
+ if (eAdapters == null)
+ {
+ eAdapters = new ESynchronizedAdapterList(this);
+ }
+ return eAdapters;
+ }
+
+
+}
diff --git a/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/resource/Renderer.java b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/resource/Renderer.java
new file mode 100644
index 0000000..4a9c37d
--- /dev/null
+++ b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/resource/Renderer.java
@@ -0,0 +1,62 @@
+/*******************************************************************************
+ * Copyright (c) 2003, 2005 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.wst.common.internal.emf.resource;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.util.Map;
+
+/**
+ * Interface that defines the api for rendering an EMF object to XML and vice versa
+ */
+public interface Renderer {
+
+ public static final String JAXP_SCHEMA_LANGUAGE = "http://java.sun.com/xml/jaxp/properties/schemaLanguage"; //$NON-NLS-1$
+
+ public static final String W3C_XML_SCHEMA = "http://www.w3.org/2001/XMLSchema"; //$NON-NLS-1$
+
+ void setResource(TranslatorResource aResource);
+
+ TranslatorResource getResource();
+
+ void doLoad(InputStream in, Map options) throws IOException;
+
+ void doSave(OutputStream outputStream, Map options) throws IOException;
+
+ boolean useStreamsForIO();
+
+ void prepareToAddContents();
+
+ int getVersionID();
+
+ boolean isModified();
+
+ void accessForWrite();
+
+ void accessForRead();
+
+ void releaseFromRead();
+
+ void releaseFromWrite();
+
+ void preDelete();
+
+ void preUnload();
+
+ boolean isShared();
+
+ boolean isSharedForWrite();
+
+ void setBatchMode(boolean isBatch);
+
+ boolean isBatchMode();
+}
diff --git a/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/resource/RendererFactory.java b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/resource/RendererFactory.java
new file mode 100644
index 0000000..19c133c
--- /dev/null
+++ b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/resource/RendererFactory.java
@@ -0,0 +1,135 @@
+/***************************************************************************************************
+ * Copyright (c) 2003, 2004 IBM Corporation 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: IBM Corporation - initial API and implementation
+ **************************************************************************************************/
+package org.eclipse.wst.common.internal.emf.resource;
+
+import java.util.Iterator;
+import java.util.Map;
+import java.util.WeakHashMap;
+
+
+public abstract class RendererFactory {
+
+ public abstract Renderer createRenderer();
+
+ private static RendererFactory defaultRendererFactory;
+
+ private static RendererFactoryDefaultHandler defaultHandler;
+
+ private boolean validating = true;
+
+ /**
+ * Interested parties can use the
+ */
+ public final static Notifier NotificationEngine = Notifier.INSTANCE;
+
+ /**
+ * @return
+ */
+ public static RendererFactory getDefaultRendererFactory() {
+ if (defaultRendererFactory == null)
+ defaultRendererFactory = getDefaultHandler().getDefaultRendererFactory();
+ return defaultRendererFactory;
+ }
+
+ /**
+ * @param factory
+ */
+ public static void setDefaultRendererFactory(RendererFactory factory) {
+
+ //System.out.println("\n\n***Setting factory: " + factory);
+ NotificationEngine.notifyListeners(factory);
+ defaultRendererFactory = factory;
+ }
+
+ public String toString() {
+ return "RendererFactory instance: " + getClass().getName(); //$NON-NLS-1$
+ }
+
+ public static class Notifier {
+
+ private static final Notifier INSTANCE = new Notifier();
+
+ // use a WeakHashMap for a weak HashSet
+ private final Map resourceFactoryListeners = new WeakHashMap();
+
+ private Notifier() {
+ }
+
+ public void notifyListeners(RendererFactory rendererFactory) {
+
+ final int length = resourceFactoryListeners.size();
+ //System.out.println("Notifying " + length + " listeners");
+
+ if (length > 0) {
+ /*
+ * Since the renderer factories are singletons, this reference check should always
+ * work
+ */
+ if (rendererFactory != RendererFactory.getDefaultRendererFactory()) {
+ synchronized (resourceFactoryListeners) {
+ for (Iterator i = resourceFactoryListeners.keySet().iterator(); i.hasNext();) {
+ Listener listener = (Listener) i.next();
+ //System.out.println("Notifying Listener: " + listener);
+ listener.updateRendererFactory(rendererFactory);
+ }
+ }
+ }
+ }
+ }
+
+ public void addListener(Listener l) {
+ //System.out.println("Adding listener: " + l);
+ synchronized (resourceFactoryListeners) {
+ resourceFactoryListeners.put(l, null);
+ }
+ }
+
+ public void removeListener(Listener listenerToRemove) {
+ synchronized (resourceFactoryListeners) {
+ resourceFactoryListeners.remove(listenerToRemove);
+ }
+ }
+
+ }
+
+ public interface Listener {
+ void updateRendererFactory(RendererFactory newRendererFactory);
+ }
+
+ /**
+ * @return
+ */
+ public boolean isValidating() {
+ return validating;
+ }
+
+ /**
+ * @param b
+ */
+ public void setValidating(boolean b) {
+ validating = b;
+ }
+
+ /**
+ * @return
+ */
+ public static RendererFactoryDefaultHandler getDefaultHandler() {
+ if (defaultHandler == null)
+ defaultHandler = EMF2DOMRendererFactoryDefaultHandler.INSTANCE;
+ return defaultHandler;
+ }
+
+ /**
+ * @param handler
+ */
+ public static void setDefaultHandler(RendererFactoryDefaultHandler handler) {
+ defaultHandler = handler;
+ }
+
+}
\ No newline at end of file
diff --git a/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/resource/RendererFactoryDefaultHandler.java b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/resource/RendererFactoryDefaultHandler.java
new file mode 100644
index 0000000..575df4f
--- /dev/null
+++ b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/resource/RendererFactoryDefaultHandler.java
@@ -0,0 +1,30 @@
+/*******************************************************************************
+ * Copyright (c) 2003, 2004 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+/*
+ * Created on Dec 1, 2003
+ *
+ * To change the template for this generated file go to
+ * Window>Preferences>Java>Code Generation>Code and Comments
+ */
+package org.eclipse.wst.common.internal.emf.resource;
+
+
+/**
+ * @author schacher
+ *
+ * To change the template for this generated type comment go to
+ * Window>Preferences>Java>Code Generation>Code and Comments
+ */
+public interface RendererFactoryDefaultHandler {
+
+ RendererFactory getDefaultRendererFactory();
+
+}
\ No newline at end of file
diff --git a/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/resource/ResourceFactoryDescriptor.java b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/resource/ResourceFactoryDescriptor.java
new file mode 100644
index 0000000..10850e9
--- /dev/null
+++ b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/resource/ResourceFactoryDescriptor.java
@@ -0,0 +1,86 @@
+/*******************************************************************************
+ * Copyright (c) 2003, 2007 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.wst.common.internal.emf.resource;
+
+import org.eclipse.core.runtime.content.IContentType;
+import org.eclipse.emf.common.util.URI;
+import org.eclipse.emf.ecore.resource.Resource;
+
+public abstract class ResourceFactoryDescriptor {
+
+
+ /**
+ * Returns true if the current descriptor is applicable to the given fileURI.
+ *
+ * @param fileURI The URI of the file to be loaded
+ * @return True if the current descriptor declares a resource factory applicable to the given URI.
+ */
+ public abstract boolean isEnabledFor(URI fileURI);
+
+ /**
+ * The contentType is one optional way that a ResourceFactory
+ * might apply to a URI. Clients should call {@link isEnabledFor}
+ * instead of comparing the content Types when searching for an
+ * applicable descriptor from a set.
+ *
+ * <p><b>Subclasses may return null.(optional)</b></p>
+ *
+ * @return The content type that this descriptor is applicable to.
+ */
+ public IContentType getContentType(){
+ return null;
+ }
+
+ /**
+ * In the case where more than one factory is defined for the same fileName,
+ * and creation is passed a uri only a default factory is needed
+ *
+ *
+ * @return The boolean describing the default factory
+ */
+ public boolean isDefault(){
+ return true;
+ }
+
+ /**
+ * The short segment is one possible way that a ResourceFactory
+ * might apply to a URI. Clients should call {@link isEnabledFor}
+ * instead of comparing the short segments when searching for an
+ * applicable descriptor from a set.
+ *
+ * <p><b>Subclasses may NOT return null unless they also override
+ * {@link #hashCode()} and {@link #equals(Object)}.</b></p>
+ *
+ * @return The short segment that this descriptor is applicable to.
+ */
+ public abstract String getShortSegment();
+
+
+ /**
+ * The correct instance of Resource.Factory. The instance returned
+ * may or may not be unique, so if you require the same instance
+ * for each call, you should cache the value returned the first
+ * time from this method.
+ *
+ * @return An instance of Resource.Factory.
+ */
+ public abstract Resource.Factory createFactory();
+
+ public int hashCode() {
+ return getShortSegment().hashCode();
+ }
+
+ public boolean equals(Object o) {
+ if(o instanceof ResourceFactoryDescriptor)
+ return getShortSegment().equals(((ResourceFactoryDescriptor)o).getShortSegment());
+ return false;
+ }
+}
diff --git a/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/resource/RootTranslator.java b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/resource/RootTranslator.java
new file mode 100644
index 0000000..f5640e9
--- /dev/null
+++ b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/resource/RootTranslator.java
@@ -0,0 +1,65 @@
+/*******************************************************************************
+ * Copyright (c) 2003, 2006 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.wst.common.internal.emf.resource;
+
+import org.eclipse.emf.common.notify.Notifier;
+import org.eclipse.emf.ecore.EClass;
+import org.eclipse.emf.ecore.EObject;
+import org.eclipse.emf.ecore.resource.Resource;
+
+public class RootTranslator extends Translator {
+
+ /**
+ * Constructor for RootTranslator.
+ *
+ * @param domNameAndPath
+ * @param eClass
+ */
+ public RootTranslator(String domNameAndPath, EClass eClass) {
+ super(domNameAndPath, eClass);
+ }
+
+ /**
+ * @see com.ibm.etools.emf2xml.impl.Translator#setMOFValue(Notifier, Object, int)
+ */
+ public void setMOFValue(Notifier owner, Object value, int newIndex) {
+ ((Resource) owner).getContents().add(newIndex, (EObject)value);
+ }
+
+ /**
+ * @see com.ibm.etools.emf2xml.impl.Translator#removeMOFValue(Notifier, Object)
+ */
+ public void removeMOFValue(Notifier owner, Object value) {
+ ((Resource) owner).getContents().remove(value);
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see com.ibm.etools.emf2xml.impl.Translator#setMOFValue(org.eclipse.emf.ecore.EObject,
+ * java.lang.Object)
+ */
+ public void setMOFValue(Resource res, Object value) {
+ if (res != null && value != null)
+ res.getContents().add((EObject)value);
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see com.ibm.etools.emf2xml.impl.Translator#isMultiValued()
+ */
+ public boolean isMultiValued() {
+ return true;
+ }
+
+
+}
diff --git a/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/resource/SourceLinkTranslator.java b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/resource/SourceLinkTranslator.java
new file mode 100644
index 0000000..d5d697b
--- /dev/null
+++ b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/resource/SourceLinkTranslator.java
@@ -0,0 +1,72 @@
+/*******************************************************************************
+ * Copyright (c) 2003, 2004 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+/*
+ * Created on Apr 1, 2003
+ *
+ */
+package org.eclipse.wst.common.internal.emf.resource;
+
+import org.eclipse.emf.ecore.EObject;
+import org.eclipse.emf.ecore.EStructuralFeature;
+
+/**
+ * @author schacher
+ */
+public class SourceLinkTranslator extends Translator {
+
+
+ /**
+ * @param domNameAndPath
+ * @param aFeature
+ * @param path
+ */
+ public SourceLinkTranslator(String domNameAndPath, EStructuralFeature aFeature, TranslatorPath path) {
+ super(domNameAndPath, aFeature, path);
+ }
+
+ /**
+ * @param domNameAndPath
+ * @param aFeature
+ * @param path
+ */
+ public SourceLinkTranslator(String domNameAndPath, EStructuralFeature aFeature, TranslatorPath path, int style) {
+ super(domNameAndPath, aFeature, path);
+ fStyle |= style;
+ }
+
+ /**
+ * @param domNameAndPath
+ * @param aFeature
+ * @param style
+ */
+ public SourceLinkTranslator(String domNameAndPath, EStructuralFeature aFeature, int style) {
+ super(domNameAndPath, aFeature, style);
+ }
+
+ public Object convertStringToValue(String strValue, EObject owner) {
+
+ Object value = null;
+ if (strValue != null)
+ // Find the object with the name that matches matchName
+ value = fTranslatorPaths[0].findObject(owner, strValue.trim());
+ if ((fStyle & Translator.STRING_RESULT_OK) != 0)
+ return ((value != null) ? value : strValue);
+ return value;
+ }
+
+ public String convertValueToString(Object value, EObject owner) {
+ TranslatorPath path = fTranslatorPaths[0];
+ Object attrValue = path.getLastMap().getMOFValue((EObject) value);
+ return path.getLastMap().convertValueToString(attrValue, owner);
+ }
+
+
+}
\ No newline at end of file
diff --git a/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/resource/StaticResourceFactoryDescriptor.java b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/resource/StaticResourceFactoryDescriptor.java
new file mode 100644
index 0000000..8caf4ea
--- /dev/null
+++ b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/resource/StaticResourceFactoryDescriptor.java
@@ -0,0 +1,52 @@
+/*******************************************************************************
+ * Copyright (c) 2005, 2006 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.wst.common.internal.emf.resource;
+
+import org.eclipse.core.runtime.Assert;
+import org.eclipse.emf.common.util.URI;
+import org.eclipse.emf.ecore.resource.Resource;
+
+/**
+ * Declares a subclass to create Resource.Factory(ies) from an extension.
+ */
+class StaticResourceFactoryDescriptor extends ResourceFactoryDescriptor {
+
+ private final String shortSegment;
+ private final Resource.Factory factory;
+
+ /**
+ *
+ * @param shortSegment A non-null name of the file associated with the given factory
+ * @param factory A non-null Resource.Factory that can load files of the given name
+ */
+ public StaticResourceFactoryDescriptor(String shortSegment, Resource.Factory factory) {
+ Assert.isNotNull(shortSegment);
+ Assert.isNotNull(factory);
+ this.shortSegment = shortSegment;
+ this.factory = factory;
+ }
+
+ public boolean isEnabledFor(URI fileURI) {
+ /* shortSegment must be non-null for the descriptor to be created,
+ * a validation check in init() verifies this requirement */
+ if(fileURI != null && fileURI.lastSegment() != null)
+ return shortSegment.equals(fileURI.lastSegment());
+ return false;
+ }
+
+ public Resource.Factory createFactory() {
+ return factory;
+ }
+
+ public String getShortSegment() {
+ return shortSegment;
+ }
+}
diff --git a/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/resource/Translator.java b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/resource/Translator.java
new file mode 100644
index 0000000..ab28074
--- /dev/null
+++ b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/resource/Translator.java
@@ -0,0 +1,799 @@
+/*******************************************************************************
+ * Copyright (c) 2003, 2006 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.wst.common.internal.emf.resource;
+
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.eclipse.emf.common.notify.Notifier;
+import org.eclipse.emf.ecore.EClass;
+import org.eclipse.emf.ecore.EDataType;
+import org.eclipse.emf.ecore.EObject;
+import org.eclipse.emf.ecore.EReference;
+import org.eclipse.emf.ecore.EStructuralFeature;
+import org.eclipse.emf.ecore.EcorePackage;
+import org.eclipse.emf.ecore.impl.EStructuralFeatureImpl;
+import org.eclipse.emf.ecore.resource.Resource;
+import org.eclipse.wst.common.internal.emf.utilities.ExtendedEcoreUtil;
+import org.eclipse.wst.common.internal.emf.utilities.FeatureValueConverter;
+import org.w3c.dom.Node;
+
+
+public class Translator {
+
+ public final static int NO_STYLE = 0;
+ public final static int DOM_ATTRIBUTE = 1;
+ public final static int EMPTY_TAG = 1 << 1;
+ public final static int CDATA_CONTENT = 1 << 2;
+ /**
+ * Style bit that indicates that the end tag should NOT be indented; by default it is.
+ */
+ public final static int END_TAG_NO_INDENT = 1 << 3;
+ /**
+ * Style bit that indicates that booleans should NOT be converted as "True" and "False"; default
+ * is that they are
+ */
+ public final static int BOOLEAN_LOWERCASE = 1 << 4;
+ /**
+ * Style bit that indicates an enum value contains hyphens If this is true, then internally the
+ * hyphens are replaced with underscores
+ */
+ public final static int ENUM_FEATURE_WITH_HYPHENS = 1 << 5;
+
+ protected final static int OBJECT_MAP = 1 << 6;
+ protected final static int BOOLEAN_FEATURE = 1 << 7;
+
+ protected final static int SHARED_REFERENCE = 1 << 8;
+
+ /**
+ * Indicates that the feature may be significant even if it is empty
+ */
+ public final static int EMPTY_CONTENT_IS_SIGNIFICANT = 1 << 9;
+
+ /**
+ * Used to indicate that feature is associated with a comment node
+ */
+ protected final static int COMMENT_FEATURE = 1 << 10;
+
+ /**
+ * If the value is null, then an eUnset() will be invoked on the feature
+ */
+ public final static int UNSET_IF_NULL = 1 << 11;
+
+ /**
+ * Return the element contents as a String if the feature is unresolveable (Used by the
+ * SourceLinkTranslator)
+ */
+ public final static int STRING_RESULT_OK = 1 << 12;
+
+ protected String[] fDOMNames;
+ protected String fDOMPath = ""; //$NON-NLS-1$
+ protected Map readAheadNames;
+ protected int fStyle = NO_STYLE;
+ protected EStructuralFeature feature;
+ protected TranslatorPath[] fTranslatorPaths;
+ protected EClass emfClass;
+ protected String fNameSpace = ""; //$NON-NLS-1$
+ // added by MDE
+ protected String domNameAndPath = null;
+
+ /**
+ * Indicates if any of the children of this Translator are themselves DependencyTranslators
+ */
+ protected Boolean isDependencyParent;
+ protected EStructuralFeature dependencyFeature;
+ protected static EcorePackage ECORE_PACKAGE = EcorePackage.eINSTANCE;
+
+ // Use this identifier for the DOMName when the attribute
+ // value is to be extracted directly from the text of the node.
+ // This is rare, but occurs in the web.xml in the case of a
+ // WelcomeFile.
+ static final public String TEXT_ATTRIBUTE_VALUE = "$TEXT_ATTRIBUTE_VALUE"; //$NON-NLS-1$
+
+ static final public EStructuralFeature CONTAINER_FEATURE = new ContainerFeature();
+
+ static final public EStructuralFeature ROOT_FEATURE = new RootFeature();
+
+ protected static class ContainerFeature extends EStructuralFeatureImpl {
+ protected ContainerFeature() {
+ super();
+ }
+ }
+
+ protected static class RootFeature extends EStructuralFeatureImpl {
+ protected RootFeature() {
+ super();
+ }
+ }
+
+ public Translator findChild(String tagName, Object target, int versionID) {
+
+ Translator result = null;
+ Translator[] maps = getChildren(target, versionID);
+
+ if (maps != null) {
+ for (int i = 0; i < maps.length; i++) {
+ Translator map = maps[i];
+ if (map.isMapFor(tagName)) {
+ result = map;
+ break;
+ }
+ }
+ }
+ if (result == null) {
+ VariableTranslatorFactory factory = getVariableTranslatorFactory();
+ if (factory != null && factory.accepts(tagName)) {
+ result = factory.create(tagName);
+ }
+ }
+ return result;
+ }
+
+ /**
+ * Utility method to string together arrays of children
+ */
+ public static Object[] concat(Object[] array1, Object[] array2) {
+ Object[] result = (Object[]) java.lang.reflect.Array.newInstance(array1.getClass().getComponentType(), array1.length + array2.length);
+ System.arraycopy(array1, 0, result, 0, array1.length);
+ System.arraycopy(array2, 0, result, array1.length, array2.length);
+ return result;
+ }
+
+ public static Object[] concat(Object[] array1, Object object2) {
+ Object[] newArray = new Object[]{object2};
+ return concat(array1, newArray);
+ }
+
+ public static Translator createParentAndTextAttributeTranslator(String domName, EStructuralFeature parentFeature, EStructuralFeature childFeature) {
+ GenericTranslator parent = new GenericTranslator(domName, parentFeature, END_TAG_NO_INDENT);
+ parent.setChildren(new Translator[]{new Translator(TEXT_ATTRIBUTE_VALUE, childFeature)});
+ return parent;
+ }
+
+ public Translator(String domNameAndPath, EClass eClass) {
+ initializeDOMNameAndPath(domNameAndPath);
+ setEMFClass(eClass);
+ }
+
+ public Translator(String domNameAndPath, EStructuralFeature aFeature) {
+ initializeDOMNameAndPath(domNameAndPath);
+ setFeature(aFeature);
+ }
+
+ public Translator(String domNameAndPath, EStructuralFeature aFeature, EClass eClass) {
+ this(domNameAndPath, aFeature);
+ setEMFClass(eClass);
+ }
+
+ public Translator(String domNameAndPath, EStructuralFeature aFeature, TranslatorPath path) {
+ this(domNameAndPath, aFeature, new TranslatorPath[]{path});
+ }
+
+ public Translator(String domNameAndPath, EStructuralFeature aFeature, TranslatorPath[] paths) {
+ initializeDOMNameAndPath(domNameAndPath);
+ fTranslatorPaths = paths;
+ setFeature(aFeature);
+ }
+
+ public Translator(String domNameAndPath, EStructuralFeature aFeature, int style) {
+ initializeDOMNameAndPath(domNameAndPath);
+ fStyle = style;
+ setFeature(aFeature);
+ }
+
+ public static EcorePackage getEcorePackage() {
+ return EcorePackage.eINSTANCE;
+ }
+
+ public String getDOMName(Object value) {
+ return fDOMNames[0];
+ }
+
+ public String[] getDOMNames() {
+ return fDOMNames;
+ }
+
+ public String getDOMPath() {
+ return fDOMPath;
+ }
+
+ public boolean hasDOMPath() {
+ return fDOMPath != null && fDOMPath.length() != 0;
+ }
+
+ public EStructuralFeature getFeature() {
+ return feature;
+ }
+
+ /**
+ * Parse the DOM names and path out of <domNameAndPath>and set the appropriate fields.
+ */
+ protected void initializeDOMNameAndPath(String domNameAndPathArg) {
+ if (domNameAndPathArg == null)
+ return;
+ int inx = domNameAndPathArg.lastIndexOf('/');
+ if (inx != -1) {
+ fDOMNames = parseDOMNames(domNameAndPathArg.substring(inx + 1));
+ fDOMPath = domNameAndPathArg.substring(0, inx);
+ } else {
+ fDOMNames = parseDOMNames(domNameAndPathArg);
+ fDOMPath = ""; //$NON-NLS-1$
+ }
+ // added by MDE
+ this.domNameAndPath = domNameAndPathArg;
+
+ }
+
+ /**
+ * Indicates whether the node should be written as an empty tag; eg, <distributable/>
+ */
+ public boolean isCDATAContent() {
+ return (fStyle & CDATA_CONTENT) != 0;
+ }
+
+ /**
+ * Indicates whether the DOMName represents a sub element name or an attribute name
+ *
+ * @return boolean True if the DOMName is an attribute name.
+ */
+ public boolean isDOMAttribute() {
+ return (fStyle & DOM_ATTRIBUTE) != 0;
+ }
+
+ /**
+ * Indicates whether the node should be written as an empty tag; eg, <distributable/>
+ */
+ public boolean isEmptyTag() {
+ return (fStyle & EMPTY_TAG) != 0;
+ }
+
+ public boolean isBooleanUppercase() {
+ return (fStyle & BOOLEAN_FEATURE) != 0 && (fStyle & BOOLEAN_LOWERCASE) == 0;
+ }
+
+ public boolean isBooleanFeature() {
+ return (fStyle & BOOLEAN_FEATURE) != 0;
+ }
+
+ public boolean shouldIndentEndTag() {
+ return (fStyle & END_TAG_NO_INDENT) == 0;
+ }
+
+ public boolean shouldIndentEndTag(Node node) {
+ return shouldIndentEndTag();
+ }
+
+ public boolean isEmptyContentSignificant() {
+ return ((fStyle & EMPTY_TAG) != 0) || ((fStyle & EMPTY_CONTENT_IS_SIGNIFICANT) != 0);
+ }
+
+ /**
+ * Returns true if this map is to another MOF object (not a primitive)
+ */
+ public boolean isObjectMap() {
+ return (fStyle & OBJECT_MAP) != 0;
+ }
+
+ /**
+ * Returns true if this map is for a shared reference
+ */
+ public boolean isShared() {
+ return (fStyle & SHARED_REFERENCE) != 0;
+ }
+
+ public boolean isEnumWithHyphens() {
+ return (fStyle & ENUM_FEATURE_WITH_HYPHENS) != 0;
+ }
+
+ /**
+ * Indicates whether the map represents a case where the text of the DOMNode represents the
+ * objects one and only attribute value. An example of this case is a <welcome-file>file.txt
+ * </welcome-file>.
+ */
+ public boolean isDOMTextValue() {
+ return fDOMNames[0] == TEXT_ATTRIBUTE_VALUE;
+ }
+
+ /**
+ * Indicates whether the id is the mof attribute that should be set.
+ */
+ public boolean isIDMap() {
+ return false;
+ }
+
+ /**
+ * Indicates whether the id is the mof attribute that should be set.
+ */
+ public boolean isLinkMap() {
+ return fTranslatorPaths != null;
+ }
+
+ public boolean isTargetLinkMap() {
+ return isLinkMap() && !isObjectMap();
+ }
+
+ /**
+ * Return true if this map is the one representing a node with the name <domName>. By default
+ * this method simply compares the DOM name of the map against the <domName>parameter
+ *
+ * @return boolean
+ * @param domName
+ * java.lang.String
+ */
+ public boolean isMapFor(String domName) {
+ if (domName.equals(getDOMPath()))
+ return true;
+ for (int i = 0; i < fDOMNames.length; i++) {
+ if (domName.equals(fDOMNames[i]))
+ return true;
+ }
+ return false;
+ }
+
+ public boolean isMapFor(Object aFeature, Object oldValue, Object newValue) {
+ return feature == aFeature;
+ }
+
+ /**
+ * Indicates whether feature being mapped is a collection.
+ *
+ * @return boolean True if the feature is multi valued.
+ */
+ public boolean isMultiValued() {
+ if (feature != null)
+ return feature.isMany();
+ return false;
+ }
+
+ /**
+ * Parses comma separated names from <domNamesString>. Returns an array containing the names.
+ *
+ * @return java.lang.String[]
+ * @param domNamesString
+ * java.lang.String
+ */
+ protected String[] parseDOMNames(String domNamesString) {
+ int startInx = 0;
+ int inx = domNamesString.indexOf(',');
+ ArrayList results = new ArrayList(1);
+ while (inx != -1) {
+ results.add(domNamesString.substring(startInx, inx));
+ startInx = inx + 1;
+ inx = domNamesString.indexOf(',', startInx);
+ }
+ if (startInx == 0)
+ results.add(domNamesString);
+ else
+ results.add(domNamesString.substring(startInx));
+ return (String[]) results.toArray(new String[results.size()]);
+ }
+
+ public String toString() {
+ StringBuffer sb = new StringBuffer();
+ String cn = getClass().getName();
+ int i = cn.lastIndexOf('.');
+ cn = cn.substring(++i, cn.length());
+ sb.append(cn);
+ sb.append('(');
+ sb.append(fDOMNames[0]);
+ for (int j = 1; j < fDOMNames.length; j++) {
+ sb.append('|');
+ sb.append(fDOMNames[j]);
+ }
+ sb.append(',');
+ sb.append(hashCode());
+ sb.append(')');
+ return sb.toString();
+ }
+
+ /**
+ * Gets the TranslatorPath.
+ *
+ * @return Returns a TranslatorPath
+ */
+ public TranslatorPath[] getTranslatorPaths() {
+ return fTranslatorPaths;
+ }
+
+ /*
+ * @see Object#equals(Object)
+ */
+ public boolean equals(Object object) {
+ if (!(object instanceof Translator))
+ return false;
+ Translator mapInfo = (Translator) object;
+ return fDOMNames.equals(mapInfo.getDOMNames()) && (feature == null && mapInfo.getFeature() == null || feature.equals(mapInfo.getFeature()));
+ }
+
+ /**
+ * Returns the isManagedByParent.
+ *
+ * @return boolean
+ */
+ public boolean isManagedByParent() {
+ return getChildren(null, -1) == null;
+ }
+
+ /*
+ * In the 99% case there is only one node name to be concerned with, but subclasses can override
+ * for the cases where multiple dom names map to one feature
+ */
+ public EObject createEMFObject(String nodeName, String readAheadName) {
+ if (emfClass == null) {
+ if (feature == null)
+ return null;
+ if (isObjectMap())
+ return createEMFObject(feature);
+ }
+ return createEMFObject(emfClass);
+ }
+
+ public static EObject createEMFObject(EStructuralFeature aFeature) {
+ if (aFeature == null)
+ return null;
+
+ return createEMFObject(((EReference) aFeature).getEReferenceType());
+ }
+
+ public static EObject createEMFObject(EClass anEClass) {
+ if (anEClass == null)
+ return null;
+ return anEClass.getEPackage().getEFactoryInstance().create(anEClass);
+ }
+
+ public void setTextValueIfNecessary(String textValue, Notifier owner, int versionId) {
+ Translator textTranslator = this.findChild(Translator.TEXT_ATTRIBUTE_VALUE, owner, versionId);
+ if (textTranslator != null) {
+ Object objectValue = textTranslator.convertStringToValue(textValue, (EObject) owner);
+ textTranslator.setMOFValue(owner, objectValue);
+ }
+ }
+
+ /**
+ * Check to see if feature is valid on a particular mofObject.
+ *
+ * @return boolean Return true if the feature specified exists on the MOF object.
+ * @param emfObject
+ * org.eclipse.emf.ecore.EObject
+ */
+ public boolean featureExists(EObject emfObject) {
+ if (feature == null)
+ return false;
+
+ return emfObject.eClass().getEStructuralFeature(feature.getName()) != null;
+ }
+
+ /**
+ * Translators which do not have a feature should override this method with custom behavior.
+ */
+ public String extractStringValue(EObject emfObject) {
+ if (isEmptyTag() && feature == null)
+ return ""; //Fake it out with a value //$NON-NLS-1$
+ return null;
+ }
+
+ public Object convertStringToValue(String nodeName, String readAheadName, String value, Notifier owner) {
+ Object result = null;
+ try {
+
+ if (!this.isManagedByParent()) {
+ result = createEMFObject(nodeName, readAheadName);
+ } else {
+ result = convertStringToValue(value, (EObject) owner);
+ }
+
+ } catch (ClassCastException cce) {
+
+ }
+ return result;
+ }
+
+ /**
+ * Converts a string value to the appropriate type.
+ *
+ * @return java.lang.Object The converted value
+ * @param strValue
+ * java.lang.String The string to convert.
+ */
+ public Object convertStringToValue(String strValue, EObject owner) {
+ if (feature == null)
+ return strValue;
+ if (strValue != null) {
+ if (isEnumWithHyphens())
+ strValue = strValue.replace('-', '_');
+ if (!isCDATAContent()) {
+ strValue = strValue.trim();
+ }
+ }
+ Object value = FeatureValueConverter.DEFAULT.convertValue(strValue, feature);
+ if (value == null) {
+ if (isEmptyTag() && !isDOMAttribute() && !isDOMTextValue() && isBooleanFeature())
+ return Boolean.TRUE;
+ EObject convertToType = feature.getEType();
+ if (convertToType == null)
+ value = strValue;
+ else if (convertToType.equals(getEcorePackage().getEString())) {
+ value = ""; //$NON-NLS-1$
+ }
+ }
+ return value;
+ }
+
+ /**
+ * Converts a value of a specified type to a string value. Subclasses may override for special
+ * cases where special conversion needs to occur based on the feature and or object type.
+ *
+ * @return String The converted value
+ * @param value
+ * java.lang.Object The object to convert.
+ */
+ public String convertValueToString(Object value, EObject owner) {
+ if (isEmptyTag() || value == null)
+ return null;
+ else if (isEnumWithHyphens())
+ return value.toString().replace('_', '-');
+ else if (isBooleanUppercase())
+ return ((Boolean) value).booleanValue() ? "True" : "False"; //$NON-NLS-1$ //$NON-NLS-2$
+
+ return value.toString();
+ }
+
+ public Translator[] getVariableChildren(Notifier target, int version) {
+ Translator[] results = null;
+ VariableTranslatorFactory factory = getVariableTranslatorFactory();
+ if (factory != null) {
+ List variableTranslators = factory.create(target);
+ if (variableTranslators != null && variableTranslators.size() > 0) {
+ Object[] vtoa = variableTranslators.toArray();
+
+ results = new Translator[vtoa.length];
+ for (int i = 0; i < results.length; i++)
+ results[i] = (Translator) vtoa[i];
+ }
+
+ }
+ if (results == null)
+ results = new Translator[0];
+ return results;
+ }
+
+ /**
+ * Returns null by default; subclasses should override to return specific children
+ */
+ public Translator[] getChildren(Object target, int versionID) {
+ return getChildren();
+ }
+
+ protected Translator[] getChildren() {
+ return null;
+ }
+
+ /**
+ * Return the list of MOF children that currently exist for the values of an attribute.
+ */
+ public List getMOFChildren(EObject mofObject) {
+ if (feature == null)
+ return Collections.EMPTY_LIST;
+ Object value = getMOFValue(mofObject);
+ List result = Collections.EMPTY_LIST;
+ if (isMultiValued())
+ result = (List) value;
+ else if (value != null)
+ result = Collections.singletonList(value);
+ return result;
+ }
+
+ public Object getMOFValue(EObject mofObject) {
+ if (feature == null)
+ return null;
+ return mofObject.eGet(feature);
+ }
+
+ /**
+ * Sets a value of a feature in a mof object.
+ */
+ public void setMOFValue(Notifier owner, Object value, int newIndex) {
+ if (feature != null) {
+ if ((fStyle & UNSET_IF_NULL) != 0 && value == null)
+ ExtendedEcoreUtil.eUnsetOrRemove((EObject) owner, feature, value);
+ else
+ ExtendedEcoreUtil.eSetOrAdd((EObject) owner, feature, value, newIndex);
+ }
+ }
+
+ public void setMOFValue(Notifier owner, Object value) {
+ if (owner instanceof EObject) {
+ setMOFValue((EObject) owner, value);
+ } else if (owner instanceof Resource) {
+ setMOFValue((Resource) owner, value);
+ }
+ }
+
+ public void setMOFValue(EObject emfObject, Object value) {
+ // if (feature != null)
+ // emfObject.eSet(feature, value);
+ setMOFValue(emfObject, value, -1);
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see com.ibm.etools.emf2xml.impl.Translator#setMOFValue(org.eclipse.emf.ecore.EObject,
+ * java.lang.Object)
+ */
+ public void setMOFValue(Resource res, Object value) {
+ if (res != null && value != null)
+ res.getContents().add((EObject)value);
+ }
+
+ public void removeMOFValue(Notifier owner, Object value) {
+ if (feature != null)
+ ExtendedEcoreUtil.eUnsetOrRemove((EObject) owner, feature, value);
+ }
+
+ public boolean isSetMOFValue(EObject emfObject) {
+ boolean isSet = feature != null && emfObject.eIsSet(feature);
+ if (isEmptyTag())
+ return isSet && ((Boolean) emfObject.eGet(feature)).booleanValue();
+ return isSet;
+ }
+
+ public void unSetMOFValue(EObject emfObject) {
+ if (feature != null)
+ emfObject.eUnset(feature);
+ }
+
+ public void clearList(EObject mofObject) {
+ if (feature != null)
+ ((List) mofObject.eGet(feature)).clear();
+ }
+
+ protected void setFeature(EStructuralFeature aFeature) {
+ this.feature = aFeature;
+ if (feature == null)
+ return;
+ //This way an instance check happens only once
+ if (aFeature instanceof EReference) {
+ fStyle |= OBJECT_MAP;
+ if (!((EReference) aFeature).isContainment())
+ fStyle |= SHARED_REFERENCE;
+ }
+
+ if (getEcorePackage().getEBoolean() == feature.getEType())
+ fStyle |= BOOLEAN_FEATURE;
+ }
+
+ protected void setEMFClass(EClass anEClass) {
+ this.emfClass = anEClass;
+ if (anEClass != null)
+ fStyle |= OBJECT_MAP;
+
+ }
+
+ public boolean hasReadAheadNames() {
+ return readAheadNames != null && !readAheadNames.isEmpty();
+ }
+
+ /**
+ * Return the read ahead names, if they are defined, for a given parent node name. This is used
+ * when creation of a specific EMF object is dependent on the value of a child node.
+ */
+ public ReadAheadHelper getReadAheadHelper(String parentName) {
+ if (readAheadNames == null)
+ return null;
+ return (ReadAheadHelper) readAheadNames.get(parentName);
+ }
+
+ public void addReadAheadHelper(ReadAheadHelper helper) {
+ if (readAheadNames == null)
+ readAheadNames = new HashMap(3);
+ readAheadNames.put(helper.getParentDOMName(), helper);
+ }
+
+ public boolean isDependencyChild() {
+ return false;
+ }
+
+ /**
+ * @return
+ */
+ public boolean isDependencyParent() {
+ if (isDependencyParent == null) {
+ isDependencyParent = Boolean.FALSE;
+ Translator[] theChildren = getChildren(null, -1);
+ if (theChildren != null) {
+ for (int i = 0; i < theChildren.length; i++) {
+ //For now we assume one
+ if (theChildren[i].isDependencyChild()) {
+ isDependencyParent = Boolean.TRUE;
+ dependencyFeature = theChildren[i].getDependencyFeature();
+ }
+ }
+ }
+ }
+ return isDependencyParent.booleanValue();
+ }
+
+ /**
+ * @return
+ */
+ public EStructuralFeature getDependencyFeature() {
+ return dependencyFeature;
+ }
+
+ public EObject basicGetDependencyObject(EObject parent) {
+ return (EObject) parent.eGet(dependencyFeature);
+ }
+
+ /**
+ * Use when the DOM path is not null, and there are no children. Default is false, but
+ * subclasses may wish to override
+ */
+ public boolean shouldRenderEmptyDOMPath(EObject eObject) {
+ return isEmptyContentSignificant();
+ }
+
+ /**
+ * Use when the translator tolerates parent nodes that relate to the DOM path, and no children;
+ * default is do nothing
+ */
+ public void setMOFValueFromEmptyDOMPath(EObject eObject) {
+
+ }
+
+ /**
+ * Namespace for the attributes
+ *
+ * @return
+ */
+ public String getNameSpace() {
+ return fNameSpace;
+ }
+
+ /**
+ * Set the namespace for the dom attribute
+ *
+ * @param string
+ */
+ public void setNameSpace(String string) {
+ fNameSpace = string;
+ }
+
+ public VariableTranslatorFactory getVariableTranslatorFactory() {
+ if (isObjectMap())
+ return DefaultTranslatorFactory.INSTANCE;
+ return null;
+ }
+
+ public boolean isEnumFeature() {
+ return feature != null && ECORE_PACKAGE.getEEnum().isInstance(feature.getEType());
+ }
+
+ public boolean isUnsettable() {
+ return feature != null && feature.isUnsettable();
+ }
+
+ public boolean isDataType() {
+ return feature != null && feature.getEType() instanceof EDataType;
+ }
+
+ /**
+ * @return
+ */
+ public boolean isComment() {
+ return (fStyle & COMMENT_FEATURE) != 0;
+ }
+
+}
diff --git a/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/resource/TranslatorFilter.java b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/resource/TranslatorFilter.java
new file mode 100644
index 0000000..b12067d
--- /dev/null
+++ b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/resource/TranslatorFilter.java
@@ -0,0 +1,220 @@
+/***************************************************************************************************
+ * Copyright (c) 2003, 2004 IBM Corporation 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: IBM Corporation - initial API and implementation
+ **************************************************************************************************/
+/*
+ * Created on Sep 21, 2003
+ *
+ */
+package org.eclipse.wst.common.internal.emf.resource;
+
+import org.eclipse.emf.ecore.EObject;
+
+
+/*
+ * Translator filters can be used to differentiate between Object and Attribute Translators without
+ * breaking them out into seperate data structures. The Filter will rely on the underlying data
+ * structure used to store the children of the given Translator.
+ *
+ * getNextChild() will return null when no other translators of the given genre are available.
+ *
+ * The processing hints which are created and then passed to getNext*Translator() store information
+ * that needs to be persisted between calls. The createProcessingHints() will create a properly
+ * initialized array. The constants NEXT_START_HINT_INDX and MODE_HINT_INDX provide pointers into
+ * the array for the NEXT_START position and the proper mode to operate in
+ * (STANDARD_TRANSLATORS_MODE or
+ *
+ */
+public abstract class TranslatorFilter {
+
+ protected final Translator translator;
+ protected final int version;
+
+ public static final int NEXT_START_HINT_INDX = 0;
+ public static final int MODE_HINT_INDX = 1;
+
+ public static final int STANDARD_TRANSLATORS_MODE = 0;
+ public static final int VARIABLE_TRANSLATORS_MODE = 1;
+
+ /*
+ * These TranslatorFilters are used in a stateless mode. Only their scanNextTranslator() methods
+ * will be invoked
+ */
+ private static final TranslatorFilter objectTranslatorFilter = new ObjectTranslatorFilter(null, -1);
+ private static final TranslatorFilter attributeTranslatorFilter = new AttributeTranslatorFilter(null, -1);
+
+
+ protected int mode = STANDARD_TRANSLATORS_MODE;
+ protected int index = -1;
+
+ protected Translator cachedPeekAheadTranslator = null;
+
+ public TranslatorFilter(Translator trans, int version) {
+ this.translator = trans;
+ this.version = version;
+ }
+
+ /**
+ * Calling peek twice will advance the current child
+ */
+ public Translator peekNextChild(EObject target) {
+ cachedPeekAheadTranslator = getNextChild(target);
+ return cachedPeekAheadTranslator;
+ }
+
+ /**
+ * getNextChild() will return null when no other translators of the given genre are available.
+ */
+ public Translator getNextChild(EObject target) {
+
+ Translator result = null;
+ if (cachedPeekAheadTranslator != null) {
+ result = cachedPeekAheadTranslator;
+ cachedPeekAheadTranslator = null;
+ return result;
+ }
+
+ int found = 0;
+ Translator children[] = null;
+ switch (mode) {
+ case STANDARD_TRANSLATORS_MODE :
+ children = this.translator.getChildren(target, this.version);
+
+ /* Look for the next Attribute Translator */
+ found = scanNextTranslator(children, this.index);
+
+ if (found >= 0) {
+ /*
+ * If found, (1) update the result, (2) update the index so we can skip ahead on
+ * the next invocation (3) escape the VARIABLE_TRANSLATORS processing
+ */
+ result = children[found];
+ this.index = found;
+ break;
+ }
+ /*
+ * Reset the index. DO NOT BREAK. Allow entry into VARIABLE_TRANSLATORS case
+ */
+ this.index = -1;
+ /*
+ * update the mode to VARIABLE_TRANSLATORS so we can skip to it directly next time
+ */
+ this.mode = VARIABLE_TRANSLATORS_MODE;
+ case VARIABLE_TRANSLATORS_MODE :
+ children = this.translator.getVariableChildren(target, this.version);
+ found = scanNextTranslator(children, this.index);
+ if (found >= 0) {
+ /*
+ * If found, (1) update the result, (2) update the index so we can skip ahead on
+ * the next invocation
+ */
+ result = children[found];
+ this.index = found;
+ }
+
+ }
+
+ return result;
+ }
+
+ public static final int[] createProcessingHints() {
+ return new int[]{-1, STANDARD_TRANSLATORS_MODE};
+ }
+
+ public static final Translator getNextAttributeTranslator(Translator translator, int startHint, int[] nextHint, EObject target, int version) {
+
+ return TranslatorFilter.getNextChild(translator, startHint, nextHint, target, version, attributeTranslatorFilter);
+ }
+
+ public static final Translator getNextObjectTranslator(Translator translator, int startHint, int[] nextHint, EObject target, int version) {
+
+ return TranslatorFilter.getNextChild(translator, startHint, nextHint, target, version, objectTranslatorFilter);
+ }
+
+ /**
+ * getNextChild() takes hints on where to begin in the children array of the given Translator.
+ * When it finds the translator, it will update the hints array with the start hint for the next
+ * invocation(hints[0]) and when necessary it will use update the mode (hints[1]) to either
+ * STANDARD_TRANSLATORS or VARIABLE_TRANSLATORS.
+ *
+ * @param translator
+ * @param startHint
+ * @param hints
+ * a two-element array: hints[0] will be updated with the next startHint and hints[1]
+ * will be used to store the mode.
+ * @param target
+ * @param version
+ * @param translatorFilter
+ * @return
+ */
+ public static final Translator getNextChild(Translator translator, int startHint, int[] hints, EObject target, int version, TranslatorFilter translatorFilter) {
+
+ Translator result = null;
+
+ int index = startHint;
+ Translator children[] = null;
+
+ switch (hints[MODE_HINT_INDX]) {
+ case STANDARD_TRANSLATORS_MODE :
+ children = translator.getChildren(target, version);
+ if (children != null && startHint < children.length) {
+
+ /* Look for the next Attribute Translator */
+ index = translatorFilter.scanNextTranslator(children, index);
+
+ if (index >= 0) {
+ /*
+ * If found, (1) update the result, (2) update the index so we can skip
+ * ahead on the next invocation (3) escape the VARIABLE_TRANSLATORS
+ * processing
+ */
+ result = children[index];
+ break;
+ }
+ /*
+ * DO NOT BREAK we will default to VARIABLE TRANSLATORS MODE so we must reset
+ * the startHint appropriately
+ */
+ startHint = -1;
+ }
+
+ case VARIABLE_TRANSLATORS_MODE :
+ hints[MODE_HINT_INDX] = VARIABLE_TRANSLATORS_MODE;
+ /*
+ * Reset the index.
+ */
+ index = startHint;
+ children = translator.getVariableChildren(target, version);
+ if (children != null && children.length > 0 && startHint < children.length) {
+ index = translatorFilter.scanNextTranslator(children, index);
+ result = (index >= 0) ? children[index] : null;
+ }
+ }
+
+ hints[NEXT_START_HINT_INDX] = (result == null && children != null) ? children.length : index;
+
+ return result;
+ }
+
+
+ public abstract int scanNextTranslator(Translator[] children, int start);
+
+ /**
+ * @return
+ */
+ public int getIndex() {
+ return index;
+ }
+
+ /**
+ * @return
+ */
+ public int getMode() {
+ return mode;
+ }
+
+}
\ No newline at end of file
diff --git a/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/resource/TranslatorPath.java b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/resource/TranslatorPath.java
new file mode 100644
index 0000000..a2d843e
--- /dev/null
+++ b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/resource/TranslatorPath.java
@@ -0,0 +1,94 @@
+/***************************************************************************************************
+ * Copyright (c) 2003, 2004 IBM Corporation 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: IBM Corporation - initial API and implementation
+ **************************************************************************************************/
+package org.eclipse.wst.common.internal.emf.resource;
+
+
+import java.util.Iterator;
+import java.util.List;
+
+import org.eclipse.emf.ecore.EObject;
+import org.eclipse.emf.ecore.EStructuralFeature;
+
+
+public class TranslatorPath {
+ protected Translator[] mapInfoPath;
+
+ /**
+ * Construct with an array of Translator that specifies the path to follow from an object to
+ * another object
+ */
+ public TranslatorPath(Translator[] path) {
+ mapInfoPath = path;
+ }
+
+ public List findObjects(EObject startObject) {
+ Object cur = startObject;
+ for (int i = 0; i < mapInfoPath.length; i++) {
+ Translator curMap = mapInfoPath[i];
+ if (cur instanceof EObject) {
+ EStructuralFeature curAttr = curMap.getFeature();
+ if (curAttr == Translator.CONTAINER_FEATURE) {
+ curAttr = ((EObject) cur).eContainmentFeature();
+ cur = ((EObject) cur).eContainer();
+ } else if (curAttr == Translator.ROOT_FEATURE) {
+ cur = ((TranslatorResource) startObject.eResource()).getRootObject();
+ } else {
+ cur = ((EObject) cur).eGet(curAttr);
+ }
+ if (curMap.isMultiValued()) {
+ return (List) cur;
+ }
+ }
+ }
+ return null;
+ }
+
+ public Object findObject(EObject startObject, Object matchValue) {
+ List objects = findObjects(startObject);
+ if (objects == null)
+ return null;
+ return findObject(objects, getLastMap(), matchValue);
+ }
+
+ private Object findObject(List objectList, Translator map, Object matchValue) {
+ for (Iterator iter = objectList.iterator(); iter.hasNext();) {
+ EObject mofObject = (EObject) iter.next();
+ Object curMatchValue = mofObject.eGet(map.getFeature());
+ if (matchValue.equals(curMatchValue))
+ return mofObject;
+ }
+ return null;
+ }
+
+ public Translator getLastMap() {
+ return mapInfoPath[mapInfoPath.length - 1];
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see java.lang.Object#toString()
+ */
+ public String toString() {
+ StringBuffer sb = new StringBuffer();
+ String cn = getClass().getName();
+ int i = cn.lastIndexOf('.');
+ cn = cn.substring(++i, cn.length());
+ sb.append(cn);
+ sb.append('(');
+ sb.append(mapInfoPath[0]);
+ for (int j = 1; j < mapInfoPath.length; j++) {
+ sb.append('\n');
+ sb.append(mapInfoPath[j]);
+ }
+ sb.append(')');
+ return sb.toString();
+ }
+
+}
\ No newline at end of file
diff --git a/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/resource/TranslatorResource.java b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/resource/TranslatorResource.java
new file mode 100644
index 0000000..32c9c47
--- /dev/null
+++ b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/resource/TranslatorResource.java
@@ -0,0 +1,79 @@
+/***************************************************************************************************
+ * Copyright (c) 2003, 2004 IBM Corporation 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: IBM Corporation - initial API and implementation
+ **************************************************************************************************/
+package org.eclipse.wst.common.internal.emf.resource;
+
+
+import org.eclipse.emf.ecore.EObject;
+import org.eclipse.emf.ecore.EStructuralFeature;
+import org.eclipse.emf.ecore.impl.EStructuralFeatureImpl;
+import org.xml.sax.EntityResolver;
+
+public interface TranslatorResource extends ReferencedResource {
+ /*
+ * must make a subclass because the constructor for EStructuralFeature is protected
+ */
+ static class DocTypeFeature extends EStructuralFeatureImpl {
+ protected DocTypeFeature() {
+ super();
+ }
+ }
+
+
+ EStructuralFeature DOC_TYPE_FEATURE = new DocTypeFeature();
+
+ /**
+ * The public id of the XML document, if specified.
+ */
+ String getPublicId();
+
+ /**
+ * Return the first element in the EList.
+ */
+ EObject getRootObject();
+
+ /**
+ * The system id of the XML document, if specified.
+ */
+ String getSystemId();
+
+ /**
+ * Sets the public id and system id of the XML document.
+ */
+ void setDoctypeValues(String publicId, String systemId);
+
+ /**
+ * Sets the default public/system ids if necessary
+ */
+ void setDefaults();
+
+ /**
+ * Returns the name that will be in the document type header of the serialized xml file
+ */
+ String getDoctype();
+
+ /**
+ * Returns the XML version of this document
+ */
+ String getXMLVersion();
+
+ Translator getRootTranslator();
+
+ /**
+ * Entity resolver that can be used when using standard parsers to read the resource
+ */
+ EntityResolver getEntityResolver();
+
+ boolean usesDTD();
+
+ public int getVersionID();
+
+ void setVersionID(int i);
+
+ Renderer getRenderer();
+}
\ No newline at end of file
diff --git a/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/resource/TranslatorResourceFactory.java b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/resource/TranslatorResourceFactory.java
new file mode 100644
index 0000000..20a450b
--- /dev/null
+++ b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/resource/TranslatorResourceFactory.java
@@ -0,0 +1,68 @@
+/***************************************************************************************************
+ * Copyright (c) 2003, 2004 IBM Corporation 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: IBM Corporation - initial API and implementation
+ **************************************************************************************************/
+package org.eclipse.wst.common.internal.emf.resource;
+
+import org.eclipse.emf.common.util.URI;
+import org.eclipse.emf.ecore.resource.Resource;
+
+public abstract class TranslatorResourceFactory extends ReferencedXMIFactoryImpl implements RendererFactory.Listener {
+
+ protected RendererFactory rendererFactory;
+ private boolean listeningForUpdates = false;
+
+ /**
+ * Constructor for TranslatorResourceFactory.
+ */
+ public TranslatorResourceFactory(RendererFactory aRendererFactory, boolean listeningForUpdates) {
+ super();
+ rendererFactory = aRendererFactory;
+ setListeningForUpdates(listeningForUpdates);
+ }
+
+ /**
+ * Constructor for TranslatorResourceFactory.
+ */
+ public TranslatorResourceFactory(RendererFactory aRendererFactory) {
+ this(aRendererFactory, true);
+ }
+
+ public void setListeningForUpdates(boolean shouldBeListeningForUpdates) {
+
+ if (this.listeningForUpdates ^ shouldBeListeningForUpdates) {
+ if (!shouldBeListeningForUpdates)
+ RendererFactory.NotificationEngine.removeListener(this);
+ else
+ RendererFactory.NotificationEngine.addListener(this);
+
+ this.listeningForUpdates = shouldBeListeningForUpdates;
+ }
+ }
+
+ public boolean isListeningForUpdates() {
+ return this.listeningForUpdates;
+ }
+
+ public Resource doCreateResource(URI uri) {
+ Renderer aRenderer = rendererFactory.createRenderer();
+ return createResource(uri, aRenderer);
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see com.ibm.etools.emf2xml.RendererFactory.Listener#updateRendererFactory(com.ibm.etools.emf2xml.RendererFactory)
+ */
+ public void updateRendererFactory(RendererFactory newRendererFactory) {
+ //System.out.println("Updating renderer factory");
+ rendererFactory = newRendererFactory;
+ }
+
+ protected abstract TranslatorResource createResource(URI uri, Renderer aRenderer);
+
+}
\ No newline at end of file
diff --git a/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/resource/TranslatorResourceImpl.java b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/resource/TranslatorResourceImpl.java
new file mode 100644
index 0000000..5d09434
--- /dev/null
+++ b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/resource/TranslatorResourceImpl.java
@@ -0,0 +1,396 @@
+/*******************************************************************************
+ * Copyright (c) 2003, 2007 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.wst.common.internal.emf.resource;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.util.Collection;
+import java.util.Map;
+
+import org.eclipse.emf.common.notify.Notification;
+import org.eclipse.emf.common.notify.impl.NotificationImpl;
+import org.eclipse.emf.common.util.EList;
+import org.eclipse.emf.common.util.URI;
+import org.eclipse.emf.ecore.EObject;
+import org.eclipse.emf.ecore.EStructuralFeature;
+import org.eclipse.emf.ecore.EcorePackage;
+import org.eclipse.emf.ecore.InternalEObject;
+import org.eclipse.emf.ecore.impl.ENotificationImpl;
+import org.eclipse.emf.ecore.resource.impl.ResourceImpl;
+import org.eclipse.jem.util.logger.proxy.Logger;
+import org.eclipse.wst.common.internal.emf.utilities.StringUtil;
+import org.xml.sax.EntityResolver;
+
+public abstract class TranslatorResourceImpl extends ReferencedXMIResourceImpl implements TranslatorResource, IRootObjectResource{
+ static final public EStructuralFeature ID_FEATURE = EcorePackage.eINSTANCE.getEClass_EIDAttribute();
+ protected static final String DEFAULT_ENCODING = "UTF-8"; //$NON-NLS-1$
+ protected static final String DEFAULT_VERSION = "1.0"; //$NON-NLS-1$
+ protected Renderer renderer;
+ /**
+ * The public Id to use at the head of the document.
+ */
+ protected String publicId;
+ /**
+ * The system Id to use at the head of the document.
+ */
+ protected String systemId;
+ protected String xmlVersion;
+ // Default the resources to J2EE 1.4
+ protected int versionID;
+
+ /**
+ * @deprecated since 4/29/2003 - used for compatibility Subclasses should
+ * be using the Renderers and translator framework
+ */
+ public TranslatorResourceImpl() {
+ super();
+ }
+
+ /**
+ * @deprecated since 4/29/2003 - used for compatibility Subclasses should
+ * be using the Renderers and translator framework
+ */
+ public TranslatorResourceImpl(URI uri) {
+ super(uri);
+ }
+
+ public TranslatorResourceImpl(URI uri, Renderer aRenderer) {
+ super(uri);
+ setRenderer(aRenderer);
+ versionID = getDefaultVersionID();
+ }
+
+ public TranslatorResourceImpl(Renderer aRenderer) {
+ super();
+ setRenderer(aRenderer);
+ }
+
+ public java.lang.String getEncoding() {
+ if (super.getEncoding() == null)
+ setEncoding(DEFAULT_ENCODING);
+ return super.getEncoding();
+ }
+
+ public String getPublicId() {
+ return publicId;
+ }
+
+ /**
+ * Return the first element in the EList.
+ */
+ public EObject getRootObject() {
+ if (contents == null || contents.isEmpty())
+ return null;
+ return (EObject) getContents().get(0);
+ }
+
+ public String getSystemId() {
+ return systemId;
+ }
+
+ public void setDoctypeValues(String aPublicId, String aSystemId) {
+ boolean changed = !(StringUtil.stringsEqual(publicId, aPublicId) && StringUtil.stringsEqual(systemId, aSystemId));
+ publicId = aPublicId;
+ systemId = aSystemId;
+ if (changed) {
+ eNotify(new NotificationImpl(Notification.SET, null, null) {
+ public Object getFeature() {
+ return DOC_TYPE_FEATURE;
+ }
+
+ public Object getNotifier() {
+ return TranslatorResourceImpl.this;
+ }
+ });
+ }
+ }
+
+ /**
+ * Returns the xmlVersion.
+ *
+ * @return String
+ */
+ public String getXMLVersion() {
+ if (xmlVersion == null)
+ xmlVersion = DEFAULT_VERSION;
+ return xmlVersion;
+ }
+
+ /**
+ * Sets the xmlVersion.
+ *
+ * @param xmlVersion
+ * The xmlVersion to set
+ */
+ public void setXMLVersion(String xmlVersion) {
+ this.xmlVersion = xmlVersion;
+ }
+
+ protected void basicDoLoad(InputStream inputStream, Map options) throws IOException {
+ // long start = System.currentTimeMillis();
+ boolean isTrackingMods = isTrackingModification();
+ try {
+ if (isTrackingMods)
+ setTrackingModification(false);
+ renderer.doLoad(inputStream, options);
+ }
+ finally {
+ if (isTrackingMods)
+ setTrackingModification(true);
+ }
+ // long end = System.currentTimeMillis();
+ // recordTime("Load", start, end);
+ }
+
+ public void save(Map options) throws IOException {
+ if (renderer.useStreamsForIO()) {
+ super.save(options);
+ } else {
+ notifyAboutToSave();
+ try {
+ doSave((OutputStream)null, options);
+ notifySaved();
+ } catch (Exception e) {
+ notifySaveFailed();
+ if (e instanceof IOException)
+ throw (IOException) e;
+ else
+ Logger.getLogger().write(e);
+ }
+ notifySaved();
+ }
+ }
+
+
+ /**
+ * @see com.ibm.etools.xmi.helpers.CompatibilityXMIResourceImpl#doSave(OutputStream,
+ * Map)
+ */
+ public void doSave(OutputStream outputStream, Map options) throws IOException {
+ // long start = System.currentTimeMillis();
+ renderer.doSave(outputStream, options);
+ setModified(false);
+ // long end = System.currentTimeMillis();
+ // recordTime("Save", start, end);
+ }
+
+ // private void recordTime(String type, long start, long end) {
+ // System.out.println(renderer.getClass().getName() + "\t" + type + "\t" +
+ // (end - start) +
+ // "\t\t\tms" + "\t" + (( this.getVersionID()) / 10.0) + "\t" + this);
+ // //$NON-NLS-1$
+ // //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
+ // }
+
+ /**
+ * @see org.eclipse.emf.ecore.xmi.impl.XMLResourceImpl#doUnload()
+ */
+ protected void doUnload() {
+ renderer.preUnload();
+ super.doUnload();
+ }
+
+ public String toString() {
+ return getClass().getName() + getURI().toString();
+ }
+
+ /**
+ * Returns the renderer.
+ *
+ * @return Renderer
+ */
+ public Renderer getRenderer() {
+ return renderer;
+ }
+
+ /**
+ * Sets the renderer.
+ *
+ * @param renderer
+ * The renderer to set
+ */
+ public void setRenderer(Renderer renderer) {
+ this.renderer = renderer;
+ if (renderer.getResource() != this)
+ renderer.setResource(this);
+ }
+
+ /**
+ * For compatibility of old subtype resources, returns the super
+ * implementation
+ *
+ * @return
+ */
+ protected EList primGetContents() {
+ return super.getContents();
+ }
+
+ public EList getContents() {
+ waitForResourceToLoadIfNecessary();
+ if (contents == null) {
+ initializeContents();
+ }
+ return contents;
+ }
+
+ protected void initializeContents() {
+ contents = new ResourceImpl.ContentsEList() {
+ public boolean add(Object object) {
+ renderer.prepareToAddContents();
+ return super.add(object);
+ }
+
+ public boolean addAll(Collection collection) {
+ renderer.prepareToAddContents();
+ return super.addAll(collection);
+ }
+ };
+ }
+
+ public void setDefaults() {
+ if (systemId != null && publicId != null)
+ return;
+ String pubId = publicId == null ? getDefaultPublicId() : publicId;
+ String sysId = systemId == null ? getDefaultSystemId() : systemId;
+ setDoctypeValues(pubId, sysId);
+ }
+
+ /**
+ * @see org.eclipse.emf.ecore.xmi.impl.XMLResourceImpl#init()
+ */
+ protected void init() {
+ super.init();
+ setEncoding(DEFAULT_ENCODING);
+ }
+
+ /**
+ * Returns null by default; subclasses can override
+ *
+ * @see com.ibm.etools.emf2xml.TranslatorResource#createEntityResolver()
+ */
+ public EntityResolver getEntityResolver() {
+ return null;
+ }
+
+ protected abstract String getDefaultPublicId();
+
+ protected abstract String getDefaultSystemId();
+
+ protected abstract int getDefaultVersionID();
+
+ /**
+ * @return
+ */
+ public int getVersionID() {
+ return versionID;
+ }
+
+ /**
+ * @param i
+ */
+ public void setVersionID(int i) {
+ versionID = i;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see com.ibm.etools.emf2xml.TranslatorResource#usesDTD()
+ */
+ public boolean usesDTD() {
+ return getPublicId() != null && getSystemId() != null;
+ }
+
+ /**
+ * Overridden to notify when the ID gets set; need this to push it into
+ * the resource
+ *
+ * @see org.eclipse.emf.ecore.xmi.XMLResource#setID(EObject, String)
+ */
+ public void setID(EObject eObject, String id) {
+ String oldId = getID(eObject);
+ super.setID(eObject, id);
+ eObject.eNotify(new ENotificationImpl((InternalEObject) eObject, Notification.SET, ID_FEATURE, oldId, id));
+ }
+
+ /**
+ * This method indicates whether or not the extent associated with the
+ * resource has been modified since the last time it was loaded or saved.
+ *
+ * @return boolean
+ */
+ public boolean isModified() {
+ return super.isModified() || renderer.isModified();
+ }
+
+ /*
+ * Overriden to give the renderer a hook
+ *
+ * @see org.eclipse.wst.common.internal.emf.resource.ReferencedResource#accessForWrite()
+ */
+ public void accessForWrite() {
+ renderer.accessForWrite();
+ super.accessForWrite();
+ }
+
+ /*
+ * Overriden to give the renderer a hook
+ *
+ * @see org.eclipse.wst.common.internal.emf.resource.ReferencedResource#accessForRead()
+ */
+ public void accessForRead() {
+ renderer.accessForRead();
+ super.accessForRead();
+ }
+
+ public void releaseFromRead() {
+ renderer.releaseFromRead();
+ super.releaseFromRead();
+ }
+
+ public void releaseFromWrite() {
+ renderer.releaseFromWrite();
+ super.releaseFromWrite();
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see com.ibm.etools.emf.workbench.ReferencedXMIResourceImpl#preDelete()
+ */
+ public void preDelete() {
+ super.preDelete();
+ renderer.preDelete();
+ }
+
+ public boolean isShared() {
+ return super.isShared() || renderer.isShared();
+ }
+
+ public boolean isSharedForWrite() {
+ return super.isSharedForWrite() || renderer.isSharedForWrite();
+ }
+
+ public void load(Map options) throws IOException {
+
+ if (isLoaded())
+ return;
+
+ if (renderer.useStreamsForIO()) {
+ super.load(options);
+ }
+ else if (!isLoaded()) {
+ isShared();
+ loadExisting(options);
+ }
+ }
+}
diff --git a/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/resource/UnsupportedFeature.java b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/resource/UnsupportedFeature.java
new file mode 100644
index 0000000..43c5864
--- /dev/null
+++ b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/resource/UnsupportedFeature.java
@@ -0,0 +1,43 @@
+/*******************************************************************************
+ * Copyright (c) 2003, 2004 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+/*
+ * Created on Apr 13, 2004
+ *
+ * TODO To change the template for this generated file go to
+ * Window - Preferences - Java - Code Generation - Code and Comments
+ */
+package org.eclipse.wst.common.internal.emf.resource;
+
+import org.eclipse.emf.ecore.EClass;
+import org.eclipse.emf.ecore.impl.EAttributeImpl;
+
+/**
+ * @author cbridgha
+ *
+ * TODO To change the template for this generated type comment go to Window - Preferences - Java -
+ * Code Generation - Code and Comments
+ */
+public class UnsupportedFeature extends EAttributeImpl {
+ /**
+ * This is used to capture features that are no longer supported
+ */
+ public static boolean isUnsupported(EClass anEClass, String featureName) {
+
+ if (featureName.equals("isZeroParams") && anEClass.getName().equals("MethodElement")) //$NON-NLS-1$ //$NON-NLS-2$
+ return true;
+ return false;
+ }
+
+ public UnsupportedFeature() {
+ super();
+ // TODO Auto-generated constructor stub
+ }
+}
\ No newline at end of file
diff --git a/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/resource/VariableTranslatorFactory.java b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/resource/VariableTranslatorFactory.java
new file mode 100644
index 0000000..1a4eef9
--- /dev/null
+++ b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/resource/VariableTranslatorFactory.java
@@ -0,0 +1,42 @@
+/*******************************************************************************
+ * Copyright (c) 2003, 2004 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+/*
+ * Created on Aug 20, 2003
+ *
+ */
+package org.eclipse.wst.common.internal.emf.resource;
+
+import java.util.List;
+
+import org.eclipse.emf.common.notify.Notification;
+import org.eclipse.emf.common.notify.Notifier;
+
+
+/**
+ * @author schacher
+ */
+public interface VariableTranslatorFactory {
+ /** Returns whether a Translator should be created for the given DOM name */
+ boolean accepts(String domName);
+
+ /** Returns whether a Translator should be created for the given feature */
+ boolean accepts(Notification notif);
+
+ Translator create(Notification notif);
+
+ /** Creates a new Translator for the DOM name */
+ Translator create(String domName);
+
+ /** Creates variable translators for an EMF object to be rendered */
+ List create(Notifier target);
+
+
+}
\ No newline at end of file
diff --git a/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/resource/XMLEncoderDecoder.java b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/resource/XMLEncoderDecoder.java
new file mode 100644
index 0000000..d7b7f3b
--- /dev/null
+++ b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/resource/XMLEncoderDecoder.java
@@ -0,0 +1,170 @@
+/*******************************************************************************
+ * Copyright (c) 2003, 2006 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+/*
+ * Created on May 20, 2004
+ *
+ * TODO To change the template for this generated file go to
+ * Window - Preferences - Java - Code Generation - Code and Comments
+ */
+package org.eclipse.wst.common.internal.emf.resource;
+
+/**
+ * @author mdelder
+ *
+ */
+public class XMLEncoderDecoder {
+
+ /**
+ *
+ */
+ public XMLEncoderDecoder() {
+ super();
+ }
+
+ /**
+ * Identifies the last printable character in the Unicode range that is supported by the
+ * encoding used with this serializer. For 8-bit encodings this will be either 0x7E or 0xFF. For
+ * 16-bit encodings this will be 0xFFFF. Characters that are not printable will be escaped using
+ * character references.
+ */
+ private int _lastPrintable = 0xFFFE;
+
+ protected static XMLEncoderDecoder _singleton;
+
+
+ /**
+ * Returns a decoded version of the value.
+ */
+ public String decode(String value) {
+ // NOT_IMPLEMENTED
+ return value;
+ }
+
+
+ /**
+ * Escapes a string so it may be printed as text content or attribute value. Non printable
+ * characters are escaped using character references. Where the format specifies a deault entity
+ * reference, that reference is used (e.g. <tt>&lt;</tt>).
+ *
+ * @param source
+ * The string to escape
+ */
+ public char[] encode(char[] value) {
+ boolean unmodified = true;
+ StringBuffer sbuf = new StringBuffer(value.length);
+ String charRef = null;
+ char ch;
+ for (int i = 0; i < value.length; ++i) {
+ ch = value[i];
+ // If there is a suitable entity reference for this
+ // character, print it. The list of available entity
+ // references is almost but not identical between
+ // XML and HTML.
+ charRef = getEntityRef(ch);
+ if (charRef != null) {
+ sbuf.append('&');
+ sbuf.append(charRef);
+ sbuf.append(';');
+ unmodified = false;
+ } else if ((ch >= ' ' && ch <= _lastPrintable && ch != 0xF7) || ch == '\n' || ch == '\r' || ch == '\t') {
+ // If the character is not printable, print as character
+ // reference.
+ // Non printables are below ASCII space but not tab or line
+ // terminator, ASCII delete, or above a certain Unicode
+ // threshold.
+ sbuf.append(ch);
+ } else {
+ sbuf.append("&#");//$NON-NLS-1$
+ sbuf.append(Integer.toString(ch));
+ sbuf.append(';');
+ unmodified = false;
+ }
+ }
+ if (unmodified)
+ return value;
+ char[] result = new char[sbuf.length()];
+ sbuf.getChars(0, sbuf.length(), result, 0);
+ return result;
+ }
+
+ /**
+ * Escapes a string so it may be printed as text content or attribute value. Non printable
+ * characters are escaped using character references. Where the format specifies a deault entity
+ * reference, that reference is used (e.g. <tt>&lt;</tt>).
+ *
+ * @param source
+ * The string to escape
+ */
+ public String encode(String value) {
+ StringBuffer sbuf = new StringBuffer(value.length());
+ String charRef = null;
+ char ch;
+ for (int i = 0; i < value.length(); ++i) {
+ ch = value.charAt(i);
+ // If there is a suitable entity reference for this
+ // character, print it. The list of available entity
+ // references is almost but not identical between
+ // XML and HTML.
+ charRef = getEntityRef(ch);
+ if (charRef != null) {
+ sbuf.append('&');
+ sbuf.append(charRef);
+ sbuf.append(';');
+ } else if ((ch >= ' ' && ch <= _lastPrintable && ch != 0xF7) || ch == '\n' || ch == '\r' || ch == '\t') {
+ // If the character is not printable, print as character
+ // reference.
+ // Non printables are below ASCII space but not tab or line
+ // terminator, ASCII delete, or above a certain Unicode
+ // threshold.
+ sbuf.append(ch);
+ } else {
+ sbuf.append("&#");//$NON-NLS-1$
+ sbuf.append(Integer.toString(ch));
+ sbuf.append(';');
+ }
+ }
+ return sbuf.toString();
+ }
+
+ public static String escape(String value) {
+ if (_singleton == null) {
+ _singleton = new XMLEncoderDecoder();
+ }
+ return _singleton.encode(value);
+ }
+
+ /**
+ * Returns the suitable entity reference for this character value, or null if no such entity
+ * exists. Calling this method with <tt>'&'</tt> will return <tt>"&amp;"</tt>.
+ *
+ * @param ch
+ * Character value
+ * @return Character entity name, or null
+ */
+ protected String getEntityRef(char ch) {
+ // Encode special XML characters into the equivalent character
+ // references.
+ // These five are defined by default for all XML documents.
+ switch (ch) {
+ case '<' :
+ return "lt";//$NON-NLS-1$
+ case '>' :
+ return "gt";//$NON-NLS-1$
+ case '"' :
+ return "quot";//$NON-NLS-1$
+ case '\'' :
+ return "apos";//$NON-NLS-1$
+ case '&' :
+ return "amp";//$NON-NLS-1$
+ }
+ return null;
+ }
+}
diff --git a/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/utilities/AdapterFactoryDescriptor.java b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/utilities/AdapterFactoryDescriptor.java
new file mode 100644
index 0000000..e6e559b
--- /dev/null
+++ b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/utilities/AdapterFactoryDescriptor.java
@@ -0,0 +1,19 @@
+/*******************************************************************************
+ * Copyright (c) 2003, 2005 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.wst.common.internal.emf.utilities;
+
+import org.eclipse.emf.common.notify.AdapterFactory;
+
+public interface AdapterFactoryDescriptor {
+
+ public AdapterFactory createAdapterFactory();
+
+}
diff --git a/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/utilities/AdapterFactoryUtil.java b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/utilities/AdapterFactoryUtil.java
new file mode 100644
index 0000000..36d9173
--- /dev/null
+++ b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/utilities/AdapterFactoryUtil.java
@@ -0,0 +1,47 @@
+/*******************************************************************************
+ * Copyright (c) 2003, 2005 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.wst.common.internal.emf.utilities;
+
+import java.util.List;
+
+import org.eclipse.emf.common.notify.AdapterFactory;
+import org.eclipse.emf.common.notify.Notifier;
+
+public class AdapterFactoryUtil {
+
+ /**
+ * Constructor for AdapterFactoryUtil.
+ */
+ public AdapterFactoryUtil() {
+ super();
+ }
+
+ public static void adaptNew(Notifier newObject, List factories) {
+ AdapterFactory fact;
+ for (int i = 0; i < factories.size(); i++) {
+ fact = (AdapterFactory) factories.get(i);
+ fact.adaptNew(newObject, null);
+ }
+ }
+
+ public static void createAdapterFactories(List descriptors, List factories) {
+ AdapterFactoryDescriptor desc;
+ AdapterFactory adapterFact;
+ for (int i = 0; i < descriptors.size(); i++) {
+ desc = (AdapterFactoryDescriptor) descriptors.get(i);
+ adapterFact = desc.createAdapterFactory();
+ if (adapterFact != null)
+ factories.add(adapterFact);
+ }
+ descriptors.clear();
+ }
+
+}
diff --git a/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/utilities/ArrayUtil.java b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/utilities/ArrayUtil.java
new file mode 100644
index 0000000..847b88d
--- /dev/null
+++ b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/utilities/ArrayUtil.java
@@ -0,0 +1,46 @@
+/***************************************************************************************************
+ * Copyright (c) 2003, 2004 IBM Corporation 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: IBM Corporation - initial API and implementation
+ **************************************************************************************************/
+package org.eclipse.wst.common.internal.emf.utilities;
+
+
+
+public class ArrayUtil {
+
+ public static Object[] concat(Object[] array1, Object[] array2) {
+ Class componentType = null;
+ if (array1.getClass().getComponentType() == array2.getClass().getComponentType())
+ componentType = array1.getClass().getComponentType();
+ else
+ componentType = Object.class;
+
+ return concat(array1, array2, componentType);
+ }
+
+ public static Object[] concat(Object[] array1, Object[] array2, Class componentType) {
+ Object[] result = (Object[]) java.lang.reflect.Array.newInstance(componentType, array1.length + array2.length);
+ System.arraycopy(array1, 0, result, 0, array1.length);
+ System.arraycopy(array2, 0, result, array1.length, array2.length);
+ return result;
+ }
+
+ public static Object[] concatAll(java.util.List arrays, Class componentType) {
+ int resultLength = 0;
+ for (int i = 0; i < arrays.size(); i++) {
+ resultLength += ((Object[]) arrays.get(i)).length;
+ }
+ Object[] result = (Object[]) java.lang.reflect.Array.newInstance(componentType, resultLength);
+ int pos = 0;
+ for (int i = 0; i < arrays.size(); i++) {
+ Object[] array = (Object[]) arrays.get(i);
+ System.arraycopy(array, 0, result, pos, array.length);
+ pos += array.length;
+ }
+ return result;
+ }
+}
\ No newline at end of file
diff --git a/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/utilities/Assert.java b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/utilities/Assert.java
new file mode 100644
index 0000000..3a44751
--- /dev/null
+++ b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/utilities/Assert.java
@@ -0,0 +1,131 @@
+/*******************************************************************************
+ * Copyright (c) 2003, 2005 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.wst.common.internal.emf.utilities;
+
+import org.eclipse.jem.util.logger.proxy.Logger;
+
+
+
+/**
+ * <code>Assert</code> is useful for for embedding runtime sanity checks in code. The predicate
+ * methods all test a condition and throw some type of unchecked exception if the condition does not
+ * hold.
+ * <p>
+ * Assertion failure exceptions, like most runtime exceptions, are thrown when something is
+ * misbehaving. Assertion failures are invariably unspecified behavior; consequently, clients should
+ * never rely on these being thrown (and certainly should not being catching them specifically).
+ * </p>
+ */
+// This class was, originally, copied directly from com.ibm.itp.common.
+// It was copied to our own package just to minimize minor dependencies
+// on other packages and internal APIs.
+public final class Assert {
+ /* This class is not intended to be instantiated. */
+
+ private Assert() {
+ }
+
+ /**
+ * Asserts that an argument is legal. If the given boolean is not <code>true</code>, an
+ * <code>IllegalArgumentException</code> is thrown.
+ *
+ * @param expression
+ * the outcode of the check
+ * @return <code>true</code> if the check passes (does not return if the check fails)
+ * @exception IllegalArgumentException
+ * if the legality test failed
+ */
+ public static boolean isLegal(boolean expression) {
+ return isLegal(expression, "");//$NON-NLS-1$
+ }
+
+ /**
+ * Asserts that an argument is legal. If the given boolean is not <code>true</code>, an
+ * <code>IllegalArgumentException</code> is thrown. The given message is included in that
+ * exception, to aid debugging.
+ *
+ * @param expression
+ * the outcode of the check
+ * @param message
+ * the message to include in the exception
+ * @return <code>true</code> if the check passes (does not return if the check fails)
+ * @exception IllegalArgumentException
+ * if the legality test failed
+ */
+ public static boolean isLegal(boolean expression, String message) {
+ if (!expression)
+ throw new IllegalArgumentException();
+ return expression;
+ }
+
+ /**
+ * Asserts that the given object is not <code>null</code>. If this is not the case, some kind
+ * of unchecked exception is thrown.
+ *
+ * @param object
+ * the value to test
+ * @exception IllegalArgumentException
+ * if the object is <code>null</code>
+ */
+ public static void isNotNull(Object object) {
+ isNotNull(object, "");//$NON-NLS-1$
+ }
+
+ /**
+ * Asserts that the given object is not <code>null</code>. If this is not the case, some kind
+ * of unchecked exception is thrown. The given message is included in that exception, to aid
+ * debugging.
+ *
+ * @param object
+ * the value to test
+ * @param message
+ * the message to include in the exception
+ * @exception IllegalArgumentException
+ * if the object is <code>null</code>
+ */
+ public static void isNotNull(Object object, String message) {
+ if (object == null) {
+ Logger.getLogger().logError("null_argument: " + message);//$NON-NLS-1$
+ throw new AssertionFailedException();
+ }
+ }
+
+ /**
+ * Asserts that the given boolean is <code>true</code>. If this is not the case, some kind of
+ * unchecked exception is thrown.
+ *
+ * @param expression
+ * the outcode of the check
+ * @return <code>true</code> if the check passes (does not return if the check fails)
+ */
+ public static boolean isTrue(boolean expression) {
+ return isTrue(expression, "");//$NON-NLS-1$
+ }
+
+ /**
+ * Asserts that the given boolean is <code>true</code>. If this is not the case, some kind of
+ * unchecked exception is thrown. The given message is included in that exception, to aid
+ * debugging.
+ *
+ * @param expression
+ * the outcode of the check
+ * @param message
+ * the message to include in the exception
+ * @return <code>true</code> if the check passes (does not return if the check fails)
+ */
+ public static boolean isTrue(boolean expression, String message) {
+ if (!expression) {
+ Logger.getLogger().logError("assertion failed: " + message);//$NON-NLS-1$
+ throw new AssertionFailedException();
+ }
+ return expression;
+ }
+}
diff --git a/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/utilities/AssertionFailedException.java b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/utilities/AssertionFailedException.java
new file mode 100644
index 0000000..044c60d
--- /dev/null
+++ b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/utilities/AssertionFailedException.java
@@ -0,0 +1,39 @@
+/*******************************************************************************
+ * Copyright (c) 2003, 2004 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.wst.common.internal.emf.utilities;
+
+
+/**
+ * <code>AssertionFailedException</code> is a runtime exception thrown by some of the methods in
+ * <code>Assert</code>.
+ * <p>
+ * This class is not declared public to prevent some misuses; programs that catch or otherwise
+ * depend on assertion failures are susceptible to unexpected breakage when assertions in the code
+ * are added or removed.
+ * </p>
+ */
+// This class was, originally, copied directly from com.ibm.itp.common.
+// It was copied to our own package just to minimize minor dependencies
+// on other packages and internal APIs.
+class AssertionFailedException extends RuntimeException {
+ /**
+ * Constructs a new exception.
+ */
+ public AssertionFailedException() {
+ }
+
+ /**
+ * Constructs a new exception with the given message.
+ */
+ public AssertionFailedException(String detail) {
+ super(detail);
+ }
+}
\ No newline at end of file
diff --git a/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/utilities/Association.java b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/utilities/Association.java
new file mode 100644
index 0000000..485d0c3
--- /dev/null
+++ b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/utilities/Association.java
@@ -0,0 +1,68 @@
+/*******************************************************************************
+ * Copyright (c) 2003, 2004 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.wst.common.internal.emf.utilities;
+
+/**
+ * Insert the type's description here. Creation date: (12/17/2000 7:38:15 PM)
+ *
+ * @author: Administrator
+ */
+public class Association {
+ protected Object key;
+ protected Object value;
+
+ /**
+ * Association constructor comment.
+ */
+ public Association(Object aKey, Object aValue) {
+ setKey(aKey);
+ setValue(aValue);
+ }
+
+ /**
+ * Insert the method's description here. Creation date: (12/17/2000 7:38:48 PM)
+ *
+ * @return java.lang.Object
+ */
+ public java.lang.Object getKey() {
+ return key;
+ }
+
+ /**
+ * Insert the method's description here. Creation date: (12/17/2000 7:38:48 PM)
+ *
+ * @return java.lang.Object
+ */
+ public java.lang.Object getValue() {
+ return value;
+ }
+
+ /**
+ * Insert the method's description here. Creation date: (12/17/2000 7:38:48 PM)
+ *
+ * @param newKey
+ * java.lang.Object
+ */
+ public void setKey(java.lang.Object newKey) {
+ key = newKey;
+ }
+
+ /**
+ * Insert the method's description here. Creation date: (12/17/2000 7:38:48 PM)
+ *
+ * @param newValue
+ * java.lang.Object
+ */
+ public void setValue(java.lang.Object newValue) {
+ value = newValue;
+ }
+}
+
diff --git a/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/utilities/CloneablePublic.java b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/utilities/CloneablePublic.java
new file mode 100644
index 0000000..2c39fbc
--- /dev/null
+++ b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/utilities/CloneablePublic.java
@@ -0,0 +1,26 @@
+/*******************************************************************************
+ * Copyright (c) 2003, 2006 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+/*
+ * Created on Sep 22, 2003
+ *
+ */
+package org.eclipse.wst.common.internal.emf.utilities;
+
+import org.eclipse.emf.common.notify.Adapter;
+
+/**
+ * Interface that exposes the clone method, for objects that need to generically copy other
+ * cloneable objects
+ */
+public interface CloneablePublic extends Cloneable, Adapter.Internal {
+ Object clone();
+
+}
diff --git a/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/utilities/CommandContext.java b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/utilities/CommandContext.java
new file mode 100644
index 0000000..4dcb883
--- /dev/null
+++ b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/utilities/CommandContext.java
@@ -0,0 +1,85 @@
+/*******************************************************************************
+ * Copyright (c) 2003, 2005 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+/*
+ * Created on Apr 27, 2004
+ */
+package org.eclipse.wst.common.internal.emf.utilities;
+
+import java.util.HashMap;
+import java.util.Map;
+
+import org.eclipse.core.runtime.IProgressMonitor;
+import org.eclipse.core.runtime.NullProgressMonitor;
+import org.eclipse.emf.ecore.resource.ResourceSet;
+import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl;
+
+
+
+/**
+ * @author John Mourra
+ */
+public class CommandContext implements ICommandContext {
+
+ private IProgressMonitor monitor;
+ private Map properties;
+ private ResourceSet resourceSet;
+
+ /**
+ * @param monitor
+ */
+ public CommandContext(IProgressMonitor monitor) {
+ this(monitor, null, null);
+ }
+
+ /**
+ * @param monitor
+ * @param configurationProperties
+ * @param resourceSet
+ */
+ public CommandContext(IProgressMonitor monitor, Map configurationProperties, ResourceSet resourceSet) {
+ this.monitor = monitor;
+ this.properties = configurationProperties;
+ this.resourceSet = resourceSet;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see com.ibm.ws.rd.command.framework.ICommandContext#getProgressMonitor()
+ */
+ public IProgressMonitor getProgressMonitor() {
+ if (monitor == null)
+ monitor = new NullProgressMonitor();
+ return monitor;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see com.ibm.ws.rd.command.framework.ICommandContext#getConfigurationProperties()
+ */
+ public Map getConfigurationProperties() {
+ if (properties == null)
+ properties = new HashMap();
+ return properties;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see com.ibm.ws.rd.command.framework.ICommandContext#getResourceSet()
+ */
+ public ResourceSet getResourceSet() {
+ if (resourceSet == null)
+ resourceSet = new ResourceSetImpl();
+ return resourceSet;
+ }
+}
diff --git a/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/utilities/CopyGroup.java b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/utilities/CopyGroup.java
new file mode 100644
index 0000000..a23928c
--- /dev/null
+++ b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/utilities/CopyGroup.java
@@ -0,0 +1,320 @@
+/*******************************************************************************
+ * Copyright (c) 2003, 2005 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.wst.common.internal.emf.utilities;
+
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+
+import org.eclipse.emf.ecore.EObject;
+import org.eclipse.emf.ecore.resource.Resource;
+import org.eclipse.emf.ecore.resource.ResourceSet;
+
+/**
+ * This class is used to copy a group of RefObjects and/or Resources. This group will ensure that
+ * all non-composite relationships are deferred until all Resources and RefObjects are copied. This
+ * allows you to make copies of a group of objects that may have non-composite relationships and
+ * ensure that these relationships are pointing to the copied object if it is part of the group
+ * (either directly or through a containment relationship). Creation date: (12/17/2000 1:21:17 PM)
+ *
+ * @author: Administrator
+ */
+public class CopyGroup {
+ protected String defaultIdSuffix;
+ protected ResourceSet copyContext;
+ protected List resources;
+ protected List refObjects;
+ protected List copiedResources;
+ protected List copiedRefObjects;
+ protected boolean preserveIds = false;
+
+ /**
+ * CopyGroup constructor comment.
+ */
+ public CopyGroup() {
+ super();
+ }
+
+ /**
+ * Insert the method's description here. Creation date: (12/17/2000 1:28:16 PM)
+ *
+ * @param aRefObject
+ * org.eclipse.emf.ecore.EObject
+ */
+ public boolean add(EObject aRefObject) {
+ return add(aRefObject, null);
+ }
+
+ /**
+ * Insert the method's description here. Creation date: (12/17/2000 1:28:16 PM)
+ *
+ * @param aRefObject
+ * org.eclipse.emf.ecore.EObject
+ */
+ public boolean add(EObject aRefObject, String idSuffix) {
+ if (aRefObject != null && !containsRefObject(aRefObject)) {
+ getRefObjects().add(createAssociation(aRefObject, idSuffix));
+ return true;
+ }
+ return false;
+ }
+
+ /**
+ * Insert the method's description here. Creation date: (12/17/2000 1:27:32 PM)
+ *
+ * @param aResources
+ * org.eclipse.emf.ecore.resource.Resource
+ */
+ public void add(Resource aResource) {
+ add(aResource, null);
+ }
+
+ /**
+ * Insert the method's description here. Creation date: (12/17/2000 1:27:32 PM)
+ *
+ * @param aResources
+ * org.eclipse.emf.ecore.resource.Resource
+ */
+ public void add(Resource aResource, String newUri) {
+ if (aResource != null)
+ getResources().add(createAssociation(aResource, newUri));
+ }
+
+ /**
+ * Insert the method's description here. Creation date: (12/17/2000 1:28:16 PM)
+ *
+ * @param aRefObject
+ * org.eclipse.emf.ecore.EObject
+ */
+ public void addCopied(EObject aRefObject) {
+ if (aRefObject != null)
+ getCopiedRefObjects().add(aRefObject);
+ }
+
+ /**
+ * Insert the method's description here. Creation date: (12/17/2000 1:27:32 PM)
+ *
+ * @param aResources
+ * org.eclipse.emf.ecore.resource.Resource
+ */
+ public void addCopied(Resource aResource) {
+ if (aResource != null) {
+ getCopiedResources().add(aResource);
+ if (getCopyContext() != null)
+ getCopyContext().getResources().add(aResource);
+ }
+ }
+
+ protected boolean contains(List associations, Object anObject) {
+ if (anObject == null)
+ return false;
+ int size = associations.size();
+ Association assoc;
+ for (int i = 0; i < size; i++) {
+ assoc = (Association) associations.get(i);
+ if (assoc.getKey() == anObject)
+ return true;
+ }
+ return false;
+ }
+
+ /**
+ * Return true if
+ *
+ * @aRefObject has been added to this group. Creation date: (12/17/2000 1:28:16 PM)
+ * @param aRefObject
+ * org.eclipse.emf.ecore.EObject
+ */
+ public boolean containsRefObject(EObject aRefObject) {
+ return contains(getRefObjects(), aRefObject);
+ }
+
+ /**
+ * Return true if
+ *
+ * @aResource has been added to this group. Creation date: (12/17/2000 1:28:16 PM)
+ * @param aRefObject
+ * org.eclipse.emf.ecore.EObject
+ */
+ public boolean containsResource(Resource aResource) {
+ return contains(getResources(), aResource);
+ }
+
+ private Association createAssociation(Object key, Object value) {
+ return new Association(key, value);
+ }
+
+ /**
+ * Returns a List of RefObjects that were copied. Creation date: (12/17/2000 1:25:46 PM)
+ *
+ * @return java.util.List
+ */
+ public java.util.List getCopiedRefObjects() {
+ if (copiedRefObjects == null)
+ copiedRefObjects = new ArrayList();
+ return copiedRefObjects;
+ }
+
+ /**
+ * Returns a List of Resources that were copied. Creation date: (12/17/2000 1:25:46 PM)
+ *
+ * @return java.util.List
+ */
+ public java.util.List getCopiedResources() {
+ if (copiedResources == null)
+ copiedResources = new ArrayList();
+ return copiedResources;
+ }
+
+ /**
+ * The context to add all copied resources into. Creation date: (12/17/2000 8:09:45 PM)
+ *
+ * @return org.eclipse.emf.ecore.resource.ResourceSet
+ */
+ public org.eclipse.emf.ecore.resource.ResourceSet getCopyContext() {
+ return copyContext;
+ }
+
+ /**
+ * Insert the method's description here. Creation date: (12/17/2000 1:44:43 PM)
+ *
+ * @return java.lang.String
+ */
+ public java.lang.String getDefaultIdSuffix() {
+ return defaultIdSuffix;
+ }
+
+ /**
+ * Should the id be copied in the case where no suffix is specified? Defaults to false
+ */
+ public boolean getPreserveIds() {
+ return preserveIds;
+ }
+
+ /**
+ * Insert the method's description here. Creation date: (12/17/2000 1:25:46 PM)
+ *
+ * @return java.util.List
+ */
+ public java.util.List getRefObjects() {
+ if (refObjects == null)
+ refObjects = new ArrayList();
+ return refObjects;
+ }
+
+ /**
+ * Insert the method's description here. Creation date: (12/17/2000 1:25:46 PM)
+ *
+ * @return java.util.List
+ */
+ public java.util.List getResources() {
+ if (resources == null)
+ resources = new ArrayList();
+ return resources;
+ }
+
+ /**
+ * Insert the method's description here. Creation date: (12/17/2000 1:25:46 PM)
+ *
+ * @return java.util.List
+ */
+ public java.util.List primGetRefObjects() {
+ return refObjects;
+ }
+
+ /**
+ * Insert the method's description here. Creation date: (12/17/2000 1:25:46 PM)
+ *
+ * @return java.util.List
+ */
+ public java.util.List primGetResources() {
+ return resources;
+ }
+
+ /**
+ * Insert the method's description here. Creation date: (12/17/2000 1:28:16 PM)
+ *
+ * @param aRefObject
+ * org.eclipse.emf.ecore.EObject
+ * @return boolean
+ */
+ public boolean remove(EObject aRefObject) {
+ if (aRefObject != null && primGetRefObjects() != null) {
+ Iterator it = primGetRefObjects().iterator();
+ Association association;
+ while (it.hasNext()) {
+ association = (Association) it.next();
+ if (association.getKey() == aRefObject)
+ return primGetRefObjects().remove(association);
+ }
+ }
+ return false;
+ }
+
+ /**
+ * Insert the method's description here. Creation date: (12/17/2000 1:27:32 PM)
+ *
+ * @param aResources
+ * org.eclipse.emf.ecore.resource.Resource
+ * @return boolean
+ */
+ public boolean remove(Resource aResource) {
+ if (aResource != null && primGetResources() != null) {
+ Iterator it = primGetResources().iterator();
+ Association association;
+ while (it.hasNext()) {
+ association = (Association) it.next();
+ if (association.getKey() == aResource)
+ return primGetResources().remove(association);
+ }
+ }
+ return false;
+ }
+
+ /**
+ * Set the context to add all copied resources into. Creation date: (12/17/2000 8:09:45 PM)
+ *
+ * @param newCopyContext
+ * org.eclipse.emf.ecore.resource.Context
+ */
+ public void setCopyContext(org.eclipse.emf.ecore.resource.ResourceSet newCopyContext) {
+ copyContext = newCopyContext;
+ }
+
+ /**
+ * If an ID suffix is not defined for a EObject that is to be copied, this value will be used.
+ * Creation date: (12/17/2000 1:44:43 PM)
+ *
+ * @param newDefaultIdSuffix
+ * java.lang.String
+ */
+ public void setDefaultIdSuffix(java.lang.String newDefaultIdSuffix) {
+ defaultIdSuffix = newDefaultIdSuffix;
+ }
+
+ /**
+ * Should the id be copied in the case where no suffix is specified?
+ */
+ public void setPreserveIds(boolean value) {
+ preserveIds = value;
+ }
+
+ /**
+ * Subclasses should override this method if they require additional processing after the group
+ * has been copied.
+ *
+ * @param copyUtil
+ */
+ public void postCopy(EtoolsCopyUtility copyUtil) {
+ }
+
+}
+
diff --git a/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/utilities/DOMLoadOptions.java b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/utilities/DOMLoadOptions.java
new file mode 100644
index 0000000..05ae8a5
--- /dev/null
+++ b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/utilities/DOMLoadOptions.java
@@ -0,0 +1,80 @@
+/*******************************************************************************
+ * Copyright (c) 2003, 2004 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+/*
+ * Created on Mar 12, 2003
+ *
+ * To change this generated comment go to
+ * Window>Preferences>Java>Code Generation>Code and Comments
+ */
+package org.eclipse.wst.common.internal.emf.utilities;
+
+/**
+ * @author schacher
+ *
+ * To change this generated comment go to Window>Preferences>Java>Code Generation>Code and Comments
+ */
+public class DOMLoadOptions {
+ protected boolean validate;
+ protected boolean allowJavaEncodings;
+ protected boolean expandEntityRefererences;
+
+ /**
+ * @return boolean
+ */
+ public boolean isAllowJavaEncodings() {
+ return allowJavaEncodings;
+ }
+
+ /**
+ * @return boolean
+ */
+ public boolean isExpandEntityRefererences() {
+ return expandEntityRefererences;
+ }
+
+ /**
+ * @return boolean
+ */
+ public boolean isValidate() {
+ return validate;
+ }
+
+ /**
+ * Sets the allowJavaEncodings.
+ *
+ * @param allowJavaEncodings
+ * The allowJavaEncodings to set
+ */
+ public void setAllowJavaEncodings(boolean allowJavaEncodings) {
+ this.allowJavaEncodings = allowJavaEncodings;
+ }
+
+ /**
+ * Sets the expandEntityRefererences.
+ *
+ * @param expandEntityRefererences
+ * The expandEntityRefererences to set
+ */
+ public void setExpandEntityRefererences(boolean expandEntityRefererences) {
+ this.expandEntityRefererences = expandEntityRefererences;
+ }
+
+ /**
+ * Sets the validate.
+ *
+ * @param validate
+ * The validate to set
+ */
+ public void setValidate(boolean validate) {
+ this.validate = validate;
+ }
+
+}
\ No newline at end of file
diff --git a/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/utilities/DOMUtilities.java b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/utilities/DOMUtilities.java
new file mode 100644
index 0000000..44f9669
--- /dev/null
+++ b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/utilities/DOMUtilities.java
@@ -0,0 +1,703 @@
+/*******************************************************************************
+ * Copyright (c) 2003, 2006 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.wst.common.internal.emf.utilities;
+
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStreamWriter;
+import java.io.PrintWriter;
+import java.io.UnsupportedEncodingException;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+
+import javax.xml.parsers.DocumentBuilder;
+import javax.xml.parsers.DocumentBuilderFactory;
+import javax.xml.parsers.ParserConfigurationException;
+
+import org.eclipse.jem.util.logger.proxy.Logger;
+import org.w3c.dom.Document;
+import org.w3c.dom.Node;
+import org.w3c.dom.NodeList;
+import org.w3c.dom.Text;
+import org.xml.sax.EntityResolver;
+import org.xml.sax.ErrorHandler;
+import org.xml.sax.SAXException;
+import org.xml.sax.SAXParseException;
+
+/**
+ * A class containing common dom manipulation and search functions.
+ */
+public class DOMUtilities {
+ // Handy Constants
+ public static final String INDENT_STRING = "\t"; //$NON-NLS-1$
+ public static final String NEWLINE_STRING = System.getProperty("line.separator"); //$NON-NLS-1$
+ //Hack to be removed when the DOM apis change such that there is an easier
+ //way to fluff up and set the doctype
+ private static final String DUMMY_ENTITY_STRING = "dummy"; //$NON-NLS-1$
+ private static final String DUMMY_ENTITY_NODE_STRING = "<dummy/>"; //$NON-NLS-1$
+ private static DocumentBuilder defaultDocumentBuilder;
+ private static EntityResolver defaultEntityResolver;
+
+ /**
+ * Returns an iterator that iterates over the sub nodes of a path.
+ */
+ static public Iterator createPathIterator(String path) {
+ String tPath = path.startsWith("/") ? path.substring(1) : path; //$NON-NLS-1$
+ if (tPath.length() == 0)
+ tPath = null;
+ final String aPath = tPath;
+
+ return new Iterator() {
+ int prevIndex = 0;
+ int curIndex = 0;
+ String pathString = aPath;
+
+ public boolean hasNext() {
+ return pathString != null && prevIndex != -1;
+ }
+
+ public Object next() {
+ curIndex = pathString.indexOf('/', prevIndex);
+ String nodeString = null;
+ if (curIndex != -1)
+ nodeString = pathString.substring(prevIndex, curIndex++);
+ else
+ nodeString = pathString.substring(prevIndex);
+ prevIndex = curIndex;
+ return nodeString;
+ }
+
+ public void remove() {
+ throw new UnsupportedOperationException();
+ }
+ };
+ }
+
+ /**
+ * Get the text for the passed in node.
+ */
+ static public String getChildText(Node node) {
+ Text textNode = getChildTextNode(node);
+ if (textNode != null)
+ return textNode.getData();
+ return null;
+ }
+
+ /**
+ * Get the text for the passed in node.
+ */
+ static public Text getChildTextNode(Node node) {
+ Node textNode = node.getFirstChild();
+ while (textNode != null && DOMUtilities.isTextNode(textNode)) {
+ if (!isWhitespace(textNode))
+ return (Text) textNode;
+ textNode = textNode.getNextSibling();
+ }
+ return null;
+ }
+
+ /**
+ * Return a string representing the current indentation of the node.
+ */
+ static public String getIndentString(Node node) {
+ Revisit.toDo();
+ return ""; //$NON-NLS-1$
+ }
+
+ /**
+ * Get the last non-text child of a node.
+ *
+ * @return org.w3c.dom.Node The last non-text child node of
+ * @node.
+ * @param node
+ * org.w3c.dom.Node The node
+ */
+ public static Node getLastNodeChild(Node node) {
+ if (node == null)
+ return null;
+ Node child = node.getLastChild();
+ while (child != null && child.getNodeType() == Node.TEXT_NODE)
+ child = child.getPreviousSibling();
+ return child;
+ }
+
+ /**
+ * Get the next non-text sibling after a node.
+ *
+ * @return org.w3c.dom.Node The first non-text sibling node after
+ * @node. If there is no next non-text sibling, null is returned.
+ * @param node
+ * org.w3c.dom.Node The node
+ */
+ public static Node getNextNodeSibling(Node node) {
+ Node sibling = node.getNextSibling();
+ while (sibling != null && sibling.getNodeType() != Node.ELEMENT_NODE)
+ sibling = sibling.getNextSibling();
+ return sibling;
+ }
+
+ /**
+ * Get the first child Node with the specified name
+ */
+ static public Node getNodeChild(Node node, String nodeName) {
+ Node child = null;
+ NodeList children = node.getChildNodes();
+ for (int i = 0; i < children.getLength(); i++) {
+ Node n = children.item(i);
+ if (n.getNodeType() == Node.ELEMENT_NODE && n.getNodeName().equals(nodeName)) {
+ child = n;
+ break;
+ }
+ }
+ return child;
+ }
+
+ /**
+ * Traverses the path passed in <pathName>. The path is a string in the form
+ * 'node1/node2/node3'. This method starts at node.
+ */
+ static public Node getNodeChildForPath(Node parent, String pathName) {
+
+ Node curNode = parent;
+ Iterator i = DOMUtilities.createPathIterator(pathName);
+ while (i.hasNext()) {
+ String child = (String) i.next();
+ curNode = DOMUtilities.getNodeChild(curNode, child);
+ if (curNode == null)
+ return null;
+ }
+ return curNode;
+ }
+
+ /**
+ * Get the Node children with the specified names
+ */
+ static public List getNodeChildren(Node node, String[] nodeNames) {
+ NodeList childNodes = node.getChildNodes();
+ ArrayList results = new ArrayList();
+
+ for (int i = 0; i < childNodes.getLength(); i++) {
+ Node n = childNodes.item(i);
+ if (n.getNodeType() == Node.ELEMENT_NODE) {
+ boolean found = false;
+ for (int j = 0; j < nodeNames.length; j++) {
+ if (nodeNames[j].equals(n.getNodeName())) {
+ found = true;
+ break;
+ }
+ }
+ if (found)
+ results.add(n);
+ }
+ }
+ return results;
+ }
+
+ /**
+ * Get the Node children with the specified name
+ */
+ static public List getNodeChildren(Node node, String nodeName) {
+ NodeList childNodes = node.getChildNodes();
+ ArrayList results = new ArrayList();
+
+ for (int i = 0; i < childNodes.getLength(); i++) {
+ Node n = childNodes.item(i);
+ if (n.getNodeType() == Node.ELEMENT_NODE && n.getNodeName().equals(nodeName))
+ results.add(n);
+ }
+ return results;
+ }
+
+ /**
+ * Get the first non-text sibling before a node.
+ *
+ * @return org.w3c.dom.Node The first non-text sibling node before
+ * @node. If there is no previous non-text sibling, null is returned.
+ * @param node
+ * org.w3c.dom.Node The node
+ */
+ public static Node getPreviousNodeSibling(Node node) {
+ if (node == null)
+ return null;
+ Node sibling = node.getPreviousSibling();
+ while (sibling != null && DOMUtilities.isTextNode(sibling))
+ sibling = sibling.getPreviousSibling();
+ return sibling;
+ }
+
+ /**
+ * Get the first text node before a node.
+ *
+ * @return org.w3c.dom.Node The first text node before
+ * @node. Null if no such node exist.
+ * @param node
+ * org.w3c.dom.Node The node
+ */
+ public static Text getPreviousText(Node node) {
+ Text sibling = getPreviousTextSibling(node);
+
+ if (sibling == null && node.getParentNode() != null)
+ sibling = getPreviousText(node.getParentNode());
+
+ return sibling;
+ }
+
+ /**
+ * Get the first text sibling before a node.
+ *
+ * @return org.w3c.dom.Node The first text sibling node before
+ * @node. If there is no previous text sibling, null is returned.
+ * @param node
+ * org.w3c.dom.Node The node
+ */
+ public static Text getPreviousTextSibling(Node node) {
+ Assert.isNotNull(node);
+
+ Node sibling = node.getPreviousSibling();
+ Node lastText = null;
+ while (sibling != null && sibling.getNodeType() == Node.TEXT_NODE) {
+ lastText = sibling;
+ sibling = sibling.getPreviousSibling();
+ }
+ return (Text) lastText;
+ }
+
+ /**
+ * Get the first text sibling before a node.
+ *
+ * @return org.w3c.dom.Node The first text sibling node before
+ * @node. If there is no previous text sibling, null is returned.
+ * @param node
+ * org.w3c.dom.Node The node
+ */
+ public static String getTrailingWhitespace(Text node) {
+ Assert.isNotNull(node);
+
+ String text = node.getData();
+ if (text.length() == 0)
+ return ""; //$NON-NLS-1$
+
+ int i = text.length() - 1;
+ for (; i >= 0; i--) {
+ if (!Character.isWhitespace(text.charAt(i))) {
+ break;
+ }
+ }
+
+ return text.substring(++i);
+ }
+
+ /**
+ * Inserts <newNode>into <parent>after <refNode>. If <refNode>is null then the node is inserted
+ * to the beginning of the parent's child nodes.
+ *
+ * @param parent
+ * org.w3c.dom.Node
+ * @param newNode
+ * org.w3c.dom.Node
+ * @param refNode
+ * org.w3c.dom.Node
+ */
+ public static void insertAfterNode(Node parent, Node newNode, Node refNode) {
+ Node insertBeforeNode = null;
+ if (refNode != null) {
+ insertBeforeNode = refNode.getNextSibling();
+ }
+ if (refNode == null)
+ insertBeforeNode(parent, newNode, parent.getFirstChild());
+ else
+ insertBeforeNode(parent, newNode, insertBeforeNode);
+ }
+
+ /**
+ * Insert a <newNode>into <parent>before <refNode>. This utility method is used to ensure that
+ * the insertion does not result in two adjacent text nodes. The DOM model does not handle
+ * adjacent text nodes. They must be joined together.
+ *
+ * @param newNode
+ * org.w3c.dom.Node
+ * @param newNode
+ * org.w3c.dom.Node
+ * @param refNode
+ * org.w3c.dom.Node
+ */
+ static public void insertBeforeNode(Node parent, Node newNode, Node refNode) {
+ if (newNode.getNodeType() == Node.TEXT_NODE) {
+ Text textNewNode = (Text) newNode;
+
+ // If the insert before node is text, join it with the new node.
+ if (refNode != null && refNode.getNodeType() == Node.TEXT_NODE) {
+ Text textRefNode = (Text) refNode;
+ textRefNode.setData(textNewNode.getData() + textRefNode.getData());
+ return;
+ }
+ // If the node we are inserting after is text,
+ // join it with the new node.
+ Node insertAfterNode = (refNode == null) ? parent.getLastChild() : refNode.getPreviousSibling();
+ if (insertAfterNode != null && insertAfterNode.getNodeType() == Node.TEXT_NODE) {
+ Text textInsertAfterNode = (Text) insertAfterNode;
+ textInsertAfterNode.setData(textInsertAfterNode.getData() + textNewNode.getData());
+ return;
+ }
+ }
+ // There is no text node to join to, simple insert the node.
+ parent.insertBefore(newNode, refNode);
+ }
+
+ /**
+ * Insert a <newNode>into <parent>before <refNode>. This method will also insert the node before
+ * any whitespace nodes that appear in the tree before <refNode>. This method will also ensure
+ * that the insertion does not result in two adjacent text nodes. The DOM model does not handle
+ * adjacent text nodes. They must be joined together.
+ *
+ * @param newNode
+ * org.w3c.dom.Node
+ * @param newNode
+ * org.w3c.dom.Node
+ * @param refNode
+ * org.w3c.dom.Node
+ */
+ static public void insertBeforeNodeAndWhitespace(Node parent, Node newNode, Node refNode) {
+ Node curNode = (refNode == null) ? parent.getLastChild() : refNode.getPreviousSibling();
+ Node lastNode = refNode;
+
+ while (curNode != null && (DOMUtilities.isWhitespace(curNode) || DOMUtilities.isComment(curNode))) {
+ lastNode = curNode;
+ curNode = curNode.getPreviousSibling();
+ }
+
+ insertBeforeNode(parent, newNode, lastNode);
+ }
+
+ /**
+ * Return whether the node is a text node.
+ *
+ * @return boolean Answer true if the node is a text node, false otherwise.
+ * @param node
+ * org.w3c.dom.Node The node to check
+ */
+ static public boolean isTextNode(Node node) {
+ Assert.isNotNull(node);
+ return (node.getNodeType() == Node.TEXT_NODE) || (node.getNodeType() == Node.CDATA_SECTION_NODE);
+ }
+
+ /**
+ * Return whether the node is entirely comment or not.
+ *
+ * @return boolean Answer true if the node is whitespace, false otherwise.
+ * @param node
+ * org.w3c.dom.Node The node to check
+ */
+ static public boolean isComment(Node node) {
+ Assert.isNotNull(node);
+
+ return node.getNodeType() == Node.COMMENT_NODE;
+ }
+
+ /**
+ * Return whether the node is entirely whitepace or not.
+ *
+ * @return boolean Answer true if the node is whitespace, false otherwise.
+ * @param node
+ * org.w3c.dom.Node The node to check
+ */
+ static public boolean isWhitespace(Node node) {
+ Assert.isNotNull(node);
+
+ if (node.getNodeType() != Node.TEXT_NODE)
+ return false;
+
+ Text textNode = (Text) node;
+ String text = textNode.getData();
+ if (text == null)
+ return false;
+
+ for (int i = 0; i < text.length(); i++) {
+ if (!Character.isWhitespace(text.charAt(i))) {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ /**
+ * Remove all the children of <node>
+ */
+ static public void removeAllChildren(Node node) {
+ NodeList list = node.getChildNodes();
+ for (int i = 0; i < list.getLength(); i++) {
+ node.removeChild(list.item(i));
+ }
+ }
+
+ // traverses the DOM starting at the specified node and returns a list
+ // of nodes matching the search string
+
+ static public ArrayList getAllNodes(Node node, String nodeName) {
+ ArrayList nodeList = new ArrayList();
+
+ String[] nodeNames = {nodeName};
+ findAllNodes(node, nodeNames, nodeList);
+
+ return nodeList;
+ }
+
+ // traverses the DOM starting at the specified node and returns a list
+ // of nodes matching the search strings
+
+ static public ArrayList getAllNodes(Node node, String[] nodeNamesArray) {
+ ArrayList nodeList = new ArrayList();
+ findAllNodes(node, nodeNamesArray, nodeList);
+
+ return nodeList;
+ }
+
+ // recursive helper for getAllNodes
+ static private void findAllNodes(Node node, String[] nodeNames, ArrayList results) {
+
+ NodeList nodes = node.getChildNodes();
+ if (nodes != null) {
+ for (int i = 0; i < nodes.getLength(); i++) {
+ for (int j = 0; j < nodeNames.length; j++) {
+ if (nodes.item(i).getNodeName().equals(nodeNames[j])) {
+ results.add(nodes.item(i));
+ }
+ }
+ findAllNodes(nodes.item(i), nodeNames, results);
+ }
+ }
+ }
+
+ /**
+ * Returns the system defined JAXP document builder
+ */
+ static public DocumentBuilder newDefaultDocumentBuilder(DOMLoadOptions options) throws ParserConfigurationException {
+ DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
+ dbf.setValidating(options.isValidate());
+ dbf.setNamespaceAware(options.isValidate());
+ /*
+ * Causes errors in IBM JDK try { dbf.setAttribute(Renderer.JAXP_SCHEMA_LANGUAGE,
+ * Renwderer.W3C_XML_SCHEMA); } catch (IllegalArgumentException x) { }
+ */
+ try {
+ dbf.setAttribute("http://apache.org/xml/features/allow-java-encodings", new Boolean(options.isAllowJavaEncodings())); //$NON-NLS-1$
+ } catch (IllegalArgumentException ignore) {
+ Logger.getLogger().log("Warning: Parser does not support \"http://apache.org/xml/features/allow-java-encodings\"."); //$NON-NLS-1$
+ }
+ try {
+ dbf.setAttribute("http://apache.org/xml/features/validation/schema", new Boolean(options.isValidate())); //$NON-NLS-1$
+ } catch (IllegalArgumentException ignore) {
+ dbf.setValidating(false);
+ Logger.getLogger().log("Warning: Parser does not support \"http://apache.org/xml/features/validation/schema\". Validation will be disabled."); //$NON-NLS-1$
+ }
+ dbf.setExpandEntityReferences(options.isExpandEntityRefererences());
+ DocumentBuilder result = dbf.newDocumentBuilder();
+ result.setErrorHandler(new ErrorHandler() {
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.xml.sax.ErrorHandler#error(org.xml.sax.SAXParseException)
+ */
+ public void error(SAXParseException arg0) throws SAXException {
+ throw arg0;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.xml.sax.ErrorHandler#fatalError(org.xml.sax.SAXParseException)
+ */
+ public void fatalError(SAXParseException arg0) throws SAXException {
+ throw arg0;
+ }
+
+ public void warning(SAXParseException arg0) throws SAXException {
+ Logger.getLogger().logWarning(arg0);
+ }
+
+ });
+ return result;
+ }
+
+ /**
+ * Creates a stub document, where the DocumentType is defined by the parameters.
+ */
+ static public Document createNewDocument(String doctype, String publicId, String systemId) throws ParserConfigurationException, SAXException, IOException {
+ DocumentBuilder builder = getDefaultDocumentBuilder();
+ InputStream in = createHeaderInputStream(doctype, publicId, systemId, true);
+ Document result = builder.parse(in);
+ removeDummyEntity(result);
+ removeExtraneousComments(result);
+ return result;
+ }
+
+ public static Document loadDocument(InputStream in, DOMLoadOptions options, EntityResolver resolver) throws ParserConfigurationException, SAXException, IOException {
+ DocumentBuilder builder = DOMUtilities.newDefaultDocumentBuilder(options);
+ builder.setEntityResolver(resolver);
+ Document result = builder.parse(in);
+ removeExtraneousComments(result);
+ return result;
+ }
+
+ /**
+ * At the time of this writing, the DOM Level 2 APIs are not advanced enough for setting the
+ * document type; so the only parser independent way of accomplishing this is by creating a
+ * stream and parsing it.
+ */
+ public static InputStream createHeaderInputStream(String doctype, String publicId, String systemId) {
+ return createHeaderInputStream(doctype, publicId, systemId, false);
+ }
+
+
+
+ private static InputStream createHeaderInputStream(String doctype, String publicId, String systemId, boolean includeDummy) {
+ ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
+
+ // The prior code (which is still in the catch block), uses
+ // the system default encoding [System.getProperty("file.encoding")];
+ // on Z/OS this is Cp1047. The combination of "UTF-8" in the header
+ // and "Cp1047" in the writer create an unusable input stream.
+
+ PrintWriter writer;
+
+ try {
+ OutputStreamWriter outputWriter = new OutputStreamWriter(outputStream, "UTF-8"); //$NON-NLS-1$
+ // throws UnsupportedEncodingException
+ writer = new PrintWriter(outputWriter);
+ } catch (UnsupportedEncodingException e) {
+ // Should never get here (earlier code)
+ writer = new PrintWriter(outputStream);
+ }
+
+ writeHeader(writer, doctype, publicId, systemId);
+ if (includeDummy)
+ addDummyEntity(writer);
+ writer.flush();
+ writer.close();
+
+ byte[] bytes = outputStream.toByteArray();
+ return new ByteArrayInputStream(bytes);
+ }
+
+
+ private static void writeHeader(PrintWriter writer, String doctype, String publicId, String systemId) {
+ writer.write("<?xml version=\""); //$NON-NLS-1$
+ writer.write("1.0"); //$NON-NLS-1$
+ writer.write("\" encoding=\""); //$NON-NLS-1$
+ writer.write("UTF-8"); //$NON-NLS-1$
+ writer.write("\"?>"); //$NON-NLS-1$
+ writer.println();
+
+ if (doctype != null) {
+ writer.write("<!DOCTYPE "); //$NON-NLS-1$
+ writer.write(doctype);
+ writer.write(" PUBLIC \""); //$NON-NLS-1$
+ writer.write(publicId);
+ writer.write("\" \""); //$NON-NLS-1$
+ writer.write(systemId);
+ writer.write("\">"); //$NON-NLS-1$
+ writer.println();
+ }
+ }
+
+ private static void addDummyEntity(PrintWriter writer) {
+ Revisit.revisit();
+ writer.println(DUMMY_ENTITY_NODE_STRING);
+ //Major hack because we can not parse an empty document
+ }
+
+ private static void removeDummyEntity(Document doc) {
+ doc.removeChild(getNodeChild(doc, DUMMY_ENTITY_STRING));
+ }
+
+ private static void removeExtraneousComments(Document doc) {
+ //another major hack because of a bug in XML4J 4.0.7 that added all the
+ //comments from the dtd to the document. Can be removed after we move up
+ //Xerces levels
+ Node aNode = doc.getFirstChild();
+ while (aNode != null) {
+ Node nextNode = aNode.getNextSibling();
+ if (aNode.getNodeType() == Node.COMMENT_NODE)
+ doc.removeChild(aNode);
+ aNode = nextNode;
+ }
+ }
+
+ /**
+ * For performance, cache a static instance of the JAXP registered document builder. Validation
+ * is disabled for this instance. If you need validation, use
+ * {@link #newDefaultDocumentBuilder(boolean, boolean, boolean)}
+ *
+ * @return DocumentBuilder
+ * @throws ParserConfigurationException
+ * if JAXP is not configured correctly
+ */
+ public static DocumentBuilder getDefaultDocumentBuilder() throws ParserConfigurationException {
+ if (defaultDocumentBuilder == null) {
+ DOMLoadOptions opts = new DOMLoadOptions();
+ opts.setAllowJavaEncodings(true);
+ opts.setExpandEntityRefererences(true);
+ opts.setValidate(false);
+ defaultDocumentBuilder = newDefaultDocumentBuilder(opts);
+ defaultDocumentBuilder.setEntityResolver(defaultEntityResolver);
+ defaultDocumentBuilder.setErrorHandler(new ErrorHandler() {
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.xml.sax.ErrorHandler#error(org.xml.sax.SAXParseException)
+ */
+ public void error(SAXParseException exception) throws SAXException {
+
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.xml.sax.ErrorHandler#fatalError(org.xml.sax.SAXParseException)
+ */
+ public void fatalError(SAXParseException exception) throws SAXException {
+
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.xml.sax.ErrorHandler#warning(org.xml.sax.SAXParseException)
+ */
+ public void warning(SAXParseException exception) throws SAXException {
+
+ }
+
+ });
+ }
+
+ return defaultDocumentBuilder;
+ }
+
+ /**
+ * @return
+ */
+ public static EntityResolver getDefaultEntityResolver() {
+ return defaultEntityResolver;
+ }
+
+ /**
+ * @param resolver
+ */
+ public static void setDefaultEntityResolver(EntityResolver resolver) {
+ defaultEntityResolver = resolver;
+ }
+
+}
diff --git a/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/utilities/DanglingHREFException.java b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/utilities/DanglingHREFException.java
new file mode 100644
index 0000000..debd006
--- /dev/null
+++ b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/utilities/DanglingHREFException.java
@@ -0,0 +1,35 @@
+/*******************************************************************************
+ * Copyright (c) 2003, 2005 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+/*
+ * Created on May 12, 2003
+ *
+ */
+package org.eclipse.wst.common.internal.emf.utilities;
+
+/**
+ * Exception thrown when a proxy can not be resolved
+ */
+public class DanglingHREFException extends Exception {
+
+
+ public DanglingHREFException() {
+ super();
+ }
+
+ /**
+ * @param s
+ */
+ public DanglingHREFException(String s) {
+ super(s);
+ }
+
+
+}
diff --git a/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/utilities/DefaultFeatureValueConverter.java b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/utilities/DefaultFeatureValueConverter.java
new file mode 100644
index 0000000..ea56697
--- /dev/null
+++ b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/utilities/DefaultFeatureValueConverter.java
@@ -0,0 +1,354 @@
+/*******************************************************************************
+ * Copyright (c) 2003, 2007 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.wst.common.internal.emf.utilities;
+
+
+
+import org.eclipse.emf.ecore.EAttribute;
+import org.eclipse.emf.ecore.EClassifier;
+import org.eclipse.emf.ecore.EEnum;
+import org.eclipse.emf.ecore.EEnumLiteral;
+import org.eclipse.emf.ecore.EObject;
+import org.eclipse.emf.ecore.EStructuralFeature;
+import org.eclipse.emf.ecore.EcorePackage;
+import org.eclipse.emf.ecore.xml.type.XMLTypePackage;
+
+/**
+ * Insert the type's description here. Creation date: (5/10/2001 2:49:49 PM)
+ *
+ * @author: Administrator
+ */
+public class DefaultFeatureValueConverter implements FeatureValueConverter {
+ private static final String FAILED_CONVERSION_PATTERN = WFTUtilsResourceHandler.Failed_to_convert__0__to___ERROR_;
+
+ /**
+ * DefaultFeatureValueConverter constructor comment.
+ */
+ public DefaultFeatureValueConverter() {
+ super();
+ }
+
+ /**
+ * Convert
+ *
+ * @aValue to a Boolean.
+ */
+ protected Object convertToBoolean(Object aValue) {
+ if (aValue instanceof String)
+ return Boolean.valueOf((String) aValue);
+ if (aValue instanceof Boolean)
+ return aValue;
+ return failedToConvert(aValue, WFTUtilsResourceHandler.Boolean_UI_);
+ }
+
+ /**
+ * Convert
+ *
+ * @aValue to a Byte.
+ */
+ protected Object convertToByte(Object aValue) {
+ if (aValue instanceof String)
+ return Byte.valueOf((String) aValue);
+ if (aValue instanceof Byte)
+ return aValue;
+ return failedToConvert(aValue, WFTUtilsResourceHandler.Byte_UI_);
+ }
+
+ /**
+ * Convert
+ *
+ * @aValue to a Character.
+ */
+ protected Object convertToCharacter(Object aValue) {
+ if (aValue instanceof String && ((String) aValue).length() == 1)
+ return new Character(((String) aValue).charAt(0));
+ if (aValue instanceof Character)
+ return aValue;
+ return failedToConvert(aValue, WFTUtilsResourceHandler.Character_UI_);
+ }
+
+ /**
+ * Convert
+ *
+ * @aValue to a Double.
+ */
+ protected Object convertToDouble(Object aValue) {
+ if (aValue instanceof String) {
+ try {
+ return Double.valueOf((String) aValue);
+ } catch (NumberFormatException e) {
+ return defaultDouble();
+ }
+ }
+ if (aValue instanceof Double)
+ return aValue;
+ return failedToConvert(aValue, WFTUtilsResourceHandler.Double_UI_);
+ }
+
+ /**
+ * Convert
+ *
+ * @aValue to a EEnumLiteral.
+ */
+ protected Object convertToEnum(Object aValue, EStructuralFeature aFeature) {
+ EEnumLiteral literal = null;
+ EEnum eenum = (EEnum) aFeature.getEType();
+ if (aValue instanceof String)
+ literal = eenum.getEEnumLiteral((String) aValue);
+ else if (aValue instanceof Integer)
+ literal = eenum.getEEnumLiteral(((Integer) aValue).intValue());
+ else if (aValue instanceof EEnumLiteral)
+ literal = (EEnumLiteral) aValue;
+
+ if (literal == null)
+ return failedToConvert(aValue, WFTUtilsResourceHandler.Enumeration_UI_);
+
+ return literal.getInstance();
+ }
+
+ /**
+ * Convert
+ *
+ * @aValue to a Float.
+ */
+ protected Object convertToFloat(Object aValue) {
+ if (aValue instanceof String) {
+ try {
+ return Float.valueOf((String) aValue);
+ } catch (NumberFormatException e) {
+ return defaultFloat();
+ }
+ }
+ if (aValue instanceof Float)
+ return aValue;
+ return failedToConvert(aValue, WFTUtilsResourceHandler.Float_UI_);
+ }
+
+ /**
+ * Convert
+ *
+ * @aValue to a Integer.
+ */
+ protected Object convertToInteger(Object aValue) {
+ if (aValue instanceof String) {
+ try {
+ return Integer.valueOf((String) aValue);
+ } catch (NumberFormatException e) {
+ return defaultInteger();
+ }
+ }
+ if (aValue instanceof Integer)
+ return aValue;
+ return failedToConvert(aValue, WFTUtilsResourceHandler.Integer_UI_);
+ }
+
+ /**
+ * Convert
+ *
+ * @aValue to a Java Object.
+ */
+ protected Object convertToJavaObject(Object aValue) {
+ return aValue;
+ }
+
+ /**
+ * Convert
+ *
+ * @aValue to a Long.
+ */
+ protected Object convertToLong(Object aValue) {
+ if (aValue instanceof String) {
+ try {
+ return Long.valueOf((String) aValue);
+ } catch (NumberFormatException e) {
+ return defaultLong();
+ }
+ }
+ if (aValue instanceof Long)
+ return aValue;
+ return failedToConvert(aValue, WFTUtilsResourceHandler.Long_UI_);
+ }
+
+ /**
+ * Convert
+ *
+ * @aValue to a MofObject.
+ */
+ protected Object convertToMofObject(Object aValue) {
+ if (aValue instanceof EObject)
+ return aValue;
+ return failedToConvert(aValue, WFTUtilsResourceHandler.MofObject_UI_);
+ }
+
+ /**
+ * Convert
+ *
+ * @aValue to a Short.
+ */
+ protected Object convertToShort(Object aValue) {
+ if (aValue instanceof String) {
+ try {
+ return Short.valueOf((String) aValue);
+ } catch (NumberFormatException e) {
+ return defaultShort();
+ }
+ }
+ if (aValue instanceof Short)
+ return aValue;
+ return failedToConvert(aValue, WFTUtilsResourceHandler.Short_UI_);
+ }
+
+ /**
+ * Convert
+ *
+ * @aValue to a String.
+ */
+ protected Object convertToString(Object aValue) {
+ return aValue.toString();
+ }
+
+ /**
+ * Convert
+ *
+ * @aValue to the type of
+ * @anAttribute.
+ */
+ protected Object convertValue(Object aValue, org.eclipse.emf.ecore.EAttribute anAttribute) {
+
+ EClassifier meta = anAttribute.getEType();
+ if (meta.eClass() == EcorePackage.eINSTANCE.getEEnum())
+ return convertToEnum(aValue, anAttribute);
+ if (meta.getEPackage() instanceof EcorePackage)
+ {
+ switch (meta.getClassifierID()) {
+ case EcorePackage.ESTRING :
+ return convertToString(aValue);
+ case EcorePackage.EBOOLEAN_OBJECT :
+ case EcorePackage.EBOOLEAN :
+ return convertToBoolean(aValue);
+ case EcorePackage.EINTEGER_OBJECT :
+ case EcorePackage.EINT :
+ return convertToInteger(aValue);
+ case EcorePackage.EFLOAT_OBJECT :
+ case EcorePackage.EFLOAT :
+ return convertToFloat(aValue);
+ case EcorePackage.ECHARACTER_OBJECT :
+ case EcorePackage.ECHAR :
+ return convertToCharacter(aValue);
+ case EcorePackage.ELONG_OBJECT :
+ case EcorePackage.ELONG :
+ return convertToLong(aValue);
+ case EcorePackage.EBYTE_OBJECT :
+ case EcorePackage.EBYTE :
+ return convertToByte(aValue);
+ case EcorePackage.EDOUBLE_OBJECT :
+ case EcorePackage.EDOUBLE :
+ return convertToDouble(aValue);
+ case EcorePackage.ESHORT_OBJECT :
+ case EcorePackage.ESHORT :
+ return convertToShort(aValue);
+ // case EcorePackage.EENUM:
+ // return convertToEnum(aValue, anAttribute);
+ case EcorePackage.EOBJECT :
+ return convertToMofObject(aValue);
+ case EcorePackage.EJAVA_OBJECT :
+ return convertToJavaObject(aValue);
+ }
+ }
+ else if (meta.getEPackage() instanceof XMLTypePackage)
+ {
+ switch (meta.getClassifierID()) {
+ case XMLTypePackage.STRING :
+ return convertToString(aValue);
+ case XMLTypePackage.BOOLEAN_OBJECT :
+ case XMLTypePackage.BOOLEAN :
+ return convertToBoolean(aValue);
+ case XMLTypePackage.INT_OBJECT :
+ case XMLTypePackage.INTEGER :
+ case XMLTypePackage.INT :
+ return convertToInteger(aValue);
+ case XMLTypePackage.FLOAT_OBJECT :
+ case XMLTypePackage.FLOAT :
+ return convertToFloat(aValue);
+ case XMLTypePackage.LONG_OBJECT :
+ case XMLTypePackage.LONG :
+ return convertToLong(aValue);
+ case XMLTypePackage.BYTE_OBJECT :
+ case XMLTypePackage.BYTE :
+ return convertToByte(aValue);
+ case XMLTypePackage.DOUBLE_OBJECT :
+ case XMLTypePackage.DOUBLE :
+ return convertToDouble(aValue);
+ case XMLTypePackage.SHORT_OBJECT :
+ case XMLTypePackage.SHORT :
+ return convertToShort(aValue);
+ }
+ }
+ return aValue;
+ }
+
+ /**
+ * Convert
+ *
+ * @aValue to the type of
+ * @aFeature.
+ */
+ public Object convertValue(Object aValue, org.eclipse.emf.ecore.EStructuralFeature aFeature) {
+ if (aValue == null || aFeature == null || !(aFeature instanceof EAttribute))
+ return aValue; //nothing to convert
+ return convertValue(aValue, (EAttribute) aFeature);
+ }
+
+ /**
+ * Return the default Double value.
+ */
+ protected Double defaultDouble() {
+ return null;
+ }
+
+ /**
+ * Return the default Float value.
+ */
+ protected Float defaultFloat() {
+ return null;
+ }
+
+ /**
+ * Return the default Integer value.
+ */
+ protected Integer defaultInteger() {
+ return null;
+ }
+
+ /**
+ * Return the default Long value.
+ */
+ protected Long defaultLong() {
+ return null;
+ }
+
+ /**
+ * Return the default Short value.
+ */
+ protected Short defaultShort() {
+ return null;
+ }
+
+ /**
+ * Failed to convert
+ *
+ * @aValue.
+ */
+ protected Object failedToConvert(Object aValue, String aString) {
+ String errorString = java.text.MessageFormat.format(FAILED_CONVERSION_PATTERN, new String[]{aValue.toString(), aString});
+ throw new FeatureValueConversionException(errorString);
+ }
+}
diff --git a/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/utilities/DefaultOverridableResourceFactoryRegistry.java b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/utilities/DefaultOverridableResourceFactoryRegistry.java
new file mode 100644
index 0000000..927c0a4
--- /dev/null
+++ b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/utilities/DefaultOverridableResourceFactoryRegistry.java
@@ -0,0 +1,75 @@
+/*******************************************************************************
+ * Copyright (c) 2003, 2007 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+/*
+ * Created on Mar 14, 2003
+ *
+ * To change this generated comment go to
+ * Window>Preferences>Java>Code Generation>Code and Comments
+ */
+package org.eclipse.wst.common.internal.emf.utilities;
+
+import org.eclipse.emf.common.util.URI;
+import org.eclipse.emf.ecore.resource.Resource;
+import org.eclipse.emf.ecore.resource.Resource.Factory;
+import org.eclipse.emf.ecore.resource.impl.ResourceFactoryRegistryImpl;
+
+/**
+ * @author DABERG
+ *
+ * To change this generated comment go to Window>Preferences>Java>Code Generation>Code and Comments
+ */
+public class DefaultOverridableResourceFactoryRegistry extends ResourceFactoryRegistryImpl {
+ protected static Resource.Factory GLOBAL_FACTORY = Resource.Factory.Registry.INSTANCE.getFactory(URI.createURI(DEFAULT_EXTENSION));
+
+ /**
+ *
+ */
+ public DefaultOverridableResourceFactoryRegistry() {
+ super();
+ }
+
+ public Resource.Factory getFactory(URI uri) {
+ return getFactory(uri, null);
+ }
+
+ public Resource.Factory getFactory(URI uri, String contentType)
+ {
+ Object resourceFactory = null;
+ if (resourceFactory == null) {
+ String protocol = uri.scheme();
+ resourceFactory = protocolToFactoryMap.get(protocol);
+ if (resourceFactory == null) {
+ String extension = uri.fileExtension();
+ resourceFactory = extensionToFactoryMap.get(extension);
+ if (resourceFactory == null) {
+ resourceFactory = delegatedGetFactory(uri);
+ if (resourceFactory == GLOBAL_FACTORY) {
+ resourceFactory = extensionToFactoryMap.get(Resource.Factory.Registry.DEFAULT_EXTENSION);
+ if (resourceFactory == null)
+ resourceFactory = GLOBAL_FACTORY;
+ }
+
+ }
+ }
+ }
+
+ return resourceFactory instanceof Resource.Factory.Descriptor ? ((Resource.Factory.Descriptor) resourceFactory).createFactory() : (Resource.Factory) resourceFactory;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.eclipse.emf.ecore.resource.impl.ResourceFactoryRegistryImpl#delegatedGetFactory(org.eclipse.emf.common.util.URI)
+ */
+ protected Factory delegatedGetFactory(URI uri) {
+ return Resource.Factory.Registry.INSTANCE.getFactory(uri);
+ }
+}
diff --git a/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/utilities/DeferredReferenceUtilityAction.java b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/utilities/DeferredReferenceUtilityAction.java
new file mode 100644
index 0000000..ec1f668
--- /dev/null
+++ b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/utilities/DeferredReferenceUtilityAction.java
@@ -0,0 +1,75 @@
+/*******************************************************************************
+ * Copyright (c) 2003, 2004 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.wst.common.internal.emf.utilities;
+
+import org.eclipse.emf.ecore.EObject;
+import org.eclipse.emf.ecore.EReference;
+
+/**
+ * Insert the type's description here. Creation date: (12/15/2000 5:25:43 PM)
+ *
+ * @author: Administrator
+ */
+public abstract class DeferredReferenceUtilityAction {
+ protected EReference reference;
+ protected Object referenceValue;
+ protected EObject copyContainer;
+ protected String idSuffix;
+
+ /**
+ * DeferredCopy constructor comment.
+ */
+ public DeferredReferenceUtilityAction(EReference aReference, Object aValue, String aSuffix, EObject aCopyContainer) {
+ reference = aReference;
+ referenceValue = aValue;
+ idSuffix = aSuffix;
+ copyContainer = aCopyContainer;
+ }
+
+ /**
+ * Insert the method's description here. Creation date: (12/16/2000 9:32:28 AM)
+ *
+ * @return org.eclipse.emf.ecore.EObject
+ */
+ public org.eclipse.emf.ecore.EObject getCopyContainer() {
+ return copyContainer;
+ }
+
+ /**
+ * Insert the method's description here. Creation date: (12/15/2000 5:34:56 PM)
+ *
+ * @return java.lang.String
+ */
+ public java.lang.String getIdSuffix() {
+ return idSuffix;
+ }
+
+ /**
+ * Insert the method's description here. Creation date: (12/15/2000 5:34:56 PM)
+ *
+ * @return org.eclipse.emf.ecore.EReference
+ */
+ public org.eclipse.emf.ecore.EReference getReference() {
+ return reference;
+ }
+
+ /**
+ * Insert the method's description here. Creation date: (12/16/2000 9:32:28 AM)
+ *
+ * @return java.lang.Object
+ */
+ public Object getReferenceValue() {
+ return referenceValue;
+ }
+
+ public abstract void performAction();
+}
+
diff --git a/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/utilities/EncoderDecoder.java b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/utilities/EncoderDecoder.java
new file mode 100644
index 0000000..69fe06b
--- /dev/null
+++ b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/utilities/EncoderDecoder.java
@@ -0,0 +1,30 @@
+/*******************************************************************************
+ * Copyright (c) 2003, 2004 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.wst.common.internal.emf.utilities;
+
+
+/**
+ * Represents an interface to an object which can encode and decode values. This typically involves
+ * cryptography algorithms. This interface, along with the supplied adapters provide an extension
+ * mechanism for pluggable crytography that can be used when storing and retrieving attribute
+ * values, and is used prevalently for encoding and decoding password values of mof objects.
+ */
+public interface EncoderDecoder {
+ /**
+ * Returns a decoded version of the value.
+ */
+ public String decode(String value);
+
+ /**
+ * Returns an encoded version of the value.
+ */
+ public String encode(String value);
+}
\ No newline at end of file
diff --git a/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/utilities/EncoderDecoderAdapter.java b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/utilities/EncoderDecoderAdapter.java
new file mode 100644
index 0000000..788b300
--- /dev/null
+++ b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/utilities/EncoderDecoderAdapter.java
@@ -0,0 +1,35 @@
+/*******************************************************************************
+ * Copyright (c) 2003, 2004 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.wst.common.internal.emf.utilities;
+
+
+/**
+ * An adapter for EncoderDecoder implementations
+ */
+public abstract class EncoderDecoderAdapter implements EncoderDecoder {
+
+ /**
+ * EncoderDecoderAdapter constructor comment.
+ */
+ public EncoderDecoderAdapter() {
+ super();
+ }
+
+ /**
+ * Returns a decoded version of the value.
+ */
+ public abstract String decode(String value);
+
+ /**
+ * Returns an encoded version of the value.
+ */
+ public abstract String encode(String value);
+}
\ No newline at end of file
diff --git a/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/utilities/EncoderDecoderRegistry.java b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/utilities/EncoderDecoderRegistry.java
new file mode 100644
index 0000000..d615112
--- /dev/null
+++ b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/utilities/EncoderDecoderRegistry.java
@@ -0,0 +1,111 @@
+/*******************************************************************************
+ * Copyright (c) 2003, 2004 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.wst.common.internal.emf.utilities;
+
+
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * Registry for storing and retrieving value decoders and encoders. Usage Example:
+ *
+ * <pre>
+ *
+ *
+ * // Use the standard WebSphere password value encoder/decoder.
+ * EncoderDecoderRegistry.getDefaultRegistry().setDefaultEncoderDecoder(new com.ibm.ejs.security.util.WASEncoderDecoder());
+ * // Begin tracking changes...
+ * WriteBackHelper.begin();
+ * // Load a resource which may have un-encoded values...
+ * // Note: The WCCM will attempt to detect un-encoded values. If unencoded values
+ * // are found, the value will be encoded, and the resource will be added to the
+ * // WriteBackHelper.
+ * Resource res = resourceSet.load("myResource");
+ * // Ensure that any changes due to encoding are written back out.
+ * WriteBackHelper.end();
+ * </pre>
+ */
+public class EncoderDecoderRegistry {
+ protected static EncoderDecoderRegistry _defaultInstance;
+ public static final EncoderDecoder INITIAL_DEFAULT_ENCODER = PassthruEncoderDecoder.INSTANCE;
+ protected Map encoders = new HashMap();
+ protected Object defaultEncoderKey;
+
+ /**
+ * EncoderDecoderRegistry constructor comment.
+ */
+ public EncoderDecoderRegistry() {
+ super();
+ initializeDefaultEncoders();
+ }
+
+ /**
+ * Insert the method's description here. Creation date: (2/2/2001 12:43:31 AM)
+ */
+ public void addEncoderDecoder(EncoderDecoder encoderDecoder) {
+ encoders.put(encoderDecoder.getClass().getName(), encoderDecoder);
+ if (defaultEncoderKey == null)
+ defaultEncoderKey = encoderDecoder.getClass().getName();
+ }
+
+ /**
+ * Returns an encoder/decoder by key.
+ */
+ public EncoderDecoder getDefaultEncoderDecoder() {
+ if (defaultEncoderKey == null)
+ return null;
+ return (EncoderDecoder) encoders.get(defaultEncoderKey);
+ }
+
+ /**
+ * Returns the default registry to use for retrieving value encoders and decoders
+ */
+ public static EncoderDecoderRegistry getDefaultRegistry() {
+ if (_defaultInstance == null) {
+ _defaultInstance = new EncoderDecoderRegistry();
+ }
+ return _defaultInstance;
+ }
+
+ /**
+ * Returns an encoder/decoder by key.
+ */
+ public EncoderDecoder getEncoderDecoder(Object key) {
+ return (EncoderDecoder) encoders.get(key);
+ }
+
+ /**
+ * Initializes a standard set of encoder/decoders.
+ */
+ public void initializeDefaultEncoders() {
+ setDefaultEncoderDecoder(INITIAL_DEFAULT_ENCODER);
+ addEncoderDecoder(new XMLValueEncoderDecoder());
+ }
+
+ /**
+ * Removes the encoder/decoder with the specified key.
+ */
+ public void removeEncoderDecoder(Object key) {
+ if (encoders.containsKey(key)) {
+ encoders.remove(key);
+ }
+ }
+
+ /**
+ * Returns an encoder/decoder by key.
+ */
+ public void setDefaultEncoderDecoder(EncoderDecoder encoder) {
+ defaultEncoderKey = encoder.getClass().getName();
+ if (!encoders.containsKey(defaultEncoderKey)) {
+ addEncoderDecoder(encoder);
+ }
+ }
+}
\ No newline at end of file
diff --git a/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/utilities/EtoolsCopySession.java b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/utilities/EtoolsCopySession.java
new file mode 100644
index 0000000..0308041
--- /dev/null
+++ b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/utilities/EtoolsCopySession.java
@@ -0,0 +1,184 @@
+/*******************************************************************************
+ * Copyright (c) 2003, 2005 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.wst.common.internal.emf.utilities;
+
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+
+import org.eclipse.emf.common.notify.impl.NotificationImpl;
+import org.eclipse.emf.ecore.EObject;
+import org.eclipse.emf.ecore.resource.Resource;
+import org.eclipse.emf.ecore.xmi.XMLResource;
+
+/**
+ * Insert the type's description here. Creation date: (05/04/01 11:25:59 PM)
+ *
+ * @author: Administrator
+ */
+public class EtoolsCopySession extends EtoolsCopyUtility {
+ public static final int RESOURCE_COPIED = 500;
+ private EtoolsCopyUtility parentCopyUtility;
+ private XMLResource currentResource;
+ private XMLResource currentCopyResource;
+
+ /**
+ * EtoolsCopySession constructor comment.
+ */
+ public EtoolsCopySession(EtoolsCopyUtility aCopyUtility) {
+ parentCopyUtility = aCopyUtility;
+ setPreserveIds(aCopyUtility.preserveIds());
+ setCopyAdapters(aCopyUtility.isCopyAdapters());
+ }
+
+ /**
+ * Copy all Resources and RefObjects within <code>aGroup</code> and add them to
+ * <code>aGroup</code>. Non composite references will be deferred until all objects are
+ * copied from <code>aGroup</code>.
+ *
+ * Copy Resources first and then copy RefObjects.
+ */
+ public void copy(CopyGroup aGroup) {
+ if (aGroup != null) {
+ copyResources(aGroup);
+ copyRefObjects(aGroup);
+ executeDeferredCopyActions();
+ aGroup.postCopy(this);
+ notifyNewResourcesCopied(aGroup);
+ }
+ }
+
+ /**
+ * This method should be used if you are only going to copy <code>aRefObject</code> in this
+ * copy execution.
+ */
+ public EObject copy(EObject aRefObject, String idSuffix) {
+ EObject copied = containmentCopy(aRefObject, idSuffix);
+ executeDeferredCopyActions();
+ return copied;
+ }
+
+ /**
+ * This method should be used if you are only going to copy <code>aRefObject</code> in this
+ * copy execution. This method only copies <code>aRefObject</code> attributes.
+ */
+ public EObject copyObject(EObject aRefObject, String idSuffix) {
+ EObject copied = containmentCopyObject(aRefObject, idSuffix);
+ executeDeferredCopyActions();
+ return copied;
+ }
+
+ /**
+ * This method should be used if you are only going to copy <code>aResource</code> in this
+ * copy execution. The copied Resource will have a URI equal to <code>newUri</code>.
+ */
+ public Resource copy(Resource aResource, String newUri) {
+ Resource copied = containmentCopy(aResource, newUri);
+ executeDeferredCopyActions();
+ copyModificationFlag(aResource, copied);
+ notifyNewResourceCopied(copied);
+ return copied;
+ }
+
+ protected void notifyNewResourcesCopied(CopyGroup group) {
+ List copied = group.getCopiedResources();
+ for (int i = 0; i < copied.size(); i++) {
+ notifyNewResourceCopied((Resource) copied.get(i));
+ }
+ }
+
+ protected void notifyNewResourceCopied(Resource copied) {
+ copied.eNotify(new NotificationImpl(RESOURCE_COPIED, null, null));
+ }
+
+ /**
+ * @see com.ibm.etools.emf.ecore.utilities.copy.EtoolsCopyUtility#primCopyObject(EObject,
+ * String)
+ */
+ protected EObject primCopyObject(EObject aRefObject, String idSuffix) {
+ EObject copy = super.primCopyObject(aRefObject, idSuffix);
+ copyIdIfNecessary(aRefObject, copy, idSuffix);
+ return copy;
+ }
+
+ protected void copyIdIfNecessary(EObject obj, EObject copy, String idSuffix) {
+ if ((idSuffix == null && !preserveIds) || currentResource == null)
+ return;
+ String id = currentResource.getID(obj);
+ if (id == null)
+ return;
+ id = idSuffix == null ? id : id + idSuffix;
+ currentCopyResource.setID(copy, id);
+ }
+
+
+ /**
+ * Set delivery back on for all the cached objects and push them to the parentCopyUtility.
+ */
+ public void flush() {
+ Iterator it = getCopiedObjects().entrySet().iterator();
+ Map parentCopies = getParentCopyUtility().getCopiedObjects();
+ Map.Entry entry;
+ EObject copy;
+ while (it.hasNext()) {
+ entry = (Map.Entry) it.next();
+ copy = (EObject) entry.getValue();
+ copy.eSetDeliver(true);
+ parentCopies.put(entry.getKey(), copy);
+ }
+ copiedObjects = null;
+ }
+
+ /**
+ * Return a cached copy.
+ */
+ public EObject getCopy(EObject anObject) {
+ EObject copied = super.getCopy(anObject);
+ if (copied == null)
+ copied = getParentCopyUtility().getCopy(anObject);
+ return copied;
+ }
+
+ /**
+ * Insert the method's description here. Creation date: (05/04/01 11:28:07 PM)
+ *
+ * @return com.ibm.etools.emf.ecore.utilities.copy.EtoolsCopyUtility
+ */
+ protected EtoolsCopyUtility getParentCopyUtility() {
+ return parentCopyUtility;
+ }
+
+ /**
+ * Return an instance of EObject that is the same type as <code>aRefObject</code>.
+ */
+ public EObject newInstance(EObject aRefObject) {
+ EObject newType = super.newInstance(aRefObject);
+ newType.eSetDeliver(false);
+ return newType;
+ }
+
+ /**
+ * @see com.ibm.etools.emf.ecore.utilities.copy.EtoolsCopyUtility#newInstance(Resource, String)
+ */
+ public Resource newInstance(Resource aResource, String newUri) {
+ Resource copy = super.newInstance(aResource, newUri);
+ if (aResource instanceof XMLResource) {
+ currentResource = (XMLResource) aResource;
+ currentCopyResource = (XMLResource) copy;
+ } else {
+ currentResource = null;
+ currentCopyResource = null;
+ }
+ return copy;
+ }
+
+}
+
diff --git a/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/utilities/EtoolsCopyUtility.java b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/utilities/EtoolsCopyUtility.java
new file mode 100644
index 0000000..22d91e0
--- /dev/null
+++ b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/utilities/EtoolsCopyUtility.java
@@ -0,0 +1,669 @@
+/*******************************************************************************
+ * Copyright (c) 2003, 2005 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.wst.common.internal.emf.utilities;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+
+import org.eclipse.emf.common.notify.Adapter;
+import org.eclipse.emf.common.util.EList;
+import org.eclipse.emf.common.util.URI;
+import org.eclipse.emf.ecore.EAttribute;
+import org.eclipse.emf.ecore.EClass;
+import org.eclipse.emf.ecore.EFactory;
+import org.eclipse.emf.ecore.EObject;
+import org.eclipse.emf.ecore.EPackage;
+import org.eclipse.emf.ecore.EReference;
+import org.eclipse.emf.ecore.ETypedElement;
+import org.eclipse.emf.ecore.EcorePackage;
+import org.eclipse.emf.ecore.resource.Resource;
+
+
+/**
+ * Insert the type's description here. Creation date: (12/13/2000 9:10:55 PM)
+ *
+ * @author: Administrator
+ */
+public class EtoolsCopyUtility {
+ protected static final String REFENUMLITERAL_TYPE_NAME = "EEnumLiteral"; //$NON-NLS-1$
+ private final EcorePackage pkg = EcorePackage.eINSTANCE;
+
+ private final ETypedElement METAENAME = pkg.getENamedElement_Name();
+
+ protected HashMap copiedObjects;
+ protected List deferredReferenceCopies;
+ protected boolean preserveIds = false;
+ protected boolean copyAdapters = false;
+ protected HashMap copiedAdapters;
+
+ protected class DeferredSingleReferenceCopyAction extends DeferredReferenceUtilityAction {
+ public DeferredSingleReferenceCopyAction(EReference aReference, Object aValue, String aSuffix, EObject aCopyContainer) {
+ super(aReference, aValue, aSuffix, aCopyContainer);
+ }
+
+ public void performAction() {
+ EObject value = (EObject) getReferenceValue();
+ getCopyContainer().eSet(getReference(), getCopyIfFound(value));
+ }
+ }
+
+ protected class DeferredManyReferenceCopyAction extends DeferredReferenceUtilityAction {
+ public DeferredManyReferenceCopyAction(EReference aReference, List aValue, String aSuffix, EObject aCopyContainer) {
+ super(aReference, aValue, aSuffix, aCopyContainer);
+ }
+
+ public void performAction() {
+ List copyList = (List) getCopyContainer().eGet(getReference());
+ Iterator it = ((List) getReferenceValue()).iterator();
+ EObject next;
+ while (it.hasNext()) {
+ next = (EObject) it.next();
+ copyList.add(getCopyIfFound(next));
+ }
+ }
+ }
+
+ /**
+ * Insert the method's description here. Creation date: (12/13/2000 9:14:26 PM)
+ *
+ * @param aRefObject
+ * org.eclipse.emf.ecore.EObject
+ */
+ public EtoolsCopyUtility() {
+ }
+
+ /**
+ * Create a <code>DeferredManyReferenceCopyAction</code> and add it to the list of deferred
+ * copy actions.
+ */
+ protected void addDeferredManyReferenceCopy(EReference reference, List aValue, String idSuffix, EObject aCopyContainer) {
+ getDeferredReferenceCopies().add(new DeferredManyReferenceCopyAction(reference, aValue, idSuffix, aCopyContainer));
+ }
+
+ /**
+ * Create a <code>DeferredSingleReferenceCopyAction</code> and add it to the list of deferred
+ * copy actions.
+ */
+ protected void addDeferredSingleReferenceCopy(EReference reference, EObject aValue, String idSuffix, EObject aCopyContainer) {
+ getDeferredReferenceCopies().add(new DeferredSingleReferenceCopyAction(reference, aValue, idSuffix, aCopyContainer));
+ }
+
+ /**
+ * Check for an already copied object first.
+ */
+ protected EObject containmentCopy(EObject anObject, String idSuffix) {
+ EObject copied = getCopy(anObject);
+ if (copied == null)
+ copied = primCopy(anObject, idSuffix);
+ return copied;
+ }
+
+ /**
+ * Check for an already copied object first.
+ */
+ protected EObject containmentCopyObject(EObject anObject, String idSuffix) {
+ EObject copied = getCopy(anObject);
+ if (copied == null)
+ copied = primCopyObject(anObject, idSuffix);
+ return copied;
+ }
+
+ protected Resource containmentCopy(Resource aResource, String newUri) {
+ /* copied resources are never cached */
+ return primCopy(aResource, newUri);
+ }
+
+ /**
+ * Copy all Resources and RefObjects within <code>aGroup</code> and add them to
+ * <code>aGroup</code>. Non composite references will be deferred until all objects are
+ * copied from <code>aGroup</code>.
+ *
+ * Copy Resources first and then copy RefObjects.
+ */
+ public void copy(CopyGroup aGroup) {
+ if (aGroup != null) {
+ EtoolsCopySession session = new EtoolsCopySession(this);
+ session.setPreserveIds(aGroup.getPreserveIds());
+ session.copy(aGroup);
+ session.flush();
+ }
+ }
+
+ public EObject copy(EObject aRefObject) {
+ return copy(aRefObject, null);
+ }
+
+ /**
+ * This method should be used if you are only going to copy <code>aRefObject</code> in this
+ * copy execution.
+ */
+ public EObject copy(EObject aRefObject, String idSuffix) {
+ EtoolsCopySession session = new EtoolsCopySession(this);
+ EObject copied = session.copy(aRefObject, idSuffix);
+ session.flush();
+ return copied;
+ }
+
+ /**
+ * This method should be used if you are only going to copy <code>aRefObject</code> in this
+ * copy execution. This method only copies <code>aRefObject</code> with its properties, not
+ * references.
+ */
+ public EObject copyObject(EObject aRefObject, String idSuffix) {
+ EtoolsCopySession session = new EtoolsCopySession(this);
+ EObject copied = session.copyObject(aRefObject, idSuffix);
+ session.flush();
+ return copied;
+ }
+
+ /**
+ * This method should be used if you are only going to copy <code>aResource</code> in this
+ * copy execution. The copied Resource will have a URI equal to <code>newUri</code>.
+ */
+ public Resource copy(Resource aResource, String newUri) {
+ EtoolsCopySession session = new EtoolsCopySession(this);
+ Resource copied = session.copy(aResource, newUri);
+ session.flush();
+ return copied;
+ }
+
+ /**
+ * If an attribute is set and its value is not <code>null</code>, then perform copy
+ * <code>attribute</code> value from <code>aRefObject</code> to <code>copyRef</code>.
+ * Null is a valid value if the attribute is set.
+ */
+
+ protected void copyAttribute(EAttribute attribute, EObject aRefObject, String idSuffix, EObject copyRef) {
+ if (!attribute.isChangeable())
+ return; //ignore
+ if (attribute.isMany()) {
+ List value = (List) aRefObject.eGet(attribute);
+ if (value != null)
+ copyManyAttribute(attribute, value, aRefObject, idSuffix, copyRef);
+ } else if (aRefObject.eIsSet(attribute)) {
+ Object value = aRefObject.eGet(attribute);
+ if (value == null)
+ copyRef.eSet(attribute, value);
+ else
+ copySingleAttribute(attribute, value, aRefObject, idSuffix, copyRef);
+ } else if (attribute == METAENAME) {
+ //set name to the ID (this is computed as a default), only get here if isSetName is
+ // false.
+ copyRef.eSet(attribute, aRefObject.eGet(attribute));
+ }
+ }
+
+ /**
+ * Iterate over the attributes of the receiver and copy each attribute.
+ */
+ protected void copyCurrentAttributes(EObject aRefObject, String idSuffix, EObject copyRef) {
+ List attributes = aRefObject.eClass().getEAllAttributes();
+ if (attributes != null) {
+ Iterator it = attributes.iterator();
+ EAttribute ra;
+ while (it.hasNext()) {
+ ra = (EAttribute) it.next();
+ copyAttribute(ra, aRefObject, idSuffix, copyRef);
+ }
+ }
+ }
+
+ /**
+ * This method will iterate over the references of the receiver. If a reference's value is not
+ * <code>null</code>, then a series of tests are done before setting the value with the
+ * copied object, <code>copyRef</code>.
+ *
+ * Tests: 1. Do nothing if the reference equals the metaEContainer or metaEContains references.
+ */
+
+ protected void copyCurrentReferences(EObject aRefObject, String idSuffix, EObject copyRef) {
+ List references = aRefObject.eClass().getEAllReferences();
+ if (references != null) {
+ Iterator it = references.iterator();
+ EReference rr;
+ while (it.hasNext()) {
+ rr = (EReference) it.next();
+ if (shouldCopyReference(rr))
+ copyReference(rr, aRefObject, idSuffix, copyRef);
+ }
+ }
+ }
+
+ /**
+ * Iterate over <code>anExtent</code> and copy each element to <code>copyExtent</code>.
+ */
+ protected void copyExtent(EList anExtent, EList copyExtent) {
+ Iterator it = anExtent.iterator();
+ EObject refObject;
+ while (it.hasNext()) {
+ refObject = (EObject) it.next();
+ copyExtent.add(containmentCopy(refObject, null));
+ }
+ }
+
+ /**
+ * Copy a many value attribute which is treated as a many valued reference.
+ *
+ * Tests:
+ *
+ * 1. If the type is <bold>not </bold> <code>null</code>, then set the value on
+ * <code>copyRef</code> without making a copy. 2. If the type is <code>null</code>, then
+ * obtain the list from <code>copyRef</code> and add a copy of each value from the original
+ * list to it.
+ */
+
+ protected void copyManyAttribute(EAttribute attribute, List aValue, EObject aRefObject, String idSuffix, EObject copyRef) {
+ if (attribute.getEType() == null)
+ copyRef.eSet(attribute, aValue);
+ else {
+ List copyList = (List) copyRef.eGet(attribute);
+ Iterator it = aValue.iterator();
+ Object next;
+ while (it.hasNext()) {
+ next = it.next();
+ if (next instanceof EObject)
+ copyList.add(containmentCopy((EObject) next, idSuffix));
+ else
+ copyList.add(next);
+ }
+ }
+ }
+
+ /**
+ * This method will iterate over the references of the receiver. If a reference's value is not
+ * <code>null</code>, then a series of tests are done before setting the value with the
+ * copied object, <code>copyRef</code>.
+ *
+ * Tests: 1. If the reference is many, obtain the list from the receiving object and make a copy
+ * of each value if the reference is composite before adding to the list; otherwise, just add
+ * each value to the of the <code>copyRef</code>.
+ */
+
+ protected void copyManyReference(EReference aReference, List aList, EObject aRefObject, String idSuffix, EObject copyRef) {
+ if (!aList.isEmpty()) {
+ if (aReference.isContainment()) {
+ List copyList = (List) copyRef.eGet(aReference);
+ Iterator it = aList.iterator();
+ EObject targetValue;
+ while (it.hasNext()) {
+ targetValue = (EObject) it.next();
+ copyList.add(containmentCopy(targetValue, idSuffix));
+ }
+ } else
+ addDeferredManyReferenceCopy(aReference, aList, idSuffix, copyRef);
+ }
+ }
+
+ /**
+ * This method will iterate over the references of the receiver. If a reference's value is not
+ * <code>null</code>, then perform the copy.
+ */
+
+ protected void copyReference(EReference aReference, EObject aRefObject, String idSuffix, EObject copyRef) {
+ if (aReference.isMany()) {
+ List value = (List) aRefObject.eGet(aReference);
+ if (value != null)
+ copyManyReference(aReference, value, aRefObject, idSuffix, copyRef);
+ } else if (aRefObject.eIsSet(aReference)) {
+ Object value = aRefObject.eGet(aReference);
+ copySingleReference(aReference, (EObject) value, aRefObject, idSuffix, copyRef);
+ }
+ }
+
+ /**
+ * Copy all RefObjects from <code>aGroup</code> and add the copy back to <code>aGroup</code>.
+ */
+ protected void copyRefObjects(CopyGroup aGroup) {
+ Association association;
+ EObject refObject;
+ String idSuffix;
+ if (aGroup.primGetRefObjects() != null) {
+ Iterator it = aGroup.primGetRefObjects().iterator();
+ while (it.hasNext()) {
+ association = (Association) it.next();
+ refObject = (EObject) association.getKey();
+ idSuffix = (String) association.getValue();
+ if (idSuffix == null)
+ idSuffix = aGroup.getDefaultIdSuffix();
+ aGroup.addCopied(containmentCopy(refObject, idSuffix));
+ }
+ }
+ }
+
+ /**
+ * Copy all Resources from <code>aGroup</code> and add the copy back to <code>aGroup</code>.
+ */
+ protected void copyResources(CopyGroup aGroup) {
+ Association association;
+ Resource resource;
+ String uri;
+ if (aGroup.primGetResources() != null) {
+ Iterator it = aGroup.primGetResources().iterator();
+ while (it.hasNext()) {
+ association = (Association) it.next();
+ resource = (Resource) association.getKey();
+ uri = (String) association.getValue();
+ Resource copied = containmentCopy(resource, uri);
+ copyModificationFlag(resource, copied);
+ aGroup.addCopied(copied);
+ }
+ }
+ }
+
+ /**
+ * Copy a single value attribute.
+ *
+ * Tests:
+ *
+ * 1. If an attribute type is not <code>null</code> then it is an object type and it must be
+ * copied. Do not copy the value if the attribute is an Enumeration type. 2. If an attribute
+ * type is <bold>not </bold> <code>null</code> then copy the value before setting it on
+ * <code>copyRef</code>.
+ */
+
+ protected void copySingleAttribute(EAttribute attribute, Object aValue, EObject aRefObject, String idSuffix, EObject copyRef) {
+ if (attribute.getEType() == null) {
+ copyRef.eSet(attribute, aValue);
+ } else {
+ //MOF108
+ // if (attribute.isObjectType())
+ if (attribute.getEType() instanceof EClass)
+ copyRef.eSet(attribute, containmentCopy((EObject) aValue, idSuffix));
+ else
+ copyRef.eSet(attribute, aValue);
+ }
+ }
+
+ /**
+ * This method will iterate over the references of the receiver. If a reference's value is not
+ * <code>null</code>, then a series of tests are done before setting the value with the
+ * copied object, <code>copyRef</code>.
+ *
+ * Tests: 1. If the reference is <bold>not </bold> many, make a copy of the value if the
+ * reference is composite before setting the value with <code>copyRef</code>; otherwise, just
+ * set the value as is.
+ */
+
+ protected void copySingleReference(EReference aReference, EObject aValue, EObject aRefObject, String idSuffix, EObject copyRef) {
+ //Exceptional case; the relationship is not the container relationship
+ //And is not navigable in the other direction; go ahead and copy
+ if (aValue != aRefObject.eContainer() || aReference.getEOpposite() == null) {
+ if (aReference.isContainment())
+ copyRef.eSet(aReference, containmentCopy(aValue, idSuffix));
+ else
+ addDeferredSingleReferenceCopy(aReference, aValue, idSuffix, copyRef);
+ }
+ }
+
+ /**
+ * Copy all Resources and RefObjects within <code>aGroup</code> and add them to
+ * <code>aGroup</code>. Non composite references will be deferred until all objects are
+ * copied from <code>aGroup</code>.
+ *
+ * Copy Resources first and then copy RefObjects.
+ */
+ public static void createCopy(CopyGroup aGroup) {
+ EtoolsCopyUtility utility = new EtoolsCopyUtility();
+ utility.copy(aGroup);
+ }
+
+ /**
+ * Copies attributes
+ */
+ public static void createAttributeCopy(EObject aRefObject, EObject copyObject) {
+ EtoolsCopyUtility utility = new EtoolsCopyUtility();
+ utility.copyCurrentAttributes(aRefObject, null, copyObject);
+ }
+
+ /**
+ * Copies all set attributes and references based on containment. Thus, it will copy the entire
+ * containment tree. Use the idSuffix to define the suffix that will be appended to the existing
+ * IDs of copied objects.
+ */
+ public static EObject createCopy(EObject aRefObject) {
+ return createCopy(aRefObject, null);
+ }
+
+ /**
+ * Copies all set attributes and references based on containment. Thus, it will copy the entire
+ * containment tree. Use the idSuffix to define the suffix that will be appended to the existing
+ * IDs of copied objects.
+ */
+ public static EObject createCopy(EObject aRefObject, String idSuffix) {
+ EtoolsCopyUtility utility = new EtoolsCopyUtility();
+ return utility.copy(aRefObject, idSuffix);
+ }
+
+ /**
+ * Copy <code>aResource</code> using <code>newUri</code> for the URI.
+ */
+ public static Resource createCopy(Resource aResource, String newUri) {
+ EtoolsCopyUtility utility = new EtoolsCopyUtility();
+ return utility.copy(aResource, newUri);
+ }
+
+ protected void executeDeferredCopyActions() {
+ if (primGetDeferredReferenceCopies() != null) {
+ Iterator it = primGetDeferredReferenceCopies().iterator();
+ DeferredReferenceUtilityAction action;
+ while (it.hasNext()) {
+ action = (DeferredReferenceUtilityAction) it.next();
+ action.performAction();
+ }
+ primGetDeferredReferenceCopies().clear();
+ }
+ }
+
+ /**
+ * Insert the method's description here. Creation date: (12/13/2000 9:17:35 PM)
+ *
+ * @return java.util.HashMap
+ */
+ protected java.util.HashMap getCopiedObjects() {
+ if (copiedObjects == null)
+ copiedObjects = new HashMap(200);
+ return copiedObjects;
+ }
+
+ protected java.util.HashMap getCopiedAdapters() {
+ if (copiedAdapters == null)
+ copiedAdapters = new HashMap(200);
+ return copiedAdapters;
+ }
+
+ /**
+ * Return a cached copy.
+ */
+ public EObject getCopy(EObject anObject) {
+ if (anObject == null)
+ return null;
+ return (EObject) getCopiedObjects().get(anObject);
+ }
+
+ /**
+ * Return a cached copy, if none, return the argument.
+ */
+ public EObject getCopyIfFound(EObject anObject) {
+ EObject copied = getCopy(anObject);
+ return copied == null ? anObject : copied;
+ }
+
+ /**
+ * Insert the method's description here. Creation date: (12/16/2000 9:11:32 AM)
+ *
+ * @return java.util.List
+ */
+ protected java.util.List getDeferredReferenceCopies() {
+ if (deferredReferenceCopies == null)
+ deferredReferenceCopies = new ArrayList(100);
+ return deferredReferenceCopies;
+ }
+
+ /**
+ * Return an instance of EObject that is the same type as <code>aRefObject</code>.
+ */
+ public EObject newInstance(EObject aRefObject) {
+ if (aRefObject == null)
+ return null;
+ EPackage epkg = (EPackage) aRefObject.eClass().eContainer();
+ EFactory factory = epkg.getEFactoryInstance();
+ EClass refObj = aRefObject.eClass();
+ return factory.create(refObj);
+ }
+
+ /**
+ * Return an instance of Resource that uses the same ResourceFactory as the one used by
+ * <code>aResource</code>. If <code>newUri</code> is <code>null</code> then use the URI
+ * from <code>aResource</code>.
+ */
+ public Resource newInstance(Resource aResource, String newUri) {
+ if (aResource == null)
+ return null;
+ Resource newResource;
+ String originalUri = aResource.getURI().toString();
+ newUri = newUri == null ? originalUri : newUri;
+
+ Resource.Factory factory = null;
+ if (aResource.getResourceSet() == null)
+ factory = Resource.Factory.Registry.INSTANCE.getFactory(URI.createURI(originalUri));
+ else
+ factory = aResource.getResourceSet().getResourceFactoryRegistry().getFactory(URI.createURI(originalUri));
+
+
+ newResource = factory.createResource(URI.createURI(newUri));
+ return newResource;
+ }
+
+ /**
+ * Should the id be copied in the case where no suffix is specified? Defaults to false
+ */
+ public boolean preserveIds() {
+ return preserveIds;
+ }
+
+ /**
+ * Copies all set attributes and references based on containment. Thus, it will copy the entire
+ * containment tree. Use the idSuffix to define the suffix that will be appended to the existing
+ * IDs of copied objects. If an idSuffix does not exist, do not set an id on the copied object.
+ */
+ protected EObject primCopy(EObject aRefObject, String idSuffix) {
+ if (aRefObject == null)
+ return null;
+ EObject copyRef = primCopyObject(aRefObject, idSuffix);
+
+ copyCurrentReferences(aRefObject, idSuffix, copyRef);
+ return copyRef;
+ }
+
+ /**
+ * Copies all set attributes based on containment. Thus, it will copy the entire containment
+ * tree. Use the idSuffix to define the suffix that will be appended to the existing IDs of
+ * copied objects. If an idSuffix does not exist, do not set an id on the copied object.
+ */
+ protected EObject primCopyObject(EObject aRefObject, String idSuffix) {
+ if (aRefObject == null)
+ return null;
+ EObject copyRef = newInstance(aRefObject);
+
+ recordCopy(aRefObject, copyRef);
+ copyCurrentAttributes(aRefObject, idSuffix, copyRef);
+ if (isCopyAdapters())
+ copyAdapters(aRefObject, copyRef);
+ return copyRef;
+ }
+
+ protected void copyAdapters(EObject aRefObject, EObject copyRef) {
+ List adapters = aRefObject.eAdapters();
+ for (int i = 0; i < adapters.size(); i++) {
+ Adapter adapter = (Adapter) adapters.get(i);
+ copyAdapter(aRefObject, copyRef, adapter);
+
+ }
+ }
+
+ protected void copyAdapter(EObject aRefObject, EObject copyRef, Adapter adapter) {
+ if (!(adapter instanceof CloneablePublic))
+ return;
+ CloneablePublic copyAdapter = (CloneablePublic) getCopiedAdapters().get(adapter);
+ if (copyAdapter == null) {
+ copyAdapter = (CloneablePublic) ((CloneablePublic) adapter).clone();
+ getCopiedAdapters().put(adapter, copyAdapter);
+ }
+ if (copyAdapter != null)
+ copyRef.eAdapters().add(copyAdapter);
+ }
+
+ /**
+ * Copies all set attributes and references based on containment. Thus, it will copy the entire
+ * containment tree. Use the idSuffix to define the suffix that will be appended to the existing
+ * IDs of copied objects.
+ */
+ protected Resource primCopy(Resource aResource, String newUri) {
+ if (aResource == null)
+ return null;
+ Resource copyResource = newInstance(aResource, newUri);
+ copyExtent(aResource.getContents(), copyResource.getContents());
+ return copyResource;
+ }
+
+ protected void copyModificationFlag(Resource aResource, Resource copied) {
+ if (aResource.isModified())
+ copied.setModified(true);
+ }
+
+ /**
+ * Insert the method's description here. Creation date: (12/16/2000 9:11:32 AM)
+ *
+ * @return java.util.List
+ */
+ private java.util.List primGetDeferredReferenceCopies() {
+ return deferredReferenceCopies;
+ }
+
+ public void recordCopy(EObject aSource, EObject aCopy) {
+ getCopiedObjects().put(aSource, aCopy);
+ }
+
+ public void recordCopy(Adapter aSource, Adapter aCopy) {
+ getCopiedAdapters().put(aSource, aCopy);
+ }
+
+ /**
+ * Should the id be copied in the case where no suffix is specified?
+ */
+ public void setPreserveIds(boolean value) {
+ preserveIds = value;
+ }
+
+ protected boolean shouldCopyReference(EReference aReference) {
+ return aReference.isChangeable();
+ }
+
+ /**
+ * @return
+ */
+ public boolean isCopyAdapters() {
+ return copyAdapters;
+ }
+
+ /**
+ * Flag used to indicate whether adapters should be copied as well. In order for an adapter to
+ * be copied, it must implement the {@link CloneablePublic}interface.
+ */
+ public void setCopyAdapters(boolean b) {
+ copyAdapters = b;
+ }
+
+}
+
+
diff --git a/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/utilities/ExceptionHelper.java b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/utilities/ExceptionHelper.java
new file mode 100644
index 0000000..7d629af
--- /dev/null
+++ b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/utilities/ExceptionHelper.java
@@ -0,0 +1,70 @@
+/*******************************************************************************
+ * Copyright (c) 2003, 2005 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.wst.common.internal.emf.utilities;
+
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.eclipse.wst.common.frameworks.internal.enablement.nonui.IWFTWrappedException;
+
+
+
+/**
+ * Utility class to factor common code for implementers of IArchiveWrappedException
+ */
+public class ExceptionHelper {
+
+ /**
+ * Utility class; cannot be instantiated
+ */
+ private ExceptionHelper() {
+ super();
+ }
+
+ /**
+ * Return the messages from
+ *
+ * @exception and
+ * all nested exceptions, in order from outermost to innermost
+ */
+ public static java.lang.String[] getAllMessages(IWFTWrappedException exception) {
+ List messages = new ArrayList(4);
+ messages.add(exception.getMessage());
+ Exception nested = exception.getNestedException();
+ while (nested != null) {
+ messages.add(nested.getMessage());
+ if (nested instanceof IWFTWrappedException)
+ nested = ((IWFTWrappedException) nested).getNestedException();
+ else
+ nested = null;
+ }
+ return (String[]) messages.toArray(new String[messages.size()]);
+ }
+
+ /**
+ * Return the messages from
+ *
+ * @exception and
+ * all nested exceptions, in order from outermost to innermost, concatenated as
+ * one
+ */
+ public static String getConcatenatedMessages(IWFTWrappedException exception) {
+ String[] messages = getAllMessages(exception);
+ StringBuffer sb = new StringBuffer(256);
+ for (int i = 0; i < messages.length; i++) {
+ sb.append(messages[i]);
+ if (i < messages.length - 1)
+ sb.append('\n');
+ }
+ return sb.toString();
+ }
+}
diff --git a/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/utilities/ExtendedEcoreUtil.java b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/utilities/ExtendedEcoreUtil.java
new file mode 100644
index 0000000..e9cf914
--- /dev/null
+++ b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/utilities/ExtendedEcoreUtil.java
@@ -0,0 +1,274 @@
+/*******************************************************************************
+ * Copyright (c) 2003, 2006 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.wst.common.internal.emf.utilities;
+
+import java.io.FileNotFoundException;
+import java.util.Iterator;
+import java.util.List;
+
+import org.eclipse.emf.common.notify.Adapter;
+import org.eclipse.emf.common.notify.impl.BasicNotifierImpl.EAdapterList;
+import org.eclipse.emf.common.util.URI;
+import org.eclipse.emf.common.util.WrappedException;
+import org.eclipse.emf.ecore.EAttribute;
+import org.eclipse.emf.ecore.ENamedElement;
+import org.eclipse.emf.ecore.EObject;
+import org.eclipse.emf.ecore.EPackage;
+import org.eclipse.emf.ecore.EStructuralFeature;
+import org.eclipse.emf.ecore.InternalEObject;
+import org.eclipse.emf.ecore.resource.Resource;
+import org.eclipse.emf.ecore.util.EcoreUtil;
+import org.eclipse.emf.ecore.xmi.XMLResource;
+
+
+
+public class ExtendedEcoreUtil extends EcoreUtil {
+ private static FileNotFoundDetector FILE_NOT_FOUND_DETECTOR;
+ private static String NAME_ATTRIBUTE_STRING = "name"; //$NON-NLS-1$
+
+
+ public interface FileNotFoundDetector {
+ boolean isFileNotFound(WrappedException wrappedEx);
+ }
+
+ public static void setFileNotFoundDetector(FileNotFoundDetector detector) {
+ FILE_NOT_FOUND_DETECTOR = detector;
+ }
+
+ public static FileNotFoundDetector getFileNotFoundDetector() {
+ if (FILE_NOT_FOUND_DETECTOR == null) {
+ FILE_NOT_FOUND_DETECTOR = new FileNotFoundDetector() {
+ public boolean isFileNotFound(WrappedException wrappedEx) {
+ if (getInnerFileNotFoundException(wrappedEx) != null)
+ return true;
+ return false;
+ }
+ };
+ }
+ return FILE_NOT_FOUND_DETECTOR;
+ }
+
+ public static FileNotFoundException getInnerFileNotFoundException(WrappedException wrappedEx) {
+ if (wrappedEx.exception() instanceof java.io.FileNotFoundException) {
+ return (FileNotFoundException) wrappedEx.exception();
+ } else if (wrappedEx.exception() instanceof WrappedException) {
+ return getInnerFileNotFoundException((WrappedException) wrappedEx.exception());
+ }
+ return null;
+ }
+
+ public static void eSetOrAdd(EObject obj, EStructuralFeature feature, Object value) {
+ eSetOrAdd(obj, feature, value, 0);
+ }
+
+ public static void eSetOrAdd(EObject obj, EStructuralFeature feature, Object value, int newIndex) {
+ if (feature.isMany() && value != null) {
+ if (newIndex >= 0)
+ ((List) obj.eGet(feature)).add(newIndex, value);
+ else
+ ((List) obj.eGet(feature)).add(value);
+ } else {
+ obj.eSet(feature, value);
+ }
+ }
+
+ public static void eUnsetOrRemove(EObject obj, EStructuralFeature feature, Object value) {
+ if (feature == null || feature.isMany())
+ ((List) obj.eGet(feature)).remove(value);
+ else
+ obj.eUnset(feature);
+ }
+
+ public static boolean endsWith(URI sourceUri, URI testUri) {
+ //TODO Waiting on new emf URI API
+ String[] sourceSegments = sourceUri.segments();
+ String[] testSegments = testUri.segments();
+ int i = testSegments.length;
+ int j = sourceSegments.length;
+ if (j >= i) {
+ boolean test = true;
+
+ while (test && i > 0) {
+ i--;
+ j--;
+ test = testSegments[i].equals(sourceSegments[j]);
+ }
+ return test;
+ }
+ return false;
+ }
+
+ public static String getName(EObject obj) {
+ if (obj == null)
+ return null;
+ if (obj instanceof ENamedElement)
+ return ((ENamedElement) obj).getName();
+ List allAtts = obj.eClass().getEAllAttributes();
+ int size = allAtts.size();
+ EAttribute att, nameAttribute = null;
+ for (int i = 0; i < size; i++) {
+ att = (EAttribute) allAtts.get(i);
+ if (NAME_ATTRIBUTE_STRING.equals(att.getName())) {
+ nameAttribute = att;
+ break;
+ }
+ }
+ if (nameAttribute != null)
+ return (String) obj.eGet(nameAttribute);
+ return null;
+ }
+
+ /**
+ * @deprecated No longer needed.
+ */
+ public static void addLoadingTag(Resource resource) {
+ //resource.eAdapters().add(IsLoadingDetector.INSTANCE);
+ }
+
+ /**
+ * @deprecated No longer needed.
+ */
+ public static void removeLoadingTag(Resource resource) {
+ //resource.eAdapters().remove(IsLoadingDetector.INSTANCE);
+ }
+
+ /**
+ * Return true if the resource is currently being loaded. This is determined by checking for the
+ * IsLoadingDector in the list of eAdapters on the resource.
+ *
+ * @param resource
+ * @return boolean
+ *
+ * @see addLoadingTag(Resource)
+ * @see removeLoadingTag(Resource)
+ * @deprecated use {@link Resource.Internal#isLoading()}
+ */
+ public static boolean isLoading(Resource resource) {
+ return resource != null ? ((Resource.Internal)resource).isLoading() : false;
+ }
+
+ public static Adapter createAdapterForLoading(Adapter targetAdapter, EObject targetObject) {
+ Resource res = targetObject.eResource();
+ if (res == null || isLoading(res))
+ return new IsLoadingProxyAdapter(targetAdapter, targetObject);
+ return targetAdapter;
+ }
+
+ public static void preRegisterPackage(String nsPrefix, EPackage.Descriptor descriptor) {
+ if (!EPackage.Registry.INSTANCE.containsKey(nsPrefix))
+ EPackage.Registry.INSTANCE.put(nsPrefix, descriptor);
+ }
+ /**
+ * Returns the adapter of the specified type.
+ * @param anObject
+ * @param adapters list of adapters to search.
+ * @param type the type of adapter.
+ * @return an adapter from the list or null.
+ */
+ public static Adapter getAdapter(EObject anObject, List adapters, Object type) {
+
+ Object [] adaptArray = ((EAdapterList)adapters).data();
+ if (adaptArray == null) return null;
+ for (int i = 0; i < adaptArray.length; i++) {
+ Adapter adapter = (Adapter) adaptArray[i];
+ if (adapter != null && adapter.isAdapterForType(type)) {
+ return adapter;
+ }
+ }
+ return null;
+ }
+
+ /**
+ * Remove this object from it's container, and make it and all it's children
+ * proxies
+ */
+ public static void unload(EObject root) {
+ Resource res = root.eResource();
+ EObject container = root.eContainer();
+ /* Making sure the proxy is created first before unloading */
+ if (root != null && res != null)
+ becomeProxy(root, res);
+ if (container == null)
+ if (res != null)
+ res.getContents().remove(root);
+ else {
+ EStructuralFeature feature = root.eContainmentFeature();
+ if (feature != null)
+ eUnsetOrRemove(container, feature, root);
+ }
+
+ }
+
+ /**
+ * Turns this object and all it's children to proxies, and removes adapters precondition: The
+ * object has been removed from it's container
+ */
+ public static void becomeProxy(EObject root, Resource res) {
+ Iterator iter = root.eAllContents();
+ while (iter.hasNext()) {
+ doBecomeProxy((InternalEObject) iter.next(), res);
+ }
+ doBecomeProxy((InternalEObject) root, res);
+ }
+
+ protected static void doBecomeProxy(InternalEObject p, Resource res) {
+ String id = res.getURIFragment(p);
+ p.eSetProxyURI(res.getURI().appendFragment(id));
+ if (res instanceof XMLResource) {
+ ((XMLResource) res).setID(p,null);
+ }
+ p.eAdapters().clear();
+ }
+
+ public static void removeProxy(EObject root, Resource res) {
+ Iterator iter = root.eAllContents();
+ while (iter.hasNext()) {
+ doRemoveProxy((InternalEObject) iter.next(), res);
+ }
+ doRemoveProxy((InternalEObject) root, res);
+ }
+
+ protected static void doRemoveProxy(InternalEObject p, Resource res) {
+ String id = p.eProxyURI().fragment();
+ if (res instanceof XMLResource) {
+ ((XMLResource) res).setID(p, id);
+ }
+ p.eSetProxyURI(null);
+ }
+
+
+ /**
+ * Ensures the passed object is not a proxy; if it is, throws an exception indicating the bad
+ * HREF. If the object is null, does nothing.
+ *
+ * @param object
+ * @throws DanglingHREFException
+ */
+ public static void checkProxy(EObject object) throws DanglingHREFException {
+ if (object == null || !object.eIsProxy())
+ return;
+ String msg = WFTUtilsResourceHandler.getString(WFTUtilsResourceHandler.DANGLING_HREF_ERROR_, new Object[]{((InternalEObject) object).eProxyURI()});
+ throw new DanglingHREFException(msg);
+ }
+
+ /**
+ * Return true if o1 and o2 are not the same values. This implementation takes into account that
+ * either parameter can be null.
+ *
+ * @param o1
+ * @param o2
+ * @return
+ */
+ public static boolean valueChanged(Object o1, Object o2) {
+ return (o1 == null ^ o2 == null) || (o1 == null || !o1.equals(o2));
+ }
+
+}
diff --git a/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/utilities/FeatureValueConversionException.java b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/utilities/FeatureValueConversionException.java
new file mode 100644
index 0000000..0525a1f
--- /dev/null
+++ b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/utilities/FeatureValueConversionException.java
@@ -0,0 +1,29 @@
+/***************************************************************************************************
+ * Copyright (c) 2003, 2004 IBM Corporation 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: IBM Corporation - initial API and implementation
+ **************************************************************************************************/
+package org.eclipse.wst.common.internal.emf.utilities;
+
+public class FeatureValueConversionException extends RuntimeException {
+
+ /**
+ * Constructor for FeatureValueConversionException.
+ */
+ public FeatureValueConversionException() {
+ super();
+ }
+
+ /**
+ * Constructor for FeatureValueConversionException.
+ *
+ * @param s
+ */
+ public FeatureValueConversionException(String s) {
+ super(s);
+ }
+
+}
\ No newline at end of file
diff --git a/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/utilities/FeatureValueConverter.java b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/utilities/FeatureValueConverter.java
new file mode 100644
index 0000000..786a687
--- /dev/null
+++ b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/utilities/FeatureValueConverter.java
@@ -0,0 +1,32 @@
+/*******************************************************************************
+ * Copyright (c) 2003, 2004 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.wst.common.internal.emf.utilities;
+
+
+
+import org.eclipse.emf.ecore.EStructuralFeature;
+
+/**
+ * Insert the type's description here. Creation date: (5/10/2001 2:46:54 PM)
+ *
+ * @author: Administrator
+ */
+public interface FeatureValueConverter {
+ static final FeatureValueConverter DEFAULT = new DefaultFeatureValueConverter();
+
+ /**
+ * Convert
+ *
+ * @aValue to the type of
+ * @aFeature.
+ */
+ Object convertValue(Object aValue, EStructuralFeature aFeature);
+}
\ No newline at end of file
diff --git a/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/utilities/ICommand.java b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/utilities/ICommand.java
new file mode 100644
index 0000000..5ed817b
--- /dev/null
+++ b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/utilities/ICommand.java
@@ -0,0 +1,37 @@
+/*******************************************************************************
+ * Copyright (c) 2003, 2005 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.wst.common.internal.emf.utilities;
+
+import org.eclipse.core.resources.IResource;
+import org.eclipse.core.resources.IResourceDelta;
+import org.eclipse.core.runtime.CoreException;
+
+/**
+ * @author John Mourra
+ */
+public interface ICommand {
+
+ /*
+ * This will contain the multi-selection of objects to deploy. This selection could be used to
+ * filter elements within a Module. Any other setup code should be done here...
+ */
+ void init(Object[] selection);
+
+ /**
+ * @param resource
+ * @param delta
+ * @param context
+ * @return
+ * @throws CoreException
+ */
+ public boolean execute(IResource resource, IResourceDelta delta, ICommandContext context) throws CoreException;
+
+}
diff --git a/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/utilities/ICommandContext.java b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/utilities/ICommandContext.java
new file mode 100644
index 0000000..e642717
--- /dev/null
+++ b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/utilities/ICommandContext.java
@@ -0,0 +1,37 @@
+/*******************************************************************************
+ * Copyright (c) 2003, 2005 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.wst.common.internal.emf.utilities;
+
+import java.util.Map;
+
+import org.eclipse.core.runtime.IProgressMonitor;
+import org.eclipse.emf.ecore.resource.ResourceSet;
+
+/**
+ * @author John Mourra
+ */
+public interface ICommandContext {
+
+ /**
+ * @return
+ */
+ public IProgressMonitor getProgressMonitor();
+
+ /**
+ * @return
+ */
+ public Map getConfigurationProperties();
+
+ /**
+ * @return
+ */
+ public ResourceSet getResourceSet();
+}
diff --git a/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/utilities/IDUtil.java b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/utilities/IDUtil.java
new file mode 100644
index 0000000..388986c
--- /dev/null
+++ b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/utilities/IDUtil.java
@@ -0,0 +1,72 @@
+/*******************************************************************************
+ * Copyright (c) 2003, 2005 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.wst.common.internal.emf.utilities;
+
+import org.eclipse.emf.ecore.EClass;
+import org.eclipse.emf.ecore.EObject;
+import org.eclipse.emf.ecore.resource.Resource;
+import org.eclipse.emf.ecore.xmi.XMLResource;
+
+public class IDUtil {
+
+ /**
+ * This method is invoked to assign a unique ID to the object. The object must be contained in a
+ * resource.
+ */
+ public static void assignID(EObject object) {
+ Resource aResource = object.eResource();
+ if (aResource instanceof XMLResource)
+ assignID(object, (XMLResource) aResource);
+
+ }
+
+ public static String getOrAssignID(EObject object) {
+ Resource aResource = object.eResource();
+ if (aResource instanceof XMLResource)
+ return getOrAssignID(object, (XMLResource) aResource);
+ return null;
+ }
+
+ public static String getOrAssignID(EObject object, XMLResource aResource) {
+ String id = aResource.getID(object);
+ if (id == null)
+ return assignID(object, aResource);
+ return id;
+ }
+
+ public static String assignID(EObject object, XMLResource aResource) {
+ String name = getBaseIDForAssignment(object);
+ if (name == null)
+ return null;
+ String id = ensureUniqueID(aResource, name);
+ aResource.setID(object, id);
+ return id;
+ }
+
+ protected static String ensureUniqueID(XMLResource aResource, String baseIDName) {
+ baseIDName += "_"; //$NON-NLS-1$
+ //Change to use the current time instead of incremental numbers to help
+ //support team development.
+ long currentTime = System.currentTimeMillis();
+ String id = baseIDName + currentTime;
+ while (aResource.getEObject(id) != null) {
+ ++currentTime;
+ id = baseIDName + currentTime;
+ }
+ return id;
+ }
+
+ protected static String getBaseIDForAssignment(EObject object) {
+ EClass metaO = object.eClass();
+ return metaO.getName();
+ }
+
+}
diff --git a/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/utilities/InvalidPasswordCipherException.java b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/utilities/InvalidPasswordCipherException.java
new file mode 100644
index 0000000..5ff513b
--- /dev/null
+++ b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/utilities/InvalidPasswordCipherException.java
@@ -0,0 +1,16 @@
+/***************************************************************************************************
+ * Copyright (c) 2003, 2004 IBM Corporation 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: IBM Corporation - initial API and implementation
+ **************************************************************************************************/
+package org.eclipse.wst.common.internal.emf.utilities;
+
+
+import org.omg.CORBA.UserException;
+
+public class InvalidPasswordCipherException extends UserException {
+}
+
diff --git a/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/utilities/InvalidPasswordDecodingException.java b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/utilities/InvalidPasswordDecodingException.java
new file mode 100644
index 0000000..2e16808
--- /dev/null
+++ b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/utilities/InvalidPasswordDecodingException.java
@@ -0,0 +1,16 @@
+/***************************************************************************************************
+ * Copyright (c) 2003, 2004 IBM Corporation 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: IBM Corporation - initial API and implementation
+ **************************************************************************************************/
+package org.eclipse.wst.common.internal.emf.utilities;
+
+
+import org.omg.CORBA.UserException;
+
+public class InvalidPasswordDecodingException extends UserException {
+}
+
diff --git a/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/utilities/InvalidPasswordEncodingException.java b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/utilities/InvalidPasswordEncodingException.java
new file mode 100644
index 0000000..dd882d7
--- /dev/null
+++ b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/utilities/InvalidPasswordEncodingException.java
@@ -0,0 +1,16 @@
+/***************************************************************************************************
+ * Copyright (c) 2003, 2004 IBM Corporation 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: IBM Corporation - initial API and implementation
+ **************************************************************************************************/
+package org.eclipse.wst.common.internal.emf.utilities;
+
+
+import org.omg.CORBA.UserException;
+
+public class InvalidPasswordEncodingException extends UserException {
+}
+
diff --git a/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/utilities/IsLoadingDetector.java b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/utilities/IsLoadingDetector.java
new file mode 100644
index 0000000..d7d114c
--- /dev/null
+++ b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/utilities/IsLoadingDetector.java
@@ -0,0 +1,41 @@
+/***************************************************************************************************
+ * Copyright (c) 2003, 2004 IBM Corporation 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: IBM Corporation - initial API and implementation
+ **************************************************************************************************/
+/*
+ * Created on Apr 1, 2003
+ *
+ * To change the template for this generated file go to Window>Preferences>Java>Code Generation>Code
+ * and Comments
+ */
+package org.eclipse.wst.common.internal.emf.utilities;
+
+import org.eclipse.emf.common.notify.Adapter;
+import org.eclipse.emf.common.notify.Notification;
+import org.eclipse.emf.common.notify.Notifier;
+
+
+public class IsLoadingDetector implements Adapter {
+ public static final IsLoadingDetector INSTANCE = new IsLoadingDetector();
+
+ private IsLoadingDetector() {
+ }
+
+ public void notifyChanged(Notification notification) {
+ }
+
+ public Notifier getTarget() {
+ return null;
+ }
+
+ public void setTarget(Notifier newTarget) {
+ }
+
+ public boolean isAdapterForType(Object type) {
+ return type == this;
+ }
+}
\ No newline at end of file
diff --git a/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/utilities/IsLoadingProxyAdapter.java b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/utilities/IsLoadingProxyAdapter.java
new file mode 100644
index 0000000..a75b865
--- /dev/null
+++ b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/utilities/IsLoadingProxyAdapter.java
@@ -0,0 +1,93 @@
+/*******************************************************************************
+ * Copyright (c) 2003, 2005 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+/*
+ * Created on Apr 1, 2003
+ *
+ * To change the template for this generated file go to
+ * Window>Preferences>Java>Code Generation>Code and Comments
+ */
+package org.eclipse.wst.common.internal.emf.utilities;
+
+import org.eclipse.emf.common.notify.Adapter;
+import org.eclipse.emf.common.notify.Notification;
+import org.eclipse.emf.common.notify.impl.AdapterImpl;
+import org.eclipse.emf.ecore.EObject;
+import org.eclipse.emf.ecore.resource.Resource;
+
+/**
+ * @author DABERG
+ *
+ * To change the template for this generated type comment go to Window>Preferences>Java>Code
+ * Generation>Code and Comments
+ */
+public class IsLoadingProxyAdapter extends AdapterImpl {
+ private Resource resource;
+ private Adapter targetAdapter;
+ private EObject targetObject;
+
+ public IsLoadingProxyAdapter(Adapter aTargetAdapter, EObject aTargetObject) {
+ targetAdapter = aTargetAdapter;
+ targetObject = aTargetObject;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.eclipse.emf.common.notify.impl.AdapterImpl#notifyChanged(org.eclipse.emf.common.notify.Notification)
+ */
+ public void notifyChanged(Notification msg) {
+ if (resource != null) {
+ //listen for the remove of the loading adapter
+ if (msg.getFeatureID(null) == Resource.RESOURCE__IS_LOADED && msg.getEventType() == Notification.SET) {
+ removeProxySupport();
+ reset();
+ }
+ } else if (cacheResource()) {
+ targetAdapter.notifyChanged(msg);
+ reset();
+ }
+ }
+
+ /**
+ * Cache the resource variable and return true if we removed the proxy support.
+ */
+ private boolean cacheResource() {
+ if (getTarget() != null) {
+ EObject eObj = (EObject) getTarget();
+ resource = eObj.eResource();
+ if (resource != null) {
+ eObj.eAdapters().remove(this);
+ if (ExtendedEcoreUtil.isLoading(resource))
+ resource.eAdapters().add(this);
+ else {
+ targetObject.eAdapters().add(targetAdapter);
+ return true;
+ }
+ }
+ }
+ return false;
+ }
+
+ /**
+ *
+ */
+ private void removeProxySupport() {
+ getTarget().eAdapters().remove(this);
+ targetObject.eAdapters().add(targetAdapter);
+ }
+
+ private void reset() {
+ resource = null;
+ targetAdapter = null;
+ targetObject = null;
+ }
+
+}
diff --git a/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/utilities/Namespace.java b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/utilities/Namespace.java
new file mode 100644
index 0000000..1a4a736
--- /dev/null
+++ b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/utilities/Namespace.java
@@ -0,0 +1,42 @@
+/***************************************************************************************************
+ * Copyright (c) 2003, 2004 IBM Corporation 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: IBM Corporation - initial API and implementation
+ **************************************************************************************************/
+/*
+ * Created on Aug 20, 2003
+ *
+ */
+package org.eclipse.wst.common.internal.emf.utilities;
+
+
+public class Namespace {
+
+ protected String prefix;
+ protected String nsURI;
+
+
+ public Namespace(String prefix, String uri) {
+ this.prefix = prefix;
+ this.nsURI = uri;
+ }
+
+ public String getNsURI() {
+ return nsURI;
+ }
+
+ public String getPrefix() {
+ return prefix;
+ }
+
+ public void setNsURI(String string) {
+ nsURI = string;
+ }
+
+ public void setPrefix(String string) {
+ prefix = string;
+ }
+}
\ No newline at end of file
diff --git a/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/utilities/NamespaceAdapter.java b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/utilities/NamespaceAdapter.java
new file mode 100644
index 0000000..0bdac76
--- /dev/null
+++ b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/utilities/NamespaceAdapter.java
@@ -0,0 +1,205 @@
+/*******************************************************************************
+ * Copyright (c) 2003, 2005 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+/*
+ * Created on Aug 20, 2003
+ *
+ */
+package org.eclipse.wst.common.internal.emf.utilities;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.eclipse.emf.common.notify.impl.AdapterImpl;
+import org.eclipse.emf.common.notify.impl.NotificationImpl;
+import org.eclipse.emf.ecore.EObject;
+import org.eclipse.emf.ecore.EStructuralFeature;
+import org.eclipse.emf.ecore.impl.EStructuralFeatureImpl;
+import org.eclipse.emf.ecore.util.EcoreUtil;
+
+
+/**
+ * Internal class used to hold namespaces parsed from an XML file using the xmlns:prefix="aURI"
+ * syntax
+ */
+public class NamespaceAdapter extends AdapterImpl implements CloneablePublic {
+
+ protected final static String ADAPTER_TYPE = NamespaceAdapter.class.getName();
+ protected Map prefixesToNS;
+ protected List namespaces;
+
+ public final static EStructuralFeature NOTIFICATION_FEATURE = new EStructuralFeatureImpl() {
+ };
+
+ private static class Notification extends NotificationImpl {
+
+ /**
+ * @param eventType
+ * @param oldValue
+ * @param newValue
+ */
+ public Notification(int eventType, Object oldValue, Object newValue) {
+ super(eventType, oldValue, newValue);
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.eclipse.emf.common.notify.impl.NotificationImpl#getFeature()
+ */
+ public Object getFeature() {
+ return NOTIFICATION_FEATURE;
+ }
+ }
+
+ protected NamespaceAdapter() {
+ super();
+ }
+
+ public static void addNamespace(String prefix, String uri, EObject obj) {
+ if (obj == null)
+ return;
+ NamespaceAdapter adapter = getAdapter(obj);
+ if (adapter != null)
+ adapter.addNamespace(prefix, uri);
+ }
+
+ public static void removeNamespace(String prefix, EObject obj) {
+ if (obj == null)
+ return;
+ NamespaceAdapter adapter = retrieveExistingAdapter(obj);
+ if (adapter != null)
+ adapter.removeNamespace(prefix);
+ }
+
+ /**
+ * Facade method for resolving prefixes to an actual namespace URI. Used for objects contained
+ * by instances of {@link com.ibm.etools.emf2xml.TranslatorResource}. Walks up the object
+ * containment path until a namespace is found, or returns null.
+ */
+ public static String getResolvedNamespaceURI(String prefix, EObject obj) {
+ if (prefix == null || obj == null)
+ return null;
+ EObject container = obj;
+ String nsURI;
+ while (container != null) {
+ nsURI = getNamespaceURIAtThisLevel(prefix, container);
+ if (nsURI != null)
+ return nsURI;
+ container = container.eContainer();
+ }
+ return null;
+ }
+
+ public static String getNamespaceURIAtThisLevel(String prefix, EObject obj) {
+ if (obj == null)
+ return null;
+ NamespaceAdapter adapter = retrieveExistingAdapter(obj);
+ return adapter == null ? null : adapter.getNamespaceURI(prefix);
+ }
+
+ public static List getNamespaces(EObject obj) {
+ if (obj == null)
+ return Collections.EMPTY_LIST;
+ NamespaceAdapter adapter = retrieveExistingAdapter(obj);
+ return adapter == null ? null : adapter.getNamespaces();
+
+ }
+
+ protected static NamespaceAdapter retrieveExistingAdapter(EObject obj) {
+ return (NamespaceAdapter) EcoreUtil.getExistingAdapter(obj, ADAPTER_TYPE);
+ }
+
+ protected static NamespaceAdapter getAdapter(EObject obj) {
+ NamespaceAdapter adapter = retrieveExistingAdapter(obj);
+ return adapter == null ? createAdapter(obj) : adapter;
+ }
+
+ protected static NamespaceAdapter createAdapter(EObject obj) {
+ NamespaceAdapter adapter = new NamespaceAdapter();
+ adapter.setTarget(obj);
+ obj.eAdapters().add(adapter);
+ return adapter;
+ }
+
+ protected void addNamespace(String prefix, String uri) {
+ Namespace ns = new Namespace(prefix, uri);
+ if (namespaces == null)
+ namespaces = new ArrayList();
+ if (prefixesToNS == null)
+ prefixesToNS = new HashMap();
+
+ prefixesToNS.put(prefix, ns);
+ namespaces.add(ns);
+ fireNotification(org.eclipse.emf.common.notify.Notification.ADD, null, ns);
+
+ }
+
+ protected void removeNamespace(String prefix) {
+ Namespace ns = null;
+ if (prefixesToNS != null)
+ ns = (Namespace) prefixesToNS.get(prefix);
+
+ if (ns != null)
+ namespaces.remove(ns);
+ fireNotification(org.eclipse.emf.common.notify.Notification.REMOVE, ns, null);
+ }
+
+ protected String getNamespaceURI(String prefix) {
+ if (prefixesToNS == null)
+ return null;
+ Namespace ns = (Namespace) prefixesToNS.get(prefix);
+ if (ns != null)
+ return ns.getNsURI();
+ return null;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.eclipse.emf.common.notify.impl.AdapterImpl#isAdapterForType(java.lang.Object)
+ */
+ public boolean isAdapterForType(Object type) {
+ return ADAPTER_TYPE.equals(type);
+ }
+
+ public List getNamespaces() {
+ return namespaces == null ? Collections.EMPTY_LIST : Collections.unmodifiableList(namespaces);
+ }
+
+ protected void fireNotification(int type, Object oldValue, Object newValue) {
+ if (target != null)
+ target.eNotify(new Notification(type, oldValue, newValue));
+ }
+
+ public boolean hasNamespaces() {
+ return namespaces != null && !namespaces.isEmpty();
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see com.ibm.etools.emf.ecore.utilities.CloneablePublic#clone()
+ */
+ public Object clone() {
+ NamespaceAdapter result = new NamespaceAdapter();
+ if (hasNamespaces()) {
+ for (int i = 0; i < namespaces.size(); i++) {
+ Namespace ns = (Namespace) namespaces.get(i);
+ result.addNamespace(ns.getPrefix(), ns.getNsURI());
+ }
+ }
+ return result;
+ }
+
+}
diff --git a/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/utilities/PassthruEncoderDecoder.java b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/utilities/PassthruEncoderDecoder.java
new file mode 100644
index 0000000..e684059
--- /dev/null
+++ b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/utilities/PassthruEncoderDecoder.java
@@ -0,0 +1,41 @@
+/*******************************************************************************
+ * Copyright (c) 2003, 2004 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.wst.common.internal.emf.utilities;
+
+
+/**
+ * A passthru EncoderDecoder implementation
+ */
+public class PassthruEncoderDecoder extends EncoderDecoderAdapter implements EncoderDecoder {
+ public static final PassthruEncoderDecoder INSTANCE = new PassthruEncoderDecoder();
+ public static final String KEY = PassthruEncoderDecoder.class.getName();
+
+ /**
+ * EncoderDecoderAdapter constructor comment.
+ */
+ private PassthruEncoderDecoder() {
+ super();
+ }
+
+ /**
+ * Returns a decoded version of the value.
+ */
+ public String decode(String value) {
+ return value;
+ }
+
+ /**
+ * Returns an encoded version of the value.
+ */
+ public String encode(String value) {
+ return value;
+ }
+}
\ No newline at end of file
diff --git a/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/utilities/PasswordCipherUtil.java b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/utilities/PasswordCipherUtil.java
new file mode 100644
index 0000000..f237158
--- /dev/null
+++ b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/utilities/PasswordCipherUtil.java
@@ -0,0 +1,66 @@
+/***************************************************************************************************
+ * Copyright (c) 2003, 2004 IBM Corporation 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: IBM Corporation - initial API and implementation
+ **************************************************************************************************/
+package org.eclipse.wst.common.internal.emf.utilities;
+
+public class PasswordCipherUtil {
+ private static final String DEFAULT_SUPPORTED_CRYPTO_ALGORITHMS[] = {"xor"}; //$NON-NLS-1$
+ private static String _supported_crypto_algorithms[];
+
+ public PasswordCipherUtil() {
+ }
+
+ public static byte[] decipher(byte abyte0[], String s) throws InvalidPasswordCipherException, UnsupportedCryptoAlgorithmException {
+ if (s == null)
+ throw new UnsupportedCryptoAlgorithmException();
+ byte abyte1[] = null;
+ if (s.equalsIgnoreCase(DEFAULT_SUPPORTED_CRYPTO_ALGORITHMS[0]))
+ abyte1 = xor(abyte0);
+ else
+ throw new UnsupportedCryptoAlgorithmException();
+
+ if (abyte1 == null)
+ throw new InvalidPasswordCipherException();
+
+ return abyte1;
+ }
+
+ public static byte[] encipher(byte abyte0[], String s) throws InvalidPasswordCipherException, UnsupportedCryptoAlgorithmException {
+ if (s == null)
+ throw new UnsupportedCryptoAlgorithmException();
+ byte abyte1[] = null;
+ if (s.equalsIgnoreCase(DEFAULT_SUPPORTED_CRYPTO_ALGORITHMS[0]))
+ abyte1 = xor(abyte0);
+ else
+ throw new UnsupportedCryptoAlgorithmException();
+
+ if (abyte1 == null)
+ throw new InvalidPasswordCipherException();
+ return abyte1;
+ }
+
+ public static String[] getSupportedCryptoAlgorithms() {
+ return _supported_crypto_algorithms;
+ }
+
+ private static byte[] xor(byte abyte0[]) {
+ byte abyte1[] = null;
+ if (abyte0 != null) {
+ abyte1 = new byte[abyte0.length];
+ for (int i = 0; i < abyte0.length; i++)
+ abyte1[i] = (byte) (0x5f ^ abyte0[i]);
+ }
+ return abyte1;
+ }
+
+ static {
+ _supported_crypto_algorithms = null;
+ if (_supported_crypto_algorithms == null)
+ _supported_crypto_algorithms = DEFAULT_SUPPORTED_CRYPTO_ALGORITHMS;
+ }
+}
\ No newline at end of file
diff --git a/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/utilities/PasswordEncoderDecoder.java b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/utilities/PasswordEncoderDecoder.java
new file mode 100644
index 0000000..2c82ced
--- /dev/null
+++ b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/utilities/PasswordEncoderDecoder.java
@@ -0,0 +1,28 @@
+/***************************************************************************************************
+ * Copyright (c) 2003, 2004 IBM Corporation 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: IBM Corporation - initial API and implementation
+ **************************************************************************************************/
+package org.eclipse.wst.common.internal.emf.utilities;
+
+public class PasswordEncoderDecoder extends EncoderDecoderAdapter implements EncoderDecoder {
+ public static final String KEY = "password-security-coder"; //$NON-NLS-1$
+
+ public PasswordEncoderDecoder() {
+ }
+
+ public String decode(String s) {
+ return PasswordUtil.passwordDecode(s);
+ }
+
+ public String encode(String s) {
+ return PasswordUtil.passwordEncode(s);
+ }
+
+ public Object getKey() {
+ return KEY;
+ }
+}
\ No newline at end of file
diff --git a/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/utilities/PasswordUtil.java b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/utilities/PasswordUtil.java
new file mode 100644
index 0000000..012f2c2
--- /dev/null
+++ b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/utilities/PasswordUtil.java
@@ -0,0 +1,331 @@
+/***************************************************************************************************
+ * Copyright (c) 2003, 2004 IBM Corporation 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: IBM Corporation - initial API and implementation
+ **************************************************************************************************/
+package org.eclipse.wst.common.internal.emf.utilities;
+
+
+import java.io.UnsupportedEncodingException;
+
+public class PasswordUtil {
+ public static final String STRING_CONVERSION_CODE = "UTF8"; //$NON-NLS-1$
+ public static final String EMPTY_STRING = ""; //$NON-NLS-1$
+ public static final byte[] EMPTY_BYTE_ARRAY = new byte[0];
+ public static final String DEFAULT_CRYPTO_ALGORITHM;
+ private static final String SUPPORTED_CRYPTO_ALGORITHMS[];
+ private static final byte BASE64_ENCODE_MAP[];
+ private static final byte BASE64_DECODE_MAP[];
+
+ public PasswordUtil() {
+ }
+
+ public static String decode(String s) throws InvalidPasswordDecodingException, UnsupportedCryptoAlgorithmException {
+ if (s == null)
+ throw new InvalidPasswordDecodingException();
+ String s1 = getCryptoAlgorithm(s);
+ if (s1 == null)
+ throw new InvalidPasswordDecodingException();
+
+ if (!isValidCryptoAlgorithm(s1))
+ throw new UnsupportedCryptoAlgorithmException();
+
+ String s2 = decode_password(removeCryptoAlgorithmTag(s), s1);
+ if (s2 == null)
+ throw new InvalidPasswordDecodingException();
+ return s2;
+ }
+
+ public static String encode(String s) throws InvalidPasswordEncodingException, UnsupportedCryptoAlgorithmException {
+ return encode(s, DEFAULT_CRYPTO_ALGORITHM);
+ }
+
+ public static String encode(String s, String s1) throws InvalidPasswordEncodingException, UnsupportedCryptoAlgorithmException {
+ if (!isValidCryptoAlgorithm(s1))
+ throw new UnsupportedCryptoAlgorithmException();
+ if (s == null)
+ throw new InvalidPasswordEncodingException();
+
+ if (getCryptoAlgorithm(s) != null)
+ throw new InvalidPasswordEncodingException();
+
+ String s2 = encode_password(s.trim(), s1.trim());
+ if (s2 == null)
+ throw new InvalidPasswordEncodingException();
+ return s2;
+ }
+
+ public static String getCryptoAlgorithm(String s) {
+ String s1 = null;
+ if (s != null) {
+ s = s.trim();
+ if (s.length() >= 2) {
+ int i = s.indexOf("{"); //$NON-NLS-1$
+ if (i == 0) {
+ int j = s.indexOf("}", ++i); //$NON-NLS-1$
+ if (j > 0)
+ if (i < j)
+ s1 = s.substring(i, j).trim();
+ else
+ s1 = EMPTY_STRING;
+ }
+ }
+ }
+ return s1;
+ }
+
+ public static String getCryptoAlgorithmTag(String s) {
+ String s1 = null;
+ String s2 = getCryptoAlgorithm(s);
+ if (s2 != null) {
+ StringBuffer stringbuffer = new StringBuffer("{"); //$NON-NLS-1$
+ if (s2.length() > 0)
+ stringbuffer.append(s2);
+ stringbuffer.append("}"); //$NON-NLS-1$
+ s1 = stringbuffer.toString();
+ }
+ return s1;
+ }
+
+ public static boolean isValidCryptoAlgorithm(String s) {
+ if (s != null) {
+ s = s.trim();
+ if (s.length() == 0)
+ return true;
+ for (int i = 0; i < SUPPORTED_CRYPTO_ALGORITHMS.length; i++)
+ if (s.equalsIgnoreCase(SUPPORTED_CRYPTO_ALGORITHMS[i]))
+ return true;
+ }
+ return false;
+ }
+
+ public static boolean isValidCryptoAlgorithmTag(String s) {
+ return isValidCryptoAlgorithm(getCryptoAlgorithm(s));
+ }
+
+ public static String passwordDecode(String s) {
+ if (s == null)
+ return null;
+ String s1 = getCryptoAlgorithm(s);
+ if (s1 == null)
+ return s;
+ if (!isValidCryptoAlgorithm(s1))
+ return null;
+ return decode_password(removeCryptoAlgorithmTag(s), s1);
+ }
+
+ public static String passwordEncode(String s) {
+ return passwordEncode(s, DEFAULT_CRYPTO_ALGORITHM);
+ }
+
+ public static String passwordEncode(String s, String s1) {
+ if (!isValidCryptoAlgorithm(s1))
+ return null;
+ if (s == null)
+ return null;
+ String s2 = getCryptoAlgorithm(s);
+ if (s2 != null) {
+ if (s2.equalsIgnoreCase(s1.trim()))
+ return s.trim();
+ return null;
+ }
+ return encode_password(s.trim(), s1.trim());
+ }
+
+ public static String removeCryptoAlgorithmTag(String s) {
+ String s1 = null;
+ if (s != null) {
+ s = s.trim();
+ if (s.length() >= 2) {
+ int i = s.indexOf("{"); //$NON-NLS-1$
+ if (i == 0) {
+ int j = s.indexOf("}", ++i); //$NON-NLS-1$
+ if (j > 0)
+ if (++j < s.length())
+ s1 = s.substring(j).trim();
+ else
+ s1 = EMPTY_STRING;
+ }
+ }
+ }
+ return s1;
+ }
+
+ private static byte[] convert_to_bytes(String s) {
+ byte abyte0[] = null;
+ if (s != null)
+ if (s.length() == 0)
+ abyte0 = EMPTY_BYTE_ARRAY;
+ else
+ try {
+ abyte0 = s.getBytes(STRING_CONVERSION_CODE);
+ } catch (UnsupportedEncodingException unsupportedencodingexception) {
+ abyte0 = null;
+ }
+ return abyte0;
+ }
+
+ private static String convert_to_string(byte abyte0[]) {
+ String s = null;
+ if (abyte0 != null)
+ if (abyte0.length == 0)
+ s = EMPTY_STRING;
+ else
+ try {
+ s = new String(abyte0, STRING_CONVERSION_CODE);
+ } catch (UnsupportedEncodingException unsupportedencodingexception) {
+ s = null;
+ }
+ return s;
+ }
+
+ private static byte[] convert_viewable_to_bytes(String s) {
+ byte abyte0[] = null;
+ if (s != null)
+ if (s.length() == 0)
+ abyte0 = EMPTY_BYTE_ARRAY;
+ else
+ try {
+ abyte0 = base64Decode(convert_to_bytes(s));
+ } catch (Exception exception) {
+ abyte0 = null;
+ }
+ return abyte0;
+ }
+
+ private static byte[] base64Decode(byte abyte0[]) {
+ int i;
+ for (i = abyte0.length; abyte0[--i] == 61;);
+ byte abyte1[] = new byte[(i + 1) - abyte0.length / 4];
+ for (int j = 0; j < abyte0.length; j++)
+ abyte0[j] = BASE64_DECODE_MAP[abyte0[j]];
+ int k = abyte1.length - 2;
+ int l = 0;
+ int i1;
+ for (i1 = 0; l < k; i1 += 4) {
+ abyte1[l] = (byte) (abyte0[i1] << 2 & 0xff | abyte0[i1 + 1] >>> 4 & 0x3);
+ abyte1[l + 1] = (byte) (abyte0[i1 + 1] << 4 & 0xff | abyte0[i1 + 2] >>> 2 & 0xf);
+ abyte1[l + 2] = (byte) (abyte0[i1 + 2] << 6 & 0xff | abyte0[i1 + 3] & 0x3f);
+ l += 3;
+ }
+ if (l < abyte1.length) {
+ abyte1[l++] = (byte) (abyte0[i1] << 2 & 0xff | abyte0[i1 + 1] >>> 4 & 0x3);
+ if (l < abyte1.length)
+ abyte1[l] = (byte) (abyte0[i1 + 1] << 4 & 0xff | abyte0[i1 + 2] >>> 2 & 0xf);
+ }
+ return abyte1;
+ }
+
+ private static String convert_viewable_to_string(byte abyte0[]) {
+ String s = null;
+ if (abyte0 != null)
+ if (abyte0.length == 0)
+ s = EMPTY_STRING;
+ else
+ try {
+ s = convert_to_string(base64Encode(abyte0));
+ } catch (Exception exception) {
+ s = null;
+ }
+ return s;
+ }
+
+ private static byte[] base64Encode(byte abyte0[]) {
+ byte abyte1[] = new byte[((abyte0.length + 2) / 3) * 4];
+ int i = 0;
+ int j = 0;
+ for (; i < abyte0.length - 2; i += 3) {
+ abyte1[j++] = BASE64_ENCODE_MAP[abyte0[i] >>> 2 & 0x3f];
+ abyte1[j++] = BASE64_ENCODE_MAP[abyte0[i + 1] >>> 4 & 0xf | abyte0[i] << 4 & 0x3f];
+ abyte1[j++] = BASE64_ENCODE_MAP[abyte0[i + 2] >>> 6 & 0x3 | abyte0[i + 1] << 2 & 0x3f];
+ abyte1[j++] = BASE64_ENCODE_MAP[abyte0[i + 2] & 0x3f];
+ }
+ if (i < abyte0.length) {
+ abyte1[j++] = BASE64_ENCODE_MAP[abyte0[i] >>> 2 & 0x3f];
+ if (i < abyte0.length - 1) {
+ abyte1[j++] = BASE64_ENCODE_MAP[abyte0[i + 1] >>> 4 & 0xf | abyte0[i] << 4 & 0x3f];
+ abyte1[j++] = BASE64_ENCODE_MAP[abyte0[i + 1] << 2 & 0x3f];
+ } else {
+ abyte1[j++] = BASE64_ENCODE_MAP[abyte0[i] << 4 & 0x3f];
+ }
+ }
+ for (; j < abyte1.length; j++)
+ abyte1[j] = 61;
+ return abyte1;
+ }
+
+ private static String decode_password(String s, String s1) {
+ StringBuffer stringbuffer = new StringBuffer();
+ if (s1.length() == 0) {
+ stringbuffer.append(s);
+ } else {
+ String s2 = null;
+ if (s.length() > 0) {
+ byte abyte0[] = convert_viewable_to_bytes(s);
+ if (abyte0 == null)
+ return null;
+ if (abyte0.length > 0) {
+ byte abyte1[] = null;
+ try {
+ abyte1 = PasswordCipherUtil.decipher(abyte0, s1);
+ } catch (InvalidPasswordCipherException invalidpasswordcipherexception) {
+ return null;
+ } catch (UnsupportedCryptoAlgorithmException unsupportedcryptoalgorithmexception) {
+ return null;
+ }
+ if (abyte1 != null && abyte1.length > 0)
+ s2 = convert_to_string(abyte1);
+ }
+ }
+ if (s2 != null && s2.length() > 0)
+ stringbuffer.append(s2);
+ }
+ return stringbuffer.toString();
+ }
+
+ private static String encode_password(String s, String s1) {
+ StringBuffer stringbuffer = new StringBuffer("{"); //$NON-NLS-1$
+ if (s1.length() == 0) {
+ stringbuffer.append("}").append(s); //$NON-NLS-1$
+ } else {
+ stringbuffer.append(s1).append("}"); //$NON-NLS-1$
+ String s2 = null;
+ if (s.length() > 0) {
+ byte abyte0[] = convert_to_bytes(s);
+ if (abyte0.length > 0) {
+ byte abyte1[] = null;
+ try {
+ abyte1 = PasswordCipherUtil.encipher(abyte0, s1);
+ } catch (InvalidPasswordCipherException invalidpasswordcipherexception) {
+ return null;
+ } catch (UnsupportedCryptoAlgorithmException unsupportedcryptoalgorithmexception) {
+ return null;
+ }
+ if (abyte1 != null && abyte1.length > 0) {
+ s2 = convert_viewable_to_string(abyte1);
+ if (s2 == null)
+ return null;
+ }
+ }
+ }
+ if (s2 != null && s2.length() > 0)
+ stringbuffer.append(s2);
+ }
+ return stringbuffer.toString();
+ }
+
+ static {
+ SUPPORTED_CRYPTO_ALGORITHMS = PasswordCipherUtil.getSupportedCryptoAlgorithms();
+ DEFAULT_CRYPTO_ALGORITHM = SUPPORTED_CRYPTO_ALGORITHMS[0];
+ byte abyte0[] = {65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 43, 47};
+ BASE64_ENCODE_MAP = abyte0;
+ BASE64_DECODE_MAP = new byte[128];
+ for (int i = 0; i < BASE64_DECODE_MAP.length; i++)
+ BASE64_DECODE_MAP[i] = -1;
+ for (int j = 0; j < BASE64_ENCODE_MAP.length; j++)
+ BASE64_DECODE_MAP[BASE64_ENCODE_MAP[j]] = (byte) j;
+ }
+}
\ No newline at end of file
diff --git a/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/utilities/PleaseMigrateYourCodeError.java b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/utilities/PleaseMigrateYourCodeError.java
new file mode 100644
index 0000000..5a548d6
--- /dev/null
+++ b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/utilities/PleaseMigrateYourCodeError.java
@@ -0,0 +1,25 @@
+/*******************************************************************************
+ * Copyright (c) 2003, 2006 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.wst.common.internal.emf.utilities;
+
+
+
+/**
+ * @author mdelder
+ *
+ */
+public class PleaseMigrateYourCodeError extends Error {
+
+ //TODO Delete me
+ public PleaseMigrateYourCodeError() {
+ super(WFTUtilsResourceHandler.PleaseMigrateYourCodeError_ERROR_0);
+ }
+}
diff --git a/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/utilities/ResourceDependencyRegister.java b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/utilities/ResourceDependencyRegister.java
new file mode 100644
index 0000000..34ff643
--- /dev/null
+++ b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/utilities/ResourceDependencyRegister.java
@@ -0,0 +1,213 @@
+/***************************************************************************************************
+ * Copyright (c) 2003, 2004 IBM Corporation 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: IBM Corporation - initial API and implementation
+ **************************************************************************************************/
+package org.eclipse.wst.common.internal.emf.utilities;
+
+
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
+
+import org.eclipse.emf.common.notify.Notification;
+import org.eclipse.emf.common.notify.impl.AdapterImpl;
+import org.eclipse.emf.common.util.URI;
+import org.eclipse.emf.ecore.resource.Resource;
+import org.eclipse.emf.ecore.resource.ResourceSet;
+import org.eclipse.emf.ecore.resource.URIConverter;
+
+public class ResourceDependencyRegister {
+ protected static Map GLOBAL_DEPENDENCIES = new HashMap();
+ private static String RESOURCE_DEPENDENCY_TYPE = "ResourceDependencyAdapter"; //$NON-NLS-1$
+ protected Map localDependencies = new HashMap();
+
+ class ResourceDependencyAdapter extends AdapterImpl {
+ Resource dependentResource;
+
+ ResourceDependencyAdapter(Resource aDependentResource) {
+ dependentResource = aDependentResource;
+ dependentResource.eAdapters().add(this);
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.eclipse.emf.common.notify.impl.AdapterImpl#isAdapterForType(java.lang.Object)
+ */
+ public boolean isAdapterForType(Object type) {
+ return RESOURCE_DEPENDENCY_TYPE.equals(type);
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.eclipse.emf.common.notify.impl.AdapterImpl#notifyChanged(org.eclipse.emf.common.notify.Notification)
+ */
+ public void notifyChanged(Notification msg) {
+ //Listen for unloads and removes
+ switch (msg.getFeatureID(null)) {
+ case Resource.RESOURCE__IS_LOADED :
+ if (msg.getNotifier() != dependentResource && msg.getOldBooleanValue() && !msg.getNewBooleanValue())
+ dependentResource.unload();
+ break;
+ case Resource.RESOURCE__RESOURCE_SET :
+ if (msg.getOldValue() != null && msg.getNewValue() == null) {
+ if (msg.getNotifier() == dependentResource)
+ ((Resource) getTarget()).eAdapters().remove(this);
+ else {
+ ResourceSet set = dependentResource.getResourceSet();
+ if (set != null)
+ set.getResources().remove(dependentResource);
+ }
+ }
+ break;
+ }
+ }
+ }
+
+ class ResourceSetListener extends AdapterImpl {
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.eclipse.emf.common.notify.impl.AdapterImpl#notifyChanged(org.eclipse.emf.common.notify.Notification)
+ */
+ public void notifyChanged(Notification msg) {
+ if (msg.getEventType() == Notification.ADD)
+ proccessAddedResource((ResourceSet) msg.getNotifier(), (Resource) msg.getNewValue());
+ }
+ }
+
+ /**
+ * Register a dependency between two URIs. The first parameter, aURIString, is the one that
+ * dependentUriString depends on.
+ *
+ * @param aUriString
+ * java.lang.String
+ * @param dependentUriString
+ * java.lang.String
+ */
+ public static void registerDependency(URI targetURI, URI dependentURI) {
+ if (targetURI != null && dependentURI != null) {
+ GLOBAL_DEPENDENCIES.put(dependentURI, targetURI);
+ }
+ }
+
+ public ResourceDependencyRegister(ResourceSet aResourceSet) {
+ initialize(aResourceSet);
+ }
+
+
+ ResourceDependencyRegister() {
+ super();
+ }
+
+ /**
+ * @param aResourceSet
+ */
+ protected void initialize(ResourceSet aResourceSet) {
+ if (aResourceSet == null)
+ throw new NullPointerException("The ResourceSet cannot be null."); //$NON-NLS-1$
+ initializeLocalDependencies(aResourceSet);
+ setupDependencyAdapters(aResourceSet);
+ setupResourceSetListener(aResourceSet);
+ }
+
+ /**
+ * @param aResourceSet
+ */
+ protected void setupResourceSetListener(ResourceSet aResourceSet) {
+ aResourceSet.eAdapters().add(new ResourceSetListener());
+ }
+
+ /**
+ * @param aResourceSet
+ * @return
+ */
+ protected void setupDependencyAdapters(ResourceSet aResourceSet) {
+ if (!aResourceSet.getResources().isEmpty()) {
+ Iterator it = localDependencies.entrySet().iterator();
+ Map.Entry entry;
+ URI dependentURI, targetURI;
+ while (it.hasNext()) {
+ entry = (Map.Entry) it.next();
+ dependentURI = (URI) entry.getKey();
+ targetURI = (URI) entry.getValue();
+ setupDependencyAdapter(aResourceSet, dependentURI, targetURI);
+ }
+ }
+ }
+
+ /**
+ * @param aResourceSet
+ * @param dependentURI
+ * @param targetURI
+ * @return
+ */
+ protected void setupDependencyAdapter(ResourceSet aResourceSet, URI dependentURI, URI targetURI) {
+ Resource dependent = aResourceSet.getResource(dependentURI, false);
+ if (dependent != null)
+ setupDependencyAdapter(dependent, targetURI, aResourceSet);
+ }
+
+ protected void setupDependencyAdapter(Resource dependent, URI targetURI, ResourceSet aResourceSet) {
+ Resource target = aResourceSet.getResource(targetURI, false);
+ if (target == null)
+ target = aResourceSet.createResource(targetURI);
+ target.eAdapters().add(new ResourceDependencyAdapter(dependent));
+ }
+
+ /**
+ * @param aResourceSet
+ */
+ protected void initializeLocalDependencies(ResourceSet aResourceSet) {
+ URIConverter converter = aResourceSet.getURIConverter();
+ initializeLocalDependencies(converter);
+ }
+
+ /**
+ * @param aResourceSet
+ */
+ protected void initializeLocalDependencies(URIConverter aConverter) {
+ Iterator it = GLOBAL_DEPENDENCIES.entrySet().iterator();
+ Map resolved = new HashMap();
+ Map.Entry entry;
+ URI key, value;
+ while (it.hasNext()) {
+ entry = (Map.Entry) it.next();
+ key = (URI) entry.getKey();
+ value = (URI) entry.getValue();
+ key = normalize(key, aConverter, resolved);
+ value = normalize(value, aConverter, resolved);
+ localDependencies.put(key, value);
+ }
+ }
+
+ /**
+ * @param relativeURI
+ * @param converter
+ * @param resolved
+ * @return
+ */
+ protected URI normalize(URI relativeURI, URIConverter converter, Map resolved) {
+ URI result = (URI) resolved.get(relativeURI);
+ if (result == null) {
+ result = converter.normalize(relativeURI);
+ resolved.put(relativeURI, result);
+ }
+ return result;
+ }
+
+ /**
+ * @param set
+ * @param resource
+ */
+ protected void proccessAddedResource(ResourceSet set, Resource resource) {
+ URI targetURI = (URI) localDependencies.get(resource.getURI());
+ if (targetURI != null)
+ setupDependencyAdapter(resource, targetURI, set);
+ }
+}
\ No newline at end of file
diff --git a/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/utilities/ResourceIsLoadingAdapter.java b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/utilities/ResourceIsLoadingAdapter.java
new file mode 100644
index 0000000..d36ea59
--- /dev/null
+++ b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/utilities/ResourceIsLoadingAdapter.java
@@ -0,0 +1,114 @@
+/*******************************************************************************
+ * Copyright (c) 2005, 2006 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+/*
+ * Created on Oct 26, 2004
+ *
+ * TODO To change the template for this generated file go to
+ * Window - Preferences - Java - Code Style - Code Templates
+ */
+package org.eclipse.wst.common.internal.emf.utilities;
+
+import org.eclipse.emf.common.notify.Adapter;
+import org.eclipse.emf.common.notify.Notification;
+import org.eclipse.emf.common.notify.impl.AdapterImpl;
+import org.eclipse.emf.ecore.resource.Resource;
+import org.eclipse.emf.ecore.util.EcoreUtil;
+
+/**
+ * @author mdelder
+ */
+public class ResourceIsLoadingAdapter extends AdapterImpl implements Adapter {
+
+ private static final Class RESOURCE_IS_LOADING_ADAPTER_CLASS = ResourceIsLoadingAdapter.class;
+
+ public ResourceIsLoadingAdapter() {
+ }
+
+ public static ResourceIsLoadingAdapter findAdapter(Resource aResource) {
+ ResourceIsLoadingAdapter adapter = null;
+ //System.out.println("ResourceIsLoadingAdapter Synchronizing on " + aResource);
+
+ /* Synchronize on the Resource (which will be the target of
+ * the ResourceIsLoadingAdapter in the list, if it exists).
+ *
+ * removeIsLoadingSupport() will coordinate with this
+ * synchronization.
+ */
+ synchronized(aResource.eAdapters()) {
+ adapter = (ResourceIsLoadingAdapter) EcoreUtil.getAdapter(aResource.eAdapters(), ResourceIsLoadingAdapter.class);
+ }
+
+ return adapter;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.eclipse.emf.common.notify.Adapter#notifyChanged(org.eclipse.emf.common.notify.Notification)
+ */
+ public void notifyChanged(Notification notification) {
+
+ if (notification.getNotifier() != null) {
+
+ // listen for the remove of the loading adapter
+ if (isSetLoadedResourceNotification(notification)) removeIsLoadingSupport();
+ }
+ }
+
+ /**
+ * Default implementation is a no-op.
+ */
+ public void waitForResourceToLoad() {
+
+ }
+
+ /**
+ * @param notification
+ * @return
+ */
+ protected boolean isSetLoadedResourceNotification(Notification notification) {
+ return notification.getFeatureID(null) == Resource.RESOURCE__IS_LOADED && notification.getEventType() == Notification.SET;
+ }
+
+ protected void removeIsLoadingSupport() {
+
+ /* Synchronize on the target of the Adapter. If
+ * the list of adapters is searched for a
+ * ResourceIsLoadingAdapter using the
+ * ResourceIsLoadingAdapter.findAdapter() API, then
+ * the access to remove the Adapter using this method
+ * will be coordinated.
+ */
+ if (getTarget() != null) {
+ //System.out.println("ResourceIsLoadingAdapter Synchronizing on " + getTarget());
+ synchronized (getTarget().eAdapters()) {
+ getTarget().eAdapters().remove(this);
+ }
+ }
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.eclipse.emf.common.notify.Adapter#isAdapterForType(java.lang.Object)
+ */
+ public boolean isAdapterForType(Object type) {
+ return type == RESOURCE_IS_LOADING_ADAPTER_CLASS;
+ }
+
+ /**
+ *
+ */
+ public void forceRelease() {
+
+ }
+
+}
diff --git a/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/utilities/ResourceIsLoadingAdapterFactory.java b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/utilities/ResourceIsLoadingAdapterFactory.java
new file mode 100644
index 0000000..5899f5d
--- /dev/null
+++ b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/utilities/ResourceIsLoadingAdapterFactory.java
@@ -0,0 +1,32 @@
+/*******************************************************************************
+ * Copyright (c) 2005, 2006 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+/*
+ * Created on Oct 26, 2004
+ *
+ * TODO To change the template for this generated file go to
+ * Window - Preferences - Java - Code Style - Code Templates
+ */
+package org.eclipse.wst.common.internal.emf.utilities;
+
+
+/**
+ * @author mdelder
+ *
+ */
+public class ResourceIsLoadingAdapterFactory {
+
+ public static ResourceIsLoadingAdapterFactory INSTANCE = new ResourceIsLoadingAdapterFactory();
+
+ public ResourceIsLoadingAdapter createResourceIsLoadingAdapter() {
+ return new ResourceIsLoadingAdapter();
+ }
+
+}
diff --git a/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/utilities/Revisit.java b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/utilities/Revisit.java
new file mode 100644
index 0000000..2ec67d4
--- /dev/null
+++ b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/utilities/Revisit.java
@@ -0,0 +1,43 @@
+/***************************************************************************************************
+ * Copyright (c) 2003, 2004 IBM Corporation 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: IBM Corporation - initial API and implementation
+ **************************************************************************************************/
+package org.eclipse.wst.common.internal.emf.utilities;
+
+
+public class Revisit {
+
+ /**
+ * Revisit constructor comment.
+ */
+ public Revisit() {
+ super();
+ }
+
+ public static void revisit() {
+ }
+
+
+ public static void unComment() {
+ }
+
+ public static void toDo() {
+ }
+
+ public static void refactor() {
+ }
+
+ public static void removeDeprecatedMethod() {
+ }
+
+ public static void deleteMe() {
+ }
+
+ public static void reviewDesign() {
+ }
+}
+
diff --git a/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/utilities/StringUtil.java b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/utilities/StringUtil.java
new file mode 100644
index 0000000..d1f2308
--- /dev/null
+++ b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/utilities/StringUtil.java
@@ -0,0 +1,39 @@
+/*******************************************************************************
+ * Copyright (c) 2003, 2004 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+/*
+ * Created on Mar 18, 2003
+ *
+ * To change this generated comment go to
+ * Window>Preferences>Java>Code Generation>Code and Comments
+ */
+package org.eclipse.wst.common.internal.emf.utilities;
+
+/**
+ * @author schacher
+ *
+ * To change this generated comment go to Window>Preferences>Java>Code Generation>Code and Comments
+ */
+public class StringUtil {
+ /**
+ * Enhanced equality check for two string parameters, that takes into consideration null values.
+ * If both values are null, this will return true.
+ *
+ * @param s1
+ * @param s2
+ * @return boolean
+ */
+ public static boolean stringsEqual(String s1, String s2) {
+ if (s1 == null)
+ return s2 == null;
+ return s1.equals(s2);
+ }
+
+}
\ No newline at end of file
diff --git a/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/utilities/TranslatorManager.java b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/utilities/TranslatorManager.java
new file mode 100644
index 0000000..79ee8b8
--- /dev/null
+++ b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/utilities/TranslatorManager.java
@@ -0,0 +1,168 @@
+/***************************************************************************************************
+ * Copyright (c) 2003, 2006 IBM Corporation 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: IBM Corporation - initial API and implementation
+ **************************************************************************************************/
+package org.eclipse.wst.common.internal.emf.utilities;
+
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Set;
+
+import org.eclipse.core.runtime.CoreException;
+import org.eclipse.core.runtime.IConfigurationElement;
+import org.eclipse.jem.util.RegistryReader;
+import org.eclipse.jem.util.logger.proxy.Logger;
+import org.eclipse.wst.common.internal.emf.plugin.EcoreUtilitiesPlugin;
+import org.eclipse.wst.common.internal.emf.resource.Translator;
+
+/**
+ * This is the TranslatorManager class used by the TranslatorService in order to discover
+ * and cache all of the extended Translators to be used by EMF2DOMAdapterImpl.
+ */
+public class TranslatorManager {
+
+ /**
+ * The singleton TranslatorManager instance
+ */
+ private static final TranslatorManager INSTANCE = new TranslatorManager();
+
+ /**
+ * Cache of all the TranslatorDescriptors
+ */
+ private final Set translators = new HashSet();
+
+ /**
+ * Default static empty array used when no descriptors found
+ */
+ private static final TranslatorDescriptor[] NO_EXTENDED_TRANSLATORS = new TranslatorDescriptor[0];
+
+ /**
+ * Returns the singleton instance of the TranslatorManager
+ * @return TranslatorManager INSTANCE
+ */
+ public static TranslatorManager getInstance() {
+ return INSTANCE;
+ }
+
+ /**
+ * Private constructor
+ */
+ private TranslatorManager() {
+ new TranslatorRegistry().readRegistry();
+ }
+
+ /**
+ * Simple Registry Reader used by Translator Manager to recognize the Translator extensions
+ */
+ private class TranslatorRegistry extends RegistryReader {
+
+ /**
+ * The Translator element of the extension point.
+ */
+ public static final String TRANSLATOR = "translator"; //$NON-NLS-1$
+
+ /**
+ * Default constructor
+ */
+ public TranslatorRegistry() {
+ super(EcoreUtilitiesPlugin.ID, EcoreUtilitiesPlugin.TRANSLATOR_EXTENSTION_POINT);
+ }
+
+ /**
+ * Add the configuration element if it matchs the expected translator element name
+ */
+ public boolean readElement(IConfigurationElement element) {
+ boolean result = false;
+ if (TRANSLATOR.equals(element.getName())) {
+ addTranslatorDescriptor(new TranslatorDescriptor(element));
+ result = true;
+ }
+ return result;
+ }
+ }
+
+ /**
+ * Describes a Translator extension point element
+ */
+ public class TranslatorDescriptor {
+
+ /**
+ * Qualified class name attribute
+ */
+ public static final String CLASSNAME = "className"; //$NON-NLS-1$
+
+ /**
+ * The config element for this Descriptor
+ */
+ private final IConfigurationElement configElement;
+
+ /**
+ * the cached qualified className value of this descriptor
+ */
+ private String className;
+
+ /**
+ * Constructor
+ * @param aConfigElement
+ */
+ public TranslatorDescriptor(IConfigurationElement aConfigElement) {
+ super();
+ configElement = aConfigElement;
+ className = configElement.getAttribute(CLASSNAME);
+ }
+
+ /**
+ * Retrieve the cached value of the qualified class name of the extended Translator
+ * @return String classname
+ */
+ public String getClassName() {
+ return className;
+ }
+
+ /**
+ * Create the actual Translator instance from the configuration element.
+ * @return Translator
+ */
+ public Translator createTranslator() {
+ Translator instance = null;
+ try {
+ instance = (Translator) configElement.createExecutableExtension(CLASSNAME);
+ } catch (CoreException e) {
+ Logger.getLogger().logError(e);
+ }
+ return instance;
+ }
+ }
+
+ /**
+ * Add the TranslatorDescriptor to the cache of descriptor extensions.
+ * @param descriptor
+ */
+ private void addTranslatorDescriptor(TranslatorDescriptor descriptor) {
+ Assert.isNotNull(descriptor);
+ translators.add(descriptor);
+ }
+
+ /**
+ * Find all the associated TranslatorDescriptors for the Traslator extensions defined.
+ * @return TranslatorDescriptor[]
+ */
+ public TranslatorDescriptor[] findTranslators() {
+ List result = new ArrayList();
+ TranslatorDescriptor descriptor = null;
+ for (Iterator translatorsItr = translators.iterator(); translatorsItr.hasNext();) {
+ descriptor = (TranslatorDescriptor) translatorsItr.next();
+ result.add(descriptor);
+ }
+ if (result.size() == 0) {
+ return NO_EXTENDED_TRANSLATORS;
+ }
+ return (TranslatorDescriptor[]) result.toArray(new TranslatorDescriptor[result.size()]);
+ }
+}
diff --git a/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/utilities/TranslatorService.java b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/utilities/TranslatorService.java
new file mode 100644
index 0000000..4012a7b
--- /dev/null
+++ b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/utilities/TranslatorService.java
@@ -0,0 +1,96 @@
+/***************************************************************************************************
+ * Copyright (c) 2003, 2006 IBM Corporation 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: IBM Corporation - initial API and implementation
+ **************************************************************************************************/
+package org.eclipse.wst.common.internal.emf.utilities;
+
+import java.util.HashMap;
+import java.util.Map;
+
+import org.eclipse.wst.common.internal.emf.resource.Translator;
+import org.eclipse.wst.common.internal.emf.utilities.TranslatorManager.TranslatorDescriptor;
+
+/**
+ * This is the service class to deliver API to use to retrieve Translator extensions from
+ * the TranslatorManager and its RegistryReader.
+ */
+public class TranslatorService {
+
+ /**
+ * Static Key value pair of descriptors as keys and Translator instances as values
+ */
+ private static final Map translators = new HashMap();
+
+ /**
+ * Static empty array used when no extensions found
+ */
+ // never used
+ //private static final Translator[] NO_TRANSLATORS = new Translator[0];
+
+ /**
+ * Singleton instance of the Translator service
+ */
+ private static final TranslatorService INSTANCE = new TranslatorService();
+
+ /**
+ * Default constructor
+ */
+ private TranslatorService() {
+ super();
+ }
+
+ public static TranslatorService getInstance() {
+ return INSTANCE;
+ }
+
+ /**
+ * This will return the associated extension point TranslatorDescriptor objects from the manager
+ * @return TranslatorDescriptor[]
+ */
+ public TranslatorDescriptor[] getTranslatorDescriptors() {
+ return TranslatorManager.getInstance().findTranslators();
+ }
+
+ /**
+ * This retrieves the extended Translators using the extension point manager and descriptors
+ * @return Translator[] (Note, the return value may contain null entries.)
+ */
+ public Translator[] getTranslators() {
+ TranslatorDescriptor[] descriptors = getTranslatorDescriptors();
+ Translator[] result = new Translator[descriptors.length];
+ //The result index could differ from the descriptors index.
+ int resultIndex = 0;
+ for (int i=0; i<descriptors.length; i++) {
+ Translator instance = getTranslator(descriptors[i]);
+ if (instance!=null) {
+ result[resultIndex] = instance;
+ resultIndex++;
+ }
+ }
+ return result;
+ }
+
+ /**
+ * Retrieve the existing associated Translator instance for the descriptor, or create a new
+ * one and cache on the Set.
+ *
+ * @param translatorDescriptor
+ * @return Translator associated with the descriptor
+ */
+ public Translator getTranslator(TranslatorDescriptor translatorDescriptor) {
+ Translator translator = (Translator) translators.get(translatorDescriptor);
+ if (translator != null)
+ return translator;
+
+ synchronized (translators) {
+ translator = translatorDescriptor.createTranslator();
+ if (translator != null)
+ translators.put(translatorDescriptor, translator);
+ }
+ return translator;
+ }
+}
diff --git a/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/utilities/UnsupportedCryptoAlgorithmException.java b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/utilities/UnsupportedCryptoAlgorithmException.java
new file mode 100644
index 0000000..f71c66d
--- /dev/null
+++ b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/utilities/UnsupportedCryptoAlgorithmException.java
@@ -0,0 +1,16 @@
+/***************************************************************************************************
+ * Copyright (c) 2003, 2004 IBM Corporation 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: IBM Corporation - initial API and implementation
+ **************************************************************************************************/
+package org.eclipse.wst.common.internal.emf.utilities;
+
+
+import org.omg.CORBA.UserException;
+
+public class UnsupportedCryptoAlgorithmException extends UserException {
+}
+
diff --git a/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/utilities/WFTUtilsResourceHandler.java b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/utilities/WFTUtilsResourceHandler.java
new file mode 100644
index 0000000..6506318
--- /dev/null
+++ b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/utilities/WFTUtilsResourceHandler.java
@@ -0,0 +1,48 @@
+/*******************************************************************************
+ * Copyright (c) 2003, 2005 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.wst.common.internal.emf.utilities;
+
+
+import org.eclipse.osgi.util.NLS;
+
+public class WFTUtilsResourceHandler extends NLS {
+ private static final String BUNDLE_NAME = "wftutils";//$NON-NLS-1$
+
+ private WFTUtilsResourceHandler() {
+ // Do not instantiate
+ }
+
+ public static String DANGLING_HREF_ERROR_;
+ public static String Integer_UI_;
+ public static String Failed_to_convert__0__to___ERROR_;
+ public static String Enumeration_UI_;
+ public static String Short_UI_;
+ public static String Character_UI_;
+ public static String Long_UI_;
+ public static String Double_UI_;
+ public static String ResourceDependencyRegister_ERROR_0;
+ public static String Float_UI_;
+ public static String Byte_UI_;
+ public static String Warning__Could_not_write_b_WARN_;
+ public static String Boolean_UI_;
+ public static String Stack_trace_of_nested_exce_ERROR_;
+ public static String MofObject_UI_;
+ public static String PleaseMigrateYourCodeError_ERROR_0;
+ public static String EMF2DOMAdapterImpl_ERROR_0;
+
+ static {
+ NLS.initializeMessages(BUNDLE_NAME, WFTUtilsResourceHandler.class);
+ }
+
+ public static String getString(String key, Object[] args) {
+ return NLS.bind(key, args);
+ }
+}
diff --git a/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/utilities/WriteBackHelper.java b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/utilities/WriteBackHelper.java
new file mode 100644
index 0000000..7a0aa43
--- /dev/null
+++ b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/utilities/WriteBackHelper.java
@@ -0,0 +1,136 @@
+/*******************************************************************************
+ * Copyright (c) 2003, 2006 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.wst.common.internal.emf.utilities;
+
+
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.Set;
+
+import org.eclipse.emf.ecore.EObject;
+import org.eclipse.emf.ecore.resource.Resource;
+
+
+/**
+ * @deprecated This class will be deleted. If you still need to use this class, please contact the
+ * WCCM team. A class which can be used in conjunction with Encoder/Decoders to save
+ * resources if they are made dirty by automatic encoding support. Usage Example:
+ *
+ * <pre>
+ *
+ *
+ * // Use the standard WebSphere password value encoder/decoder.
+ * EncoderDecoderRegistry.getDefaultRegistry().setDefaultEncoderDecoder(new com.ibm.ejs.security.util.WASEncoderDecoder());
+ * // Begin tracking changes...
+ * WriteBackHelper.begin();
+ * // Load a resource which may have un-encoded values...
+ * // Note: The WCCM will attempt to detect un-encoded values. If unencoded values
+ * // are found, the value will be encoded, and the resource will be added to the
+ * // WriteBackHelper.
+ * Resource res = resourceSet.load("myResource");
+ * // Ensure that any changes due to encoding are written back out.
+ * WriteBackHelper.end();
+ * </pre>
+ */
+public class WriteBackHelper {
+ private Set dirtyObjects = new HashSet();
+ private boolean trackingChanges = false;
+ private static WriteBackHelper _instance;
+ static {
+ //Deprecated class
+ Revisit.deleteMe();
+ }
+
+ /**
+ * Private constructor ensures proper usage through singleton.
+ */
+ private WriteBackHelper() {
+ super();
+ }
+
+ /**
+ * Adds a resource which is dirty, and needs to be saved.
+ */
+ public void addDirtyObject(EObject dirtyObject) {
+ dirtyObjects.add(dirtyObject);
+ }
+
+ /**
+ * Begin collecting objects which have changed.
+ */
+ public void begin() {
+ trackingChanges = true;
+ }
+
+ /**
+ * Attempts to save all dirty resources (if possible), then marks the resources as non-dirty.
+ */
+ public void end() {
+ saveDirtyResources();
+ reset();
+ trackingChanges = false;
+ }
+
+ /**
+ * Returns true if changes to mof objects are currently being tracked.
+ */
+ public boolean isActive() {
+ return trackingChanges;
+ }
+
+ /**
+ * Clears the list of dirty resources.
+ */
+ protected void reset() {
+ dirtyObjects.clear();
+ }
+
+ /**
+ * Attempts to save all dirty resources (if possible), then marks the resources as non-dirty.
+ */
+ protected void saveDirtyResources() {
+ Set dirtyResources = new HashSet();
+ Iterator dirtyObjIter = dirtyObjects.iterator();
+ while (dirtyObjIter.hasNext()) {
+ EObject dirtyObject = (EObject) dirtyObjIter.next();
+ if (dirtyObject.eResource() != null && !dirtyResources.contains(dirtyObject)) {
+ dirtyResources.add(dirtyObject.eResource());
+ }
+ }
+ Iterator dirtyIter = dirtyResources.iterator();
+ while (dirtyIter.hasNext()) {
+ Resource dirtyResource = (Resource) dirtyIter.next();
+ try {
+ dirtyResource.save(Collections.EMPTY_MAP);
+ } catch (Exception e) {
+ warn(dirtyResource, e);
+ }
+ }
+ }
+
+ /**
+ * Adds a resource which is dirty, and needs to be saved.
+ */
+ public static WriteBackHelper singleton() {
+ if (_instance == null) {
+ _instance = new WriteBackHelper();
+ }
+ return _instance;
+ }
+
+ /**
+ * Warn the user of problems during save.
+ */
+ protected void warn(Resource res, Exception e) {
+ System.err.println(WFTUtilsResourceHandler.getString(WFTUtilsResourceHandler.Warning__Could_not_write_b_WARN_, new Object[]{res.getURI()}));
+ }
+}
diff --git a/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/utilities/XMLValueEncoderDecoder.java b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/utilities/XMLValueEncoderDecoder.java
new file mode 100644
index 0000000..d9a1d2c
--- /dev/null
+++ b/plugins/org.eclipse.wst.common.emf/wtpemf/org/eclipse/wst/common/internal/emf/utilities/XMLValueEncoderDecoder.java
@@ -0,0 +1,111 @@
+/*******************************************************************************
+ * Copyright (c) 2003, 2004 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.wst.common.internal.emf.utilities;
+
+
+/**
+ * An XML value escaping EncoderDecoder implementation
+ */
+public class XMLValueEncoderDecoder extends EncoderDecoderAdapter implements EncoderDecoder {
+ /**
+ * Identifies the last printable character in the Unicode range that is supported by the
+ * encoding used with this serializer. For 8-bit encodings this will be either 0x7E or 0xFF. For
+ * 16-bit encodings this will be 0xFFFF. Characters that are not printable will be escaped using
+ * character references.
+ */
+ private int _lastPrintable = 0x7E;
+ protected static XMLValueEncoderDecoder _singleton;
+
+ /**
+ * EncoderDecoderAdapter constructor comment.
+ */
+ public XMLValueEncoderDecoder() {
+ super();
+ }
+
+ /**
+ * Returns a decoded version of the value.
+ */
+ public String decode(String value) {
+ // NOT_IMPLEMENTED
+ return value;
+ }
+
+ /**
+ * Escapes a string so it may be printed as text content or attribute value. Non printable
+ * characters are escaped using character references. Where the format specifies a deault entity
+ * reference, that reference is used (e.g. <tt>&lt;</tt>).
+ *
+ * @param source
+ * The string to escape
+ */
+ public String encode(String value) {
+ StringBuffer sbuf = new StringBuffer(value.length());
+ String charRef = null;
+ char ch;
+ for (int i = 0; i < value.length(); ++i) {
+ ch = value.charAt(i);
+ // If there is a suitable entity reference for this
+ // character, print it. The list of available entity
+ // references is almost but not identical between
+ // XML and HTML.
+ charRef = getEntityRef(ch);
+ if (charRef != null) {
+ sbuf.append('&');
+ sbuf.append(charRef);
+ sbuf.append(';');
+ } else if ((ch >= ' ' && ch <= _lastPrintable && ch != 0xF7) || ch == '\n' || ch == '\r' || ch == '\t') {
+ // If the character is not printable, print as character reference.
+ // Non printables are below ASCII space but not tab or line
+ // terminator, ASCII delete, or above a certain Unicode threshold.
+ sbuf.append(ch);
+ } else {
+ sbuf.append("&#");//$NON-NLS-1$
+ sbuf.append(Integer.toString(ch));
+ sbuf.append(';');
+ }
+ }
+ return sbuf.toString();
+ }
+
+ public static String escape(String value) {
+ if (_singleton == null) {
+ _singleton = new XMLValueEncoderDecoder();
+ }
+ return _singleton.encode(value);
+ }
+
+ /**
+ * Returns the suitable entity reference for this character value, or null if no such entity
+ * exists. Calling this method with <tt>'&'</tt> will return <tt>"&amp;"</tt>.
+ *
+ * @param ch
+ * Character value
+ * @return Character entity name, or null
+ */
+ protected String getEntityRef(char ch) {
+ // Encode special XML characters into the equivalent character references.
+ // These five are defined by default for all XML documents.
+ switch (ch) {
+ case '<' :
+ return "lt";//$NON-NLS-1$
+ case '>' :
+ return "gt";//$NON-NLS-1$
+ case '"' :
+ return "quot";//$NON-NLS-1$
+ case '\'' :
+ return "apos";//$NON-NLS-1$
+ case '&' :
+ return "amp";//$NON-NLS-1$
+ }
+ return null;
+ }
+}
\ No newline at end of file
diff --git a/plugins/org.eclipse.wst.common.emf/wtpemf/wftutils.properties b/plugins/org.eclipse.wst.common.emf/wtpemf/wftutils.properties
new file mode 100644
index 0000000..4b2e2ae
--- /dev/null
+++ b/plugins/org.eclipse.wst.common.emf/wtpemf/wftutils.properties
@@ -0,0 +1,28 @@
+###############################################################################
+# Copyright (c) 2003, 2005 IBM Corporation 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:
+# IBM Corporation - initial API and implementation
+###############################################################################
+Warning__Could_not_write_b_WARN_=IWAE0008W Warning: Could not write back {0}
+Stack_trace_of_nested_exce_ERROR_=IWAE0009E Stack trace of nested exception:
+Enumeration_UI_=Enumeration
+Double_UI_=Double
+Float_UI_=Float
+Long_UI_=Long
+Short_UI_=Short
+Boolean_UI_=Boolean
+Integer_UI_=Integer
+Character_UI_=Character
+Byte_UI_=Byte
+Failed_to_convert__0__to___ERROR_=IWAE0014E Failed to convert {0} to {1}.
+DANGLING_HREF_ERROR_=IWAE0001E Unable to resolve HREF {0}. Check the descriptor files and ensure the ids are valid.
+MofObject_UI_=MofObject_UI_
+PleaseMigrateYourCodeError_ERROR_0=PleaseMigrateYourCodeError_ERROR_0
+EMF2DOMAdapterImpl_ERROR_0=EMF2DOMAdapterImpl_ERROR_0
+
+ResourceDependencyRegister_ERROR_0=IWAE0002E The ResourceSet cannot be null.
diff --git a/plugins/org.eclipse.wst.common.emfworkbench.integration/.classpath b/plugins/org.eclipse.wst.common.emfworkbench.integration/.classpath
index 377edbf..fe45152 100644
--- a/plugins/org.eclipse.wst.common.emfworkbench.integration/.classpath
+++ b/plugins/org.eclipse.wst.common.emfworkbench.integration/.classpath
@@ -2,7 +2,13 @@
<classpath>
<classpathentry kind="src" path="src"/>
<classpathentry kind="src" path="property_file"/>
- <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
- <classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/>
+ <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/J2SE-1.4"/>
+ <classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins">
+ <accessrules>
+ <accessrule kind="accessible" pattern="org/eclipse/wst/common/**"/>
+ <accessrule kind="accessible" pattern="org/eclipse/wst/validation/**"/>
+ <accessrule kind="accessible" pattern="org/eclipse/jem/**"/>
+ </accessrules>
+ </classpathentry>
<classpathentry kind="output" path="bin"/>
</classpath>
diff --git a/plugins/org.eclipse.wst.common.emfworkbench.integration/.settings/org.eclipse.jdt.core.prefs b/plugins/org.eclipse.wst.common.emfworkbench.integration/.settings/org.eclipse.jdt.core.prefs
new file mode 100644
index 0000000..46468f9
--- /dev/null
+++ b/plugins/org.eclipse.wst.common.emfworkbench.integration/.settings/org.eclipse.jdt.core.prefs
@@ -0,0 +1,62 @@
+#Sat Mar 24 02:06:45 EDT 2007
+eclipse.preferences.version=1
+org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
+org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.2
+org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve
+org.eclipse.jdt.core.compiler.compliance=1.4
+org.eclipse.jdt.core.compiler.debug.lineNumber=generate
+org.eclipse.jdt.core.compiler.debug.localVariable=generate
+org.eclipse.jdt.core.compiler.debug.sourceFile=generate
+org.eclipse.jdt.core.compiler.problem.annotationSuperInterface=ignore
+org.eclipse.jdt.core.compiler.problem.assertIdentifier=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.emptyStatement=ignore
+org.eclipse.jdt.core.compiler.problem.enumIdentifier=warning
+org.eclipse.jdt.core.compiler.problem.fallthroughCase=ignore
+org.eclipse.jdt.core.compiler.problem.fieldHiding=ignore
+org.eclipse.jdt.core.compiler.problem.finalParameterBound=ignore
+org.eclipse.jdt.core.compiler.problem.finallyBlockNotCompletingNormally=error
+org.eclipse.jdt.core.compiler.problem.forbiddenReference=error
+org.eclipse.jdt.core.compiler.problem.hiddenCatchBlock=error
+org.eclipse.jdt.core.compiler.problem.incompatibleNonInheritedInterfaceMethod=error
+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=error
+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=error
+org.eclipse.jdt.core.compiler.problem.nonExternalizedStringLiteral=ignore
+org.eclipse.jdt.core.compiler.problem.nullReference=ignore
+org.eclipse.jdt.core.compiler.problem.overridingPackageDefaultMethod=error
+org.eclipse.jdt.core.compiler.problem.parameterAssignment=ignore
+org.eclipse.jdt.core.compiler.problem.possibleAccidentalBooleanAssignment=ignore
+org.eclipse.jdt.core.compiler.problem.rawTypeReference=ignore
+org.eclipse.jdt.core.compiler.problem.redundantNullCheck=ignore
+org.eclipse.jdt.core.compiler.problem.specialParameterHidingField=disabled
+org.eclipse.jdt.core.compiler.problem.staticAccessReceiver=error
+org.eclipse.jdt.core.compiler.problem.suppressWarnings=enabled
+org.eclipse.jdt.core.compiler.problem.syntheticAccessEmulation=ignore
+org.eclipse.jdt.core.compiler.problem.typeParameterHiding=error
+org.eclipse.jdt.core.compiler.problem.uncheckedTypeOperation=ignore
+org.eclipse.jdt.core.compiler.problem.undocumentedEmptyBlock=ignore
+org.eclipse.jdt.core.compiler.problem.unhandledWarningToken=ignore
+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=error
+org.eclipse.jdt.core.compiler.problem.unusedLabel=error
+org.eclipse.jdt.core.compiler.problem.unusedLocal=ignore
+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=error
+org.eclipse.jdt.core.compiler.problem.varargsArgumentNeedCast=ignore
+org.eclipse.jdt.core.compiler.source=1.3
diff --git a/plugins/org.eclipse.wst.common.emfworkbench.integration/META-INF/MANIFEST.MF b/plugins/org.eclipse.wst.common.emfworkbench.integration/META-INF/MANIFEST.MF
index f3be5c9..6afb47c 100644
--- a/plugins/org.eclipse.wst.common.emfworkbench.integration/META-INF/MANIFEST.MF
+++ b/plugins/org.eclipse.wst.common.emfworkbench.integration/META-INF/MANIFEST.MF
@@ -2,7 +2,7 @@
Bundle-ManifestVersion: 2
Bundle-Name: %pluginName
Bundle-SymbolicName: org.eclipse.wst.common.emfworkbench.integration; singleton:=true
-Bundle-Version: 1.1.6.qualifier
+Bundle-Version: 1.1.202.qualifier
Bundle-Activator: org.eclipse.wst.common.internal.emfworkbench.integration.EMFWorkbenchEditPlugin
Bundle-Vendor: %pluginVendor
Bundle-Localization: plugin
@@ -10,15 +10,17 @@
org.eclipse.wst.common.internal.emfworkbench.edit;x-internal:=true,
org.eclipse.wst.common.internal.emfworkbench.integration;x-internal:=true,
org.eclipse.wst.common.internal.emfworkbench.validateedit;x-internal:=true
-Require-Bundle: org.eclipse.wst.common.frameworks;bundle-version="[1.1.0,1.2.0)",
- org.eclipse.jem.util;bundle-version="[1.2.0,1.3.0)",
- org.eclipse.emf.edit;bundle-version="[2.2.0,2.3.0)",
- org.eclipse.emf.ecore.xmi;bundle-version="[2.2.0,2.3.0)",
- org.eclipse.wst.common.emf;bundle-version="[1.1.0,1.2.0)",
- org.eclipse.core.runtime;bundle-version="[3.2.0,4.0.0)",
- org.eclipse.core.resources;bundle-version="[3.2.0,4.0.0)",
- org.eclipse.xsd;bundle-version="[2.2.0,2.3.0)",
- org.eclipse.wst.validation;bundle-version="[1.1.0,1.2.0)",
- org.eclipse.wst.common.project.facet.core;bundle-version="[1.1.0,1.2.0)",
- org.eclipse.core.expressions;bundle-version="[3.2.0,4.0.0)"
-Eclipse-AutoStart: true
+Require-Bundle: org.eclipse.wst.common.frameworks;bundle-version="[1.1.200,2.0.0)",
+ org.eclipse.jem.util;bundle-version="[2.0.100,3.0.0)",
+ org.eclipse.emf.edit;bundle-version="[2.4.0,3.0.0)",
+ org.eclipse.emf.ecore.xmi;bundle-version="[2.4.0,3.0.0)",
+ org.eclipse.wst.common.emf;bundle-version="[1.1.200,2.0.0)",
+ org.eclipse.core.runtime;bundle-version="[3.4.0,4.0.0)",
+ org.eclipse.core.resources;bundle-version="[3.4.0,4.0.0)",
+ org.eclipse.wst.validation;bundle-version="[1.2.0,2.0.0)",
+ org.eclipse.wst.common.project.facet.core;bundle-version="[1.3.0,2.0.0)",
+ org.eclipse.core.expressions;bundle-version="[3.4.0,4.0.0)"
+Eclipse-LazyStart: true
+Bundle-RequiredExecutionEnvironment: J2SE-1.4,
+ J2SE-1.5
+Bundle-ActivationPolicy: lazy
diff --git a/plugins/org.eclipse.wst.common.emfworkbench.integration/about.html b/plugins/org.eclipse.wst.common.emfworkbench.integration/about.html
index 4ec5989..2199df3 100644
--- a/plugins/org.eclipse.wst.common.emfworkbench.integration/about.html
+++ b/plugins/org.eclipse.wst.common.emfworkbench.integration/about.html
@@ -10,7 +10,7 @@
<H3>About This Content</H3>
-<P>May 2, 2006</P>
+<P>June, 2008</P>
<H3>License</H3>
diff --git a/plugins/org.eclipse.wst.common.emfworkbench.integration/plugin.properties b/plugins/org.eclipse.wst.common.emfworkbench.integration/plugin.properties
index 3a6ba45..cdc1ce7 100644
--- a/plugins/org.eclipse.wst.common.emfworkbench.integration/plugin.properties
+++ b/plugins/org.eclipse.wst.common.emfworkbench.integration/plugin.properties
@@ -1,5 +1,5 @@
###############################################################################
-# Copyright (c) 2005 IBM Corporation and others.
+# Copyright (c) 2005, 2006 IBM Corporation 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
@@ -13,4 +13,4 @@
Adapter_Factory_Extension=Adapter Factory Extension
ModifierHelperFactory=ModifierHelperFactory
pluginName=EMF Workbench Edit Plug-in
-pluginVendor=Eclipse.org
\ No newline at end of file
+pluginVendor=Eclipse.org
diff --git a/plugins/org.eclipse.wst.common.emfworkbench.integration/src/org/eclipse/wst/common/internal/emfworkbench/DynamicGrowthModel.java b/plugins/org.eclipse.wst.common.emfworkbench.integration/src/org/eclipse/wst/common/internal/emfworkbench/DynamicGrowthModel.java
index 8aed2ee..d6a9a6d 100644
--- a/plugins/org.eclipse.wst.common.emfworkbench.integration/src/org/eclipse/wst/common/internal/emfworkbench/DynamicGrowthModel.java
+++ b/plugins/org.eclipse.wst.common.emfworkbench.integration/src/org/eclipse/wst/common/internal/emfworkbench/DynamicGrowthModel.java
@@ -1,3 +1,13 @@
+/*******************************************************************************
+ * Copyright (c) 2005, 2006 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
package org.eclipse.wst.common.internal.emfworkbench;
import java.util.HashMap;
diff --git a/plugins/org.eclipse.wst.common.emfworkbench.integration/src/org/eclipse/wst/common/internal/emfworkbench/EMFWorkbenchContext.java b/plugins/org.eclipse.wst.common.emfworkbench.integration/src/org/eclipse/wst/common/internal/emfworkbench/EMFWorkbenchContext.java
index 378788b..66c6b35 100644
--- a/plugins/org.eclipse.wst.common.emfworkbench.integration/src/org/eclipse/wst/common/internal/emfworkbench/EMFWorkbenchContext.java
+++ b/plugins/org.eclipse.wst.common.emfworkbench.integration/src/org/eclipse/wst/common/internal/emfworkbench/EMFWorkbenchContext.java
@@ -1,5 +1,5 @@
/*******************************************************************************
- * Copyright (c) 2003, 2005 IBM Corporation and others.
+ * Copyright (c) 2003, 2006 IBM Corporation 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
@@ -105,11 +105,11 @@
editModel.access(accessorKey);
}
} else {
+ if (editModel.isDisposed() || editModel.isDisposing()) {
+ editModel = createEditModelForWrite(editModelID, params);
+ cacheEditModel(editModel, params);
+ }
synchronized (editModel) {
- if (editModel.isDisposed() || editModel.isDisposing()) {
- editModel = createEditModelForWrite(editModelID, params);
- cacheEditModel(editModel, params);
- }
editModel.access(accessorKey);
}
}
@@ -136,11 +136,11 @@
editModel.access(accessorKey);
}
} else {
+ if (editModel.isDisposed() || editModel.isDisposing()) {
+ editModel = createEditModelForRead(editModelID, params);
+ cacheEditModel(editModel, params);
+ }
synchronized (editModel) {
- if (editModel.isDisposed() || editModel.isDisposing()) {
- editModel = createEditModelForRead(editModelID, params);
- cacheEditModel(editModel, params);
- }
EditModelLeastUsedCache.getInstance().access(editModel);
editModel.access(accessorKey);
}
diff --git a/plugins/org.eclipse.wst.common.emfworkbench.integration/src/org/eclipse/wst/common/internal/emfworkbench/EditModelLeastUsedCache.java b/plugins/org.eclipse.wst.common.emfworkbench.integration/src/org/eclipse/wst/common/internal/emfworkbench/EditModelLeastUsedCache.java
index f0c22ea..0401cb7 100644
--- a/plugins/org.eclipse.wst.common.emfworkbench.integration/src/org/eclipse/wst/common/internal/emfworkbench/EditModelLeastUsedCache.java
+++ b/plugins/org.eclipse.wst.common.emfworkbench.integration/src/org/eclipse/wst/common/internal/emfworkbench/EditModelLeastUsedCache.java
@@ -1,3 +1,13 @@
+/*******************************************************************************
+ * Copyright (c) 2005, 2006 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
package org.eclipse.wst.common.internal.emfworkbench;
import java.util.Collection;
@@ -75,8 +85,8 @@
}
}
if (shouldAccess) {
+ editModel.access(this);
synchronized (lru) {
- editModel.access(this);
lru.add(editModel);
}
}
@@ -88,6 +98,7 @@
*/
public void optimizeLRUSizeIfNecessary() {
EditModel model = null;
+
synchronized (lru) {
if (lru.size() > threshhold) {
// remove oldest element and release the edit model.
@@ -97,9 +108,9 @@
lru.remove(model);
}
}
+ }
if (model != null)
model.releaseAccess(this);
- }
}
/**
diff --git a/plugins/org.eclipse.wst.common.emfworkbench.integration/src/org/eclipse/wst/common/internal/emfworkbench/EmfPackagePropertyTester.java b/plugins/org.eclipse.wst.common.emfworkbench.integration/src/org/eclipse/wst/common/internal/emfworkbench/EmfPackagePropertyTester.java
index c685199..9959402 100644
--- a/plugins/org.eclipse.wst.common.emfworkbench.integration/src/org/eclipse/wst/common/internal/emfworkbench/EmfPackagePropertyTester.java
+++ b/plugins/org.eclipse.wst.common.emfworkbench.integration/src/org/eclipse/wst/common/internal/emfworkbench/EmfPackagePropertyTester.java
@@ -1,3 +1,13 @@
+/*******************************************************************************
+ * Copyright (c) 2005, 2006 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
package org.eclipse.wst.common.internal.emfworkbench;
import org.eclipse.core.expressions.PropertyTester;
diff --git a/plugins/org.eclipse.wst.common.emfworkbench.integration/src/org/eclipse/wst/common/internal/emfworkbench/PassthruResourceSet.java b/plugins/org.eclipse.wst.common.emfworkbench.integration/src/org/eclipse/wst/common/internal/emfworkbench/PassthruResourceSet.java
index 863e0dd..d1b36ea 100644
--- a/plugins/org.eclipse.wst.common.emfworkbench.integration/src/org/eclipse/wst/common/internal/emfworkbench/PassthruResourceSet.java
+++ b/plugins/org.eclipse.wst.common.emfworkbench.integration/src/org/eclipse/wst/common/internal/emfworkbench/PassthruResourceSet.java
@@ -1,5 +1,5 @@
/*******************************************************************************
- * Copyright (c) 2003, 2005 IBM Corporation and others.
+ * Copyright (c) 2003, 2006 IBM Corporation 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
@@ -47,7 +47,7 @@
return false;
ResourceSet set = WorkbenchResourceHelperBase.getResourceSet(((Resource) object).getURI());
if (set != null)
- return set.getResources().add(object);
+ return set.getResources().add((Resource)object);
return super.add(object);
}
diff --git a/plugins/org.eclipse.wst.common.emfworkbench.integration/src/org/eclipse/wst/common/internal/emfworkbench/WorkbenchResourceHelper.java b/plugins/org.eclipse.wst.common.emfworkbench.integration/src/org/eclipse/wst/common/internal/emfworkbench/WorkbenchResourceHelper.java
index fd8d587..6296984 100644
--- a/plugins/org.eclipse.wst.common.emfworkbench.integration/src/org/eclipse/wst/common/internal/emfworkbench/WorkbenchResourceHelper.java
+++ b/plugins/org.eclipse.wst.common.emfworkbench.integration/src/org/eclipse/wst/common/internal/emfworkbench/WorkbenchResourceHelper.java
@@ -1,5 +1,5 @@
/*******************************************************************************
- * Copyright (c) 2003, 2005 IBM Corporation and others.
+ * Copyright (c) 2003, 2006 IBM Corporation 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
diff --git a/plugins/org.eclipse.wst.common.emfworkbench.integration/src/org/eclipse/wst/common/internal/emfworkbench/edit/AdapterFactoryDescriptor.java b/plugins/org.eclipse.wst.common.emfworkbench.integration/src/org/eclipse/wst/common/internal/emfworkbench/edit/AdapterFactoryDescriptor.java
index bf2c38c..e72153d 100644
--- a/plugins/org.eclipse.wst.common.emfworkbench.integration/src/org/eclipse/wst/common/internal/emfworkbench/edit/AdapterFactoryDescriptor.java
+++ b/plugins/org.eclipse.wst.common.emfworkbench.integration/src/org/eclipse/wst/common/internal/emfworkbench/edit/AdapterFactoryDescriptor.java
@@ -1,5 +1,5 @@
/*******************************************************************************
- * Copyright (c) 2003, 2005 IBM Corporation and others.
+ * Copyright (c) 2003, 2006 IBM Corporation 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
diff --git a/plugins/org.eclipse.wst.common.emfworkbench.integration/src/org/eclipse/wst/common/internal/emfworkbench/edit/ClientAccessRegistry.java b/plugins/org.eclipse.wst.common.emfworkbench.integration/src/org/eclipse/wst/common/internal/emfworkbench/edit/ClientAccessRegistry.java
index 9fae464..5f0f82d 100644
--- a/plugins/org.eclipse.wst.common.emfworkbench.integration/src/org/eclipse/wst/common/internal/emfworkbench/edit/ClientAccessRegistry.java
+++ b/plugins/org.eclipse.wst.common.emfworkbench.integration/src/org/eclipse/wst/common/internal/emfworkbench/edit/ClientAccessRegistry.java
@@ -1,5 +1,5 @@
/*******************************************************************************
- * Copyright (c) 2003, 2005 IBM Corporation and others.
+ * Copyright (c) 2003, 2006 IBM Corporation 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
diff --git a/plugins/org.eclipse.wst.common.emfworkbench.integration/src/org/eclipse/wst/common/internal/emfworkbench/edit/ClientAccessRegistryException.java b/plugins/org.eclipse.wst.common.emfworkbench.integration/src/org/eclipse/wst/common/internal/emfworkbench/edit/ClientAccessRegistryException.java
index a49c8a0..a5aa1cb 100644
--- a/plugins/org.eclipse.wst.common.emfworkbench.integration/src/org/eclipse/wst/common/internal/emfworkbench/edit/ClientAccessRegistryException.java
+++ b/plugins/org.eclipse.wst.common.emfworkbench.integration/src/org/eclipse/wst/common/internal/emfworkbench/edit/ClientAccessRegistryException.java
@@ -1,5 +1,5 @@
/*******************************************************************************
- * Copyright (c) 2003, 2005 IBM Corporation and others.
+ * Copyright (c) 2003, 2006 IBM Corporation 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
diff --git a/plugins/org.eclipse.wst.common.emfworkbench.integration/src/org/eclipse/wst/common/internal/emfworkbench/edit/EMFWorkbenchEditContextFactory.java b/plugins/org.eclipse.wst.common.emfworkbench.integration/src/org/eclipse/wst/common/internal/emfworkbench/edit/EMFWorkbenchEditContextFactory.java
index 4110873..0a8d2f8 100644
--- a/plugins/org.eclipse.wst.common.emfworkbench.integration/src/org/eclipse/wst/common/internal/emfworkbench/edit/EMFWorkbenchEditContextFactory.java
+++ b/plugins/org.eclipse.wst.common.emfworkbench.integration/src/org/eclipse/wst/common/internal/emfworkbench/edit/EMFWorkbenchEditContextFactory.java
@@ -1,5 +1,5 @@
/*******************************************************************************
- * Copyright (c) 2003, 2005 IBM Corporation and others.
+ * Copyright (c) 2003, 2007 IBM Corporation 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
diff --git a/plugins/org.eclipse.wst.common.emfworkbench.integration/src/org/eclipse/wst/common/internal/emfworkbench/edit/EditModelRegistry.java b/plugins/org.eclipse.wst.common.emfworkbench.integration/src/org/eclipse/wst/common/internal/emfworkbench/edit/EditModelRegistry.java
index dcfa367..facd9cb 100644
--- a/plugins/org.eclipse.wst.common.emfworkbench.integration/src/org/eclipse/wst/common/internal/emfworkbench/edit/EditModelRegistry.java
+++ b/plugins/org.eclipse.wst.common.emfworkbench.integration/src/org/eclipse/wst/common/internal/emfworkbench/edit/EditModelRegistry.java
@@ -1,5 +1,5 @@
/*******************************************************************************
- * Copyright (c) 2003, 2005 IBM Corporation and others.
+ * Copyright (c) 2003, 2006 IBM Corporation 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
@@ -312,10 +312,12 @@
editModelResources = new ArrayList();
IConfigurationElement[] resources = configurationElement.getChildren(EditModelResource.EDIT_MODEL_RESOURCE_ELEMENT);
+ IConfigurationElement[] resExtensions = configurationElement.getChildren(EDIT_MODEL_RESOURCE_EXTENSION);
+ // set the configurationElement to null- keeps code from reentering
+ discardConfigurationElementIfNecessary();
for (int j = 0; j < resources.length; j++) {
editModelResources.add(new EditModelResource(resources[j]));
}
- IConfigurationElement[] resExtensions = configurationElement.getChildren(EDIT_MODEL_RESOURCE_EXTENSION);
if (resExtensions == null || resExtensions.length == 0) {
editModelExtensions = Collections.EMPTY_LIST;
} else {
@@ -325,7 +327,6 @@
editModelExtensions.add(extension);
}
}
- discardConfigurationElementIfNecessary();
} else {
editModelResources = Collections.EMPTY_LIST;
editModelExtensions = Collections.EMPTY_LIST;
diff --git a/plugins/org.eclipse.wst.common.emfworkbench.integration/src/org/eclipse/wst/common/internal/emfworkbench/edit/ReadOnlyClientAccessRegistry.java b/plugins/org.eclipse.wst.common.emfworkbench.integration/src/org/eclipse/wst/common/internal/emfworkbench/edit/ReadOnlyClientAccessRegistry.java
index dc8f9c8..e845428 100644
--- a/plugins/org.eclipse.wst.common.emfworkbench.integration/src/org/eclipse/wst/common/internal/emfworkbench/edit/ReadOnlyClientAccessRegistry.java
+++ b/plugins/org.eclipse.wst.common.emfworkbench.integration/src/org/eclipse/wst/common/internal/emfworkbench/edit/ReadOnlyClientAccessRegistry.java
@@ -1,5 +1,5 @@
/*******************************************************************************
- * Copyright (c) 2005 IBM Corporation and others.
+ * Copyright (c) 2005, 2006 IBM Corporation 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
diff --git a/plugins/org.eclipse.wst.common.emfworkbench.integration/src/org/eclipse/wst/common/internal/emfworkbench/edit/Snapshot.java b/plugins/org.eclipse.wst.common.emfworkbench.integration/src/org/eclipse/wst/common/internal/emfworkbench/edit/Snapshot.java
index 91e6f2d..a2b64b4 100644
--- a/plugins/org.eclipse.wst.common.emfworkbench.integration/src/org/eclipse/wst/common/internal/emfworkbench/edit/Snapshot.java
+++ b/plugins/org.eclipse.wst.common.emfworkbench.integration/src/org/eclipse/wst/common/internal/emfworkbench/edit/Snapshot.java
@@ -1,5 +1,5 @@
/*******************************************************************************
- * Copyright (c) 2003, 2005 IBM Corporation and others.
+ * Copyright (c) 2003, 2006 IBM Corporation 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
diff --git a/plugins/org.eclipse.wst.common.emfworkbench.integration/src/org/eclipse/wst/common/internal/emfworkbench/integration/ComposedEditModel.java b/plugins/org.eclipse.wst.common.emfworkbench.integration/src/org/eclipse/wst/common/internal/emfworkbench/integration/ComposedEditModel.java
index b17f88c..e46fa9a 100644
--- a/plugins/org.eclipse.wst.common.emfworkbench.integration/src/org/eclipse/wst/common/internal/emfworkbench/integration/ComposedEditModel.java
+++ b/plugins/org.eclipse.wst.common.emfworkbench.integration/src/org/eclipse/wst/common/internal/emfworkbench/integration/ComposedEditModel.java
@@ -1,5 +1,5 @@
/*******************************************************************************
- * Copyright (c) 2003, 2005 IBM Corporation and others.
+ * Copyright (c) 2003, 2006 IBM Corporation 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
diff --git a/plugins/org.eclipse.wst.common.emfworkbench.integration/src/org/eclipse/wst/common/internal/emfworkbench/integration/DynamicAdapterFactory.java b/plugins/org.eclipse.wst.common.emfworkbench.integration/src/org/eclipse/wst/common/internal/emfworkbench/integration/DynamicAdapterFactory.java
index 5e40cb9..37571ee 100644
--- a/plugins/org.eclipse.wst.common.emfworkbench.integration/src/org/eclipse/wst/common/internal/emfworkbench/integration/DynamicAdapterFactory.java
+++ b/plugins/org.eclipse.wst.common.emfworkbench.integration/src/org/eclipse/wst/common/internal/emfworkbench/integration/DynamicAdapterFactory.java
@@ -1,5 +1,5 @@
/*******************************************************************************
- * Copyright (c) 2003, 2005 IBM Corporation and others.
+ * Copyright (c) 2003, 2006 IBM Corporation 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
diff --git a/plugins/org.eclipse.wst.common.emfworkbench.integration/src/org/eclipse/wst/common/internal/emfworkbench/integration/EMFWorkbenchEditPlugin.java b/plugins/org.eclipse.wst.common.emfworkbench.integration/src/org/eclipse/wst/common/internal/emfworkbench/integration/EMFWorkbenchEditPlugin.java
index 234fe1d..e409b3b 100644
--- a/plugins/org.eclipse.wst.common.emfworkbench.integration/src/org/eclipse/wst/common/internal/emfworkbench/integration/EMFWorkbenchEditPlugin.java
+++ b/plugins/org.eclipse.wst.common.emfworkbench.integration/src/org/eclipse/wst/common/internal/emfworkbench/integration/EMFWorkbenchEditPlugin.java
@@ -1,5 +1,5 @@
/*******************************************************************************
- * Copyright (c) 2003, 2005 IBM Corporation and others.
+ * Copyright (c) 2003, 2006 IBM Corporation 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
diff --git a/plugins/org.eclipse.wst.common.emfworkbench.integration/src/org/eclipse/wst/common/internal/emfworkbench/integration/EditModel.java b/plugins/org.eclipse.wst.common.emfworkbench.integration/src/org/eclipse/wst/common/internal/emfworkbench/integration/EditModel.java
index 2d077f9..d22d645 100644
--- a/plugins/org.eclipse.wst.common.emfworkbench.integration/src/org/eclipse/wst/common/internal/emfworkbench/integration/EditModel.java
+++ b/plugins/org.eclipse.wst.common.emfworkbench.integration/src/org/eclipse/wst/common/internal/emfworkbench/integration/EditModel.java
@@ -1,11 +1,13 @@
-/***************************************************************************************************
- * Copyright (c) 2003, 2005 IBM Corporation and others. All rights reserved. This program and the
- * accompanying materials are made available under the terms of the Eclipse Public License v1.0
+/*******************************************************************************
+ * Copyright (c) 2003, 2007 IBM Corporation 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: IBM Corporation - initial API and implementation
- **************************************************************************************************/
+ *
+ * Contributors:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
package org.eclipse.wst.common.internal.emfworkbench.integration;
@@ -35,7 +37,6 @@
import org.eclipse.core.runtime.SafeRunner;
import org.eclipse.core.runtime.Status;
import org.eclipse.emf.common.command.BasicCommandStack;
-import org.eclipse.emf.common.command.CommandStack;
import org.eclipse.emf.common.command.CommandStackListener;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.common.notify.impl.AdapterImpl;
@@ -232,7 +233,7 @@
}
/**
- * This is called with the {@link CommandStack}'s state has changed.
+ * This is called with the {@linkorg.eclipse.emf.common.command.CommandStack}'s state has changed.
*/
public void commandStackChanged(java.util.EventObject event) {
if (dirtyModelEvent == null)
diff --git a/plugins/org.eclipse.wst.common.emfworkbench.integration/src/org/eclipse/wst/common/internal/emfworkbench/integration/ModelModifier.java b/plugins/org.eclipse.wst.common.emfworkbench.integration/src/org/eclipse/wst/common/internal/emfworkbench/integration/ModelModifier.java
index 53d88ec..c0ed86a 100644
--- a/plugins/org.eclipse.wst.common.emfworkbench.integration/src/org/eclipse/wst/common/internal/emfworkbench/integration/ModelModifier.java
+++ b/plugins/org.eclipse.wst.common.emfworkbench.integration/src/org/eclipse/wst/common/internal/emfworkbench/integration/ModelModifier.java
@@ -338,6 +338,11 @@
return aHelper.createNewObjectFromFeature();
}
+
+ /**
+ * Used to remove an object on unset. Makes the object a proxy
+ * on execute and redo commands. Undo will remove the proxy.
+ */
public class ProxyWrappingCommand extends AbstractCommand {
protected Command baseCommand = null;
protected EObject eObject = null;
@@ -368,6 +373,7 @@
}
public void redo() {
+ ExtendedEcoreUtil.becomeProxy(eObject, resource);
baseCommand.redo();
}
diff --git a/plugins/org.eclipse.wst.common.emfworkbench.integration/src/org/eclipse/wst/common/internal/emfworkbench/integration/ModifierHelper.java b/plugins/org.eclipse.wst.common.emfworkbench.integration/src/org/eclipse/wst/common/internal/emfworkbench/integration/ModifierHelper.java
index 1936a2c..ad949b3 100644
--- a/plugins/org.eclipse.wst.common.emfworkbench.integration/src/org/eclipse/wst/common/internal/emfworkbench/integration/ModifierHelper.java
+++ b/plugins/org.eclipse.wst.common.emfworkbench.integration/src/org/eclipse/wst/common/internal/emfworkbench/integration/ModifierHelper.java
@@ -1,5 +1,5 @@
/*******************************************************************************
- * Copyright (c) 2003, 2005 IBM Corporation and others.
+ * Copyright (c) 2003, 2006 IBM Corporation 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
diff --git a/plugins/org.eclipse.wst.common.emfworkbench.integration/src/org/eclipse/wst/common/internal/emfworkbench/integration/ProjectResourceSetEditImpl.java b/plugins/org.eclipse.wst.common.emfworkbench.integration/src/org/eclipse/wst/common/internal/emfworkbench/integration/ProjectResourceSetEditImpl.java
index aa8f271..07a326e 100644
--- a/plugins/org.eclipse.wst.common.emfworkbench.integration/src/org/eclipse/wst/common/internal/emfworkbench/integration/ProjectResourceSetEditImpl.java
+++ b/plugins/org.eclipse.wst.common.emfworkbench.integration/src/org/eclipse/wst/common/internal/emfworkbench/integration/ProjectResourceSetEditImpl.java
@@ -18,6 +18,7 @@
import org.eclipse.core.resources.IProject;
import org.eclipse.emf.common.util.URI;
+import org.eclipse.emf.ecore.resource.ContentHandler;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.jem.internal.util.emf.workbench.ProjectResourceSetImpl;
import org.eclipse.wst.common.internal.emf.resource.ReferencedResource;
@@ -43,11 +44,14 @@
*
* @see org.eclipse.jem.internal.util.emf.workbench.ProjectResourceSetImpl#createResource(org.eclipse.emf.common.util.URI)
*/
- public Resource createResource(URI uri) {
- Resource result = super.createResource(uri);
+ public Resource createResource(URI uri, String contentType) {
+ Resource result = super.createResource(uri, contentType);
if (result != null && WorkbenchResourceHelper.isReferencedResource(result))
WorkbenchResourceHelper.cacheSynchronizationStamp((ReferencedResource) result);
return result;
}
+ public Resource createResource(URI uri) {
+ return createResource(uri, ContentHandler.UNSPECIFIED_CONTENT_TYPE);
+ }
}
diff --git a/plugins/org.eclipse.wst.common.emfworkbench.integration/src/org/eclipse/wst/common/internal/emfworkbench/integration/ResourceSetWorkbenchEditSynchronizer.java b/plugins/org.eclipse.wst.common.emfworkbench.integration/src/org/eclipse/wst/common/internal/emfworkbench/integration/ResourceSetWorkbenchEditSynchronizer.java
index 94d46e3..3718afe 100644
--- a/plugins/org.eclipse.wst.common.emfworkbench.integration/src/org/eclipse/wst/common/internal/emfworkbench/integration/ResourceSetWorkbenchEditSynchronizer.java
+++ b/plugins/org.eclipse.wst.common.emfworkbench.integration/src/org/eclipse/wst/common/internal/emfworkbench/integration/ResourceSetWorkbenchEditSynchronizer.java
@@ -1,5 +1,5 @@
/*******************************************************************************
- * Copyright (c) 2003, 2005 IBM Corporation and others.
+ * Copyright (c) 2003, 2006 IBM Corporation 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
@@ -16,9 +16,11 @@
*/
package org.eclipse.wst.common.internal.emfworkbench.integration;
+import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
+import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
@@ -33,7 +35,9 @@
import org.eclipse.core.resources.IWorkspaceRunnable;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
+import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
+import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.jobs.ILock;
import org.eclipse.emf.common.util.URI;
@@ -57,8 +61,63 @@
public class ResourceSetWorkbenchEditSynchronizer extends ResourceSetWorkbenchSynchronizer implements IResourceDeltaVisitor {
private static final String CLASS_EXTENSION = "class"; //$NON-NLS-1$
private static final String JAVA_EXTENSION = "java"; //$NON-NLS-1$
+ private static final String JAVA_ARCHIVE = "jar"; //$NON-NLS-1$
private Set recentlySavedFiles = new HashSet();
private Map ignoredFilesCache = new HashMap();
+ private class SavedFileKey {
+ private WeakReference res;
+ private IFile savedFile;
+ public SavedFileKey(Resource res, IFile savedFile) {
+ super();
+ this.res = new WeakReference(res);
+ this.savedFile = savedFile;
+ }
+ public Resource getRes() {
+ return this.res == null ? null : (Resource)res.get();
+ }
+ public void setRes(Resource res) {
+ this.res = new WeakReference(res);
+ }
+ public IFile getSavedFile() {
+ return savedFile;
+ }
+ public void setSavedFile(IFile savedFile) {
+ this.savedFile = savedFile;
+ }
+ public int hashCode() {
+ final int prime = 31;
+ int result = 1;
+ result = prime * result + getOuterType().hashCode();
+ result = prime * result + ((getRes() == null) ? 0 : getRes().hashCode());
+ result = prime * result + ((savedFile == null) ? 0 : savedFile.hashCode());
+ return result;
+ }
+ public boolean equals(Object obj) {
+ if (this == obj)
+ return true;
+ if (obj == null)
+ return false;
+ if (getClass() != obj.getClass())
+ return false;
+ SavedFileKey other = (SavedFileKey) obj;
+ if (!getOuterType().equals(other.getOuterType()))
+ return false;
+ if (getRes() == null) {
+ if (other.getRes() != null)
+ return false;
+ } else if (!getRes().equals(other.getRes()))
+ return false;
+ if (savedFile == null) {
+ if (other.savedFile != null)
+ return false;
+ } else if (!savedFile.equals(other.savedFile))
+ return false;
+ return true;
+ }
+ private ResourceSetWorkbenchEditSynchronizer getOuterType() {
+ return ResourceSetWorkbenchEditSynchronizer.this;
+ }
+ }
/** The emf resources to be removed from the resource set as a result of a delta */
protected List deferredRemoveResources = new ArrayList();
@@ -76,7 +135,7 @@
public ResourceSetWorkbenchEditSynchronizer(ResourceSet aResourceSet, IProject aProject) {
super(aResourceSet, aProject);
}
-
+
/*
* (non-Javadoc)
*
@@ -261,55 +320,88 @@
* @post Return true if a <code>Resource</code> was queued up to be reloaded.
*/
protected boolean addedResource(IFile aFile) {
- boolean didProcess = false;
- Resource resource = getResource(aFile);
- if ((resource != null) || (recentlySavedFiles.contains(resource))){
- /*
- * The IFile was just added to the workspace but we have a resource
- * in memory. Need to decide if it should be unloaded.
- */
- if (resource.isModified()) {
- if (WorkbenchResourceHelper.isReferencedResource(resource)) {
- ReferencedResource refRes = (ReferencedResource) resource;
- if (refRes.shouldForceRefresh()) {
- deferredUnloadResources.add(resource);
- didProcess = true;
- }
- }
- } else {
- /*Unload if found and is not modified but inconsistent.*/
- if (resource.isLoaded() && WorkbenchResourceHelper.isReferencedResource(resource) && !WorkbenchResourceHelper.isConsistent((ReferencedResource)resource)) {
- deferredUnloadResources.add(resource);
- didProcess = true;
- }
- }
- } else {
- //Process resource as a refresh.
- URI uri = URI.createPlatformResourceURI(aFile.getFullPath().toString());
- if ((autoloadResourcesURIs.contains(uri)) || (autoloadResourcesExts.contains(aFile.getFileExtension()))) {
- deferredLoadResources.add(uri);
- didProcess = true;
- }
- }
- return didProcess;
-}
+ boolean didProcess = false;
+ List resources = getResources(aFile);
+ for (Iterator iterator = resources.iterator(); iterator.hasNext();) {
+ Resource resource = (Resource) iterator.next();
+
+ if (resource != null) {
+ if (recentlySavedFilesContains(resource)) {
+
+ /*
+ * The IFile was just added to the workspace but we have a
+ * changed resource in memory. Need to decide if it should
+ * be unloaded.
+ */
+ if (resource.isModified()) {
+ if (WorkbenchResourceHelper.isReferencedResource(resource)) {
+ ReferencedResource refRes = (ReferencedResource) resource;
+ if (refRes.shouldForceRefresh()) {
+ deferredUnloadResources.add(resource);
+ didProcess = true;
+ }
+ }
+ }
+ } else {
+ /* Unload if found and is not modified but inconsistent. */
+ if (resource.isLoaded()) {
+ if (WorkbenchResourceHelper.isReferencedResource(resource)) {
+ if (!WorkbenchResourceHelper.isConsistent((ReferencedResource) resource)) {
+ deferredUnloadResources.add(resource);
+ didProcess = true;
+ }
+ } else {
+ deferredUnloadResources.add(resource);
+ didProcess = true;
+ }
+ } else {
+ /* Process autoload resources on added file */
+ URI uri = URI.createPlatformResourceURI(aFile.getFullPath().toString());
+ if ((autoloadResourcesURIs.contains(uri)) || (autoloadResourcesExts.contains(aFile.getFileExtension()))) {
+ deferredLoadResources.add(uri);
+ didProcess = true;
+ }
+ }
+ }
+ }
+ }
+ return didProcess;
+ }
+
+ private synchronized boolean recentlySavedFilesContains(Resource resource) {
+ for (Iterator iterator = recentlySavedFiles.iterator(); iterator.hasNext();) {
+ SavedFileKey key = (SavedFileKey) iterator.next();
+ if (key.getRes() != null && (key.getRes().getURI().equals(resource.getURI()) && key.getRes().getClass().equals(resource.getClass())))
+ return true;
+ }
+ return false;
+ }
protected boolean processResource(IFile aFile, boolean isRemove) {
- Resource resource = getResource(aFile);
- if ((resource != null) || (recentlySavedFiles.contains(resource))){
- if (resource.isModified()) {
- if (WorkbenchResourceHelper.isReferencedResource(resource)) {
- ReferencedResource refRes = (ReferencedResource) resource;
- if (!refRes.shouldForceRefresh())
- return false; //Do not do anything
- } else
- return false;
+ List resources = getResources(aFile);
+ for (Iterator iterator = resources.iterator(); iterator.hasNext();) {
+ Resource resource = (Resource) iterator.next();
+ if ((resource != null)) {
+ if (recentlySavedFilesContains(resource)) {
+ if (resource.isModified()) {
+ if (WorkbenchResourceHelper.isReferencedResource(resource)) {
+ ReferencedResource refRes = (ReferencedResource) resource;
+ if (!refRes.shouldForceRefresh())
+ continue; // Do not do anything
+ } else
+ continue;
+ }
+ }
+ if (isRemove)
+ deferredRemoveResources.add(resource);
+ else if (resource.isLoaded()) {
+ if (WorkbenchResourceHelper.isReferencedResource(resource)) {
+ if (!WorkbenchResourceHelper.isConsistent((ReferencedResource) resource))
+ deferredUnloadResources.add(resource);
+ } else
+ deferredUnloadResources.add(resource);
+ }
}
-
- if (isRemove)
- deferredRemoveResources.add(resource);
- else if (resource.isLoaded() && WorkbenchResourceHelper.isReferencedResource(resource) && !WorkbenchResourceHelper.isConsistent((ReferencedResource)resource))
- deferredUnloadResources.add(resource);
}
return false;
}
@@ -339,6 +431,28 @@
return resourceSet.getResource(URI.createPlatformResourceURI(aFile.getFullPath().toString()), false);
}
+
+ protected List getResources(IFile aFile) {
+
+ List resources = new ArrayList();
+ List allResources = resourceSet.getResources();
+ for (Iterator iterator = allResources.iterator(); iterator.hasNext();) {
+ Resource res = (Resource) iterator.next();
+ URI resURI = res.getURI();
+ String resURIString = "";
+ if (resURI.path() != null) {
+ IPath resURIPath;
+ if (WorkbenchResourceHelper.isPlatformResourceURI(resURI))
+ resURIPath = new Path(URI.decode(resURI.path())).removeFirstSegments(2);
+ else
+ resURIPath = new Path(URI.decode(resURI.path())).removeFirstSegments(1);
+ resURIString = resURIPath.toString();
+ }
+ if (!resURIString.equals("") && aFile.getFullPath().toString().indexOf(resURIString) != -1)
+ resources.add(res);
+ }
+ return resources;
+ }
/**
@@ -346,21 +460,63 @@
*/
public void preSave(IFile aFile) {
if (aFile != null) {
- recentlySavedFiles.add(aFile);
+ recentlySavedFilesAdd(aFile,null);
ignoredFilesCache.remove(aFile);
}
}
+
+ /**
+ * This method should be called prior to writing to an IFile from a MOF resource.
+ */
+ public void preSave(IFile aFile, Resource res) {
+ if (aFile != null) {
+ recentlySavedFilesAdd(aFile, res);
+ ignoredFilesCache.remove(aFile);
+ }
+ }
+
+ private synchronized boolean recentlySavedFilesAdd(IFile file, Resource res) {
+ return recentlySavedFiles.add(new SavedFileKey(res, file));
+ }
/**
* This method should be called after a preSave if the save fails
*/
public void removeFromRecentlySavedList(IFile aFile) {
if (aFile != null) {
- recentlySavedFiles.remove(aFile);
+ recentlySavedFilesForceRemove(aFile);
ignoredFilesCache.remove(aFile);
}
}
+ private synchronized boolean recentlySavedFilesRemove(IFile file) {
+
+ boolean removedFromList = false;
+ for (Iterator iterator = recentlySavedFiles.iterator(); iterator.hasNext();) {
+ SavedFileKey key = (SavedFileKey) iterator.next();
+ if (key.savedFile != null && key.savedFile.equals(file)) {
+ List resources = getResources(file);
+ if (key.getRes() == null || resources.contains(key.getRes()) ) {
+ iterator.remove();
+ removedFromList = true;
+ }
+ }
+ }
+ return removedFromList;
+ }
+ private synchronized boolean recentlySavedFilesForceRemove(IFile file) {
+
+ boolean removedFromList = false;
+ for (Iterator iterator = recentlySavedFiles.iterator(); iterator.hasNext();) {
+ SavedFileKey key = (SavedFileKey) iterator.next();
+ if (key.savedFile != null && key.savedFile.equals(file)) {
+ iterator.remove();
+ removedFromList = true;
+ }
+ }
+ return removedFromList;
+ }
+
/**
* This method should be called just after writing to an IFile from a MOF resource.
*
@@ -383,11 +539,11 @@
*/
protected boolean isInterrestedInFile(IFile aFile) {
String extension = aFile.getFileExtension();
- if (CLASS_EXTENSION.equals(extension) || JAVA_EXTENSION.equals(extension))
+ if (CLASS_EXTENSION.equals(extension) || JAVA_EXTENSION.equals(extension) || JAVA_ARCHIVE.equals(extension))
return false;
- if (recentlySavedFiles.remove(aFile)) {
- cacheIgnored(aFile);
- return false;
+ if (recentlySavedFilesRemove(aFile)) {
+ cacheIgnored(aFile);
+ return false;
}
return !hasIgnored(aFile);
}
diff --git a/plugins/org.eclipse.wst.common.emfworkbench.integration/src/org/eclipse/wst/common/internal/emfworkbench/validateedit/ResourceStateValidatorImpl.java b/plugins/org.eclipse.wst.common.emfworkbench.integration/src/org/eclipse/wst/common/internal/emfworkbench/validateedit/ResourceStateValidatorImpl.java
index 729443f..b00b6f9 100644
--- a/plugins/org.eclipse.wst.common.emfworkbench.integration/src/org/eclipse/wst/common/internal/emfworkbench/validateedit/ResourceStateValidatorImpl.java
+++ b/plugins/org.eclipse.wst.common.emfworkbench.integration/src/org/eclipse/wst/common/internal/emfworkbench/validateedit/ResourceStateValidatorImpl.java
@@ -1,5 +1,5 @@
/*******************************************************************************
- * Copyright (c) 2003, 2005 IBM Corporation and others.
+ * Copyright (c) 2003, 2006 IBM Corporation 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
diff --git a/plugins/org.eclipse.wst.common.modulecore/.classpath b/plugins/org.eclipse.wst.common.modulecore/.classpath
index 48c8e15..0c7fcda 100644
--- a/plugins/org.eclipse.wst.common.modulecore/.classpath
+++ b/plugins/org.eclipse.wst.common.modulecore/.classpath
@@ -1,7 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="src" path="modulecore-src/"/>
- <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
+ <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/J2SE-1.5"/>
<classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/>
<classpathentry kind="output" path="bin"/>
</classpath>
diff --git a/plugins/org.eclipse.wst.common.modulecore/.settings/org.eclipse.jdt.core.prefs b/plugins/org.eclipse.wst.common.modulecore/.settings/org.eclipse.jdt.core.prefs
new file mode 100644
index 0000000..31bb1e6
--- /dev/null
+++ b/plugins/org.eclipse.wst.common.modulecore/.settings/org.eclipse.jdt.core.prefs
@@ -0,0 +1,62 @@
+#Thu May 10 18:38:08 EDT 2007
+eclipse.preferences.version=1
+org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
+org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.5
+org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve
+org.eclipse.jdt.core.compiler.compliance=1.5
+org.eclipse.jdt.core.compiler.debug.lineNumber=generate
+org.eclipse.jdt.core.compiler.debug.localVariable=generate
+org.eclipse.jdt.core.compiler.debug.sourceFile=generate
+org.eclipse.jdt.core.compiler.problem.annotationSuperInterface=ignore
+org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
+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.emptyStatement=ignore
+org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
+org.eclipse.jdt.core.compiler.problem.fallthroughCase=ignore
+org.eclipse.jdt.core.compiler.problem.fieldHiding=ignore
+org.eclipse.jdt.core.compiler.problem.finalParameterBound=ignore
+org.eclipse.jdt.core.compiler.problem.finallyBlockNotCompletingNormally=error
+org.eclipse.jdt.core.compiler.problem.forbiddenReference=error
+org.eclipse.jdt.core.compiler.problem.hiddenCatchBlock=error
+org.eclipse.jdt.core.compiler.problem.incompatibleNonInheritedInterfaceMethod=error
+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=error
+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=error
+org.eclipse.jdt.core.compiler.problem.nonExternalizedStringLiteral=ignore
+org.eclipse.jdt.core.compiler.problem.nullReference=ignore
+org.eclipse.jdt.core.compiler.problem.overridingPackageDefaultMethod=error
+org.eclipse.jdt.core.compiler.problem.parameterAssignment=ignore
+org.eclipse.jdt.core.compiler.problem.possibleAccidentalBooleanAssignment=ignore
+org.eclipse.jdt.core.compiler.problem.rawTypeReference=ignore
+org.eclipse.jdt.core.compiler.problem.redundantNullCheck=ignore
+org.eclipse.jdt.core.compiler.problem.specialParameterHidingField=disabled
+org.eclipse.jdt.core.compiler.problem.staticAccessReceiver=error
+org.eclipse.jdt.core.compiler.problem.suppressWarnings=enabled
+org.eclipse.jdt.core.compiler.problem.syntheticAccessEmulation=ignore
+org.eclipse.jdt.core.compiler.problem.typeParameterHiding=error
+org.eclipse.jdt.core.compiler.problem.uncheckedTypeOperation=ignore
+org.eclipse.jdt.core.compiler.problem.undocumentedEmptyBlock=ignore
+org.eclipse.jdt.core.compiler.problem.unhandledWarningToken=ignore
+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=error
+org.eclipse.jdt.core.compiler.problem.unusedLabel=error
+org.eclipse.jdt.core.compiler.problem.unusedLocal=ignore
+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=error
+org.eclipse.jdt.core.compiler.problem.varargsArgumentNeedCast=ignore
+org.eclipse.jdt.core.compiler.source=1.5
diff --git a/plugins/org.eclipse.wst.common.modulecore/.settings/org.eclipse.jdt.ui.prefs b/plugins/org.eclipse.wst.common.modulecore/.settings/org.eclipse.jdt.ui.prefs
new file mode 100644
index 0000000..a18ff1d
--- /dev/null
+++ b/plugins/org.eclipse.wst.common.modulecore/.settings/org.eclipse.jdt.ui.prefs
@@ -0,0 +1,4 @@
+#Wed Mar 19 17:18:41 EDT 2008
+eclipse.preferences.version=1
+org.eclipse.jdt.ui.javadoc=false
+org.eclipse.jdt.ui.text.custom_code_templates=<?xml version\="1.0" encoding\="UTF-8" standalone\="no"?><templates><template autoinsert\="true" context\="gettercomment_context" deleted\="false" description\="Comment for getter method" enabled\="true" id\="org.eclipse.jdt.ui.text.codetemplates.gettercomment" name\="gettercomment">/**\r\n * @return the ${bare_field_name}\r\n */</template><template autoinsert\="true" context\="settercomment_context" deleted\="false" description\="Comment for setter method" enabled\="true" id\="org.eclipse.jdt.ui.text.codetemplates.settercomment" name\="settercomment">/**\r\n * @param ${param} the ${bare_field_name} to set\r\n */</template><template autoinsert\="true" context\="constructorcomment_context" deleted\="false" description\="Comment for created constructors" enabled\="true" id\="org.eclipse.jdt.ui.text.codetemplates.constructorcomment" name\="constructorcomment">/**\r\n * ${tags}\r\n */</template><template autoinsert\="true" context\="filecomment_context" deleted\="false" description\="Comment for created Java files" enabled\="true" id\="org.eclipse.jdt.ui.text.codetemplates.filecomment" name\="filecomment">/**\r\n * \r\n */</template><template autoinsert\="true" context\="typecomment_context" deleted\="false" description\="Comment for created types" enabled\="true" id\="org.eclipse.jdt.ui.text.codetemplates.typecomment" name\="typecomment">/**\r\n * @author ${user}\r\n *\r\n * ${tags}\r\n */</template><template autoinsert\="true" context\="fieldcomment_context" deleted\="false" description\="Comment for fields" enabled\="true" id\="org.eclipse.jdt.ui.text.codetemplates.fieldcomment" name\="fieldcomment">/**\r\n * \r\n */</template><template autoinsert\="true" context\="methodcomment_context" deleted\="false" description\="Comment for non-overriding methods" enabled\="true" id\="org.eclipse.jdt.ui.text.codetemplates.methodcomment" name\="methodcomment">/**\r\n * ${tags}\r\n */</template><template autoinsert\="true" context\="overridecomment_context" deleted\="false" description\="Comment for overriding methods" enabled\="true" id\="org.eclipse.jdt.ui.text.codetemplates.overridecomment" name\="overridecomment">/* (non-Javadoc)\r\n * ${see_to_overridden}\r\n */</template><template autoinsert\="true" context\="delegatecomment_context" deleted\="false" description\="Comment for delegate methods" enabled\="true" id\="org.eclipse.jdt.ui.text.codetemplates.delegatecomment" name\="delegatecomment">/**\r\n * ${tags}\r\n * ${see_to_target}\r\n */</template><template autoinsert\="true" context\="newtype_context" deleted\="false" description\="Newly created files" enabled\="true" id\="org.eclipse.jdt.ui.text.codetemplates.newtype" name\="newtype">${filecomment}\r\n${package_declaration}\r\n\r\n${typecomment}\r\n${type_declaration}</template><template autoinsert\="true" context\="classbody_context" deleted\="false" description\="Code in new class type bodies" enabled\="true" id\="org.eclipse.jdt.ui.text.codetemplates.classbody" name\="classbody">\r\n</template><template autoinsert\="true" context\="interfacebody_context" deleted\="false" description\="Code in new interface type bodies" enabled\="true" id\="org.eclipse.jdt.ui.text.codetemplates.interfacebody" name\="interfacebody">\r\n</template><template autoinsert\="true" context\="enumbody_context" deleted\="false" description\="Code in new enum type bodies" enabled\="true" id\="org.eclipse.jdt.ui.text.codetemplates.enumbody" name\="enumbody">\r\n</template><template autoinsert\="true" context\="annotationbody_context" deleted\="false" description\="Code in new annotation type bodies" enabled\="true" id\="org.eclipse.jdt.ui.text.codetemplates.annotationbody" name\="annotationbody">\r\n</template><template autoinsert\="false" context\="catchblock_context" deleted\="false" description\="Code in new catch blocks" enabled\="true" id\="org.eclipse.jdt.ui.text.codetemplates.catchblock" name\="catchblock">org.eclipse.wst.common.componentcore.internal.ModulecorePlugin.logError(${exception_var});</template><template autoinsert\="true" context\="methodbody_context" deleted\="false" description\="Code in created method stubs" enabled\="true" id\="org.eclipse.jdt.ui.text.codetemplates.methodbody" name\="methodbody">// ${todo} Auto-generated method stub\r\n${body_statement}</template><template autoinsert\="true" context\="constructorbody_context" deleted\="false" description\="Code in created constructor stubs" enabled\="true" id\="org.eclipse.jdt.ui.text.codetemplates.constructorbody" name\="constructorbody">${body_statement}\r\n// ${todo} Auto-generated constructor stub</template><template autoinsert\="true" context\="getterbody_context" deleted\="false" description\="Code in created getters" enabled\="true" id\="org.eclipse.jdt.ui.text.codetemplates.getterbody" name\="getterbody">return ${field};</template><template autoinsert\="true" context\="setterbody_context" deleted\="false" description\="Code in created setters" enabled\="true" id\="org.eclipse.jdt.ui.text.codetemplates.setterbody" name\="setterbody">${field} \= ${param};</template></templates>
diff --git a/plugins/org.eclipse.wst.common.modulecore/META-INF/MANIFEST.MF b/plugins/org.eclipse.wst.common.modulecore/META-INF/MANIFEST.MF
index b34d92c..522a71f 100644
--- a/plugins/org.eclipse.wst.common.modulecore/META-INF/MANIFEST.MF
+++ b/plugins/org.eclipse.wst.common.modulecore/META-INF/MANIFEST.MF
@@ -1,9 +1,9 @@
Manifest-Version: 1.0
Bundle-ManifestVersion: 2
-Bundle-Name: Modulecore Plug-in
+Bundle-Name: %Bundle-Name.0
Bundle-Vendor: %provider
Bundle-SymbolicName: org.eclipse.wst.common.modulecore; singleton:=true
-Bundle-Version: 1.1.54.qualifier
+Bundle-Version: 1.1.206.qualifier
Bundle-Activator: org.eclipse.wst.common.componentcore.internal.ModulecorePlugin
Bundle-Localization: plugin
Export-Package: org.eclipse.wst.common.componentcore,
@@ -16,18 +16,19 @@
org.eclipse.wst.common.componentcore.internal.resources;x-internal:=true,
org.eclipse.wst.common.componentcore.internal.util;x-internal:=true,
org.eclipse.wst.common.componentcore.resources
-Require-Bundle: org.eclipse.core.runtime;bundle-version="[3.2.0,4.0.0)",
- org.eclipse.wst.common.frameworks;bundle-version="[1.1.0,1.2.0)",
- org.eclipse.core.resources;bundle-version="[3.2.0,4.0.0)",
- org.eclipse.emf.ecore;bundle-version="[2.2.0,2.3.0)",
- org.eclipse.wst.common.emfworkbench.integration;bundle-version="[1.1.0,1.2.0)",
- org.eclipse.wst.common.emf;bundle-version="[1.1.0,1.2.0)",
- org.eclipse.emf.ecore.xmi;bundle-version="[2.2.0,2.3.0)",
- org.eclipse.core.commands;bundle-version="[3.2.0,4.0.0)",
- org.eclipse.emf.edit;bundle-version="[2.2.0,2.3.0)",
- org.eclipse.jem.util;bundle-version="[1.2.0,1.3.0)",
- org.eclipse.wst.common.uriresolver;bundle-version="[1.1.0,1.2.0)",
- org.eclipse.wst.common.project.facet.core;bundle-version="[1.1.0,1.2.0)",
- org.eclipse.wst.common.environment;bundle-version="[1.0.100,1.1.0)",
- org.eclipse.wst.validation;bundle-version="[1.1.0,1.2.0)"
+Require-Bundle: org.eclipse.core.runtime;bundle-version="[3.4.0,4.0.0)",
+ org.eclipse.wst.common.frameworks;bundle-version="[1.1.200,2.0.0)",
+ org.eclipse.core.resources;bundle-version="[3.4.0,4.0.0)",
+ org.eclipse.emf.ecore;bundle-version="[2.4.0,3.0.0)",
+ org.eclipse.wst.common.emfworkbench.integration;bundle-version="[1.1.200,2.0.0)",
+ org.eclipse.wst.common.emf;bundle-version="[1.1.200,2.0.0)",
+ org.eclipse.emf.ecore.xmi;bundle-version="[2.4.0,3.0.0)",
+ org.eclipse.core.commands;bundle-version="[3.4.0,4.0.0)",
+ org.eclipse.emf.edit;bundle-version="[2.4.0,3.0.0)",
+ org.eclipse.jem.util;bundle-version="[2.0.100,3.0.0)",
+ org.eclipse.wst.common.uriresolver;bundle-version="[1.1.301,2.0.0)",
+ org.eclipse.wst.common.project.facet.core;bundle-version="[1.3.0,2.0.0)",
+ org.eclipse.wst.common.environment;bundle-version="[1.0.200,2.0.0)",
+ org.eclipse.wst.validation;bundle-version="[1.2.0,2.0.0)"
Eclipse-LazyStart: true
+Bundle-RequiredExecutionEnvironment: J2SE-1.5
diff --git a/plugins/org.eclipse.wst.common.modulecore/about.html b/plugins/org.eclipse.wst.common.modulecore/about.html
index 4ec5989..2199df3 100644
--- a/plugins/org.eclipse.wst.common.modulecore/about.html
+++ b/plugins/org.eclipse.wst.common.modulecore/about.html
@@ -10,7 +10,7 @@
<H3>About This Content</H3>
-<P>May 2, 2006</P>
+<P>June, 2008</P>
<H3>License</H3>
diff --git a/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/ArtifactEdit.java b/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/ArtifactEdit.java
index 709cf5b..77cca57 100644
--- a/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/ArtifactEdit.java
+++ b/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/ArtifactEdit.java
@@ -1,5 +1,5 @@
/*******************************************************************************
- * Copyright (c) 2003, 2005 IBM Corporation and others.
+ * Copyright (c) 2003, 2007 IBM Corporation 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
@@ -11,10 +11,14 @@
package org.eclipse.wst.common.componentcore;
import java.util.EventObject;
+import java.util.HashMap;
import java.util.List;
import java.util.Map;
+import java.util.logging.Level;
+import java.util.logging.Logger;
import org.eclipse.core.resources.IProject;
+import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
@@ -28,12 +32,17 @@
import org.eclipse.jem.util.UIContextDetermination;
import org.eclipse.wst.common.componentcore.internal.ArtifactEditModel;
import org.eclipse.wst.common.componentcore.internal.BinaryComponentHelper;
+import org.eclipse.wst.common.componentcore.internal.impl.ArtifactEditModelFactory;
import org.eclipse.wst.common.componentcore.internal.impl.ModuleURIUtil;
+import org.eclipse.wst.common.componentcore.internal.util.IModuleConstants;
import org.eclipse.wst.common.componentcore.resources.IVirtualComponent;
import org.eclipse.wst.common.frameworks.internal.operations.IOperationHandler;
import org.eclipse.wst.common.internal.emfworkbench.integration.EditModel;
import org.eclipse.wst.common.internal.emfworkbench.integration.EditModelListener;
import org.eclipse.wst.common.internal.emfworkbench.validateedit.IValidateEditContext;
+import org.eclipse.wst.common.project.facet.core.IFacetedProject;
+import org.eclipse.wst.common.project.facet.core.IProjectFacet;
+import org.eclipse.wst.common.project.facet.core.ProjectFacetsManager;
/**
* Provides a Facade pattern for accessing Module Content Metamodels for Web Tools Platform flexible
@@ -272,13 +281,22 @@
* {@see ModuleCoreNature}
*/
protected ArtifactEdit(ModuleCoreNature aNature, IVirtualComponent aModule, boolean toAccessAsReadOnly) {
- if (toAccessAsReadOnly)
- artifactEditModel = aNature.getArtifactEditModelForRead(ModuleURIUtil.fullyQualifyURI(aModule.getProject()), this);
- else
- artifactEditModel = aNature.getArtifactEditModelForWrite(ModuleURIUtil.fullyQualifyURI(aModule.getProject()), this);
+
isReadOnly = toAccessAsReadOnly;
isArtifactEditModelSelfManaged = true;
project = aNature.getProject();
+ IProject aProject = aModule.getProject();
+ URI componentURI = ModuleURIUtil.fullyQualifyURI(aProject);
+ Map editModelParams = null;
+ if (getContentTypeDescriber() != null) {
+ editModelParams = new HashMap();
+ editModelParams.put(ArtifactEditModelFactory.PARAM_ROOT_URI, getRootURI());
+ editModelParams.put(ArtifactEditModelFactory.PARAM_ROOT_CONTENT_TYPE, getContentTypeDescriber());
+ }
+ if (toAccessAsReadOnly)
+ artifactEditModel = aNature.getArtifactEditModelForRead(componentURI, this, null, editModelParams);
+ else
+ artifactEditModel = aNature.getArtifactEditModelForWrite(componentURI, this, null, editModelParams);
}
/**
@@ -311,6 +329,25 @@
this(aProject,toAccessAsReadOnly,forCreate,projectType,null);
}
+
+ protected void verifyOperationSupported() {
+ if(!validArtifactEdit){
+ throw new RuntimeException("Invalid Artifact Edit access (model version not supported)");
+ }
+ }
+
+ private boolean validArtifactEdit = true;
+
+ public boolean isValid() {
+ return validArtifactEdit;
+ }
+
+ protected void markInvalid(){
+ Logger.global.log(Level.WARNING, "Invalid Artifact Edit access (model version not supported)");
+ validArtifactEdit = false;
+ }
+
+
/**
* <p>
* Creates an instance facade for the given {@see WorkbenchComponent}.
@@ -332,24 +369,82 @@
if (nature == null)
throw new IllegalArgumentException("Project does not have ModuleCoreNature: " + aProject);
-
+ if (!validProjectVersion(aProject)){
+ markInvalid();
+ }
IVirtualComponent component = ComponentCore.createComponent(aProject);
if (component == null)
throw new IllegalArgumentException("Invalid component handle: " + aProject);
if (!forCreate && !isValidEditableModule(component))
throw new IllegalArgumentException("Invalid component handle: " + aProject);
+ project = aProject;
URI componentURI = ModuleURIUtil.fullyQualifyURI(aProject);
-
- if (toAccessAsReadOnly)
+ if (getContentTypeDescriber() != null) {
+ if (editModelParams == null)
+ editModelParams = new HashMap();
+ editModelParams.put(ArtifactEditModelFactory.PARAM_ROOT_URI, getRootURI());
+ editModelParams.put(ArtifactEditModelFactory.PARAM_ROOT_CONTENT_TYPE, getContentTypeDescriber());
+ }
+ if (toAccessAsReadOnly)
artifactEditModel = nature.getArtifactEditModelForRead(componentURI, this, projectType, editModelParams);
- else
+ else
artifactEditModel = nature.getArtifactEditModelForWrite(componentURI, this, projectType, editModelParams);
+
+
isReadOnly = toAccessAsReadOnly;
isArtifactEditModelSelfManaged = true;
+ }
+
+ public boolean isProjectOfType(IProject project, String typeID) {
+ IFacetedProject facetedProject = null;
+ try {
+ facetedProject = ProjectFacetsManager.create(project);
+ } catch (CoreException e) {
+ return false;
+ }
+ if (facetedProject != null && ProjectFacetsManager.isProjectFacetDefined(typeID)) {
+ IProjectFacet projectFacet = ProjectFacetsManager.getProjectFacet(typeID);
+ return projectFacet != null && facetedProject.hasProjectFacet(projectFacet);
+ }
+ return false;
+ }
+ /**
+ * Used to optionally define an associated content type for XML file creation
+ * @return
+ */
+ protected String getContentTypeDescriber() {
- project = aProject;
+ if (isProjectOfType(project, IModuleConstants.JST_EJB_MODULE))
+ return "org.eclipse.jst.j2ee.ejbDD";
+ if (isProjectOfType(project, IModuleConstants.JST_WEB_MODULE))
+ return "org.eclipse.jst.j2ee.webDD";
+ if (isProjectOfType(project, IModuleConstants.JST_EAR_MODULE))
+ return "org.eclipse.jst.j2ee.earDD";
+ if (isProjectOfType(project, IModuleConstants.JST_APPCLIENT_MODULE))
+ return "org.eclipse.jst.j2ee.appclientDD";
+ return null;
+ }
+
+ /**
+ * Used to optionally define an root URI for the project
+ * @return
+ */
+ protected URI getRootURI() {
+
+ if (isProjectOfType(project, IModuleConstants.JST_EJB_MODULE))
+ return URI.createURI("META-INF/ejb-jar.xml");
+ if (isProjectOfType(project, IModuleConstants.JST_WEB_MODULE))
+ return URI.createURI("WEB-INF/web.xml");
+ if (isProjectOfType(project, IModuleConstants.JST_EAR_MODULE))
+ return URI.createURI("META-INF/application.xml");
+ if (isProjectOfType(project, IModuleConstants.JST_APPCLIENT_MODULE))
+ return URI.createURI("META-INF/application-client.xml");
+ return null;
}
+ protected boolean validProjectVersion(IProject project2) {
+ return true;
+ }
/**
* <p>
@@ -388,7 +483,7 @@
/**
* Validate edit for resource state
*/
- protected IStatus validateEdit() {
+ public IStatus validateEdit() {
IValidateEditContext validator = (IValidateEditContext) UIContextDetermination.createInstance(IValidateEditContext.CLASS_KEY);
return validator.validateState(getArtifactEditModel());
}
@@ -458,7 +553,7 @@
*/
public void dispose() {
if(isBinary()){
- binaryComponentHelper.releaseAccess(this);
+ binaryComponentHelper.dispose();
} else if (isArtifactEditModelSelfManaged && artifactEditModel != null)
artifactEditModel.releaseAccess(this);
}
diff --git a/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/ComponentCore.java b/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/ComponentCore.java
index e6467b7..062a5e5 100644
--- a/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/ComponentCore.java
+++ b/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/ComponentCore.java
@@ -1,5 +1,5 @@
/*******************************************************************************
- * Copyright (c) 2003, 2005 IBM Corporation and others.
+ * Copyright (c) 2003, 2007 IBM Corporation 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
@@ -16,7 +16,6 @@
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.wst.common.componentcore.internal.ComponentResource;
import org.eclipse.wst.common.componentcore.internal.StructureEdit;
import org.eclipse.wst.common.componentcore.internal.impl.ResourceTreeNode;
@@ -25,7 +24,6 @@
import org.eclipse.wst.common.componentcore.internal.resources.VirtualResource;
import org.eclipse.wst.common.componentcore.internal.util.ComponentImplManager;
import org.eclipse.wst.common.componentcore.resources.IVirtualComponent;
-import org.eclipse.wst.common.componentcore.resources.IVirtualContainer;
import org.eclipse.wst.common.componentcore.resources.IVirtualFile;
import org.eclipse.wst.common.componentcore.resources.IVirtualFolder;
import org.eclipse.wst.common.componentcore.resources.IVirtualReference;
@@ -56,7 +54,7 @@
* A valid, accessible project to contain the component
* @return A handle to an IVirtualComponent that may or may not exist or
* null if passed project does not contain ModuleCoreNature.
- * @see IVirtualContainer#create(int, IProgressMonitor)
+ * @see org.eclipse.core.runtime.IProgressMonitor#create(int, org.eclipse.core.runtime.IProgressMonitor)
*/
public static IVirtualComponent createComponent(IProject aProject) {
if (aProject == null || !aProject.isAccessible()){
@@ -72,10 +70,30 @@
*
* @param aProject
* A valid, accessible project to contain the component
+ * @param checkForComponentFile
+ * A flag to indicate if the presence of the component file should be checked
+ * @return A handle to an IVirtualComponent that may or may not exist or
+ * null if passed project does not contain ModuleCoreNature.
+ * @see org.eclipse.core.runtime.IProgressMonitor#create(int, org.eclipse.core.runtime.IProgressMonitor)
+ */
+ public static IVirtualComponent createComponent(IProject aProject, boolean checkForComponentFile) {
+ if (aProject == null || !aProject.isAccessible()){
+ return null;
+ }
+ return ComponentImplManager.instance().createComponent(aProject, checkForComponentFile);
+ }
+
+ /**
+ * Return an IVirtualComponent with the given name (aComponentName)
+ * contained by the given project (aProject). Component names should be
+ * unique across a project.
+ *
+ * @param aProject
+ * A valid, accessible project to contain the component
* @return A handle to an IVirtualComponent that may or may not exist or
* null if passed project does not contain ModuleCoreNature.
* @deprecated
- * @see IVirtualContainer#create(int, IProgressMonitor)
+ * @see org.eclipse.core.runtime.IProgressMonitor#create(int, org.eclipse.core.runtime.IProgressMonitor)
*/
public static IVirtualComponent createComponent(IProject aProject, String aName) {
return createComponent(aProject);
@@ -89,7 +107,7 @@
* lib/<Absolute path of a jar> or
* var/<CLASSPATH_VARIABLE/library namer>
* @return A handle to an IVirtualComponent that may or may not exist.
- * @see IVirtualContainer#create(int, IProgressMonitor)
+ * @see org.eclipse.core.runtime.IProgressMonitor#create(int, org.eclipse.core.runtime.IProgressMonitor)
*/
public static IVirtualComponent createArchiveComponent(IProject aProject, String aComponentName) {
return ComponentImplManager.instance().createArchiveComponent(aProject, aComponentName);
@@ -106,8 +124,8 @@
* The runtime path of the IVirtualFolder to return.
* @return An IVirtualFolder contained by the specified component with the
* given runtime path
- * @see IVirtualContainer#create(int, IProgressMonitor)
- * @see IVirtualResource#createLink(IPath, int, IProgressMonitor)
+ * @see org.eclipse.core.runtime.IProgressMonitor#create(int, org.eclipse.core.runtime.IProgressMonitor)
+ * @see IVirtualResource#createLink(IPath, int, org.eclipse.core.runtime.IProgressMonitor)
*/
public static IVirtualFolder createFolder(IProject aProject, IPath aRuntimePath) {
return ComponentImplManager.instance().createFolder(aProject, aRuntimePath);
@@ -127,7 +145,7 @@
* The runtime path of the IVirtualFolder to return.
* @return An IVirtualFile contained by the specified component with the
* given runtime path
- * @see IVirtualResource#createLink(IPath, int, IProgressMonitor)
+ * @see IVirtualResource#createLink(IPath, int, org.eclipse.core.runtime.IProgressMonitor)
*/
public static IVirtualFile createFile(IProject aProject, IPath aRuntimePath) {
return new VirtualFile(aProject, aRuntimePath);
@@ -145,7 +163,7 @@
* A valid, existing IVirtualComponent
* @return An IVirtualReference that captures the relationship between
* aComponent and aReferencedComponent.
- * @see IVirtualReference#create(int, IProgressMonitor)
+ * @see IVirtualReference#create(int, org.eclipse.core.runtime.IProgressMonitor)
*/
public static IVirtualReference createReference(IVirtualComponent aComponent, IVirtualComponent aReferencedComponent) {
return new VirtualReference(aComponent, aReferencedComponent);
diff --git a/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/ModuleCoreNature.java b/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/ModuleCoreNature.java
index 017920f..a3704cf 100644
--- a/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/ModuleCoreNature.java
+++ b/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/ModuleCoreNature.java
@@ -1,5 +1,5 @@
/*******************************************************************************
- * Copyright (c) 2003, 2005 IBM Corporation and others.
+ * Copyright (c) 2003, 2007 IBM Corporation 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
@@ -13,6 +13,7 @@
import java.util.HashMap;
import java.util.Map;
+import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IProjectDescription;
import org.eclipse.core.resources.IProjectNature;
@@ -31,15 +32,14 @@
import org.eclipse.jem.util.emf.workbench.ISynchronizerExtender;
import org.eclipse.jem.util.emf.workbench.ProjectResourceSet;
import org.eclipse.jem.util.emf.workbench.ProjectUtilities;
-import org.eclipse.jem.util.emf.workbench.nature.EMFNature;
import org.eclipse.wst.common.componentcore.internal.ArtifactEditModel;
import org.eclipse.wst.common.componentcore.internal.ModuleStructuralModel;
import org.eclipse.wst.common.componentcore.internal.ModulecorePlugin;
import org.eclipse.wst.common.componentcore.internal.StructureEdit;
-import org.eclipse.wst.common.componentcore.internal.WorkbenchComponent;
import org.eclipse.wst.common.componentcore.internal.impl.ArtifactEditModelFactory;
import org.eclipse.wst.common.componentcore.internal.impl.ComponentCoreURIConverter;
import org.eclipse.wst.common.componentcore.internal.impl.ModuleStructuralModelFactory;
+import org.eclipse.wst.common.componentcore.internal.impl.WTPModulesResourceFactory;
import org.eclipse.wst.common.componentcore.internal.impl.WTPResourceFactoryRegistry;
import org.eclipse.wst.common.componentcore.internal.util.IModuleConstants;
import org.eclipse.wst.common.componentcore.internal.util.ModuleCoreMessages;
@@ -49,6 +49,7 @@
import org.eclipse.wst.common.project.facet.core.IFacetedProject;
import org.eclipse.wst.common.project.facet.core.IProjectFacet;
import org.eclipse.wst.common.project.facet.core.ProjectFacetsManager;
+import org.eclipse.wst.validation.internal.plugin.ValidationPlugin;
/**
* <p>
@@ -137,14 +138,15 @@
* @see org.eclipse.wst.common.componentcore.internal.StructureEdit#getStructureEditForRead(IProject)
* @see org.eclipse.wst.common.componentcore.internal.StructureEdit#getStructureEditForWrite(IProject)
* @see org.eclipse.wst.common.componentcore.ArtifactEdit
- * @see org.eclipse.wst.common.componentcore.ArtifactEdit#getArtifactEditForRead(WorkbenchComponent)
- * @see org.eclipse.wst.common.componentcore.ArtifactEdit#getArtifactEditForWrite(WorkbenchComponent)
+ * @see org.eclipse.wst.common.componentcore.ArtifactEdit#getArtifactEditForRead(org.eclipse.wst.common.componentcore.internal.WorkbenchComponent)
+ * @see org.eclipse.wst.common.componentcore.ArtifactEdit#getArtifactEditForWrite(org.eclipse.wst.common.componentcore.internal.WorkbenchComponent)
* @plannedfor 1.0
*/
public class ModuleCoreNature extends EditModelNature implements IProjectNature, IModuleConstants, ISynchronizerExtender {
- public static final String VALIDATION_BUILDER_ID = "org.eclipse.wst.validation.validationbuilder"; // plugin id of the validation builder//$NON-NLS-1$
- private ModuleStructuralModel cachedModel;
+ public static final String VALIDATION_BUILDER_ID = ValidationPlugin.VALIDATION_BUILDER_ID;
+ private ModuleStructuralModel cachedWriteHandle;
+ private ModuleStructuralModel cachedReadHandle;
/**
* <p>
* Find and return the ModuleCoreNature of aProject, if available.
@@ -165,8 +167,33 @@
}
return null;
}
+ // The existence of this Nature plus the component file on disk makes a flexible project
public static boolean isFlexibleProject(IProject project) {
- return ModuleCoreNature.getModuleCoreNature(project) != null;
+ boolean foundNature = ModuleCoreNature.getModuleCoreNature(project) != null;
+ if (foundNature) {
+ return componentResourceExists(project);
+ }
+ return false;
+ }
+ public static boolean componentResourceExists(IProject project) {
+
+ IFile compFile = project.getFile(StructureEdit.MODULE_META_FILE_NAME);
+ if (compFile.isAccessible())
+ return true;
+ else { //Need to check for legacy file locations also....
+ compFile = project.getFile(ModuleStructuralModel.R1_MODULE_META_FILE_NAME);
+ if (compFile.isAccessible())
+ return true;
+ else {
+ compFile = project.getFile(ModuleStructuralModel.R0_7_MODULE_META_FILE_NAME);
+ if (compFile.isAccessible())
+ return true;
+ else {
+ compFile = project.getFile(WTPModulesResourceFactory.FIRST_WTP_MODULES_SHORT_NAME);
+ return compFile.isAccessible();
+ }
+ }
+ }
}
/**
@@ -238,7 +265,20 @@
* @return A {@see ModuleStructuralModel}for the project of the current nature.
*/
public ModuleStructuralModel getModuleStructuralModelForRead(Object anAccessorKey) {
- return (ModuleStructuralModel) getEditModelForRead(ModuleStructuralModelFactory.MODULE_STRUCTURAL_MODEL_ID, anAccessorKey);
+ // Return self managed edit model - will always cache locally
+ ModuleStructuralModel editModel = (ModuleStructuralModel)getEmfContext().getExistingEditModel(ModuleStructuralModelFactory.MODULE_STRUCTURAL_MODEL_ID, null,true);
+ if (editModel == null) {
+ editModel = (ModuleStructuralModel)EditModelRegistry.getInstance().createEditModelForRead(ModuleStructuralModelFactory.MODULE_STRUCTURAL_MODEL_ID, getEmfContext(), null);
+ synchronized (editModel) {
+ getEmfContext().cacheEditModel(editModel, null);
+ editModel.access(anAccessorKey);
+ }
+ } else {
+ synchronized (editModel) {
+ editModel.access(anAccessorKey);
+ }
+ }
+ return editModel;
}
/**
@@ -264,14 +304,27 @@
* @return A {@see ModuleStructuralModel}for the project of the current nature.
*/
public ModuleStructuralModel getModuleStructuralModelForWrite(Object anAccessorKey) {
- return (ModuleStructuralModel) getEditModelForWrite(ModuleStructuralModelFactory.MODULE_STRUCTURAL_MODEL_ID, anAccessorKey);
+ // Return self managed edit model - will always cache locally
+ ModuleStructuralModel editModel = (ModuleStructuralModel)getEmfContext().getExistingEditModel(ModuleStructuralModelFactory.MODULE_STRUCTURAL_MODEL_ID, null,false);
+ if (editModel == null) {
+ editModel = (ModuleStructuralModel)EditModelRegistry.getInstance().createEditModelForWrite(ModuleStructuralModelFactory.MODULE_STRUCTURAL_MODEL_ID, getEmfContext(), null);
+ synchronized (editModel) {
+ getEmfContext().cacheEditModel(editModel, null);
+ editModel.access(anAccessorKey);
+ }
+ } else {
+ synchronized (editModel) {
+ editModel.access(anAccessorKey);
+ }
+ }
+ return editModel;
}
/**
* <p>
* Returns an {@see ArtifactEditModel} to work with the underlying content of an
- * individual {@see WorkbenchComponent} contained in the project. {@see ArtifactEditModel}s
- * are used to manipulate the content models for individual {@see WorkbenchComponent}s. In
+ * individual {@see org.eclipse.wst.common.componentcore.internal.WorkbenchComponent} contained in the project. {@see ArtifactEditModel}s
+ * are used to manipulate the content models for individual {@see org.eclipse.wst.common.componentcore.internal.WorkbenchComponent}s. In
* general, a content model will contain an EMF representation of the module's relevant
* deployment descriptor, and possibly other EMF resources as well.
* </p>
@@ -296,7 +349,7 @@
* <code>WebEdit editFacade = WebEdit.getWebEditForRead(aWorkbenchModule);</code>
* </p>
* <p>
- * If a particular Edit Facade is not applicable to the supplied {@see WorkbenchComponent}, then
+ * If a particular Edit Facade is not applicable to the supplied {@see org.eclipse.wst.common.componentcore.internal.WorkbenchComponent}, then
* <b>null </b> will be returned.
* </p>
*
@@ -317,7 +370,7 @@
* {@see ModuleStructuralModel}.
* @return
* @see ArtifactEdit
- * @see ArtifactEdit#getArtifactEditForRead(WorkbenchComponent)
+ * @see ArtifactEdit#getArtifactEditForRead(org.eclipse.wst.common.componentcore.internal.WorkbenchComponent)
*/
public ArtifactEditModel getArtifactEditModelForRead(URI aModuleURI, Object anAccessorKey) {
return getArtifactEditModelForRead(aModuleURI, anAccessorKey, null);
@@ -372,8 +425,8 @@
/**
* <p>
* Returns an {@see ArtifactEditModel} to work with the underlying content of an
- * individual {@see WorkbenchComponent} contained in the project. {@see ArtifactEditModel}s
- * are used to manipulate the content models for individual {@see WorkbenchComponent}s. In
+ * individual {@see org.eclipse.wst.common.componentcore.internal.WorkbenchComponent} contained in the project. {@see ArtifactEditModel}s
+ * are used to manipulate the content models for individual {@see org.eclipse.wst.common.componentcore.internal.WorkbenchComponent}s. In
* general, a content model will contain an EMF representation of the module's relevant
* deployment descriptor, and possibly other EMF resources as well.
* </p>
@@ -399,7 +452,7 @@
* <code>WebEdit editFacade = WebEdit.getWebEditForWrite(aWorkbenchModule);</code>
* </p>
* <p>
- * If a particular Edit Facade is not applicable to the supplied {@see WorkbenchComponent}, then
+ * If a particular Edit Facade is not applicable to the supplied {@see org.eclipse.wst.common.componentcore.internal.WorkbenchComponent}, then
* <b>null </b> will be returned.
* </p>
*
@@ -420,7 +473,7 @@
* {@see ModuleStructuralModel}.
* @return
* @see ArtifactEdit
- * @see ArtifactEdit#getArtifactEditForRead(WorkbenchComponent)
+ * @see ArtifactEdit#getArtifactEditForRead(org.eclipse.wst.common.componentcore.internal.WorkbenchComponent)
*/
public ArtifactEditModel getArtifactEditModelForWrite(URI aModuleURI, Object anAccessorKey) {
return getArtifactEditModelForWrite(aModuleURI, anAccessorKey, null);
@@ -496,11 +549,12 @@
// addAdapterFactories(set);
// set.getSynchronizer().addExtender(this); // added so we can be informed of closes to the
// new J2EEResourceDependencyRegister(set); // This must be done after the URIConverter is
- cacheModuleStructuralModel();
+ projectResourceSet.getSynchronizer().addExtender(this); // added so we can be informed of closes
+ cacheModuleStructuralModels();
}
/**
- * @see EMFNature.primConfigure
+ * @see org.eclipse.jem.util.emf.workbench.nature.EMFNature.primConfigure
*/
protected void primConfigure() throws CoreException {
super.primConfigure();
@@ -552,9 +606,11 @@
}
- private void cacheModuleStructuralModel() {
- if (cachedModel == null)
- cachedModel = getModuleStructuralModelForRead(this);
+ private void cacheModuleStructuralModels() {
+ if (cachedWriteHandle == null)
+ cachedWriteHandle = getModuleStructuralModelForWrite(this);
+ if (cachedReadHandle == null)
+ cachedReadHandle = getModuleStructuralModelForRead(this);
}
protected String getPluginID() {
@@ -567,9 +623,17 @@
public void shutdown() {
super.shutdown();
- if (cachedModel != null) {
- cachedModel.dispose();
- cachedModel = null;
+ if (cachedWriteHandle != null) {
+ if (cachedWriteHandle.isDirty())
+ cachedWriteHandle.saveIfNecessary(this);
+ cachedWriteHandle.dispose();
+ cachedWriteHandle = null;
+ }
+ if (cachedReadHandle != null) {
+ if (cachedReadHandle.isDirty())
+ cachedReadHandle.saveIfNecessary(this);
+ cachedReadHandle.dispose();
+ cachedReadHandle = null;
}
}
@@ -579,9 +643,12 @@
* @see org.eclipse.wst.common.internal.emfworkbench.ISynchronizerExtender#projectChanged(org.eclipse.core.resources.IResourceDelta)
*/
public void projectChanged(IResourceDelta delta) {
- if (delta.getKind() == IResourceDelta.OPEN)
- if (cachedModel == null)
- cachedModel = getModuleStructuralModelForRead(this);
+ if (delta.getKind() == IResourceDelta.OPEN) {
+ if (cachedWriteHandle == null)
+ cachedWriteHandle = getModuleStructuralModelForWrite(this);
+ if (cachedReadHandle == null)
+ cachedReadHandle = getModuleStructuralModelForRead(this);
+ }
}
@@ -591,10 +658,19 @@
* @see org.eclipse.wst.common.internal.emfworkbench.ISynchronizerExtender#projectClosed()
*/
public void projectClosed() {
+// StringBuffer buffer = new StringBuffer("Disposing Module models for project: ");
+// buffer.append(this.getProject());
+// System.out.println(buffer.toString());
this.emfContext = null;
- if (cachedModel != null) {
- cachedModel.dispose();
- cachedModel = null;
+ if (cachedWriteHandle != null) {
+ if (cachedWriteHandle.isDirty())
+ cachedWriteHandle.saveIfNecessary(this);
+ cachedWriteHandle.dispose();
+ cachedWriteHandle = null;
+ }
+ if (cachedReadHandle != null) {
+ cachedReadHandle.dispose();
+ cachedReadHandle = null;
}
}
diff --git a/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/datamodel/FacetDataModelConfigAdapter.java b/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/datamodel/FacetDataModelConfigAdapter.java
index 705a702..431c7ee 100644
--- a/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/datamodel/FacetDataModelConfigAdapter.java
+++ b/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/datamodel/FacetDataModelConfigAdapter.java
@@ -13,11 +13,13 @@
import org.eclipse.core.runtime.IAdapterFactory;
import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Status;
import org.eclipse.wst.common.componentcore.datamodel.properties.IFacetDataModelProperties;
import org.eclipse.wst.common.frameworks.datamodel.IDataModel;
-import org.eclipse.wst.common.project.facet.core.IActionConfig;
+import org.eclipse.wst.common.project.facet.core.ActionConfig;
+import org.eclipse.wst.common.project.facet.core.IFacetedProjectWorkingCopy;
import org.eclipse.wst.common.project.facet.core.IProjectFacetVersion;
+import org.eclipse.wst.common.project.facet.core.events.IFacetedProjectEvent;
+import org.eclipse.wst.common.project.facet.core.events.IFacetedProjectListener;
/**
* @author <a href="mailto:kosta@bea.com">Konstantin Komissarchik</a>
@@ -25,7 +27,7 @@
public final class FacetDataModelConfigAdapter
- implements IActionConfig
+ extends ActionConfig
{
private final IDataModel dm;
@@ -35,19 +37,30 @@
this.dm = dm;
}
- public void setVersion( final IProjectFacetVersion fv )
+ public void setProjectFacetVersion( final IProjectFacetVersion fv )
{
dm.setProperty( IFacetDataModelProperties.FACET_VERSION, fv );
}
-
- public void setProjectName( final String pjname )
+
+ public void setFacetedProjectWorkingCopy( final IFacetedProjectWorkingCopy fpjwc )
{
- dm.setStringProperty( IFacetDataModelProperties.FACET_PROJECT_NAME, pjname );
+ dm.setProperty( IFacetDataModelProperties.FACETED_PROJECT_WORKING_COPY, fpjwc );
+
+ final IFacetedProjectListener nameChangeListener = new IFacetedProjectListener()
+ {
+ public void handleEvent( final IFacetedProjectEvent event )
+ {
+ dm.setStringProperty( IFacetDataModelProperties.FACET_PROJECT_NAME, fpjwc.getProjectName() );
+ }
+ };
+
+ fpjwc.addListener( nameChangeListener, IFacetedProjectEvent.Type.PROJECT_NAME_CHANGED );
+ nameChangeListener.handleEvent( null );
}
public IStatus validate()
{
- return Status.OK_STATUS;
+ return dm.validate();
}
public static final class Factory
@@ -55,13 +68,12 @@
implements IAdapterFactory
{
- private static final Class[] ADAPTER_TYPES
- = { IActionConfig.class };
+ private static final Class[] ADAPTER_TYPES = { ActionConfig.class };
public Object getAdapter( final Object adaptable,
final Class adapterType )
{
- if( adapterType == IActionConfig.class )
+ if( adapterType == ActionConfig.class )
{
return new FacetDataModelConfigAdapter( (IDataModel) adaptable );
}
diff --git a/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/datamodel/FacetDataModelProvider.java b/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/datamodel/FacetDataModelProvider.java
index 1300287..59a3b2d 100644
--- a/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/datamodel/FacetDataModelProvider.java
+++ b/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/datamodel/FacetDataModelProvider.java
@@ -1,10 +1,10 @@
/*******************************************************************************
- * Copyright (c) 2003, 2005 IBM Corporation and others.
+ * Copyright (c) 2003, 2006 IBM Corporation 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:
* IBM Corporation - initial API and implementation
*******************************************************************************/
@@ -31,6 +31,7 @@
public Set getPropertyNames() {
Set names = super.getPropertyNames();
+ names.add(FACETED_PROJECT_WORKING_COPY);
names.add(FACET_PROJECT_NAME);
names.add(FACET_ID);
names.add(FACET_VERSION_STR);
diff --git a/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/datamodel/FacetInstallDataModelProvider.java b/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/datamodel/FacetInstallDataModelProvider.java
index cb2ab1d..5022348 100644
--- a/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/datamodel/FacetInstallDataModelProvider.java
+++ b/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/datamodel/FacetInstallDataModelProvider.java
@@ -1,10 +1,10 @@
/*******************************************************************************
- * Copyright (c) 2003, 2005 IBM Corporation and others.
+ * Copyright (c) 2003, 2007 IBM Corporation 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:
* IBM Corporation - initial API and implementation
*******************************************************************************/
@@ -43,8 +43,8 @@
IProjectFacetVersion version = (IProjectFacetVersion) getProperty(FACET_VERSION);
return version.getVersionString();
} else if (FACET_VERSION.equals(propertyName)) {
- DataModelPropertyDescriptor[] validVersions = getValidPropertyDescriptors(FACET_VERSION);
- return validVersions[validVersions.length - 1].getPropertyValue();
+ IProjectFacetVersion version = ProjectFacetsManager.getProjectFacet(getStringProperty(FACET_ID)).getDefaultVersion();
+ return version;
}
return super.getDefaultProperty(propertyName);
}
@@ -107,4 +107,4 @@
return DataModelFactory.createDataModel(this);
}
-}
\ No newline at end of file
+}
diff --git a/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/datamodel/FacetProjectCreationDataModelProvider.java b/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/datamodel/FacetProjectCreationDataModelProvider.java
index bf7c505..d8cb5d6 100644
--- a/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/datamodel/FacetProjectCreationDataModelProvider.java
+++ b/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/datamodel/FacetProjectCreationDataModelProvider.java
@@ -1,10 +1,10 @@
/*******************************************************************************
- * Copyright (c) 2003, 2005 IBM Corporation and others.
+ * Copyright (c) 2003, 2007 IBM Corporation 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:
* IBM Corporation - initial API and implementation
*******************************************************************************/
@@ -15,12 +15,15 @@
import java.util.Collection;
import java.util.Comparator;
import java.util.HashMap;
+import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IStatus;
+import org.eclipse.core.runtime.Path;
+import org.eclipse.core.runtime.Platform;
import org.eclipse.jem.util.logger.proxy.Logger;
import org.eclipse.wst.common.componentcore.datamodel.properties.IFacetDataModelProperties;
import org.eclipse.wst.common.componentcore.datamodel.properties.IFacetProjectCreationDataModelProperties;
@@ -36,10 +39,15 @@
import org.eclipse.wst.common.frameworks.internal.operations.ProjectCreationDataModelProviderNew;
import org.eclipse.wst.common.frameworks.internal.plugin.WTPCommonMessages;
import org.eclipse.wst.common.frameworks.internal.plugin.WTPCommonPlugin;
+import org.eclipse.wst.common.project.facet.core.FacetedProjectFramework;
+import org.eclipse.wst.common.project.facet.core.IFacetedProject;
+import org.eclipse.wst.common.project.facet.core.IFacetedProjectWorkingCopy;
import org.eclipse.wst.common.project.facet.core.IProjectFacet;
import org.eclipse.wst.common.project.facet.core.IProjectFacetVersion;
import org.eclipse.wst.common.project.facet.core.ProjectFacetsManager;
import org.eclipse.wst.common.project.facet.core.IFacetedProject.Action;
+import org.eclipse.wst.common.project.facet.core.events.IFacetedProjectEvent;
+import org.eclipse.wst.common.project.facet.core.events.IFacetedProjectListener;
import org.eclipse.wst.common.project.facet.core.runtime.IRuntime;
import org.eclipse.wst.common.project.facet.core.runtime.RuntimeManager;
@@ -62,6 +70,7 @@
public Set getPropertyNames() {
Set names = super.getPropertyNames();
+ names.add(FACETED_PROJECT_WORKING_COPY);
names.add(FACET_PROJECT_NAME);
names.add(FACET_DM_MAP);
names.add(FACET_ACTION_MAP);
@@ -73,12 +82,65 @@
public void init() {
super.init();
+
+ final IFacetedProjectWorkingCopy fpjwc = FacetedProjectFramework.createNewProject();
+ model.setProperty(FACETED_PROJECT_WORKING_COPY, fpjwc);
+
+ fpjwc.addListener
+ (
+ new IFacetedProjectListener()
+ {
+ public void handleEvent( final IFacetedProjectEvent event )
+ {
+ for( IFacetedProject.Action action : fpjwc.getProjectFacetActions() )
+ {
+ final Object config = action.getConfig();
+
+ if( config != null && config instanceof IDataModel )
+ {
+ final IDataModel dm = (IDataModel) config;
+
+ if( dm.getAllProperties().contains( FacetInstallDataModelProvider.MASTER_PROJECT_DM ) )
+ {
+ dm.setProperty( FacetInstallDataModelProvider.MASTER_PROJECT_DM, model );
+ }
+ }
+ }
+ }
+ },
+ IFacetedProjectEvent.Type.PROJECT_FACETS_CHANGED
+ );
+
+ fpjwc.addListener
+ (
+ new IFacetedProjectListener()
+ {
+ public void handleEvent( final IFacetedProjectEvent event )
+ {
+ model.notifyPropertyChange(FACET_RUNTIME, IDataModel.VALID_VALUES_CHG);
+ }
+ },
+ IFacetedProjectEvent.Type.AVAILABLE_RUNTIMES_CHANGED
+ );
+
IDataModel projectDataModel = DataModelFactory.createDataModel(new ProjectCreationDataModelProviderNew());
projectDataModel.addListener(new IDataModelListener() {
- public void propertyChanged(DataModelEvent event) {
- if (IProjectCreationPropertiesNew.PROJECT_NAME.equals(event.getPropertyName())) {
- getDataModel().setProperty(FACET_PROJECT_NAME, event.getProperty());
+ public void propertyChanged(DataModelEvent event)
+ {
+ final String prop = event.getPropertyName();
+
+ if( event.getFlag() == IDataModel.VALUE_CHG &&
+ prop.equals( IProjectCreationPropertiesNew.PROJECT_NAME ) )
+ {
+ final String projectName = (String) event.getProperty();
+ getDataModel().setProperty(FACET_PROJECT_NAME, projectName);
+ fpjwc.setProjectName( projectName );
}
+ else if( prop.equals( IProjectCreationPropertiesNew.PROJECT_LOCATION ) )
+ {
+ final String location = (String) event.getProperty();
+ fpjwc.setProjectLocation( location == null ? null : new Path( location ) );
+ }
}
});
model.addNestedModel(NESTED_PROJECT_DM, projectDataModel);
@@ -222,8 +284,6 @@
} else {
event.getDataModel().removeListener(this);
}
- } else if (event.getPropertyName().equals(IFacetDataModelProperties.FACET_VERSION)) {
- getDataModel().notifyPropertyChange(FACET_RUNTIME, IDataModel.VALID_VALUES_CHG);
}
}
@@ -266,6 +326,30 @@
}
}
}
+ else if( REQUIRED_FACETS_COLLECTION.equals(propertyName) )
+ {
+ final IFacetedProjectWorkingCopy fpjwc
+ = (IFacetedProjectWorkingCopy) this.model.getProperty( FACETED_PROJECT_WORKING_COPY );
+
+ final Collection<IProjectFacet> fixedFacets = (Collection<IProjectFacet>) propertyValue;
+
+ fpjwc.setFixedProjectFacets( new HashSet<IProjectFacet>( fixedFacets ) );
+
+ final FacetDataModelMap facetDmMap = (FacetDataModelMap) getProperty( FACET_DM_MAP );
+
+ for( IProjectFacet facet : fixedFacets )
+ {
+ final IFacetedProject.Action action = fpjwc.getProjectFacetAction( facet );
+ Object config = action.getConfig();
+
+ if( ! ( config instanceof IDataModel ) )
+ {
+ config = Platform.getAdapterManager().getAdapter( config, IDataModel.class );
+ }
+
+ facetDmMap.add( (IDataModel) config );
+ }
+ }
return super.propertySet(propertyName, propertyValue);
}
@@ -292,7 +376,7 @@
if (FACET_RUNTIME.equals(propertyName)) {
IRuntime runtime = (IRuntime) getProperty(propertyName);
if (null != runtime) {
- return new DataModelPropertyDescriptor(runtime, runtime.getName());
+ return new DataModelPropertyDescriptor(runtime, runtime.getLocalizedName());
}
return new DataModelPropertyDescriptor(null, WTPCommonPlugin.getResourceString(WTPCommonMessages.RUNTIME_NONE, null));
}
@@ -300,33 +384,40 @@
}
public DataModelPropertyDescriptor[] getValidPropertyDescriptors(String propertyName) {
- if (FACET_RUNTIME.equals(propertyName)) {
- Collection projectFacets = (Collection)getProperty(REQUIRED_FACETS_COLLECTION);
- Set runtimes = RuntimeManager.getRuntimes();
- ArrayList list = new ArrayList();
+ if (FACET_RUNTIME.equals(propertyName))
+ {
+ final IFacetedProjectWorkingCopy fpjwc
+ = (IFacetedProjectWorkingCopy) this.model.getProperty( FACETED_PROJECT_WORKING_COPY );
+
+ final Set<IProjectFacet> fixedFacets = fpjwc.getFixedProjectFacets();
+ final ArrayList list = new ArrayList();
- for (Iterator it = runtimes.iterator(); it.hasNext();) {
- IRuntime rt = (IRuntime) it.next();
+ for( IRuntime rt : RuntimeManager.getRuntimes() )
+ {
+ // add this runtime in the list only if it supports all of the required facets
- // add this runtime in the list only if it supports all of the required facets
- boolean supportsFactet = true;
- for (Iterator facetIt = projectFacets.iterator(); facetIt.hasNext();) {
- IProjectFacet facet = (IProjectFacet) facetIt.next();
- if (!rt.supports(facet)) {
- supportsFactet = false;
- break;
- }
- }
- if (supportsFactet) {
- list.add(rt);
- }
- }
+ boolean supports = true;
+
+ for( IProjectFacet facet : fixedFacets )
+ {
+ if( ! rt.supports( facet ) )
+ {
+ supports = false;
+ break;
+ }
+ }
+
+ if( supports )
+ {
+ list.add(rt);
+ }
+ }
- DataModelPropertyDescriptor[] descriptors = new DataModelPropertyDescriptor[list.size() + 1];
+ DataModelPropertyDescriptor[] descriptors = new DataModelPropertyDescriptor[list.size() + 1];
Iterator iterator = list.iterator();
for (int i = 0; i < descriptors.length - 1; i++) {
IRuntime runtime = (IRuntime) iterator.next();
- descriptors[i] = new DataModelPropertyDescriptor(runtime, runtime.getName());
+ descriptors[i] = new DataModelPropertyDescriptor(runtime, runtime.getLocalizedName());
}
if(descriptors.length > 2){
Arrays.sort(descriptors, 0, descriptors.length - 2, new Comparator() {
@@ -344,11 +435,21 @@
return super.getValidPropertyDescriptors(propertyName);
}
- public IStatus validate(String propertyName) {
- if (FACET_PROJECT_NAME.equals(propertyName)) {
+ public IStatus validate(String propertyName)
+ {
+ if (FACET_PROJECT_NAME.equals(propertyName))
+ {
IDataModel projModel = model.getNestedModel(NESTED_PROJECT_DM);
return projModel.validateProperty(IProjectCreationPropertiesNew.PROJECT_NAME);
}
+ else if( propertyName.equals( FACETED_PROJECT_WORKING_COPY ) )
+ {
+ final IFacetedProjectWorkingCopy fpjwc
+ = (IFacetedProjectWorkingCopy) this.model.getProperty( FACETED_PROJECT_WORKING_COPY );
+
+ return fpjwc.validate();
+ }
+
return super.validate(propertyName);
}
diff --git a/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/datamodel/FlexibleProjectCreationDataModelProvider.java b/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/datamodel/FlexibleProjectCreationDataModelProvider.java
deleted file mode 100644
index 37f1403..0000000
--- a/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/datamodel/FlexibleProjectCreationDataModelProvider.java
+++ /dev/null
@@ -1,127 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2005 IBM Corporation 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.common.componentcore.datamodel;
-
-import java.util.Set;
-
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.wst.common.componentcore.datamodel.properties.IFlexibleProjectCreationDataModelProperties;
-import org.eclipse.wst.common.componentcore.internal.operation.FlexibleProjectCreationOperation;
-import org.eclipse.wst.common.frameworks.datamodel.AbstractDataModelProvider;
-import org.eclipse.wst.common.frameworks.datamodel.DataModelFactory;
-import org.eclipse.wst.common.frameworks.datamodel.IDataModel;
-import org.eclipse.wst.common.frameworks.datamodel.IDataModelOperation;
-import org.eclipse.wst.common.frameworks.internal.DoNotUseMeThisWillBeDeletedPost15;
-import org.eclipse.wst.common.frameworks.internal.operations.IProjectCreationProperties;
-import org.eclipse.wst.common.frameworks.internal.operations.ProjectCreationDataModelProvider;
-
-/**
- * This has been slated for removal post WTP 1.5. Do not use this class/interface
- *
- * @deprecated
- *
- * @see FacetProjectCreationDataModelProvider
- */
-public class FlexibleProjectCreationDataModelProvider extends AbstractDataModelProvider implements IFlexibleProjectCreationDataModelProperties, DoNotUseMeThisWillBeDeletedPost15 {
-
- public FlexibleProjectCreationDataModelProvider() {
- super();
-
- }
-
- public void init() {
- super.init();
- initNestedProjectModel();
- }
-
- protected void initNestedProjectModel() {
- IDataModel projModel = DataModelFactory.createDataModel(new ProjectCreationDataModelProvider());
- model.addNestedModel(NESTED_MODEL_PROJECT_CREATION, projModel);
- }
-
- public Set getPropertyNames() {
- Set propertyNames = super.getPropertyNames();
- propertyNames.add(PROJECT_NAME);
- propertyNames.add(PROJECT_LOCATION);
- propertyNames.add(NESTED_MODEL_PROJECT_CREATION);
- return propertyNames;
- }
-
- public Object getDefaultProperty(String propertyName) {
- if (PROJECT_LOCATION.equals(propertyName)) {
- return getDefaultLocation();
- }
- return super.getDefaultProperty(propertyName);
- }
-
- public boolean propertySet(String propertyName, Object propertyValue) {
- boolean status = super.propertySet(propertyName, propertyValue);
- if (PROJECT_NAME.equals(propertyName)) {
- IDataModel projModel = model.getNestedModel(NESTED_MODEL_PROJECT_CREATION);
- projModel.setProperty(IProjectCreationProperties.PROJECT_NAME, propertyValue);
- } else if (PROJECT_LOCATION.equals(propertyName)) {
- IDataModel projModel = model.getNestedModel(NESTED_MODEL_PROJECT_CREATION);
- projModel.setProperty(IProjectCreationProperties.PROJECT_LOCATION, propertyValue);
- }
- return status;
- }
-
- public IStatus validate(String propertyName) {
- if (PROJECT_NAME.equals(propertyName)) {
- return validateProjectName();
- } else if (PROJECT_LOCATION.equals(propertyName)) {
- return validateProjectLocation();
- }
- return OK_STATUS;
- }
-
- private IStatus validateProjectName() {
- IDataModel projModel = model.getNestedModel(NESTED_MODEL_PROJECT_CREATION);
- return projModel.validateProperty(IProjectCreationProperties.PROJECT_NAME);
- }
-
- private IStatus validateProjectLocation() {
- IDataModel projModel = model.getNestedModel(NESTED_MODEL_PROJECT_CREATION);
- return projModel.validateProperty(IProjectCreationProperties.PROJECT_LOCATION);
- }
-
- private String getDefaultLocation() {
- IPath path = getRootLocation();
- String projectName = (String) getProperty(PROJECT_NAME);
- if (projectName != null)
- path = path.append(projectName);
- return path.toOSString();
- }
-
- private IPath getRootLocation() {
- return ResourcesPlugin.getWorkspace().getRoot().getLocation();
- }
-
- //
- // protected void initNestedModels() {
- // super.initNestedModels();
- // initProjectModel();
- // addNestedModel(NESTED_MODEL_PROJECT_CREATION, projectDataModel);
- //
- // serverTargetDataModel = new J2EEProjectServerTargetDataModel();
- // addNestedModel(NESTED_MODEL_SERVER_TARGET, serverTargetDataModel);
- // }
-
- // protected void initProjectModel() {
- // projectDataModel = new ProjectCreationDataModel();
- // }
- //
- public IDataModelOperation getDefaultOperation() {
- return new FlexibleProjectCreationOperation(model);
- }
-}
diff --git a/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/datamodel/properties/IComponentCreationDataModelProperties.java b/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/datamodel/properties/IComponentCreationDataModelProperties.java
index 09fbe2f..c8dcf56 100644
--- a/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/datamodel/properties/IComponentCreationDataModelProperties.java
+++ b/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/datamodel/properties/IComponentCreationDataModelProperties.java
@@ -1,5 +1,5 @@
/*******************************************************************************
- * Copyright (c) 2003, 2005 IBM Corporation and others.
+ * Copyright (c) 2003, 2006 IBM Corporation 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
diff --git a/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/datamodel/properties/ICreateReferenceComponentsDataModelProperties.java b/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/datamodel/properties/ICreateReferenceComponentsDataModelProperties.java
index 5030462..0dec083 100644
--- a/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/datamodel/properties/ICreateReferenceComponentsDataModelProperties.java
+++ b/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/datamodel/properties/ICreateReferenceComponentsDataModelProperties.java
@@ -1,5 +1,5 @@
/*******************************************************************************
- * Copyright (c) 2005 IBM Corporation and others.
+ * Copyright (c) 2005, 2007 IBM Corporation 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
@@ -10,59 +10,55 @@
*******************************************************************************/
package org.eclipse.wst.common.componentcore.datamodel.properties;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-import org.eclipse.wst.common.componentcore.resources.IVirtualComponent;
-import org.eclipse.wst.common.frameworks.internal.DoNotUseMeThisWillBeDeletedPost15;
-
public interface ICreateReferenceComponentsDataModelProperties {
/**
* <p>
- * This required property is the {@link IVirtualComponent} which will reference the
- * {@link IVirtualComponent}s specified by {@link #TARGET_COMPONENT_LIST}.
+ * This required property is the {@link org.eclipse.wst.common.componentcore.resources.IVirtualComponent} which will reference the
+ * {@link org.eclipse.wst.common.componentcore.resources.IVirtualComponent}s specified by {@link #TARGET_COMPONENT_LIST}.
* </p>
* <p>
- * For example, if {@link IVirtualComponent}s A, B, and C exist and references are required
+ * For example, if {@link org.eclipse.wst.common.componentcore.resources.IVirtualComponent}s A, B, and C exist and references are required
* from A to B and A to C, then {@link #SOURCE_COMPONENT} should be set to A, and
- * {@link #TARGET_COMPONENT_LIST} should be set to a {@link List} containing B and C.
+ * {@link #TARGET_COMPONENT_LIST} should be set to a {@link java.util.List} containing B and C.
* </p>
*/
public static final String SOURCE_COMPONENT = "ICreateReferenceComponentsDataModelProperties.SOURCE_COMPONENT"; //$NON-NLS-1$
/**
* <p>
- * This required property is the {@link List} containing the {@link IVirtualComponent}s that
- * will be referenced from the {@link IVirtualComponent} specified by {@link #SOURCE_COMPONENT}.
+ * This required property is the {@link java.util.List} containing the {@link org.eclipse.wst.common.componentcore.resources.IVirtualComponent}s that
+ * will be referenced from the {@link org.eclipse.wst.common.componentcore.resources.IVirtualComponent} specified by {@link #SOURCE_COMPONENT}.
* </p>
*/
public static final String TARGET_COMPONENT_LIST = "ICreateReferenceComponentsDataModelProperties.TARGET_COMPONENT"; //$NON-NLS-1$
- //TODO this should be a map
/**
* Optional, deploy path for the dependent component, default is "/"
+ * Note: this is the default for the entire archive. See {@link #TARGET_COMPONENTS_DEPLOY_PATH_MAP}
*/
public static final String TARGET_COMPONENTS_DEPLOY_PATH = "ICreateReferenceComponentsDataModelProperties.TARGET_COMPONENT_DEPLOY_PATH"; //$NON-NLS-1$
/**
- * Optional, archive name for the dependent component, default is ""
- *
- * @deprecated
- * @see DoNotUseMeThisWillBeDeletedPost15
- */
- public static final String TARGET_COMPONENT_ARCHIVE_NAME = "ICreateReferenceComponentsDataModelProperties.TARGET_COMPONENT_ARCHIVE_NAME"; //$NON-NLS-1$
-
- /**
* <p>
* This optional property is the {@link Map} containing keys of {@link IVirtualComponent}s and
* values of {@link String}s. This map is used to specify the String which should be used by
* the {@link IVirtualComponent} specified by the {@link #SOURCE_COMPONENT} property to lookup
- * the keyed {@link IVirtualComponent}. The {@link Set} of {@link IVirtualComponent}s in the
+ * the deploy path. The {@link Set} of {@link IVirtualComponent}s in the
* keys of this {@link Map} should have the same contents as the {@link List}.
* </p>
*/
+ public static final String TARGET_COMPONENTS_DEPLOY_PATH_MAP = "ICreateReferenceComponentsDataModelProperties.TARGET_COMPONENT_DEPLOY_PATH_MAP"; //$NON-NLS-1$
+
+ /**
+ * <p>
+ * This optional property is the {@link java.util.Map} containing keys of {@link org.eclipse.wst.common.componentcore.resources.IVirtualComponent}s and
+ * values of {@link String}s. This map is used to specify the String which should be used by
+ * the {@link org.eclipse.wst.common.componentcore.resources.IVirtualComponent} specified by the {@link #SOURCE_COMPONENT} property to lookup
+ * the keyed {@link org.eclipse.wst.common.componentcore.resources.IVirtualComponent}. The {@link java.util.Set} of {@link org.eclipse.wst.common.componentcore.resources.IVirtualComponent}s in the
+ * keys of this {@link java.util.Map} should have the same contents as the {@link java.util.List}.
+ * </p>
+ */
public static final String TARGET_COMPONENTS_TO_URI_MAP = "ICreateReferenceComponentsDataModelProperties.TARGET_COMPONENTS_TO_URI_MAP"; //$NON-NLS-1$
}
diff --git a/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/datamodel/properties/IFacetDataModelProperties.java b/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/datamodel/properties/IFacetDataModelProperties.java
index 5f647cc..91c694d 100644
--- a/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/datamodel/properties/IFacetDataModelProperties.java
+++ b/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/datamodel/properties/IFacetDataModelProperties.java
@@ -1,10 +1,10 @@
/*******************************************************************************
- * Copyright (c) 2003, 2005 IBM Corporation and others.
+ * Copyright (c) 2003, 2006 IBM Corporation 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:
* IBM Corporation - initial API and implementation
*******************************************************************************/
@@ -38,4 +38,6 @@
public static final String FACET_ACTION = "IFacetDataModelProperties.FACET_ACTION"; //$NON-NLS-1$
public static final String SHOULD_EXECUTE = "IFacetDataModelProperties.SHOULD_EXECUTE"; //$NON-NLS-1$
+
+ public static final String FACETED_PROJECT_WORKING_COPY = "IFacetDataModelProperties.FACETED_PROJECT_WORKING_COPY"; //$NON-NLS-1$
}
diff --git a/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/datamodel/properties/IFacetProjectCreationDataModelProperties.java b/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/datamodel/properties/IFacetProjectCreationDataModelProperties.java
index c92d8c6..0d76a0f 100644
--- a/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/datamodel/properties/IFacetProjectCreationDataModelProperties.java
+++ b/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/datamodel/properties/IFacetProjectCreationDataModelProperties.java
@@ -1,10 +1,10 @@
/*******************************************************************************
- * Copyright (c) 2003, 2005 IBM Corporation and others.
+ * Copyright (c) 2003, 2006 IBM Corporation 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:
* IBM Corporation - initial API and implementation
*******************************************************************************/
@@ -17,6 +17,9 @@
import org.eclipse.wst.common.project.facet.core.IFacetedProject;
public interface IFacetProjectCreationDataModelProperties extends IDataModelProperties {
+
+ public static final String FACETED_PROJECT_WORKING_COPY
+ = "IFacetProjectCreationDataModelProperties.FACETED_PROJECT_WORKING_COPY"; //$NON-NLS-1$";
/**
* A String
diff --git a/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/datamodel/properties/IFlexibleProjectCreationDataModelProperties.java b/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/datamodel/properties/IFlexibleProjectCreationDataModelProperties.java
deleted file mode 100644
index b101ec6..0000000
--- a/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/datamodel/properties/IFlexibleProjectCreationDataModelProperties.java
+++ /dev/null
@@ -1,48 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2005 IBM Corporation 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.common.componentcore.datamodel.properties;
-
-import org.eclipse.wst.common.frameworks.internal.DoNotUseMeThisWillBeDeletedPost15;
-import org.eclipse.wst.common.frameworks.internal.operations.IProjectCreationProperties;
-/**
- * <p>
- * IFlexibleProjectCreationDataModelProperties provides properties to the DataModel associated with the
- * FlexibleProjectCreationDataModelProperties as well as all extending interfaces extending
- * IFlexibleProjectCreationDataModelProperties specifically, but not limited to the Java releated creatoin in the
- * JST layer.
- * @see FlexibleJavaProjectCreationDataModelProvider
- * </p>
- * <p>
- * This interface is not intended to be implemented by clients.
- * </p>
- *
- * @see org.eclipse.wst.common.frameworks.datamodel.IDataModelProvider
- * @see org.eclipse.wst.common.frameworks.datamodel.DataModelFactory
- * @see org.eclipse.wst.common.frameworks.datamodel.IDataModelProperties
- *
- * @plannedfor 1.0
- */
-/**
- * This has been slated for removal post WTP 1.5. Do not use this class/interface
- *
- * @deprecated
- *
- * @see IFacetProjectCreationDataModelProperties
- */
-public interface IFlexibleProjectCreationDataModelProperties extends IProjectCreationProperties, DoNotUseMeThisWillBeDeletedPost15 {
-
- /**
- * Required, type IDataModel. The user set IDataModel used to create the initial project. Providers which currently exist for
- * this IDataModel include IProjectCreationProperties.
- * @see org.eclipse.wst.common.frameworks.internal.operations.IProjectCreationProperties
- */
- public static final String NESTED_MODEL_PROJECT_CREATION = "IFlexibleProjectCreationDataModelProperties.NESTED_MODEL_PROJECT_CREATION"; //$NON-NLS-1$
-}
diff --git a/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/datamodel/properties/IServerContextRootDataModelProperties.java b/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/datamodel/properties/IServerContextRootDataModelProperties.java
new file mode 100644
index 0000000..c939138
--- /dev/null
+++ b/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/datamodel/properties/IServerContextRootDataModelProperties.java
@@ -0,0 +1,24 @@
+/*******************************************************************************
+ * Copyright (c) 2008 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.wst.common.componentcore.datamodel.properties;
+
+import org.eclipse.wst.common.componentcore.internal.operation.ServerContextRootDataModelProvider;
+
+public interface IServerContextRootDataModelProperties {
+ /**
+ * This field should not be used. It is not part of the API and may be modified in the future.
+ */
+ public static Class _provider_class = ServerContextRootDataModelProvider.class;
+
+ public static final String PROJECT = "IServerContextRootDataModelProperties.PROJECT"; //$NON-NLS-1$
+ public static final String CONTEXT_ROOT = "IServerContextRootDataModelProperties.CONTEXT_ROOT"; //$NON-NLS-1$
+
+}
diff --git a/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/ArtifactEditModel.java b/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/ArtifactEditModel.java
index 199ee9e..9e38950 100644
--- a/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/ArtifactEditModel.java
+++ b/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/ArtifactEditModel.java
@@ -1,5 +1,5 @@
/*******************************************************************************
- * Copyright (c) 2003, 2005 IBM Corporation and others.
+ * Copyright (c) 2003, 2006 IBM Corporation 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
@@ -66,6 +66,8 @@
public static final Class ADAPTER_TYPE = ArtifactEditModel.class;
private final IProject componentProject;
private final IPath modulePath;
+ private URI rootURI;
+ private String rootContentType;
private final IVirtualComponent virtualComponent;
private final URI componentURI;
@@ -101,7 +103,16 @@
public ArtifactEditModel(String anEditModelId, EMFWorkbenchContext aContext, boolean toMakeReadOnly, URI aModuleURI) {
this(anEditModelId, aContext, toMakeReadOnly, true, aModuleURI);
}
-
+
+ public ArtifactEditModel(String anEditModelId, EMFWorkbenchContext aContext, boolean toMakeReadOnly, boolean toAccessUnknownResourcesAsReadOnly, URI aModuleURI,URI rootURI,
+ String rootContentType) {
+ this(anEditModelId, aContext, toMakeReadOnly, toAccessUnknownResourcesAsReadOnly, aModuleURI);
+ this.rootURI = rootURI;
+ this.rootContentType = rootContentType;
+
+ }
+
+
/**
*
* <p>
@@ -154,6 +165,14 @@
processLoadedResources(componentProject);
}
+ public ArtifactEditModel(String editModelID, EMFWorkbenchContext context, boolean toMakeReadOnly, URI moduleURI, URI rootURI,
+ String rootContentType) {
+ this(editModelID, context, toMakeReadOnly, true, moduleURI);
+ this.rootURI = rootURI;
+ this.rootContentType = rootContentType;
+
+ }
+
/**
* <p>
* Accesses resources within the underlying resource set. Takes a standard URI attaches module
@@ -168,8 +187,15 @@
* @return Resource (@see Resource)
*/
public Resource getResource(URI aUri) {
- // First check if passed URI is already normalized...
- IPath requestPath = modulePath.append(new Path(aUri.path()));
+ IPath requestPath;
+ //If requesting rootURI, use content type describer if available
+ if (rootURI != null && rootURI.equals(aUri) && rootContentType != null) {
+ requestPath = modulePath.append(new Path(rootContentType));
+ requestPath = requestPath.append(new Path(aUri.path()));
+ }
+ else {// First check if passed URI is already normalized...
+ requestPath = modulePath.append(new Path(aUri.path()));
+ }
URI resourceURI = URI.createURI(PlatformURLModuleConnection.MODULE_PROTOCOL + requestPath.toString());
return super.getResource(resourceURI);
}
diff --git a/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/BinaryComponentHelper.java b/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/BinaryComponentHelper.java
index bcade13..ea71b40 100644
--- a/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/BinaryComponentHelper.java
+++ b/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/BinaryComponentHelper.java
@@ -1,10 +1,10 @@
/*******************************************************************************
- * Copyright (c) 2003, 2005 IBM Corporation and others.
+ * Copyright (c) 2003, 2006 IBM Corporation 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:
* IBM Corporation - initial API and implementation
*******************************************************************************/
@@ -13,7 +13,6 @@
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.resource.Resource;
-import org.eclipse.wst.common.componentcore.ArtifactEdit;
import org.eclipse.wst.common.componentcore.resources.IVirtualComponent;
public abstract class BinaryComponentHelper {
@@ -28,8 +27,6 @@
return component;
}
- public abstract void releaseAccess(ArtifactEdit edit);
-
public abstract EObject getPrimaryRootObject();
public abstract Resource getResource(URI uri);
diff --git a/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/ComponentType.java b/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/ComponentType.java
index c9351db..48a0703 100644
--- a/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/ComponentType.java
+++ b/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/ComponentType.java
@@ -1,5 +1,5 @@
/*******************************************************************************
- * Copyright (c) 2003, 2005 IBM Corporation and others.
+ * Copyright (c) 2003, 2006 IBM Corporation 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
diff --git a/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/DependencyType.java b/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/DependencyType.java
index e44eded..09914ab 100644
--- a/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/DependencyType.java
+++ b/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/DependencyType.java
@@ -1,5 +1,5 @@
/*******************************************************************************
- * Copyright (c) 2003, 2005 IBM Corporation and others.
+ * Copyright (c) 2003, 2006 IBM Corporation 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
diff --git a/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/ModuleCoreValidator.java b/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/ModuleCoreValidator.java
index 556f612..0372d3c 100644
--- a/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/ModuleCoreValidator.java
+++ b/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/ModuleCoreValidator.java
@@ -1,16 +1,27 @@
+/*******************************************************************************
+ * Copyright (c) 2005, 2007 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
package org.eclipse.wst.common.componentcore.internal;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
+import org.eclipse.core.runtime.jobs.ILock;
import org.eclipse.core.runtime.jobs.ISchedulingRule;
import org.eclipse.emf.ecore.resource.Resource;
-import org.eclipse.emf.ecore.resource.ResourceSet;
import org.eclipse.emf.ecore.xmi.XMIResource;
import org.eclipse.wst.common.componentcore.ModuleCoreNature;
import org.eclipse.wst.common.componentcore.internal.impl.WTPModulesResource;
import org.eclipse.wst.common.internal.emf.resource.TranslatorResource;
+import org.eclipse.wst.common.internal.emfworkbench.edit.EMFWorkbenchEditContextFactory;
import org.eclipse.wst.common.project.facet.core.internal.FacetedProjectNature;
import org.eclipse.wst.validation.internal.core.Message;
import org.eclipse.wst.validation.internal.core.ValidationException;
@@ -40,18 +51,30 @@
if (structuralModel != null) {
// acquiring the ModuleStructuralModel lock here first because the call to getPrimaryResource()
// will cause this lock to be acquired later resulting in a potential deadlock
- synchronized (structuralModel) {
- return structuralModel.getPrimaryResource();
+ ILock lock = EMFWorkbenchEditContextFactory.getProjectLockObject(structuralModel.getProject());
+ try{
+ if(null != lock){
+ lock.acquire();
+ }
+ synchronized(structuralModel){
+ return structuralModel.getPrimaryResource();
+ }
+ } finally{
+ if(null != lock){
+ lock.release();
+ }
}
}
}
return null;
}
+/* bug197531 - standardize compiler settings
private ResourceSet getResourceSet(IProject proj) {
ModuleCoreNature nature = ModuleCoreNature.getModuleCoreNature(proj);
return nature.getResourceSet();
}
+*/
public IStatus validateInJob(IValidationContext helper, IReporter reporter)
throws ValidationException {
diff --git a/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/ModuleCoreValidatorHelper.java b/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/ModuleCoreValidatorHelper.java
index 2495975..1969f61 100644
--- a/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/ModuleCoreValidatorHelper.java
+++ b/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/ModuleCoreValidatorHelper.java
@@ -1,3 +1,13 @@
+/*******************************************************************************
+ * Copyright (c) 2005, 2006 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
package org.eclipse.wst.common.componentcore.internal;
import org.eclipse.core.resources.IResource;
diff --git a/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/ModuleMigratorManager.java b/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/ModuleMigratorManager.java
index 51558ab..88a9078 100644
--- a/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/ModuleMigratorManager.java
+++ b/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/ModuleMigratorManager.java
@@ -1,5 +1,5 @@
/*******************************************************************************
- * Copyright (c) 2005 IBM Corporation and others.
+ * Copyright (c) 2005, 2006 IBM Corporation 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
diff --git a/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/ModuleStructuralModel.java b/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/ModuleStructuralModel.java
index 75b0fdd..2bdacb1 100644
--- a/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/ModuleStructuralModel.java
+++ b/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/ModuleStructuralModel.java
@@ -1,5 +1,5 @@
/*******************************************************************************
- * Copyright (c) 2003, 2005 IBM Corporation and others.
+ * Copyright (c) 2003, 2007 IBM Corporation 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
@@ -46,7 +46,6 @@
import org.eclipse.wst.common.internal.emf.resource.TranslatorResource;
import org.eclipse.wst.common.internal.emfworkbench.EMFWorkbenchContext;
import org.eclipse.wst.common.internal.emfworkbench.integration.EditModel;
-import org.eclipse.wst.common.internal.emfworkbench.validateedit.ResourceStateValidator;
import org.eclipse.wst.common.internal.emfworkbench.validateedit.ResourceStateValidatorPresenter;
import org.eclipse.wst.common.project.facet.core.internal.FacetedProjectNature;
/**
@@ -79,8 +78,8 @@
*/
public class ModuleStructuralModel extends EditModel implements IAdaptable {
- private static final String R0_7_MODULE_META_FILE_NAME = ".component";
- private static final String R1_MODULE_META_FILE_NAME = ".settings/.component";
+ public static final String R0_7_MODULE_META_FILE_NAME = ".component";
+ public static final String R1_MODULE_META_FILE_NAME = ".settings/.component";
public static final String MODULE_CORE_ID = "moduleCoreId"; //$NON-NLS-1$
private static final String PROJECT_VERSION_1_5 = "1.5.0";
private boolean useOldFormat = false;
@@ -99,6 +98,8 @@
}
protected boolean removeResource(Resource aResource) {
if (aResource != null) {
+ //First checking if resource is loaded (Which will prevent removing in middle of loading by checking resource adapter lock)
+ aResource.isLoaded();
synchronized (aResource) {
aResource.eAdapters().remove(resourceAdapter);
return getResources().remove(aResource);
@@ -273,6 +274,24 @@
return true;
else return componentFile.isSynchronized(IResource.DEPTH_ZERO);
}
+
+ public IFile getComponentFile() {
+ IFile compFile = getProject().getFile(StructureEdit.MODULE_META_FILE_NAME);
+ if (compFile.isAccessible())
+ return compFile;
+ else { //Need to check for legacy file locations also....
+ compFile = getProject().getFile(ModuleStructuralModel.R1_MODULE_META_FILE_NAME);
+ if (compFile.isAccessible())
+ return compFile;
+ else {
+ compFile = getProject().getFile(ModuleStructuralModel.R0_7_MODULE_META_FILE_NAME);
+ if (compFile.isAccessible())
+ return compFile;
+ }
+ }
+ return getProject().getFile(StructureEdit.MODULE_META_FILE_NAME);
+ }
+
public WTPModulesResource makeWTPModulesResource() {
return (WTPModulesResource) createResource(WTPModulesResourceFactory.WTP_MODULES_URI_OBJ);
}
@@ -284,7 +303,7 @@
}
}
/**
- * @see ResourceStateValidator#checkActivation(ResourceStateValidatorPresenter)
+ * @see org.eclipse.wst.common.internal.emfworkbench.validateedit.ResourceStateValidator#checkActivation(ResourceStateValidatorPresenter)
*/
public void checkActivation(ResourceStateValidatorPresenter presenter) throws CoreException {
super.checkActivation(presenter);
@@ -300,15 +319,15 @@
// First will try to load from .settings/org.eclipse.wst.common.component
// Second will try to load from the old location(s) .settings/.component or .component
- URI uri = (URI) URI.createURI(StructureEdit.MODULE_META_FILE_NAME);
+ URI uri = URI.createURI(StructureEdit.MODULE_META_FILE_NAME);
WTPModulesResource res = (WTPModulesResource)getResource(uri);
if (res == null || !res.isLoaded()) {
removeResource(res);
- uri = (URI) URI.createURI(R1_MODULE_META_FILE_NAME);
+ uri = URI.createURI(R1_MODULE_META_FILE_NAME);
res = (WTPModulesResource)getResource(uri);
if (res == null || !res.isLoaded()) {
removeResource(res);
- uri = (URI) URI.createURI(R0_7_MODULE_META_FILE_NAME);
+ uri = URI.createURI(R0_7_MODULE_META_FILE_NAME);
res = (WTPModulesResource)getResource(uri);
if (res == null || !res.isLoaded()) {
removeResource(res);
@@ -368,4 +387,40 @@
public void setUseOldFormat(boolean useOldFormat) {
this.useOldFormat = useOldFormat;
}
+
+ public void saveIfNecessary(IProgressMonitor monitor, Object accessorKey) {
+ // Always force save
+ super.save(monitor, accessorKey);
+ }
+ @Override
+ public void access(Object accessorKey) {
+
+ super.access(accessorKey);
+// StringBuffer buffer = new StringBuffer("Access Module model (");
+// buffer.append(this.hashCode());
+// buffer.append(") Project: ");
+// buffer.append(this.getProject());
+// if (isReadOnly())
+// buffer.append(" R = "); //$NON-NLS-1$
+// else
+// buffer.append(" W = "); //$NON-NLS-1$
+// buffer.append(getRegistry().size());
+// System.out.println(buffer.toString());
+
+ }
+ @Override
+ public void releaseAccess(Object accessorKey) {
+
+ super.releaseAccess(accessorKey);
+// StringBuffer buffer = new StringBuffer("Release Module model (");
+// buffer.append(this.hashCode());
+// buffer.append(") Project: ");
+// buffer.append(this.getProject());
+// if (isReadOnly())
+// buffer.append(" R = "); //$NON-NLS-1$
+// else
+// buffer.append(" W = "); //$NON-NLS-1$
+// buffer.append(getRegistry().size());
+// System.out.println(buffer.toString());
+ }
}
diff --git a/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/ModulecorePlugin.java b/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/ModulecorePlugin.java
index 82eaa76..abb55db 100644
--- a/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/ModulecorePlugin.java
+++ b/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/ModulecorePlugin.java
@@ -1,5 +1,5 @@
/*******************************************************************************
- * Copyright (c) 2005 IBM Corporation and others.
+ * Copyright (c) 2005, 2006 IBM Corporation 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
@@ -26,6 +26,8 @@
import org.eclipse.wst.common.componentcore.internal.util.ModuleCoreEclipseAdapterFactory;
import org.eclipse.wst.common.componentcore.resources.IVirtualComponent;
import org.osgi.framework.BundleContext;
+import java.lang.Throwable;
+import org.eclipse.core.runtime.CoreException;
/**
* The main plugin class to be used in the desktop.
@@ -170,4 +172,20 @@
Throwable exception) {
return createStatus(IStatus.ERROR, aCode, aMessage, exception);
}
+
+ public static IStatus createStatus(int severity, String message, Throwable exception) {
+ return new Status(severity, PLUGIN_ID, message, exception);
+ }
+
+ public static IStatus createStatus(int severity, String message) {
+ return createStatus(severity, message, null);
+ }
+
+ public static void logError(Throwable exception) {
+ Platform.getLog(Platform.getBundle(PLUGIN_ID)).log( createStatus(IStatus.ERROR, exception.getMessage(), exception));
+ }
+
+ public static void logError(CoreException exception) {
+ Platform.getLog(Platform.getBundle(PLUGIN_ID)).log( exception.getStatus() );
+ }
}
diff --git a/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/ProjectComponents.java b/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/ProjectComponents.java
index 8e83f55..70a8a80 100644
--- a/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/ProjectComponents.java
+++ b/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/ProjectComponents.java
@@ -1,5 +1,5 @@
/*******************************************************************************
- * Copyright (c) 2003, 2005 IBM Corporation and others.
+ * Copyright (c) 2003, 2006 IBM Corporation 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
diff --git a/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/ReferencedComponent.java b/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/ReferencedComponent.java
index 774a705..dea5cf0 100644
--- a/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/ReferencedComponent.java
+++ b/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/ReferencedComponent.java
@@ -1,5 +1,5 @@
/*******************************************************************************
- * Copyright (c) 2003, 2005 IBM Corporation and others.
+ * Copyright (c) 2003, 2006 IBM Corporation 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
diff --git a/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/StructureEdit.java b/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/StructureEdit.java
index 27586f6..9b04b00 100644
--- a/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/StructureEdit.java
+++ b/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/StructureEdit.java
@@ -1,5 +1,5 @@
/*******************************************************************************
- * Copyright (c) 2003, 2005 IBM Corporation and others.
+ * Copyright (c) 2003, 2007 IBM Corporation 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
@@ -11,6 +11,7 @@
package org.eclipse.wst.common.componentcore.internal;
+import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
@@ -18,6 +19,7 @@
import java.util.List;
import java.util.Map;
+import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.ResourcesPlugin;
@@ -435,10 +437,25 @@
* to add or remove {@see WorkbenchComponent}s. If a client needs to just read the existing
* {@see WorkbenchComponent}s, use {@see #getWorkbenchModules()}.
* </p>
+ * <p>
+ * Deadlock Warning: Calling this method requires two locks. First the component file's file lock
+ * is required and then the EMFWorkbenchEditContextFactory's projectILock is required. If another
+ * thread acquires these same two locks in the opposite order, deadlock could occur.
+ * </p>
*
* @return The root object of the underlying model
*/
public ProjectComponents getComponentModelRoot() {
+ IFile file = structuralModel.getComponentFile();
+ if (!file.isSynchronized(IResource.DEPTH_ONE)) {
+ try {
+ File iofile = file.getFullPath().toFile();
+ if (iofile.exists() || file.exists())
+ file.refreshLocal(IResource.DEPTH_ONE, null);
+ } catch (CoreException ce) {
+ //ignore
+ }
+ }
ProjectComponents comps = null;
ILock lock = EMFWorkbenchEditContextFactory.getProjectLockObject(structuralModel.getProject());
try{
diff --git a/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/WorkbenchComponent.java b/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/WorkbenchComponent.java
index 5095c07..e8d7586 100644
--- a/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/WorkbenchComponent.java
+++ b/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/WorkbenchComponent.java
@@ -1,5 +1,5 @@
/*******************************************************************************
- * Copyright (c) 2003, 2005 IBM Corporation and others.
+ * Copyright (c) 2003, 2006 IBM Corporation 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
diff --git a/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/builder/DependencyGraph.java b/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/builder/DependencyGraph.java
index e811f34..74341f2 100644
--- a/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/builder/DependencyGraph.java
+++ b/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/builder/DependencyGraph.java
@@ -10,45 +10,39 @@
*******************************************************************************/
package org.eclipse.wst.common.componentcore.internal.builder;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Map;
+import java.util.Collections;
import java.util.Set;
import org.eclipse.core.resources.IProject;
+/**
+ * @deprecated use {@link IDependencyGraph}
+ */
public class DependencyGraph {
-
+
private static final DependencyGraph INSTANCE = new DependencyGraph();
-
- private final Map dependencies = new HashMap();
-
+
public static DependencyGraph getInstance() {
return INSTANCE;
}
public IProject[] getReferencingComponents(IProject target) {
- Set referencingComponents = internalGetReferencingComponents(target);
+ Set<IProject> referencingComponents = IDependencyGraph.INSTANCE.getReferencingComponents(target);
return (IProject[]) referencingComponents.toArray(new IProject[referencingComponents.size()]);
}
-
+
public void addReference(IProject target, IProject referencingComponent) {
- internalGetReferencingComponents(target).add(referencingComponent);
+ // do nothing
}
-
+
public void removeReference(IProject target, IProject referencingComponent) {
- internalGetReferencingComponents(target).remove(referencingComponent);
-
+ // do nothing
}
-
+
protected Set internalGetReferencingComponents(IProject target) {
- Set referencingComponents = (Set) dependencies.get(target);
- if(referencingComponents == null)
- dependencies.put(target, (referencingComponents = new HashSet()));
- return referencingComponents;
+ return Collections.EMPTY_SET;
}
-
+
public void clear() {
- dependencies.clear();
}
}
diff --git a/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/builder/DependencyGraphImpl.java b/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/builder/DependencyGraphImpl.java
new file mode 100644
index 0000000..678b9bd
--- /dev/null
+++ b/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/builder/DependencyGraphImpl.java
@@ -0,0 +1,502 @@
+package org.eclipse.wst.common.componentcore.internal.builder;
+
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.Set;
+
+import org.eclipse.core.resources.IProject;
+import org.eclipse.core.resources.IResource;
+import org.eclipse.core.resources.IResourceChangeEvent;
+import org.eclipse.core.resources.IResourceChangeListener;
+import org.eclipse.core.resources.IResourceDelta;
+import org.eclipse.core.resources.IResourceDeltaVisitor;
+import org.eclipse.core.resources.ResourcesPlugin;
+import org.eclipse.core.runtime.CoreException;
+import org.eclipse.core.runtime.IProgressMonitor;
+import org.eclipse.core.runtime.ISafeRunnable;
+import org.eclipse.core.runtime.IStatus;
+import org.eclipse.core.runtime.ListenerList;
+import org.eclipse.core.runtime.SafeRunner;
+import org.eclipse.core.runtime.Status;
+import org.eclipse.core.runtime.jobs.Job;
+import org.eclipse.wst.common.componentcore.ComponentCore;
+import org.eclipse.wst.common.componentcore.internal.ModulecorePlugin;
+import org.eclipse.wst.common.componentcore.internal.impl.WTPModulesResourceFactory;
+import org.eclipse.wst.common.componentcore.internal.resources.VirtualComponent;
+import org.eclipse.wst.common.componentcore.resources.IVirtualComponent;
+import org.eclipse.wst.common.componentcore.resources.IVirtualReference;
+
+public class DependencyGraphImpl implements IDependencyGraph {
+
+ /**
+ * Don't read or write the graph without first obtaining the graphLock.
+ */
+ private Object graphLock = new Object();
+
+ /**
+ * If projects and and B both depend on C an entry in this graph would be {C ->
+ * {A, B} }
+ */
+ private Map<IProject, Set<IProject>> graph = null;
+
+ private long modStamp = 0;
+
+ private Map<String, Object> referenceOptions = new HashMap<String, Object>();
+
+
+ /**
+ * This is not public; only {@link IDependencyGraph#INSTANCE} should be
+ * used.
+ *
+ * @return
+ */
+ static IDependencyGraph getInstance() {
+ if (instance == null) {
+ instance = new DependencyGraphImpl();
+ instance.initGraph();
+ }
+ return instance;
+ }
+
+ private static DependencyGraphImpl instance = null;
+
+ private DependencyGraphImpl() {
+ }
+
+ public long getModStamp() {
+ synchronized (graphLock) {
+ return modStamp;
+ }
+ }
+
+ public Set<IProject> getReferencingComponents(IProject targetProject) {
+ waitForAllUpdates(null);
+ synchronized (graphLock) {
+ Set<IProject> set = graph.get(targetProject);
+ if (set == null) {
+ return Collections.EMPTY_SET;
+ } else {
+ for (Iterator<IProject> iterator = set.iterator(); iterator.hasNext();) {
+ IProject project = iterator.next();
+ if (!project.isAccessible()) {
+ iterator.remove();
+ }
+ }
+ Set<IProject> copy = new HashSet<IProject>();
+ copy.addAll(set);
+ return copy;
+ }
+ }
+ }
+
+ private class DependencyGraphResourceChangedListener implements IResourceChangeListener, IResourceDeltaVisitor {
+ // only registered for post change events
+ public void resourceChanged(IResourceChangeEvent event) {
+ try {
+ preUpdate();
+ event.getDelta().accept(this);
+ } catch (CoreException e) {
+ ModulecorePlugin.logError(e);
+ } finally {
+ postUpdate();
+ }
+ }
+
+ public boolean visit(IResourceDelta delta) throws CoreException {
+ IResource resource = delta.getResource();
+ switch (resource.getType()) {
+ case IResource.ROOT:
+ return true;
+ case IResource.PROJECT: {
+ int kind = delta.getKind();
+ if ((IResourceDelta.ADDED & kind) != 0) {
+ queueProjectAdded((IProject) resource);
+ return false;
+ } else if ((IResourceDelta.REMOVED & kind) != 0) {
+ queueProjectDeleted((IProject) resource);
+ return false;
+ } else if ((IResourceDelta.CHANGED & kind) != 0) {
+ int flags = delta.getFlags();
+ if ((IResourceDelta.OPEN & flags) != 0) {
+ boolean isOpen = ((IProject) resource).isOpen();
+ if (isOpen) {
+ queueProjectAdded((IProject) resource);
+ } else {
+ queueProjectDeleted((IProject) resource);
+ }
+ return false;
+ }
+ return true;
+ }
+ return false;
+ }
+ case IResource.FOLDER:
+ if (resource.getName().equals(".settings")) {
+ return true;
+ }
+ return false;
+ case IResource.FILE:
+ String name = resource.getName();
+ if (name.equals(WTPModulesResourceFactory.WTP_MODULES_SHORT_NAME)) {
+ update(resource.getProject());
+ }
+ default:
+ return false;
+ }
+ }
+ };
+
+ private DependencyGraphResourceChangedListener listener = null;
+
+ /**
+ * The graph is built lazily once. Afterwards, the graph is updated as
+ * necessary.
+ */
+ private void initGraph() {
+ synchronized (graphLock) {
+ referenceOptions.put("GET_JAVA_REFS", Boolean.FALSE);
+ try {
+ preUpdate();
+ graph = new HashMap<IProject, Set<IProject>>();
+ listener = new DependencyGraphResourceChangedListener();
+ ResourcesPlugin.getWorkspace().addResourceChangeListener(listener, IResourceChangeEvent.POST_CHANGE);
+ initAll();
+ } finally {
+ postUpdate();
+ }
+ }
+ }
+
+ private void initAll(){
+ synchronized (graphLock) {
+ try{
+ preUpdate();
+ IProject[] allProjects = ResourcesPlugin.getWorkspace().getRoot().getProjects();
+ for (IProject sourceProject : allProjects) {
+ queueProjectAdded(sourceProject);
+ }
+ } finally{
+ postUpdate();
+ }
+
+ }
+ }
+
+ private void removeAllReferences(IProject project) {
+ synchronized (graphLock) {
+ graph.remove(project);
+ for (Iterator<Set<IProject>> iterator = graph.values().iterator(); iterator.hasNext();) {
+ iterator.next().remove(project);
+ }
+ modStamp++;
+ }
+ }
+
+ private void removeReference(IProject sourceProject, IProject targetProject) {
+ synchronized (graphLock) {
+ Set<IProject> referencingProjects = graph.get(targetProject);
+ if (referencingProjects != null) {
+ referencingProjects.remove(sourceProject);
+ }
+ modStamp++;
+ }
+ }
+
+ private void addReference(IProject sourceProject, IProject targetProject) {
+ synchronized (graphLock) {
+ Set<IProject> referencingProjects = graph.get(targetProject);
+ if (referencingProjects == null) {
+ referencingProjects = new HashSet<IProject>();
+ graph.put(targetProject, referencingProjects);
+ }
+ referencingProjects.add(sourceProject);
+ modStamp++;
+ }
+ }
+
+ public static final Object GRAPH_UPDATE_JOB_FAMILY = new Object();
+
+ private static final int JOB_DELAY = 100;
+
+ private final GraphUpdateJob graphUpdateJob = new GraphUpdateJob();
+ private final Object jobLock = new Object();
+
+ private class GraphUpdateJob extends Job {
+
+ public GraphUpdateJob() {
+ super("Graph Update Job");
+ setSystem(true);
+ //[Bug 238685] need to lock on workspace to avoid dead lock
+ setRule(ResourcesPlugin.getWorkspace().getRoot());
+ }
+
+ public boolean belongsTo(Object family) {
+ if (family == GRAPH_UPDATE_JOB_FAMILY) {
+ return true;
+ }
+ return super.belongsTo(family);
+ }
+
+ // We use the listener list as a thread safe queue.
+ private class Queue extends ListenerList {
+ public synchronized Object[] getListeners() {
+ Object[] data = super.getListeners();
+ clear();
+ return data;
+ }
+
+ public synchronized boolean isEmpty() {
+ return super.isEmpty();
+ }
+ };
+
+ private Queue projectsAdded = new Queue();
+
+ private Queue projectsRemoved = new Queue();
+
+ private Queue projectsUpdated = new Queue();
+
+ public void queueProjectAdded(IProject project) {
+ synchronized (graphLock) {
+ modStamp++;
+ }
+ projectsAdded.add(project);
+ }
+
+ public void queueProjectDeleted(IProject project) {
+ synchronized (graphLock) {
+ modStamp++;
+ }
+ projectsRemoved.add(project);
+ }
+
+ public void queueProjectUpdated(IProject project) {
+ synchronized (graphLock) {
+ modStamp++;
+ }
+ projectsUpdated.add(project);
+ }
+
+ @Override
+ public boolean shouldSchedule() {
+ boolean isEmpty = projectsAdded.isEmpty() && projectsRemoved.isEmpty() && projectsUpdated.isEmpty();
+ return !isEmpty;
+ }
+
+ protected IStatus run(IProgressMonitor monitor) {
+ final Object[] removed = projectsRemoved.getListeners();
+ final Object[] updated = projectsUpdated.getListeners();
+ final Object[] added = projectsAdded.getListeners();
+ if (removed.length == 0 && updated.length == 0 && added.length == 0) {
+ return Status.OK_STATUS;
+ }
+ synchronized (graphLock) {
+ modStamp++;
+ }
+ SafeRunner.run(new ISafeRunnable() {
+ public void handleException(Throwable e) {
+ ModulecorePlugin.logError(e);
+ }
+
+ public void run() throws Exception {
+ // this is the simple case; just remove them all
+ synchronized (graphLock) {
+ for (Object o : removed) {
+ IProject project = (IProject) o;
+ removeAllReferences(project);
+ }
+ }
+ // get the updated queue in case there are any adds
+ // if there are any added projects, then unfortunately the
+ // entire workspace needs to be processed
+ if (added.length > 0) {
+ IProject[] allProjects = ResourcesPlugin.getWorkspace().getRoot().getProjects();
+ for (IProject sourceProject : allProjects) {
+ IVirtualComponent component = ComponentCore.createComponent(sourceProject);
+ if (component != null) {
+ IVirtualReference[] references = null;
+ if(referenceOptions != null && component instanceof VirtualComponent) {
+ references = ((VirtualComponent)component).getReferences(referenceOptions);
+ } else {
+ references = component.getReferences();
+ }
+ for (IVirtualReference ref : references) {
+ IVirtualComponent targetComponent = ref.getReferencedComponent();
+ if (targetComponent != null) {
+ IProject targetProject = targetComponent.getProject();
+ if (targetProject != null && !targetProject.equals(sourceProject)) {
+ addReference(sourceProject, targetProject);
+ }
+ }
+ }
+ }
+ }
+ } else if (updated.length > 0) {
+ IProject[] allProjects = ResourcesPlugin.getWorkspace().getRoot().getProjects();
+ Set<IProject> validRefs = new HashSet<IProject>();
+ for (Object o : updated) {
+ IProject sourceProject = (IProject) o;
+ IVirtualComponent component = ComponentCore.createComponent(sourceProject);
+ if (component != null) {
+ validRefs.clear();
+ IVirtualReference[] references = null;
+ if(referenceOptions != null && component instanceof VirtualComponent) {
+ references = ((VirtualComponent)component).getReferences(referenceOptions);
+ } else {
+ references = component.getReferences();
+ }
+ for (IVirtualReference ref : references) {
+ IVirtualComponent targetComponent = ref.getReferencedComponent();
+ if (targetComponent != null) {
+ IProject targetProject = targetComponent.getProject();
+ if (targetProject != null && !targetProject.equals(sourceProject)) {
+ validRefs.add(targetProject);
+ }
+ }
+ }
+ synchronized (graphLock) {
+ for (IProject targetProject : allProjects) {
+ // if the reference was identified
+ // above, be sure to add it
+ // otherwise, remove it
+ if (validRefs.remove(targetProject)) {
+ addReference(sourceProject, targetProject);
+ } else {
+ removeReference(sourceProject, targetProject);
+ }
+ }
+ }
+ } else {
+ // if this project is not a component, then it
+ // should be completely removed.
+ removeAllReferences(sourceProject);
+ }
+ }
+ }
+ boolean scheduleUpdate = false;
+ synchronized (graphLock) {
+ if(referenceOptions != null){
+ scheduleUpdate = true;
+ referenceOptions = null;
+ }
+ }
+ if(scheduleUpdate){
+ initAll();
+ }
+
+ }
+ });
+ // System.err.println(IDependencyGraph.INSTANCE);
+ return Status.OK_STATUS;
+ }
+ };
+
+ /**
+ * @deprecated use {@link #update(IProject, int)}
+ */
+ public void queueProjectAdded(IProject project) {
+ update(project, IDependencyGraph.ADDED);
+ }
+
+ /**
+ * @deprecated use {@link #update(IProject, int)}
+ */
+ public void queueProjectDeleted(IProject project) {
+ update(project, IDependencyGraph.REMOVED);
+ }
+
+ /**
+ * @deprecated use {@link #update(IProject, int)}
+ */
+ public void update(IProject project) {
+ update(project, IDependencyGraph.MODIFIED);
+ }
+
+ public void update(IProject project, final int updateType){
+ switch(updateType){
+ case IDependencyGraph.MODIFIED:
+ graphUpdateJob.queueProjectUpdated(project);
+ break;
+ case IDependencyGraph.ADDED:
+ graphUpdateJob.queueProjectAdded(project);
+ break;
+ case IDependencyGraph.REMOVED:
+ graphUpdateJob.queueProjectDeleted(project);
+ break;
+ }
+ synchronized (jobLock) {
+ if (pauseCount > 0) {
+ return;
+ }
+ }
+ graphUpdateJob.schedule(JOB_DELAY);
+ }
+
+
+
+ private int pauseCount = 0;
+
+ /**
+ * Pauses updates; any caller of this method must ensure through a
+ * try/finally block that resumeUpdates is subsequently called.
+ */
+ public void preUpdate() {
+ synchronized (jobLock) {
+ pauseCount++;
+ }
+ }
+
+ public void postUpdate() {
+ synchronized (jobLock) {
+ if (pauseCount > 0) {
+ pauseCount--;
+ }
+ if (pauseCount > 0) {
+ return;
+ }
+ }
+ graphUpdateJob.schedule(JOB_DELAY);
+ }
+
+ /**
+ * Blocks until the graph is finished updating
+ */
+ public void waitForAllUpdates(IProgressMonitor monitor) {
+ Thread graphUpdateThread = graphUpdateJob.getThread();
+ if(graphUpdateThread != null && graphUpdateThread != Thread.currentThread()) {
+ try {
+ graphUpdateJob.join();
+ } catch (InterruptedException e) {
+ ModulecorePlugin.logError(e);
+ }
+ }
+
+ if(graphUpdateJob.shouldSchedule()){
+ graphUpdateJob.run(monitor);
+ }
+ }
+
+ public String toString() {
+ synchronized (graphLock) {
+ StringBuffer buff = new StringBuffer("Dependency Graph:\n{\n");
+ for (Iterator<Map.Entry<IProject, Set<IProject>>> iterator = graph.entrySet().iterator(); iterator.hasNext();) {
+ Map.Entry<IProject, Set<IProject>> entry = iterator.next();
+ buff.append(" " + entry.getKey().getName() + " -> {");
+ for (Iterator<IProject> mappedProjects = entry.getValue().iterator(); mappedProjects.hasNext();) {
+ buff.append(mappedProjects.next().getName());
+ if (mappedProjects.hasNext()) {
+ buff.append(", ");
+ }
+ }
+ buff.append("}\n");
+ }
+ buff.append("}");
+ return buff.toString();
+ }
+
+ }
+
+}
diff --git a/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/builder/DependencyGraphManager.java b/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/builder/DependencyGraphManager.java
index 3d95164..0b275c8 100644
--- a/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/builder/DependencyGraphManager.java
+++ b/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/builder/DependencyGraphManager.java
@@ -10,264 +10,46 @@
*******************************************************************************/
package org.eclipse.wst.common.componentcore.internal.builder;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-
-import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.Path;
-import org.eclipse.jem.util.emf.workbench.ProjectUtilities;
-import org.eclipse.jem.util.logger.proxy.Logger;
-import org.eclipse.wst.common.componentcore.ComponentCore;
-import org.eclipse.wst.common.componentcore.internal.resources.VirtualArchiveComponent;
-import org.eclipse.wst.common.componentcore.internal.util.ComponentUtilities;
-import org.eclipse.wst.common.componentcore.internal.util.IModuleConstants;
-import org.eclipse.wst.common.componentcore.resources.IVirtualComponent;
-import org.eclipse.wst.common.componentcore.resources.IVirtualReference;
+/**
+ * @deprecated use {@link IDependencyGraph}
+ */
public class DependencyGraphManager {
-
- private class DependencyReference {
-
- public IProject componentProject;
- public IProject targetProject;
-
- public DependencyReference(IProject target, IProject component) {
- super();
- componentProject=component;
- targetProject=target;
- }
- }
private static DependencyGraphManager INSTANCE = null;
- private static final String MANIFEST_URI = "META-INF/MANIFEST.MF";
- private HashMap wtpModuleTimeStamps = null;
- private HashMap manifestTimeStamps = null;
- private long modStamp = System.currentTimeMillis();
-
+
private DependencyGraphManager() {
super();
}
-
+
public synchronized static final DependencyGraphManager getInstance() {
if (INSTANCE == null)
INSTANCE = new DependencyGraphManager();
return INSTANCE;
}
-
+
public void construct(IProject project) {
- if (project!=null && project.isAccessible() && getComponentFile(project) !=null) //$NON-NLS-1$
- constructIfNecessary();
- }
-
- private IResource getComponentFile(IProject project) {
- IResource componentFile = project.findMember(IModuleConstants.COMPONENT_FILE_PATH);
- if (componentFile == null)
- componentFile = project.findMember(IModuleConstants.R1_MODULE_META_FILE_PATH);
- return componentFile;
-
- }
-
- private void constructIfNecessary() {
- if (metadataChanged()) {
- buildDependencyGraph();
- }
- }
-
- private boolean metadataChanged() {
- return moduleTimeStampsChanged() || manifestTimeStampsChanged();
- }
-
- private boolean manifestTimeStampsChanged() {
- HashMap workspaceTimeStamps = collectManifestTimeStamps();
- if (timestampsMatch(getManifestTimeStamps(),workspaceTimeStamps))
- return false;
- return true;
- }
-
- private HashMap getManifestTimeStamps() {
- if (manifestTimeStamps == null)
- manifestTimeStamps = new HashMap();
- return manifestTimeStamps;
- }
-
- private HashMap collectManifestTimeStamps() {
- HashMap timeStamps = new HashMap();
- IProject[] projects = ProjectUtilities.getAllProjects();
- for (int i=0; i<projects.length; i++) {
- IFile manifestFile = null;
- if (projects[i]==null || !projects[i].isAccessible())
- continue;
- manifestFile = getTimeStampFile(projects[i]);
- if (manifestFile != null && manifestFile.exists() && ComponentCore.createComponent(projects[i]) != null) {
- Long currentTimeStamp = new Long(manifestFile.getModificationStamp());
- timeStamps.put(projects[i],currentTimeStamp);
- }
- }
- return timeStamps;
- }
-
- /**
- * This returns the file used for time stamp purposes. Typically this will be the manifest file.
- * @param p
- * @return
- */
- private IFile getTimeStampFile(IProject p) {
- IVirtualComponent component = ComponentCore.createComponent(p);
- if(null == component){
- return null;
- }
- if(component.isBinary()){
- return ((VirtualArchiveComponent)component).getUnderlyingWorkbenchFile();
- } else {
- try {
- IFile file = ComponentUtilities.findFile(component, new Path(MANIFEST_URI));
- if (file != null)
- return file;
- } catch (CoreException ce) {
- Logger.getLogger().log(ce);
- }
- }
- return null;
- }
-
- private boolean moduleTimeStampsChanged() {
- HashMap workspaceTimeStamps = collectModuleTimeStamps();
- if (timestampsMatch(getWtpModuleTimeStamps(),workspaceTimeStamps))
- return false;
- return true;
- }
-
- private boolean timestampsMatch(HashMap savedTimeStamps, HashMap workspaceTimeStamps) {
- return savedTimeStamps.equals(workspaceTimeStamps);
-
- }
-
- private HashMap collectModuleTimeStamps() {
- HashMap timeStamps = new HashMap();
- IProject[] projects = ProjectUtilities.getAllProjects();
- for (int i=0; i<projects.length; i++) {
- if (projects[i]==null || !projects[i].isAccessible())
- continue;
- IResource wtpModulesFile = getComponentFile(projects[i]); //$NON-NLS-1$
- if (wtpModulesFile != null && wtpModulesFile.exists() && ComponentCore.createComponent(projects[i]) != null) {
- Long currentTimeStamp = new Long(wtpModulesFile.getModificationStamp());
- timeStamps.put(projects[i],currentTimeStamp);
- }
- }
- return timeStamps;
- }
-
- private void buildDependencyGraph() {
- // Process and collect dependency references to add
- List referencesToAdd = new ArrayList();
- List componentProjects = new ArrayList();
- IProject[] projects = ProjectUtilities.getAllProjects();
-
- for (int k=0; k<projects.length; k++) {
- if (!projects[k].isAccessible() || getComponentFile(projects[k])==null)
- continue;
- IVirtualComponent component= ComponentCore.createComponent(projects[k]);
- if (component == null) continue;
- referencesToAdd.addAll(getDependencyReferences(component));
- componentProjects.add(projects[k]);
- }
-
- //Update the actual graph/timestamps and block other threads here
- synchronized (this) {
- cleanDependencyGraph();
- for (Iterator iter = componentProjects.iterator(); iter.hasNext();) {
- IProject proj = (IProject) iter.next();
- //For All projects (regardless if involved in references), update timestamps
- addTimeStamp(proj);
- }
- for (int i=0; i<referencesToAdd.size(); i++) {
- DependencyReference ref = (DependencyReference) referencesToAdd.get(i);
- if (ref.targetProject == null || ref.componentProject == null || ref.targetProject.equals(ref.componentProject))
- continue;
- DependencyGraph.getInstance().addReference(ref.targetProject,ref.componentProject);
- }
- }
- }
-
- private List getDependencyReferences(IVirtualComponent component) {
- List refs = new ArrayList();
- IProject componentProject = component.getProject();
- IVirtualReference[] depRefs = component.getReferences();
- for(int i = 0; i<depRefs.length; i++){
- IVirtualComponent targetComponent = depRefs[i].getReferencedComponent();
- if (targetComponent!=null) {
- IProject targetProject = targetComponent.getProject();
- refs.add(new DependencyReference(targetProject,componentProject));
- }
- }
- return refs;
- }
-
- private boolean addTimeStamp(IProject project) {
- // Get the .component file for the given project
- IResource wtpModulesFile = getComponentFile(project);
- if (wtpModulesFile==null)
- return false;
- Long currentTimeStamp = new Long(wtpModulesFile.getModificationStamp());
- getWtpModuleTimeStamps().put(project,currentTimeStamp);
- // Get the MANIFEST file for the given project
- IResource manifestFile = getTimeStampFile(project);
-
- if (manifestFile==null)
- return false;
- currentTimeStamp = new Long(manifestFile.getModificationStamp());
- getManifestTimeStamps().put(project,currentTimeStamp);
- return true;
- }
-
- private void cleanDependencyGraph() {
- DependencyGraph.getInstance().clear();
- getWtpModuleTimeStamps().clear();
- getManifestTimeStamps().clear();
- setModStamp(System.currentTimeMillis());
+ // do nothing
}
/**
- * Lazy initialization and return of the key valued pair of projects and wtp modules file
- * timestamps.
- *
- * @return HashMap of projects to .component file stamps
- */
- private HashMap getWtpModuleTimeStamps() {
- if (wtpModuleTimeStamps == null)
- wtpModuleTimeStamps = new HashMap();
- return wtpModuleTimeStamps;
- }
-
- /**
- * Return the dependency graph which was initialized if need be in the
+ * Return the dependency graph which was initialized if need be in the
* singleton manager method.
- */
+ */
public DependencyGraph getDependencyGraph() {
- constructIfNecessary();
return DependencyGraph.getInstance();
}
-
+
public void forceRefresh() {
- buildDependencyGraph();
+ // do nothing
}
-
public long getModStamp() {
- return modStamp;
- }
-
-
- private void setModStamp(long modStamp) {
- this.modStamp = modStamp;
+ return IDependencyGraph.INSTANCE.getModStamp();
}
public boolean checkIfStillValid(long timeStamp) {
- return (getModStamp() == timeStamp && !metadataChanged());
+ return IDependencyGraph.INSTANCE.getModStamp() == timeStamp;
}
}
diff --git a/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/builder/IDependencyGraph.java b/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/builder/IDependencyGraph.java
new file mode 100644
index 0000000..aa4f58c
--- /dev/null
+++ b/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/builder/IDependencyGraph.java
@@ -0,0 +1,132 @@
+package org.eclipse.wst.common.componentcore.internal.builder;
+
+import java.util.Set;
+
+import org.eclipse.core.resources.IProject;
+import org.eclipse.core.resources.IResourceDeltaVisitor;
+import org.eclipse.wst.common.componentcore.resources.IVirtualComponent;
+
+/**
+ * This graph provides a backward mapping of project component dependencies. It
+ * provides a project limited inverse of
+ * {@link IVirtualComponent#getReferences()}.
+ *
+ * For example:
+ * <ul>
+ * <li>if the IVirtualComponent for project A has a dependency on the
+ * IVirtualComponent for project B, then calling
+ * {@link #getReferencingComponents(IProject)} on project B will return project
+ * A. </li>
+ * <li>if the IVirtualComponent for project A has a dependency on on the
+ * IVirtualComponent for a jar in project B, then calling
+ * {@link #getReferencingComponents(IProject)} for project B will return project
+ * A. This is true even if project B is not defined as an IVirtualComponent.
+ * </li>
+ * </ul>
+ *
+ * Any call to {@link #getReferencingComponents(IProject)} is always expected to
+ * be up to date. The only case where a client may need to force an update is if
+ * that client is also defining dynamic IVirtualComponent dependencies, i.e. the
+ * client is using the org.eclipse.wst.common.modulecore.componentimpl extension
+ * point. Only in this case should a client be calling any of
+ * {@link #preUpdate()}, {@link #postUpdate()}, or {@link #update(IProject)}
+ *
+ */
+public interface IDependencyGraph {
+
+ /**
+ * Flag used by {@link #update(IProject, int)} to specify that something has
+ * modified in a project which has changed the component dependencies.
+ */
+ public static final int MODIFIED = 0;
+
+ /**
+ * Flag used by {@link #update(IProject, int)} to specify a project has been
+ * added or opened. This flag should be used as sparingly as possible
+ * because there are performance implications.
+ */
+ public static final int ADDED = 1;
+
+ /**
+ * Flag used by {@link #update(IProject, int)} to specify a project has been
+ * removed or closed.
+ */
+ public static final int REMOVED = 2;
+
+ /**
+ * The static instance of this graph
+ */
+ public static IDependencyGraph INSTANCE = DependencyGraphImpl.getInstance();
+
+ /**
+ * Returns the set of component projects referencing the specified target
+ * project.
+ *
+ * @param targetProject
+ * @return
+ */
+ public Set<IProject> getReferencingComponents(IProject targetProject);
+
+ /**
+ * Returns a modification stamp. This modification stamp will be different
+ * if the project dependencies ever change.
+ */
+ public long getModStamp();
+
+ /**
+ * WARNING: this should only be called by implementors of the
+ * org.eclipse.wst.common.modulecore.componentimpl extension point.
+ *
+ * This method is part of the update API.
+ *
+ * @see {@link #update(IProject)}
+ */
+ public void preUpdate();
+
+ /**
+ * WARNING: this should only be called by implementors of the
+ * org.eclipse.wst.common.modulecore.componentimpl extension point.
+ *
+ * This method is part of the update API.
+ *
+ * @see {@link #update(IProject)}
+ */
+ public void postUpdate();
+
+ /**
+ * @deprecated use {@link #update(IProject, int) using the #MODIFIED flag.
+ */
+ public void update(IProject sourceProject);
+
+ /**
+ * WARNING: this should only be called by implementors of the
+ * org.eclipse.wst.common.modulecore.componentimpl extension point.
+ *
+ * This method must be called when a resource change is detected which will
+ * affect how dependencies behave. For example, the core IVirtualComponent
+ * framework updates when changes are made to the
+ * .settings/org.eclipse.wst.common.component file changes, and also when
+ * IProjects are added or removed from the workspace. In the case for J2EE,
+ * this occurs when changes are made to the META-INF/MANIFEST.MF file. In
+ * general a call to update should only be made from a fast
+ * {@link IResourceDeltaVisitor}.
+ *
+ * In order to improve efficiency and avoid unnecessary update processing,
+ * it is necessary to always proceed calls to update() with a call to
+ * preUpdate() and follow with a call to postUpdate() using a try finally
+ * block as follows: <code>
+ * try {
+ * preUpdate();
+ * // perform 0 or more update() calls here
+ * } finally {
+ * IDependencyGraph.INSTANCE.postUpdate();
+ * }
+ * </code>
+ *
+ * Valid updateType flags are {@link #MODIFIED}, {@link #ADDED}, and
+ * {@link #REMOVED}
+ *
+ */
+ public void update(IProject sourceProject, int updateType);
+
+}
diff --git a/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/impl/ArtifactEditModelFactory.java b/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/impl/ArtifactEditModelFactory.java
index aad88e4..17c57ea 100644
--- a/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/impl/ArtifactEditModelFactory.java
+++ b/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/impl/ArtifactEditModelFactory.java
@@ -29,15 +29,21 @@
public static final String PARAM_MODULE_URI = "MODULE_URI"; //$NON-NLS-1$
+ public static final String PARAM_ROOT_URI = "ROOT_URI"; //$NON-NLS-1$
+
+ public static final String PARAM_ROOT_CONTENT_TYPE = "ROOT_CONTENT_TYPE"; //$NON-NLS-1$
+
/* (non-Javadoc)
* @see org.eclipse.wst.common.internal.emfworkbench.integration.EditModelFactory#createEditModelForRead(java.lang.String, org.eclipse.wst.common.internal.emfworkbench.EMFWorkbenchContext, java.util.Map)
*/
public EditModel createEditModelForRead(String editModelID, EMFWorkbenchContext context, Map params) {
URI moduleURI = (URI) ((params != null) ? params.get(PARAM_MODULE_URI) : null);
+ URI rootURI = (URI) ((params != null) ? params.get(PARAM_ROOT_URI) : null);
+ String rootContentType = (String) ((params != null) ? params.get(PARAM_ROOT_CONTENT_TYPE) : null);
if(moduleURI == null)
throw new IllegalStateException("A Module URI must be provided");
- return new ArtifactEditModel(editModelID, context, true, moduleURI);
+ return new ArtifactEditModel(editModelID, context, true, moduleURI, rootURI, rootContentType);
}
/* (non-Javadoc)
@@ -45,9 +51,11 @@
*/
public EditModel createEditModelForWrite(String editModelID, EMFWorkbenchContext context, Map params) {
URI moduleURI = (URI) ((params != null) ? params.get(PARAM_MODULE_URI) : null);
+ URI rootURI = (URI) ((params != null) ? params.get(PARAM_ROOT_URI) : null);
+ String rootContentType = (String) ((params != null) ? params.get(PARAM_ROOT_CONTENT_TYPE) : null);
if(moduleURI == null)
throw new IllegalStateException("A Module URI must be provided");
- return new ArtifactEditModel(editModelID, context, false,false, moduleURI);
+ return new ArtifactEditModel(editModelID, context, false, moduleURI, rootURI, rootContentType);
}
/* (non-Javadoc)
diff --git a/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/impl/ComponentCoreURIConverter.java b/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/impl/ComponentCoreURIConverter.java
index f8582be..a2722b6 100644
--- a/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/impl/ComponentCoreURIConverter.java
+++ b/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/impl/ComponentCoreURIConverter.java
@@ -1,5 +1,5 @@
/*******************************************************************************
- * Copyright (c) 2003, 2005 IBM Corporation and others.
+ * Copyright (c) 2003, 2007 IBM Corporation 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
@@ -17,16 +17,15 @@
import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.Path;
import org.eclipse.emf.common.util.URI;
+import org.eclipse.emf.ecore.resource.impl.URIMappingRegistryImpl;
import org.eclipse.jem.util.emf.workbench.ResourceSetWorkbenchSynchronizer;
import org.eclipse.jem.util.emf.workbench.WorkbenchResourceHelperBase;
import org.eclipse.wst.common.componentcore.ComponentCore;
-import org.eclipse.wst.common.componentcore.internal.StructureEdit;
import org.eclipse.wst.common.componentcore.resources.IVirtualComponent;
import org.eclipse.wst.common.componentcore.resources.IVirtualFile;
import org.eclipse.wst.common.componentcore.resources.IVirtualFolder;
@@ -41,7 +40,7 @@
public class ComponentCoreURIConverter extends CompatibilityWorkbenchURIConverterImpl {
private IProject containingProject;
- private IFolder archiveRoot;
+// private IFolder archiveRoot;
/**
*
*/
@@ -98,7 +97,7 @@
private URI newPlatformURI(URI aNewURI) {
try {
- String componentName = StructureEdit.getDeployedName(aNewURI);
+// String componentName = StructureEdit.getDeployedName(aNewURI);
IVirtualComponent component = ComponentCore.createComponent(containingProject);
URI deployPathSegment = ModuleURIUtil.trimToDeployPathSegment(aNewURI);
@@ -161,5 +160,36 @@
return containingProject;
}
+ @Override
+ protected URIMap getInternalURIMap() {
+
+ if (uriMap == null)
+ {
+ URIMappingRegistryImpl mappingRegistryImpl =
+ new URIMappingRegistryImpl()
+ {
+ private static final long serialVersionUID = 1L;
+
+ @Override
+ protected URI delegatedGetURI(URI uri)
+ {
+ if (ModuleURIUtil.hasContentTypeName(uri))
+ return newPlatformURI(uri);
+ return URIMappingRegistryImpl.INSTANCE.getURI(uri);
+ }
+ };
+
+ uriMap = (URIMap)mappingRegistryImpl.map();
+ }
+
+ URIMap uriConverterImplURIMap = null;
+ if (uriMap instanceof URIMap)
+ {
+ uriConverterImplURIMap = (URIMap)uriMap;
+ }
+ return uriConverterImplURIMap;
+
+ }
+
}
diff --git a/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/impl/IResourceFactoryExtPtConstants.java b/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/impl/IResourceFactoryExtPtConstants.java
index 8d63f9c..c6e1e45 100644
--- a/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/impl/IResourceFactoryExtPtConstants.java
+++ b/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/impl/IResourceFactoryExtPtConstants.java
@@ -1,13 +1,13 @@
/*******************************************************************************
- * Copyright (c) 2003, 2004 IBM Corporation and others.
+ * Copyright (c) 2003, 2007 IBM Corporation 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:
* IBM Corporation - initial API and implementation
- *******************************************************************************/
+ *******************************************************************************/
package org.eclipse.wst.common.componentcore.internal.impl;
public interface IResourceFactoryExtPtConstants {
@@ -20,6 +20,14 @@
String ATT_CLASS = "class"; //$NON-NLS-1$
String ATT_SHORT_SEGMENT = "shortSegment"; //$NON-NLS-1$
+
+ String TAG_CONTENTTYPE = "contentTypeBinding"; //$NON-NLS-1$
+
+ String ATT_CONTENTTYPEID = "contentTypeId"; //$NON-NLS-1$
+
+ String ATT_ISDEFAULT = "isDefault"; //$NON-NLS-1$
+
+ String ATT_OVERRIDES_FACTORY ="overridesFactoryClass"; //$NON-NLS-1$
}
diff --git a/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/impl/ModuleURIUtil.java b/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/impl/ModuleURIUtil.java
index 71b0576..170c513 100644
--- a/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/impl/ModuleURIUtil.java
+++ b/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/impl/ModuleURIUtil.java
@@ -1,5 +1,5 @@
/*******************************************************************************
- * Copyright (c) 2003, 2005 IBM Corporation and others.
+ * Copyright (c) 2003, 2007 IBM Corporation 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
@@ -12,7 +12,9 @@
import org.eclipse.core.resources.IProject;
import org.eclipse.core.runtime.IPath;
+import org.eclipse.core.runtime.Platform;
import org.eclipse.emf.common.util.URI;
+import org.eclipse.jem.util.emf.workbench.WorkbenchResourceHelperBase;
import org.eclipse.wst.common.componentcore.UnresolveableURIException;
import org.eclipse.wst.common.componentcore.internal.StructureEdit;
import org.eclipse.wst.common.componentcore.internal.WorkbenchComponent;
@@ -34,6 +36,7 @@
public static final int SUB_PROTOCOL_INDX = 0;
public static final int PROJECT_NAME_INDX = 1;
public static final int MODULE_NAME_INDX = 2;
+ public static final int CONTENT_TYPE_INDX = 3;
}
@@ -70,6 +73,12 @@
}
return true;
}
+ public static boolean isValidFullyQualifiedModuleURI(URI aModuleURI) {
+ if (aModuleURI.segmentCount() < 3) {
+ return false;
+ }
+ return true;
+ }
public static boolean ensureValidFullyQualifiedPlatformURI(URI aFullyQualifiedResourceURI, boolean toThrowExceptionIfNecessary) throws UnresolveableURIException {
if (aFullyQualifiedResourceURI.segmentCount() < 2 || !PLATFORM_SCHEME.equals(aFullyQualifiedResourceURI.scheme()) || !RESOURCE_PROTOCOL.equals(aFullyQualifiedResourceURI.segment(0))) {
@@ -86,7 +95,8 @@
public static URI trimModuleResourcePathToModuleURI(URI aModuleResourcePath) throws UnresolveableURIException {
ensureValidFullyQualifiedModuleURI(aModuleResourcePath);
- return aModuleResourcePath.trimSegments(aModuleResourcePath.segmentCount() - 3);
+ int trimIndex = (hasContentTypeName(aModuleResourcePath) ? 4 : 3);
+ return aModuleResourcePath.trimSegments(aModuleResourcePath.segmentCount() - trimIndex);
}
public static URI trimWorkspacePathToProjectRelativeURI(URI aFullyQualifiedResourceURI) throws UnresolveableURIException {
@@ -129,8 +139,9 @@
public static URI trimToDeployPathSegment(URI aFullyQualifiedModuleResourcePath) {
int segmentCount = aFullyQualifiedModuleResourcePath.segmentCount();
URI uri;
- if(segmentCount > 4){
- uri = aFullyQualifiedModuleResourcePath.deresolve(aFullyQualifiedModuleResourcePath.trimSegments(segmentCount - 4));
+ int trimIndex = (hasContentTypeName(aFullyQualifiedModuleResourcePath) ? 5 : 4);
+ if(segmentCount > trimIndex){
+ uri = aFullyQualifiedModuleResourcePath.deresolve(aFullyQualifiedModuleResourcePath.trimSegments(segmentCount - trimIndex), false,false,true);
} else {
uri = URI.createURI(aFullyQualifiedModuleResourcePath.segment(segmentCount-1));
}
@@ -160,6 +171,9 @@
public static URI fullyQualifyURI(IProject aProject) {
return URI.createURI(RESOURCE_URI_PROTOCOL + aProject.getName() + IPath.SEPARATOR + aProject.getName());
}
+ public static URI fullyQualifyURI(IProject aProject, String contentTypeDescriber) {
+ return URI.createURI(RESOURCE_URI_PROTOCOL + aProject.getName() + IPath.SEPARATOR + aProject.getName() + IPath.SEPARATOR + contentTypeDescriber);
+ }
public static URI archiveComponentfullyQualifyURI(String aComponentName) {
return URI.createURI(ARCHIVE_URI_PROTOCOL + aComponentName);
@@ -188,4 +202,25 @@
else
return "[" + aComponent.getProject().getFullPath() + "]:" + aComponent.getProject().getName();
}
+
+ public static String getContentTypeName(URI uri) {
+
+ if (WorkbenchResourceHelperBase.isPlatformResourceURI(uri) || !isValidFullyQualifiedModuleURI(uri))
+ return null;
+ String contentTypeIdentifier = (uri.segmentCount() > 3 ? uri.segment(ModuleURI.CONTENT_TYPE_INDX) : null);
+ if (contentTypeIdentifier != null && Platform.getContentTypeManager().getContentType(uri.segment(ModuleURI.CONTENT_TYPE_INDX)) != null)
+ return contentTypeIdentifier;
+ else
+ return null;
+ }
+ public static boolean hasContentTypeName(URI uri) {
+
+ if (WorkbenchResourceHelperBase.isPlatformResourceURI(uri))
+ return false;
+ String contentTypeIdentifier = (uri.segmentCount() > 3 ? uri.segment(ModuleURI.CONTENT_TYPE_INDX) : null);
+ if (contentTypeIdentifier != null && Platform.getContentTypeManager().getContentType(uri.segment(ModuleURI.CONTENT_TYPE_INDX)) != null)
+ return true;
+ else
+ return false;
+ }
}
diff --git a/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/impl/PlatformURLModuleConnection.java b/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/impl/PlatformURLModuleConnection.java
index 9b95e51..6033687 100644
--- a/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/impl/PlatformURLModuleConnection.java
+++ b/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/impl/PlatformURLModuleConnection.java
@@ -1,5 +1,5 @@
/*******************************************************************************
- * Copyright (c) 2005 IBM Corporation and others.
+ * Copyright (c) 2005, 2007 IBM Corporation 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
@@ -27,7 +27,6 @@
import org.eclipse.core.runtime.Path;
import org.eclipse.emf.common.util.URI;
import org.eclipse.wst.common.componentcore.ComponentCore;
-import org.eclipse.wst.common.componentcore.UnresolveableURIException;
import org.eclipse.wst.common.componentcore.internal.StructureEdit;
import org.eclipse.wst.common.componentcore.resources.IVirtualComponent;
import org.eclipse.wst.common.componentcore.resources.IVirtualFile;
@@ -57,25 +56,27 @@
public static URI resolve(URI aModuleResourceRuntimePath) throws IOException {
try {
IProject componentProject = StructureEdit.getContainingProject(aModuleResourceRuntimePath);
- String componentName = ModuleURIUtil.getDeployedName(aModuleResourceRuntimePath);
+ //String componentName = ModuleURIUtil.getDeployedName(aModuleResourceRuntimePath);
URI runtimeURI = ModuleURIUtil.trimToDeployPathSegment(aModuleResourceRuntimePath);
IPath runtimePath = new Path(runtimeURI.path());
IVirtualComponent component = ComponentCore.createComponent(componentProject);
//IVirtualFile vFile = component.getFile(runtimePath);
IVirtualFolder rootFolder = component.getRootFolder();
+ int matchingSegs = runtimePath.matchingFirstSegments(rootFolder.getProjectRelativePath());
+ if(matchingSegs > 0)
+ runtimePath = runtimePath.removeFirstSegments(matchingSegs);
IVirtualFile vFile = rootFolder.getFile(runtimePath);
return URI.createPlatformResourceURI(vFile.getWorkspaceRelativePath().toString());
- } catch (UnresolveableURIException e) {
+ } catch (Exception e) {
}
return aModuleResourceRuntimePath;
}
- private static URI normalizeToWorkspaceRelative(IProject project, IPath sourcePath, URI moduleResourceDeployPath) throws UnresolveableURIException {
- String projectName = project.getName();
- return URI.createURI(projectName + '/' + sourcePath.toString());
-
- }
+// private static URI normalizeToWorkspaceRelative(IProject project, IPath sourcePath, URI moduleResourceDeployPath) throws UnresolveableURIException {
+// String projectName = project.getName();
+// return URI.createURI(projectName + '/' + sourcePath.toString());
+// }
/*
* (non-Javadoc)
diff --git a/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/impl/ReferencedComponentImpl.java b/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/impl/ReferencedComponentImpl.java
index 9f97403..f17b3dc 100644
--- a/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/impl/ReferencedComponentImpl.java
+++ b/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/impl/ReferencedComponentImpl.java
@@ -2,7 +2,7 @@
* <copyright>
* </copyright>
*
- * $Id: ReferencedComponentImpl.java,v 1.3 2006/03/27 21:49:41 vbhadrir Exp $
+ * $Id: ReferencedComponentImpl.java,v 1.4 2007/02/14 16:00:52 jsholl Exp $
*/
package org.eclipse.wst.common.componentcore.internal.impl;
@@ -217,7 +217,7 @@
public EObject getDependentObject() {
if (dependentObject != null && dependentObject.eIsProxy()) {
EObject oldDependentObject = dependentObject;
- dependentObject = (EObject)eResolveProxy((InternalEObject)dependentObject);
+ dependentObject = eResolveProxy((InternalEObject)dependentObject);
if (dependentObject != oldDependentObject) {
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.RESOLVE, ComponentcorePackage.REFERENCED_COMPONENT__DEPENDENT_OBJECT, oldDependentObject, dependentObject));
diff --git a/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/impl/ResourceTreeNode.java b/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/impl/ResourceTreeNode.java
index 1baafac..eaab41d 100644
--- a/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/impl/ResourceTreeNode.java
+++ b/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/impl/ResourceTreeNode.java
@@ -1,5 +1,5 @@
/*******************************************************************************
- * Copyright (c) 2003, 2005 IBM Corporation and others.
+ * Copyright (c) 2003, 2006 IBM Corporation 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
diff --git a/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/impl/ResourceTreeRoot.java b/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/impl/ResourceTreeRoot.java
index 1a42a88..53293cd 100644
--- a/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/impl/ResourceTreeRoot.java
+++ b/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/impl/ResourceTreeRoot.java
@@ -1,5 +1,5 @@
/*******************************************************************************
- * Copyright (c) 2003, 2005 IBM Corporation and others.
+ * Copyright (c) 2003, 2006 IBM Corporation 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
diff --git a/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/impl/ResourceTreeRootAdapter.java b/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/impl/ResourceTreeRootAdapter.java
index eee6cce..24c4d17 100644
--- a/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/impl/ResourceTreeRootAdapter.java
+++ b/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/impl/ResourceTreeRootAdapter.java
@@ -1,5 +1,5 @@
/*******************************************************************************
- * Copyright (c) 2003, 2005 IBM Corporation and others.
+ * Copyright (c) 2003, 2007 IBM Corporation 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
diff --git a/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/impl/WTPModulesInit.java b/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/impl/WTPModulesInit.java
index 3865a93..85b5516 100644
--- a/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/impl/WTPModulesInit.java
+++ b/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/impl/WTPModulesInit.java
@@ -1,5 +1,5 @@
/*******************************************************************************
- * Copyright (c) 2003, 2005 IBM Corporation and others.
+ * Copyright (c) 2003, 2006 IBM Corporation 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
diff --git a/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/impl/WTPModulesResourceFactory.java b/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/impl/WTPModulesResourceFactory.java
index 3e254f2..ee2a6dd 100644
--- a/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/impl/WTPModulesResourceFactory.java
+++ b/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/impl/WTPModulesResourceFactory.java
@@ -1,5 +1,5 @@
/*******************************************************************************
- * Copyright (c) 2003, 2005 IBM Corporation and others.
+ * Copyright (c) 2003, 2006 IBM Corporation 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
diff --git a/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/impl/WTPResourceFactoryRegistry.java b/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/impl/WTPResourceFactoryRegistry.java
index 89fe082..ecdb100 100644
--- a/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/impl/WTPResourceFactoryRegistry.java
+++ b/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/impl/WTPResourceFactoryRegistry.java
@@ -1,5 +1,5 @@
/*******************************************************************************
- * Copyright (c) 2003, 2005 IBM Corporation and others.
+ * Copyright (c) 2003, 2007 IBM Corporation 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
@@ -10,20 +10,40 @@
*******************************************************************************/
package org.eclipse.wst.common.componentcore.internal.impl;
+import java.io.IOException;
+import java.util.Arrays;
+import java.util.Comparator;
+import java.util.Iterator;
+import java.util.Set;
+
+import org.eclipse.core.resources.IFile;
+import org.eclipse.core.resources.IProject;
import org.eclipse.core.runtime.Assert;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IConfigurationElement;
import org.eclipse.core.runtime.ISafeRunnable;
import org.eclipse.core.runtime.IStatus;
+import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.SafeRunner;
+import org.eclipse.core.runtime.content.IContentDescription;
+import org.eclipse.core.runtime.content.IContentType;
+import org.eclipse.core.runtime.jobs.ILock;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.jem.util.RegistryReader;
+import org.eclipse.wst.common.componentcore.ComponentCore;
+import org.eclipse.wst.common.componentcore.UnresolveableURIException;
import org.eclipse.wst.common.componentcore.internal.ModulecorePlugin;
+import org.eclipse.wst.common.componentcore.internal.StructureEdit;
+import org.eclipse.wst.common.componentcore.resources.IVirtualComponent;
+import org.eclipse.wst.common.componentcore.resources.IVirtualFile;
+import org.eclipse.wst.common.componentcore.resources.IVirtualFolder;
import org.eclipse.wst.common.internal.emf.resource.FileNameResourceFactoryRegistry;
import org.eclipse.wst.common.internal.emf.resource.ResourceFactoryDescriptor;
import org.eclipse.wst.common.internal.emf.utilities.DefaultOverridableResourceFactoryRegistry;
+import org.eclipse.wst.common.internal.emfworkbench.WorkbenchResourceHelper;
+import org.eclipse.wst.common.internal.emfworkbench.edit.EMFWorkbenchEditContextFactory;
/**
* <p>
@@ -47,19 +67,45 @@
return WTPResourceFactoryRegistry.INSTANCE.getFactory(uri);
}
- public synchronized Resource.Factory getFactory(URI uri) {
-
- Resource.Factory resourceFactory = null;
- if(uri != null && uri.lastSegment() != null) {
- ResourceFactoryDescriptor descriptor = getDescriptor(uri);
-
- if(descriptor != null) {
- resourceFactory = getFactory(descriptor);
- }
+ public Resource.Factory getFactory(URI uri, IContentDescription description) {
+ IProject componentProject = null;
+ try {
+ componentProject = StructureEdit.getContainingProject(uri);
+ } catch (UnresolveableURIException e) {
+ // don't do anything
}
- if(resourceFactory == null)
- resourceFactory = super.getFactory(uri);
- return resourceFactory;
+ ILock lock = EMFWorkbenchEditContextFactory.getProjectLockObject(componentProject);
+ try{
+ if(null != lock){
+ lock.acquire();
+ }
+ synchronized(this){
+ Resource.Factory resourceFactory = null;
+ if(uri != null && uri.lastSegment() != null) {
+ ResourceFactoryDescriptor descriptor = null;
+ if(null == description){
+ descriptor = getDescriptor(uri);
+ } else {
+ descriptor = getDescriptor(uri, description);
+ }
+
+ if(descriptor != null) {
+ resourceFactory = getFactory(descriptor);
+ }
+ }
+ if(resourceFactory == null)
+ resourceFactory = super.getFactory(uri);
+ return resourceFactory;
+ }
+ } finally{
+ if(null != lock){
+ lock.release();
+ }
+ }
+ }
+
+ public Resource.Factory getFactory(URI uri) {
+ return getFactory(uri, (IContentDescription)null);
}
@@ -86,6 +132,18 @@
super.registerLastFileSegment(aSimpleFileName, aFactory);
}
+ private WTPResourceFactoryRegistryKey getKey(ResourceFactoryDescriptor descriptor) {
+ WTPResourceFactoryRegistryKey key = new WTPResourceFactoryRegistryKey();
+ key.shortName = descriptor.getShortSegment();
+ key.type = descriptor.getContentType();
+ key.isDefault = descriptor.isDefault();
+ if(descriptor instanceof ConfigurationResourceFactoryDescriptor){
+ ConfigurationResourceFactoryDescriptor configurationDescriptor = (ConfigurationResourceFactoryDescriptor)descriptor;
+ key.factoryClassName = configurationDescriptor.getFactoryClassName();
+ key.overridesFactoryClassName = configurationDescriptor.getOverridesFactoryClassName();
+ }
+ return key;
+ }
/**
* Declares a subclass to create Resource.Factory(ies) from an extension.
@@ -93,6 +151,10 @@
private class ConfigurationResourceFactoryDescriptor extends ResourceFactoryDescriptor implements IResourceFactoryExtPtConstants {
private String shortSegment;
+ private IContentType contentType;
+ private boolean isDefault = true;
+ private String factoryClassName = null;
+ private String overridesFactoryClassName = null;
private final IConfigurationElement element;
public ConfigurationResourceFactoryDescriptor(IConfigurationElement ext) throws CoreException {
@@ -101,22 +163,52 @@
init();
}
+ public String getOverridesFactoryClassName() {
+ return overridesFactoryClassName;
+ }
+
+ public String getFactoryClassName() {
+ return factoryClassName;
+ }
+
private void init() throws CoreException {
shortSegment = element.getAttribute(ATT_SHORT_SEGMENT);
- if(shortSegment == null || shortSegment.trim().length() == 0)
+
+ IConfigurationElement[] bindings = element.getChildren(TAG_CONTENTTYPE);
+ if (bindings.length > 0) {
+ String contentTypeId = null;
+ contentTypeId = bindings[0].getAttribute(ATT_CONTENTTYPEID);
+ if (contentTypeId != null)
+ contentType = Platform.getContentTypeManager().getContentType(contentTypeId);
+ }
+
+ if ((shortSegment == null || shortSegment.trim().length() == 0)
+ && contentType == null) {
throw new CoreException(
ModulecorePlugin.createErrorStatus(0,
- "The shortSegment attribute of " + TAG_RESOURCE_FACTORY + //$NON-NLS-1$
- " must specify a valid, non-null, non-empty value in " + //$NON-NLS-1$
- element.getNamespaceIdentifier(), null));
+ "Either the shortSegment attribute or the contentType element of " //$NON-NLS-1$
+ + TAG_RESOURCE_FACTORY
+ + " must be specified in "
+ + element.getNamespaceIdentifier()
+ + ". The shortSegment attribute is specified with a valid, non-null, " //$NON-NLS-1$
+ + "non-empty value, and the contentType element is specified with a " //$NON-NLS-1$
+ + "valid, non-null, non-empty contentTypeId." //$NON-NLS-1$
+ , null));
+ }
+ if ("false".equals(element.getAttribute(ATT_ISDEFAULT)))
+ isDefault = false;
+
+ factoryClassName = element.getAttribute(ATT_CLASS);
+ overridesFactoryClassName = element.getAttribute(ATT_OVERRIDES_FACTORY);
}
public boolean isEnabledFor(URI fileURI) {
- /* shortSegment must be non-null for the descriptor to be created,
- * a validation check in init() verifies this requirement */
- if(fileURI != null && fileURI.lastSegment() != null)
+ // Not sure where this is actually used, so not sure what the proper
+ // implementation should be, so simply checking the short segment for now
+ if (fileURI != null && fileURI.lastSegment() != null && shortSegment != null) {
return shortSegment.equals(fileURI.lastSegment());
+ }
return false;
}
@@ -141,14 +233,46 @@
public String getShortSegment() {
return shortSegment;
- }
- }
+ }
+
+ public IContentType getContentType() {
+ return contentType;
+ }
+
+ public boolean isDefault() {
+ return isDefault;
+ }
+
+ public int hashCode() {
+ int hashCode = 0;
+ if (getContentType() != null) {
+ hashCode |= getContentType().hashCode();
+ }
+ if (getShortSegment() != null) {
+ hashCode |= getShortSegment().hashCode();
+ }
+ return hashCode;
+ }
+
+ public boolean equals(Object o) {
+ if (! (o instanceof ResourceFactoryDescriptor)) {
+ return false;
+ }
+ ResourceFactoryDescriptor rfdo = (ResourceFactoryDescriptor) o;
+ boolean equals = true;
+ equals &= (getContentType() == null) ? rfdo.getContentType() == null :
+ getContentType().equals(rfdo.getContentType());
+ equals &= (getShortSegment() == null) ? rfdo.getShortSegment() == null :
+ getShortSegment().equals(rfdo.getShortSegment());
+ return equals;
+ }
+ }
private class ResourceFactoryRegistryReader extends RegistryReader implements IResourceFactoryExtPtConstants {
public ResourceFactoryRegistryReader() {
- super(Platform.getPluginRegistry(), ModulecorePlugin.PLUGIN_ID, EXTPT_RESOURCE_FACTORIES);
+ super(ModulecorePlugin.PLUGIN_ID, EXTPT_RESOURCE_FACTORIES);
}
public boolean readElement(final IConfigurationElement element) {
@@ -172,4 +296,194 @@
}
}
}
+ private class WTPResourceFactoryRegistryKey {
+
+ public String overridesFactoryClassName;
+ public String factoryClassName;
+ public String shortName;
+ public IContentType type;
+ public boolean isDefault = true;
+ public WTPResourceFactoryRegistryKey() {
+ super();
+ }
+
+ /**
+ * Sort in the following manner:
+ * First, sort by shortName, if shortName is null, then it comes last
+ * If shortNames are equal, then sort by isDefault
+ * If isDefault is also equal, then the one defining a factoryClassName wins
+ * If both have factoryClassNames, then check to see if one overrides the other via overridesFactoryClassName
+ * If neither override the other factory class, then sort by factoryClassname
+ * @param other
+ * @return
+ */
+ public int compareTo(WTPResourceFactoryRegistryKey other){
+ if(this == other){
+ return 0;
+ }
+ if(shortName == null && other.shortName == null){
+ return 0;
+ } else if(shortName == null){
+ return 1;
+ } else if(other.shortName == null){
+ return -1;
+ }
+
+ int shortNameCompare = this.shortName.compareTo(other.shortName);
+ if(shortNameCompare != 0){
+ return shortNameCompare;
+ } else {
+ if(this.isDefault != other.isDefault){
+ if(this.isDefault){
+ return -1;
+ } else {
+ return 1;
+ }
+ } else {
+ if(this.factoryClassName == null && other.factoryClassName == null){
+ return 0;
+ } else if(other.factoryClassName == null){
+ return -1;
+ } else if (this.factoryClassName == null){
+ return 1;
+ } else if(other.factoryClassName.equals(this.overridesFactoryClassName)){
+ return -1;
+ } else if(this.factoryClassName.equals(other.overridesFactoryClassName)){
+ return 1;
+ } else {
+ return this.factoryClassName.compareTo(other.factoryClassName);
+ }
+ }
+ }
+ }
+ }
+
+ protected void addDescriptor(ResourceFactoryDescriptor descriptor) {
+ getDescriptors().put(getKey(descriptor), descriptor);
+ }
+
+ private WTPResourceFactoryRegistryKey [] sortedDescriptors = null;
+
+ private WTPResourceFactoryRegistryKey [] getSortedDescriptorKeys() {
+ if(sortedDescriptors == null || sortedDescriptors.length != getDescriptors().size()){
+ Set keys = getDescriptors().keySet();
+ WTPResourceFactoryRegistryKey [] array = new WTPResourceFactoryRegistryKey [keys.size()];
+ int count = 0;
+ for (Iterator iterator = keys.iterator(); iterator.hasNext();count++) {
+ WTPResourceFactoryRegistryKey key = (WTPResourceFactoryRegistryKey) iterator.next();
+ array[count] = key;
+ }
+ Arrays.sort(array, new Comparator<WTPResourceFactoryRegistryKey>() {
+ public int compare(WTPResourceFactoryRegistryKey key1,
+ WTPResourceFactoryRegistryKey key2) {
+ return key1.compareTo(key2);
+ }
+ });
+ sortedDescriptors = array;
+ }
+ return sortedDescriptors;
+ }
+
+ protected synchronized ResourceFactoryDescriptor getDescriptor(URI uri, IContentDescription description) {
+ WTPResourceFactoryRegistryKey [] keys = getSortedDescriptorKeys();
+ ResourceFactoryDescriptor defaultDescriptor = null;
+
+ // first check content type
+ if (description != null) {
+ for (WTPResourceFactoryRegistryKey key : keys) {
+ ResourceFactoryDescriptor descriptor = (ResourceFactoryDescriptor) getDescriptors().get(key);
+
+ if ((key.type != null) && (description.getContentType().equals(key.type))) {
+ if ((defaultDescriptor == null) || (key.isDefault)) {
+ defaultDescriptor = descriptor;
+ }
+ }
+ }
+ }
+
+ // then check short name, overriding default if necessary
+ for (WTPResourceFactoryRegistryKey key : keys) {
+ ResourceFactoryDescriptor descriptor = (ResourceFactoryDescriptor) getDescriptors().get(key);
+
+ if ((key.shortName != null) && (uri.lastSegment().equals(key.shortName))) {
+ if ((defaultDescriptor == null)
+ || ((description == null) && (key.isDefault))) {
+ defaultDescriptor = descriptor;
+ }
+ }
+ }
+
+ return defaultDescriptor;
+ }
+
+ private URI newPlatformURI(URI aNewURI, IProject project) {
+
+ if (project == null)
+ return ModuleURIUtil.trimToDeployPathSegment(aNewURI);
+ try {
+ IVirtualComponent component = ComponentCore.createComponent(project);
+
+ URI deployPathSegment = ModuleURIUtil.trimToDeployPathSegment(aNewURI);
+
+ //IVirtualFile newFile = component.getFile(new Path(deployPathSegment.path()));
+ IVirtualFolder rootFolder = component.getRootFolder();
+ IVirtualFile newFile = rootFolder.getFile(new Path(deployPathSegment.path()));
+
+ return URI.createPlatformResourceURI(newFile.getWorkspaceRelativePath().toString());
+
+ } catch(Exception e) {
+ e.printStackTrace();
+ }
+ return null;
+ }
+
+ private IContentDescription getDescriptionFromURI(URI uri) {
+ String contentTypeIdentifier = ModuleURIUtil.getContentTypeName(uri);
+ if (contentTypeIdentifier != null)
+ return Platform.getContentTypeManager().getContentType(contentTypeIdentifier).getDefaultDescription();
+ else
+ return null;
+
+ }
+
+ protected synchronized ResourceFactoryDescriptor getDescriptor(URI uri) {
+ IFile file = WorkbenchResourceHelper.getPlatformFile(uri);
+ IContentDescription description = null;
+ if (file != null && file.exists()) {
+ try {
+ description = file.getContentDescription();
+ } catch (CoreException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+ }
+ if (description == null) {//Check for optional embedded uri segment, then normalize
+ description = getDescriptionFromURI(uri);
+ try {
+ if (description != null) {
+ IProject componentProject = null;
+ try {
+ componentProject = StructureEdit.getContainingProject(uri);
+ } catch (UnresolveableURIException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+ uri = PlatformURLModuleConnection.resolve(uri);
+ uri = newPlatformURI(uri,componentProject);
+ }
+ } catch (IOException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+ }
+
+ ResourceFactoryDescriptor defaultDesc = getDescriptor(uri, description);
+ // Ok no content type match - go to super
+ if (defaultDesc != null){
+ return defaultDesc;
+ }
+ else{
+ return super.getDescriptor(uri);
+ }
+ }
}
diff --git a/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/impl/WorkbenchComponentImpl.java b/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/impl/WorkbenchComponentImpl.java
index 940ca63..883ebb9 100644
--- a/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/impl/WorkbenchComponentImpl.java
+++ b/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/impl/WorkbenchComponentImpl.java
@@ -2,15 +2,13 @@
* <copyright>
* </copyright>
*
- * $Id: WorkbenchComponentImpl.java,v 1.12.2.1 2006/09/28 17:01:20 cbridgha Exp $
+ * $Id: WorkbenchComponentImpl.java,v 1.14 2007/02/14 16:00:52 jsholl Exp $
*/
package org.eclipse.wst.common.componentcore.internal.impl;
import java.util.Collection;
-import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
-import java.util.Map;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.runtime.IPath;
@@ -187,14 +185,14 @@
*/
protected EList metadataResources = null;
- private final Map resourceIndexByDeployPath = new HashMap();
- private final Map resourceIndexBySourcePath = new HashMap();
+// private final Map resourceIndexByDeployPath = new HashMap();
+// private final Map resourceIndexBySourcePath = new HashMap();
- private boolean isIndexedByDeployPath;
+// private boolean isIndexedByDeployPath;
- private boolean isIndexedBySourcePath;
+// private boolean isIndexedBySourcePath;
- private static final ComponentResource[] NO_MODULE_RESOURCES = new ComponentResource[0];
+// private static final ComponentResource[] NO_MODULE_RESOURCES = new ComponentResource[0];
private URI handle;
@@ -254,7 +252,7 @@
// TODO A more advanced adapter should be applied to keep the handle up to date.
if (eResource() != null) {
URI resourceURI = eResource().getURI();
- String safeDeployedName = getName() != null ? getName() : ""; //$NON-NLS-1$
+// String safeDeployedName = getName() != null ? getName() : ""; //$NON-NLS-1$
if (resourceURI != null && resourceURI.segmentCount() >= 2)
setHandle(computeHandle());
}
diff --git a/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/operation/ArtifactEditOperationDataModelProvider.java b/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/operation/ArtifactEditOperationDataModelProvider.java
index b713cde..1a61422 100644
--- a/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/operation/ArtifactEditOperationDataModelProvider.java
+++ b/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/operation/ArtifactEditOperationDataModelProvider.java
@@ -1,5 +1,5 @@
/*******************************************************************************
- * Copyright (c) 2005 IBM Corporation and others.
+ * Copyright (c) 2005, 2006 IBM Corporation 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
diff --git a/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/operation/ArtifactEditProviderOperation.java b/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/operation/ArtifactEditProviderOperation.java
index ea7575c..b956516 100644
--- a/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/operation/ArtifactEditProviderOperation.java
+++ b/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/operation/ArtifactEditProviderOperation.java
@@ -1,5 +1,5 @@
/*******************************************************************************
- * Copyright (c) 2005 IBM Corporation and others.
+ * Copyright (c) 2005, 2007 IBM Corporation 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
@@ -114,7 +114,6 @@
* Validate edit for resource state
*/
protected IStatus validateEdit() {
- IStatus status = OK_STATUS;
IValidateEditContext validator = (IValidateEditContext) UIContextDetermination.createInstance(IValidateEditContext.CLASS_KEY);
return validator.validateState((EditModel)getArtifactEdit().getAdapter(ArtifactEditModel.ADAPTER_TYPE));
diff --git a/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/operation/ComponentCreationDataModelProvider.java b/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/operation/ComponentCreationDataModelProvider.java
deleted file mode 100644
index 1202171..0000000
--- a/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/operation/ComponentCreationDataModelProvider.java
+++ /dev/null
@@ -1,247 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2003, 2005 IBM Corporation 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.common.componentcore.internal.operation;
-
-import java.util.List;
-import java.util.Set;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.IWorkspace;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.emf.ecore.EClass;
-import org.eclipse.jem.util.emf.workbench.ProjectUtilities;
-import org.eclipse.wst.common.componentcore.ComponentCore;
-import org.eclipse.wst.common.componentcore.datamodel.FacetProjectCreationDataModelProvider;
-import org.eclipse.wst.common.componentcore.datamodel.properties.IComponentCreationDataModelProperties;
-import org.eclipse.wst.common.componentcore.datamodel.properties.IFlexibleProjectCreationDataModelProperties;
-import org.eclipse.wst.common.frameworks.datamodel.AbstractDataModelProvider;
-import org.eclipse.wst.common.frameworks.datamodel.DataModelEvent;
-import org.eclipse.wst.common.frameworks.datamodel.IDataModel;
-import org.eclipse.wst.common.frameworks.internal.DoNotUseMeThisWillBeDeletedPost15;
-import org.eclipse.wst.common.frameworks.internal.plugin.WTPCommonMessages;
-import org.eclipse.wst.common.frameworks.internal.plugin.WTPCommonPlugin;
-
-/**
- * This dataModel is a common super class used for creation of WTP Components.
- *
- * This class (and all its fields and methods) is likely to change during the WTP 1.0 milestones as
- * the new project structures are adopted. Use at your own risk.
- *
- * @plannedfor WTP 1.0
- */
-/**
- * This has been slated for removal post WTP 1.5. Do not use this class/interface
- *
- * @deprecated
- *
- * @see FacetProjectCreationDataModelProvider
- */
-public abstract class ComponentCreationDataModelProvider extends AbstractDataModelProvider implements IComponentCreationDataModelProperties, DoNotUseMeThisWillBeDeletedPost15 {
-
- // protected boolean isProjMultiComponents = false;
-
- public void init() {
- super.init();
- // isProjMultiComponents =
- // FlexibleJavaProjectPreferenceUtil.getMultipleModulesPerProjectProp();
- // model.getBooleanProperty(SUPPORT_MULTIPLE_MODULES) =
- // model.getBooleanProperty(SUPPORT_MULTIPLE_MODULES);
- initProjectCreationModel();
- }
-
- public Set getPropertyNames() {
- Set propertyNames = super.getPropertyNames();
- propertyNames.add(PROJECT_NAME);
- propertyNames.add(NESTED_PROJECT_CREATION_DM);
- propertyNames.add(COMPONENT_NAME);
- propertyNames.add(COMPONENT_NAME);
- propertyNames.add(LOCATION);
- propertyNames.add(COMPONENT_DEPLOY_NAME);
- propertyNames.add(CREATE_DEFAULT_FILES);
- propertyNames.add(COMPONENT);
- return propertyNames;
- }
-
- public void propertyChanged(DataModelEvent event) {
- if (event.getFlag() == DataModelEvent.VALUE_CHG) {
- event.getDataModel();
- }
- }
-
- public boolean propertySet(String propertyName, Object propertyValue) {
- if (COMPONENT_NAME.equals(propertyName)) {
- model.setProperty(COMPONENT_DEPLOY_NAME, propertyValue);
- model.setProperty(PROJECT_NAME, propertyValue);
- } else if (COMPONENT_DEPLOY_NAME.equals(propertyName)) {
- model.setProperty(COMPONENT_DEPLOY_NAME, propertyValue);
- } else if (COMPONENT.equals(propertyName)) {
- throw new RuntimeException(propertyName + " should not be set.");
- } else if (PROJECT_NAME.equals(propertyName)) {
- // if(!FlexibleJavaProjectPreferenceUtil.getMultipleModulesPerProjectProp()){
- // model.notifyPropertyChange(PROJECT_NAME, IDataModel.VALUE_CHG);
- // set the property in nested FlexibleJavaProjectCreationDataModelProvider
- IDataModel dm = model.getNestedModel(NESTED_PROJECT_CREATION_DM);
- dm.setProperty(IFlexibleProjectCreationDataModelProperties.PROJECT_NAME, propertyValue);
- return true;
- // }
- }
- return true;
- }
-
- public Object getDefaultProperty(String propertyName) {
- if (propertyName.equals(CREATE_DEFAULT_FILES)) {
- return Boolean.TRUE;
- } else if (propertyName.equals(COMPONENT)) {
- String projectName = getStringProperty(PROJECT_NAME);
- IProject project = ProjectUtilities.getProject(projectName);
- return ComponentCore.createComponent(project);
- }
- return super.getDefaultProperty(propertyName);
- }
-
- public IStatus validate(String propertyName) {
- if (propertyName.equals(COMPONENT_NAME)) {
- IStatus status = OK_STATUS;
- String moduleName = model.getStringProperty(COMPONENT_NAME);
- if (status.isOK()) {
- if (moduleName.indexOf("#") != -1 || moduleName.indexOf("/") != -1) { //$NON-NLS-1$
- String errorMessage = WTPCommonPlugin.getResourceString(WTPCommonMessages.ERR_INVALID_CHARS); //$NON-NLS-1$
- return WTPCommonPlugin.createErrorStatus(errorMessage);
- } else if (moduleName == null || moduleName.equals("")) { //$NON-NLS-1$
- String errorMessage = WTPCommonPlugin.getResourceString(WTPCommonMessages.ERR_EMPTY_MODULE_NAME);
- return WTPCommonPlugin.createErrorStatus(errorMessage);
- } else
- return OK_STATUS;
- } else
- return status;
- } else if (propertyName.equals(PROJECT_NAME)) {
- IStatus status = OK_STATUS;
-
- String projectName = model.getStringProperty(PROJECT_NAME);
- if (projectName == null || projectName.length() == 0) {
- String errorMessage = WTPCommonPlugin.getResourceString(WTPCommonMessages.PROJECT_NAME_EMPTY);
- status = WTPCommonPlugin.createErrorStatus(errorMessage);
- }
- if (status.isOK()) {
- status = validateProjectName(projectName);
- if (status.isOK()) {
- IProject proj = ProjectUtilities.getProject(projectName);
- if (proj.exists()) {
- String errorMessage = WTPCommonPlugin.getResourceString(WTPCommonMessages.PROJECT_EXISTS_ERROR);
- status = WTPCommonPlugin.createErrorStatus(errorMessage);
- }
- }
- }
-
- return status;
- } else if (propertyName.equals(COMPONENT_DEPLOY_NAME)) {
- return OK_STATUS;
- } else if (propertyName.equals(CREATE_DEFAULT_FILES)) {
- return OK_STATUS;
- }
- return OK_STATUS;
- }
-
- protected IStatus validateProjectName(String projectName) {
- IWorkspace workspace = ResourcesPlugin.getWorkspace();
- IStatus status = workspace.validateName(projectName, IResource.PROJECT);
- if (!status.isOK())
- return status;
-
- if (ProjectUtilities.getProject(projectName).exists())
- return WTPCommonPlugin.createErrorStatus(WTPCommonPlugin.getResourceString(WTPCommonMessages.PROJECT_EXISTS_ERROR, new Object[]{projectName}));
-
- if (projectName.indexOf("#") != -1) { //$NON-NLS-1$
- // String errorMessage = J2EECreationResourceHandler.getString("InvalidCharsError");
- // //$NON-NLS-1$
- String errorMessage = "InvalidCharsError"; //$NON-NLS-1$
- return WTPCommonPlugin.createErrorStatus(errorMessage);
- }
- return OK_STATUS;
- }
-
- // protected static String[] getServerVersions(String moduleID, IRuntimeType type) {
- // List list = new ArrayList();
- // if (type == null)
- // return null;
- // IModuleType[] moduleTypes = type.getModuleTypes();
- // if (moduleTypes != null) {
- // int size = moduleTypes.length;
- // for (int i = 0; i < size; i++) {
- // IModuleType moduleType = moduleTypes[i];
- // if (matches(moduleType.getId(), moduleID)) {
- // list.add(moduleType.getVersion());
- // }
- //
- // }
- // }
- // String[] versions = null;
- // if (!list.isEmpty()) {
- // versions = new String[list.size()];
- // list.toArray(versions);
- // }
- // return versions;
- // }
-
-// protected static boolean matches(String serverTypeID, String j2eeModuleID) {
-//
-// if (serverTypeID.equals("j2ee")) {
-// if (j2eeModuleID.equals(IModuleConstants.JST_WEB_MODULE) || j2eeModuleID.equals(IModuleConstants.JST_EJB_MODULE) || j2eeModuleID.equals(IModuleConstants.JST_EAR_MODULE) || j2eeModuleID.equals(IModuleConstants.JST_APPCLIENT_MODULE) || j2eeModuleID.equals(IModuleConstants.JST_CONNECTOR_MODULE)) {
-// return true;
-// }
-// } else if (serverTypeID.equals("j2ee.*")) {
-// if (j2eeModuleID.equals(IModuleConstants.JST_WEB_MODULE) || j2eeModuleID.equals(IModuleConstants.JST_EJB_MODULE) || j2eeModuleID.equals(IModuleConstants.JST_EAR_MODULE) || j2eeModuleID.equals(IModuleConstants.JST_APPCLIENT_MODULE) || j2eeModuleID.equals(IModuleConstants.JST_CONNECTOR_MODULE)) {
-// return true;
-// }
-// } else if (serverTypeID.equals("j2ee.web")) {//$NON-NLS-1$
-// if (j2eeModuleID.equals(IModuleConstants.JST_WEB_MODULE)) {
-// return true;
-// }
-// } else if (serverTypeID.equals("j2ee.ejb")) {//$NON-NLS-1$
-// if (j2eeModuleID.equals(IModuleConstants.JST_EJB_MODULE)) {
-// return true;
-// }
-// } else if (serverTypeID.equals("j2ee.ear")) {//$NON-NLS-1$
-// if (j2eeModuleID.equals(IModuleConstants.JST_EAR_MODULE) || j2eeModuleID.equals(IModuleConstants.JST_APPCLIENT_MODULE) || j2eeModuleID.equals(IModuleConstants.JST_CONNECTOR_MODULE)) {
-// return true;
-// }
-// }
-// return false;
-// }
-
- // private static boolean matches(String a, String b) {
- // if (a == null || b == null || "*".equals(a) || "*".equals(b) || a.startsWith(b) ||
- // b.startsWith(a)) //$NON-NLS-1$ //$NON-NLS-2$
- // return true;
- // return false;
- // }
-
-
- protected String getComponentName() {
- return model.getStringProperty(COMPONENT_NAME);
- }
-
- protected String getComponentDeployName() {
- return model.getStringProperty(COMPONENT_DEPLOY_NAME);
- }
-
- protected abstract void initProjectCreationModel();
-
- protected abstract EClass getComponentType();
-
- protected abstract String getComponentExtension();
-
- protected abstract List getProperties();
-
- protected abstract Integer getDefaultComponentVersion();
-}
diff --git a/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/operation/ComponentCreationOperation.java b/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/operation/ComponentCreationOperation.java
deleted file mode 100644
index 769c2dd..0000000
--- a/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/operation/ComponentCreationOperation.java
+++ /dev/null
@@ -1,105 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2003, 2005 IBM Corporation 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.common.componentcore.internal.operation;
-
-import java.util.List;
-
-import org.eclipse.core.commands.ExecutionException;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IAdaptable;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.jem.util.emf.workbench.ProjectUtilities;
-import org.eclipse.jem.util.logger.proxy.Logger;
-import org.eclipse.wst.common.componentcore.datamodel.properties.IComponentCreationDataModelProperties;
-import org.eclipse.wst.common.componentcore.datamodel.properties.IFlexibleProjectCreationDataModelProperties;
-import org.eclipse.wst.common.componentcore.internal.StructureEdit;
-import org.eclipse.wst.common.frameworks.datamodel.AbstractDataModelOperation;
-import org.eclipse.wst.common.frameworks.datamodel.IDataModel;
-import org.eclipse.wst.common.frameworks.datamodel.IDataModelOperation;
-import org.eclipse.wst.common.frameworks.internal.DoNotUseMeThisWillBeDeletedPost15;
-
-
-/**
- * This has been slated for removal post WTP 1.5. Do not use this class/interface
- *
- * @deprecated
- *
- * @see FacetProjectCreationOperation
- */
-public abstract class ComponentCreationOperation extends AbstractDataModelOperation implements IComponentCreationDataModelProperties, DoNotUseMeThisWillBeDeletedPost15 {
-
- public ComponentCreationOperation(IDataModel model) {
- super(model);
- }
-
- public IStatus execute(IProgressMonitor monitor, IAdaptable info) {
- createProjectIfNeeded(monitor, info);
- StructureEdit edit = null;
- try {
- edit = StructureEdit.getStructureEditForWrite(getProject());
-
- createAndLinkJ2EEComponentsForSingleComponent();
- }
- catch (CoreException e) {
- Logger.getLogger().log(e);
- }
- finally {
- if (edit != null) {
- edit.saveIfNecessary(monitor);
- edit.dispose();
- }
-
- }
-
- return OK_STATUS;
- }
-
- private void createProjectIfNeeded(IProgressMonitor monitor, IAdaptable info) {
- Object dm = model.getNestedModel(NESTED_PROJECT_CREATION_DM);
- if(dm == null) return;
- String projName = ((IDataModel)dm).getStringProperty(IFlexibleProjectCreationDataModelProperties.PROJECT_NAME);
-
- IProject proj = ProjectUtilities.getProject(projName);
- if(projName == null || projName.equals("") || proj.exists()) return;
- IDataModelOperation op = ((IDataModel)dm).getDefaultOperation();
- try {
- op.execute(monitor, info);
- } catch (ExecutionException e) {
- e.printStackTrace();
- }
- }
-
-
- protected abstract void createAndLinkJ2EEComponentsForMultipleComponents() throws CoreException;
-
- protected abstract void createAndLinkJ2EEComponentsForSingleComponent() throws CoreException;
-
- protected String getComponentName() {
- return model.getStringProperty(COMPONENT_NAME);
- }
-
- public String getComponentDeployName() {
- return model.getStringProperty(COMPONENT_DEPLOY_NAME);
- }
-
- protected abstract String getVersion();
-
- protected abstract List getProperties();
-
- public IProject getProject() {
- String projName = model.getStringProperty(PROJECT_NAME);
- return ProjectUtilities.getProject(projName);
- }
-
-}
diff --git a/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/operation/CreateReferenceComponentsDataModelProvider.java b/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/operation/CreateReferenceComponentsDataModelProvider.java
index bf6e0c7..3967a2a 100644
--- a/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/operation/CreateReferenceComponentsDataModelProvider.java
+++ b/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/operation/CreateReferenceComponentsDataModelProvider.java
@@ -1,5 +1,5 @@
/*******************************************************************************
- * Copyright (c) 2005 IBM Corporation and others.
+ * Copyright (c) 2005, 2007 IBM Corporation 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
@@ -12,7 +12,6 @@
import java.util.ArrayList;
import java.util.HashMap;
-import java.util.List;
import java.util.Map;
import java.util.Set;
@@ -31,7 +30,7 @@
propertyNames.add(SOURCE_COMPONENT);
propertyNames.add(TARGET_COMPONENT_LIST);
propertyNames.add(TARGET_COMPONENTS_DEPLOY_PATH);
- propertyNames.add(TARGET_COMPONENT_ARCHIVE_NAME);
+ propertyNames.add(TARGET_COMPONENTS_DEPLOY_PATH_MAP);
propertyNames.add(TARGET_COMPONENTS_TO_URI_MAP);
return propertyNames;
}
@@ -46,17 +45,16 @@
setProperty(propertyName, map);
return map;
}
+ else if (TARGET_COMPONENTS_DEPLOY_PATH_MAP.equals(propertyName)) {
+ Map map = new HashMap();
+ setProperty(propertyName, map);
+ return map;
+ }
if (propertyName.equals(TARGET_COMPONENT_LIST))
return new ArrayList();
else if (propertyName.equals(TARGET_COMPONENTS_DEPLOY_PATH)){
return "/"; //$NON-NLS-1$
- } else if (propertyName.equals(TARGET_COMPONENT_ARCHIVE_NAME)){
- List components = (List) getProperty(TARGET_COMPONENT_LIST);
- if(components.size() == 0){
- Map map = (Map)getProperty(TARGET_COMPONENTS_TO_URI_MAP);
- map.put(components.get(0), getProperty(propertyName));
- }
}
return super.getDefaultProperty(propertyName);
}
diff --git a/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/operation/CreateReferenceComponentsOp.java b/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/operation/CreateReferenceComponentsOp.java
index fb0833d..dfcc622 100644
--- a/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/operation/CreateReferenceComponentsOp.java
+++ b/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/operation/CreateReferenceComponentsOp.java
@@ -1,5 +1,5 @@
/*******************************************************************************
- * Copyright (c) 2005 IBM Corporation and others.
+ * Copyright (c) 2005, 2007 IBM Corporation 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
@@ -15,26 +15,25 @@
import java.util.Map;
import org.eclipse.core.commands.ExecutionException;
+import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
+import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IAdaptable;
+import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Status;
import org.eclipse.jem.util.UIContextDetermination;
import org.eclipse.jem.util.emf.workbench.ProjectUtilities;
-import org.eclipse.wst.common.componentcore.ArtifactEdit;
import org.eclipse.wst.common.componentcore.ComponentCore;
import org.eclipse.wst.common.componentcore.datamodel.properties.ICreateReferenceComponentsDataModelProperties;
-import org.eclipse.wst.common.componentcore.internal.ArtifactEditModel;
import org.eclipse.wst.common.componentcore.internal.StructureEdit;
-import org.eclipse.wst.common.componentcore.internal.util.ComponentUtilities;
import org.eclipse.wst.common.componentcore.resources.IVirtualComponent;
import org.eclipse.wst.common.componentcore.resources.IVirtualReference;
import org.eclipse.wst.common.frameworks.datamodel.AbstractDataModelOperation;
import org.eclipse.wst.common.frameworks.datamodel.IDataModel;
-import org.eclipse.wst.common.internal.emfworkbench.integration.EditModel;
import org.eclipse.wst.common.internal.emfworkbench.validateedit.IValidateEditContext;
public class CreateReferenceComponentsOp extends AbstractDataModelOperation {
@@ -60,14 +59,7 @@
IValidateEditContext validator = (IValidateEditContext) UIContextDetermination.createInstance(IValidateEditContext.CLASS_KEY);
IVirtualComponent sourceComp = (IVirtualComponent) model.getProperty(ICreateReferenceComponentsDataModelProperties.SOURCE_COMPONENT);
IProject project = sourceComp.getProject();
- ArtifactEdit edit = null;
- try {
- edit = ComponentUtilities.getArtifactEditForWrite(sourceComp);
- status = validator.validateState((EditModel)edit.getAdapter(ArtifactEditModel.ADAPTER_TYPE));
- } finally {
- if (edit !=null)
- edit.dispose();
- }
+
if (status.isOK()) {
StructureEdit sEdit = null;
try {
@@ -78,6 +70,10 @@
sEdit.dispose();
}
}
+
+ IFile [] files = new IFile[1];
+ files[0] = project.getFile(ProjectUtilities.DOT_PROJECT);
+ status = ResourcesPlugin.getWorkspace().validateEdit(files, null);
return status;
}
@@ -103,13 +99,29 @@
IVirtualComponent sourceComp = (IVirtualComponent) model.getProperty(ICreateReferenceComponentsDataModelProperties.SOURCE_COMPONENT);
List vlist = new ArrayList();
List modList = (List) model.getProperty(ICreateReferenceComponentsDataModelProperties.TARGET_COMPONENT_LIST);
+ Map modDeployPathMap = (Map) model.getProperty(ICreateReferenceComponentsDataModelProperties.TARGET_COMPONENTS_DEPLOY_PATH_MAP);
+ String deployPathStr = model.getStringProperty(ICreateReferenceComponentsDataModelProperties.TARGET_COMPONENTS_DEPLOY_PATH);
+ IPath deployPath = null;
+ IPath archiveDeployPath = null;
+ if (deployPathStr != null && deployPathStr.length() > 0){
+ deployPath = new Path(deployPathStr);
+ }
for (int i = 0; i < modList.size(); i++) {
IVirtualComponent comp = (IVirtualComponent) modList.get(i);
- if (!srcComponentContainsReference(sourceComp, comp)) {
+ if (!srcComponentContainsReference(sourceComp, comp, deployPath)) {
IVirtualReference ref = ComponentCore.createReference(sourceComp, comp);
- String deployPath = model.getStringProperty(ICreateReferenceComponentsDataModelProperties.TARGET_COMPONENTS_DEPLOY_PATH);
- if (deployPath != null && deployPath.length() > 0)
- ref.setRuntimePath(new Path(deployPath));
+ deployPathStr = (String)modDeployPathMap.get(comp);
+ if (deployPathStr != null)
+ {
+ archiveDeployPath = new Path(deployPathStr);
+ }
+ else
+ {
+ archiveDeployPath = deployPath;
+ }
+ if(archiveDeployPath != null){
+ ref.setRuntimePath(archiveDeployPath);
+ }
String archiveName = getArchiveName(comp);
if (archiveName.length() > 0) {
@@ -130,17 +142,21 @@
}
- private boolean srcComponentContainsReference(IVirtualComponent sourceComp, IVirtualComponent comp) {
+ private boolean srcComponentContainsReference(IVirtualComponent sourceComp, IVirtualComponent comp, IPath deployPath) {
if ((sourceComp != null && sourceComp.getProject() != null) && (comp != null && comp.getProject() != null)) {
-
IVirtualReference[] existingReferences = sourceComp.getReferences();
IVirtualComponent referencedComponent = null;
if (existingReferences != null) {
for (int i = 0; i < existingReferences.length; i++) {
- if (existingReferences[i] != null ) {
- referencedComponent = existingReferences[i].getReferencedComponent();
- if (referencedComponent != null && referencedComponent.equals(comp) )
+ IVirtualReference ref = existingReferences[i];
+ if(ref != null){
+ //also check to see if the deploy path is the same (remember that it can be null)
+ if((ref.getRuntimePath() == null && deployPath != null) || ref.getRuntimePath().equals(deployPath)){
+ referencedComponent = ref.getReferencedComponent();
+ if (referencedComponent != null && referencedComponent.equals(comp) ){
return true;
+ }
+ }
}
}
}
diff --git a/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/operation/FacetProjectCreationOperation.java b/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/operation/FacetProjectCreationOperation.java
index 5873c52..abdcd14 100644
--- a/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/operation/FacetProjectCreationOperation.java
+++ b/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/operation/FacetProjectCreationOperation.java
@@ -1,10 +1,10 @@
/*******************************************************************************
- * Copyright (c) 2003, 2005 IBM Corporation and others.
+ * Copyright (c) 2003, 2007 IBM Corporation 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:
* IBM Corporation - initial API and implementation
*******************************************************************************/
@@ -32,6 +32,7 @@
import org.eclipse.wst.common.frameworks.datamodel.IDataModel;
import org.eclipse.wst.common.frameworks.internal.operations.IProjectCreationPropertiesNew;
import org.eclipse.wst.common.project.facet.core.IFacetedProject;
+import org.eclipse.wst.common.project.facet.core.IFacetedProjectWorkingCopy;
import org.eclipse.wst.common.project.facet.core.IProjectFacet;
import org.eclipse.wst.common.project.facet.core.IProjectFacetVersion;
import org.eclipse.wst.common.project.facet.core.ProjectFacetsManager;
@@ -101,7 +102,7 @@
}
if (runtimeAdded) {
IRuntime runtime = (IRuntime) model.getProperty(IFacetProjectCreationDataModelProperties.FACET_RUNTIME);
- addDefaultFacets(facetProj, runtime.getDefaultFacets(fixedFacets));
+ addDefaultFactets(facetProj, runtime);
}
} catch (CoreException e) {
@@ -150,14 +151,13 @@
}
public static void addDefaultFactets(IFacetedProject facetProj, IRuntime runtime) throws ExecutionException {
- try {
+
if (runtime != null) {
- addDefaultFacets(facetProj, runtime.getDefaultFacets(facetProj.getFixedProjectFacets()));
+ final IFacetedProjectWorkingCopy fpjwc = facetProj.createWorkingCopy();
+ Set<IProjectFacetVersion> presetFacets = fpjwc.getDefaultConfiguration().getProjectFacets();
+ addDefaultFacets(facetProj, presetFacets);
}
- } catch (CoreException e) {
- Logger.getLogger().logError(e);
- throw new ExecutionException(e.getMessage(), e);
- }
+
}
}
diff --git a/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/operation/FlexibleProjectCreationOperation.java b/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/operation/FlexibleProjectCreationOperation.java
deleted file mode 100644
index 460b068..0000000
--- a/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/operation/FlexibleProjectCreationOperation.java
+++ /dev/null
@@ -1,101 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2005 IBM Corporation 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.common.componentcore.internal.operation;
-
-import java.lang.reflect.InvocationTargetException;
-
-import org.eclipse.core.commands.ExecutionException;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IAdaptable;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.wst.common.componentcore.datamodel.FacetProjectCreationDataModelProvider;
-import org.eclipse.wst.common.componentcore.datamodel.properties.IFlexibleProjectCreationDataModelProperties;
-import org.eclipse.wst.common.componentcore.internal.ProjectComponents;
-import org.eclipse.wst.common.componentcore.internal.StructureEdit;
-import org.eclipse.wst.common.componentcore.internal.util.IModuleConstants;
-import org.eclipse.wst.common.frameworks.datamodel.AbstractDataModelOperation;
-import org.eclipse.wst.common.frameworks.datamodel.IDataModel;
-import org.eclipse.wst.common.frameworks.datamodel.IDataModelOperation;
-import org.eclipse.wst.common.frameworks.internal.DoNotUseMeThisWillBeDeletedPost15;
-import org.eclipse.wst.common.frameworks.internal.WTPProjectUtilities;
-
-/**
- * This has been slated for removal post WTP 1.5. Do not use this class/interface
- *
- * @deprecated
- *
- * @see FacetProjectCreationDataModelProvider
- */
-public class FlexibleProjectCreationOperation extends AbstractDataModelOperation implements DoNotUseMeThisWillBeDeletedPost15{
-
- public FlexibleProjectCreationOperation(IDataModel model) {
- super(model);
- // TODO Auto-generated constructor stub
- }
-
- public IStatus execute(IProgressMonitor monitor, IAdaptable info) throws ExecutionException {
- try {
- createProject(monitor);
- WTPProjectUtilities.addNatureToProjectLast(getProject(), IModuleConstants.MODULE_NATURE_ID);
- } catch (CoreException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } catch (InvocationTargetException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- createInitialWTPModulesFile();
- return OK_STATUS;
- }
-
- private void createProject(IProgressMonitor monitor) throws CoreException, InvocationTargetException, InterruptedException, ExecutionException {
- IDataModel projModel = model.getNestedModel(IFlexibleProjectCreationDataModelProperties.NESTED_MODEL_PROJECT_CREATION);
- IDataModelOperation op = projModel.getDefaultOperation();
- op.execute(monitor, null);
- }
-
- private void createInitialWTPModulesFile() {
- StructureEdit moduleCore = null;
- try {
- IProject containingProject = getProject();
- moduleCore = StructureEdit.getStructureEditForWrite(containingProject);
- moduleCore.prepareProjectComponentsIfNecessary();
- ProjectComponents projectModules = moduleCore.getComponentModelRoot();
- moduleCore.saveIfNecessary(null);
- } finally {
- if(moduleCore != null)
- moduleCore.dispose();
- }
- }
-
- protected IProject getProject() {
- String name = model.getStringProperty(IFlexibleProjectCreationDataModelProperties.PROJECT_NAME);
- if (name != null && name.length() > 0)
- return ResourcesPlugin.getWorkspace().getRoot().getProject(name);
- return null;
- }
-
- public IStatus redo(IProgressMonitor monitor, IAdaptable info) throws ExecutionException {
- // TODO Auto-generated method stub
- return null;
- }
-
- public IStatus undo(IProgressMonitor monitor, IAdaptable info) throws ExecutionException {
- // TODO Auto-generated method stub
- return null;
- }
-}
diff --git a/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/operation/ProjectMigratorDataModelOperation.java b/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/operation/ProjectMigratorDataModelOperation.java
index 68e14fd..d507389 100644
--- a/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/operation/ProjectMigratorDataModelOperation.java
+++ b/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/operation/ProjectMigratorDataModelOperation.java
@@ -1,10 +1,10 @@
/*******************************************************************************
- * Copyright (c) 2003, 2005 IBM Corporation and others.
+ * Copyright (c) 2003, 2007 IBM Corporation 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:
* IBM Corporation - initial API and implementation
*******************************************************************************/
@@ -21,7 +21,6 @@
import org.eclipse.wst.common.componentcore.internal.ProjectMigratorRegistry;
import org.eclipse.wst.common.frameworks.datamodel.AbstractDataModelOperation;
import org.eclipse.wst.common.frameworks.datamodel.IDataModel;
-import org.eclipse.wst.common.project.facet.core.IFacetedProject;
public class ProjectMigratorDataModelOperation extends AbstractDataModelOperation {
@@ -30,7 +29,6 @@
}
public IStatus execute(IProgressMonitor monitor, IAdaptable info) throws ExecutionException {
- IFacetedProject facetProj;
try {
IProject proj = ProjectUtilities.getProject(model.getStringProperty(IProjectMigratorDataModelProperties.PROJECT_NAME));
IComponentProjectMigrator[] migrators = ProjectMigratorRegistry.getInstance().getProjectMigrators();
@@ -44,6 +42,4 @@
return OK_STATUS;
}
-
-
}
diff --git a/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/operation/RemoveReferenceComponentOperation.java b/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/operation/RemoveReferenceComponentOperation.java
index 091bb0f..bb1f2c3 100644
--- a/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/operation/RemoveReferenceComponentOperation.java
+++ b/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/operation/RemoveReferenceComponentOperation.java
@@ -1,5 +1,5 @@
/*******************************************************************************
- * Copyright (c) 2005 IBM Corporation and others.
+ * Copyright (c) 2005, 2006 IBM Corporation 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
@@ -11,7 +11,6 @@
package org.eclipse.wst.common.componentcore.internal.operation;
import java.util.ArrayList;
-import java.util.Arrays;
import java.util.List;
import org.eclipse.core.commands.ExecutionException;
@@ -23,6 +22,7 @@
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Path;
import org.eclipse.jem.util.emf.workbench.ProjectUtilities;
+import org.eclipse.jem.util.logger.proxy.Logger;
import org.eclipse.wst.common.componentcore.datamodel.properties.ICreateReferenceComponentsDataModelProperties;
import org.eclipse.wst.common.componentcore.internal.resources.VirtualComponent;
import org.eclipse.wst.common.componentcore.resources.IVirtualComponent;
@@ -48,43 +48,72 @@
protected void removeReferencedComponents(IProgressMonitor monitor) {
IVirtualComponent sourceComp = (IVirtualComponent) model.getProperty(ICreateReferenceComponentsDataModelProperties.SOURCE_COMPONENT);
- if (!sourceComp.getProject().isAccessible()) return;
+ if (sourceComp == null || !sourceComp.getProject().isAccessible() || sourceComp.isBinary()) return;
- List modList = (List) model.getProperty(ICreateReferenceComponentsDataModelProperties.TARGET_COMPONENT_LIST);
+ IVirtualReference [] existingReferencesArray = sourceComp.getReferences();
+ if(existingReferencesArray == null || existingReferencesArray.length == 0){
+ return;
+ }
+
+ List existingReferences = new ArrayList();
+ for(int i=0;i<existingReferencesArray.length; i++){
+ existingReferences.add(existingReferencesArray[i]);
+ }
+
+ String deployPath = model.getStringProperty( ICreateReferenceComponentsDataModelProperties.TARGET_COMPONENTS_DEPLOY_PATH );
+ IPath path = new Path( deployPath );
+
+ List modList = (List) model.getProperty(ICreateReferenceComponentsDataModelProperties.TARGET_COMPONENT_LIST);
List targetprojectList = new ArrayList();
- for (int i = 0; i < modList.size(); i++) {
+ for (int i = 0; i < modList.size() && !existingReferences.isEmpty(); i++) {
IVirtualComponent comp = (IVirtualComponent) modList.get(i);
- if (comp==null || sourceComp==null)
+ if (comp==null )
continue;
- IVirtualReference ref = sourceComp.getReference(comp.getName());
- if( ref != null && ref.getReferencedComponent() != null && ref.getReferencedComponent().isBinary()){
+
+ IVirtualReference ref = findMatchingReference(existingReferences, comp, path);
+ //if a ref was found matching the specified deployPath, then remove it
+ if(ref != null){
removeRefereneceInComponent(sourceComp, ref);
- }else if(ref != null){
- if (Arrays.asList(comp.getReferencingComponents()).contains(sourceComp)) {
-
- String deployPath = model.getStringProperty( ICreateReferenceComponentsDataModelProperties.TARGET_COMPONENTS_DEPLOY_PATH );
- IPath path = new Path( deployPath );
-
- if( ref.getRuntimePath() != null && path != null && ref.getRuntimePath().equals( path )){
- removeRefereneceInComponent(sourceComp,sourceComp.getReference(comp.getName()));
- IProject targetProject = comp.getProject();
- targetprojectList.add(targetProject);
- }
- }
+ existingReferences.remove(ref);
+ //after removing the ref, check to see if it was the last ref removed to that component
+ //and if it was, then also remove the project reference
+ ref = findMatchingReference(existingReferences, comp);
+ if(ref == null){
+ IProject targetProject = comp.getProject();
+ targetprojectList.add(targetProject);
+ }
}
}
try {
ProjectUtilities.removeReferenceProjects(sourceComp.getProject(),targetprojectList);
} catch (CoreException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
+ Logger.getLogger().logError(e);
}
}
+ private IVirtualReference findMatchingReference(List existingReferences, IVirtualComponent comp, IPath path) {
+ for(int i=0;i<existingReferences.size(); i++){
+ IVirtualReference ref = (IVirtualReference)existingReferences.get(i);
+ IVirtualComponent c = ref.getReferencedComponent();
+ if(c != null && c.getName().equals(comp.getName())){
+ if(path == null){
+ return ref;
+ } else if(path.equals(ref.getRuntimePath())){
+ return ref;
+ }
+ }
+ }
+ return null;
+ }
+
+ private IVirtualReference findMatchingReference(List existingReferences, IVirtualComponent comp) {
+ return findMatchingReference(existingReferences, comp, null);
+ }
+
protected void removeRefereneceInComponent(IVirtualComponent component, IVirtualReference reference) {
((VirtualComponent)component.getComponent()).removeReference(reference);
}
diff --git a/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/operation/ServerContextRootDataModelProvider.java b/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/operation/ServerContextRootDataModelProvider.java
new file mode 100644
index 0000000..01ded49
--- /dev/null
+++ b/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/operation/ServerContextRootDataModelProvider.java
@@ -0,0 +1,39 @@
+package org.eclipse.wst.common.componentcore.internal.operation;
+
+/*******************************************************************************
+ * Copyright (c) 2008 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+
+import java.util.Set;
+
+import org.eclipse.wst.common.componentcore.datamodel.properties.IServerContextRootDataModelProperties;
+import org.eclipse.wst.common.frameworks.datamodel.AbstractDataModelProvider;
+import org.eclipse.wst.common.frameworks.datamodel.IDataModelOperation;
+
+public class ServerContextRootDataModelProvider
+ extends AbstractDataModelProvider
+ implements IServerContextRootDataModelProperties{
+
+ public ServerContextRootDataModelProvider(){
+ super();
+ }
+
+ public Set getPropertyNames() {
+ Set names = super.getPropertyNames();
+ names.add(PROJECT);
+ names.add(CONTEXT_ROOT);
+ return names;
+ }
+
+ public IDataModelOperation getDefaultOperation() {
+ return new ServerContextRootUpdateOperation(model);
+ }
+
+}
diff --git a/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/operation/ServerContextRootUpdateOperation.java b/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/operation/ServerContextRootUpdateOperation.java
new file mode 100644
index 0000000..962b731
--- /dev/null
+++ b/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/operation/ServerContextRootUpdateOperation.java
@@ -0,0 +1,45 @@
+package org.eclipse.wst.common.componentcore.internal.operation;
+
+/*******************************************************************************
+ * Copyright (c) 2008 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+
+import org.eclipse.core.commands.ExecutionException;
+import org.eclipse.core.resources.IProject;
+import org.eclipse.core.runtime.IAdaptable;
+import org.eclipse.core.runtime.IProgressMonitor;
+import org.eclipse.core.runtime.IStatus;
+import org.eclipse.wst.common.componentcore.ComponentCore;
+import org.eclipse.wst.common.componentcore.datamodel.properties.IServerContextRootDataModelProperties;
+import org.eclipse.wst.common.componentcore.internal.util.IModuleConstants;
+import org.eclipse.wst.common.componentcore.resources.IVirtualComponent;
+import org.eclipse.wst.common.frameworks.datamodel.AbstractDataModelOperation;
+import org.eclipse.wst.common.frameworks.datamodel.IDataModel;
+
+public class ServerContextRootUpdateOperation
+ extends AbstractDataModelOperation
+ implements IServerContextRootDataModelProperties{
+
+
+ public ServerContextRootUpdateOperation(IDataModel model) {
+ super(model);
+ }
+
+ public IStatus execute(IProgressMonitor monitor, IAdaptable info) throws ExecutionException {
+ IProject project = (IProject)model.getProperty( IServerContextRootDataModelProperties.PROJECT );
+ String contextRoot = model.getStringProperty( IServerContextRootDataModelProperties.CONTEXT_ROOT );
+ if (contextRoot != null) {
+ IVirtualComponent comp = ComponentCore.createComponent(project);
+ comp.setMetaProperty(IModuleConstants.CONTEXTROOT, contextRoot);
+ }
+ return OK_STATUS;
+ }
+
+}
diff --git a/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/resources/ResourceTimestampMappings.java b/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/resources/ResourceTimestampMappings.java
index 6182b44..47710ab 100644
--- a/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/resources/ResourceTimestampMappings.java
+++ b/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/resources/ResourceTimestampMappings.java
@@ -1,11 +1,13 @@
-/***************************************************************************************************
- * Copyright (c) 2003, 2004 IBM Corporation and others. All rights reserved. This program and the
- * accompanying materials are made available under the terms of the Eclipse Public License v1.0
+/*******************************************************************************
+ * Copyright (c) 2003, 2006 IBM Corporation 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: IBM Corporation - initial API and implementation
- **************************************************************************************************/
+ *
+ * Contributors:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
package org.eclipse.wst.common.componentcore.internal.resources;
import java.util.HashMap;
diff --git a/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/resources/VirtualArchiveComponent.java b/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/resources/VirtualArchiveComponent.java
index 0e5410a..0d66c2f 100644
--- a/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/resources/VirtualArchiveComponent.java
+++ b/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/resources/VirtualArchiveComponent.java
@@ -1,5 +1,5 @@
/*******************************************************************************
- * Copyright (c) 2003, 2005 IBM Corporation and others.
+ * Copyright (c) 2003, 2007 IBM Corporation 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
@@ -16,7 +16,6 @@
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IAdaptable;
@@ -36,19 +35,23 @@
public static final Class ADAPTER_TYPE = VirtualArchiveComponent.class;
public static final String LIBARCHIVETYPE = "lib";
public static final String VARARCHIVETYPE = "var";
-
+ /**
+ * VirtualArchiveComponent type for VirtualArchiveComponents that represent classpath component dependencies.
+ */
+ public static final String CLASSPATHARCHIVETYPE = "cpe"; //$NON-NLS-1
+
private static final IVirtualReference[] NO_REFERENCES = new VirtualReference[0];
private static final IVirtualComponent[] NO_COMPONENTS = new VirtualComponent[0];
- private static final IResource[] NO_RESOURCES = null;
+// private static final IResource[] NO_RESOURCES = null;
private static final IVirtualResource[] NO_VIRTUAL_RESOURCES = null;
private static final Properties NO_PROPERTIES = new Properties();
private static final IPath[] NO_PATHS = new Path[0];
- private IPath runtimePath;
+// private IPath runtimePath;
private IProject componentProject;
- private IVirtualFolder rootFolder;
+// private IVirtualFolder rootFolder;
private int flag = 1;
- private String archiveLocation;
+// private String archiveLocation;
private IPath archivePath;
@@ -61,7 +64,7 @@
throw new NullPointerException();
}
componentProject = aComponentProject;
- runtimePath = aRuntimePath;
+// runtimePath = aRuntimePath;
String archivePathString = archiveLocation.substring(4, archiveLocation.length());
archiveType = archiveLocation.substring(0, archiveLocation.length() - archivePathString.length() -1);
@@ -240,12 +243,10 @@
IFile file = getProject().getFile(archivePath);
if(file.exists())
loc = file.getLocation();
- else {
- if( archivePath.segmentCount() >= 2 ){
- file = ResourcesPlugin.getWorkspace().getRoot().getFile(archivePath);
- if(file.exists())
- loc = file.getLocation();
- }
+ else if(archivePath.segmentCount() > 1) {
+ file = ResourcesPlugin.getWorkspace().getRoot().getFile(archivePath);
+ if(file.exists())
+ loc = file.getLocation();
}
// this is a file on the local filesystem
if(loc != null)
@@ -258,7 +259,7 @@
File diskFile = new File(osPath);
return diskFile;
}
-
+
public String toString() {
if(archivePath != null){
return componentProject + " " +archivePath;
diff --git a/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/resources/VirtualComponent.java b/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/resources/VirtualComponent.java
index a196265..104db30 100644
--- a/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/resources/VirtualComponent.java
+++ b/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/resources/VirtualComponent.java
@@ -1,5 +1,5 @@
/*******************************************************************************
- * Copyright (c) 2003, 2005 IBM Corporation and others.
+ * Copyright (c) 2003, 2006 IBM Corporation 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
@@ -14,6 +14,7 @@
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
+import java.util.Map;
import java.util.Properties;
import org.eclipse.core.resources.IProject;
@@ -113,7 +114,7 @@
if(value == null){
value = ""; //$NON-NLS-1$
String message = "WARNING: The component file in "+getProject().getName()+" has no value defined for the property: "+name; //$NON-NLS-1$//$NON-NLS-2$
- ModulecorePlugin.getDefault().logError(IStatus.ERROR, message, null);
+ ModulecorePlugin.logError(IStatus.ERROR, message, null);
}
props.setProperty(name, value);
}
@@ -205,9 +206,11 @@
List metaResources = new ArrayList();
try {
moduleCore = StructureEdit.getStructureEditForRead(getProject());
- WorkbenchComponent component = moduleCore.getComponent();
- if (component != null)
- metaResources.addAll(component.getMetadataResources());
+ if (moduleCore != null) {
+ WorkbenchComponent component = moduleCore.getComponent();
+ if (component != null)
+ metaResources.addAll(component.getMetadataResources());
+ }
} finally {
if (moduleCore != null) {
moduleCore.dispose();
@@ -265,6 +268,10 @@
}
}
+ public IVirtualReference[] getReferences(Map<String, Object> options) {
+ return getReferences();
+ }
+
public IVirtualReference[] getReferences() {
StructureEdit core = null;
List references = new ArrayList();
@@ -322,7 +329,9 @@
referencedComponent.setArchiveName(references[i].getArchiveName());
}
//clean up any old obsolete references
- cleanUpReferences(component);
+ if (component != null){
+ cleanUpReferences(component);
+ }
} finally {
if(core != null) {
core.saveIfNecessary(null);
diff --git a/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/resources/VirtualContainer.java b/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/resources/VirtualContainer.java
index eb9cde6..51f4f15 100644
--- a/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/resources/VirtualContainer.java
+++ b/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/resources/VirtualContainer.java
@@ -1,5 +1,5 @@
/*******************************************************************************
- * Copyright (c) 2003, 2005 IBM Corporation and others.
+ * Copyright (c) 2003, 2007 IBM Corporation 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
@@ -18,7 +18,6 @@
import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.ResourcesPlugin;
@@ -32,6 +31,7 @@
import org.eclipse.wst.common.componentcore.internal.WorkbenchComponent;
import org.eclipse.wst.common.componentcore.internal.impl.ResourceTreeNode;
import org.eclipse.wst.common.componentcore.internal.impl.ResourceTreeRoot;
+import org.eclipse.wst.common.componentcore.resources.IVirtualComponent;
import org.eclipse.wst.common.componentcore.resources.IVirtualContainer;
import org.eclipse.wst.common.componentcore.resources.IVirtualFile;
import org.eclipse.wst.common.componentcore.resources.IVirtualFolder;
@@ -122,14 +122,14 @@
}
/**
- * @see IFolder#getFile(java.lang.String)
+ * @see org.eclipse.core.resources.IFolder#getFile(java.lang.String)
*/
public IVirtualFile getFile(String name) {
return new VirtualFile(getProject(), getRuntimePath().append(name));
}
/**
- * @see IFolder#getFolder(java.lang.String)
+ * @see org.eclipse.core.resources.IFolder#getFolder(java.lang.String)
*/
public IVirtualFolder getFolder(String name) {
return ComponentCore.createFolder(getProject(), getRuntimePath().append(name));
@@ -156,7 +156,10 @@
List virtualResources = new ArrayList(); // result
Set allNames = new HashSet();
// Ignore all meta data paths in the virtual container resource set
- IPath[] metaPaths = getComponent().getMetaResources();
+ IVirtualComponent component = getComponent();
+ if (component == null)
+ return new IVirtualResource[0];
+ IPath[] metaPaths = component.getMetaResources();
for (int i = 0; i < metaPaths.length; i++) {
String localName = getLocalName(metaPaths[i]);
if (localName != null)
@@ -240,7 +243,7 @@
}
/**
- * @see IFolder#createLink(org.eclipse.core.runtime.IPath, int,
+ * @see org.eclipse.core.resources.IFolder#createLink(org.eclipse.core.runtime.IPath, int,
* org.eclipse.core.runtime.IProgressMonitor)
*/
public void createLink(IPath aProjectRelativeLocation, int updateFlags, IProgressMonitor monitor) throws CoreException {
diff --git a/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/resources/VirtualFile.java b/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/resources/VirtualFile.java
index 57480a2..ee9ec04 100644
--- a/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/resources/VirtualFile.java
+++ b/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/resources/VirtualFile.java
@@ -1,5 +1,5 @@
/*******************************************************************************
- * Copyright (c) 2003, 2005 IBM Corporation and others.
+ * Copyright (c) 2003, 2007 IBM Corporation 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
@@ -14,7 +14,6 @@
import java.util.List;
import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.CoreException;
@@ -42,7 +41,7 @@
}
/**
- * @see IFolder#createLink(org.eclipse.core.runtime.IPath, int,
+ * @see org.eclipse.core.resources.IFolder#createLink(org.eclipse.core.runtime.IPath, int,
* org.eclipse.core.runtime.IProgressMonitor)
*/
public void createLink(IPath aProjectRelativeLocation, int updateFlags, IProgressMonitor monitor) throws CoreException {
diff --git a/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/resources/VirtualReference.java b/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/resources/VirtualReference.java
index 272cbb4..007b1ce 100644
--- a/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/resources/VirtualReference.java
+++ b/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/resources/VirtualReference.java
@@ -1,5 +1,5 @@
/*******************************************************************************
- * Copyright (c) 2003, 2005 IBM Corporation and others.
+ * Copyright (c) 2003, 2006 IBM Corporation 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
diff --git a/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/resources/VirtualResource.java b/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/resources/VirtualResource.java
index c5ec204..5f637f9 100644
--- a/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/resources/VirtualResource.java
+++ b/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/resources/VirtualResource.java
@@ -1,5 +1,5 @@
/*******************************************************************************
- * Copyright (c) 2003, 2005 IBM Corporation and others.
+ * Copyright (c) 2003, 2006 IBM Corporation 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
@@ -45,7 +45,7 @@
private static final String EMPTY_STRING = ""; //$NON-NLS-1$
private IVirtualComponent component;
private String resourceType;
-
+
private final ResourceTimestampMappings mapping = new ResourceTimestampMappings();
@@ -70,7 +70,8 @@
WorkbenchComponent aComponent = moduleCore.getComponent();
ComponentResource[] resources = aComponent.findResourcesByRuntimePath(getRuntimePath());
aComponent.getResources().removeAll(Arrays.asList(resources));
- } finally {
+ }
+ finally {
if (moduleCore != null) {
moduleCore.saveIfNecessary(monitor);
moduleCore.dispose();
@@ -82,12 +83,13 @@
protected abstract void doDeleteRealResources(int updateFlags, IProgressMonitor monitor) throws CoreException;
public boolean exists() {
- // verify all underlying resources exist for the virtual resource to exist
+ // verify all underlying resources exist for the virtual resource to
+ // exist
IResource[] resources = getUnderlyingResources();
- if (resources==null || resources.length==0)
+ if (resources == null || resources.length == 0)
return false;
- for (int i=0; i<resources.length; i++) {
- if (resources[i]==null || !resources[i].exists())
+ for (int i = 0; i < resources.length; i++) {
+ if (resources[i] == null || !resources[i].exists())
return false;
}
return true;
@@ -112,11 +114,12 @@
}
public IPath[] getProjectRelativePaths() {
-
+
WorkbenchComponent aComponent = getReadOnlyComponent();
if (aComponent != null) {
ResourceTreeRoot root = ResourceTreeRoot.getDeployResourceTreeRoot(aComponent);
- // still need some sort of loop here to search subpieces of the runtime path.
+ // still need some sort of loop here to search subpieces of the
+ // runtime path.
ComponentResource[] componentResources = null;
if (root != null) {
@@ -124,29 +127,32 @@
IPath searchPath = null;
do {
searchPath = (searchPath == null) ? getRuntimePath() : searchPath.removeLastSegments(1);
+ if (searchPath.isAbsolute())
+ searchPath = searchPath.makeRelative();
componentResources = root.findModuleResources(searchPath, ResourceTreeNode.CREATE_NONE);
estimatedPaths = findBestMatches(componentResources);
- } while (estimatedPaths.length==0 && canSearchContinue(componentResources, searchPath));
- if (estimatedPaths==null || estimatedPaths.length==0)
- return new IPath[] {getRuntimePath()};
+ }
+ while (estimatedPaths.length == 0 && canSearchContinue(componentResources, searchPath));
+ if (estimatedPaths == null || estimatedPaths.length == 0)
+ return new IPath[]{getRuntimePath()};
return estimatedPaths;
}
- }
-
- return new IPath[] {getRuntimePath()};
+ }
+
+ return new IPath[]{getRuntimePath()};
}
- public IPath getProjectRelativePath() {
- if (getRuntimePath().equals(new Path("/"))) {
+ public IPath getProjectRelativePath() {
+ if (getRuntimePath().equals(new Path("/"))) {
WorkbenchComponent aComponent = getReadOnlyComponent();
if (aComponent != null) {
if (((WorkbenchComponentImpl) aComponent).getDefaultSourceRoot() != null)
return ((WorkbenchComponentImpl) aComponent).getDefaultSourceRoot();
- }
+ }
}
return getProjectRelativePaths()[0];
}
-
+
private boolean canSearchContinue(ComponentResource[] componentResources, IPath searchPath) {
return (searchPath.segmentCount() > 0);
}
@@ -164,7 +170,7 @@
if (currentPath.segmentCount() == aRuntimePath.segmentCount()) {
result.add(theComponentResources[i].getSourcePath());
continue;
- }
+ }
currentMatchLength = currentPath.matchingFirstSegments(aRuntimePath);
if (currentMatchLength == currentPath.segmentCount() && currentMatchLength > bestMatchLength) {
bestMatchLength = currentMatchLength;
@@ -174,15 +180,15 @@
}
}
}
- if (result.size()>0)
+ if (result.size() > 0)
return (IPath[]) result.toArray(new IPath[result.size()]);
if (estimatedPath == null)
- return new IPath[] {};
- return new IPath[] {estimatedPath};
+ return new IPath[]{};
+ return new IPath[]{estimatedPath};
}
public String getName() {
- if (getRuntimePath().segmentCount()>0)
+ if (getRuntimePath().segmentCount() > 0)
return getRuntimePath().lastSegment();
return getRuntimePath().toString();
}
@@ -192,8 +198,8 @@
component = ComponentCore.createComponent(getProject());
return component;
}
-
- //returns null if the folder is already the root folder
+
+ // returns null if the folder is already the root folder
public IVirtualContainer getParent() {
if (getRuntimePath().segmentCount() >= 1)
return ComponentCore.createFolder(getProject(), getRuntimePath().removeLastSegments(1));
@@ -241,25 +247,25 @@
}
public void setResourceType(String aResourceType) {
- resourceType = aResourceType;
+ resourceType = aResourceType;
WorkbenchComponent aComponent = getReadOnlyComponent();
ComponentResource[] resources = aComponent.findResourcesByRuntimePath(getRuntimePath());
for (int i = 0; i < resources.length; i++) {
resources[i].setResourceType(aResourceType);
}
-
+
}
// TODO Fetch the resource type from the model.
public String getResourceType() {
- if (null == resourceType) {
+ if (null == resourceType) {
WorkbenchComponent aComponent = getReadOnlyComponent();
ComponentResource[] resources = aComponent.findResourcesByRuntimePath(getRuntimePath());
for (int i = 0; i < resources.length; i++) {
resourceType = resources[i].getResourceType();
return resourceType;
}
-
+
}
resourceType = ""; //$NON-NLS-1$
return resourceType;
@@ -281,48 +287,58 @@
return aRuntimePath.isPrefixOf(getRuntimePath());
}
- /* (non-Javadoc)
- * @see org.eclipse.wst.common.componentcore.resources.IVirtualResource#removeLink(org.eclipse.core.runtime.IPath, int, org.eclipse.core.runtime.IProgressMonitor)
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.eclipse.wst.common.componentcore.resources.IVirtualResource#removeLink(org.eclipse.core.runtime.IPath,
+ * int, org.eclipse.core.runtime.IProgressMonitor)
*/
public void removeLink(IPath aProjectRelativeLocation, int updateFlags, IProgressMonitor monitor) throws CoreException {
StructureEdit moduleCore = null;
try {
moduleCore = StructureEdit.getStructureEditForWrite(getProject());
WorkbenchComponent component = moduleCore.getComponent();
- ResourceTreeRoot root = ResourceTreeRoot.getDeployResourceTreeRoot(component);
- ComponentResource[] resources = root.findModuleResources(getRuntimePath(), ResourceTreeNode.CREATE_NONE);
- if (resources.length > 0) {
- for (int resourceIndx = 0; resourceIndx < resources.length; resourceIndx++) {
- if (aProjectRelativeLocation.makeAbsolute().equals(resources[resourceIndx].getSourcePath())) {
- component.getResources().remove(resources[resourceIndx]);
+ if (component != null) {
+ ResourceTreeRoot root = ResourceTreeRoot.getDeployResourceTreeRoot(component);
+ ComponentResource[] resources = root.findModuleResources(getRuntimePath(), ResourceTreeNode.CREATE_NONE);
+ if (resources.length > 0) {
+ for (int resourceIndx = 0; resourceIndx < resources.length; resourceIndx++) {
+ if (aProjectRelativeLocation.makeAbsolute().equals(resources[resourceIndx].getSourcePath())) {
+ component.getResources().remove(resources[resourceIndx]);
+ }
}
}
}
- } finally {
+ }
+ finally {
if (moduleCore != null) {
- moduleCore.saveIfNecessary(monitor);
+ if (component != null)
+ moduleCore.saveIfNecessary(monitor);
moduleCore.dispose();
}
}
}
-
+
protected final WorkbenchComponent getReadOnlyComponent() {
- if(!mapping.hasChanged(getProject()) && mapping.hasCacheData(getProject()))
+ if (!mapping.hasChanged(getProject()) && mapping.hasCacheData(getProject()))
return (WorkbenchComponent) mapping.getData(getProject());
-
+
StructureEdit moduleCore = null;
WorkbenchComponent component = null;
try {
moduleCore = StructureEdit.getStructureEditForRead(getProject());
- component = moduleCore.getComponent();
- mapping.mark(getProject(), component);
- } finally {
- if (moduleCore != null) {
+ if (moduleCore != null) {
+ component = moduleCore.getComponent();
+ mapping.mark(getProject(), component);
+ }
+ }
+ finally {
+ if (moduleCore != null) {
moduleCore.dispose();
}
}
return component;
-
-
+
+
}
}
diff --git a/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/util/ArtifactEditAdapterFactory.java b/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/util/ArtifactEditAdapterFactory.java
index a37da71..14d94f8 100644
--- a/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/util/ArtifactEditAdapterFactory.java
+++ b/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/util/ArtifactEditAdapterFactory.java
@@ -1,5 +1,5 @@
/*******************************************************************************
- * Copyright (c) 2003, 2005 IBM Corporation and others.
+ * Copyright (c) 2003, 2007 IBM Corporation 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
@@ -19,14 +19,11 @@
import org.eclipse.wst.common.componentcore.ArtifactEdit;
import org.eclipse.wst.common.componentcore.ModuleCoreNature;
import org.eclipse.wst.common.componentcore.internal.ArtifactEditModel;
-import org.eclipse.wst.common.componentcore.internal.ModulecorePlugin;
import org.eclipse.wst.common.componentcore.internal.impl.ArtifactEditModelFactory;
import org.eclipse.wst.common.componentcore.internal.impl.ModuleURIUtil;
import org.eclipse.wst.common.componentcore.resources.IVirtualComponent;
import org.eclipse.wst.common.internal.emfworkbench.edit.EditModelRegistry;
import org.eclipse.wst.common.internal.emfworkbench.integration.EditModel;
-import org.eclipse.wst.common.project.facet.core.IFacetedProject;
-import org.eclipse.wst.common.project.facet.core.ProjectFacetsManager;
/**
* <p>
@@ -36,9 +33,9 @@
* Adapts {@see ArtifactEditModel} to an {@see ArtifactEdit)
* instance facade, if possible. The following class is
* registered with the Platform Adapter Manager in
- * {@see ModulecorePlugin#start(BundleContext)}
+ * {@see org.eclipse.wst.common.componentcore.internal.ModulecorePlugin#start(BundleContext)}
* </p>
- * @see ModulecorePlugin
+ * @see org.eclipse.wst.common.componentcore.internal.ModulecorePlugin
*/
public class ArtifactEditAdapterFactory implements IAdapterFactory {
@@ -61,7 +58,6 @@
Map params = new HashMap();
params.put(ArtifactEditModelFactory.PARAM_MODULE_URI, componentURI);
try {
- IFacetedProject facetedProject = ProjectFacetsManager.create(aProject);
String[] editModelIDs = EditModelRegistry.getInstance().getRegisteredEditModelIDs();
for (int i=0; i<editModelIDs.length; i++) {
try {
diff --git a/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/util/ArtifactEditRegistryReader.java b/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/util/ArtifactEditRegistryReader.java
index 96c7895..1eb05c3 100644
--- a/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/util/ArtifactEditRegistryReader.java
+++ b/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/util/ArtifactEditRegistryReader.java
@@ -1,5 +1,5 @@
/*******************************************************************************
- * Copyright (c) 2003, 2005 IBM Corporation and others.
+ * Copyright (c) 2003, 2006 IBM Corporation 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
diff --git a/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/util/ComponentImplManager.java b/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/util/ComponentImplManager.java
index 01dd80a..60a9feb 100644
--- a/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/util/ComponentImplManager.java
+++ b/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/util/ComponentImplManager.java
@@ -1,10 +1,10 @@
/*******************************************************************************
- * Copyright (c) 2003, 2005 IBM Corporation and others.
+ * Copyright (c) 2003, 2007 IBM Corporation 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:
* IBM Corporation - initial API and implementation
*******************************************************************************/
@@ -43,7 +43,7 @@
private static final String ATT_CLASS = "class"; //$NON-NLS-1$
private static final ComponentImplManager instance = new ComponentImplManager();
- private static final Object LOAD_FAILED = new Object();
+// private static final Object LOAD_FAILED = new Object();
private final Map/* <String, ComponentImplDescriptor> */ descriptors = new Hashtable();
@@ -169,6 +169,23 @@
return new VirtualComponent(project, new Path("/")); //$NON-NLS-1$
}
+ public IVirtualComponent createComponent(IProject project, boolean checkSettings) {
+ if (checkSettings)
+ return createComponent(project);
+ try {
+ IComponentImplFactory factory = findFactoryForProject(project);
+ if(null != factory){
+ return factory.createComponent(project);
+ }
+ } catch (Exception e) {
+ // Just return a default component
+ }
+ if (ModuleCoreNature.getModuleCoreNature(project) == null){
+ return null;
+ }
+ return new VirtualComponent(project, new Path("/")); //$NON-NLS-1$
+ }
+
public IVirtualComponent createArchiveComponent(IProject aProject, String aComponentName) {
try {
IComponentImplFactory factory = findFactoryForProject(aProject);
diff --git a/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/util/ComponentResolver.java b/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/util/ComponentResolver.java
index f480993..94f8334 100644
--- a/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/util/ComponentResolver.java
+++ b/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/util/ComponentResolver.java
@@ -1,10 +1,10 @@
/*******************************************************************************
- * Copyright (c) 2001, 2005 IBM Corporation and others.
+ * Copyright (c) 2001, 2007 IBM Corporation 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:
* IBM Corporation - initial API and implementation
*
diff --git a/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/util/ComponentUtilities.java b/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/util/ComponentUtilities.java
index a9596d6..0ddeaf9 100644
--- a/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/util/ComponentUtilities.java
+++ b/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/util/ComponentUtilities.java
@@ -1,5 +1,5 @@
/*******************************************************************************
- * Copyright (c) 2003, 2005 IBM Corporation and others.
+ * Copyright (c) 2003, 2006 IBM Corporation 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
@@ -12,8 +12,11 @@
import java.util.ArrayList;
import java.util.Arrays;
+import java.util.HashMap;
import java.util.List;
+import java.util.Map;
+import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
@@ -23,6 +26,7 @@
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
+import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.Path;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.resource.Resource;
@@ -31,6 +35,7 @@
import org.eclipse.wst.common.componentcore.ComponentCore;
import org.eclipse.wst.common.componentcore.ModuleCoreNature;
import org.eclipse.wst.common.componentcore.datamodel.properties.ICreateReferenceComponentsDataModelProperties;
+import org.eclipse.wst.common.componentcore.datamodel.properties.IServerContextRootDataModelProperties;
import org.eclipse.wst.common.componentcore.internal.Property;
import org.eclipse.wst.common.componentcore.internal.StructureEdit;
import org.eclipse.wst.common.componentcore.internal.WorkbenchComponent;
@@ -114,8 +119,12 @@
return null;
IVirtualFolder root = comp.getRootFolder();
IVirtualResource file = root.findMember(aPath);
- if (file != null)
- return (IFile) file.getUnderlyingResource();
+ if (file != null && file.getType() == IVirtualResource.FILE){
+ IResource resource = file.getUnderlyingResource();
+ if(resource.getType() == IResource.FILE){
+ return (IFile) resource;
+ }
+ }
return null;
}
@@ -211,6 +220,18 @@
modHandlesList.addAll(targetComponentProjects);
model.setProperty(ICreateReferenceComponentsDataModelProperties.TARGET_COMPONENT_LIST, modHandlesList);
model.setProperty(ICreateReferenceComponentsDataModelProperties.TARGET_COMPONENTS_DEPLOY_PATH,"/WEB-INF/lib"); //$NON-NLS-1$
+ if(modHandlesList != null){
+ Map map = new HashMap();
+ for(int i=0; i<modHandlesList.size();i++){
+ IVirtualComponent comp = (IVirtualComponent)modHandlesList.get(i);
+ String uri = comp.getName().replace(' ', '_') + ".jar";
+ map.put(comp, uri);
+ }
+ if(map.size() > 0){
+ model.setProperty(ICreateReferenceComponentsDataModelProperties.TARGET_COMPONENTS_TO_URI_MAP, map);
+ }
+ }
+
return new CreateReferenceComponentsOp(model);
}
@@ -305,19 +326,37 @@
*
* @param contextRoot string
*/
- public static void setServerContextRoot(IProject project, String contextRoot) {
- IVirtualComponent comp = ComponentCore.createComponent(project);
- comp.setMetaProperty(IModuleConstants.CONTEXTROOT, contextRoot);
+ public static void setServerContextRoot(IProject project, String newContextRoot) {
+
+ IDataModel model = DataModelFactory.createDataModel(IServerContextRootDataModelProperties.class);
+ model.setProperty(IServerContextRootDataModelProperties.PROJECT, project);
+ model.setStringProperty(IServerContextRootDataModelProperties.CONTEXT_ROOT,
+ newContextRoot);
+
+ try {
+ model.getDefaultOperation().execute(new NullProgressMonitor(), null);
+ }
+ catch (ExecutionException e) {
+ org.eclipse.wst.common.componentcore.internal.ModulecorePlugin.logError(e);
+ }
}
+ /**
+ * @deprecated use {@link #getDeployUriOfComponent(IVirtualReference, String)}
+ * @param reference
+ * @return
+ */
public static String getDeployUriOfUtilComponent(IVirtualReference reference){
+ return ComponentUtilities.getDeployUriOfComponent(reference, ".jar"); //$NON-NLS-1$
+ }
+
+ public static String getDeployUriOfComponent(IVirtualReference reference, String extension) {
String archiveName = reference.getArchiveName();
String uri = null;
- if( archiveName != null && archiveName != "" ){ //$NON-NLS-1$
+ if( archiveName != null && !archiveName.equals("") ){ //$NON-NLS-1$
uri = reference.getRuntimePath() + "/" + reference.getArchiveName(); //$NON-NLS-1$
}else{
- uri = reference.getRuntimePath() + "/" + reference.getReferencedComponent().getProject().getName() + ".jar"; //$NON-NLS-1$ //$NON-NLS-2$
+ uri = reference.getRuntimePath() + "/" + reference.getReferencedComponent().getProject().getName() + extension; //$NON-NLS-1$
}
return uri;
- }
-}
+ }}
diff --git a/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/util/EclipseResourceAdapter.java b/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/util/EclipseResourceAdapter.java
index 95f6623..0109525 100644
--- a/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/util/EclipseResourceAdapter.java
+++ b/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/util/EclipseResourceAdapter.java
@@ -1,5 +1,5 @@
/*******************************************************************************
- * Copyright (c) 2003, 2005 IBM Corporation and others.
+ * Copyright (c) 2003, 2007 IBM Corporation 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
@@ -51,15 +51,17 @@
IProject container = null;
ComponentResource moduleResource = (ComponentResource) getTarget();
- IPath sourcePath = moduleResource.getSourcePath();
- if (moduleResource.getOwningProject() != null)
- container = moduleResource.getOwningProject();
- else
- container = StructureEdit.getContainingProject(moduleResource.getComponent());
- if (container != null)
- resource = container.findMember(sourcePath);
- if(resource == null)
- resource = ResourcesPlugin.getWorkspace().getRoot().findMember(sourcePath);
+ if (moduleResource != null) {
+ IPath sourcePath = moduleResource.getSourcePath();
+ if (moduleResource.getOwningProject() != null)
+ container = moduleResource.getOwningProject();
+ else
+ container = StructureEdit.getContainingProject(moduleResource.getComponent());
+ if (container != null)
+ resource = container.findMember(sourcePath);
+ if(resource == null)
+ resource = ResourcesPlugin.getWorkspace().getRoot().findMember(sourcePath);
+ }
}
}
return resource;
diff --git a/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/util/HRefTranslator.java b/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/util/HRefTranslator.java
index f7b59a5..8fba627 100644
--- a/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/util/HRefTranslator.java
+++ b/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/util/HRefTranslator.java
@@ -1,5 +1,5 @@
/*******************************************************************************
- * Copyright (c) 2005 IBM Corporation and others.
+ * Copyright (c) 2005, 2006 IBM Corporation 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
@@ -20,6 +20,7 @@
import org.eclipse.wst.common.componentcore.internal.StructureEdit;
import org.eclipse.wst.common.componentcore.internal.WorkbenchComponent;
import org.eclipse.wst.common.componentcore.resources.IVirtualComponent;
+import org.eclipse.wst.common.internal.emf.resource.CompatibilityXMIResource;
import org.eclipse.wst.common.internal.emf.resource.Translator;
import org.eclipse.wst.common.internal.emf.resource.TranslatorPath;
@@ -64,14 +65,33 @@
* @see org.eclipse.wst.common.internal.emf.resource.Translator#convertStringToValue(java.lang.String,
* org.eclipse.emf.ecore.EObject)
*/
- public Object convertStringToValue(String aValue, EObject anOwner) {
- WorkbenchComponent earComp = (WorkbenchComponent)anOwner.eContainer();
- IVirtualComponent virtualComp = ComponentCore.createComponent(StructureEdit.getContainingProject(earComp));
- ArtifactEdit edit = (ArtifactEdit)virtualComp.getAdapter(ArtifactEdit.class);
- if (edit == null) return null;
- if( edit.getContentModelRoot() == null ) return null;
- Resource res = edit.getContentModelRoot().eResource();
- return res.getEObject(aValue);
+ public Object convertStringToValue(String aValue, EObject anOwner) {
+ Object retVal = null;
+ if (aValue != null)
+ {
+ Resource res = null;
+ try {
+ WorkbenchComponent earComp = (WorkbenchComponent)anOwner.eContainer();
+ IVirtualComponent virtualComp = ComponentCore.createComponent(StructureEdit.getContainingProject(earComp));
+ ArtifactEdit edit = (ArtifactEdit)virtualComp.getAdapter(ArtifactEdit.class);
+ if (edit != null)
+ {
+ EObject contentModelRoot = edit.getContentModelRoot();
+ if( contentModelRoot != null )
+ {
+ res = contentModelRoot.eResource();
+ if (res != null && res instanceof CompatibilityXMIResource)
+ retVal = res.getEObject(aValue);
+ }
+ }
+ } finally {
+// if ((res != null) && res.getResourceSet() != null) {
+// res.getResourceSet().getResources().remove(res);
+// res.unload();
+// }
+ }
+ }
+ return retVal;
}
/*
@@ -82,8 +102,14 @@
*/
public String convertValueToString(Object aValue, EObject anOwner) {
String frag = null;
- if (((EObject)aValue).eResource() != null)
- frag = ((EObject)aValue).eResource().getURIFragment((EObject)aValue);
+ Resource theResource = ((EObject)aValue).eResource();
+ if (theResource != null)
+ {
+ if (theResource instanceof CompatibilityXMIResource)
+ frag = theResource.getURIFragment((EObject)aValue);
+ else
+ frag = null;
+ }
else
frag = EcoreUtil.getID((EObject)aValue);
return frag;
diff --git a/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/util/IComponentImplFactory.java b/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/util/IComponentImplFactory.java
index f38b3f5..8673b16 100644
--- a/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/util/IComponentImplFactory.java
+++ b/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/util/IComponentImplFactory.java
@@ -1,10 +1,10 @@
/*******************************************************************************
- * Copyright (c) 2003, 2005 IBM Corporation and others.
+ * Copyright (c) 2003, 2006 IBM Corporation 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:
* IBM Corporation - initial API and implementation
*******************************************************************************/
diff --git a/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/util/IModuleConstants.java b/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/util/IModuleConstants.java
index e6b2a70..f1c98d0 100644
--- a/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/util/IModuleConstants.java
+++ b/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/util/IModuleConstants.java
@@ -1,5 +1,5 @@
/*******************************************************************************
- * Copyright (c) 2003, 2005 IBM Corporation and others.
+ * Copyright (c) 2003, 2006 IBM Corporation 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
diff --git a/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/util/WTPModulesTranslator.java b/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/util/WTPModulesTranslator.java
index f2210ca..b88af6b 100644
--- a/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/util/WTPModulesTranslator.java
+++ b/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/util/WTPModulesTranslator.java
@@ -1,5 +1,5 @@
/*******************************************************************************
- * Copyright (c) 2005 IBM Corporation and others.
+ * Copyright (c) 2005, 2006 IBM Corporation 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
diff --git a/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/util/WTPModulesXmlMapperI.java b/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/util/WTPModulesXmlMapperI.java
index 13d7c17..9ed9de9 100644
--- a/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/util/WTPModulesXmlMapperI.java
+++ b/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/util/WTPModulesXmlMapperI.java
@@ -1,5 +1,5 @@
/*******************************************************************************
- * Copyright (c) 2005 IBM Corporation and others.
+ * Copyright (c) 2005, 2006 IBM Corporation 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
diff --git a/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/util/ZipFileExporter.java b/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/util/ZipFileExporter.java
index 7be0c31..cc0a5b6 100644
--- a/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/util/ZipFileExporter.java
+++ b/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/util/ZipFileExporter.java
@@ -1,5 +1,5 @@
/*******************************************************************************
- * Copyright (c) 2003, 2005 IBM Corporation and others.
+ * Copyright (c) 2003, 2007 IBM Corporation 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
@@ -28,7 +28,6 @@
*/
public class ZipFileExporter {
private ZipOutputStream outputStream;
- private StringBuffer manifestContents;
private boolean useCompression = true;
diff --git a/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/resources/IVirtualComponent.java b/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/resources/IVirtualComponent.java
index d07c71f..7de081d 100644
--- a/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/resources/IVirtualComponent.java
+++ b/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/resources/IVirtualComponent.java
@@ -1,5 +1,5 @@
/*******************************************************************************
- * Copyright (c) 2003, 2005 IBM Corporation and others.
+ * Copyright (c) 2003, 2006 IBM Corporation 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
diff --git a/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/resources/IVirtualReference.java b/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/resources/IVirtualReference.java
index fd25628..6ef2274 100644
--- a/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/resources/IVirtualReference.java
+++ b/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/resources/IVirtualReference.java
@@ -1,5 +1,5 @@
/*******************************************************************************
- * Copyright (c) 2003, 2005 IBM Corporation and others.
+ * Copyright (c) 2003, 2006 IBM Corporation 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
diff --git a/plugins/org.eclipse.wst.common.modulecore/plugin.properties b/plugins/org.eclipse.wst.common.modulecore/plugin.properties
index aef7448..883476b 100644
--- a/plugins/org.eclipse.wst.common.modulecore/plugin.properties
+++ b/plugins/org.eclipse.wst.common.modulecore/plugin.properties
@@ -1,5 +1,5 @@
###############################################################################
-# Copyright (c) 2003, 2005 IBM Corporation and others.
+# Copyright (c) 2003, 2007 IBM Corporation 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
@@ -9,3 +9,8 @@
# IBM Corporation - initial API and implementation
###############################################################################
provider=Eclipse.org
+
+Bundle-Name.0 = Modulecore Plug-in
+ValidationMarker.name=ModuleCore Validation Marker
+Validator.name=ModuleCore Validator
+Nature.name=Web Properties
\ No newline at end of file
diff --git a/plugins/org.eclipse.wst.common.modulecore/plugin.xml b/plugins/org.eclipse.wst.common.modulecore/plugin.xml
index 2c2fd98..569dd44 100644
--- a/plugins/org.eclipse.wst.common.modulecore/plugin.xml
+++ b/plugins/org.eclipse.wst.common.modulecore/plugin.xml
@@ -15,7 +15,7 @@
<!--============================-->
<extension
id="ModuleCoreNature"
- name="Web Properties"
+ name="%Nature.name"
point="org.eclipse.core.resources.natures">
<runtime>
<run
@@ -70,13 +70,13 @@
<factory
class="org.eclipse.wst.common.componentcore.datamodel.FacetDataModelConfigAdapter$Factory"
adaptableType="org.eclipse.wst.common.frameworks.datamodel.IDataModel">
- <adapter type="org.eclipse.wst.common.project.facet.core.IActionConfig"/>
+ <adapter type="org.eclipse.wst.common.project.facet.core.ActionConfig"/>
</factory>
</extension>
<extension
id="ModuleCoreValidator"
- name="ModuleCore Validator"
+ name="%Validator.name"
point="org.eclipse.wst.validation.validator">
<validator>
<projectNature
@@ -106,7 +106,7 @@
<extension
id="ModuleCoreValidatorMarker"
- name="ModuleCore Validation Marker"
+ name="%ValidationMarker.name"
point="org.eclipse.core.resources.markers">
<super
type="org.eclipse.wst.validation.problemmarker">
diff --git a/plugins/org.eclipse.wst.common.modulecore/schema/componentimpl.exsd b/plugins/org.eclipse.wst.common.modulecore/schema/componentimpl.exsd
index 2ec75cf..667317e 100644
--- a/plugins/org.eclipse.wst.common.modulecore/schema/componentimpl.exsd
+++ b/plugins/org.eclipse.wst.common.modulecore/schema/componentimpl.exsd
@@ -1,10 +1,10 @@
<?xml version='1.0' encoding='UTF-8'?>
<!-- Schema file written by PDE -->
-<schema targetNamespace="org.eclipse.wst.common.modulecore">
+<schema targetNamespace="org.eclipse.wst.common.modulecore" xmlns="http://www.w3.org/2001/XMLSchema">
<annotation>
- <appInfo>
+ <appinfo>
<meta.schema plugin="org.eclipse.wst.common.modulecore" id="componentimpl" name="componentimpl"/>
- </appInfo>
+ </appinfo>
<documentation>
[Enter description of this extension point.]
</documentation>
@@ -33,9 +33,9 @@
<documentation>
</documentation>
- <appInfo>
+ <appinfo>
<meta.attribute translatable="true"/>
- </appInfo>
+ </appinfo>
</annotation>
</attribute>
</complexType>
@@ -50,65 +50,55 @@
</documentation>
</annotation>
</attribute>
- <attribute name="class" use="required">
+ <attribute name="class" type="string" use="required">
<annotation>
<documentation>
</documentation>
+ <appinfo>
+ <meta.attribute kind="java" basedOn=":org.eclipse.wst.common.componentcore.resources.IVirtualComponent"/>
+ </appinfo>
</annotation>
- <simpleType>
- <restriction base="string">
- <enumeration value="instanceof IVirtualComponent">
- </enumeration>
- </restriction>
- </simpleType>
</attribute>
</complexType>
</element>
<annotation>
- <appInfo>
+ <appinfo>
<meta.section type="since"/>
- </appInfo>
+ </appinfo>
<documentation>
[Enter the first release in which this extension point appears.]
</documentation>
</annotation>
<annotation>
- <appInfo>
+ <appinfo>
<meta.section type="examples"/>
- </appInfo>
+ </appinfo>
<documentation>
[Enter extension point usage example here.]
</documentation>
</annotation>
<annotation>
- <appInfo>
+ <appinfo>
<meta.section type="apiInfo"/>
- </appInfo>
+ </appinfo>
<documentation>
[Enter API information here.]
</documentation>
</annotation>
+
<annotation>
- <appInfo>
+ <appinfo>
<meta.section type="implementation"/>
- </appInfo>
+ </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/plugins/org.eclipse.wst.common.modulecore/schema/resourceFactories.exsd b/plugins/org.eclipse.wst.common.modulecore/schema/resourceFactories.exsd
index 08cf3b5..49f7a80 100644
--- a/plugins/org.eclipse.wst.common.modulecore/schema/resourceFactories.exsd
+++ b/plugins/org.eclipse.wst.common.modulecore/schema/resourceFactories.exsd
@@ -1,16 +1,21 @@
<?xml version='1.0' encoding='UTF-8'?>
<!-- Schema file written by PDE -->
-<schema targetNamespace="org.eclipse.wst.common.modulecore">
+<schema targetNamespace="org.eclipse.wst.common.modulecore" xmlns="http://www.w3.org/2001/XMLSchema">
<annotation>
- <appInfo>
+ <appinfo>
<meta.schema plugin="org.eclipse.wst.common.modulecore" id="resourceFactories" name="Resource Factory Association (Internal)"/>
- </appInfo>
+ </appinfo>
<documentation>
An *internal* extension point that declares an association between a short-segment filename and a Resource.Factory.
</documentation>
</annotation>
<element name="extension">
+ <annotation>
+ <appinfo>
+ <meta.element />
+ </appinfo>
+ </annotation>
<complexType>
<sequence>
<element ref="resourceFactory"/>
@@ -34,9 +39,9 @@
<documentation>
</documentation>
- <appInfo>
+ <appinfo>
<meta.attribute translatable="true"/>
- </appInfo>
+ </appinfo>
</annotation>
</attribute>
</complexType>
@@ -45,24 +50,64 @@
<element name="resourceFactory">
<annotation>
<documentation>
- Associates a short name (e.g. "web.xml") with the appropriate Resource.Factory to create the Resource type when loading files of the declared shortname.
+ Associates a short name (e.g. "web.xml") with the appropriate Resource.Factory to create the Resource type when loading files of the declared shortname.
</documentation>
</annotation>
<complexType>
+ <sequence>
+ <element ref="contentTypeBinding" minOccurs="0" maxOccurs="1"/>
+ </sequence>
<attribute name="class" type="string" use="required">
<annotation>
<documentation>
Declares an implementation of <code>org.eclipse.emf.ecore.resource.Resource.Factory</code>.
</documentation>
- <appInfo>
+ <appinfo>
<meta.attribute kind="java" basedOn="org.eclipse.emf.ecore.resource.Resource.Factory"/>
- </appInfo>
+ </appinfo>
</annotation>
</attribute>
- <attribute name="shortSegment" type="string" use="required">
+ <attribute name="shortSegment" type="string">
<annotation>
<documentation>
- Declares the short segment of a filename that the resource factory applies to (e.g. "web.xml").
+ Optionally declares the short segment of a filename that the resource factory applies to (e.g. "web.xml").
+ </documentation>
+ </annotation>
+ </attribute>
+ <attribute name="isDefault" type="boolean" use="default" value="true">
+ <annotation>
+ <documentation>
+ If multiple factories are declared for the same fileName - then the "default" is used.
+ </documentation>
+ </annotation>
+ </attribute>
+ <attribute name="overridesFactoryClass" type="string">
+ <annotation>
+ <documentation>
+ This optional attribute is to resolve conflicts between multiple defeault factories registered to the same content type and short segments. The value should be the fully qualified class name of the factory being overridden.
+ </documentation>
+ <appinfo>
+ <meta.attribute kind="java" basedOn="org.eclipse.emf.ecore.resource.Resource.Factory:"/>
+ </appinfo>
+ </annotation>
+ </attribute>
+ </complexType>
+ </element>
+
+ <element name="contentTypeBinding">
+ <annotation>
+ <appinfo>
+ <meta.element labelAttribute="contentTypeId"/>
+ </appinfo>
+ <documentation>
+ Advertises that the containing editor understands the given content type and is suitable for editing files of that type.
+ </documentation>
+ </annotation>
+ <complexType>
+ <attribute name="contentTypeId" type="string" use="required">
+ <annotation>
+ <documentation>
+ The content type identifier. This is an ID defined by the 'org.eclipse.core.runtime.contentTypes' extension point.
</documentation>
</annotation>
</attribute>
@@ -70,48 +115,40 @@
</element>
<annotation>
- <appInfo>
+ <appinfo>
<meta.section type="since"/>
- </appInfo>
+ </appinfo>
<documentation>
[Enter the first release in which this extension point appears.]
</documentation>
</annotation>
<annotation>
- <appInfo>
+ <appinfo>
<meta.section type="examples"/>
- </appInfo>
+ </appinfo>
<documentation>
[Enter extension point usage example here.]
</documentation>
</annotation>
<annotation>
- <appInfo>
+ <appinfo>
<meta.section type="apiInfo"/>
- </appInfo>
+ </appinfo>
<documentation>
[Enter API information here.]
</documentation>
</annotation>
<annotation>
- <appInfo>
+ <appinfo>
<meta.section type="implementation"/>
- </appInfo>
+ </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/plugins/org.eclipse.wst.validation.ui/.classpath b/plugins/org.eclipse.wst.validation.ui/.classpath
new file mode 100644
index 0000000..7acdda6
--- /dev/null
+++ b/plugins/org.eclipse.wst.validation.ui/.classpath
@@ -0,0 +1,9 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<classpath>
+ <classpathentry kind="src" path="validateui"/>
+ <classpathentry kind="src" path="property_files"/>
+ <classpathentry kind="src" path="vf2"/>
+ <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/J2SE-1.5"/>
+ <classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/>
+ <classpathentry kind="output" path="bin"/>
+</classpath>
diff --git a/plugins/org.eclipse.wst.validation.ui/.cvsignore b/plugins/org.eclipse.wst.validation.ui/.cvsignore
new file mode 100644
index 0000000..b39f8f4
--- /dev/null
+++ b/plugins/org.eclipse.wst.validation.ui/.cvsignore
@@ -0,0 +1,7 @@
+bin
+temp.folder
+build.xml
+runtime
+@dot
+src.zip
+javaCompiler...args
diff --git a/plugins/org.eclipse.wst.validation.ui/.project b/plugins/org.eclipse.wst.validation.ui/.project
new file mode 100644
index 0000000..32471f6
--- /dev/null
+++ b/plugins/org.eclipse.wst.validation.ui/.project
@@ -0,0 +1,26 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<projectDescription>
+ <name>org.eclipse.wst.validation.ui</name>
+ <comment></comment>
+ <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.jdt.core.javanature</nature>
+ <nature>org.eclipse.pde.PluginNature</nature>
+ </natures>
+</projectDescription>
diff --git a/plugins/org.eclipse.wst.validation.ui/.settings/org.eclipse.core.resources.prefs b/plugins/org.eclipse.wst.validation.ui/.settings/org.eclipse.core.resources.prefs
new file mode 100644
index 0000000..9306ade
--- /dev/null
+++ b/plugins/org.eclipse.wst.validation.ui/.settings/org.eclipse.core.resources.prefs
@@ -0,0 +1,3 @@
+#Mon May 08 09:24:56 EDT 2006
+eclipse.preferences.version=1
+encoding/<project>=ISO-8859-1
diff --git a/plugins/org.eclipse.wst.validation.ui/.settings/org.eclipse.jdt.core.prefs b/plugins/org.eclipse.wst.validation.ui/.settings/org.eclipse.jdt.core.prefs
new file mode 100644
index 0000000..7f1fe24
--- /dev/null
+++ b/plugins/org.eclipse.wst.validation.ui/.settings/org.eclipse.jdt.core.prefs
@@ -0,0 +1,71 @@
+#Tue Feb 12 12:30:46 EST 2008
+eclipse.preferences.version=1
+org.eclipse.jdt.core.codeComplete.argumentPrefixes=
+org.eclipse.jdt.core.codeComplete.argumentSuffixes=
+org.eclipse.jdt.core.codeComplete.fieldPrefixes=_
+org.eclipse.jdt.core.codeComplete.fieldSuffixes=
+org.eclipse.jdt.core.codeComplete.localPrefixes=
+org.eclipse.jdt.core.codeComplete.localSuffixes=
+org.eclipse.jdt.core.codeComplete.staticFieldPrefixes=_
+org.eclipse.jdt.core.codeComplete.staticFieldSuffixes=
+org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
+org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.5
+org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve
+org.eclipse.jdt.core.compiler.compliance=1.5
+org.eclipse.jdt.core.compiler.debug.lineNumber=generate
+org.eclipse.jdt.core.compiler.debug.localVariable=generate
+org.eclipse.jdt.core.compiler.debug.sourceFile=generate
+org.eclipse.jdt.core.compiler.problem.annotationSuperInterface=warning
+org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
+org.eclipse.jdt.core.compiler.problem.autoboxing=ignore
+org.eclipse.jdt.core.compiler.problem.deprecation=ignore
+org.eclipse.jdt.core.compiler.problem.deprecationInDeprecatedCode=disabled
+org.eclipse.jdt.core.compiler.problem.deprecationWhenOverridingDeprecatedMethod=disabled
+org.eclipse.jdt.core.compiler.problem.discouragedReference=ignore
+org.eclipse.jdt.core.compiler.problem.emptyStatement=ignore
+org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
+org.eclipse.jdt.core.compiler.problem.fallthroughCase=ignore
+org.eclipse.jdt.core.compiler.problem.fatalOptionalError=disabled
+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=warning
+org.eclipse.jdt.core.compiler.problem.nullReference=ignore
+org.eclipse.jdt.core.compiler.problem.overridingPackageDefaultMethod=warning
+org.eclipse.jdt.core.compiler.problem.parameterAssignment=ignore
+org.eclipse.jdt.core.compiler.problem.possibleAccidentalBooleanAssignment=ignore
+org.eclipse.jdt.core.compiler.problem.rawTypeReference=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=warning
+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=error
+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=error
+org.eclipse.jdt.core.compiler.problem.unusedLabel=error
+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
+org.eclipse.jdt.core.compiler.source=1.5
diff --git a/plugins/org.eclipse.wst.validation.ui/.settings/org.eclipse.jdt.ui.prefs b/plugins/org.eclipse.wst.validation.ui/.settings/org.eclipse.jdt.ui.prefs
new file mode 100644
index 0000000..4638d6c
--- /dev/null
+++ b/plugins/org.eclipse.wst.validation.ui/.settings/org.eclipse.jdt.ui.prefs
@@ -0,0 +1,6 @@
+#Tue Feb 12 12:30:46 EST 2008
+eclipse.preferences.version=1
+org.eclipse.jdt.ui.exception.name=e
+org.eclipse.jdt.ui.gettersetter.use.is=true
+org.eclipse.jdt.ui.keywordthis=false
+org.eclipse.jdt.ui.overrideannotation=true
diff --git a/plugins/org.eclipse.wst.validation.ui/META-INF/MANIFEST.MF b/plugins/org.eclipse.wst.validation.ui/META-INF/MANIFEST.MF
new file mode 100644
index 0000000..6e0dd26
--- /dev/null
+++ b/plugins/org.eclipse.wst.validation.ui/META-INF/MANIFEST.MF
@@ -0,0 +1,21 @@
+Manifest-Version: 1.0
+Bundle-ManifestVersion: 2
+Bundle-Name: %Bundle-Name.0
+Bundle-SymbolicName: org.eclipse.wst.validation.ui; singleton:=true
+Bundle-Version: 1.2.4.qualifier
+Bundle-Activator: org.eclipse.wst.validation.internal.ui.plugin.ValidationUIPlugin
+Bundle-Vendor: %Bundle-Vendor.0
+Bundle-Localization: plugin
+Export-Package: org.eclipse.wst.validation.internal.ui;x-internal:=true,
+ org.eclipse.wst.validation.internal.ui.plugin;x-internal:=true
+Require-Bundle: org.eclipse.ui.ide;bundle-version="[3.4.0,4.0.0)",
+ org.eclipse.core.resources;bundle-version="[3.4.0,4.0.0)",
+ org.eclipse.ui;bundle-version="[3.4.0,4.0.0)",
+ org.eclipse.swt;bundle-version="[3.4.0,4.0.0)",
+ org.eclipse.wst.common.frameworks.ui;bundle-version="[1.1.200,2.0.0)",
+ org.eclipse.core.runtime;bundle-version="[3.4.0,4.0.0)",
+ org.eclipse.wst.common.frameworks;bundle-version="[1.1.200,2.0.0)",
+ org.eclipse.wst.validation;bundle-version="[1.2.0,2.0.0)",
+ org.eclipse.ui.forms;bundle-version="[3.3.100,4.0.0)"
+Bundle-ActivationPolicy: lazy
+Bundle-RequiredExecutionEnvironment: J2SE-1.5
diff --git a/plugins/org.eclipse.wst.validation.ui/about.html b/plugins/org.eclipse.wst.validation.ui/about.html
new file mode 100644
index 0000000..2199df3
--- /dev/null
+++ b/plugins/org.eclipse.wst.validation.ui/about.html
@@ -0,0 +1,34 @@
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN">
+<HTML>
+
+<head>
+<title>About</title>
+<meta http-equiv=Content-Type content="text/html; charset=ISO-8859-1">
+</head>
+
+<BODY lang="EN-US">
+
+<H3>About This Content</H3>
+
+<P>June, 2008</P>
+
+<H3>License</H3>
+
+<P>The Eclipse Foundation makes available all content in this plug-in
+("Content"). Unless otherwise indicated below, the Content is provided to you
+under the terms and conditions of the Eclipse Public License Version 1.0
+("EPL"). A copy of the EPL is available at
+<A href="http://www.eclipse.org/org/documents/epl-v10.php">http://www.eclipse.org/org/documents/epl-v10.php</A>.
+For purposes of the EPL, "Program" will mean the Content.</P>
+
+<P>If you did not receive this Content directly from the Eclipse Foundation, the
+Content is being redistributed by another party ("Redistributor") and different
+terms and conditions may apply to your use of any object code in the Content.
+Check the RedistributorÂ’s license that was provided with the Content. If no such
+license exists, contact the Redistributor. Unless otherwise indicated below, the
+terms and conditions of the EPL still apply to any source code in the Content
+and such source code may be obtained at
+<A href="http://www.eclipse.org/">http://www.eclipse.org/</A>.</P>
+
+</BODY>
+</HTML>
diff --git a/plugins/org.eclipse.wst.validation.ui/build.properties b/plugins/org.eclipse.wst.validation.ui/build.properties
new file mode 100644
index 0000000..1749ccd
--- /dev/null
+++ b/plugins/org.eclipse.wst.validation.ui/build.properties
@@ -0,0 +1,20 @@
+###############################################################################
+# Copyright (c) 2001, 2007 IBM Corporation 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:
+# IBM Corporation - initial API and implementation
+###############################################################################
+bin.includes = .,\
+ plugin.xml,\
+ META-INF/,\
+ about.html,\
+ icons/,\
+ plugin.properties
+source.. = validateui/,\
+ property_files/,\
+ vf2/
+output.. = bin/
diff --git a/plugins/org.eclipse.wst.validation.ui/icons/fail_tbl.gif b/plugins/org.eclipse.wst.validation.ui/icons/fail_tbl.gif
new file mode 100644
index 0000000..9bd9b0c
--- /dev/null
+++ b/plugins/org.eclipse.wst.validation.ui/icons/fail_tbl.gif
Binary files differ
diff --git a/plugins/org.eclipse.wst.validation.ui/icons/fail_tbl_disabled.gif b/plugins/org.eclipse.wst.validation.ui/icons/fail_tbl_disabled.gif
new file mode 100644
index 0000000..91333a1
--- /dev/null
+++ b/plugins/org.eclipse.wst.validation.ui/icons/fail_tbl_disabled.gif
Binary files differ
diff --git a/plugins/org.eclipse.wst.validation.ui/icons/ok_tbl.gif b/plugins/org.eclipse.wst.validation.ui/icons/ok_tbl.gif
new file mode 100644
index 0000000..9cacb96
--- /dev/null
+++ b/plugins/org.eclipse.wst.validation.ui/icons/ok_tbl.gif
Binary files differ
diff --git a/plugins/org.eclipse.wst.validation.ui/icons/ok_tbl_disabled.gif b/plugins/org.eclipse.wst.validation.ui/icons/ok_tbl_disabled.gif
new file mode 100644
index 0000000..1d8900b
--- /dev/null
+++ b/plugins/org.eclipse.wst.validation.ui/icons/ok_tbl_disabled.gif
Binary files differ
diff --git a/plugins/org.eclipse.wst.validation.ui/icons/settings.gif b/plugins/org.eclipse.wst.validation.ui/icons/settings.gif
new file mode 100644
index 0000000..9c99aad
--- /dev/null
+++ b/plugins/org.eclipse.wst.validation.ui/icons/settings.gif
Binary files differ
diff --git a/plugins/org.eclipse.wst.validation.ui/icons/settings_disabled.gif b/plugins/org.eclipse.wst.validation.ui/icons/settings_disabled.gif
new file mode 100644
index 0000000..09166da
--- /dev/null
+++ b/plugins/org.eclipse.wst.validation.ui/icons/settings_disabled.gif
Binary files differ
diff --git a/plugins/org.eclipse.wst.validation.ui/plugin.properties b/plugins/org.eclipse.wst.validation.ui/plugin.properties
new file mode 100644
index 0000000..b8d12f2
--- /dev/null
+++ b/plugins/org.eclipse.wst.validation.ui/plugin.properties
@@ -0,0 +1,19 @@
+###############################################################################
+# Copyright (c) 2001, 2007 IBM Corporation 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:
+# IBM Corporation - initial API and implementation
+###############################################################################
+#
+# Version 1.3
+#
+VBF_TITLE_PROPERTIES=Validation
+VBF_UI_POPUP_RUNVALIDATION=Validate
+VBF_TITLE_PREFERENCE=Validation
+
+Bundle-Name.0 = Validation Framework UI
+Bundle-Vendor.0 = Eclipse.org
diff --git a/plugins/org.eclipse.wst.validation.ui/plugin.xml b/plugins/org.eclipse.wst.validation.ui/plugin.xml
new file mode 100644
index 0000000..20502a4
--- /dev/null
+++ b/plugins/org.eclipse.wst.validation.ui/plugin.xml
@@ -0,0 +1,55 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<?eclipse version="3.0"?>
+<plugin>
+
+
+<!-- ============================================== -->
+<!-- Popup Contributions -->
+<!-- ============================================== -->
+<!-- By saying "adaptable=true", this item will appear on both IProject and IJavaProject -->
+ <extension
+ point="org.eclipse.ui.popupMenus">
+ <objectContribution
+ adaptable="true"
+ objectClass="org.eclipse.core.resources.IResource"
+ id="ValidationMenuAction">
+ <action
+ label="%VBF_UI_POPUP_RUNVALIDATION"
+ class="org.eclipse.wst.validation.internal.ui.ValidationMenuAction"
+ menubarPath="additions"
+ enablesFor="+"
+ id="ValidationAction">
+ </action>
+ </objectContribution>
+ </extension>
+
+
+<!-- ====================================================== -->
+<!-- Validation preference page -->
+<!-- ====================================================== -->
+ <extension
+ point="org.eclipse.ui.preferencePages">
+ <page
+ name="%VBF_TITLE_PREFERENCE"
+ class="org.eclipse.wst.validation.ui.internal.preferences.ValidationPreferencePage"
+ id="ValidationPreferencePage">
+ </page>
+ </extension>
+
+<!-- ====================================================== -->
+<!-- Validation properties page -->
+<!-- ====================================================== -->
+<!-- By saying "adaptable=true", this item will appear on both IProject and IJavaProject -->
+ <extension
+ point="org.eclipse.ui.propertyPages">
+ <page
+ name="%VBF_TITLE_PROPERTIES"
+ class="org.eclipse.wst.validation.ui.internal.preferences.ValidationPropertyPage"
+ id="ValidationPropertiesPage">
+ <enabledWhen>
+ <adapt type="org.eclipse.core.resources.IProject"/>
+ </enabledWhen>
+ </page>
+ </extension>
+
+</plugin>
diff --git a/plugins/org.eclipse.wst.validation.ui/property_files/org/eclipse/wst/validation/internal/ui/validationui.properties b/plugins/org.eclipse.wst.validation.ui/property_files/org/eclipse/wst/validation/internal/ui/validationui.properties
new file mode 100644
index 0000000..4db102d
--- /dev/null
+++ b/plugins/org.eclipse.wst.validation.ui/property_files/org/eclipse/wst/validation/internal/ui/validationui.properties
@@ -0,0 +1,39 @@
+###############################################################################
+# Copyright (c) 2008 IBM Corporation 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:
+# IBM Corporation - initial API and implementation
+###############################################################################
+
+SaveFilesDialog_saving=Saving Resources
+SaveFilesDialog_always_save=&Always save all modified resources automatically prior to validating
+SaveFilesDialog_save_all_resources=Save All Modified Resources
+SaveFilesDialog_must_save=All modified resources must be saved before this operation.
+
+PrefPage_always_save=&Save all modified resources automatically prior to validating
+
+RunValidationDialogTitle=Running Validation
+UnableToSave=Unable to set save automatically preference in save files for validation dialog:
+Validate=Validate
+
+ValResults=Validation Results
+
+ValError1Resource1=The validation completed, one error was discovered. One resource was validated in {0}.
+ValErrorsResource1=The validation completed, {0} errors were discovered. One resource was validated in {1}.
+ValWarn1Resource1=The validation completed with one warning. One resource was validated in {0}.
+ValWarnResource1=The validation completed with {0} warnings. One resource was validated in {1}.
+ValInfo1Resource1=The validation completed with one informational message. One resource was validated in {0}.
+ValInfoResource1=The validation completed with {0} informational messages. One resource was validated in {1}.
+
+ValError1Resources=The validation completed, one error was discovered. {0} resources were validated in {1}.
+ValErrorsResources=The validation completed, {0} errors were discovered. {1} resources were validated in {2}.
+ValWarn1Resources=The validation completed with one warning. {0} resources were validated in {1}.
+ValWarnResources=The validation completed with {0} warnings. {1} resources were validated in {2}.
+ValInfo1Resources=The validation completed with one informational message. {0} resources were validated in {1}.
+ValInfoResources=The validation completed with {0} informational messages. {1} resources were validated in {2}.
+
+ValSuccess=The validation completed with no errors or warnings.
diff --git a/plugins/org.eclipse.wst.validation.ui/property_files/org/eclipse/wst/validation/ui/internal/messages.properties b/plugins/org.eclipse.wst.validation.ui/property_files/org/eclipse/wst/validation/ui/internal/messages.properties
new file mode 100644
index 0000000..af8e823
--- /dev/null
+++ b/plugins/org.eclipse.wst.validation.ui/property_files/org/eclipse/wst/validation/ui/internal/messages.properties
@@ -0,0 +1,158 @@
+###############################################################################
+# Copyright (c) 2001, 2008 IBM Corporation 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:
+# IBM Corporation - initial API and implementation
+###############################################################################
+# *************************************************************************
+# * Code oriented instructions:
+# *
+# * In the string, you may see the following special sequences:
+# * a) {n} where n is a number. These are replaceable parameters.
+# * b) '' In .properties files, in order to see one apostrophe (') in the final
+# * string, sometimes two apostrophes must be entered in the string. In the translated
+# * string, if there is at least one {n} in the string, then to show one apostrophe
+# * to the user, put two apostrophes in the string. If there are no {n} in the string,
+# * then put one apostrophe.
+# * For example, say that you want the user to read "George's file".
+# * GEORGE=George's file was on the desk.
+# * GEORGE2=George''s file and {0} were on the desk.
+# * GEORGE uses one apostrophe because there are no {n} and GEORGE2
+# * uses two apostrophes because there is a {n}.
+# * c) '' text '' where text can be any word(s). The text between the double
+# * apostrophes should not be translated.
+# * d) <text> where text can be any word(s). The text between the angle
+# * brackets should NOT be translated.
+# * e) "text" where text can be any word(s). The text between the quotation
+# * marks should NOT be translated.
+# *
+# *************************************************************************
+# * Other instructions
+# * a) Do not translate any text that is on a line which begins with a comment
+# * symbol (#).
+# * b) Do not translate these words:
+# * schema, EJB, RDB, JAR, RMI, BMP, CMP, OOSQL
+# * c) Please return the .properties files using the same directory structure.
+# * This is necessary because two of the files have the same name.
+# *
+# *************************************************************************
+# Any other comments to the translators are on lines which start like this: # 2TC:
+#
+# Version 1.12
+#
+#
+# ID:
+# VBF - Validation Builder Framework
+#
+
+#
+# Begin Validation Builder Framework UI Strings
+#
+# IDs:
+# VBF_EXC=Exception or error text
+# VBF_UI=UI label
+#
+PREF_BUTTON_OVERRIDE=Allow projects to override these preference settings
+PREF_BUTTON_ENABLEALL=Enable All
+PREF_BUTTON_DISABLEALL=Disable All
+PREF_VALLIST_TITLE=The selected validators will run when validation is performed:
+PREF_MNU_MANUAL=&Manual
+PREF_MNU_BUILD=&Build
+PREF_MNU_SETTINGS=&Settings...
+
+VBF_EXC_INTERNAL_TITLE=Internal error
+VBF_EXC_INTERNAL_PAGE=An unexpected error occurred; click Cancel to close the wizard.
+
+VBF_EXC_INVALID_REGISTER=Validators can run only on open resources.
+ProjectOverridesNotAllowed=The workspace validation preferences do not allow projects to override the workspace settings. In order to allow project settings you need to configure the workspace settings to allow project overrides.
+
+VBF_UI_NO_VALIDATORS_INSTALLED=No validators are installed.
+
+DISABLE_VALIDATION=Suspend all validators
+
+DelegatesDialogTitle=Validator Preferences
+DelegatesComboLabel=Implementation:
+ADD_VALIDATION_BUILDER=Add Validation Builder to project
+ConfigWsSettings=Configure Workspace Settings...
+VALIDATOR=Validator
+MANUAL=Manual
+BUILD=Build
+SETTINGS=Settings
+
+SaveFilesDialog_saving=Saving Resources
+SaveFilesDialog_always_save=&Always save all modified resources automatically prior to validating
+SaveFilesDialog_save_all_resources=Save All Modified Resources
+SaveFilesDialog_must_save=All modified resources must be saved before this operation.
+
+PrefPage_always_save=&Save all modified resources automatically prior to validating
+PrefPageConfirmDialog=Show a confirmation dialog when performing manual validations
+
+RunValidationDialogTitle=Running Validation
+
+fdTitle=Validation Filters for {0}
+fdNoFilters=The validator does not have currently have any filters installed.
+ErrConfig=Extension configuration error. An internal error has happened, the validator {0} has incorrectly configured the validation extension point.
+
+FilterHelp=Filter rules are grouped into groups. Inside of any one group the rules are combined by using the logical OR operator. There are two types of groups Include and Exclude. If any of the rules in the Exclude group match, the resource is not validated. If there are Include groups, at least one rule from each group must match before the resource is validated.
+ButtonAddGroupInclude=Add Include Group...
+ButtonAddGroupExclude=Add Exclude Group...
+ButtonAddRule=Add Rule...
+ButtonRemove=Remove
+
+LabelEnableProjectSpecific=Enable project specific settings
+
+LabelExtension=File extension
+LabelFile=Folder or file name
+LabelProjects=Project nature
+LabelFacets=Facet
+LabelContentType=Content Type
+
+# Note to translators, keep the <A> and </A> tags exactly as they are
+DoNotShowResults=Do not show this dialog in the future.
+
+DescExtension=File extension, for example "html" for HTML files.
+DescFile=Either a folder, a relative file, or a fully qualified file name.
+DescProjects=A project nature.
+DescFacets=A facet.
+DescContentType=A content type, for example the XML content type.
+
+ErrorsWarnings=Errors/Warnings
+
+Validation=Validation
+ValidationStatus=Validation Status
+
+ErrSummary=Validation results. Errors={0}, Warnings={1}, Information={2}
+ValidationSuccessful=Validation was successful
+
+FrWizard=New Filter Rule Wizard
+FrSelectFilterType=Select Filter Type
+FrFileExtension=File Extension
+FrFileExtensionLabel=File extension, for example html:
+FrCaseSensitive=Is the comparison case sensitive?
+FrExactMatch=Check this if the content type needs to match exactly. Do not check it, if sub types need to match as well.
+FrSimpleFileName=For file based comparisons, use only the simple file name.
+FrFolderOrFile=Folder or File Name
+FrFolderOrFileLabel=File or folder:
+FrBrowseFile=Browse File...
+FrFileFilter=Select the file that will serve as the filter
+FrBrowseFolder=Browse Folder...
+FrFolderFilter=Select the folder that will serve as the filter
+FrProjectNature=Project Nature
+FrProjectNatureLabel=Project nature:
+FrFacit=Facet
+FrFacitLabel=Facet id:
+FrContentType=Content Type
+FrContentTypeLabel=Content Type:
+FrMsgSev=Select the severity level for the following problems
+
+RebuildTitle=Validation Settings Changed
+RebuildMsg=The validation settings have changed. A full rebuild is required for the changes to take effect. Do the full build now?
+
+#
+# End Validation Builder Framework UI Strings
+#
+
diff --git a/plugins/org.eclipse.wst.validation.ui/validateui/org/eclipse/wst/validation/internal/ui/ContextIds.java b/plugins/org.eclipse.wst.validation.ui/validateui/org/eclipse/wst/validation/internal/ui/ContextIds.java
new file mode 100644
index 0000000..d8ce485
--- /dev/null
+++ b/plugins/org.eclipse.wst.validation.ui/validateui/org/eclipse/wst/validation/internal/ui/ContextIds.java
@@ -0,0 +1,46 @@
+/*******************************************************************************
+ * Copyright (c) 2001, 2006 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.wst.validation.internal.ui;
+
+import org.eclipse.wst.common.frameworks.internal.ui.WTPUIPlugin;
+
+public interface ContextIds {
+ static final String PREFIX = WTPUIPlugin.PLUGIN_ID;
+
+ // context ids for the Validation Properties Page
+ public static final String VALIDATION_PROPERTIES_PAGE = PREFIX + ".jvpp0000"; //$NON-NLS-1$
+ public static final String VALIDATION_PROPERTIES_PAGE_DISABLED_OVERRIDE = PREFIX + ".jvpp0001"; //$NON-NLS-1$
+ public static final String VALIDATION_PROPERTIES_PAGE_DISABLED_BUILD_NOVALSELECTED = PREFIX + ".jvpp0003"; //$NON-NLS-1$
+ public static final String VALIDATION_PROPERTIES_PAGE_DISABLED_AUTO_AUTOBUILD = PREFIX + ".jvpp0004"; //$NON-NLS-1$
+ public static final String VALIDATION_PROPERTIES_PAGE_DISABLED_AUTO_NOINCVALSELECTED = PREFIX + ".jvpp0005"; //$NON-NLS-1$
+ public static final String VALIDATION_PROPERTIES_PAGE_DISABLED_AUTO_NOINCVALCONFIG = PREFIX + ".jvpp0006"; //$NON-NLS-1$
+ public static final String VALIDATION_PROPERTIES_PAGE_AUTO_ENABLED = PREFIX + ".jvpp0020"; //$NON-NLS-1$
+ public static final String VALIDATION_PROPERTIES_PAGE_OVERRIDE_ENABLED = PREFIX + ".jvpp0030"; //$NON-NLS-1$
+ public static final String VALIDATION_PROPERTIES_PAGE_OVERRIDE_ENABLED_CANNOT_HONOUR_BOTH = PREFIX + ".jvpp0031"; //$NON-NLS-1$
+ public static final String VALIDATION_PROPERTIES_PAGE_OVERRIDE_ENABLED_CANNOT_HONOUR_AUTO = PREFIX + ".jvpp0032"; //$NON-NLS-1$
+ public static final String VALIDATION_PROPERTIES_PAGE_OVERRIDE_ENABLED_CANNOT_HONOUR_MANUAL = PREFIX + ".jvpp0033"; //$NON-NLS-1$
+ public static final String VALIDATION_PROPERTIES_PAGE_REBUILD_ENABLED = PREFIX + ".jvpp0040"; //$NON-NLS-1$
+ public static final String VALIDATION_PROPERTIES_PAGE_MAX_MESSAGES = PREFIX + ".jvpp0050"; //$NON-NLS-1$
+
+ public static final String VALIDATION_PREFERENCE_PAGE = PREFIX + ".jvgp0000"; //$NON-NLS-1$
+ public static final String VALIDATION_PREFERENCE_PAGE_OVERRIDE = PREFIX + ".jvgp0005"; //$NON-NLS-1$
+ public static final String VALIDATION_PREFERENCE_PAGE_DISABLE_ALL_ENABLED = PREFIX + ".jvgp0010"; //$NON-NLS-1$
+ // public static final String VALIDATION_PREFERENCE_PAGE_REBUILD_DISABLED = PREFIX +
+ // ".jvgp0011"; //$NON-NLS-1$
+ public static final String VALIDATION_PREFERENCE_PAGE_AUTO_ENABLED = PREFIX + ".jvgp0020"; //$NON-NLS-1$
+ // public static final String VALIDATION_PREFERENCE_PAGE_AUTO_DISABLED_AUTOBUILD = PREFIX +
+ // ".jvgp0021"; //$NON-NLS-1$
+ // public static final String VALIDATION_PREFERENCE_PAGE_AUTO_DISABLED_NOINCVALSELECTED = PREFIX
+ // + ".jvgp0022"; //$NON-NLS-1$
+ // public static final String VALIDATION_PREFERENCE_PAGE_AUTO_DISABLED_NOINCVALCONFIG = PREFIX +
+ // ".jvgp0023"; //$NON-NLS-1$
+ public static final String VALIDATION_PREFERENCE_PAGE_MAX_MESSAGES = PREFIX + ".jvgp0030"; //$NON-NLS-1$
+}
diff --git a/plugins/org.eclipse.wst.validation.ui/validateui/org/eclipse/wst/validation/internal/ui/DelegatingValidatorPreferencesDialog.java b/plugins/org.eclipse.wst.validation.ui/validateui/org/eclipse/wst/validation/internal/ui/DelegatingValidatorPreferencesDialog.java
new file mode 100644
index 0000000..e00900a
--- /dev/null
+++ b/plugins/org.eclipse.wst.validation.ui/validateui/org/eclipse/wst/validation/internal/ui/DelegatingValidatorPreferencesDialog.java
@@ -0,0 +1,270 @@
+/*******************************************************************************
+ * Copyright (c) 2006, 2008 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ * David Schneider, david.schneider@unisys.com - [142500] WTP properties pages fonts don't follow Eclipse preferences
+ *******************************************************************************/
+
+package org.eclipse.wst.validation.internal.ui;
+
+import java.util.Map;
+
+import org.eclipse.jface.dialogs.Dialog;
+import org.eclipse.jface.resource.JFaceResources;
+import org.eclipse.jface.viewers.ComboViewer;
+import org.eclipse.jface.viewers.ILabelProvider;
+import org.eclipse.jface.viewers.ILabelProviderListener;
+import org.eclipse.jface.viewers.ISelectionChangedListener;
+import org.eclipse.jface.viewers.IStructuredContentProvider;
+import org.eclipse.jface.viewers.IStructuredSelection;
+import org.eclipse.jface.viewers.StructuredSelection;
+import org.eclipse.jface.viewers.Viewer;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.graphics.Image;
+import org.eclipse.swt.layout.GridData;
+import org.eclipse.swt.layout.GridLayout;
+import org.eclipse.swt.widgets.Combo;
+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.wst.validation.internal.ValidatorMetaData;
+import org.eclipse.wst.validation.internal.delegates.ValidatorDelegateDescriptor;
+import org.eclipse.wst.validation.internal.delegates.ValidatorDelegatesRegistry;
+import org.eclipse.wst.validation.ui.internal.ValUIMessages;
+
+/**
+ * Dialog used to allow the user to select a validator delegate from the list of
+ * registered delegates for a given delegating validator.
+ */
+public class DelegatingValidatorPreferencesDialog extends Dialog
+{
+ /**
+ * The delegating validator's descriptor.
+ */
+ private ValidatorMetaData delegatingValidatorDescriptor;
+
+ /**
+ * The selected validator delegate ID.
+ */
+ private String delegateID;
+
+ /**
+ * Constructs the dialog on the given shell.
+ *
+ * @param parentShell
+ * the dialog's parent. Must not be null.
+ * @param targetID
+ * the delegating validator's id
+ *
+ * @param delegateID
+ * the ID of the currently selected validator delegate.
+ */
+ public DelegatingValidatorPreferencesDialog(Shell parentShell, ValidatorMetaData vmd, String delegateID)
+ {
+ super(parentShell);
+
+ delegatingValidatorDescriptor = vmd;
+ this.delegateID = delegateID;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.eclipse.jface.dialogs.Dialog#createDialogArea(org.eclipse.swt.widgets.Composite)
+ */
+ protected Control createDialogArea(Composite parent)
+ {
+ super.createDialogArea(parent);
+
+ getShell().setText(ValUIMessages.DelegatesDialogTitle);
+
+ GridLayout layout = new GridLayout();
+ parent.setLayout(layout);
+
+ Label label = new Label(parent, SWT.NONE);
+ GridData labelData = new GridData(SWT.FILL, SWT.CENTER, true, false);
+ labelData.widthHint = 250;
+ label.setLayoutData(labelData);
+ label.setFont(JFaceResources.getFontRegistry().getBold(JFaceResources.DIALOG_FONT));
+ String delegatingValidatorName = delegatingValidatorDescriptor.getValidatorDisplayName();
+ label.setText(delegatingValidatorName);
+
+ Label separator = new Label(parent, SWT.SEPARATOR | SWT.HORIZONTAL);
+ GridData separatorData = new GridData(SWT.FILL, SWT.CENTER, true, false);
+ separator.setLayoutData(separatorData);
+
+ Composite group = new Composite(parent, SWT.NONE);
+ GridData groupGridData = new GridData(SWT.FILL, SWT.CENTER, true, false);
+ group.setLayoutData(groupGridData);
+ GridLayout groupLayout = new GridLayout(2, false);
+ group.setLayout(groupLayout);
+
+ Label comboLabel = new Label(group, SWT.NONE);
+ comboLabel.setLayoutData(new GridData());
+ comboLabel.setText(ValUIMessages.DelegatesComboLabel);
+
+ Combo combo = new Combo(group, SWT.READ_ONLY);
+ GridData comboGridData = new GridData(SWT.FILL, SWT.CENTER, true, false);
+ combo.setLayoutData(comboGridData);
+
+ final ComboViewer comboViewer = new ComboViewer(combo);
+ comboViewer.setContentProvider(new DelegatesContentProvider());
+ comboViewer.setLabelProvider(new DelegatesLabelProvider());
+ String targetID = delegatingValidatorDescriptor.getValidatorUniqueName();
+
+ comboViewer.addSelectionChangedListener(new ISelectionChangedListener()
+ {
+
+ public void selectionChanged(org.eclipse.jface.viewers.SelectionChangedEvent event)
+ {
+ IStructuredSelection selection = (IStructuredSelection) comboViewer.getSelection();
+ setDelegateID(((ValidatorDelegateDescriptor) selection.getFirstElement()).getId());
+ }
+ });
+
+ comboViewer.setInput(targetID);
+
+ ValidatorDelegateDescriptor selected = ValidatorDelegatesRegistry.getInstance().getDescriptor(targetID, delegateID);
+
+ if (selected != null)
+ {
+ comboViewer.setSelection(new StructuredSelection(new Object[] { selected }));
+ }
+
+ Label endSeparator = new Label(parent, SWT.SEPARATOR | SWT.HORIZONTAL);
+ GridData endSeparatorData = new GridData(SWT.FILL, SWT.CENTER, true, false);
+ endSeparator.setLayoutData(endSeparatorData);
+ Dialog.applyDialogFont(parent);
+
+ return parent;
+ }
+
+ /**
+ * Provides contents for the delegate validators combo box.
+ */
+ private final class DelegatesContentProvider implements IStructuredContentProvider
+ {
+ public void dispose()
+ {
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.eclipse.jface.viewers.IStructuredContentProvider#getElements(java.lang.Object)
+ */
+ public Object[] getElements(Object inputElement)
+ {
+ String targetID = (String) inputElement;
+ Map delegatesByID = ValidatorDelegatesRegistry.getInstance().getDelegateDescriptors(targetID);
+
+ if (delegatesByID == null)
+ {
+ return new Object[] {};
+ }
+
+ return delegatesByID.values().toArray();
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.eclipse.jface.viewers.IContentProvider#inputChanged(org.eclipse.jface.viewers.Viewer,
+ * java.lang.Object, java.lang.Object)
+ */
+ public void inputChanged(Viewer viewer, Object oldInput, Object newInput)
+ {
+ }
+ }
+
+ /**
+ * Provides the labels/images for the delegate validator combo box
+ *
+ * @author vbaciul
+ *
+ */
+ private final class DelegatesLabelProvider implements ILabelProvider
+ {
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.eclipse.jface.viewers.IBaseLabelProvider#addListener(org.eclipse.jface.viewers.ILabelProviderListener)
+ */
+ public void addListener(ILabelProviderListener listener)
+ {
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.eclipse.jface.viewers.IBaseLabelProvider#dispose()
+ */
+ public void dispose()
+ {
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.eclipse.jface.viewers.ILabelProvider#getImage(java.lang.Object)
+ */
+ public Image getImage(Object element)
+ {
+ return null;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.eclipse.jface.viewers.ILabelProvider#getText(java.lang.Object)
+ */
+ public String getText(Object element)
+ {
+ return ((ValidatorDelegateDescriptor) element).getName();
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.eclipse.jface.viewers.IBaseLabelProvider#isLabelProperty(java.lang.Object,
+ * java.lang.String)
+ */
+ public boolean isLabelProperty(Object element, String property)
+ {
+ return false;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.eclipse.jface.viewers.IBaseLabelProvider#removeListener(org.eclipse.jface.viewers.ILabelProviderListener)
+ */
+ public void removeListener(ILabelProviderListener listener)
+ {
+ }
+ }
+
+ /*
+ * Provides the ID of the currently selected validator delegate ID.
+ */
+ public String getDelegateID()
+ {
+ return delegateID;
+ }
+
+ /**
+ * Sets the currently selected validator delegate ID.
+ *
+ * @param delegateID
+ */
+ private void setDelegateID(String delegateID)
+ {
+ this.delegateID = delegateID;
+ }
+}
diff --git a/plugins/org.eclipse.wst.validation.ui/validateui/org/eclipse/wst/validation/internal/ui/ListContentProvider.java b/plugins/org.eclipse.wst.validation.ui/validateui/org/eclipse/wst/validation/internal/ui/ListContentProvider.java
new file mode 100644
index 0000000..90b6d02
--- /dev/null
+++ b/plugins/org.eclipse.wst.validation.ui/validateui/org/eclipse/wst/validation/internal/ui/ListContentProvider.java
@@ -0,0 +1,49 @@
+/*******************************************************************************
+ * Copyright (c) 2000, 2006 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.wst.validation.internal.ui;
+
+import java.util.List;
+
+import org.eclipse.jface.viewers.IStructuredContentProvider;
+import org.eclipse.jface.viewers.Viewer;
+
+/**
+ * A specialized content provider to show a list of editor parts.
+ * This class has been copied from org.eclipse.jdt.internal.ui.viewsupport.ListContentProvider
+ * This class should be removed once a generic solution is made available.
+ */
+public class ListContentProvider implements IStructuredContentProvider {
+ List fContents;
+
+ public ListContentProvider() {
+ }
+
+ public Object[] getElements(Object input) {
+ if (fContents != null && fContents == input)
+ return fContents.toArray();
+ return new Object[0];
+ }
+
+ public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
+ if (newInput instanceof List)
+ fContents= (List)newInput;
+ else
+ fContents= null;
+ // we use a fixed set.
+ }
+
+ public void dispose() {
+ }
+
+ public boolean isDeleted(Object o) {
+ return fContents != null && !fContents.contains(o);
+ }
+}
diff --git a/plugins/org.eclipse.wst.validation.ui/validateui/org/eclipse/wst/validation/internal/ui/SaveFilesDialog.java b/plugins/org.eclipse.wst.validation.ui/validateui/org/eclipse/wst/validation/internal/ui/SaveFilesDialog.java
new file mode 100644
index 0000000..2deb872
--- /dev/null
+++ b/plugins/org.eclipse.wst.validation.ui/validateui/org/eclipse/wst/validation/internal/ui/SaveFilesDialog.java
@@ -0,0 +1,91 @@
+/*******************************************************************************
+ * Copyright (c) 2006, 2007 IBM Corporation 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:
+ * IBM - Initial API and implementation
+ * /
+ *******************************************************************************/
+package org.eclipse.wst.validation.internal.ui;
+
+import java.lang.reflect.InvocationTargetException;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+
+import org.eclipse.jface.viewers.ILabelProvider;
+import org.eclipse.jface.viewers.LabelProvider;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.events.SelectionAdapter;
+import org.eclipse.swt.events.SelectionEvent;
+import org.eclipse.swt.graphics.Image;
+import org.eclipse.swt.widgets.Button;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.Control;
+import org.eclipse.swt.widgets.Shell;
+import org.eclipse.ui.IEditorPart;
+import org.eclipse.ui.dialogs.ListDialog;
+import org.eclipse.wst.validation.internal.ConfigurationManager;
+import org.eclipse.wst.validation.internal.GlobalConfiguration;
+import org.eclipse.wst.validation.internal.ui.plugin.ValidationUIPlugin;
+
+/**
+ * A generic save files dialog. The bulk of the code
+ * for this dialog was taken from the JDT refactoring
+ * support in org.eclipse.jdt.internal.ui.refactoring.RefactoringSaveHelper.
+ * This class is a good candidate for reuse amoung components.
+ */
+public class SaveFilesDialog extends ListDialog {
+
+ public SaveFilesDialog(Shell parent)
+ {
+ super(parent);
+ setTitle(ValidationUIMessages.SaveFilesDialog_save_all_resources);
+ setAddCancelButton(true);
+ setLabelProvider(createDialogLabelProvider());
+ setMessage(ValidationUIMessages.SaveFilesDialog_must_save);
+ setContentProvider(new ListContentProvider());
+ }
+
+ protected Control createDialogArea(Composite container)
+ {
+ Composite result= (Composite) super.createDialogArea(container);
+ boolean fAllowSaveAlways = true;
+ if (fAllowSaveAlways) {
+ final Button check= new Button(result, SWT.CHECK);
+ check.setText(ValidationUIMessages.SaveFilesDialog_always_save);
+ //check.setSelection(RefactoringSavePreferences.getSaveAllEditors());
+ check.addSelectionListener(new SelectionAdapter() {
+ public void widgetSelected(SelectionEvent e) {
+ try
+ {
+ GlobalConfiguration config = ConfigurationManager.getManager().getGlobalConfiguration();
+ config.setSaveAutomatically(check.getSelection());
+ config.store();
+ }
+ catch(InvocationTargetException exc)
+ {
+ Logger.getLogger(ValidationUIPlugin.getBundleName()).log(Level.WARNING,
+ ValidationUIMessages.UnableToSave + exc);
+ }
+
+ }
+ });
+ applyDialogFont(result);
+ }
+ return result;
+ }
+
+ private ILabelProvider createDialogLabelProvider() {
+ return new LabelProvider() {
+ public Image getImage(Object element) {
+ return ((IEditorPart) element).getTitleImage();
+ }
+ public String getText(Object element) {
+ return ((IEditorPart) element).getTitle();
+ }
+ };
+ }
+}
diff --git a/plugins/org.eclipse.wst.validation.ui/validateui/org/eclipse/wst/validation/internal/ui/SaveFilesHelper.java b/plugins/org.eclipse.wst.validation.ui/validateui/org/eclipse/wst/validation/internal/ui/SaveFilesHelper.java
new file mode 100644
index 0000000..f323332
--- /dev/null
+++ b/plugins/org.eclipse.wst.validation.ui/validateui/org/eclipse/wst/validation/internal/ui/SaveFilesHelper.java
@@ -0,0 +1,67 @@
+/*******************************************************************************
+ * Copyright (c) 2006, 2007 IBM Corporation 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:
+ * IBM - Initial API and implementation
+ * /
+ *******************************************************************************/
+package org.eclipse.wst.validation.internal.ui;
+
+import java.util.HashSet;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Set;
+
+import org.eclipse.ui.IEditorInput;
+import org.eclipse.ui.IEditorPart;
+import org.eclipse.ui.IFileEditorInput;
+import org.eclipse.ui.IWorkbench;
+import org.eclipse.ui.IWorkbenchPage;
+import org.eclipse.ui.IWorkbenchWindow;
+import org.eclipse.ui.PlatformUI;
+
+/**
+ * A helper class for the save dirty files dialog.
+ */
+public class SaveFilesHelper {
+
+ /**
+ * Retreive an array of IEditorParts representing all the dirty
+ * editors open for the files provided in the list.
+ *
+ * @param files
+ * A list of IFiles.
+ * @return
+ * An array of IEditorParts containing all the dirty editors for the files in the list.
+ */
+ public static IEditorPart[] getDirtyEditors(List files) {
+ Set<IEditorInput> inputs = new HashSet<IEditorInput>();
+ List<IEditorPart> result = new LinkedList<IEditorPart>();
+ IWorkbench workbench = PlatformUI.getWorkbench();
+ IWorkbenchWindow[] windows = workbench.getWorkbenchWindows();
+ for (int i = 0; i < windows.length; i++) {
+ IWorkbenchPage[] pages = windows[i].getPages();
+ for (int x = 0; x < pages.length; x++) {
+ IEditorPart[] editors = pages[x].getDirtyEditors();
+ for (int z = 0; z < editors.length; z++) {
+ IEditorPart ep = editors[z];
+ IEditorInput input = ep.getEditorInput();
+ if (input instanceof IFileEditorInput) {
+ IFileEditorInput fileInput = (IFileEditorInput) input;
+ if (files.contains(fileInput.getFile())) {
+ if (!inputs.contains(input)) {
+ inputs.add(input);
+ result.add(ep);
+ }
+ }
+ }
+ }
+ }
+ }
+ return result.toArray(new IEditorPart[result.size()]);
+ }
+}
diff --git a/plugins/org.eclipse.wst.validation.ui/validateui/org/eclipse/wst/validation/internal/ui/ValidateAction.java b/plugins/org.eclipse.wst.validation.ui/validateui/org/eclipse/wst/validation/internal/ui/ValidateAction.java
new file mode 100644
index 0000000..a04c829
--- /dev/null
+++ b/plugins/org.eclipse.wst.validation.ui/validateui/org/eclipse/wst/validation/internal/ui/ValidateAction.java
@@ -0,0 +1,67 @@
+/*******************************************************************************
+ * Copyright (c) 2001, 2008 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.wst.validation.internal.ui;
+
+
+import org.eclipse.core.resources.IResource;
+import org.eclipse.jface.viewers.IStructuredSelection;
+import org.eclipse.ui.actions.SelectionListenerAction;
+
+
+public class ValidateAction extends SelectionListenerAction {
+ protected ValidationMenuAction delegate;
+
+ public ValidateAction() {
+ super(ValidationUIMessages.Validate);
+ delegate = new ValidationMenuAction();
+ }
+
+ /**
+ * Implementation of method defined on <code>IAction</code>.
+ */
+ public void run() {
+ delegate.run(this);
+ }
+
+ /**
+ * Updates this action in response to the given selection.
+ * <p>
+ * The <code>SelectionListenerAction</code> implementation of this method returns
+ * <code>true</code>. Subclasses may extend to react to selection changes; however, if the
+ * super method returns <code>false</code>, the overriding method must also return
+ * <code>false</code>.
+ * </p>
+ *
+ * @param selection
+ * the new selection
+ * @return <code>true</code> if the action should be enabled for this selection, and
+ * <code>false</code> otherwise
+ */
+ protected boolean updateSelection(IStructuredSelection selection) {
+ if (!super.updateSelection(selection))
+ return false;
+
+ delegate.selectionChanged(this, selection);
+
+ return isEnabled(); // "Enabled" is set by the delegate.
+ }
+
+ /**
+ * If a subclass of ValidateAction enables this menu action on a type that is not an IResource,
+ * this method returns the IResource[] that represent that object. If null is returned, the
+ * object will be ignored and the user will not be notified that the object was not validated.
+ * This method will be called when updateSelection and run are called. (The result of this
+ * method is used to determine which resources will be validated)
+ */
+ protected IResource[] getResource(Object selected) {
+ return null;
+ }
+}
diff --git a/plugins/org.eclipse.wst.validation.ui/validateui/org/eclipse/wst/validation/internal/ui/ValidationJob.java b/plugins/org.eclipse.wst.validation.ui/validateui/org/eclipse/wst/validation/internal/ui/ValidationJob.java
new file mode 100644
index 0000000..aa37f64
--- /dev/null
+++ b/plugins/org.eclipse.wst.validation.ui/validateui/org/eclipse/wst/validation/internal/ui/ValidationJob.java
@@ -0,0 +1,41 @@
+/*******************************************************************************
+ * Copyright (c) 2005, 2007 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.wst.validation.internal.ui;
+
+import java.util.Map;
+
+import org.eclipse.core.runtime.IProgressMonitor;
+import org.eclipse.core.runtime.IStatus;
+import org.eclipse.core.runtime.jobs.Job;
+
+public class ValidationJob extends Job {
+
+
+ private Map projects;
+ public ValidationJob(String name) {
+ super(name);
+ }
+
+
+ public void setProjectsMap(Map projects){
+ this.projects = projects;
+ }
+
+
+ protected IStatus run(IProgressMonitor monitor) {
+
+ return null;
+ }
+
+ protected Map getProjects() {
+ return projects;
+ }
+}
diff --git a/plugins/org.eclipse.wst.validation.ui/validateui/org/eclipse/wst/validation/internal/ui/ValidationMenuAction.java b/plugins/org.eclipse.wst.validation.ui/validateui/org/eclipse/wst/validation/internal/ui/ValidationMenuAction.java
new file mode 100644
index 0000000..126c407
--- /dev/null
+++ b/plugins/org.eclipse.wst.validation.ui/validateui/org/eclipse/wst/validation/internal/ui/ValidationMenuAction.java
@@ -0,0 +1,393 @@
+/*******************************************************************************
+ * Copyright (c) 2001, 2008 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.wst.validation.internal.ui;
+
+import java.lang.reflect.InvocationTargetException;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import org.eclipse.core.resources.IFile;
+import org.eclipse.core.resources.IFolder;
+import org.eclipse.core.resources.IProject;
+import org.eclipse.core.resources.IResource;
+import org.eclipse.core.resources.IResourceVisitor;
+import org.eclipse.core.runtime.CoreException;
+import org.eclipse.core.runtime.IProgressMonitor;
+import org.eclipse.core.runtime.SubProgressMonitor;
+import org.eclipse.jface.action.IAction;
+import org.eclipse.jface.dialogs.ProgressMonitorDialog;
+import org.eclipse.jface.operation.IRunnableWithProgress;
+import org.eclipse.jface.viewers.ISelection;
+import org.eclipse.jface.viewers.IStructuredSelection;
+import org.eclipse.jface.window.Window;
+import org.eclipse.swt.widgets.Display;
+import org.eclipse.swt.widgets.Shell;
+import org.eclipse.ui.IEditorPart;
+import org.eclipse.ui.IViewActionDelegate;
+import org.eclipse.ui.IViewPart;
+import org.eclipse.wst.validation.ValidationFramework;
+import org.eclipse.wst.validation.internal.ConfigurationManager;
+import org.eclipse.wst.validation.internal.DisabledResourceManager;
+import org.eclipse.wst.validation.internal.ValType;
+import org.eclipse.wst.validation.internal.ValidationRegistryReader;
+import org.eclipse.wst.validation.internal.ValidationSelectionHandlerRegistryReader;
+import org.eclipse.wst.validation.internal.plugin.ValidationPlugin;
+import org.eclipse.wst.validation.internal.ui.plugin.ValidationUIPlugin;
+import org.eclipse.wst.validation.ui.internal.ManualValidationRunner;
+
+/**
+ * This class implements the pop-up menu item "Run Validation" When the item is selected, this
+ * action triggers a validation of the project, using all configured, enabled validators.
+ */
+public class ValidationMenuAction implements IViewActionDelegate {
+ private ISelection _currentSelection;
+ protected static final String SEP = "/"; //$NON-NLS-1$
+ private Display _currentDisplay;
+ private IResourceVisitor _folderVisitor;
+ private IResourceVisitor _projectVisitor;
+ private Map<IProject, Set<IResource>> _selectedResources;
+
+ public ValidationMenuAction() {
+ // cache the display before this action is forked. After the action is forked,
+ // Display.getCurrent() returns null.
+ _currentDisplay = Display.getCurrent();
+ _selectedResources = new HashMap<IProject, Set<IResource>>();
+ }
+
+ private Display getDisplay() {
+ return (_currentDisplay == null) ? Display.getCurrent() : _currentDisplay;
+ }
+
+ /**
+ * Return the wizard's shell.
+ */
+ Shell getShell() {
+ Display display = getDisplay();
+ Shell shell = (display == null) ? null : display.getActiveShell();
+ if (shell == null && display != null) {
+ Shell[] shells = display.getShells();
+ if (shells.length > 0)
+ shell = shells[0];
+ }
+ return shell;
+ }
+
+ /**
+ * Return a map of the selected elements. Each key of the map is an IProject, and the value is a
+ * Set of the selected resources in that project. If a project is selected, and nothing else in
+ * the project is selected, a full validation (null value) will be done on the project. If a
+ * project is selected, and some files/folders in the project are also selected, only the
+ * files/folders will be validated. If a folder is selected, all of its contents are also
+ * validated.
+ *
+ * @return null if there is no selection.
+ */
+ private Map<IProject, Set<IResource>> loadSelected(ValidateAction action) {
+ // GRK previously this did not do a clear, but I couldn't understand why that would be so I am forcing a clear
+ // GRK In my testing, not doing a clear caused duplicate validations
+ _selectedResources.clear();
+ if ((_currentSelection == null) || _currentSelection.isEmpty() ||
+ !(_currentSelection instanceof IStructuredSelection))return null;
+
+ Object[] elements = ((IStructuredSelection) _currentSelection).toArray();
+ for (Object element : elements) {
+ if (element != null)addSelected(action, element);
+ }
+ return _selectedResources;
+ }
+
+ private void addSelected(ValidateAction action, Object selected) {
+ if (selected instanceof IProject) {
+ addVisitor((IProject) selected);
+ } else if (selected instanceof IFile) {
+ addSelected((IFile) selected);
+ } else if (selected instanceof IFolder) {
+ addVisitor((IFolder) selected);
+ } else if (isValidType(getExtendedType(selected))) {
+ addSelected(action,getExtendedType(selected));
+ } else {
+ // Not a valid input type. Must be IProject, IJavaProject, or IResource.
+ // If this ValidationMenuAction is a delegate of ValidateAction, is
+ // the input type recognized by the ValidateAction?
+ boolean valid = false;
+ if (action != null) {
+ IResource[] resources = action.getResource(selected);
+ if (resources != null) {
+ valid = true;
+ for (int i = 0; i < resources.length; i++) {
+ addSelected(action, resources[i]);
+ }
+ }
+ }
+ if (!valid) {
+ // Stop processing. This allows the "Run Validation" menu item
+ // to gray out once an element that can not be validated is selected.
+ _selectedResources.clear();
+ }
+ }
+ }
+
+ private Object getExtendedType(Object selected) {
+ Object result = ValidationSelectionHandlerRegistryReader.getInstance().getExtendedType(selected);
+ return result == null ? selected : result;
+ }
+
+ private boolean isValidType(Object object) {
+ return object instanceof IProject || object instanceof IFile || object instanceof IFolder;
+ }
+
+
+ void addSelected(IResource selected) {
+ IProject project = selected.getProject();
+ boolean added = _selectedResources.containsKey(project);
+ Set<IResource> changedRes = null;
+ if (added) {
+ // If the value is null, the entire project needs to be validated anyway.
+ changedRes = _selectedResources.get(project);
+ if (changedRes == null)return;
+
+ } else {
+ changedRes = new HashSet<IResource>();
+ }
+ if (changedRes.add(selected)) {
+ _selectedResources.put(project, changedRes);
+ }
+ }
+
+ private void addVisitor(IFolder selected) {
+ // add the folder and its children
+ try {
+ selected.accept(getFolderVisitor());
+ } catch (CoreException exc) {
+ ValidationUIPlugin.getPlugin().handleException(exc);
+ return;
+ }
+ }
+
+ private IResourceVisitor getFolderVisitor() {
+ if (_folderVisitor == null) {
+ _folderVisitor = new IResourceVisitor() {
+ public boolean visit(IResource res) {
+ if (res instanceof IFile) {
+ addSelected(res);
+ } else if (res instanceof IFolder) {
+ addSelected(res);
+ }
+ return true; // visit the resource's children
+ }
+ };
+ }
+ return _folderVisitor;
+ }
+
+ private void addVisitor(IProject selected) {
+ // add the folder and its children
+ if(!selected.isAccessible())return;
+ try {
+ selected.accept(getProjectVisitor());
+ } catch (CoreException exc) {
+ ValidationUIPlugin.getPlugin().handleException(exc);
+ return;
+ }
+ }
+
+ private IResourceVisitor getProjectVisitor() {
+ if (_projectVisitor == null) {
+ _projectVisitor = new IResourceVisitor() {
+ public boolean visit(IResource res) {
+ if (DisabledResourceManager.getDefault().isDisabled(res))return false;
+ if (res instanceof IFile)addSelected(res);
+ else if (res instanceof IFolder)addSelected(res);
+ else if (res instanceof IProject)addSelected(res);
+
+ return true;
+ }
+ };
+ }
+ return _projectVisitor;
+ }
+
+ /**
+ * The delegating action has been invoked. This method does the actual work.
+ *
+ * @param action
+ * Action proxy that handles the presentation portion of the plug-in action.
+ */
+ public void run(IAction action) {
+ ValidateAction vaction = null;
+ if (action instanceof ValidateAction) {
+ vaction = (ValidateAction) action;
+ }
+ final Map<IProject, Set<IResource>> projects = loadSelected(vaction);
+ if ((projects == null) || (projects.size() == 0)) {
+ return;
+ }
+
+ // If the files aren't saved do not run validation.
+ if(!handleFilesToSave(projects))return;
+
+ boolean confirm = org.eclipse.wst.validation.internal.ValManager.getDefault().getGlobalPreferences()
+ .getConfirmDialog();
+ ManualValidationRunner.validate(projects, ValType.Manual, confirm);
+ }
+
+ /**
+ * Selection in the desktop has changed. Plug-in provider can use it to change the availability
+ * of the action or to modify other presentation properties.
+ *
+ * <p>
+ * Action delegate cannot be notified about selection changes before it is loaded. For that
+ * reason, control of action's enable state should also be performed through simple XML rules
+ * defined for the extension point. These rules allow enable state control before the delegate
+ * has been loaded.
+ * </p>
+ *
+ * @param action
+ * action proxy that handles presentation portion of the plug-in action
+ * @param selection
+ * current selection in the desktop
+ */
+ public void selectionChanged(IAction action, ISelection selection) {
+ _currentSelection = selection;
+ boolean enabled = quickCheck(selection);
+
+ // Don't force the plug-in to be activated just to check this setting.
+ if (enabled && ValidationPlugin.isActivated() && ValidationRegistryReader.isActivated()){
+ enabled = hasManualValidators(selection);
+ }
+ action.setEnabled(enabled);
+ }
+
+ /**
+ * Do a quick check on the selection, so see if we know that we don't want to validate the selection.
+ *
+ * @param selection
+ * @return false if we are sure that we don't want to validate it. Return true if we are still not sure.
+ */
+ private boolean quickCheck(ISelection selection){
+ if (selection == null || selection.isEmpty())return false;
+ if (selection instanceof IStructuredSelection){
+ IStructuredSelection ss = (IStructuredSelection)selection;
+ Object sel = ss.getFirstElement();
+ if (sel != null){
+ if (sel instanceof IProject){
+ IProject project = (IProject)sel;
+ if (!project.isOpen())return false;
+ }
+ }
+ }
+
+ return true;
+ }
+
+ /**
+ * Answer true if any of the selected items have manual validators enabled.
+ * @param selection
+ */
+ private boolean hasManualValidators(ISelection selection){
+
+ if (selection instanceof IStructuredSelection){
+ IStructuredSelection ss = (IStructuredSelection)selection;
+ for (Iterator it = ss.iterator(); it.hasNext();){
+ Object sel = it.next();
+ if (sel instanceof IResource){
+ IResource resource = (IResource)sel;
+ if (ValidationFramework.getDefault().hasValidators(resource, true, false))return true;
+ }
+ }
+ }
+
+ return false;
+
+ }
+
+ /* (non-Javadoc)
+ * @see org.eclipse.ui.IViewActionDelegate#init(org.eclipse.ui.IViewPart)
+ */
+ public void init(IViewPart view) {
+ }
+
+ /**
+ * Handle any files that must be saved prior to running
+ * validation.
+ *
+ * @param projects
+ * The list of projects that will be validated.
+ * @return
+ * True if all files have been saved, false otherwise.
+ */
+ protected boolean handleFilesToSave(Map<IProject, Set<IResource>> projects)
+ {
+ List fileList = getIFiles(projects);
+ final IEditorPart[] dirtyEditors = SaveFilesHelper.getDirtyEditors(fileList);
+ if(dirtyEditors == null || dirtyEditors.length == 0)return true;
+ boolean saveAutomatically = false;
+ try
+ {
+ saveAutomatically = ConfigurationManager.getManager().getGlobalConfiguration().getSaveAutomatically();
+ }
+ catch(InvocationTargetException e)
+ {
+ // In this case simply default to false.
+ }
+ SaveFilesDialog sfDialog = null;
+ if(!saveAutomatically)
+ {
+ sfDialog = new SaveFilesDialog(ValidationUIPlugin.getPlugin().getWorkbench().getActiveWorkbenchWindow().getShell());
+ sfDialog.setInput(Arrays.asList(dirtyEditors));
+ }
+
+ if(saveAutomatically || sfDialog.open() == Window.OK){
+ ProgressMonitorDialog ctx = new ProgressMonitorDialog(getShell());
+
+ IRunnableWithProgress runnable = new IRunnableWithProgress(){
+ public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException{
+ try {
+ monitor.beginTask(ValidationUIMessages.SaveFilesDialog_saving, dirtyEditors.length);
+ int numDirtyEditors = dirtyEditors.length;
+ for(int i = 0; i < numDirtyEditors; i++){
+ dirtyEditors[i].doSave(new SubProgressMonitor(monitor, 1));
+ }
+ } finally {
+ monitor.done();
+ }
+ }
+ };
+
+ try {
+ ctx.run(false, true, runnable);
+ return true;
+ } catch (InvocationTargetException e) {
+ ValidationUIPlugin.getPlugin().handleException(e);
+ } catch (InterruptedException e) {
+ ValidationUIPlugin.getPlugin().handleException(e);
+ }
+ }
+ return false;
+ }
+
+ protected List<IFile> getIFiles(Map<IProject, Set<IResource>> projects) {
+ List<IFile> fileList = new LinkedList<IFile>();
+ for(IProject project : projects.keySet()) {
+ for(IResource resource : projects.get(project)) {
+ if(resource instanceof IFile)fileList.add((IFile)resource);
+ }
+ }
+ return fileList;
+ }
+
+}
diff --git a/plugins/org.eclipse.wst.validation.ui/validateui/org/eclipse/wst/validation/internal/ui/ValidationUIMessages.java b/plugins/org.eclipse.wst.validation.ui/validateui/org/eclipse/wst/validation/internal/ui/ValidationUIMessages.java
new file mode 100644
index 0000000..d6963b3
--- /dev/null
+++ b/plugins/org.eclipse.wst.validation.ui/validateui/org/eclipse/wst/validation/internal/ui/ValidationUIMessages.java
@@ -0,0 +1,61 @@
+/*******************************************************************************
+ * Copyright (c) 2006, 2008 IBM Corporation 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:
+ * IBM - Initial API and implementation
+ * /
+ *******************************************************************************/
+package org.eclipse.wst.validation.internal.ui;
+
+import org.eclipse.osgi.util.NLS;
+
+/**
+ * Strings used by Validation UI.
+ */
+public class ValidationUIMessages extends NLS {
+ private static final String BUNDLE_NAME = "org.eclipse.wst.validation.internal.ui.validationui";//$NON-NLS-1$
+
+ public static String SaveFilesDialog_saving;
+ public static String SaveFilesDialog_always_save;
+ public static String SaveFilesDialog_save_all_resources;
+ public static String SaveFilesDialog_must_save;
+ public static String PrefPage_always_save;
+ public static String RunValidationDialogTitle;
+ public static String UnableToSave;
+
+ public static String Validate;
+
+ public static String ValResults;
+
+ // results validating one resource
+ public static String ValError1Resource1;
+ public static String ValErrorsResource1;
+ public static String ValWarn1Resource1;
+ public static String ValWarnResource1;
+ public static String ValInfo1Resource1;
+ public static String ValInfoResource1;
+
+ // results validating multiple resources
+ public static String ValError1Resources;
+ public static String ValErrorsResources;
+ public static String ValWarn1Resources;
+ public static String ValWarnResources;
+ public static String ValInfo1Resources;
+ public static String ValInfoResources;
+
+ public static String ValSuccess;
+
+
+ static {
+ // load message values from bundle file
+ NLS.initializeMessages(BUNDLE_NAME, ValidationUIMessages.class);
+ }
+
+ private ValidationUIMessages() {
+ // cannot create new instance
+ }
+}
diff --git a/plugins/org.eclipse.wst.validation.ui/validateui/org/eclipse/wst/validation/internal/ui/plugin/RunnableWithProgressWrapper.java b/plugins/org.eclipse.wst.validation.ui/validateui/org/eclipse/wst/validation/internal/ui/plugin/RunnableWithProgressWrapper.java
new file mode 100644
index 0000000..4a8acb8
--- /dev/null
+++ b/plugins/org.eclipse.wst.validation.ui/validateui/org/eclipse/wst/validation/internal/ui/plugin/RunnableWithProgressWrapper.java
@@ -0,0 +1,97 @@
+/*******************************************************************************
+ * Copyright (c) 2001, 2005 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.wst.validation.internal.ui.plugin;
+
+import java.lang.reflect.InvocationTargetException;
+
+import org.eclipse.core.resources.IWorkspaceRunnable;
+import org.eclipse.core.resources.ResourcesPlugin;
+import org.eclipse.core.runtime.CoreException;
+import org.eclipse.core.runtime.IProgressMonitor;
+import org.eclipse.jface.operation.IRunnableWithProgress;
+import org.eclipse.wst.common.frameworks.internal.operations.IHeadlessRunnableWithProgress;
+import org.eclipse.wst.validation.internal.operations.ValidationOperation;
+
+
+/**
+ * This is a wrapper for an IWorkspaceRunnable to the IRunnableWithProgress. This class needs to be
+ * used when running the operation from a IRunnableContext.
+ *
+ * @see IRunnableContext
+ * @see ValidationUIPlugin#getRunnableWithProgress Creation date: (5/8/2001 1:28:45 PM)
+ * @author: Administrator
+ */
+public class RunnableWithProgressWrapper implements IRunnableWithProgress {
+ private IHeadlessRunnableWithProgress headlessRunnable = null;
+ private IWorkspaceRunnable workspaceRunnable = null;
+ private ValidationOperation validationOperation = null;
+
+ /**
+ * @deprecated Will be removed in Milestone 3. Use
+ * RunnableWithProgressWrapper(IWorkspaceRunnable)
+ */
+ public RunnableWithProgressWrapper(IHeadlessRunnableWithProgress aHeadlessRunnableWithProgress) {
+ setHeadlessRunnable(aHeadlessRunnableWithProgress);
+ }
+
+ public RunnableWithProgressWrapper(IWorkspaceRunnable aHeadlessRunnableWithProgress) {
+ setWorkspaceRunnable(aHeadlessRunnableWithProgress);
+ }
+
+ public RunnableWithProgressWrapper(ValidationOperation op) {
+ setValidationOperation(op);
+ }
+
+ /**
+ * @deprecated Will be removed in Milestone 3. Use getWorkspaceRunnable()
+ */
+ protected IHeadlessRunnableWithProgress getHeadlessRunnable() {
+ return headlessRunnable;
+ }
+
+ protected IWorkspaceRunnable getWorkspaceRunnable() {
+ return workspaceRunnable;
+ }
+
+ /**
+ * @see IRunnableWithProgress
+ */
+ public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
+ try {
+ if (getHeadlessRunnable() != null) {
+ getHeadlessRunnable().run(monitor);
+ } else {
+ IWorkspaceRunnable runnable = (getWorkspaceRunnable() == null) ? validationOperation : getWorkspaceRunnable();
+ if (runnable == null) {
+ return;
+ }
+ ResourcesPlugin.getWorkspace().run(runnable, monitor);
+ }
+ } catch (CoreException exc) {
+ throw new InvocationTargetException(exc);
+ }
+ }
+
+ /**
+ * @deprecated Will be removed in Milestone 3. Use setWorkspaceRunnable(IWorkspaceRunnable)
+ */
+ protected void setHeadlessRunnable(IHeadlessRunnableWithProgress newHeadlessRunnable) {
+ headlessRunnable = newHeadlessRunnable;
+ }
+
+ protected void setWorkspaceRunnable(IWorkspaceRunnable newWorkspaceRunnable) {
+ workspaceRunnable = newWorkspaceRunnable;
+ }
+
+ protected void setValidationOperation(ValidationOperation op) {
+ validationOperation = op;
+ }
+}
diff --git a/plugins/org.eclipse.wst.validation.ui/validateui/org/eclipse/wst/validation/internal/ui/plugin/ValidationUIPlugin.java b/plugins/org.eclipse.wst.validation.ui/validateui/org/eclipse/wst/validation/internal/ui/plugin/ValidationUIPlugin.java
new file mode 100644
index 0000000..3f0496b
--- /dev/null
+++ b/plugins/org.eclipse.wst.validation.ui/validateui/org/eclipse/wst/validation/internal/ui/plugin/ValidationUIPlugin.java
@@ -0,0 +1,171 @@
+/*******************************************************************************
+ * Copyright (c) 2001, 2008 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.wst.validation.internal.ui.plugin;
+
+import java.net.MalformedURLException;
+import java.net.URL;
+
+import org.eclipse.core.resources.IWorkspaceRunnable;
+import org.eclipse.core.runtime.IPath;
+import org.eclipse.core.runtime.IStatus;
+import org.eclipse.core.runtime.Path;
+import org.eclipse.core.runtime.Platform;
+import org.eclipse.core.runtime.Status;
+import org.eclipse.jface.operation.IRunnableWithProgress;
+import org.eclipse.jface.resource.ImageDescriptor;
+import org.eclipse.jface.resource.ImageRegistry;
+import org.eclipse.swt.graphics.Image;
+import org.eclipse.wst.common.frameworks.internal.ui.WTPUIPlugin;
+import org.eclipse.wst.validation.internal.operations.ValidationOperation;
+import org.osgi.framework.Bundle;
+import org.osgi.framework.BundleContext;
+
+
+
+public class ValidationUIPlugin extends WTPUIPlugin {
+ private static ValidationUIPlugin _plugin = null;
+
+ public final static String VALIDATION_PROP_FILE_NAME = "validate_ui"; //$NON-NLS-1$
+ public static final String VALIDATION_PLUGIN_ID = "org.eclipse.wst.validation.ui"; //$NON-NLS-1$
+ public static final String[] ICON_DIRS = new String[]{"icons"}; //$NON-NLS-1$
+
+ public ValidationUIPlugin() {
+ super();
+ if (_plugin == null) {
+ _plugin = this;
+ }
+ }
+
+ public static String getBundleName() {
+ return VALIDATION_PROP_FILE_NAME;
+ }
+
+ public static ValidationUIPlugin getPlugin() {
+ return _plugin;
+ }
+
+ /**
+ * Returns the translated String found with the given key.
+ *
+ * @param key
+ * java.lang.String
+ * @return java.lang.String
+ */
+ public static String getResourceString(String key) {
+ try {
+ return Platform.getResourceString(Platform.getBundle(VALIDATION_PLUGIN_ID), key);
+ } catch (Exception e) {
+ ValidationUIPlugin.getPlugin().handleException(e);
+ return key;
+ }
+ }
+
+ /**
+ * This method should be called whenever you need to run one of our headless operations in the
+ * UI.
+ */
+ public static IRunnableWithProgress getRunnableWithProgress(IWorkspaceRunnable aWorkspaceRunnable) {
+ return new RunnableWithProgressWrapper(aWorkspaceRunnable);
+ }
+
+// public static IRunnableWithProgress getRunnableWithProgress(IHeadlessRunnableWithProgress aHeadlessRunnableWithProgress) {
+// return new RunnableWithProgressWrapper(aHeadlessRunnableWithProgress);
+// }
+
+ // Need a third, ValidationOperation version of this method, because ValidationOperation
+ // is both an IWorkspaceRunnable and an IHeadlessRunnableWithProgress. This method will
+ // exist only while IHeadlessRunnableWithProgress exists.
+ public static IRunnableWithProgress getRunnableWithProgress(ValidationOperation op) {
+ return new RunnableWithProgressWrapper(op);
+ }
+
+ public void start(BundleContext context) throws Exception {
+ super.start(context);
+ // org.eclipse.wst.validation.internal.operations.ValidatorManager.setResourceUtilClass(org.eclipse.wst.validation.internal.operations.ui.UIResourceUtil.class);
+ }
+
+ /**
+ * Get a .gif from the image registry.
+ */
+ public Image getImage(String key) {
+ ImageRegistry imageRegistry = getImageRegistry();
+ Image image = imageRegistry.get(key);
+ if (image == null || image.isDisposed()) {
+ ImageDescriptor descriptor = getImageDescriptor(key);
+ if (descriptor != null) {
+ image = descriptor.createImage();
+ imageRegistry.put(key, image);
+ }
+ }
+ return image;
+ }
+
+ /**
+ * This gets a .gif from the icons folder.
+ */
+ public ImageDescriptor getImageDescriptor(String key) {
+ ImageDescriptor imageDescriptor = null;
+ URL gifImageURL = getImageURL(key);
+ if (gifImageURL != null)
+ imageDescriptor = ImageDescriptor.createFromURL(gifImageURL);
+ return imageDescriptor;
+ }
+
+ /**
+ * @param key
+ * @return
+ */
+ private URL getImageURL(String key) {
+ return ValidationUIPlugin.getImageURL(key, getBundle());
+ }
+
+ /**
+ * This gets a .gif from the icons folder.
+ */
+ public static URL getImageURL(String key, Bundle bundle) {
+ String gif = "/" + key + ".gif"; //$NON-NLS-1$ //$NON-NLS-2$
+ IPath path = null;
+ for (int i = 0; i < ICON_DIRS.length; i++) {
+ path = new Path(ICON_DIRS[i]).append(gif);
+ if (Platform.find(bundle,path) == null)
+ continue;
+ try {
+ return new URL( bundle.getEntry("/"), path.toString()); //$NON-NLS-1$
+ } catch (MalformedURLException exception) {
+ exception.printStackTrace();
+ continue;
+ }
+ }
+ return null;
+ }
+
+
+ public void handleException(Throwable e){
+ Status status = new Status(IStatus.ERROR, PLUGIN_ID, e.getLocalizedMessage(), e);
+ getLog().log(status);
+ }
+
+ /**
+ * Write a message into the log.
+ *
+ * We are in the transition of moving to a new approach for localized messages. This is the new
+ * approach for exceptions.
+ *
+ * @param severity message severity, see IStaus
+ * @param message a localized message
+ */
+ public void logMessage(int severity, String message){
+ Status status = new Status(severity, PLUGIN_ID, message);
+ getLog().log(status);
+
+ }
+
+}
diff --git a/plugins/org.eclipse.wst.validation.ui/vf2/org/eclipse/wst/validation/ui/internal/AdapterFactory.java b/plugins/org.eclipse.wst.validation.ui/vf2/org/eclipse/wst/validation/ui/internal/AdapterFactory.java
new file mode 100644
index 0000000..750c6fd
--- /dev/null
+++ b/plugins/org.eclipse.wst.validation.ui/vf2/org/eclipse/wst/validation/ui/internal/AdapterFactory.java
@@ -0,0 +1,116 @@
+/*******************************************************************************
+ * Copyright (c) 2005, 2007 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.wst.validation.ui.internal;
+
+import org.eclipse.core.runtime.IAdapterFactory;
+import org.eclipse.jface.resource.ImageDescriptor;
+import org.eclipse.ui.model.IWorkbenchAdapter;
+import org.eclipse.wst.validation.Validator;
+import org.eclipse.wst.validation.internal.ValidatorMutable;
+import org.eclipse.wst.validation.internal.model.FilterGroup;
+import org.eclipse.wst.validation.internal.model.FilterRule;
+
+public class AdapterFactory implements IAdapterFactory {
+
+ public Object getAdapter(Object adaptableObject, Class adapterType) {
+ if (adapterType == IWorkbenchAdapter.class && adaptableObject instanceof Validator.V2)return _valAdaptor;
+ if (adapterType == IWorkbenchAdapter.class && adaptableObject instanceof FilterGroup)return _fgAdaptor;
+ if (adapterType == IWorkbenchAdapter.class && adaptableObject instanceof FilterRule)return _ruleAdaptor;
+ if (adapterType == IWorkbenchAdapter.class && adaptableObject instanceof ValidatorMutable)return _valMutableAdaptor;
+
+ return null;
+ }
+
+ public Class[] getAdapterList() {
+ return new Class[] { IWorkbenchAdapter.class };
+ }
+
+ private IWorkbenchAdapter _valAdaptor = new IWorkbenchAdapter() {
+
+ public Object[] getChildren(Object o) {
+ return ((Validator.V2) o).getGroups();
+ }
+
+ public ImageDescriptor getImageDescriptor(Object o) {
+ return null;
+ }
+
+ public String getLabel(Object o) {
+ return ((Validator.V2) o).getName();
+ }
+
+ public Object getParent(Object o) {
+ return null;
+ }
+
+ };
+ private IWorkbenchAdapter _valMutableAdaptor = new IWorkbenchAdapter() {
+
+ public Object[] getChildren(Object o) {
+ return ((ValidatorMutable) o).getGroups();
+ }
+
+ public ImageDescriptor getImageDescriptor(Object o) {
+ return null;
+ }
+
+ public String getLabel(Object o) {
+ return ((ValidatorMutable) o).getName();
+ }
+
+ public Object getParent(Object o) {
+ return null;
+ }
+
+ };
+
+ private IWorkbenchAdapter _fgAdaptor = new IWorkbenchAdapter() {
+
+ public Object[] getChildren(Object o) {
+ return ((FilterGroup) o).getRules();
+ }
+
+ public ImageDescriptor getImageDescriptor(Object o) {
+ return null;
+ }
+
+ public String getLabel(Object o) {
+ FilterGroup fg = (FilterGroup) o;
+ return fg.getDisplayableType();
+ }
+
+ public Object getParent(Object o) {
+ return null;
+ }
+ };
+
+ private IWorkbenchAdapter _ruleAdaptor = new IWorkbenchAdapter() {
+
+ public Object[] getChildren(Object o) {
+ return new Object[0];
+ }
+
+ public ImageDescriptor getImageDescriptor(Object o) {
+ return null;
+ }
+
+ public String getLabel(Object o) {
+ FilterRule rule = (FilterRule) o;
+ return rule.getName();
+ }
+
+ public Object getParent(Object o) {
+ return null;
+ }
+
+ };
+
+}
diff --git a/plugins/org.eclipse.wst.validation.ui/vf2/org/eclipse/wst/validation/ui/internal/HelpContextIds.java b/plugins/org.eclipse.wst.validation.ui/vf2/org/eclipse/wst/validation/ui/internal/HelpContextIds.java
new file mode 100644
index 0000000..1af7aeb
--- /dev/null
+++ b/plugins/org.eclipse.wst.validation.ui/vf2/org/eclipse/wst/validation/ui/internal/HelpContextIds.java
@@ -0,0 +1,18 @@
+package org.eclipse.wst.validation.ui.internal;
+
+import org.eclipse.wst.validation.internal.ui.plugin.ValidationUIPlugin;
+
+public interface HelpContextIds {
+ String PreferencePage = ValidationUIPlugin.VALIDATION_PLUGIN_ID + ".jvgp0000"; //$NON-NLS-1$
+
+ String FilterRule = ValidationUIPlugin.VALIDATION_PLUGIN_ID + ".jvgp0100"; //$NON-NLS-1$
+ String FRFileExt = ValidationUIPlugin.VALIDATION_PLUGIN_ID + ".jvgp0101"; //$NON-NLS-1$
+ String FRName = ValidationUIPlugin.VALIDATION_PLUGIN_ID + ".jvgp0102"; //$NON-NLS-1$
+ String FRProjectNature = ValidationUIPlugin.VALIDATION_PLUGIN_ID + ".jvgp0103"; //$NON-NLS-1$
+ String FRFacet = ValidationUIPlugin.VALIDATION_PLUGIN_ID + ".jvgp0104"; //$NON-NLS-1$
+ String FRContentType = ValidationUIPlugin.VALIDATION_PLUGIN_ID + ".jvgp0105"; //$NON-NLS-1$
+
+ String ProjectPage = ValidationUIPlugin.VALIDATION_PLUGIN_ID + ".jvpp0000"; //$NON-NLS-1$
+ String ProjectFilterRule = ValidationUIPlugin.VALIDATION_PLUGIN_ID + ".jvpp0100"; //$NON-NLS-1$
+
+}
diff --git a/plugins/org.eclipse.wst.validation.ui/vf2/org/eclipse/wst/validation/ui/internal/ImageNames.java b/plugins/org.eclipse.wst.validation.ui/vf2/org/eclipse/wst/validation/ui/internal/ImageNames.java
new file mode 100644
index 0000000..5873170
--- /dev/null
+++ b/plugins/org.eclipse.wst.validation.ui/vf2/org/eclipse/wst/validation/ui/internal/ImageNames.java
@@ -0,0 +1,24 @@
+/*******************************************************************************
+ * Copyright (c) 2005, 2007 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.wst.validation.ui.internal;
+
+/**
+ * Names of the images.
+ * @author karasiuk
+ *
+ */
+public interface ImageNames {
+
+ String okTable = "ok_tbl"; //$NON-NLS-1$
+ String failTable = "fail_tbl"; //$NON-NLS-1$
+ String settings = "settings"; //$NON-NLS-1$
+ String disabled = "_disabled"; //$NON-NLS-1$
+}
diff --git a/plugins/org.eclipse.wst.validation.ui/vf2/org/eclipse/wst/validation/ui/internal/ManualValidationRunner.java b/plugins/org.eclipse.wst.validation.ui/vf2/org/eclipse/wst/validation/ui/internal/ManualValidationRunner.java
new file mode 100644
index 0000000..f70bcce
--- /dev/null
+++ b/plugins/org.eclipse.wst.validation.ui/vf2/org/eclipse/wst/validation/ui/internal/ManualValidationRunner.java
@@ -0,0 +1,105 @@
+/*******************************************************************************
+ * Copyright (c) 2007, 2008 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.wst.validation.ui.internal;
+
+import java.util.Map;
+import java.util.Set;
+
+import org.eclipse.core.resources.IProject;
+import org.eclipse.core.resources.IResource;
+import org.eclipse.core.resources.WorkspaceJob;
+import org.eclipse.core.runtime.CoreException;
+import org.eclipse.core.runtime.IProgressMonitor;
+import org.eclipse.core.runtime.IStatus;
+import org.eclipse.core.runtime.Status;
+import org.eclipse.core.runtime.jobs.MultiRule;
+import org.eclipse.swt.widgets.Display;
+import org.eclipse.wst.validation.internal.ValOperation;
+import org.eclipse.wst.validation.internal.ValType;
+import org.eclipse.wst.validation.internal.ValidationResultSummary;
+import org.eclipse.wst.validation.internal.ValidationRunner;
+import org.eclipse.wst.validation.ui.internal.dialog.ResultsDialog;
+
+/**
+ * Run a manual validation.
+ * @author karasiuk
+ *
+ */
+public class ManualValidationRunner extends WorkspaceJob {
+
+ private Map<IProject, Set<IResource>> _projects;
+ private ValType _valType;
+ private boolean _showResults;
+
+ /**
+ * Validate the selected projects and/or resources.
+ *
+ * @param projects
+ * The selected projects. The key is an IProject and the value is
+ * the Set of IResources that were selected. Often this will be
+ * every resource in the project.
+ *
+ * @param isManual
+ * Is this a manual validation?
+ *
+ * @param isBuild
+ * Is this a build based validation?
+ *
+ * @param showResults
+ * When the validation is finished, show the results in a dialog box.
+ */
+ public static void validate(Map<IProject, Set<IResource>> projects, ValType valType, boolean showResults){
+ ManualValidationRunner me = new ManualValidationRunner(projects, valType, showResults);
+
+ //TODO optimize this, I don't like the idea of validators having to lock the entire project
+ Set<IProject> keys = projects.keySet();
+ IProject[] projectArray = new IProject[keys.size()];
+ keys.toArray(projectArray);
+ if (projectArray.length == 1)me.setRule(projectArray[0]);
+ else {
+ me.setRule(MultiRule.combine(projectArray));
+ }
+ me.schedule();
+ }
+
+ private ManualValidationRunner(Map<IProject, Set<IResource>> projects, ValType valType, boolean showResults){
+ super(ValUIMessages.Validation);
+ _projects = projects;
+ _valType = valType;
+ _showResults = showResults;
+ }
+
+ public IStatus runInWorkspace(IProgressMonitor monitor) throws CoreException {
+
+ long start = System.currentTimeMillis();
+ final ValOperation vo = ValidationRunner.validate(_projects, _valType, monitor, false);
+ final long time = System.currentTimeMillis() - start;
+ int resourceCount = 0;
+ for (Set s : _projects.values())resourceCount += s.size();
+ final int finalResourceCount = resourceCount;
+ if (vo.isCanceled())return Status.CANCEL_STATUS;
+
+ if (_showResults){
+ Display display = Display.getDefault();
+ Runnable run = new Runnable(){
+
+ public void run() {
+ ValidationResultSummary vr = vo.getResult();
+ ResultsDialog rd = new ResultsDialog(null, vr, time, finalResourceCount);
+ rd.open();
+ }
+
+ };
+ display.asyncExec(run);
+ }
+ return Status.OK_STATUS;
+ }
+}
diff --git a/plugins/org.eclipse.wst.validation.ui/vf2/org/eclipse/wst/validation/ui/internal/ValUIMessages.java b/plugins/org.eclipse.wst.validation.ui/vf2/org/eclipse/wst/validation/ui/internal/ValUIMessages.java
new file mode 100644
index 0000000..99da9b9
--- /dev/null
+++ b/plugins/org.eclipse.wst.validation.ui/vf2/org/eclipse/wst/validation/ui/internal/ValUIMessages.java
@@ -0,0 +1,118 @@
+/*******************************************************************************
+ * Copyright (c) 2007, 2008 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+
+package org.eclipse.wst.validation.ui.internal;
+
+import org.eclipse.osgi.util.NLS;
+
+public class ValUIMessages extends NLS {
+
+ private static final String BUNDLE_NAME = "org.eclipse.wst.validation.ui.internal.messages"; //$NON-NLS-1$
+
+ public static String ADD_VALIDATION_BUILDER;
+
+ public static String PREF_BUTTON_OVERRIDE;
+ public static String PREF_VALLIST_TITLE;
+ public static String PREF_BUTTON_ENABLEALL;
+ public static String PREF_BUTTON_DISABLEALL;
+ public static String PREF_MNU_MANUAL;
+ public static String PREF_MNU_BUILD;
+ public static String PREF_MNU_SETTINGS;
+
+ public static String ConfigWsSettings;
+ public static String DoNotShowResults;
+ public static String DelegatesDialogTitle;
+ public static String DelegatesComboLabel;
+
+ public static String ErrorsWarnings;
+
+ public static String VBF_EXC_INTERNAL_TITLE;
+ public static String VBF_EXC_INTERNAL_PAGE;
+ public static String VBF_EXC_INVALID_REGISTER;
+ public static String DISABLE_VALIDATION;
+
+ public static String MANUAL;
+ public static String BUILD;
+ public static String SETTINGS;
+ public static String VALIDATOR;
+ public static String VBF_UI_NO_VALIDATORS_INSTALLED;
+
+ public static String SaveFilesDialog_saving;
+ public static String SaveFilesDialog_always_save;
+ public static String SaveFilesDialog_save_all_resources;
+ public static String SaveFilesDialog_must_save;
+ public static String PrefPage_always_save;
+ public static String PrefPageConfirmDialog;
+ public static String ProjectOverridesNotAllowed;
+ public static String RunValidationDialogTitle;
+
+ /* Validator Filters */
+ public static String fdTitle;
+ public static String fdNoFilters;
+
+ public static String ErrConfig;
+
+ public static String FilterHelp;
+
+ public static String ButtonAddGroupInclude;
+ public static String ButtonAddGroupExclude;
+ public static String ButtonAddRule;
+ public static String ButtonRemove;
+
+ public static String LabelExtension;
+ public static String LabelFile;
+ public static String LabelProjects;
+ public static String LabelFacets;
+ public static String LabelContentType;
+ public static String LabelEnableProjectSpecific;
+
+ public static String DescExtension;
+ public static String DescFile;
+ public static String DescProjects;
+ public static String DescFacets;
+ public static String DescContentType;
+
+ public static String Validation;
+ public static String ValidationStatus;
+
+ public static String ErrSummary;
+ public static String ValidationSuccessful;
+
+ public static String FrWizard;
+ public static String FrSelectFilterType;
+ public static String FrFileExtension;
+ public static String FrFileExtensionLabel;
+ public static String FrCaseSensitive;
+ public static String FrExactMatch;
+ public static String FrFolderOrFile;
+ public static String FrFolderOrFileLabel;
+ public static String FrBrowseFile;
+ public static String FrFileFilter;
+ public static String FrBrowseFolder;
+ public static String FrFolderFilter;
+ public static String FrProjectNature;
+ public static String FrProjectNatureLabel;
+ public static String FrSimpleFileName;
+ public static String FrFacit;
+ public static String FrFacitLabel;
+ public static String FrContentType;
+ public static String FrContentTypeLabel;
+ public static String FrMsgSev;
+
+ public static String RebuildTitle;
+ public static String RebuildMsg;
+
+
+ static {
+ NLS.initializeMessages(BUNDLE_NAME, ValUIMessages.class);
+ }
+
+}
diff --git a/plugins/org.eclipse.wst.validation.ui/vf2/org/eclipse/wst/validation/ui/internal/dialog/FilterDialog.java b/plugins/org.eclipse.wst.validation.ui/vf2/org/eclipse/wst/validation/ui/internal/dialog/FilterDialog.java
new file mode 100644
index 0000000..186eaae
--- /dev/null
+++ b/plugins/org.eclipse.wst.validation.ui/vf2/org/eclipse/wst/validation/ui/internal/dialog/FilterDialog.java
@@ -0,0 +1,469 @@
+/*******************************************************************************
+ * Copyright (c) 2005, 2009 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.wst.validation.ui.internal.dialog;
+
+import java.lang.reflect.InvocationTargetException;
+import java.util.Iterator;
+import java.util.Map;
+
+import org.eclipse.core.resources.IProject;
+import org.eclipse.core.runtime.IAdapterFactory;
+import org.eclipse.core.runtime.Platform;
+import org.eclipse.jface.dialogs.Dialog;
+import org.eclipse.jface.resource.JFaceResources;
+import org.eclipse.jface.viewers.ISelectionChangedListener;
+import org.eclipse.jface.viewers.IStructuredSelection;
+import org.eclipse.jface.viewers.SelectionChangedEvent;
+import org.eclipse.jface.viewers.TreeViewer;
+import org.eclipse.jface.wizard.WizardDialog;
+import org.eclipse.osgi.util.NLS;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.events.SelectionEvent;
+import org.eclipse.swt.events.SelectionListener;
+import org.eclipse.swt.graphics.Point;
+import org.eclipse.swt.layout.GridData;
+import org.eclipse.swt.layout.GridLayout;
+import org.eclipse.swt.layout.RowLayout;
+import org.eclipse.swt.widgets.Button;
+import org.eclipse.swt.widgets.Combo;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.Control;
+import org.eclipse.swt.widgets.Group;
+import org.eclipse.swt.widgets.Label;
+import org.eclipse.swt.widgets.Shell;
+import org.eclipse.ui.model.BaseWorkbenchContentProvider;
+import org.eclipse.ui.model.WorkbenchLabelProvider;
+import org.eclipse.wst.validation.MessageSeveritySetting;
+import org.eclipse.wst.validation.Validator;
+import org.eclipse.wst.validation.internal.ValManager;
+import org.eclipse.wst.validation.internal.ValMessages;
+import org.eclipse.wst.validation.internal.ValidatorMutable;
+import org.eclipse.wst.validation.internal.delegates.ValidatorDelegateDescriptor;
+import org.eclipse.wst.validation.internal.delegates.ValidatorDelegatesRegistry;
+import org.eclipse.wst.validation.internal.model.FilterGroup;
+import org.eclipse.wst.validation.internal.model.FilterRule;
+import org.eclipse.wst.validation.internal.model.ValidatorHelper;
+import org.eclipse.wst.validation.ui.internal.AdapterFactory;
+import org.eclipse.wst.validation.ui.internal.ValUIMessages;
+
+/**
+ * Display a filter dialog for a particular Validator, that is a list of all the filters that are active for
+ * the validator.
+ *
+ * @author karasiuk
+ *
+ */
+public final class FilterDialog extends Dialog {
+
+ /**
+ * If we are doing project level filters this will point to the project. This is null if we are doing
+ * workspace level filters.
+ */
+ private IProject _project;
+
+ private ValidatorMutable _validator;
+
+ private TreeViewer _tree;
+ private Combo _delegating;
+ private IAdapterFactory _adaptorFactory = new AdapterFactory();
+
+ private Button _addGroupInclude;
+ private Button _addGroupExclude;
+ private Button _addRule;
+ private Button _remove;
+ private ISelectionChangedListener _nodeChangedListener;
+
+ /** The currently selected group. If a rule is selected instead, then this will be null. */
+ private FilterGroup _selectedGroup;
+
+ /** The currently selected rule. If a group is selected instead, then this will be null. */
+ private FilterRule _selectedRule;
+
+ private Combo[] _messageSev;
+
+ private static String[] _messages = new String[]{
+ ValMessages.SevError, ValMessages.SevWarning, ValMessages.SevIgnore};
+
+ private Shell _shell;
+
+ /**
+ * Create a dialog that knows how to change a validator's filters.
+ *
+ * @param shell
+ *
+ * @param validator the validator that is being updated.
+ *
+ * @param project the project that the filters are being added to. If these are workspace
+ * level filters, then this must be null.
+ */
+ public FilterDialog(Shell shell, ValidatorMutable validator, IProject project){
+ super(shell);
+ _shell = shell;
+ setShellStyle(getShellStyle() | SWT.CLOSE|SWT.MIN|SWT.MAX|SWT.RESIZE);
+ _validator = validator;
+ _project = project;
+ }
+
+ protected void configureShell(Shell newShell) {
+ super.configureShell(newShell);
+ newShell.setText(NLS.bind(ValUIMessages.fdTitle, _validator.getName()));
+ }
+
+ protected Control createDialogArea(Composite parent) {
+ Composite c = (Composite)super.createDialogArea(parent);
+ c.setLayout(new GridLayout(2, false));
+ if (!_validator.isV2Validator()){
+ new Label(c, SWT.NONE).setText(ValUIMessages.fdNoFilters);
+ }
+ else {
+ Label blurb = new Label(c, SWT.LEFT | SWT.WRAP);
+ blurb.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false, 2, 1));
+ blurb.setText(ValUIMessages.FilterHelp);
+
+ _tree = new TreeViewer(c, SWT.SINGLE | SWT.H_SCROLL | SWT.V_SCROLL | SWT.BORDER);
+ _tree.getControl().setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
+ Platform.getAdapterManager().registerAdapters(_adaptorFactory, ValidatorMutable.class);
+ Platform.getAdapterManager().registerAdapters(_adaptorFactory, FilterGroup.class);
+ Platform.getAdapterManager().registerAdapters(_adaptorFactory, FilterRule.class);
+ _tree.setContentProvider(new BaseWorkbenchContentProvider());
+ _tree.setLabelProvider(new WorkbenchLabelProvider());
+ _tree.setInput(_validator);
+ _tree.expandAll();
+
+ addButtons(c);
+
+ String delegatingId = _validator.getDelegatingId();
+ if (delegatingId != null){
+ addDelegatorSelection(c);
+ }
+
+ _nodeChangedListener = new ISelectionChangedListener(){
+
+ public void selectionChanged(SelectionChangedEvent event) {
+ _selectedGroup = null;
+ _selectedRule = null;
+ if (event.getSelection() instanceof IStructuredSelection){
+ IStructuredSelection sel = (IStructuredSelection)event.getSelection();
+ if (sel.getFirstElement() instanceof FilterGroup){
+ _selectedGroup = (FilterGroup)sel.getFirstElement();
+ }
+ else if (sel.getFirstElement() instanceof FilterRule){
+ _selectedRule = (FilterRule)sel.getFirstElement();
+ }
+ }
+ updateButtons();
+ }
+
+ };
+
+ _tree.addSelectionChangedListener(_nodeChangedListener);
+
+ addMessageMappings(c);
+ }
+ return c;
+ }
+
+ private void addButtons(Composite c) {
+ Composite buttons = new Composite(c, SWT.TOP);
+ GridData gd = new GridData(SWT.LEFT, SWT.TOP, false, false, 1, 1);
+ buttons.setLayoutData(gd);
+ buttons.setLayout(new GridLayout(1, true));
+ _addGroupInclude = new Button(buttons, SWT.PUSH | SWT.FILL | SWT.CENTER);
+ _addGroupInclude.setText(ValUIMessages.ButtonAddGroupInclude);
+ _addGroupInclude.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false, 1, 1));
+
+ _addGroupInclude.addSelectionListener(new SelectionListener(){
+
+ public void widgetDefaultSelected(SelectionEvent e) {
+ addGroup(false);
+ }
+
+ public void widgetSelected(SelectionEvent e) {
+ addGroup(false);
+ }
+
+ });
+
+ _addGroupExclude = new Button(buttons, SWT.PUSH | SWT.FILL | SWT.CENTER);
+ _addGroupExclude.setText(ValUIMessages.ButtonAddGroupExclude);
+ _addGroupExclude.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false, 1, 1));
+
+ _addGroupExclude.addSelectionListener(new SelectionListener(){
+
+ public void widgetDefaultSelected(SelectionEvent e) {
+ addGroup(true);
+ }
+
+ public void widgetSelected(SelectionEvent e) {
+ addGroup(true);
+ }
+
+ });
+
+ _addRule = new Button(buttons, SWT.PUSH | SWT.FILL | SWT.CENTER);
+ _addRule.setText(ValUIMessages.ButtonAddRule);
+ _addRule.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false, 1, 1));
+ _addRule.addSelectionListener(new SelectionListener(){
+
+ public void widgetDefaultSelected(SelectionEvent e) {
+ doIt();
+ }
+
+ public void widgetSelected(SelectionEvent e) {
+ doIt();
+ }
+
+ private void doIt(){
+ NewFilterRule nfr = new NewFilterRule(_project);
+ WizardDialog wd = new WizardDialog(_shell, nfr);
+ wd.setBlockOnOpen(true);
+ int rc = wd.open();
+ if (rc == WizardDialog.CANCEL)return;
+
+ FilterRule rule = nfr.getRule();
+ if (rule != null){
+ FilterGroup newGroup = FilterGroup.addRule(_selectedGroup, rule);
+ _validator.replaceFilterGroup(_selectedGroup, newGroup);
+ _selectedGroup = newGroup;
+ refresh();
+ }
+ }
+
+ });
+
+ _remove = new Button(buttons, SWT.PUSH | SWT.FILL | SWT.CENTER);
+ _remove.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false, 1, 1));
+ _remove.setText(ValUIMessages.ButtonRemove);
+ _remove.addSelectionListener(new SelectionListener(){
+
+ public void widgetDefaultSelected(SelectionEvent e) {
+ remove();
+ }
+
+ public void widgetSelected(SelectionEvent e) {
+ remove();
+ }
+ });
+
+ Button restore = new Button(buttons, SWT.PUSH | SWT.FILL | SWT.CENTER);
+ restore.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false, 1, 1));
+ String defaults = JFaceResources.getString("defaults"); //$NON-NLS-1$
+ restore.setText(defaults);
+ restore.addSelectionListener(new SelectionListener(){
+
+ public void widgetDefaultSelected(SelectionEvent e) {
+ restoreDefaults();
+ }
+
+ public void widgetSelected(SelectionEvent e) {
+ restoreDefaults();
+ }
+ });
+ }
+
+ private void restoreDefaults() {
+ if (_validator.isV2Validator()){
+ try {
+ String id = _validator.getId();
+ Validator[] vals = ValManager.getDefaultValidators();
+ for (Validator v : vals){
+ if (v.getId().equals(id)){
+ _validator = new ValidatorMutable(v);
+ _tree.setInput(_validator);
+ _tree.expandAll();
+ refresh();
+ return;
+ }
+ }
+ }
+ catch (InvocationTargetException e){
+
+ }
+ }
+
+ }
+
+
+ private void addMessageMappings(Composite c) {
+ if (!_validator.isV2Validator())return;
+ Map<String,MessageSeveritySetting> mappings = _validator.getMessageSettings();
+ if (mappings == null || mappings.size() == 0)return;
+
+ Group group = new Group(c, SWT.NONE);
+ group.setText(ValUIMessages.FrMsgSev);
+ group.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false, 2, 1));
+ group.setLayout(new GridLayout(2, false));
+
+// Label heading = new Label(c, SWT.LEFT);
+// heading.setText(ValUIMessages.ErrorsWarnings);
+// heading.setFont(JFaceResources.getHeaderFont());
+// heading.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false, 2, 1));
+
+ _messageSev = new Combo[mappings.size()];
+ int i= 0;
+ for (MessageSeveritySetting ms : mappings.values()){
+ Label label = new Label(group, SWT.LEFT);
+ label.setText(" " + ms.getLabel() + ":"); //$NON-NLS-1$ //$NON-NLS-2$
+
+ Combo sev = new Combo(group, SWT.RIGHT);
+ _messageSev[i++] = sev;
+ sev.setItems(_messages);
+ sev.select(ms.getCurrent().ordinal());
+ sev.setData(ms);
+ sev.addSelectionListener(new SelectionListener(){
+
+ public void widgetDefaultSelected(SelectionEvent e) {
+ select(e);
+ }
+
+ public void widgetSelected(SelectionEvent e) {
+ select(e);
+ }
+
+ private void select(SelectionEvent e){
+ Combo w = (Combo)e.widget;
+ MessageSeveritySetting ms = (MessageSeveritySetting)w.getData();
+ int i = w.getSelectionIndex();
+ if (ms.setCurrent(MessageSeveritySetting.Severity.values()[i]))
+ _validator.bumpChangeCountMessages();
+ }
+
+ });
+ }
+ }
+
+ /**
+ * Add a combo box so that the user can change which delegating validator to call.
+ */
+ private void addDelegatorSelection(Composite c) {
+ Map map = ValidatorDelegatesRegistry.getInstance().getDelegateDescriptors(_validator.getValidatorClassname());
+ if (map == null)return;
+
+ Composite line = new Composite(c, SWT.NONE);
+ line.setLayout(new RowLayout(SWT.HORIZONTAL));
+ line.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false, 2, 1));
+
+ Label label = new Label(line, SWT.CENTER);
+ label.setText(ValUIMessages.DelegatesComboLabel);
+
+
+ _delegating = new Combo(line, SWT.READ_ONLY);
+ String[] items = new String[map.size()];
+ final String ids[] = new String[map.size()];
+ String selected = null;
+ Iterator it = map.values().iterator();
+ for (int i=0; i<items.length;i++){
+ ValidatorDelegateDescriptor vd = (ValidatorDelegateDescriptor)it.next();
+ items[i] = vd.getName();
+ ids[i] = vd.getId();
+ if (vd.getId().equals(_validator.getDelegatingId())){
+ selected = vd.getName();
+ }
+ }
+ _delegating.setItems(items);
+ _delegating.setText(selected);
+ _delegating.addSelectionListener(new SelectionListener(){
+
+ public void widgetDefaultSelected(SelectionEvent e) {
+ }
+
+ public void widgetSelected(SelectionEvent e) {
+ int sel = _delegating.getSelectionIndex();
+ _validator.setDelegatingId(ids[sel]);
+ }
+
+ });
+ }
+
+ /**
+ * Add a new filter group to the validator.
+ * @param exclude
+ */
+ private void addGroup(boolean exclude){
+ if (!_validator.isV2Validator())return;
+ FilterRule[] rules = new FilterRule[0];
+ _validator.add(FilterGroup.create(exclude, rules));
+ refresh();
+
+ }
+
+ private void refresh(){
+ _tree.refresh();
+ _tree.expandAll();
+ updateButtons();
+ }
+
+ /**
+ * Remove the current selection from the validator.
+ */
+ private void remove(){
+ if (_selectedRule != null){
+ FilterGroup group = findGroup(_selectedRule);
+ if (group != null){
+ FilterGroup newGroup = FilterGroup.removeRule(group, _selectedRule);
+ _validator.replaceFilterGroup(group, newGroup);
+ refresh();
+ }
+ }
+
+ if (_selectedGroup != null){
+ _validator.remove(_selectedGroup);
+ refresh();
+ return;
+ }
+ }
+
+ /**
+ * Find the group in the current validator that has this rule.
+ * @param rule The rule that we are searching for.
+ * @return null if we can not find the group.
+ */
+ private FilterGroup findGroup(FilterRule rule) {
+ for (FilterGroup group : _validator.getGroups()){
+ for (FilterRule fr : group.getRules()){
+ if (fr.equals(rule))return group;
+ }
+ }
+ return null;
+ }
+
+ private void updateButtons() {
+ if (_validator.isV2Validator()){
+ _addGroupExclude.setEnabled(!ValidatorHelper.hasExcludeGroup(_validator));
+ }
+ _addRule.setEnabled(_selectedGroup != null);
+ _remove.setEnabled(_selectedGroup != null || _selectedRule != null);
+ if (_messageSev != null){
+ Map<String,MessageSeveritySetting> msgs = _validator.getMessageSettings();
+ if (msgs != null && _messageSev.length == msgs.size()){
+ int i = 0;
+ for (MessageSeveritySetting ms : msgs.values()){
+ _messageSev[i++].select(ms.getCurrent().ordinal());
+ }
+ }
+ }
+ }
+
+
+ public boolean close() {
+ Platform.getAdapterManager().unregisterAdapters(_adaptorFactory);
+ if (_tree != null)_tree.removeSelectionChangedListener(_nodeChangedListener);
+ return super.close();
+ }
+
+ protected Point getInitialSize() {
+ return new Point(600, 475);
+ }
+
+ public ValidatorMutable getValidator() {
+ return _validator;
+ }
+}
diff --git a/plugins/org.eclipse.wst.validation.ui/vf2/org/eclipse/wst/validation/ui/internal/dialog/NewFilterRule.java b/plugins/org.eclipse.wst.validation.ui/vf2/org/eclipse/wst/validation/ui/internal/dialog/NewFilterRule.java
new file mode 100644
index 0000000..fad49d7
--- /dev/null
+++ b/plugins/org.eclipse.wst.validation.ui/vf2/org/eclipse/wst/validation/ui/internal/dialog/NewFilterRule.java
@@ -0,0 +1,568 @@
+/*******************************************************************************
+ * Copyright (c) 2005, 2008 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.wst.validation.ui.internal.dialog;
+
+import java.util.Map;
+import java.util.TreeMap;
+
+import org.eclipse.core.resources.IProject;
+import org.eclipse.core.resources.IProjectNatureDescriptor;
+import org.eclipse.core.resources.ResourcesPlugin;
+import org.eclipse.core.runtime.IPath;
+import org.eclipse.core.runtime.Path;
+import org.eclipse.core.runtime.Platform;
+import org.eclipse.core.runtime.content.IContentType;
+import org.eclipse.jface.wizard.IWizardPage;
+import org.eclipse.jface.wizard.Wizard;
+import org.eclipse.jface.wizard.WizardPage;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.events.ModifyEvent;
+import org.eclipse.swt.events.ModifyListener;
+import org.eclipse.swt.events.SelectionEvent;
+import org.eclipse.swt.events.SelectionListener;
+import org.eclipse.swt.layout.GridData;
+import org.eclipse.swt.layout.GridLayout;
+import org.eclipse.swt.widgets.Button;
+import org.eclipse.swt.widgets.Combo;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.DirectoryDialog;
+import org.eclipse.swt.widgets.FileDialog;
+import org.eclipse.swt.widgets.Label;
+import org.eclipse.swt.widgets.Text;
+import org.eclipse.ui.PlatformUI;
+import org.eclipse.wst.validation.internal.model.FilterRule;
+import org.eclipse.wst.validation.ui.internal.HelpContextIds;
+import org.eclipse.wst.validation.ui.internal.ValUIMessages;
+
+/**
+ * A wizard that adds new rules to validators.
+ * @author karasiuk
+ *
+ */
+public class NewFilterRule extends Wizard {
+
+ private Page1 _page1;
+ private IWizardPage _page2;
+
+ private IProject _project;
+
+ private FilterRule _rule;
+
+ public NewFilterRule(IProject project){
+ _project = project;
+ setWindowTitle(ValUIMessages.FrWizard);
+ _page1 = new Page1(project);
+ addPage(_page1);
+ setForcePreviousAndNextButtons(true);
+ }
+
+ public boolean canFinish() {
+ if (_page2 != null)return _page2.isPageComplete();
+ return false;
+ }
+
+ public FilterRule getRule(){
+ return _rule;
+ }
+
+ public boolean performFinish() {
+ if (_page2 == null)return false;
+ FilterWizardPage page = (FilterWizardPage)_page2;
+ _rule = page.getFilterRule();
+ return _rule != null;
+ }
+
+ public IWizardPage getNextPage(IWizardPage page) {
+ if (page == _page1){
+ setForcePreviousAndNextButtons(false);
+ _page2 = returnOrBuildPage(_page1.getSelectedFilter());
+ return _page2;
+ }
+ return null;
+ }
+
+ private IWizardPage returnOrBuildPage(int selectedFilter) {
+ IWizardPage page = null;
+ if (_project != null && selectedFilter == 2)selectedFilter = 4;
+ switch (selectedFilter){
+ case 0:
+ page = new FileExtPage();
+ break;
+ case 1:
+ page = new FilePage(_project);
+ break;
+ case 2:
+ page = new ProjectPage();
+ break;
+ case 3:
+ page = new FacetPage();
+ break;
+ case 4:
+ page = new ContentTypePage();
+ break;
+ }
+ addPage(page);
+ return page;
+ }
+
+ public static class Page1 extends WizardPage {
+
+ private int _selectedFilter;
+ private IProject _project;
+
+
+ public Page1(IProject project){
+ super("page1", ValUIMessages.FrSelectFilterType, null); //$NON-NLS-1$
+ setPageComplete(true);
+ _project = project;
+ }
+
+ public void createControl(Composite parent) {
+ String helpId = _project == null ? HelpContextIds.FilterRule : HelpContextIds.ProjectFilterRule;
+ PlatformUI.getWorkbench().getHelpSystem().setHelp(parent, helpId);
+ String[] labels = null;
+ String[] desc = null;
+ if (_project != null){
+ labels = new String[]{ValUIMessages.LabelExtension, ValUIMessages.LabelFile,
+ ValUIMessages.LabelContentType};
+
+ desc = new String[]{ValUIMessages.DescExtension, ValUIMessages.DescFile,
+ ValUIMessages.DescContentType};
+ }
+ else {
+ labels = new String[]{ValUIMessages.LabelExtension, ValUIMessages.LabelFile,
+ ValUIMessages.LabelProjects, ValUIMessages.LabelFacets,
+ ValUIMessages.LabelContentType};
+
+ desc = new String[]{ValUIMessages.DescExtension, ValUIMessages.DescFile,
+ ValUIMessages.DescProjects, ValUIMessages.DescFacets,
+ ValUIMessages.DescContentType};
+ }
+
+ Composite control = new Composite(parent, SWT.NONE);
+ control.setLayout(new GridLayout(2, false));
+
+ SelectionListener listener = new SelectionListener(){
+
+ public void widgetDefaultSelected(SelectionEvent e) {
+ doIt(e);
+ }
+
+ public void widgetSelected(SelectionEvent e) {
+ doIt(e);
+ }
+
+ private void doIt(SelectionEvent e){
+ if (e.getSource() instanceof Button){
+ Button b = (Button)e.getSource();
+ if (b.getData() instanceof Integer) {
+ Integer index = (Integer) b.getData();
+ setSelectedFilter(index.intValue());
+ }
+ }
+ }
+
+ };
+ for (int i=0; i<labels.length; i++){
+ Button button = new Button(control, SWT.RADIO);
+ button.setText(labels[i]);
+ button.setData(new Integer(i));
+ button.addSelectionListener(listener);
+ (new Label(control, SWT.WRAP)).setText(desc[i]);
+ if (i == 0)button.setSelection(true);
+ }
+ setControl(control);
+ }
+
+ public int getSelectedFilter() {
+ return _selectedFilter;
+ }
+
+ public void setSelectedFilter(int selectedFilter) {
+ _selectedFilter = selectedFilter;
+ getContainer().updateButtons();
+ }
+
+ }
+
+ public static class FileExtPage extends WizardPage implements FilterWizardPage {
+
+ private Text _pattern;
+ private Button _case;
+
+ public FileExtPage(){
+ super("fileext", ValUIMessages.FrFileExtension, null); //$NON-NLS-1$
+ }
+
+ public void createControl(Composite parent) {
+ PlatformUI.getWorkbench().getHelpSystem().setHelp(parent, HelpContextIds.FRFileExt);
+ Composite control = new Composite(parent, SWT.NONE);
+ setControl(control);
+ control.setLayout(new GridLayout(2, false));
+ (new Label(control, SWT.NONE)).setText(ValUIMessages.FrFileExtensionLabel);
+ _pattern = new Text(control, SWT.NONE);
+ _pattern.setFocus();
+ _pattern.addModifyListener(new ModifyListener(){
+
+ public void modifyText(ModifyEvent e) {
+ getContainer().updateButtons();
+ }
+
+ });
+
+ _case = new Button(control, SWT.CHECK);
+ _case.setText(ValUIMessages.FrCaseSensitive);
+ _case.setSelection(false);
+ _case.setLayoutData(new GridData(SWT.BEGINNING, SWT.BEGINNING,false, false, 2, 1));
+
+ }
+
+ public FilterRule getFilterRule() {
+ if (!isPageComplete())return null;
+ return FilterRule.FileExt.createFileExt(_pattern.getText(), _case.getSelection());
+ }
+
+ public boolean isPageComplete() {
+ return _pattern != null && _pattern.getText().trim().length() > 0;
+ }
+
+
+ }
+
+ public static class FilePage extends WizardPage implements FilterWizardPage {
+
+ private Text _pattern;
+ private Button _browseFile;
+ private Button _browseFolder;
+ private Button _case;
+ private Button _simpleFileName;
+
+ private IProject _project;
+ private int _type = FilterRule.File.FileTypeFile;
+ private IPath _fullFileName;
+ private String _root;
+
+ public FilePage(IProject project){
+ super("file", ValUIMessages.FrFolderOrFile, null); //$NON-NLS-1$
+ _project = project;
+ }
+
+ public void createControl(Composite parent) {
+ PlatformUI.getWorkbench().getHelpSystem().setHelp(parent, HelpContextIds.FRName);
+ final Composite control = new Composite(parent, SWT.NONE);
+ setControl(control);
+ control.setLayout(new GridLayout(4, false));
+ (new Label(control, SWT.NONE)).setText(ValUIMessages.FrFolderOrFileLabel);
+ _pattern = new Text(control, SWT.NONE);
+ _pattern.setFocus();
+ _pattern.setLayoutData(new GridData(300, SWT.DEFAULT));
+ _pattern.addModifyListener(new ModifyListener(){
+
+ public void modifyText(ModifyEvent e) {
+ getContainer().updateButtons();
+ }
+
+ });
+
+ _root = null;
+ IPath base = _project == null ? ResourcesPlugin.getWorkspace().getRoot().getLocation() :
+ _project.getLocation();
+ if (base != null)_root = base.toOSString();
+
+ _browseFile = new Button(control, SWT.PUSH);
+ _browseFile.setText(ValUIMessages.FrBrowseFile);
+ _browseFile.setEnabled(_root != null);
+ _browseFile.addSelectionListener(new SelectionListener(){
+
+ public void widgetDefaultSelected(SelectionEvent e) {
+ browse();
+ }
+
+ public void widgetSelected(SelectionEvent e) {
+ browse();
+ }
+
+ private void browse(){
+ FileDialog fd = new FileDialog(control.getShell(), SWT.OPEN);
+ fd.setText(ValUIMessages.FrFileFilter);
+ fd.setFilterPath(_root);
+
+ String file = fd.open();
+ if (file != null){
+ if (file.startsWith(_root))file = file.substring(_root.length()+1);
+ else file = null;
+ }
+ if (file != null){
+ _fullFileName = new Path(file);
+ if (_project == null)_fullFileName = _fullFileName.removeFirstSegments(1);
+
+ if (_simpleFileName.getSelection()){
+ _type = FilterRule.File.FileTypeFile;
+ _pattern.setText(_fullFileName.lastSegment());
+ }
+ else {
+ _type = FilterRule.File.FileTypeFull;
+ _pattern.setText(_fullFileName.toPortableString());
+ }
+ }
+ else {
+ _fullFileName = null;
+ _pattern.setText(""); //$NON-NLS-1$
+ }
+ }
+ });
+
+ _browseFolder = new Button(control, SWT.PUSH);
+ _browseFolder.setText(ValUIMessages.FrBrowseFolder);
+ _browseFolder.setEnabled(_root != null);
+ _browseFolder.addSelectionListener(new SelectionListener(){
+
+ public void widgetDefaultSelected(SelectionEvent e) {
+ browse();
+ }
+
+ public void widgetSelected(SelectionEvent e) {
+ browse();
+ }
+
+ private void browse(){
+ DirectoryDialog fd = new DirectoryDialog(control.getShell());
+ fd.setMessage(ValUIMessages.FrFolderFilter);
+ fd.setFilterPath(_root);
+ String dir = fd.open();
+ if (dir != null){
+ _fullFileName = null;
+ _type = FilterRule.File.FileTypeFolder;
+ if (dir.startsWith(_root) && dir.length() > _root.length()){
+ dir = dir.substring(_root.length()+1);
+ IPath path = new Path(dir);
+ if (_project == null)path = path.removeFirstSegments(1);
+ _pattern.setText(path.toPortableString());
+ }
+ else {
+ _pattern.setText(""); //$NON-NLS-1$
+ }
+ }
+ }
+
+ });
+
+ _case = new Button(control, SWT.CHECK);
+ _case.setText(ValUIMessages.FrCaseSensitive);
+ _case.setSelection(false);
+ _case.setLayoutData(new GridData(SWT.BEGINNING, SWT.BEGINNING,false, false, 4, 1));
+
+ addSimpleFileNameButton(control);
+ }
+
+ private void addSimpleFileNameButton(final Composite control) {
+ _simpleFileName = new Button(control, SWT.CHECK);
+ _simpleFileName.setText(ValUIMessages.FrSimpleFileName);
+ _simpleFileName.setSelection(_type == FilterRule.File.FileTypeFile);
+ _simpleFileName.setLayoutData(new GridData(SWT.BEGINNING, SWT.BEGINNING,false, false, 4, 1));
+
+ _simpleFileName.addSelectionListener(new SelectionListener(){
+
+ public void widgetDefaultSelected(SelectionEvent e) {
+ }
+
+ public void widgetSelected(SelectionEvent e) {
+ if (_type == FilterRule.File.FileTypeFolder)return;
+ if (_simpleFileName.getSelection()){
+ if (_fullFileName != null)_pattern.setText(_fullFileName.lastSegment());
+ _type = FilterRule.File.FileTypeFile;
+ }
+ else {
+ if (_fullFileName != null)_pattern.setText(_fullFileName.toPortableString());
+ _type = FilterRule.File.FileTypeFull; }
+ }
+ });
+ }
+
+ public FilterRule getFilterRule() {
+ if (!isPageComplete())return null;
+ return FilterRule.createFile(_pattern.getText(), _case.getSelection(), _type);
+ }
+
+ public boolean isPageComplete() {
+ if (_pattern == null)return false;
+ if (_pattern.getText() == null)return false;
+ return _pattern.getText().trim().length() > 0;
+ }
+
+ }
+
+ public static class ProjectPage extends WizardPage implements FilterWizardPage{
+
+ private Combo _natures;
+ private String[] _ids;
+
+ public ProjectPage(){
+ super("project", ValUIMessages.FrProjectNature, null); //$NON-NLS-1$
+ }
+
+ public void createControl(Composite parent) {
+ PlatformUI.getWorkbench().getHelpSystem().setHelp(parent, HelpContextIds.FRProjectNature);
+ Composite control = new Composite(parent, SWT.NONE);
+ setControl(control);
+ control.setLayout(new GridLayout(2, false));
+ (new Label(control, SWT.NONE)).setText(ValUIMessages.FrProjectNatureLabel);
+
+ IProjectNatureDescriptor[] pn = ResourcesPlugin.getWorkspace().getNatureDescriptors();
+ String items[] = new String[pn.length];
+ _ids = new String[pn.length];
+ for (int i=0; i<pn.length; i++){
+ _ids[i] = pn[i].getNatureId();
+ items[i] = pn[i].getLabel() + " - " + _ids[i]; //$NON-NLS-1$
+ }
+ _natures = new Combo(control, SWT.DROP_DOWN);
+ _natures.setItems(items);
+ _natures.addModifyListener(new ModifyListener(){
+
+ public void modifyText(ModifyEvent e) {
+ getContainer().updateButtons();
+ }
+
+ });
+
+ }
+
+ public FilterRule getFilterRule() {
+ if (!isPageComplete())return null;
+ int i = _natures.getSelectionIndex();
+ if (i == -1)return null;
+
+ return FilterRule.createProject(_ids[i]);
+ }
+
+ public boolean isPageComplete() {
+ if (_natures == null)return false;
+ if (_natures.getText() == null)return false;
+ return _natures.getText().trim().length() > 0;
+ }
+
+ }
+
+ public static class FacetPage extends WizardPage implements FilterWizardPage {
+
+ private Text _pattern;
+
+ public FacetPage(){
+ super("facet", ValUIMessages.FrFacit, null); //$NON-NLS-1$
+ }
+
+ public void createControl(Composite parent) {
+ PlatformUI.getWorkbench().getHelpSystem().setHelp(parent, HelpContextIds.FRFacet);
+ Composite control = new Composite(parent, SWT.NONE);
+ setControl(control);
+ control.setLayout(new GridLayout(2, false));
+ (new Label(control, SWT.NONE)).setText(ValUIMessages.FrFacitLabel);
+ _pattern = new Text(control, SWT.NONE);
+ _pattern.setFocus();
+ _pattern.setLayoutData(new GridData(300, SWT.DEFAULT));
+ _pattern.addModifyListener(new ModifyListener(){
+
+ public void modifyText(ModifyEvent e) {
+ getContainer().updateButtons();
+ }
+
+ });
+ }
+
+ public FilterRule getFilterRule() {
+ if (!isPageComplete())return null;
+ FilterRule rule = FilterRule.createFacet(_pattern.getText());
+ return rule;
+ }
+
+ public boolean isPageComplete() {
+ if (_pattern == null)return false;
+ if (_pattern.getText() == null)return false;
+ return _pattern.getText().trim().length() > 0;
+ }
+
+ }
+
+ public static class ContentTypePage extends WizardPage implements FilterWizardPage {
+ private Combo _pattern;
+ private Button _exactMatch;
+ private Map<String, IContentType> _map;
+
+ public ContentTypePage(){
+ super("contentType", ValUIMessages.FrContentType, null); //$NON-NLS-1$
+ }
+
+ public void createControl(Composite parent) {
+ PlatformUI.getWorkbench().getHelpSystem().setHelp(parent, HelpContextIds.FRContentType);
+ Composite control = new Composite(parent, SWT.NONE);
+ setControl(control);
+ control.setLayout(new GridLayout(2, false));
+ (new Label(control, SWT.NONE)).setText(ValUIMessages.FrContentTypeLabel);
+
+ IContentType[] types = Platform.getContentTypeManager().getAllContentTypes();
+ _map = new TreeMap<String, IContentType>();
+ for (IContentType type : types){
+ String name = type.getName();
+ if (name == null)name = type.getId();
+ _map.put(name, type);
+ }
+ String items[] = new String[_map.size()];
+ int i = 0;
+ for (String label : _map.keySet()){
+ items[i++] = label;
+ }
+ _pattern = new Combo(control, SWT.DROP_DOWN | SWT.READ_ONLY);
+ _pattern.setFocus();
+ _pattern.setLayoutData(new GridData(300, SWT.DEFAULT));
+ _pattern.setVisibleItemCount(20);
+ _pattern.setItems(items);
+ _pattern.addModifyListener(new ModifyListener(){
+
+ public void modifyText(ModifyEvent e) {
+ getContainer().updateButtons();
+ }
+
+ });
+
+ _exactMatch = new Button(control, SWT.CHECK);
+ _exactMatch.setText(ValUIMessages.FrExactMatch);
+ _exactMatch.setSelection(false);
+ _exactMatch.setLayoutData(new GridData(SWT.BEGINNING, SWT.BEGINNING,false, false, 2, 1));
+
+ }
+
+ public FilterRule getFilterRule() {
+ if (!isPageComplete())return null;
+ IContentType type = _map.get(_pattern.getText());
+ if (type == null)return null;
+ FilterRule rule = FilterRule.createContentType(type.getId(), _exactMatch.getSelection());
+ return rule;
+ }
+
+ public boolean isPageComplete() {
+ if (_pattern == null)return false;
+ if (_pattern.getText() == null)return false;
+ return _pattern.getText().trim().length() > 0;
+ }
+
+ }
+
+ interface FilterWizardPage {
+ /**
+ * Answer the rule that was created.
+ *
+ * @return null if the user didn't create a new rule.
+ */
+ FilterRule getFilterRule();
+ }
+
+
+}
diff --git a/plugins/org.eclipse.wst.validation.ui/vf2/org/eclipse/wst/validation/ui/internal/dialog/ResultsDialog.java b/plugins/org.eclipse.wst.validation.ui/vf2/org/eclipse/wst/validation/ui/internal/dialog/ResultsDialog.java
new file mode 100644
index 0000000..3534eb7
--- /dev/null
+++ b/plugins/org.eclipse.wst.validation.ui/vf2/org/eclipse/wst/validation/ui/internal/dialog/ResultsDialog.java
@@ -0,0 +1,162 @@
+/*******************************************************************************
+ * Copyright (c) 2008 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+
+package org.eclipse.wst.validation.ui.internal.dialog;
+
+
+import org.eclipse.jface.dialogs.ErrorDialog;
+import org.eclipse.jface.dialogs.IDialogConstants;
+import org.eclipse.jface.dialogs.IconAndMessageDialog;
+import org.eclipse.jface.layout.GridDataFactory;
+import org.eclipse.osgi.util.NLS;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.graphics.Image;
+import org.eclipse.swt.widgets.Button;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.Control;
+import org.eclipse.swt.widgets.Label;
+import org.eclipse.swt.widgets.Shell;
+import org.eclipse.wst.validation.internal.Misc;
+import org.eclipse.wst.validation.internal.ValManager;
+import org.eclipse.wst.validation.internal.ValPrefManagerGlobal;
+import org.eclipse.wst.validation.internal.ValidationResultSummary;
+import org.eclipse.wst.validation.internal.model.GlobalPreferences;
+import org.eclipse.wst.validation.internal.model.GlobalPreferencesValues;
+import org.eclipse.wst.validation.internal.ui.ValidationUIMessages;
+import org.eclipse.wst.validation.ui.internal.ValUIMessages;
+
+/**
+ * A dialog for displaying the results of a manual validation.
+ * @author karasiuk
+ *
+ */
+public class ResultsDialog extends IconAndMessageDialog {
+
+ private ValidationResultSummary _result;
+ private long _time;
+ private int _resourceCount;
+ private Button _hideButton;
+
+ /**
+ * Create a dialog for displaying validation results.
+ *
+ * @param parentShell this can be null
+ * @param results the results of the validation
+ * @param time the time that the validation took in milliseconds
+ * @param resourceCount the number of resources that were validated
+ */
+ public ResultsDialog(Shell parentShell, ValidationResultSummary results, long time, int resourceCount) {
+ super(parentShell);
+ _result = results;
+ _time = time;
+ _resourceCount = resourceCount;
+ }
+
+ @Override
+ protected void okPressed() {
+ if(_hideButton!=null) {
+ ValManager vm = ValManager.getDefault();
+ GlobalPreferences gp = vm.getGlobalPreferences();
+ GlobalPreferencesValues gpv = gp.asValues();
+ gpv.confirmDialog = !_hideButton.getSelection();
+ int changes = vm.replace(gpv);
+ if (changes != 0)ValPrefManagerGlobal.getDefault().savePreferences();
+ }
+ super.okPressed();
+ }
+
+ @Override
+ public int open() {
+ if (!ErrorDialog.AUTOMATED_MODE) {
+ return super.open();
+ }
+ setReturnCode(OK);
+ return OK;
+ }
+
+ @Override
+ protected Image getImage() {
+ if (_result.getSeverityError() > 0)return getErrorImage();
+ if (_result.getSeverityWarning() > 0)return getWarningImage();
+ return getInfoImage();
+ }
+
+ @Override
+ protected Control createDialogArea(Composite parent) {
+ message = getMessage();
+ createMessageArea(parent);
+
+ new Label(parent, SWT.NONE).setLayoutData(GridDataFactory.swtDefaults().span(2, 1).create());
+ addHideCheckbox(parent);
+
+ Control c = super.createDialogArea(parent);
+ return c;
+ }
+
+ private void addHideCheckbox(Composite parent) {
+ _hideButton = new Button(parent, SWT.CHECK);
+ GridDataFactory.swtDefaults().align(SWT.BEGINNING, SWT.BEGINNING).span(2, 1).applyTo(_hideButton);
+ _hideButton.setText(ValUIMessages.DoNotShowResults);
+ if (ValManager.getDefault().getGlobalPreferences().getConfirmDialog() && _hideButton.getSelection()) {
+ // tell the user where to re-enable it?
+ }
+ _hideButton.setSelection(!ValManager.getDefault().getGlobalPreferences().getConfirmDialog());
+ }
+
+
+ @Override
+ protected void configureShell(Shell newShell) {
+ super.configureShell(newShell);
+ newShell.setText(ValidationUIMessages.ValResults);
+ }
+
+ @Override
+ protected void createButtonsForButtonBar(Composite parent) {
+ Button ok = createButton(parent, IDialogConstants.OK_ID, IDialogConstants.OK_LABEL, false);
+ ok.setFocus();
+ }
+
+ private String getMessage(){
+ if (_resourceCount > 1) {
+ if (_result.getSeverityError() > 1)
+ return NLS.bind(ValidationUIMessages.ValErrorsResources, new Object[]{_result.getSeverityError(), _resourceCount, Misc.getTimeMS(_time)});
+ if (_result.getSeverityError() == 1)
+ return NLS.bind(ValidationUIMessages.ValError1Resources, _resourceCount, Misc.getTimeMS(_time));
+
+ if (_result.getSeverityWarning() > 1)
+ return NLS.bind(ValidationUIMessages.ValWarnResources, new Object[]{_result.getSeverityWarning(), _resourceCount, Misc.getTimeMS(_time)});
+ if (_result.getSeverityWarning() == 1)
+ return NLS.bind(ValidationUIMessages.ValWarn1Resources, _resourceCount, Misc.getTimeMS(_time));
+
+ if (_result.getSeverityInfo() > 1)
+ return NLS.bind(ValidationUIMessages.ValInfoResources, new Object[]{_result.getSeverityInfo(), _resourceCount, Misc.getTimeMS(_time)});
+ if (_result.getSeverityInfo() == 1)
+ return NLS.bind(ValidationUIMessages.ValInfo1Resources, _resourceCount, Misc.getTimeMS(_time));
+ }
+ else if (_resourceCount == 1) {
+ if (_result.getSeverityError() > 1)
+ return NLS.bind(ValidationUIMessages.ValErrorsResource1, _result.getSeverityError(), Misc.getTimeMS(_time));
+ if (_result.getSeverityError() == 1)
+ return NLS.bind(ValidationUIMessages.ValError1Resource1, Misc.getTimeMS(_time));
+
+ if (_result.getSeverityWarning() > 1)
+ return NLS.bind(ValidationUIMessages.ValWarnResource1, _result.getSeverityWarning(), Misc.getTimeMS(_time));
+ if (_result.getSeverityWarning() == 1)
+ return NLS.bind(ValidationUIMessages.ValWarn1Resource1, Misc.getTimeMS(_time));
+
+ if (_result.getSeverityInfo() > 1)
+ return NLS.bind(ValidationUIMessages.ValInfoResource1, _result.getSeverityInfo(), Misc.getTimeMS(_time));
+ if (_result.getSeverityInfo() == 1)
+ return NLS.bind(ValidationUIMessages.ValInfo1Resource1, Misc.getTimeMS(_time));
+ }
+ return ValidationUIMessages.ValSuccess;
+ }
+}
diff --git a/plugins/org.eclipse.wst.validation.ui/vf2/org/eclipse/wst/validation/ui/internal/preferences/ValidationPreferencePage.java b/plugins/org.eclipse.wst.validation.ui/vf2/org/eclipse/wst/validation/ui/internal/preferences/ValidationPreferencePage.java
new file mode 100644
index 0000000..30e1556
--- /dev/null
+++ b/plugins/org.eclipse.wst.validation.ui/vf2/org/eclipse/wst/validation/ui/internal/preferences/ValidationPreferencePage.java
@@ -0,0 +1,844 @@
+/*******************************************************************************
+ * Copyright (c) 2001, 2008 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.wst.validation.ui.internal.preferences;
+
+import java.lang.reflect.InvocationTargetException;
+import java.util.LinkedList;
+import java.util.List;
+
+import org.eclipse.jface.dialogs.MessageDialog;
+import org.eclipse.jface.layout.GridDataFactory;
+import org.eclipse.jface.preference.PreferencePage;
+import org.eclipse.jface.viewers.IStructuredContentProvider;
+import org.eclipse.jface.viewers.IStructuredSelection;
+import org.eclipse.jface.viewers.ITableLabelProvider;
+import org.eclipse.jface.viewers.LabelProvider;
+import org.eclipse.jface.viewers.TableViewer;
+import org.eclipse.jface.viewers.Viewer;
+import org.eclipse.jface.viewers.ViewerSorter;
+import org.eclipse.jface.window.Window;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.custom.ScrolledComposite;
+import org.eclipse.swt.events.FocusAdapter;
+import org.eclipse.swt.events.FocusEvent;
+import org.eclipse.swt.events.MenuAdapter;
+import org.eclipse.swt.events.MenuEvent;
+import org.eclipse.swt.events.MouseAdapter;
+import org.eclipse.swt.events.MouseEvent;
+import org.eclipse.swt.events.SelectionAdapter;
+import org.eclipse.swt.events.SelectionEvent;
+import org.eclipse.swt.graphics.Image;
+import org.eclipse.swt.graphics.Point;
+import org.eclipse.swt.graphics.Rectangle;
+import org.eclipse.swt.layout.GridData;
+import org.eclipse.swt.layout.GridLayout;
+import org.eclipse.swt.widgets.Button;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.Control;
+import org.eclipse.swt.widgets.Display;
+import org.eclipse.swt.widgets.Label;
+import org.eclipse.swt.widgets.Menu;
+import org.eclipse.swt.widgets.MenuItem;
+import org.eclipse.swt.widgets.MessageBox;
+import org.eclipse.swt.widgets.Shell;
+import org.eclipse.swt.widgets.Table;
+import org.eclipse.swt.widgets.TableColumn;
+import org.eclipse.swt.widgets.TableItem;
+import org.eclipse.ui.IWorkbench;
+import org.eclipse.ui.IWorkbenchPreferencePage;
+import org.eclipse.ui.PlatformUI;
+import org.eclipse.wst.validation.Validator;
+import org.eclipse.wst.validation.internal.ConfigurationManager;
+import org.eclipse.wst.validation.internal.FullBuildJob;
+import org.eclipse.wst.validation.internal.GlobalConfiguration;
+import org.eclipse.wst.validation.internal.ValManager;
+import org.eclipse.wst.validation.internal.ValPrefManagerGlobal;
+import org.eclipse.wst.validation.internal.ValidatorMetaData;
+import org.eclipse.wst.validation.internal.ValidatorMutable;
+import org.eclipse.wst.validation.internal.model.GlobalPreferences;
+import org.eclipse.wst.validation.internal.model.GlobalPreferencesValues;
+import org.eclipse.wst.validation.internal.ui.DelegatingValidatorPreferencesDialog;
+import org.eclipse.wst.validation.internal.ui.plugin.ValidationUIPlugin;
+import org.eclipse.wst.validation.ui.internal.HelpContextIds;
+import org.eclipse.wst.validation.ui.internal.ImageNames;
+import org.eclipse.wst.validation.ui.internal.ValUIMessages;
+import org.eclipse.wst.validation.ui.internal.dialog.FilterDialog;
+
+/**
+ * From this page the user can configure individual validators.
+ * <p>
+ * This class and its inner classes are not intended to be subclassed outside of
+ * the validation framework.
+ * </p>
+ */
+public class ValidationPreferencePage extends PreferencePage implements IWorkbenchPreferencePage {
+
+ private IValidationPage _pageImpl = null;
+ private Shell _shell;
+
+ public interface IValidationPage {
+
+ Composite createPage(Composite parent) throws InvocationTargetException;
+ boolean performOk() throws InvocationTargetException;
+ boolean performDefaults() throws InvocationTargetException;
+ Composite getControl();
+ void dispose();
+ void loseFocus();
+ void gainFocus();
+ }
+
+ public final class InvalidPage implements IValidationPage {
+ private Composite page = null;
+
+ private Composite composite = null;
+ private GridLayout layout = null;
+ private Label messageLabel = null;
+
+ public InvalidPage(Composite parent) {
+ page = createPage(parent);
+ }
+
+ /**
+ * This page is added to the Properties guide if some internal problem
+ * occurred; for example, the highlighted item in the workbench is not
+ * an IProject (according to this page's plugin.xml, this page is only
+ * valid when an IProject is selected).
+ */
+ public Composite createPage(Composite parent) {
+ // Don't create the default and apply buttons.
+ noDefaultAndApplyButton();
+
+ final ScrolledComposite sc1 = new ScrolledComposite(parent, SWT.H_SCROLL | SWT.V_SCROLL);
+ sc1.setLayoutData(new GridData(GridData.FILL_BOTH));
+ composite = new Composite(sc1, SWT.NONE);
+ sc1.setContent(composite);
+ layout = new GridLayout();
+ composite.setLayout(layout);
+
+ messageLabel = new Label(composite, SWT.NONE);
+ messageLabel.setText(ValUIMessages.VBF_EXC_INVALID_REGISTER);
+
+ composite.setSize(composite.computeSize(SWT.DEFAULT, SWT.DEFAULT));
+
+ return composite;
+ }
+
+ public boolean performDefaults() {
+ return true;
+ }
+
+ /**
+ * Since this page occurs under invalid circumstances, there is nothing
+ * to save.
+ */
+ public boolean performOk() {
+ return true;
+ }
+
+ public Composite getControl() {
+ return page;
+ }
+
+ public void dispose() {
+ messageLabel.dispose();
+ // layout.dispose();
+ composite.dispose();
+ }
+
+ public void loseFocus() {
+ // This page does not depend on the contents of any other page in
+ // the wizard, so do nothing.
+ }
+
+ public void gainFocus() {
+ // This page does not depend on the contents of any other page in
+ // the wizard, so do nothing.
+ }
+ }
+
+ private final class ValidatorListPage implements IValidationPage {
+ private Composite _page;
+ private TableViewer _validatorList;
+ private Button _enableAllButton;
+ private Button _disableAllButton;
+ private Button _override;
+ private Button _suspend;
+ private Button _autoSave;
+ private Button _confirmButton;
+ private Label _listLabel;
+ private Table _validatorsTable;
+ private GlobalPreferencesValues _globalPreferences = ValManager.getDefault().getGlobalPreferences().asValues();
+ private GlobalConfiguration _globalConfig;
+ private ValidatorMutable[] _validators;
+
+ private int _changeCount;
+
+ /**
+ * This class is provided for the CheckboxTableViewer in the
+ * ValidationPropertiesPage$ValidatorListPage class.
+ */
+ public class ValidationContentProvider implements IStructuredContentProvider {
+ public void dispose() {
+ }
+
+ public Object[] getElements(Object inputElement) {
+ if (inputElement instanceof ValidatorMutable[]) {
+ return (ValidatorMutable[]) inputElement;
+ }
+ return new Object[0];
+ }
+
+ public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
+ }
+ }
+
+ /**
+ * This class is provided for
+ * ValidationPropertiesPage$ValidatorListPage's checkboxTableViewer element.
+ */
+ public class ValidationLabelProvider extends LabelProvider implements ITableLabelProvider {
+ public String getText(Object element) {
+ if (element == null)return ""; //$NON-NLS-1$
+ else if (element instanceof ValidatorMutable)
+ return ((ValidatorMutable) element).getName();
+ else
+ return super.getText(element);
+ }
+
+ private Image getImage(String imageName) {
+ boolean isDisabled = !_validatorsTable.isEnabled();
+ if (isDisabled)imageName = imageName + ImageNames.disabled;
+
+ return ValidationUIPlugin.getPlugin().getImage(imageName);
+ }
+
+ public Image getColumnImage(Object element, int columnIndex) {
+ ValidatorMutable v = (ValidatorMutable) element;
+ if (columnIndex == 1) {
+ return getImage(v.isManualValidation() ? ImageNames.okTable : ImageNames.failTable);
+ } else if (columnIndex == 2) {
+ return getImage(v.isBuildValidation() ? ImageNames.okTable : ImageNames.failTable);
+ } else if (columnIndex == 3) {
+ if (hasSettings(v))return getImage(ImageNames.settings);
+ return null;
+
+ }
+ return null;
+ }
+
+ public String getColumnText(Object element, int columnIndex) {
+ if (columnIndex == 0)return ((ValidatorMutable) element).getName();
+ return null;
+ }
+ }
+
+ /**
+ * This class is used to sort the CheckboxTableViewer elements.
+ */
+ public class ValidationViewerSorter extends ViewerSorter {
+ public int compare(Viewer viewer, Object e1, Object e2) {
+ // Can't instantiate ViewerSorter because it's abstract, so use this
+ // inner class to represent it.
+ return super.compare(viewer, e1, e2);
+ }
+ }
+
+ public ValidatorListPage(Composite parent) throws InvocationTargetException {
+ _page = createPage(parent);
+ }
+
+ private void setupTableColumns(Table table) {
+ TableColumn validatorColumn = new TableColumn(table, SWT.NONE);
+ validatorColumn.setText(ValUIMessages.VALIDATOR);
+ validatorColumn.setWidth(245);
+ TableColumn manualColumn = new TableColumn(table, SWT.CENTER);
+ manualColumn.setText(ValUIMessages.MANUAL);
+ manualColumn.pack();
+ TableColumn buildColumn = new TableColumn(table, SWT.CENTER);
+ buildColumn.setText(ValUIMessages.BUILD);
+ buildColumn.pack();
+ TableColumn settingsColumn = new TableColumn(table, SWT.CENTER);
+ settingsColumn.setText(ValUIMessages.SETTINGS);
+ settingsColumn.pack();
+ }
+
+ private ValidatorMutable[] getDefaultValidators(){
+ Validator[] vals = ValManager.getDefault().getValidators();
+ ValidatorMutable[] vms = new ValidatorMutable[vals.length];
+ for (int i=0; i<vals.length; i++)vms[i] = new ValidatorMutable(vals[i]);
+ return vms;
+ }
+
+ public Composite createPage(Composite parent) throws InvocationTargetException {
+ _globalConfig = new GlobalConfiguration(ConfigurationManager.getManager().getGlobalConfiguration());
+ _validators = getDefaultValidators();
+
+ Composite validatorGroup = new Composite(parent, SWT.NONE);
+
+ GridLayout validatorGroupLayout = new GridLayout();
+ validatorGroupLayout.numColumns = 2;
+ validatorGroup.setLayout(validatorGroupLayout);
+ GridDataFactory.fillDefaults().grab(true, true).applyTo(validatorGroup);
+
+ new Label(validatorGroup, SWT.NONE).setLayoutData(new GridData());
+
+ addOverride(validatorGroup);
+ addSuspend(validatorGroup);
+ addAutoSave(validatorGroup);
+ addConfirm(validatorGroup);
+
+ _listLabel = new Label(validatorGroup, SWT.NONE);
+ GridData listLabelData = new GridData(GridData.FILL_HORIZONTAL);
+ listLabelData.horizontalSpan = 2;
+ _listLabel.setLayoutData(listLabelData);
+ _listLabel.setText(ValUIMessages.PREF_VALLIST_TITLE);
+
+ _validatorsTable = new Table(validatorGroup, SWT.SINGLE | SWT.BORDER | SWT.FULL_SELECTION);
+ Point preferredSize = _validatorsTable.computeSize(SWT.DEFAULT, SWT.DEFAULT);
+ GridDataFactory.fillDefaults().grab(true, true).hint(preferredSize)
+ .span(2,1).applyTo(_validatorsTable);
+
+
+ _validatorsTable.setHeaderVisible(true);
+ _validatorsTable.setLinesVisible(true);
+
+ _validatorList = new TableViewer(_validatorsTable);
+// _validatorsTable.setLayoutData(validatorListData);
+// _validatorList.getTable().setLayoutData(validatorListData);
+ _validatorList.setLabelProvider(new ValidationLabelProvider());
+ _validatorList.setContentProvider(new ValidationContentProvider());
+ _validatorList.setSorter(new ValidationViewerSorter());
+ setupTableColumns(_validatorsTable);
+
+ _validatorList.setInput(_validators);
+ _validatorsTable.addMouseListener(new MouseAdapter() {
+
+ public void mouseDown(MouseEvent e) {
+ if (e.button != 1)return;
+
+ TableItem tableItem = _validatorsTable.getItem(new Point(e.x, e.y));
+ if (tableItem == null || tableItem.isDisposed())return;
+ int columnNumber;
+ int columnsCount = _validatorsTable.getColumnCount();
+ if (columnsCount == 0) {
+ // If no TableColumn, Table acts as if it has a single
+ // column which takes the whole width.
+ columnNumber = 0;
+ } else {
+ columnNumber = -1;
+ for (int i = 0; i < columnsCount; i++) {
+ Rectangle bounds = tableItem.getBounds(i);
+ if (bounds.contains(e.x, e.y)) {
+ columnNumber = i;
+ break;
+ }
+ }
+ if (columnNumber == -1)return;
+ }
+
+ columnClicked(columnNumber);
+ }
+ });
+
+ _validatorsTable.setMenu(createContextMenu());
+ _validatorsTable.addFocusListener(new FocusAdapter() {
+
+ public void focusGained(FocusEvent e) {
+ super.focusGained(e);
+ if (_validatorsTable.getSelectionCount() == 0) {
+ _validatorsTable.select(0);
+ }
+ }
+ });
+
+ addEnableDisable(validatorGroup);
+
+ // Have to set the tab order or only the first checkbox in a
+ // Composite can be tabbed to. (Seems to apply only to checkboxes. Have to use the
+ // arrow key to navigate the checkboxes.)
+ validatorGroup.setTabList(new Control[] { _suspend, _autoSave,
+ _validatorsTable, _enableAllButton, _disableAllButton });
+
+ updateWidgets();
+
+ applyDialogFont(validatorGroup);
+ validatorGroup.setSize(validatorGroup.computeSize(SWT.DEFAULT, SWT.DEFAULT));
+ return validatorGroup;
+ }
+
+ private void addEnableDisable(Composite validatorGroup) {
+ _enableAllButton = new Button(validatorGroup, SWT.PUSH);
+ _enableAllButton.setLayoutData(new GridData());
+ _enableAllButton.setText(ValUIMessages.PREF_BUTTON_ENABLEALL);
+ _enableAllButton.addSelectionListener(new SelectionAdapter() {
+ public void widgetSelected(SelectionEvent e) {
+ try {
+ performEnableAll();
+ } catch (InvocationTargetException exc) {
+ displayAndLogError(ValUIMessages.VBF_EXC_INTERNAL_TITLE,
+ ValUIMessages.VBF_EXC_INTERNAL_PAGE, exc);
+ }
+ }
+ });
+
+ _disableAllButton = new Button(validatorGroup, SWT.PUSH);
+ _disableAllButton.setLayoutData(new GridData());
+ _disableAllButton.setText(ValUIMessages.PREF_BUTTON_DISABLEALL);
+ _disableAllButton.addSelectionListener(new SelectionAdapter() {
+ public void widgetSelected(SelectionEvent e) {
+ try {
+ performDisableAll();
+ } catch (InvocationTargetException exc) {
+ displayAndLogError(ValUIMessages.VBF_EXC_INTERNAL_TITLE,
+ ValUIMessages.VBF_EXC_INTERNAL_PAGE, exc);
+ }
+ }
+ });
+ }
+
+ private void addConfirm(Composite validatorGroup) {
+ GridData gd;
+ gd = new GridData(GridData.FILL_HORIZONTAL);
+ gd.horizontalSpan = 2;
+ _confirmButton = new Button(validatorGroup, SWT.CHECK);
+ _confirmButton.setLayoutData(gd);
+ _confirmButton.setText(ValUIMessages.PrefPageConfirmDialog);
+ _confirmButton.setSelection(_globalPreferences.confirmDialog);
+ _confirmButton.addSelectionListener(new SelectionAdapter() {
+ public void widgetSelected(SelectionEvent e) {
+ // do not increment the _changeCount as this by itself should not trigger a build prompt
+ _globalPreferences.confirmDialog = _confirmButton.getSelection();
+ _confirmButton.setFocus();
+ }
+ });
+ }
+
+ private void addAutoSave(Composite validatorGroup) {
+ GridData gd;
+ gd = new GridData(GridData.FILL_HORIZONTAL);
+ gd.horizontalSpan = 2;
+ _autoSave = new Button(validatorGroup, SWT.CHECK);
+ _autoSave.setLayoutData(gd);
+ _autoSave.setText(ValUIMessages.PrefPage_always_save);
+ _autoSave.setSelection(_globalPreferences.saveAutomatically);
+ _autoSave.addSelectionListener(new SelectionAdapter() {
+ public void widgetSelected(SelectionEvent e) {
+ // do not increment the _changeCount as this by itself should not trigger a build prompt
+ _globalPreferences.saveAutomatically = _autoSave.getSelection();
+ _autoSave.setFocus();
+ }
+ });
+ }
+
+ private void addSuspend(Composite validatorGroup) {
+ GridData gd;
+ gd = new GridData(GridData.FILL_HORIZONTAL);
+ gd.horizontalSpan = 2;
+
+ _suspend = new Button(validatorGroup, SWT.CHECK);
+ _suspend.setLayoutData(gd);
+ _suspend.setText(ValUIMessages.DISABLE_VALIDATION);
+ _suspend.setSelection(_globalPreferences.disableAllValidation);
+ _suspend.addSelectionListener(new SelectionAdapter() {
+ public void widgetSelected(SelectionEvent e) {
+ _suspend.setFocus();
+ _validatorsTable.setEnabled(!_suspend.getSelection());
+ _enableAllButton.setEnabled(!_suspend.getSelection());
+ _disableAllButton.setEnabled(!_suspend.getSelection());
+ _validatorList.refresh();
+ }
+ });
+ }
+
+ private void addOverride(Composite validatorGroup) {
+ GridData gd = new GridData(GridData.FILL_HORIZONTAL);
+ gd.horizontalSpan = 2;
+
+ _override = new Button(validatorGroup, SWT.CHECK);
+ _override.setLayoutData(gd);
+ _override.setText(ValUIMessages.PREF_BUTTON_OVERRIDE);
+ _override.setEnabled(true);
+ _override.setSelection(_globalPreferences.override);
+ _override.addSelectionListener(new SelectionAdapter() {
+ public void widgetSelected(SelectionEvent e) {
+ _globalPreferences.override = _override.getSelection();
+ _override.setFocus();
+
+ }
+ });
+ }
+
+ protected Menu createContextMenu() {
+ final Menu menu = new Menu(_validatorsTable.getShell(), SWT.POP_UP);
+ final MenuItem manualItem = new MenuItem(menu, SWT.CHECK);
+ manualItem.setText(ValUIMessages.PREF_MNU_MANUAL);
+ final MenuItem buildItem = new MenuItem(menu, SWT.CHECK);
+ buildItem.setText(ValUIMessages.PREF_MNU_BUILD);
+ final MenuItem settingsItem = new MenuItem(menu, SWT.PUSH);
+ settingsItem.setText(ValUIMessages.PREF_MNU_SETTINGS);
+
+ class MenuItemListener extends SelectionAdapter {
+ public void widgetSelected(SelectionEvent e) {
+ MenuItem menuItem = (MenuItem) e.getSource();
+ int index = menu.indexOf(menuItem) + 1;
+ columnClicked(index);
+ }
+ }
+ MenuItemListener listener = new MenuItemListener();
+ manualItem.addSelectionListener(listener);
+ buildItem.addSelectionListener(listener);
+ settingsItem.addSelectionListener(listener);
+
+ menu.addMenuListener(new MenuAdapter() {
+ public void menuShown(MenuEvent e) {
+ IStructuredSelection selection = (IStructuredSelection) _validatorList.getSelection();
+ ValidatorMutable vw = (ValidatorMutable) selection.getFirstElement();
+ manualItem.setSelection(vw.isManualValidation());
+ buildItem.setSelection(vw.isBuildValidation());
+ settingsItem.setEnabled(hasSettings(vw));
+ }
+ });
+
+ return menu;
+ }
+
+ protected void columnClicked(int columnToEdit) {
+ IStructuredSelection selection = (IStructuredSelection) _validatorList.getSelection();
+ ValidatorMutable val = (ValidatorMutable) selection.getFirstElement();
+
+ switch (columnToEdit) {
+ case 1:
+ _changeCount++;
+ val.setManualValidation(!val.isManualValidation());
+ break;
+ case 2:
+ _changeCount++;
+ val.setBuildValidation(!val.isBuildValidation());
+ break;
+ case 3:
+ if (val.isV2Validator()){
+ ValidatorMutable newVal = new ValidatorMutable(val);
+ FilterDialog fd = new FilterDialog(_shell, newVal, null);
+ if (Window.OK == fd.open()){
+ _changeCount++;
+ newVal = fd.getValidator();
+ int i = findit(val);
+ if (i != -1)_validators[i] = newVal;
+ }
+ }
+ else {
+ handleOldDelegate(val);
+ }
+
+ break;
+ default:
+ break;
+ }
+ _validatorList.refresh();
+ }
+
+ private int findit(ValidatorMutable val) {
+ for (int i=0; i<_validators.length; i++)if (_validators[i] == val)return i;
+ return -1;
+ }
+
+ private void handleOldDelegate(ValidatorMutable val) {
+ if (!val.isV1Validator())return;
+
+ ValidatorMetaData vmd = val.getVmd();
+ if (!vmd.isDelegating())return;
+
+ String delegateID = _globalConfig.getDelegateUniqueName(vmd);
+ Shell shell = Display.getCurrent().getActiveShell();
+ DelegatingValidatorPreferencesDialog dialog =
+ new DelegatingValidatorPreferencesDialog(shell, vmd, delegateID);
+
+ dialog.setBlockOnOpen(true);
+ dialog.create();
+
+ int result = dialog.open();
+ if (result == Window.OK){
+ _changeCount++;
+ _globalConfig.setDelegateUniqueName(vmd, dialog.getDelegateID());
+ }
+ }
+
+ /**
+ * Does this validator have extra settings that can be configured?
+ * @param v
+ * @return true if it does
+ */
+ boolean hasSettings(ValidatorMutable v){
+ if (v.isV2Validator())return true;
+ if (v.getDelegatingId() != null)return true;
+ return false;
+ }
+
+ protected void updateWidgets() throws InvocationTargetException {
+ // Need to update even the widgets that do not change based on another
+ // widgets because of performDefaults(). If performDefaults() is
+ // selected, then the pagePreferences values are reset, and these widgets
+ // might also need to be updated.
+ updateAllWidgets();
+ updateHelp();
+ }
+
+ private void updateAllWidgets() throws InvocationTargetException {
+ _suspend.setSelection(_globalPreferences.disableAllValidation);
+ _autoSave.setSelection(_globalPreferences.saveAutomatically);
+ _confirmButton.setSelection(_globalPreferences.confirmDialog);
+ _override.setSelection(_globalPreferences.override);
+ _validatorsTable.setEnabled(!_suspend.getSelection());
+ _enableAllButton.setEnabled(!_suspend.getSelection());
+ _disableAllButton.setEnabled(!_suspend.getSelection());
+ _validatorList.setInput(_validators);
+ _validatorList.refresh();
+ }
+
+ public boolean performOk() throws InvocationTargetException {
+ _globalPreferences.disableAllValidation = _suspend.getSelection();
+ _globalPreferences.saveAutomatically = _autoSave.getSelection();
+ ValManager vm = ValManager.getDefault();
+ int changes = vm.replace(_globalPreferences);
+ if ((changes & GlobalPreferences.BuildChangeMask) != 0)_changeCount++;
+
+ ValPrefManagerGlobal vpm = ValPrefManagerGlobal.getDefault();
+ vpm.savePreferences(vm.getGlobalPreferences(), _validators, null);
+ saveV1Preferences();
+
+ if (_changeCount > 0 &&
+ MessageDialog.openQuestion(_shell, ValUIMessages.RebuildTitle, ValUIMessages.RebuildMsg)){
+
+ FullBuildJob fbj = new FullBuildJob();
+ fbj.schedule();
+ }
+ return true;
+ }
+
+ /**
+ * Save the V1 preferences, so that the old validators continue to work.
+ */
+ private void saveV1Preferences(){
+ try {
+ GlobalConfiguration gc = ConfigurationManager.getManager().getGlobalConfiguration();
+ gc.setDisableAllValidation(_globalPreferences.disableAllValidation);
+ gc.setEnabledManualValidators(getEnabledManualValidators());
+ gc.setEnabledBuildValidators(getEnabledBuildValidators());
+
+ gc.passivate();
+ gc.store();
+ }
+ catch (InvocationTargetException e){
+ ValidationUIPlugin.getPlugin().handleException(e);
+ }
+ }
+
+ /**
+ * Answer all the V1 validators that are manually enabled.
+ * @return
+ */
+ private ValidatorMetaData[] getEnabledManualValidators() {
+ List<ValidatorMetaData> list = new LinkedList<ValidatorMetaData>();
+ for (ValidatorMutable v : _validators){
+ if (v.isManualValidation() && v.isV1Validator())list.add(v.getVmd());
+ }
+ ValidatorMetaData[] result = new ValidatorMetaData[list.size()];
+ list.toArray(result);
+ return result;
+ }
+
+ /**
+ * Answer all the V1 validators that are enabled for build.
+ * @return
+ */
+ private ValidatorMetaData[] getEnabledBuildValidators() {
+ List<ValidatorMetaData> list = new LinkedList<ValidatorMetaData>();
+ for (ValidatorMutable v : _validators){
+ if (v.isBuildValidation() && v.isV1Validator())list.add(v.getVmd());
+ }
+ ValidatorMetaData[] result = new ValidatorMetaData[list.size()];
+ list.toArray(result);
+ return result;
+ }
+
+ public boolean performDefaults() throws InvocationTargetException {
+ _changeCount++;
+ Validator[] vals = ValManager.getDefaultValidators();
+ _validators = new ValidatorMutable[vals.length];
+ for (int i=0; i<vals.length; i++)_validators[i] = new ValidatorMutable(vals[i]);
+ updateWidgets();
+ getDefaultsButton().setFocus();
+ return true;
+ }
+
+ public boolean performEnableAll() throws InvocationTargetException {
+ setAllValidators(true);
+ _enableAllButton.setFocus();
+ _validatorList.refresh();
+ return true;
+ }
+
+ public boolean performDisableAll() throws InvocationTargetException {
+ setAllValidators(false);
+ _disableAllButton.setFocus();
+ _validatorList.refresh();
+ return true;
+ }
+
+ private void setAllValidators(boolean bool){
+ _changeCount++;
+ for (ValidatorMutable v : _validators){
+ v.setBuildValidation(bool);
+ v.setManualValidation(bool);
+ }
+ }
+
+ protected void updateHelp() {
+// PlatformUI.getWorkbench().getHelpSystem().setHelp(_suspend, ContextIds.VALIDATION_PREFERENCE_PAGE_DISABLE_ALL_ENABLED);
+ }
+
+ /*
+ * Store the current values of the controls into the preference store.
+ */
+
+ public Composite getControl() {
+ return _page;
+ }
+
+ public void dispose() {
+ _autoSave.dispose();
+ _suspend.dispose();
+ _disableAllButton.dispose();
+ _enableAllButton.dispose();
+ _listLabel.dispose();
+ _suspend.dispose();
+ _validatorList.getTable().dispose();
+ }
+
+ public void loseFocus() {
+ }
+
+ public void gainFocus() {
+ }
+ }
+
+ /*
+ * @see PreferencePage#createContents(Composite)
+ */
+ protected Control createContents(Composite parent) {
+ PlatformUI.getWorkbench().getHelpSystem().setHelp(parent, HelpContextIds.PreferencePage);
+ try {
+ _shell = parent.getShell();
+ _pageImpl = new ValidatorListPage(parent);
+ } catch (Exception exc) {
+ _pageImpl = new InvalidPage(parent);
+ displayAndLogError(ValUIMessages.VBF_EXC_INTERNAL_TITLE, ValUIMessages.VBF_EXC_INTERNAL_PAGE, exc);
+ }
+
+ return _pageImpl.getControl();
+ }
+
+ public void init(IWorkbench workbench) {
+ }
+
+ /**
+ * Performs special processing when this page's Defaults button has been
+ * pressed.
+ * <p>
+ * This is a framework hook method for subclasses to do special things when
+ * the Defaults button has been pressed. Subclasses may override, but should
+ * call <code>super.performDefaults</code>.
+ * </p>
+ */
+ protected void performDefaults() {
+ super.performDefaults();
+
+ try {
+ _pageImpl.performDefaults();
+ } catch (Exception exc) {
+ displayAndLogError(ValUIMessages.VBF_EXC_INTERNAL_TITLE, ValUIMessages.VBF_EXC_INTERNAL_PAGE, exc);
+ }
+ }
+
+ /**
+ * When the user presses the "OK" or "Apply" button on the Properties
+ * Guide/Properties Page, respectively, some processing is performed by this
+ * PropertyPage. If the page is found, and completes successfully, true is
+ * returned. Otherwise, false is returned, and the guide doesn't finish.
+ */
+ public boolean performOk() {
+ try {
+ return _pageImpl.performOk();
+ }
+ catch (Exception exc) {
+ displayAndLogError(ValUIMessages.VBF_EXC_INTERNAL_TITLE, ValUIMessages.VBF_EXC_INTERNAL_PAGE, exc);
+ return false;
+ }
+ }
+
+ /**
+ * Since the pages are inner classes of a child PreferencePage, not a
+ * PreferencePage itself, DialogPage's automatic disposal of its children's
+ * widgets cannot be used. Instead, dispose of each inner class' widgets
+ * explicitly.
+ */
+ public void dispose() {
+ super.dispose();
+ try {
+ if (_pageImpl != null) {
+ _pageImpl.dispose();
+ _pageImpl = null;
+ }
+
+ // TODO figure out what this thing did
+ // ExtensionManger.instance().getDelegate().disposePreferencePage();
+ } catch (Exception exc) {
+ displayAndLogError(ValUIMessages.VBF_EXC_INTERNAL_TITLE, ValUIMessages.VBF_EXC_INTERNAL_PAGE, exc);
+ }
+ }
+
+ private void logError(Throwable exc) {
+ ValidationUIPlugin.getPlugin().handleException(exc);
+ }
+
+ /*
+ * package visibility because if this method is private, then the compiler
+ * needs to create a synthetic accessor method for the internal classes, and
+ * that can have performance implications.
+ */
+ void displayAndLogError(String title, String message, Throwable exc) {
+ logError(exc);
+ displayMessage(title, message, org.eclipse.swt.SWT.ICON_ERROR);
+ }
+
+ private void displayMessage(String title, String message, int iIconType) {
+ MessageBox messageBox = new MessageBox(getShell(),
+ org.eclipse.swt.SWT.OK | iIconType | org.eclipse.swt.SWT.APPLICATION_MODAL);
+ messageBox.setMessage(message);
+ messageBox.setText(title);
+ messageBox.open();
+ }
+
+ /**
+ * @see org.eclipse.jface.dialogs.IDialogPage#setVisible(boolean)
+ */
+ public void setVisible(boolean visible) {
+ super.setVisible(visible);
+
+ if (_pageImpl == null)return;
+ if (visible)_pageImpl.gainFocus();
+ else _pageImpl.loseFocus();
+ }
+
+ protected Button getDefaultsButton() {
+ return super.getDefaultsButton();
+ }
+}
diff --git a/plugins/org.eclipse.wst.validation.ui/vf2/org/eclipse/wst/validation/ui/internal/preferences/ValidationPropertyPage.java b/plugins/org.eclipse.wst.validation.ui/vf2/org/eclipse/wst/validation/ui/internal/preferences/ValidationPropertyPage.java
new file mode 100644
index 0000000..9aabee4
--- /dev/null
+++ b/plugins/org.eclipse.wst.validation.ui/vf2/org/eclipse/wst/validation/ui/internal/preferences/ValidationPropertyPage.java
@@ -0,0 +1,872 @@
+/*******************************************************************************
+ * Copyright (c) 2001, 2008 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.wst.validation.ui.internal.preferences;
+
+import java.lang.reflect.InvocationTargetException;
+import org.eclipse.core.resources.ICommand;
+import org.eclipse.core.resources.IProject;
+import org.eclipse.core.resources.IProjectDescription;
+import org.eclipse.core.runtime.CoreException;
+import org.eclipse.core.runtime.IAdaptable;
+import org.eclipse.jface.dialogs.MessageDialog;
+import org.eclipse.jface.layout.GridDataFactory;
+import org.eclipse.jface.viewers.IStructuredContentProvider;
+import org.eclipse.jface.viewers.IStructuredSelection;
+import org.eclipse.jface.viewers.ITableLabelProvider;
+import org.eclipse.jface.viewers.LabelProvider;
+import org.eclipse.jface.viewers.TableViewer;
+import org.eclipse.jface.viewers.Viewer;
+import org.eclipse.jface.viewers.ViewerSorter;
+import org.eclipse.jface.window.Window;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.custom.ScrolledComposite;
+import org.eclipse.swt.events.FocusAdapter;
+import org.eclipse.swt.events.FocusEvent;
+import org.eclipse.swt.events.MenuAdapter;
+import org.eclipse.swt.events.MenuEvent;
+import org.eclipse.swt.events.MouseAdapter;
+import org.eclipse.swt.events.MouseEvent;
+import org.eclipse.swt.events.SelectionAdapter;
+import org.eclipse.swt.events.SelectionEvent;
+import org.eclipse.swt.events.SelectionListener;
+import org.eclipse.swt.graphics.Image;
+import org.eclipse.swt.graphics.Point;
+import org.eclipse.swt.graphics.Rectangle;
+import org.eclipse.swt.layout.GridData;
+import org.eclipse.swt.layout.GridLayout;
+import org.eclipse.swt.layout.RowLayout;
+import org.eclipse.swt.widgets.Button;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.Control;
+import org.eclipse.swt.widgets.Display;
+import org.eclipse.swt.widgets.Label;
+import org.eclipse.swt.widgets.Link;
+import org.eclipse.swt.widgets.Menu;
+import org.eclipse.swt.widgets.MenuItem;
+import org.eclipse.swt.widgets.MessageBox;
+import org.eclipse.swt.widgets.Shell;
+import org.eclipse.swt.widgets.Table;
+import org.eclipse.swt.widgets.TableColumn;
+import org.eclipse.swt.widgets.TableItem;
+import org.eclipse.ui.PlatformUI;
+import org.eclipse.ui.dialogs.PreferencesUtil;
+import org.eclipse.ui.dialogs.PropertyPage;
+import org.eclipse.wst.validation.Validator;
+import org.eclipse.wst.validation.internal.ConfigurationManager;
+import org.eclipse.wst.validation.internal.GlobalConfiguration;
+import org.eclipse.wst.validation.internal.ProjectConfiguration;
+import org.eclipse.wst.validation.internal.ValManager;
+import org.eclipse.wst.validation.internal.ValPrefManagerProject;
+import org.eclipse.wst.validation.internal.ValidatorMetaData;
+import org.eclipse.wst.validation.internal.ValidatorMutable;
+import org.eclipse.wst.validation.internal.ValManager.UseProjectPreferences;
+import org.eclipse.wst.validation.internal.model.ProjectPreferences;
+import org.eclipse.wst.validation.internal.operations.ValidatorManager;
+import org.eclipse.wst.validation.internal.plugin.ValidationPlugin;
+import org.eclipse.wst.validation.internal.ui.DelegatingValidatorPreferencesDialog;
+import org.eclipse.wst.validation.internal.ui.plugin.ValidationUIPlugin;
+import org.eclipse.wst.validation.ui.internal.HelpContextIds;
+import org.eclipse.wst.validation.ui.internal.ImageNames;
+import org.eclipse.wst.validation.ui.internal.ValUIMessages;
+import org.eclipse.wst.validation.ui.internal.dialog.FilterDialog;
+
+/**
+ * From this page the user can configure individual validators on individual projects.
+ *
+ * @author karasiuk
+ */
+public class ValidationPropertyPage extends PropertyPage {
+
+ private IValidationPage _pageImpl;
+ private Shell _shell;
+
+ public interface IValidationPage {
+
+ Composite createPage(Composite parent) throws InvocationTargetException;
+ boolean performOk() throws InvocationTargetException;
+ boolean performDefaults() throws InvocationTargetException;
+ Composite getControl();
+ void dispose();
+ void loseFocus();
+ void gainFocus();
+ }
+
+ public class InvalidPage implements IValidationPage {
+
+ private Composite page = null;
+ private Composite composite = null;
+ private GridLayout layout = null;
+ private Label messageLabel = null;
+
+ public InvalidPage(Composite parent) {
+ page = createPage(parent);
+ }
+
+ /**
+ * This page is added to the Properties guide if some internal problem
+ * occurred; for example, the highlighted item in the workbench is not
+ * an IProject (according to this page's plugin.xml, this page is only
+ * valid when an IProject is selected).
+ */
+ public Composite createPage(Composite parent) {
+ noDefaultAndApplyButton();
+
+ final ScrolledComposite sc1 = new ScrolledComposite(parent, SWT.H_SCROLL | SWT.V_SCROLL);
+ sc1.setLayoutData(new GridData(GridData.FILL_BOTH));
+ composite = new Composite(sc1, SWT.NONE);
+ sc1.setContent(composite);
+ layout = new GridLayout();
+ composite.setLayout(layout);
+
+ messageLabel = new Label(composite, SWT.NONE);
+ messageLabel.setText(ValUIMessages.VBF_EXC_INVALID_REGISTER);
+
+ composite.setSize(composite.computeSize(SWT.DEFAULT, SWT.DEFAULT));
+
+ return composite;
+ }
+
+ public boolean performDefaults() {
+ return true;
+ }
+
+ /**
+ * Since this page occurs under invalid circumstances, there is nothing
+ * to save.
+ */
+ public boolean performOk() {
+ return true;
+ }
+
+ public Composite getControl() {
+ return page;
+ }
+
+ public void dispose() {
+ messageLabel.dispose();
+ // layout.dispose();
+ composite.dispose();
+ }
+
+ public void loseFocus() {
+ }
+
+ public void gainFocus() {
+ }
+ }
+
+ private final class ValidatorListPage implements IValidationPage {
+ private Composite _page;
+
+ private TableViewer _validatorList;
+ private Button _enableAllButton;
+ private Button _disableAllButton;
+ private Button _override;
+ private Button _suspend;
+ private Link _configLink;
+ private Button _addValidationBuilder;
+ private Table _validatorsTable;
+ private ValidatorMutable[] _validators;
+
+ /** Number of things that may have changed. */
+ private int _changes;
+
+ /**
+ * This class is provided for the CheckboxTableViewer in the
+ * ValidationPropertiesPage$ValidatorListPage class.
+ */
+ public class ValidationContentProvider implements IStructuredContentProvider {
+ public void dispose() {
+ }
+
+ public Object[] getElements(Object inputElement) {
+ if (inputElement instanceof ValidatorMutable[]) {
+ return (ValidatorMutable[]) inputElement;
+ }
+ return new Object[0];
+ }
+
+ public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
+ }
+ }
+
+ /**
+ * This class is provided for
+ * ValidationPropertiesPage$ValidatorListPage's checkboxTableViewer
+ * element.
+ */
+ public class ValidationLabelProvider extends LabelProvider implements ITableLabelProvider {
+ public String getText(Object element) {
+ if (element == null)return ""; //$NON-NLS-1$
+ else if (element instanceof Validator)
+ return ((ValidatorMutable) element).getName();
+ else
+ return super.getText(element);
+ }
+
+ private Image getImage(String imageName) {
+ boolean isDisabled = !_validatorsTable.isEnabled();
+ if (isDisabled)
+ imageName = imageName + ImageNames.disabled;
+
+ return ValidationUIPlugin.getPlugin().getImage(imageName);
+ }
+
+ public Image getColumnImage(Object element, int columnIndex) {
+ ValidatorMutable v = (ValidatorMutable) element;
+ if (columnIndex == 1) {
+ return getImage(v.isManualValidation() ? ImageNames.okTable
+ : ImageNames.failTable);
+ } else if (columnIndex == 2) {
+ return getImage(v.isBuildValidation() ? ImageNames.okTable
+ : ImageNames.failTable);
+ } else if (columnIndex == 3) {
+ if (hasSettings(v))return getImage(ImageNames.settings);
+ return null;
+ }
+ return null;
+ }
+
+ public String getColumnText(Object element, int columnIndex) {
+ if (columnIndex == 0)return ((ValidatorMutable) element).getName();
+ return null;
+ }
+ }
+
+ public ValidatorListPage(Composite parent) throws InvocationTargetException {
+ _page = createPage(parent);
+ }
+
+ private void setupTableColumns(Table table) {
+ TableColumn validatorColumn = new TableColumn(table, SWT.NONE);
+ validatorColumn.setText(ValUIMessages.VALIDATOR);
+ validatorColumn.setWidth(245);
+ TableColumn manualColumn = new TableColumn(table, SWT.CENTER);
+ manualColumn.setText(ValUIMessages.MANUAL);
+ manualColumn.pack();
+ TableColumn buildColumn = new TableColumn(table, SWT.CENTER);
+ buildColumn.setText(ValUIMessages.BUILD);
+ buildColumn.pack();
+ TableColumn settingsColumn = new TableColumn(table, SWT.CENTER);
+ settingsColumn.setText(ValUIMessages.SETTINGS);
+ settingsColumn.pack();
+ }
+
+ public Composite createPage(Composite parent) throws InvocationTargetException {
+ Validator[] vals = ValManager.getDefault()
+ .getValidatorsConfiguredForProject(getProject(), UseProjectPreferences.MustUse);
+ _validators = new ValidatorMutable[vals.length];
+ for (int i=0; i<vals.length; i++)_validators[i] = new ValidatorMutable(vals[i]);
+
+ Composite validatorGroup = new Composite(parent, SWT.NONE);
+
+ GridLayout validatorGroupLayout = new GridLayout();
+ validatorGroupLayout.numColumns = 2;
+ validatorGroup.setLayout(validatorGroupLayout);
+ GridDataFactory.fillDefaults().grab(true, true).applyTo(validatorGroup);
+
+ addOverride(validatorGroup);
+ addConfigLink(validatorGroup);
+ addSuspend(validatorGroup);
+ addValidationBuilder(validatorGroup);
+ new Label(validatorGroup, SWT.NONE).setLayoutData(new GridData());
+
+ Label listLabel = new Label(validatorGroup, SWT.NONE);
+ GridData listLabelData = new GridData(GridData.FILL_HORIZONTAL);
+ listLabelData.horizontalSpan = 2;
+ listLabel.setLayoutData(listLabelData);
+ listLabel.setText(ValUIMessages.PREF_VALLIST_TITLE);
+
+ _validatorsTable = new Table(validatorGroup, SWT.BORDER | SWT.FULL_SELECTION);
+ Point preferredSize = _validatorsTable.computeSize(SWT.DEFAULT, SWT.DEFAULT);
+ GridDataFactory.fillDefaults().grab(true, true).hint(preferredSize)
+ .span(2,1).applyTo(_validatorsTable);
+
+ _validatorsTable.setHeaderVisible(true);
+ _validatorsTable.setLinesVisible(true);
+
+ _validatorList = new TableViewer(_validatorsTable);
+ _validatorList.setLabelProvider(new ValidationLabelProvider());
+ _validatorList.setContentProvider(new ValidationContentProvider());
+ _validatorList.setSorter(new ViewerSorter());
+ setupTableColumns(_validatorsTable);
+
+ _validatorList.setInput(_validators);
+ _validatorsTable.addMouseListener(new MouseAdapter() {
+
+ public void mouseDown(MouseEvent e) {
+ if (e.button != 1)return;
+
+ TableItem tableItem = _validatorsTable.getItem(new Point(e.x, e.y));
+ if (tableItem == null || tableItem.isDisposed()) {
+ // item no longer exists
+ return;
+ }
+ int columnNumber;
+ int columnsCount = _validatorsTable.getColumnCount();
+ if (columnsCount == 0) {
+ // If no TableColumn, Table acts as if it has a single column
+ // which takes the whole width.
+ columnNumber = 0;
+ } else {
+ columnNumber = -1;
+ for (int i = 0; i < columnsCount; i++) {
+ Rectangle bounds = tableItem.getBounds(i);
+ if (bounds.contains(e.x, e.y)) {
+ columnNumber = i;
+ break;
+ }
+ }
+ if (columnNumber == -1)return;
+ }
+
+ columnClicked(columnNumber);
+ }
+ });
+
+ _validatorsTable.setMenu(createContextMenu());
+ _validatorsTable.addFocusListener(new FocusAdapter() {
+
+ public void focusGained(FocusEvent e) {
+ super.focusGained(e);
+ if (_validatorsTable.getSelectionCount() == 0) {
+ _validatorsTable.select(0);
+ }
+ }
+ });
+
+ addButtons(validatorGroup);
+
+ // Have to set the tab order or only the first checkbox in a
+ // Composite can be tabbed to. (Seems to apply only to checkboxes. Have to use the
+ // arrow key to navigate the checkboxes.)
+ validatorGroup.setTabList(new Control[] { _override, _suspend});
+
+ updateWidgets();
+
+ applyDialogFont(validatorGroup);
+ validatorGroup.setSize(validatorGroup.computeSize(SWT.DEFAULT, SWT.DEFAULT));
+
+ return validatorGroup;
+ }
+
+ private void addButtons(Composite validatorGroup) {
+
+ Composite buttons = new Composite(validatorGroup, SWT.NONE);
+ GridData gd = new GridData(GridData.FILL_HORIZONTAL);
+ gd.horizontalSpan = 2;
+ buttons.setLayout(new RowLayout());
+
+ _enableAllButton = new Button(buttons, SWT.PUSH);
+ _enableAllButton.setText(ValUIMessages.PREF_BUTTON_ENABLEALL);
+ _enableAllButton.addSelectionListener(new SelectionAdapter() {
+ public void widgetSelected(SelectionEvent e) {
+ try {
+ performEnableAll();
+ } catch (InvocationTargetException exc) {
+ displayAndLogError(ValUIMessages.VBF_EXC_INTERNAL_TITLE,ValUIMessages.VBF_EXC_INTERNAL_PAGE, exc);
+ }
+ }
+ });
+
+ _disableAllButton = new Button(buttons, SWT.PUSH);
+ _disableAllButton.setText(ValUIMessages.PREF_BUTTON_DISABLEALL);
+ _disableAllButton.addSelectionListener(new SelectionAdapter() {
+ public void widgetSelected(SelectionEvent e) {
+ try {
+ performDisableAll();
+ } catch (InvocationTargetException exc) {
+ displayAndLogError(ValUIMessages.VBF_EXC_INTERNAL_TITLE, ValUIMessages.VBF_EXC_INTERNAL_PAGE, exc);
+ }
+ }
+ });
+ }
+
+ private void addSuspend(Composite validatorGroup) {
+ GridData gd = new GridData(GridData.FILL_HORIZONTAL);
+ gd.horizontalSpan = 2;
+ _suspend = new Button(validatorGroup, SWT.CHECK);
+ _suspend.setLayoutData(gd);
+ _suspend.setText(ValUIMessages.DISABLE_VALIDATION);
+ _suspend.setSelection(getProjectPreferences().getSuspend());
+ _suspend.addSelectionListener(new SelectionAdapter() {
+ public void widgetSelected(SelectionEvent e) {
+ _suspend.setFocus();
+ _changes++;
+ enableDisableWidgets();
+ _validatorList.refresh();
+ }
+ });
+ }
+
+ private void addConfigLink(Composite validatorGroup){
+ _configLink = new Link(validatorGroup,SWT.None);
+ GridData layout = new GridData(GridData.HORIZONTAL_ALIGN_END);
+ _configLink.setLayoutData(layout);
+ _configLink.setText("<A>"+ //$NON-NLS-1$
+ ValUIMessages.ConfigWsSettings+"</A>"); //$NON-NLS-1$
+ _configLink.addSelectionListener(new SelectionListener() {
+ public static final String DATA_NO_LINK = "PropertyAndPreferencePage.nolink"; //$NON-NLS-1$
+
+ public void doLinkActivated(Link e) {
+ String id = getPreferencePageID();
+ PreferencesUtil.createPreferenceDialogOn(getShell(), id, new String[]{id}, DATA_NO_LINK).open();
+ try {
+ updateWidgets();
+ } catch (InvocationTargetException ie) {
+
+ }
+ }
+
+ private String getPreferencePageID() {
+ return "ValidationPreferencePage"; //$NON-NLS-1$
+ }
+
+ public void widgetDefaultSelected(SelectionEvent e) {
+ doLinkActivated((Link) e.widget);
+ }
+
+ public void widgetSelected(SelectionEvent e) {
+ doLinkActivated((Link) e.widget);
+ }
+ });
+
+ }
+
+ /**
+ * If the current project doesn't have the validation builder configured on it,
+ * and the user has asked us to add a builder, add the builder.
+ * Otherwise return without doing anything.
+ */
+ private void addBuilder() {
+ if (_addValidationBuilder != null && _addValidationBuilder.getSelection())
+ ValidatorManager.addProjectBuildValidationSupport(getProject());
+ }
+
+
+ private void addValidationBuilder(Composite validatorGroup) {
+ if (hasValidationBuilder())return;
+
+ GridData gd = new GridData(GridData.FILL_HORIZONTAL);
+ gd.horizontalSpan = 2;
+ _addValidationBuilder = new Button(validatorGroup, SWT.CHECK);
+ _addValidationBuilder.setLayoutData(gd);
+ _addValidationBuilder.setText(ValUIMessages.ADD_VALIDATION_BUILDER);
+ _addValidationBuilder.setSelection(false);
+ }
+
+ /**
+ * Does this validator have extra settings that can be configured?
+ * @param v
+ * @return true if it does
+ */
+ boolean hasSettings(ValidatorMutable v){
+ if (v.isV2Validator())return true;
+ if (v.getDelegatingId() != null)return true;
+ return false;
+ }
+
+ /**
+ * Answer if this project has a validator builder assigned to it.
+ */
+ private boolean hasValidationBuilder(){
+ try {
+ IProjectDescription description = getProject().getDescription();
+ ICommand[] commands = description.getBuildSpec();
+ for (int i = 0; i < commands.length; i++) {
+ if (commands[i].getBuilderName().equals(ValidationPlugin.VALIDATION_BUILDER_ID))
+ return true;
+ }
+ return false;
+ }
+ catch (CoreException e){
+ ValidationPlugin.getPlugin().handleException(e);
+ }
+ return false;
+ }
+
+
+ private void addOverride(Composite validatorGroup) {
+ GridData gd = new GridData(GridData.FILL_HORIZONTAL);
+// gd.horizontalSpan = 2;
+ _override = new Button(validatorGroup, SWT.CHECK);
+ _override.setLayoutData(gd);
+ _override.setText(ValUIMessages.LabelEnableProjectSpecific);
+ _override.setSelection(getProjectPreferences().getOverride());
+ _override.addSelectionListener(new SelectionAdapter() {
+ public void widgetSelected(SelectionEvent e) {
+ _override.setFocus();
+ _changes++;
+ ValManager vm = ValManager.getDefault();
+ if (vm.getGlobalPreferences().getOverride()){
+// IProject project = getProject();
+// UseProjectPreferences useProject = UseProjectPreferences.Normal;
+// if (_override.getSelection())useProject = UseProjectPreferences.MustUse;
+// _validators = copyValidators(vm.getValidatorsConfiguredForProject(project, useProject));
+// _validatorList.setInput(_validators);
+ enableDisableWidgets();
+ _validatorList.refresh();
+ }
+ else {
+ MessageDialog.openWarning(_shell, ValUIMessages.Validation,
+ ValUIMessages.ProjectOverridesNotAllowed);
+ }
+ }
+
+ });
+ }
+
+ protected Menu createContextMenu() {
+ final Menu menu = new Menu(_validatorsTable.getShell(), SWT.POP_UP);
+ final MenuItem manualItem = new MenuItem(menu, SWT.CHECK);
+ manualItem.setText(ValUIMessages.PREF_MNU_MANUAL);
+ final MenuItem buildItem = new MenuItem(menu, SWT.CHECK);
+ buildItem.setText(ValUIMessages.PREF_MNU_BUILD);
+ final MenuItem settingsItem = new MenuItem(menu, SWT.PUSH);
+ settingsItem.setText(ValUIMessages.PREF_MNU_SETTINGS);
+
+ class MenuItemListener extends SelectionAdapter {
+ public void widgetSelected(SelectionEvent e) {
+ MenuItem menuItem = (MenuItem) e.getSource();
+ int index = menu.indexOf(menuItem) + 1;
+ columnClicked(index);
+ }
+ }
+ MenuItemListener listener = new MenuItemListener();
+ manualItem.addSelectionListener(listener);
+ buildItem.addSelectionListener(listener);
+ settingsItem.addSelectionListener(listener);
+
+ menu.addMenuListener(new MenuAdapter() {
+ public void menuShown(MenuEvent e) {
+ IStructuredSelection selection = (IStructuredSelection) _validatorList.getSelection();
+ ValidatorMutable val = (ValidatorMutable) selection.getFirstElement();
+ manualItem.setSelection(val.isManualValidation());
+ buildItem.setSelection(val.isBuildValidation());
+ settingsItem.setEnabled(hasSettings(val));
+ }
+ });
+
+ return menu;
+ }
+
+ protected void columnClicked(int columnToEdit) {
+ IStructuredSelection selection = (IStructuredSelection) _validatorList.getSelection();
+ ValidatorMutable val = (ValidatorMutable) selection.getFirstElement();
+
+ switch (columnToEdit) {
+ case 1:
+ val.setManualValidation(!val.isManualValidation());
+ break;
+ case 2:
+ val.setBuildValidation(!val.isBuildValidation());
+ break;
+ case 3:
+ if (val.isV2Validator()){
+ ValidatorMutable newVal = new ValidatorMutable(val);
+ FilterDialog fd = new FilterDialog(_shell, newVal, getProject());
+ if (Window.OK == fd.open()){
+ _changes++;
+ newVal = fd.getValidator();
+ int i = findit(val);
+ if (i != -1)_validators[i] = newVal;
+ }
+ }
+ else {
+ handleOldDelegate(val);
+ }
+
+ break;
+ default:
+ break;
+ }
+ _validatorList.refresh();
+ }
+
+ private int findit(ValidatorMutable val) {
+ for (int i=0; i<_validators.length; i++)if (_validators[i] == val)return i;
+ return -1;
+ }
+
+ private void handleOldDelegate(ValidatorMutable val) {
+ try {
+ if (!val.isV1Validator())return;
+
+ ValidatorMetaData vmd = val.getVmd();
+ if (!vmd.isDelegating())return;
+
+ GlobalConfiguration gc = ConfigurationManager.getManager().getGlobalConfiguration();
+ String delegateID = gc.getDelegateUniqueName(vmd);
+ Shell shell = Display.getCurrent().getActiveShell();
+ DelegatingValidatorPreferencesDialog dialog =
+ new DelegatingValidatorPreferencesDialog(shell, vmd, delegateID);
+
+ dialog.setBlockOnOpen(true);
+ dialog.create();
+
+ int result = dialog.open();
+ if (result == Window.OK){
+ _changes++;
+ gc.setDelegateUniqueName(vmd, dialog.getDelegateID());
+ }
+ }
+ catch (InvocationTargetException e){
+
+ }
+ }
+
+ protected void updateWidgets() throws InvocationTargetException {
+ // Need to update even the widgets that do not change based on another
+ // widgets because of performDefaults(). If performDefaults() is selected,
+ // then the pagePreferences values are reset, and these widgets
+ // might also need to be updated.
+ updateAllWidgets();
+ updateHelp();
+ }
+
+ protected void updateWidgetsForDefaults() throws InvocationTargetException {
+ _suspend.setSelection(false);
+ _override.setSelection(false);
+ enableDisableWidgets();
+ _validatorList.setInput(_validators);
+ _validatorList.refresh();
+ }
+
+ private void updateAllWidgets() throws InvocationTargetException {
+ _suspend.setSelection(getProjectPreferences().getSuspend());
+ _override.setSelection(getProjectPreferences().getOverride());
+ enableDisableWidgets();
+ _validatorList.setInput(_validators);
+ _validatorList.refresh();
+ }
+
+ public boolean performOk() throws InvocationTargetException {
+
+ addBuilder();
+ for (ValidatorMutable vm : _validators)if (vm.isChanged())_changes++;
+ if (_changes == 0)return true;
+ // [213631] this warning should only be shown if the user actually tried to override
+ // the validators
+ if (!ValManager.getDefault().getGlobalPreferences().getOverride() && _override.getSelection()){
+ MessageDialog.openWarning(_shell, ValUIMessages.Validation, ValUIMessages.ProjectOverridesNotAllowed);
+ return false;
+ }
+ updateV1ProjectSettings();
+ IProject project = getProject();
+ ProjectPreferences pp = new ProjectPreferences(project, _override.getSelection(), _suspend.getSelection(), null);
+ ValPrefManagerProject vpm = new ValPrefManagerProject(project);
+ vpm.savePreferences(pp, _validators);
+ return true;
+ }
+
+ /**
+ * Update the version 1 project settings.
+ */
+ private void updateV1ProjectSettings() {
+ try {
+ ProjectConfiguration pc = ConfigurationManager.getManager().getProjectConfiguration(getProject());
+ pc.setDoesProjectOverride(_override.getSelection());
+ pc.setDisableAllValidation(_suspend.getSelection());
+ }
+ catch (InvocationTargetException e){
+ ValidationPlugin.getPlugin().handleException(e);
+ }
+ }
+
+ /**
+ * Answer the specific project preferences. If the project didn't have any specific project
+ * preferences, then create a default set.
+ * @return
+ */
+ private ProjectPreferences getProjectPreferences(){
+ return ValManager.getDefault().getProjectPreferences(getProject());
+ }
+
+ public boolean performDefaults() throws InvocationTargetException {
+ Validator[] vals = ValManager.getDefault()
+ .getValidatorsConfiguredForProject(getProject(), UseProjectPreferences.MustNotUse);
+ _validators = new ValidatorMutable[vals.length];
+ for (int i=0; i<vals.length; i++)_validators[i] = new ValidatorMutable(vals[i]);
+
+ _changes++;
+ updateWidgetsForDefaults();
+ getDefaultsButton().setFocus();
+ return true;
+ }
+
+ public boolean performEnableAll() throws InvocationTargetException {
+ setAllValidators(true);
+ _enableAllButton.setFocus();
+ _validatorList.refresh();
+ return true;
+ }
+
+ private void setAllValidators(boolean bool) {
+ for (TableItem item : _validatorsTable.getItems()) {
+ ValidatorMutable val = (ValidatorMutable) item.getData();
+ val.setManualValidation(bool);
+ val.setBuildValidation(bool);
+ }
+ }
+
+ public boolean performDisableAll() throws InvocationTargetException {
+ setAllValidators(false);
+ _disableAllButton.setFocus();
+ _validatorList.refresh();
+ return true;
+ }
+
+ protected void updateHelp() {
+// PlatformUI.getWorkbench().getHelpSystem().setHelp(_suspend, ContextIds.VALIDATION_PREFERENCE_PAGE_DISABLE_ALL_ENABLED);
+ }
+
+ /*
+ * Store the current values of the controls into the preference store.
+ */
+
+ public Composite getControl() {
+ return _page;
+ }
+
+ public void dispose() {
+ _override.dispose();
+ _suspend.dispose();
+ _configLink.dispose();
+ _disableAllButton.dispose();
+ _enableAllButton.dispose();
+ _validatorList.getTable().dispose();
+ }
+
+ /**
+ * Enable or disable the widgets based on some top level preferences.
+ */
+ private void enableDisableWidgets() {
+ boolean globalOverride = ValManager.getDefault().getGlobalPreferences().getOverride();
+ boolean enable = !_suspend.getSelection() & _override.getSelection() & globalOverride;
+ _suspend.setEnabled(_override.getSelection() & globalOverride);
+ _validatorsTable.setEnabled(enable);
+ _enableAllButton.setEnabled(enable);
+ _disableAllButton.setEnabled(enable);
+ _configLink.setEnabled(!globalOverride || !_override.getSelection());
+ }
+
+ public void loseFocus() {
+ // This page does not need to cache anything before it loses focus.
+ }
+
+ public void gainFocus() {
+ }
+ }
+
+ protected Control createContents(Composite parent) {
+ try {
+ PlatformUI.getWorkbench().getHelpSystem().setHelp(parent, HelpContextIds.ProjectPage);
+ _shell = parent.getShell();
+ _pageImpl = new ValidatorListPage(parent);
+ } catch (Exception exc) {
+ _pageImpl = new InvalidPage(parent);
+ displayAndLogError(ValUIMessages.VBF_EXC_INTERNAL_TITLE, ValUIMessages.VBF_EXC_INTERNAL_PAGE, exc);
+ }
+
+ return _pageImpl.getControl();
+ }
+
+ protected void performDefaults() {
+ super.performDefaults();
+
+ try {
+ _pageImpl.performDefaults();
+ } catch (Exception exc) {
+ displayAndLogError(ValUIMessages.VBF_EXC_INTERNAL_TITLE, ValUIMessages.VBF_EXC_INTERNAL_PAGE, exc);
+ }
+ }
+
+ public boolean performOk() {
+ try {
+ return _pageImpl.performOk();
+ } catch (Exception exc) {
+ displayAndLogError(ValUIMessages.VBF_EXC_INTERNAL_TITLE, ValUIMessages.VBF_EXC_INTERNAL_PAGE, exc);
+ return false;
+ }
+ }
+
+ /**
+ * Since the pages are inner classes of a child PreferencePage, not a
+ * PreferencePage itself, DialogPage's automatic disposal of its children's
+ * widgets cannot be used. Instead, dispose of each inner class' widgets
+ * explicitly.
+ */
+ public void dispose() {
+ super.dispose();
+ try {
+ if (_pageImpl != null) {
+ _pageImpl.dispose();
+ _pageImpl = null;
+ }
+ } catch (Exception exc) {
+ displayAndLogError(ValUIMessages.VBF_EXC_INTERNAL_TITLE, ValUIMessages.VBF_EXC_INTERNAL_PAGE, exc);
+ }
+ }
+
+ private void logError(Throwable exc) {
+ ValidationUIPlugin.getPlugin().handleException(exc);
+ }
+
+ /*
+ * package visibility because if this method is private, then the compiler
+ * needs to create a synthetic accessor method for the internal classes, and
+ * that can have performance implications.
+ */
+ void displayAndLogError(String title, String message, Throwable exc) {
+ logError(exc);
+ displayMessage(title, message, org.eclipse.swt.SWT.ICON_ERROR);
+ }
+
+ private void displayMessage(String title, String message, int iIconType) {
+ MessageBox messageBox = new MessageBox(getShell(),
+ org.eclipse.swt.SWT.OK | iIconType | org.eclipse.swt.SWT.APPLICATION_MODAL);
+ messageBox.setMessage(message);
+ messageBox.setText(title);
+ messageBox.open();
+ }
+
+ /**
+ * @see org.eclipse.jface.dialogs.IDialogPage#setVisible(boolean)
+ */
+ public void setVisible(boolean visible) {
+ super.setVisible(visible);
+
+ if (_pageImpl == null)return;
+ if (visible)_pageImpl.gainFocus();
+ else _pageImpl.loseFocus();
+ }
+
+ /**
+ * @see org.eclipse.jface.preference.PreferencePage#getDefaultsButton()
+ */
+ protected Button getDefaultsButton() {
+ return super.getDefaultsButton();
+ }
+
+ /**
+ * Returns the selected project.
+ */
+ public IProject getProject() {
+ IAdaptable selectedElement = getElement();
+ if (selectedElement == null)return null;
+ if (selectedElement instanceof IProject)return (IProject) selectedElement;
+
+ Object adaptedObject = selectedElement.getAdapter(IProject.class);
+ if (adaptedObject instanceof IProject)return (IProject) adaptedObject;
+ return null;
+
+ }
+}
diff --git a/plugins/org.eclipse.wst.validation/.classpath b/plugins/org.eclipse.wst.validation/.classpath
index f8323da..64ae09a 100644
--- a/plugins/org.eclipse.wst.validation/.classpath
+++ b/plugins/org.eclipse.wst.validation/.classpath
@@ -3,7 +3,12 @@
<classpathentry kind="src" path="validate"/>
<classpathentry kind="src" path="validate_core"/>
<classpathentry kind="src" path="property_files"/>
- <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
- <classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/>
+ <classpathentry kind="src" path="vf2"/>
+ <classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins">
+ <accessrules>
+ <accessrule kind="accessible" pattern="org/eclipse/wst/common/**"/>
+ </accessrules>
+ </classpathentry>
+ <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/J2SE-1.5"/>
<classpathentry kind="output" path="bin"/>
</classpath>
diff --git a/plugins/org.eclipse.wst.validation/.options b/plugins/org.eclipse.wst.validation/.options
index 26565de..404c71b 100644
--- a/plugins/org.eclipse.wst.validation/.options
+++ b/plugins/org.eclipse.wst.validation/.options
@@ -1,2 +1,37 @@
-com.ibm.etools.validation/debug=true
-com.ibm.etools.validation/tracefilter=
\ No newline at end of file
+org.eclipse.wst.validation/debug=true
+
+# Set this to true if you wish performance information to be logged
+org.eclipse.wst.validation/timings=false
+
+# set this to true if you want version 1 validator tracing
+org.eclipse.wst.validation/v1=false
+
+# Set this to a file name, if you wish the results to be logged to a file, otherwise
+# they will be written to stderr. When logged to a file the results are in a
+# CSV (comma separated values) form. When logged to stderr they are in a more
+# human readable form.
+org.eclipse.wst.validation/timings/tracefile=
+
+# By default times that are written to the trace file are in milliseconds for elapsed
+# time and nanoseconds for cpu time. If you find these times easier to read as seconds
+# as expressed by a double, the following flag can be turned on.
+org.eclipse.wst.validation/timings/useDoubles=false
+
+# If extra detail is needed for a particular validator it's id can be specified here.
+# For example, if you wanted more detail on the XML validator you would use
+# org.eclipse.wst.xml.core.xml
+org.eclipse.wst.validation/extraValDetail=
+
+# To make debugging easier, you can make it appear is if only one validator has been
+# registered via the extension points. You do this by setting the following filter
+# to validator id of the one validator that you want registered.
+#
+# As an example, you could use this plug-in id for a v1 validator: org.eclipse.jst.j2ee.ejb.EJBValidator
+# and org.eclipse.wst.html.ui.HTMLValidator for a v2 validator
+org.eclipse.wst.validation/filter/allExcept=
+
+# The tracing level. If not supplied a default of zero is used. The higher the number the
+# more verbose the tracing.
+org.eclipse.wst.validation/trace/level=
+
+
diff --git a/plugins/org.eclipse.wst.validation/.settings/org.eclipse.jdt.core.prefs b/plugins/org.eclipse.wst.validation/.settings/org.eclipse.jdt.core.prefs
index 62c0483..58507dd 100644
--- a/plugins/org.eclipse.wst.validation/.settings/org.eclipse.jdt.core.prefs
+++ b/plugins/org.eclipse.wst.validation/.settings/org.eclipse.jdt.core.prefs
@@ -1,12 +1,78 @@
-#Wed Mar 29 04:07:08 EST 2006
+#Fri Apr 11 07:15:44 EDT 2008
eclipse.preferences.version=1
-org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=disabled
-org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.2
+org.eclipse.jdt.core.codeComplete.argumentPrefixes=
+org.eclipse.jdt.core.codeComplete.argumentSuffixes=
+org.eclipse.jdt.core.codeComplete.fieldPrefixes=_
+org.eclipse.jdt.core.codeComplete.fieldSuffixes=
+org.eclipse.jdt.core.codeComplete.localPrefixes=
+org.eclipse.jdt.core.codeComplete.localSuffixes=
+org.eclipse.jdt.core.codeComplete.staticFieldPrefixes=_
+org.eclipse.jdt.core.codeComplete.staticFieldSuffixes=
+org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
+org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.5
org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve
-org.eclipse.jdt.core.compiler.compliance=1.4
+org.eclipse.jdt.core.compiler.compliance=1.5
org.eclipse.jdt.core.compiler.debug.lineNumber=generate
org.eclipse.jdt.core.compiler.debug.localVariable=generate
org.eclipse.jdt.core.compiler.debug.sourceFile=generate
-org.eclipse.jdt.core.compiler.problem.assertIdentifier=warning
-org.eclipse.jdt.core.compiler.problem.enumIdentifier=warning
-org.eclipse.jdt.core.compiler.source=1.3
+org.eclipse.jdt.core.compiler.problem.annotationSuperInterface=warning
+org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
+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.enumIdentifier=error
+org.eclipse.jdt.core.compiler.problem.fallthroughCase=ignore
+org.eclipse.jdt.core.compiler.problem.fatalOptionalError=enabled
+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=warning
+org.eclipse.jdt.core.compiler.problem.nullReference=ignore
+org.eclipse.jdt.core.compiler.problem.overridingPackageDefaultMethod=warning
+org.eclipse.jdt.core.compiler.problem.parameterAssignment=ignore
+org.eclipse.jdt.core.compiler.problem.possibleAccidentalBooleanAssignment=ignore
+org.eclipse.jdt.core.compiler.problem.potentialNullReference=ignore
+org.eclipse.jdt.core.compiler.problem.rawTypeReference=warning
+org.eclipse.jdt.core.compiler.problem.redundantNullCheck=ignore
+org.eclipse.jdt.core.compiler.problem.redundantSuperinterface=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=warning
+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.unusedDeclaredThrownExceptionExemptExceptionAndThrowable=enabled
+org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionIncludeDocCommentReference=enabled
+org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionWhenOverriding=disabled
+org.eclipse.jdt.core.compiler.problem.unusedImport=error
+org.eclipse.jdt.core.compiler.problem.unusedLabel=warning
+org.eclipse.jdt.core.compiler.problem.unusedLocal=warning
+org.eclipse.jdt.core.compiler.problem.unusedParameter=ignore
+org.eclipse.jdt.core.compiler.problem.unusedParameterIncludeDocCommentReference=enabled
+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.unusedWarningToken=warning
+org.eclipse.jdt.core.compiler.problem.varargsArgumentNeedCast=warning
+org.eclipse.jdt.core.compiler.source=1.5
diff --git a/plugins/org.eclipse.wst.validation/.settings/org.eclipse.jdt.ui.prefs b/plugins/org.eclipse.wst.validation/.settings/org.eclipse.jdt.ui.prefs
index 35ee23b..76ddc11 100644
--- a/plugins/org.eclipse.wst.validation/.settings/org.eclipse.jdt.ui.prefs
+++ b/plugins/org.eclipse.wst.validation/.settings/org.eclipse.jdt.ui.prefs
@@ -1,3 +1,7 @@
-#Wed Mar 29 04:07:07 EST 2006
+#Mon Jun 11 14:58:22 EDT 2007
eclipse.preferences.version=1
-internal.default.compliance=default
+org.eclipse.jdt.ui.exception.name=e
+org.eclipse.jdt.ui.gettersetter.use.is=true
+org.eclipse.jdt.ui.javadoc=false
+org.eclipse.jdt.ui.keywordthis=false
+org.eclipse.jdt.ui.overrideannotation=true
diff --git a/plugins/org.eclipse.wst.validation/META-INF/MANIFEST.MF b/plugins/org.eclipse.wst.validation/META-INF/MANIFEST.MF
index 03348a6..8fb0e19 100644
--- a/plugins/org.eclipse.wst.validation/META-INF/MANIFEST.MF
+++ b/plugins/org.eclipse.wst.validation/META-INF/MANIFEST.MF
@@ -1,22 +1,24 @@
Manifest-Version: 1.0
Bundle-ManifestVersion: 2
-Bundle-Name: Validation Framework
+Bundle-Name: %Bundle-Name.0
Bundle-SymbolicName: org.eclipse.wst.validation; singleton:=true
-Bundle-Version: 1.1.5.qualifier
+Bundle-Version: 1.2.10.qualifier
Bundle-Activator: org.eclipse.wst.validation.internal.plugin.ValidationPlugin
-Bundle-Vendor: Eclipse.org
+Bundle-Vendor: %Bundle-Vendor.0
Bundle-Localization: plugin
-Export-Package: org.eclipse.wst.validation.internal;x-internal:=true,
- org.eclipse.wst.validation.internal.core;x-internal:=true,
+Export-Package: org.eclipse.wst.validation,
+ org.eclipse.wst.validation.internal;x-friends:="org.eclipse.wst.common.tests.validation",
+ org.eclipse.wst.validation.internal.core;x-friends:="org.eclipse.wst.common.tests.validation",
org.eclipse.wst.validation.internal.delegates;x-internal:=true,
- org.eclipse.wst.validation.internal.operations;x-internal:=true,
- org.eclipse.wst.validation.internal.plugin;x-internal:=true,
+ org.eclipse.wst.validation.internal.model;x-internal:=true,
+ org.eclipse.wst.validation.internal.operations;x-friends:="org.eclipse.wst.common.tests.validation",
+ org.eclipse.wst.validation.internal.plugin;x-friends:="org.eclipse.wst.common.tests.validation",
org.eclipse.wst.validation.internal.provisional;x-internal:=true,
- org.eclipse.wst.validation.internal.provisional.core;x-internal:=true
-Require-Bundle: org.eclipse.core.resources;bundle-version="[3.2.0,4.0.0)",
- org.eclipse.wst.common.frameworks;bundle-version="[1.1.0,1.2.0)",
- org.eclipse.jem.util;bundle-version="[1.2.0,1.3.0)",
- org.eclipse.core.runtime;bundle-version="[3.2.0,4.0.0)",
- org.eclipse.wst.common.project.facet.core;bundle-version="[1.1.0,1.2.0)",
- org.eclipse.core.expressions;bundle-version="[3.2.0,4.0.0)"
-Eclipse-LazyStart: true
+ org.eclipse.wst.validation.internal.provisional.core
+Require-Bundle: org.eclipse.core.resources;bundle-version="[3.4.0,4.0.0)",
+ org.eclipse.wst.common.frameworks;bundle-version="[1.1.200,2.0.0)",
+ org.eclipse.core.runtime;bundle-version="[3.4.0,4.0.0)",
+ org.eclipse.wst.common.project.facet.core;bundle-version="[1.3.0,2.0.0)",
+ org.eclipse.core.expressions;bundle-version="[3.4.0,4.0.0)"
+Bundle-ActivationPolicy: lazy
+Bundle-RequiredExecutionEnvironment: J2SE-1.5
diff --git a/plugins/org.eclipse.wst.validation/about.html b/plugins/org.eclipse.wst.validation/about.html
index 4ec5989..2199df3 100644
--- a/plugins/org.eclipse.wst.validation/about.html
+++ b/plugins/org.eclipse.wst.validation/about.html
@@ -10,7 +10,7 @@
<H3>About This Content</H3>
-<P>May 2, 2006</P>
+<P>June, 2008</P>
<H3>License</H3>
diff --git a/plugins/org.eclipse.wst.validation/build.properties b/plugins/org.eclipse.wst.validation/build.properties
index 8a3225d..167d165 100644
--- a/plugins/org.eclipse.wst.validation/build.properties
+++ b/plugins/org.eclipse.wst.validation/build.properties
@@ -1,10 +1,10 @@
###############################################################################
-# Copyright (c) 2001, 2004 IBM Corporation and others.
+# Copyright (c) 2001, 2008 IBM Corporation 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:
# IBM Corporation - initial API and implementation
###############################################################################
@@ -12,11 +12,14 @@
plugin.properties,\
META-INF/,\
about.html,\
- .
+ .,\
+ .options,\
+ xsds/
jars.compile.order = .
src.includes = component.xml,\
xsds/
output.. = bin/
source.. = validate_core/,\
property_files/,\
- validate/
+ validate/,\
+ vf2/
diff --git a/plugins/org.eclipse.wst.validation/plugin.properties b/plugins/org.eclipse.wst.validation/plugin.properties
index 4561d96..d7722e4 100644
--- a/plugins/org.eclipse.wst.validation/plugin.properties
+++ b/plugins/org.eclipse.wst.validation/plugin.properties
@@ -1,21 +1,26 @@
###############################################################################
-# Copyright (c) 2001, 2004 IBM Corporation and others.
+# Copyright (c) 2001, 2008 IBM Corporation 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:
# IBM Corporation - initial API and implementation
###############################################################################
-#
-# Version 1.3
-#
+
VALIDATION_BUILDER_NAME=Validation
VALIDATION_PROBLEMMARKER_NAME=Validation Message
+ProblemMarkerV2=Validation Message
+
VALIDATION_PROJECTMARKER_NAME=Enabled Validators
VALIDATION_PREFERENCEMARKER_NAME=Validation Preferences
Validator=Validator
ReferencialFileValidator=ReferencialFileValidator
validationSelectionHandler=validationSelectionHandler
ValidatorDelegates=Validator Delegates
+
+Bundle-Name.0 = Validation Framework
+Bundle-Vendor.0 = Eclipse.org
+
+Extension.validator=Validator (Version 2)
diff --git a/plugins/org.eclipse.wst.validation/plugin.xml b/plugins/org.eclipse.wst.validation/plugin.xml
index 9187915..1b17568 100644
--- a/plugins/org.eclipse.wst.validation/plugin.xml
+++ b/plugins/org.eclipse.wst.validation/plugin.xml
@@ -1,14 +1,16 @@
<?xml version="1.0" encoding="UTF-8"?>
<?eclipse version="3.0"?>
<plugin>
-
-
+
<!-- Validation extension points -->
<extension-point id="validator" name="%Validator" schema="xsds/validatorExtSchema.exsd"/>
+ <extension-point id="validatorV2" name="%Extension.validator" schema="xsds/validator.exsd"/>
<extension-point id="referencialFileValidator" name="%ReferencialFileValidator" schema="xsds/referencialFileExtSchema.exsd"/>
<extension-point id="validationSelectionHandler" name="%validationSelectionHandler" schema="xsds/validationSelectionHandler.exsd"/>
<extension-point id="validationHelper" name="validationHelper" schema="xsds/validationHelper.exsd"/>
<extension-point id="validatorDelegates" name="%ValidatorDelegates" schema="xsds/validatorDelegates.exsd"/>
+ <extension-point id="validatorGroup" name="Validator Group" schema="xsds/validatorgroup.exsd"/>
+ <extension-point id="exclude" name="Validator Exclusions" schema="xsds/exclude.exsd"/>
<!--============================-->
<!-- Validation Contributions -->
@@ -110,5 +112,20 @@
name="version">
</attribute>
</extension>
+ <!-- GRK - I added a new problem marker so that we can keep the v2 changes separate from the v1 framework. -->
+ <extension
+ id="problemmarker2"
+ name="%ProblemMarkerV2"
+ point="org.eclipse.core.resources.markers">
+ <super
+ type="org.eclipse.core.resources.problemmarker">
+ </super>
+ <persistent
+ value="true">
+ </persistent>
+ <attribute
+ name="owner">
+ </attribute>
+ </extension>
</plugin>
diff --git a/plugins/org.eclipse.wst.validation/property_files/org/eclipse/wst/validation/internal/messages.properties b/plugins/org.eclipse.wst.validation/property_files/org/eclipse/wst/validation/internal/messages.properties
new file mode 100644
index 0000000..a5062b8
--- /dev/null
+++ b/plugins/org.eclipse.wst.validation/property_files/org/eclipse/wst/validation/internal/messages.properties
@@ -0,0 +1,73 @@
+###############################################################################
+# Copyright (c) 2005, 2008 IBM Corporation 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:
+# IBM Corporation - initial API and implementation
+###############################################################################
+ErrConfig=IWAE0100E Extension configuration error. An internal error has happened, the validator {0} has incorrectly configured the validation extension point.
+ErrGroupName=IWAE0101E Invalid element, expect either the element "include" or "exclude".
+ErrFilterRule=IWAE0102E An invalid filter rule has been encountered.
+
+ErrGroupNoType=IWAE0103E Groups must have a valid type, no type was returned
+ErrGroupInvalidType=IWAE0104E Groups must have a valid type, the following invalid type was returned: {0}
+ErrDependencyVersion=IWAE0105E Only version {0} is supported
+
+ErrPatternAttrib=IWAE0106E The pattern attribute must be supplied
+ErrTypeReq=IWAE0107E Type is a required attribute for file filters
+
+VbfExcSyntaxNoValClass=IWAE0016E Validator cannot be created because no "class" attribute is specified in the <run> element of the plugin.xml file for the validator named {0}. Cannot create a validator unless a <run> element exists that specifies the "class" attribute. The value of the "class" attribute should be the name of the class that implements the IWorkbenchHelper interface.
+VbfExcSyntaxNoValRun=IWAE0015E Validator cannot be created because no <run> element is specified in the plugin.xml file for the validator named {0}. Cannot create a validator unless a <run> element exists that specifies the "class" attribute. The value of the "class" attribute should be the name of the class that implements the IWorkbenchHelper interface.
+VbfExcSyntaxNoValNull=IWAE0018E Validator class {0} could not be created. IConfigurationElement.createExecutableExtension(String) returned null.
+
+ErrType=The value of the type attribute is incorrect. It was specified as {0} but the only valid values are: {1}, {2}, {3}
+ConfigError=It appears that validator {0} (with id {1}) has been configured incorrectly, it produced {2} messages while validating {3}. It has been disabled. Try restoring the defaults for this validator.
+
+DecodeError1=IWAE0019E There was a problem deserializing a string. A boolean was expected but not found.
+Error20=IWAE0020E Internal error, the incoming validator must be a v2 validator
+GroupInclude=Include Group
+GroupExclude=Exclude Group
+
+TypeInclude=include
+TypeExclude=exclude
+
+JobName=Validation
+JobNameMonitor=Validation Monitor
+JobIndexSave=Index Save
+
+MigrationJobName=Validation Setup
+
+RuleProjectNature=Project nature
+RuleFileExt=File extension
+RuleFile=File
+RuleContentType=Content Type
+RuleFacet=Facet
+RuleFolder=Folder
+RuleFull=Qualified File
+
+FileExtWithCase={0}: {1} (case sensitive)
+FileExtWithoutCase={0}: {1}
+
+ContentTypeExact={0}: {1} (excludes subtypes)
+ContentTypeNotExact={0}: {1} (includes subtypes)
+
+LogValStart=Validator {0} starting to validate: {1}
+LogValEnd=Validator {0} finished validating: {1}
+LogValEndTime=Validator {0} with id {1} finished validating: {2} in {3}
+LogValSummary=Validator {0} with id {1} validated {2} resources in {3}
+LogValSummary2=Validator {0} with id {1} validated {2} resources in {3} using {4} of CPU time
+LogSession=Session started on: {0}
+
+SevError=Error
+SevWarning=Warning
+SevIgnore=Ignore
+
+TimeUnder=under a second
+TimeNano={0} nanoseconds
+TimeMicro={0} microseconds
+TimeSec={0} seconds
+TimeMin={0} minutes
+
diff --git a/plugins/org.eclipse.wst.validation/property_files/validate_base.properties b/plugins/org.eclipse.wst.validation/property_files/validate_base.properties
index 0a0955a..9e2583d 100644
--- a/plugins/org.eclipse.wst.validation/property_files/validate_base.properties
+++ b/plugins/org.eclipse.wst.validation/property_files/validate_base.properties
@@ -1,10 +1,10 @@
###############################################################################
-# Copyright (c) 2001, 2004 IBM Corporation and others.
+# Copyright (c) 2001, 2008 IBM Corporation 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:
# IBM Corporation - initial API and implementation
###############################################################################
@@ -79,14 +79,10 @@
VBF_EXC_RUNTIME=IWAE0010E Run-time exception {0} occurred during validation. The validator being run was {1} and the message thrown was {2}.
-VBF_EXC_SYNTAX_NULL_NAME=IWAE0011E Resource {0} cannot be added to file list because IWorkbenchContext.getPortableName() returns null. This resource will not be validated by the validator named {1}.
VBF_EXC_SYNTAX_NO_HELPER=IWAE0012E No <helper> element is specified in the plugin.xml file for validator {0}. Since the helper cannot be created, the validator will not be loaded.
VBF_EXC_SYNTAX_NO_HELPER_CLASS=IWAE0013E No "class" attribute in the <helper> element is specified in the plugin.xml file for validator {0}. The helper cannot be created without the name of the class that implements it. Since the helper cannot be created, the validator will not be loaded.
VBF_EXC_SYNTAX_NO_HELPER_THROWABLE=IWAE0014E The helper {0} cannot be created because a Throwable was caught.
-VBF_EXC_SYNTAX_NO_VAL_RUN=IWAE0015E Validator cannot be created because no <run> element is specified in the plugin.xml file for the validator named {0}. Cannot create a validator unless a <run> element exists that specifies the "class" attribute. The value of the "class" attribute should be the name of the class that implements the IWorkbenchHelper interface.
-VBF_EXC_SYNTAX_NO_VAL_CLASS=IWAE0016E Validator cannot be created because no "class" attribute is specified in the <run> element of the plugin.xml file for the validator named {0}. Cannot create a validator unless a <run> element exists that specifies the "class" attribute. The value of the "class" attribute should be the name of the class that implements the IWorkbenchHelper interface.
VBF_EXC_SYNTAX_NO_VAL_THROWABLE=IWAE0017E Cannot create validator {0} because a Throwable was caught.
-VBF_EXC_SYNTAX_NO_VAL_NULL=IWAE0018E Validator class {0} could not be created. IConfigurationElement.createExecutableExtension(String) returned null.
VBF_EXC_DISABLEV=IWAE0019E Cannot instantiate validator {0}. Disabling the validator; read the log for details.
VBF_EXC_DISABLEH=IWAE0020E Cannot instantiate helper {0}. Disabling validator {1}; read the log for details.
diff --git a/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/ConfigurationConstants.java b/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/ConfigurationConstants.java
index 171596b..16aef08 100644
--- a/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/ConfigurationConstants.java
+++ b/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/ConfigurationConstants.java
@@ -1,85 +1,86 @@
/*******************************************************************************
- * Copyright (c) 2001, 2004 IBM Corporation and others.
+ * Copyright (c) 2001, 2008 IBM Corporation 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:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.wst.validation.internal;
-
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.QualifiedName;
import org.eclipse.wst.validation.internal.plugin.ValidationPlugin;
-
/**
* Validation constants needed to implement the marker extension point and the user's preferences.
*
* Only the validation framework should use this interface.
*/
public interface ConfigurationConstants {
- public static final String DISABLE_ALL_VALIDATION_SETTING = "disableAllValidation"; //$NON-NLS-1$ // boolean
- ///* package */static final String AUTO_SETTING = "autoValidate"; //$NON-NLS-1$ // boolean
- ///* package */static final String BUILD_SETTING = "runWhenBuild"; //$NON-NLS-1$ // boolean
- public static final String SAVE_AUTOMATICALLY_SETTING = "saveAutomatically"; //$NON-NLS-1$ // boolean
+ String DISABLE_ALL_VALIDATION_SETTING = "disableAllValidation"; //$NON-NLS-1$ // boolean
+ String SAVE_AUTOMATICALLY_SETTING = "saveAutomatically"; //$NON-NLS-1$ // boolean
// Defaults for the preference and project values
- /* package */static String CURRENT_VERSION = (String) ValidationPlugin.getPlugin().getBundle().getHeaders().get(org.osgi.framework.Constants.BUNDLE_VERSION); //$NON-NLS-1$ // this is a constant, so it should be intern
- /* package */static final boolean DEFAULT_ASYNC = true;
- /* package */static final boolean DEFAULT_DISABLE_VALIDATION_SETTING = false;
- ///* package */static final boolean DEFAULT_AUTO_SETTING = true;
- ///* package */static final boolean DEFAULT_BUILD_SETTING = true;
- /* package */static ValidatorMetaData[] DEFAULT_ENABLED_VALIDATORS = ValidationRegistryReader.getReader().getValidatorMetaDataArrayEnabledByDefault(); //$NON-NLS-1$ // store a copy here so that we don't modify the original and don't create a copy every time we need this value
- /* package */static final int DEFAULT_MAXNUMMESSAGES = 50;
- public static final int DEPTH_INFINITE = IResource.DEPTH_INFINITE;
- public static final int DEPTH_ZERO = IResource.DEPTH_ZERO;
- /* package */static final String ELEMENT_SEPARATOR = ";"; //$NON-NLS-1$ // separates the name of one IValidator from the next in the list of enabled validators for a project or preference
- static final String DELEGATES_SEPARATOR = "="; //$NON-NLS-1$ // Separates the delegating validator id from the delegate validator id in the list of delegates
- // The following values must match the attributes in the preference marker as shown in
- // plugin.xml
+ String CURRENT_VERSION = (String) ValidationPlugin.getPlugin().getBundle().getHeaders().get(org.osgi.framework.Constants.BUNDLE_VERSION); // this is a constant, so it should be intern
+ boolean DEFAULT_ASYNC = true;
+ boolean DEFAULT_DISABLE_VALIDATION_SETTING = false;
+ ValidatorMetaData[] DEFAULT_ENABLED_VALIDATORS = ValidationRegistryReader.getReader().getValidatorMetaDataArrayEnabledByDefault(); // store a copy here so that we don't modify the original and don't create a copy every time we need this value
+ int DEFAULT_MAXNUMMESSAGES = 50;
+ int DEPTH_INFINITE = IResource.DEPTH_INFINITE;
+ int DEPTH_ZERO = IResource.DEPTH_ZERO;
+ String ELEMENT_SEPARATOR = ";"; //$NON-NLS-1$ // separates the name of one IValidator from the next in the list of enabled validators for a project or preference
+ String DELEGATES_SEPARATOR = "="; //$NON-NLS-1$ // Separates the delegating validator id from the delegate validator id in the list of delegates
+
+ // The following values must match the attributes in the preference marker as shown in plugin.xml
// Even though the plugin.xml values are not used to create new Preference or Project markers,
// maintaining one local name ensures that there's no confusion writing the migration code.
// These are the QualifiedNames used to persist the user's settings.
- /* package */static final String ENABLED_MANUAL_VALIDATORS = "enabledManualValidatorList"; //$NON-NLS-1$ // String
- /* package */static final String ENABLED_BUILD_VALIDATORS = "enabledBuildValidatorList"; //$NON-NLS-1$ // String
- /* package */static final String DELEGATE_VALIDATORS = "delegateValidatorList"; //$NON-NLS-1$ // String
- public static final String J2EE_PLUGIN_ID = "org.eclipse.jst.j2ee"; //$NON-NLS-1$ // For 4.03, this is the plugin id that the validation constants were declared in.
- /* package */static final String MAXNUMMESSAGES = "maxNumMessages"; //$NON-NLS-1$ // integer
- public static final String PLUGIN_ID = ValidationPlugin.PLUGIN_ID;
- /* package */static final String PREF_PROJECTS_CAN_OVERRIDE = "projectsCanOverride"; //$NON-NLS-1$ // boolean
+ String ENABLED_MANUAL_VALIDATORS = "enabledManualValidatorList"; //$NON-NLS-1$ // String
+ String ENABLED_BUILD_VALIDATORS = "enabledBuildValidatorList"; //$NON-NLS-1$ // String
+ String DELEGATE_VALIDATORS = "delegateValidatorList"; //$NON-NLS-1$ // String
+ String J2EE_PLUGIN_ID = "org.eclipse.jst.j2ee"; //$NON-NLS-1$ // For 4.03, this is the plugin id that the validation constants were declared in.
+ String MAXNUMMESSAGES = "maxNumMessages"; //$NON-NLS-1$ // integer
+ String PLUGIN_ID = ValidationPlugin.PLUGIN_ID;
+ String PREF_PROJECTS_CAN_OVERRIDE = "projectsCanOverride"; //$NON-NLS-1$ // boolean
// end validation message marker constants
// Preference and Project constants
- /* package */static final String PREFERENCE_MARKER = PLUGIN_ID + ".preferencemarker"; //$NON-NLS-1$
- /* package */static final String PRJ_MARKER = PLUGIN_ID + ".projectmarker"; //$NON-NLS-1$ // The extension which saves user validation preferences for a particular project (e.g. which validators run on the project)
- /* package */static final String PRJ_MARKER_403 = J2EE_PLUGIN_ID + ".projectmarker"; //$NON-NLS-1$ // The extension which saves user validation preferences for a particular project (e.g. which validators run on the project)
- /* package */static final String PRJ_OVERRIDEGLOBAL = "overrideGlobalPreferences"; //$NON-NLS-1$ // boolean (Use the global preferences or override)
+ String PREFERENCE_MARKER = PLUGIN_ID + ".preferencemarker"; //$NON-NLS-1$
+ String PRJ_MARKER = PLUGIN_ID + ".projectmarker"; //$NON-NLS-1$ // The extension which saves user validation preferences for a particular project (e.g. which validators run on the project)
+ String PRJ_MARKER_403 = J2EE_PLUGIN_ID + ".projectmarker"; //$NON-NLS-1$ // The extension which saves user validation preferences for a particular project (e.g. which validators run on the project)
+ String PRJ_OVERRIDEGLOBAL = "overrideGlobalPreferences"; //$NON-NLS-1$ // boolean (Use the global preferences or override)
- /* package */static final QualifiedName USER_PREFERENCE = new QualifiedName(PLUGIN_ID, "ValidationConfiguration"); //$NON-NLS-1$ // ValidationConfiguration for the IResource
- /* package */static final QualifiedName USER_MANUAL_PREFERENCE = new QualifiedName(PLUGIN_ID, "ValidationManualConfiguration"); //$NON-NLS-1$ // ValidationConfiguration for the IResource
- /* package */static final QualifiedName USER_BUILD_PREFERENCE = new QualifiedName(PLUGIN_ID, "ValidationBuildConfiguration"); //$NON-NLS-1$ // ValidationConfiguration for the IResource
- /* package */static final QualifiedName DELEGATES_PREFERENCE = new QualifiedName(PLUGIN_ID, "ValidationDelegatesConfiguration"); //$NON-NLS-1$ // ValidationConfiguration for the IResource
+ QualifiedName USER_PREFERENCE = new QualifiedName(PLUGIN_ID, "ValidationConfiguration"); //$NON-NLS-1$ // ValidationConfiguration for the IResource
+ QualifiedName USER_MANUAL_PREFERENCE = new QualifiedName(PLUGIN_ID, "ValidationManualConfiguration"); //$NON-NLS-1$ // ValidationConfiguration for the IResource
+ QualifiedName USER_BUILD_PREFERENCE = new QualifiedName(PLUGIN_ID, "ValidationBuildConfiguration"); //$NON-NLS-1$ // ValidationConfiguration for the IResource
+ QualifiedName DELEGATES_PREFERENCE = new QualifiedName(PLUGIN_ID, "ValidationDelegatesConfiguration"); //$NON-NLS-1$ // ValidationConfiguration for the IResource
// Validation message marker constants
- /* package */static final String VALIDATION_MARKER = PLUGIN_ID + ".problemmarker"; //$NON-NLS-1$ // The extension which is used to add validation markers to the task list
- /* package */static final String VALIDATION_MARKER_GROUP = "groupName"; //$NON-NLS-1$ // For incremental validation, this field associates a message with a group, so that a subset of messages may be removed from a file.
- /* package */static final String VALIDATION_MARKER_MESSAGEID = "messageId"; //$NON-NLS-1$ // Persist the message id of the message, not just the translated text.
-
- // The following values must match the attributes in the validation message marker as shown in
- // plugin.xml
- /* package */static final String VALIDATION_MARKER_OWNER = "owner"; //$NON-NLS-1$ // The IValidator who owns the IMarker on the task list
- /* package */static final String VALIDATION_MARKER_SEVERITY = "validationSeverity"; //$NON-NLS-1$ // one of the SeverityEnum values
- /* package */static final String VALIDATION_MARKER_TARGETOBJECT = "targetObject"; //$NON-NLS-1$ // When more than one target object resolves to the same IResource, this field identifies which targetObject owns a particular message.
- /* package */static final String VERSION = "version"; //$NON-NLS-1$
+
+ /**
+ * org.eclipse.wst.validation.problemmarker - The marker id which is used to add v1 validation markers
+ * to the task list */
+ String VALIDATION_MARKER = PLUGIN_ID + ".problemmarker"; //$NON-NLS-1$
+
+ /** For incremental validation, this field associates a message with a group, so that a subset of messages may be removed from a file. */
+ String VALIDATION_MARKER_GROUP = "groupName"; //$NON-NLS-1$
+
+ /** Persist the message id of the message, not just the translated text. */
+ String VALIDATION_MARKER_MESSAGEID = "messageId"; //$NON-NLS-1$
+
+ // The following values must match the attributes in the validation message marker as shown in plugin.xml
+ String VALIDATION_MARKER_OWNER = "owner"; //$NON-NLS-1$ // The IValidator who owns the IMarker on the task list
+ String VALIDATION_MARKER_SEVERITY = "validationSeverity"; //$NON-NLS-1$ // one of the SeverityEnum values
+ String VALIDATION_MARKER_TARGETOBJECT = "targetObject"; //$NON-NLS-1$ // When more than one target object resolves to the same IResource, this field identifies which targetObject owns a particular message.
+ String VERSION = "version"; //$NON-NLS-1$
// WSAD versions which created markers of these types
- /* package */static final String VERSION4_03 = "4.03"; //$NON-NLS-1$
- /* package */static final String VERSION5_0 = "5.0"; //$NON-NLS-1$
- /* package */static final String VERSION5_01 = "5.0.1"; //$NON-NLS-1$
+ String VERSION4_03 = "4.03"; //$NON-NLS-1$
+ String VERSION5_0 = "5.0"; //$NON-NLS-1$
+ String VERSION5_01 = "5.0.1"; //$NON-NLS-1$
// end preference and project defaults
-}
\ No newline at end of file
+}
diff --git a/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/ConfigurationManager.java b/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/ConfigurationManager.java
index 537d69a..47e919c 100644
--- a/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/ConfigurationManager.java
+++ b/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/ConfigurationManager.java
@@ -1,25 +1,22 @@
/*******************************************************************************
- * Copyright (c) 2001, 2004 IBM Corporation and others.
+ * Copyright (c) 2001, 2009 IBM Corporation 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:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.wst.validation.internal;
import java.lang.reflect.InvocationTargetException;
-import java.util.logging.Level;
import org.eclipse.core.resources.IMarker;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IWorkspaceRoot;
+import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.Preferences;
-import org.eclipse.jem.util.logger.LogEntry;
-import org.eclipse.jem.util.logger.proxy.Logger;
import org.eclipse.wst.validation.internal.plugin.ValidationPlugin;
@@ -27,17 +24,15 @@
* Only the validation framework can use this class.
*/
public final class ConfigurationManager implements ConfigurationConstants {
- private static ConfigurationManager inst = null;
+ private static ConfigurationManager _instance = null;
- private ConfigurationManager() {
- //Default constructor
- }
+ private ConfigurationManager() {}
public static ConfigurationManager getManager() {
- if (inst == null) {
- inst = new ConfigurationManager();
+ if (_instance == null) {
+ _instance = new ConfigurationManager();
}
- return inst;
+ return _instance;
}
/**
@@ -46,29 +41,16 @@
* return null.
*/
public String getValidator(IMarker marker) {
- if (marker == null) {
- return null;
- }
+ if (marker == null)return null;
try {
- if (!marker.getType().equals(VALIDATION_MARKER)) {
- return null;
- }
+ if (!marker.getType().equals(VALIDATION_MARKER))return null;
Object attrib = marker.getAttribute(VALIDATION_MARKER_OWNER);
- if (attrib == null) {
- // owner not set
- return null;
- }
+ if (attrib == null)return null;
return attrib.toString();
- } catch (CoreException exc) {
- Logger logger = ValidationPlugin.getPlugin().getMsgLogger();
- if (logger.isLoggingLevel(Level.SEVERE)) {
- LogEntry entry = ValidationPlugin.getLogEntry();
- entry.setSourceIdentifier("InternalPreferenceManager.getValidator(IMarker)"); //$NON-NLS-1$
- entry.setTargetException(exc);
- logger.write(Level.SEVERE, entry);
- }
+ } catch (CoreException e) {
+ ValidationPlugin.getPlugin().handleException(e);
return null;
}
}
@@ -77,47 +59,30 @@
* Return true if the given marker is a validation marker. Otherwise return false.
*/
public boolean isValidationMarker(IMarker marker) {
- if (marker == null) {
- return false;
- }
+ if (marker == null)return false;
try {
return marker.getType().equals(VALIDATION_MARKER);
- } catch (CoreException exc) {
- Logger logger = ValidationPlugin.getPlugin().getMsgLogger();
- if (logger.isLoggingLevel(Level.SEVERE)) {
- LogEntry entry = ValidationPlugin.getLogEntry();
- entry.setSourceIdentifier("InternalPreferenceManager.isValidationMarker(IMarker)"); //$NON-NLS-1$
- entry.setTargetException(exc);
- logger.write(Level.SEVERE, entry);
- }
+ } catch (CoreException e) {
+ ValidationPlugin.getPlugin().handleException(e);
return false;
}
}
/**
- * This method is for use by the TVT Validation plugin ONLY!!! No code should access the
+ * This method is for use by the TVT Validation plug-in ONLY!!! No code should access the
* validation markers in the list directly except for the validation framework and the TVT
- * Validation plugin.
+ * Validation plug-in.
*/
public void removeAllValidationMarkers(IProject project) {
- if ((project == null) || (!project.isOpen())) {
- return;
- }
+ if ((project == null) || (!project.isOpen()))return;
try {
project.deleteMarkers(VALIDATION_MARKER, false, DEPTH_INFINITE); // false means only
// consider VALIDATION_MARKER, not variants of VALIDATION_MARKER.
//Since addTask only adds VALIDATION_MARKER, we don't need to consider its subtypes.
- } catch (CoreException exc) {
- // Couldn't retrieve the markers from the resource for some reason...
- Logger logger = ValidationPlugin.getPlugin().getMsgLogger();
- if (logger.isLoggingLevel(Level.SEVERE)) {
- LogEntry entry = ValidationPlugin.getLogEntry();
- entry.setSourceIdentifier("WorkbenchMonitor.removeAllValidationMarkers(IProject)"); //$NON-NLS-1$
- entry.setTargetException(exc);
- logger.write(Level.SEVERE, entry);
- }
+ } catch (CoreException e) {
+ ValidationPlugin.getPlugin().handleException(e);
}
}
@@ -125,16 +90,25 @@
* This method returns the global preferences for the workspace.
*/
public GlobalConfiguration getGlobalConfiguration() throws InvocationTargetException {
- IWorkspaceRoot root = ValidationConfiguration.getRoot();
+ IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
+ GlobalConfiguration gp = null;
+ try {
+ gp = (GlobalConfiguration) root.getSessionProperty(USER_PREFERENCE);
+ if (gp == null)gp = getGlobalConfiguration(root);
+ } catch (CoreException exc) {
+ throw new InvocationTargetException(exc, ResourceHandler.getExternalizedMessage(ResourceConstants.VBF_EXC_RETRIEVE, new String[]{root.getName()}));
+ }
+ return gp;
+ }
+
+ private synchronized GlobalConfiguration getGlobalConfiguration(IWorkspaceRoot root) throws InvocationTargetException {
GlobalConfiguration gp = null;
try {
gp = (GlobalConfiguration) root.getSessionProperty(USER_PREFERENCE);
if (gp == null) {
gp = new GlobalConfiguration(root);
- Preferences prefs = ValidationPlugin.getPlugin().getPluginPreferences();
- if( prefs != null ){
- prefs.addPropertyChangeListener(gp);
- }
+ PreferencesWrapper prefs = PreferencesWrapper.getPreferences(null, null);
+// prefs.addPropertyChangeListener(gp);
gp.getVersion(); // initialize the configuration's version attribute
gp.load(); // initialize this instance from the stored values
@@ -181,45 +155,36 @@
/**
* The nature of the project has changed; update the enabled validators on the project.
+ *
+ * @deprecated this method doesn't do anything.
*/
public void resetProjectNature(IProject project) throws InvocationTargetException {
- resetProjectNature(getProjectConfiguration(project));
- }
-
- /**
- * When a project has been created for the first time, its natures may not have been complete at
- * the time that this Preference was recreated. Call this method to recalculate the vmds.
- */
- protected void resetProjectNature(ProjectConfiguration prjp) throws InvocationTargetException {
- prjp.resetProjectNature();
}
public void closing(IProject project) {
try {
if (isMigrated(project)) {
ProjectConfiguration prjp = ConfigurationManager.getManager().getProjectConfiguration(project);
- if(!prjp.useGlobalPreference())
- prjp.store();
+ if(!prjp.useGlobalPreference())prjp.store();
}
- } catch (InvocationTargetException exc) {
- Logger logger = ValidationPlugin.getPlugin().getMsgLogger();
- if (logger.isLoggingLevel(Level.SEVERE)) {
- LogEntry entry = ValidationPlugin.getLogEntry();
- entry.setSourceIdentifier("InternalPreferenceManager::closing(" + project.getName() + ")"); //$NON-NLS-1$ //$NON-NLS-2$
- entry.setTargetException(exc);
- logger.write(Level.SEVERE, entry);
-
- if (exc.getTargetException() != null) {
- entry.setTargetException(exc);
- logger.write(Level.SEVERE, entry);
- }
- }
+ } catch (InvocationTargetException e) {
+ ValidationPlugin.getPlugin().handleException(e);
+ if (e.getTargetException() != null)
+ ValidationPlugin.getPlugin().handleException(e.getTargetException());
}
}
+ /**
+ * @deprecated this method does not do anything.
+ * @param project
+ */
public void deleting(IProject project) {
}
+ /**
+ * @deprecated this method does not do anything.
+ * @param project
+ */
public void opening(IProject project) {
// Do not load or migrate the project in this method; let the getConfiguration(IProject)
// method do that. Do not load the project before it's necessary.
@@ -230,9 +195,7 @@
*/
public boolean isGlobalMigrated() throws InvocationTargetException {
IWorkspaceRoot root = ValidationConfiguration.getRoot();
- if (root == null) {
- return false;
- }
+ if (root == null)return false;
try {
GlobalConfiguration gp = (GlobalConfiguration) root.getSessionProperty(USER_PREFERENCE);
@@ -257,20 +220,17 @@
* Return true if the given project has the current level of metadata, false otherwise.
*/
public boolean isMigrated(IProject project) throws InvocationTargetException {
- if (project == null) {
- return false;
- }
+ if (project == null)return false;
+
try {
if (project.isAccessible()) {
ProjectConfiguration prjp = (ProjectConfiguration) project.getSessionProperty(USER_PREFERENCE);
- if (prjp != null) {
- return prjp.isVersionCurrent();
- }
+ if (prjp != null)return prjp.isVersionCurrent();
+
String serializedPrjp = project.getPersistentProperty(USER_PREFERENCE);
if (serializedPrjp != null) {
prjp = new ProjectConfiguration(project);
- prjp.getVersion(); // initialize the configuration's
- // version attribute
+ prjp.getVersion();
return prjp.isVersionCurrent();
}
}
@@ -280,4 +240,17 @@
return false;
}
-}
\ No newline at end of file
+ /**
+ * Answer the appropriate configuration based on whether the project has overridden the configuration
+ * or not. If the project exists and is allowed to override the global configuration answer the
+ * project configuration, otherwise answer the global configuration.
+ * @param project it can be null
+ */
+ public ValidationConfiguration getConfiguration(IProject project) throws InvocationTargetException {
+ if (project == null)return getGlobalConfiguration();
+ ProjectConfiguration pc = getProjectConfiguration(project);
+ if (pc != null && !pc.useGlobalPreference())return pc;
+ return getGlobalConfiguration();
+ }
+
+}
diff --git a/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/EventManager.java b/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/EventManager.java
index ab83e87..d603b8d 100644
--- a/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/EventManager.java
+++ b/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/EventManager.java
@@ -1,17 +1,18 @@
/*******************************************************************************
- * Copyright (c) 2001, 2004 IBM Corporation and others.
+ * Copyright (c) 2001, 2008 IBM Corporation 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:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.wst.validation.internal;
import java.lang.reflect.InvocationTargetException;
-import java.util.logging.Level;
+import java.util.Set;
+import java.util.concurrent.CopyOnWriteArraySet;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
@@ -23,9 +24,6 @@
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
-import org.eclipse.jem.util.UIContextDetermination;
-import org.eclipse.jem.util.logger.LogEntry;
-import org.eclipse.jem.util.logger.proxy.Logger;
import org.eclipse.wst.validation.internal.operations.IWorkbenchContext;
import org.eclipse.wst.validation.internal.plugin.ValidationPlugin;
@@ -33,47 +31,70 @@
* This class manages resource change events for the validation framework.
*/
public class EventManager implements IResourceChangeListener {
- private static EventManager _inst = null;
- private boolean _shutdown = false; // false means that eclipse is not shutting down, and true
- // means that it is shutting down. Used in two methods:
- // shutdown(),and resourceChanged(IResourceChangeEvent)
- private IResourceDeltaVisitor _postAutoBuildVisitor = null;
- private boolean _isActive = false; // has the registry been read?
+ private static EventManager _inst;
+
+ // false means that eclipse is not shutting down, and true means that it is shutting down.
+ private boolean _shutdown;
+
+ private IResourceDeltaVisitor _postAutoBuildVisitor;
+ private boolean _isActive; // has the registry been read?
+
+ private Set<IProjectChangeListener> _listeners = new CopyOnWriteArraySet<IProjectChangeListener>();
private EventManager() {
- super();
}
public static EventManager getManager() {
- if (_inst == null) {
- _inst = new EventManager();
- }
+ if (_inst == null)_inst = new EventManager();
return _inst;
}
+
+ public void addProjectChangeListener(IProjectChangeListener listener){
+ Tracing.log("EventManager-03: add listener: ", listener); //$NON-NLS-1$
+ _listeners.add(listener);
+ }
+
+ public void removeProjectChangeListener(IProjectChangeListener listener){
+ _listeners.remove(listener);
+ }
+
+ private void signal(IProject project, int type){
+ if (Tracing.isLogging()){
+ String name = "Null"; //$NON-NLS-1$
+ if (project != null)name = project.getName();
+ Tracing.log("EventManager-02: signal project: " + name + ", IProjectChangeListener type: " + type); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+ for (IProjectChangeListener pcl : _listeners){
+ try {
+ pcl.projectChanged(project, type);
+ }
+ catch (Exception e){
+ ValidationPlugin.getPlugin().handleException(e);
+ }
+ }
+ }
public void opening(IProject project) {
- if (project == null || !ValidationPlugin.isActivated()) {
- return;
- }
+ if (project == null || !ValidationPlugin.isActivated())return;
+
+ signal(project, IProjectChangeListener.ProjectOpened);
- // When the project is opened, check for any orphaned tasks
- // or tasks whose owners need to be updated.
- ConfigurationManager.getManager().opening(project);
+ // When the project is opened, check for any orphaned tasks or tasks whose owners need to be updated.
+// ConfigurationManager.getManager().opening(project);
}
public void closing(IProject project) {
- if (project == null || !ValidationPlugin.isActivated()) {
- return;
- }
-
+ if (project == null || !ValidationPlugin.isActivated())return;
+
+ signal(project, IProjectChangeListener.ProjectClosed);
+
try {
boolean isMigrated = ConfigurationManager.getManager().isMigrated(project);
// If it's not migrated, then it hasn't been loaded, and we don't want to load the
- // validator and its prerequisite plugins until they're needed.
+ // validator and its prerequisite plug-ins until they're needed.
if (isMigrated) {
ValidatorMetaData[] vmds = ConfigurationManager.getManager().getProjectConfiguration(project).getValidators();
- for (int i = 0; i < vmds.length; i++) {
- ValidatorMetaData vmd = vmds[i];
+ for (ValidatorMetaData vmd : vmds) {
if (!vmd.isActive()) {
// If this validator has not been activated, or if it has been shut down,
@@ -85,66 +106,39 @@
try {
helper = vmd.getHelper(project);
helper.closing();
- } catch (InstantiationException exc) {
+ } catch (InstantiationException e) {
// Remove the vmd from the reader's list
ValidationRegistryReader.getReader().disableValidator(vmd);
- // Log the reason for the disabled validator
- Logger logger = ValidationPlugin.getPlugin().getMsgLogger();
- if (logger.isLoggingLevel(Level.SEVERE)) {
- LogEntry entry = ValidationPlugin.getLogEntry();
- entry.setSourceID("EventManager::closing(IProject)"); //$NON-NLS-1$
- entry.setTargetException(exc);
- logger.write(Level.SEVERE, entry);
- }
-
- continue;
- } catch (Throwable exc) {
+ ValidationPlugin.getPlugin().handleException(e);
+ } catch (Exception e) {
// If there is a problem with this particular helper, log the error and
- // continue
- // with the next validator.
- Logger logger = ValidationPlugin.getPlugin().getMsgLogger();
- if (logger.isLoggingLevel(Level.SEVERE)) {
- LogEntry entry = ValidationPlugin.getLogEntry();
- entry.setSourceID("EventManager::closing(IProject)"); //$NON-NLS-1$
- entry.setTargetException(exc);
- logger.write(Level.SEVERE, entry);
- }
- continue;
+ // continue with the next validator.
+ ValidationPlugin.getPlugin().handleException(e);
}
}
ConfigurationManager.getManager().closing(project);
}
- } catch (InvocationTargetException exc) {
- Logger logger = ValidationPlugin.getPlugin().getMsgLogger();
- if (logger.isLoggingLevel(Level.SEVERE)) {
- LogEntry entry = ValidationPlugin.getLogEntry();
- entry.setSourceIdentifier("EventManager::closing(" + project.getName() + ")"); //$NON-NLS-1$ //$NON-NLS-2$
- entry.setTargetException(exc);
- logger.write(Level.SEVERE, entry);
-
- if (exc.getTargetException() != null) {
- entry.setTargetException(exc);
- logger.write(Level.SEVERE, entry);
- }
- }
+ } catch (InvocationTargetException e) {
+ ValidationPlugin.getPlugin().handleException(e);
+ if (e.getTargetException() != null)
+ ValidationPlugin.getPlugin().handleException(e.getTargetException());
}
}
public void deleting(IProject project) {
- if (project == null) {
- return;
- }
+ if (project == null)return;
+
+ signal(project, IProjectChangeListener.ProjectDeleted);
try {
boolean isMigrated = ConfigurationManager.getManager().isMigrated(project);
// If it's not migrated, then it hasn't been loaded, and we don't want to load the
- // validator and its prerequisite plugins until they're needed.
+ // validator and its prerequisite plug-ins until they're needed.
if (isMigrated) {
ValidatorMetaData[] vmds = ConfigurationManager.getManager().getProjectConfiguration(project).getValidators();
- for (int i = 0; i < vmds.length; i++) {
- ValidatorMetaData vmd = vmds[i];
+ for (ValidatorMetaData vmd : vmds) {
if (!vmd.isActive()) {
// If this validator has not been activated, or if it has been shut down,
@@ -156,50 +150,26 @@
try {
helper = vmd.getHelper(project);
helper.deleting();
- } catch (InstantiationException exc) {
+ } catch (InstantiationException e) {
// Remove the vmd from the reader's list
ValidationRegistryReader.getReader().disableValidator(vmd);
-
- // Log the reason for the disabled validator
- Logger logger = ValidationPlugin.getPlugin().getMsgLogger();
- if (logger.isLoggingLevel(Level.SEVERE)) {
- LogEntry entry = ValidationPlugin.getLogEntry();
- entry.setSourceID("EventManager::deleting(IProject)"); //$NON-NLS-1$
- entry.setTargetException(exc);
- logger.write(Level.SEVERE, entry);
- }
-
+ ValidationPlugin.getPlugin().handleException(e);
continue;
- } catch (Throwable exc) {
+ } catch (Exception e) {
// If there is a problem with this particular helper, log the error and
- // continue
- // with the next validator.
- Logger logger = ValidationPlugin.getPlugin().getMsgLogger();
- if (logger.isLoggingLevel(Level.SEVERE)) {
- LogEntry entry = ValidationPlugin.getLogEntry();
- entry.setSourceID("EventManager::deleting(IProject)"); //$NON-NLS-1$
- entry.setTargetException(exc);
- logger.write(Level.SEVERE, entry);
- }
+ // continue with the next validator.
+ ValidationPlugin.getPlugin().handleException(e);
continue;
}
}
- ConfigurationManager.getManager().deleting(project);
+// ConfigurationManager.getManager().deleting(project);
}
- } catch (InvocationTargetException exc) {
- Logger logger = ValidationPlugin.getPlugin().getMsgLogger();
- if (logger.isLoggingLevel(Level.SEVERE)) {
- LogEntry entry = ValidationPlugin.getLogEntry();
- entry.setSourceIdentifier("EventManager::deleting(" + project.getName() + ")"); //$NON-NLS-1$ //$NON-NLS-2$
- entry.setTargetException(exc);
- logger.write(Level.SEVERE, entry);
+ } catch (InvocationTargetException e) {
+ ValidationPlugin.getPlugin().handleException(e);
+ if (e.getTargetException() != null)
+ ValidationPlugin.getPlugin().handleException(e.getTargetException());
- if (exc.getTargetException() != null) {
- entry.setTargetException(exc);
- logger.write(Level.SEVERE, entry);
- }
- }
}
}
@@ -211,55 +181,33 @@
if (_postAutoBuildVisitor == null) {
_postAutoBuildVisitor = new IResourceDeltaVisitor() {
public boolean visit(IResourceDelta subdelta) throws CoreException {
- if (subdelta == null)
- return true;
+ if (subdelta == null)return false;
IResource resource = subdelta.getResource();
+ if (resource instanceof IWorkspaceRoot)return true;
if (resource instanceof IProject) {
IProject project = (IProject) resource;
if ((subdelta.getFlags() & IResourceDelta.DESCRIPTION) == IResourceDelta.DESCRIPTION) {
- try {
- ConfigurationManager.getManager().resetProjectNature(project); // flush
- // existing
- // "enabled
- // validator"
- // settings
- // and
- // reset
- // to
- // default
- } catch (InvocationTargetException exc) {
- Logger logger = ValidationPlugin.getPlugin().getMsgLogger();
- if (logger.isLoggingLevel(Level.SEVERE)) {
- LogEntry entry = ValidationPlugin.getLogEntry();
- entry.setSourceIdentifier("EventManager::postAutoChange"); //$NON-NLS-1$
- entry.setTargetException(exc);
- logger.write(Level.SEVERE, entry);
-
- if (exc.getTargetException() != null) {
- entry.setTargetException(exc);
- logger.write(Level.SEVERE, entry);
- }
- }
- }
+ signal(project, IProjectChangeListener.ProjectChanged);
return false;
}
if ((subdelta.getFlags() & IResourceDelta.OPEN) == IResourceDelta.OPEN) {
if (project.isOpen()) {
// Project was just opened. If project.isOpen() had returned false,
- // project
- // would just have been closed.
+ // project would just have been closed.
opening(project);
}
- // closing is called by PRE_CLOSE in resourceChanged
- // else {
- // closing(project);
- // }
+ return false;
+ }
+
+ if ((subdelta.getFlags() & IResourceDelta.ADDED) == IResourceDelta.ADDED) {
+ signal(project, IProjectChangeListener.ProjectAdded);
+ return false;
}
}
- return true;
+ return false;
}
};
}
@@ -267,7 +215,7 @@
try {
delta.accept(_postAutoBuildVisitor, true);
} catch (CoreException exc) {
- exc.printStackTrace();
+ ValidationPlugin.getPlugin().handleException(exc);
}
}
@@ -279,50 +227,42 @@
* @see IResource
*/
public void resourceChanged(IResourceChangeEvent event) {
- if (_shutdown && (!isActive())) {
- // If we're shutting down, and nothing has been activated, don't need to
- // do anything.
+ if (_shutdown && !isActive()) {
+ // If we're shutting down, and nothing has been activated, don't need to do anything.
return;
}
- /*
- * StringBuffer buffer = new StringBuffer(); buffer.append("IResourceChangeEvent type = ");
- * buffer.append(event.getType()); buffer.append(", resource = ");
- * buffer.append(event.getResource()); buffer.append(", source = ");
- * buffer.append(event.getSource()); buffer.append(", delta = ");
- * buffer.append(event.getDelta()); System.out.println(buffer.toString());
- */
-
+ if (Tracing.isLogging()){
+ Tracing.log("Eventmanager-01: IResourceChangeEvent type=" + //$NON-NLS-1$
+ Misc.resourceChangeEventType(event.getType()) +
+ ", resource=" + //$NON-NLS-1$
+ event.getResource() + ", source=" + event.getSource() + ", delta=" + //$NON-NLS-1$//$NON-NLS-2$
+ event.getDelta());
+ }
+
if (event.getSource() instanceof IWorkspace) {
- if ((event.getType() == IResourceChangeEvent.PRE_DELETE) && (event.getResource() instanceof IProject)) {
+ boolean isProject = event.getResource() instanceof IProject;
+ if ((event.getType() == IResourceChangeEvent.PRE_DELETE) && isProject) {
deleting((IProject) event.getResource());
- } else if ((event.getType() == IResourceChangeEvent.PRE_CLOSE) && (event.getResource() instanceof IProject)) {
+ } else if ((event.getType() == IResourceChangeEvent.PRE_CLOSE) && isProject) {
closing((IProject) event.getResource());
} else if (event.getType() == IResourceChangeEvent.POST_BUILD) {
postAutoChange(event.getDelta());
}
-
}
}
/**
* Notifies this manager that the ValidationPlugin is shutting down. (Usually implies that
- * either the plugin could not load, or that the workbench is shutting down.)
- *
+ * either the plug-in could not load, or that the workbench is shutting down.)
+ * <p>
* The manager will then notify all active helpers of the shutdown, so that they may perform any
* last-minute writes to disk, cleanup, etc.
*/
public void shutdown() {
try {
- _shutdown = true; // resourceChanged(IResourceChangeEvent) needs to know when a shutdown
- // has started.
-
- /*
- * if( !isHeadless() && ConfigurationManager.getManager().isGlobalMigrated()) {
- * GlobalConfiguration gp = ConfigurationManager.getManager().getGlobalConfiguration();
- * gp.store(); // First, see if any validators are loaded. If none are, there is nothing
- * to // clean up. if(gp.numberOfValidators() == 0) { return; } }
- */
+ // resourceChanged(IResourceChangeEvent) needs to know when a shutdown has started.
+ _shutdown = true;
// If the validators are loaded, then for every project in the workbench,
// we must see if it has been loaded. If it has, every enabled IWorkbenchContext
@@ -332,9 +272,7 @@
IWorkspaceRoot workspaceRoot = workspace.getRoot();
IProject[] projects = workspaceRoot.getProjects();
ProjectConfiguration prjp = null;
- IProject project = null;
- for (int i = 0; i < projects.length; i++) {
- project = projects[i];
+ for (IProject project : projects) {
if (!project.isOpen()) {
// If the project isn't opened, there's nothing to clean up.
// If the project was opened, it would have been migrated, and there's something
@@ -345,17 +283,12 @@
try {
boolean isMigrated = ConfigurationManager.getManager().isMigrated(project);
// If it's not migrated, then it hasn't been loaded, and we don't want to load
- // the
- // validator and its prerequisite plugins until they're needed.
+ // the validator and its prerequisite plug-ins until they're needed.
if (isMigrated) {
prjp = ConfigurationManager.getManager().getProjectConfiguration(project);
- //No need to save project level validation preferences at shutdown.b
- //if(!prjp.useGlobalPreference())
- // prjp.store();
ValidatorMetaData[] vmdList = prjp.getEnabledValidators();
- // if vmdList is null, IProject has never been loaded, so nothing to clean
- // up
+ // if vmdList is null, IProject has never been loaded, so nothing to clean up
if (vmdList != null) {
for (int j = 0; j < vmdList.length; j++) {
ValidatorMetaData vmd = vmdList[j];
@@ -370,36 +303,28 @@
if (helper != null) {
try {
helper.shutdown();
- } catch (Throwable exc) {
+ } catch (Exception exc) {
// Since we're shutting down, ignore the exception.
}
}
}
}
}
- } catch (InvocationTargetException exc) {
- Logger logger = ValidationPlugin.getPlugin().getMsgLogger();
- if (logger.isLoggingLevel(Level.SEVERE)) {
- LogEntry entry = ValidationPlugin.getLogEntry();
- entry.setSourceIdentifier("EventManager::shutdown(" + project.getName() + ")"); //$NON-NLS-1$ //$NON-NLS-2$
- entry.setTargetException(exc);
- logger.write(Level.SEVERE, entry);
+ } catch (InvocationTargetException e) {
+ ValidationPlugin.getPlugin().handleException(e);
+ if (e.getTargetException() != null)
+ ValidationPlugin.getPlugin().handleException(e.getTargetException());
- if (exc.getTargetException() != null) {
- entry.setTargetException(exc);
- logger.write(Level.SEVERE, entry);
- }
- }
}
}
- } catch (Throwable exc) {
+ } catch (Exception exc) {
// Since we're shutting down, ignore the exception.
}
}
public boolean isActive() {
// Have to use this convoluted technique for the shutdown problem.
- // i.e., when eclipse is shut down, if validation plugin hasn't been loaded,
+ // i.e., when eclipse is shut down, if validation plug-in hasn't been loaded,
// the EventManager is activated for the first time, and it
// sends many exceptions to the .log. At first, I wrote a
// static method on ValidationRegistryReader, which returned true
@@ -421,12 +346,13 @@
}
/**
- * This method should be used to determine if the workbench is running in UI or Headless
+ * This method should be used to determine if the workbench is running in UI or Headless.
+ *
+ * @deprecated This plug-in no longer depends on jem. If you need this function use the jem
+ * code directly.
*/
public static boolean isHeadless() {
- boolean ret = UIContextDetermination.getCurrentContext() == UIContextDetermination.HEADLESS_CONTEXT;
- return ret;
- //return UIContextDetermination.getCurrentContext() ==
- // UIContextDetermination.HEADLESS_CONTEXT;
+ //return UIContextDetermination.getCurrentContext() == UIContextDetermination.HEADLESS_CONTEXT;
+ return false;
}
-}
\ No newline at end of file
+}
diff --git a/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/FilterUtil.java b/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/FilterUtil.java
index 3a82813..39a36bc 100644
--- a/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/FilterUtil.java
+++ b/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/FilterUtil.java
@@ -1,23 +1,20 @@
/*******************************************************************************
- * Copyright (c) 2001, 2004 IBM Corporation and others.
+ * Copyright (c) 2001, 2008 IBM Corporation 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:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.wst.validation.internal;
-import java.text.MessageFormat;
import java.util.HashMap;
import java.util.HashSet;
-import java.util.Iterator;
import java.util.Map;
import java.util.Set;
-import java.util.logging.Level;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
@@ -28,10 +25,9 @@
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
+import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.OperationCanceledException;
-import org.eclipse.jem.util.logger.LogEntry;
-import org.eclipse.jem.util.logger.proxy.Logger;
import org.eclipse.wst.validation.internal.core.IFileDelta;
import org.eclipse.wst.validation.internal.operations.IWorkbenchContext;
import org.eclipse.wst.validation.internal.operations.WorkbenchFileDelta;
@@ -45,9 +41,9 @@
private static VMDResourceVisitor _resourceVisitor = null;
private interface VMDRecorder {
- public Map getResult();
+ public Map<ValidatorMetaData, Set<IFileDelta>> getResult();
- public void setEnabledValidators(Set enabledValidators);
+ public void setEnabledValidators(Set<ValidatorMetaData> enabledValidators);
public void setProgressMonitor(IProgressMonitor monitor);
@@ -55,53 +51,40 @@
}
private interface VMDDeltaVisitor extends VMDRecorder, IResourceDeltaVisitor {
- //constructor
}
private interface VMDResourceVisitor extends VMDRecorder, IResourceVisitor {
- //constructor
}
- /**
- * Don't let anyone create an instance of this class.
- */
private FilterUtil() {
- //default
}
/**
* Given a Set of enabled ValidatorMetaData, create a Map with each ValidatorMetaData as a key
* with an associated null value.
*/
- static Map wrapInMap(Set enabledValidators) {
- Map result = new HashMap();
- if ((enabledValidators == null) || (enabledValidators.size() == 0)) {
- return result;
- }
+ static Map<ValidatorMetaData, Set<IFileDelta>> wrapInMap(Set<ValidatorMetaData> enabledValidators) {
+ Map<ValidatorMetaData, Set<IFileDelta>> result = new HashMap<ValidatorMetaData, Set<IFileDelta>>();
+ if ((enabledValidators == null) || (enabledValidators.size() == 0))return result;
- Iterator iterator = enabledValidators.iterator();
- while (iterator.hasNext()) {
- result.put(iterator.next(), null);
- }
+ for (ValidatorMetaData vmd : enabledValidators)result.put(vmd, null);
return result;
}
static void checkCanceled(IProgressMonitor monitor) throws OperationCanceledException {
- if (monitor == null) {
- return;
- } else if (monitor.isCanceled()) {
- throw new OperationCanceledException(""); //$NON-NLS-1$
- }
+ if (monitor == null)return;
+ else if (monitor.isCanceled())throw new OperationCanceledException(""); //$NON-NLS-1$
}
/**
* Given a Map of VMD <=>Set(IFileDelta), either return the existing Set or create a Set and
* return it.
*/
- private static Set getResourceDeltas(Map enabledValidators, ValidatorMetaData vmd) {
- Set fileDeltas = (Set) enabledValidators.get(vmd);
+ private static Set<IFileDelta> getResourceDeltas(Map<ValidatorMetaData, Set<IFileDelta>> enabledValidators,
+ ValidatorMetaData vmd) {
+ Set<IFileDelta> fileDeltas = enabledValidators.get(vmd);
if (fileDeltas == null) {
- fileDeltas = new HashSet();
+ fileDeltas = new HashSet<IFileDelta>();
enabledValidators.put(vmd, fileDeltas);
}
return fileDeltas;
@@ -168,8 +151,9 @@
* Return the validators which are both configured on this type of project, (as stored in
* getProject()), and enabled by the user on this project.
*/
- static void addFileDelta(Map enabledValidators, ValidatorMetaData vmd, WorkbenchFileDelta fileDelta) {
- Set fileDeltas = getResourceDeltas(enabledValidators, vmd);
+ static void addFileDelta(Map<ValidatorMetaData, Set<IFileDelta>> enabledValidators,
+ ValidatorMetaData vmd, WorkbenchFileDelta fileDelta) {
+ Set<IFileDelta> fileDeltas = getResourceDeltas(enabledValidators, vmd);
fileDeltas.add(fileDelta);
enabledValidators.put(vmd, fileDeltas);
}
@@ -181,59 +165,43 @@
* If filterIn is true, do not check if the resources are filtered in by the validator. If
* filterIn is false, check if the resources are filtered in by the validator (recommended).
*/
- public static Map getFileDeltas(Set enabledValidators, Object[] changedResources, boolean filterIn) {
- return getFileDeltas(enabledValidators, changedResources, IFileDelta.CHANGED, filterIn); // by
- // default,
- // assume
- // that
- // the
- // resources
- // have
- // changed,
- // not
- // added
- // or
- // deleted
+ public static Map<ValidatorMetaData, Set<IFileDelta>>
+ getFileDeltas(Set<ValidatorMetaData> enabledValidators, Object[] changedResources, boolean filterIn) {
+ // by default assume that the resources have changed, i.e. not added or deleted
+ return getFileDeltas(enabledValidators, changedResources, IFileDelta.CHANGED, filterIn);
}
/**
* Return a Map wrapper, with each VMD from enabledValidators as the key, and the value a Set of
* IFileDelta wrapper around the changed Object[], with each delta of type deltaType.
*/
- public static Map getFileDeltas(Set enabledValidators, Object[] changedResources, int ifileDeltaType) {
- return getFileDeltas(enabledValidators, changedResources, ifileDeltaType, false); // by
- // default,
- // check
- // if the
- // Object[]
- // are
- // filtered
- // in by
- // the
- // validator
+ public static Map<ValidatorMetaData, Set<IFileDelta>>
+ getFileDeltas(Set<ValidatorMetaData> enabledValidators, Object[] changedResources, int ifileDeltaType) {
+ // by default check if the Objects are filtered in by the validator
+ return getFileDeltas(enabledValidators, changedResources, ifileDeltaType, false);
}
/**
* Return a Map wrapper, with each VMD from enabledValidators as the key, and the value a Set of
* IFileDelta wrapper around the changed Object[].
- *
+ * <p>
* If "force" is true, then don't check if the object is filtered in by the validator or not.
* ValidatorSubsetOperation can use validators that don't filter in these particular resources,
* but can use a defaultExtension's validators instead.
*/
- public static Map getFileDeltas(Set enabledValidators, Object[] changedResources, int ifileDeltaType, boolean force) {
- Map result = new HashMap();
+ public static Map<ValidatorMetaData, Set<IFileDelta>> getFileDeltas(Set<ValidatorMetaData> enabledValidators,
+ Object[] changedResources, int ifileDeltaType, boolean force) {
+
+ Map<ValidatorMetaData, Set<IFileDelta>> result = new HashMap<ValidatorMetaData, Set<IFileDelta>>();
if ((enabledValidators == null) || (enabledValidators.size() == 0)) {
return result;
}
- Iterator iterator = enabledValidators.iterator();
boolean cannotLoad = false;
IWorkbenchContext helper = null;
- while (iterator.hasNext()) {
- ValidatorMetaData vmd = (ValidatorMetaData) iterator.next();
+ for (ValidatorMetaData vmd : enabledValidators) {
try {
- Set deltas = new HashSet();
+ Set<IFileDelta> deltas = new HashSet<IFileDelta>();
IProgressMonitor monitor = new NullProgressMonitor();
for (int i = 0; i < changedResources.length; i++) {
Object obj = changedResources[i];
@@ -254,20 +222,12 @@
}
}
result.put(vmd, deltas);
- } catch (InstantiationException exc) {
+ } catch (InstantiationException e) {
cannotLoad = true;
// Remove the vmd from the reader's list
ValidationRegistryReader.getReader().disableValidator(vmd);
-
- // Log the reason for the disabled validator
- Logger logger = ValidationPlugin.getPlugin().getMsgLogger();
- if (logger.isLoggingLevel(Level.SEVERE)) {
- LogEntry entry = ValidationPlugin.getLogEntry();
- entry.setSourceID("FilterUtil::getFileDeltas(Set, Object[], int, boolean)"); //$NON-NLS-1$
- entry.setTargetException(exc);
- logger.write(Level.SEVERE, entry);
- }
+ ValidationPlugin.getPlugin().handleException(e);
continue;
}
@@ -285,7 +245,6 @@
}
}
-
return result;
}
@@ -295,16 +254,11 @@
if (fileName == null) {
// The resource is not contained in the current project.
// Can't see how this would happen, but check for it anyway.
- Logger logger = ValidationPlugin.getPlugin().getMsgLogger();
- if (logger.isLoggingLevel(Level.SEVERE)) {
- LogEntry entry = ValidationPlugin.getLogEntry();
- entry.setSourceID("FilterUtil::getFileDelta(IWorkbenchContext, ValidatorMetaData, IResource, int)"); //$NON-NLS-1$
- entry.setMessageTypeID(ResourceConstants.VBF_EXC_SYNTAX_NULL_NAME);
- String result = MessageFormat.format(ResourceHandler.getExternalizedMessage(ResourceConstants.VBF_EXC_SYNTAX_NULL_NAME), new String[]{resource.getName(), vmd.getValidatorDisplayName()});
- entry.setText(result);
- //entry.setTokens(new String[]{resource.getName(), vmd.getValidatorDisplayName()});
- logger.write(Level.SEVERE, entry);
- }
+
+ // [122960] null should be allowed
+// String result = MessageFormat.format(ResourceHandler.getExternalizedMessage(ResourceConstants.VBF_EXC_SYNTAX_NULL_NAME),
+// new Object[]{resource.getName(), vmd.getValidatorDisplayName()});
+// ValidationPlugin.getPlugin().logMessage(IStatus.ERROR, result);
IPath resourcePath = resource.getFullPath();
if (resourcePath != null) {
@@ -312,12 +266,8 @@
// resource.
fileName = resourcePath.toString();
} else {
- if (logger.isLoggingLevel(Level.SEVERE)) {
- LogEntry entry = ValidationPlugin.getLogEntry();
- entry.setSourceID("FilterUtil::getFileDelta(IWorkbenchContext, ValidtaorMetaData, IResource, int)"); //$NON-NLS-1$
- entry.setText("portableName is null and path is null for resource " + resource); //$NON-NLS-1$
- logger.write(Level.SEVERE, entry);
- }
+ ValidationPlugin.getPlugin().logMessage(IStatus.ERROR,
+ "portableName is null and path is null for resource " + resource); //$NON-NLS-1$
return null;
}
}
@@ -331,23 +281,15 @@
* Add the IResource to the vmd's list of resources to validate. Return true if the add was
* successful or false if the add was not successful.
*/
- static boolean addToFileList(Map enabledValidators, IWorkbenchContext helper, ValidatorMetaData vmd, IResource resource, int resourceDelta, boolean isFullBuild) {
+ static boolean addToFileList(Map<ValidatorMetaData, Set<IFileDelta>> enabledValidators, IWorkbenchContext helper, ValidatorMetaData vmd, IResource resource, int resourceDelta, boolean isFullBuild) {
if ((vmd == null) || (resource == null)) {
return false;
}
try {
helper.registerResource(resource);
- } catch (Throwable exc) {
- // How to log this????
- Logger logger = ValidationPlugin.getPlugin().getMsgLogger();
- if (logger.isLoggingLevel(Level.SEVERE)) {
- LogEntry entry = ValidationPlugin.getLogEntry();
- entry.setSourceID("FilterUtil.addToFileList"); //$NON-NLS-1$
- entry.setTargetException(exc);
- logger.write(Level.SEVERE, entry);
- }
-
+ } catch (Exception exc) {
+ ValidationPlugin.getPlugin().handleException(exc);
InternalValidatorManager.getManager().addInternalErrorTask(resource.getProject(), vmd, exc);
// Don't return ... even though the register threw an exception, that's not to say
@@ -398,55 +340,50 @@
}
/**
- * Whether a full verification or a delta verification is in progress, both will call this
- * method to process the resource. This method calls the current Validator to filter the
- * resource (i.e., this method returns if the resource fails the filter test).
- * <code>process</code> also sends output to the <code>IProgressMonitor</code>, and calls
- * the current Validator to validate the resource.
- *
- * To process a resource, there are several steps: 1. check if the resource is registered for
- * this validator (i.e., the validator has either specified it in a filter, or has not filtered
- * it out explicitly) 2. call <code>isValidationSource</code> on the current validator with
- * the current resource. This method performs further filtering by the Validator itself, in
- * addition to the static filtering done by the framework, based on the information in
- * plugin.xml. 3. If the resource passes both filters, call <code>validate</code> on the
- * validator, with the resource. 4. When complete (either by failing to pass a filter, or by the
- * completion of the <code>validate</code>), increment the IProgressMonitor's status by one
- * (i.e., one resource has been processed.)
+ * Whether a full verification or a delta verification is in progress, both
+ * will call this method to process the resource. This method calls the
+ * current Validator to filter the resource (i.e., this method returns if
+ * the resource fails the filter test). It also sends output to the
+ * <code>IProgressMonitor</code>, and calls the current Validator to
+ * validate the resource.
+ * <p>
+ * To process a resource, there are several steps:
+ * <ol>
+ * <li>Check if the resource is registered for this validator (i.e., the
+ * validator has either specified it in a filter, or has not filtered it out
+ * explicitly)
+ * <li>Call <code>isValidationSource</code> on the current validator with
+ * the current resource. This method performs further filtering by the
+ * Validator itself, in addition to the static filtering done by the
+ * framework, based on the information in the extension point.
+ * <li>If the resource passes both filters, call <code>validate</code> on
+ * the validator, with the resource.
+ * <li>When complete (either by failing to pass a filter, or by the
+ * completion of the <code>validate</code>), increment the
+ * IProgressMonitor's status by one (i.e., one resource has been processed.)
+ * </ol>
*/
- static void filterOut(IProgressMonitor monitor, Map enabledValidators, IResource resource, int resourceDelta, boolean isFullBuild) {
- if (monitor == null) {
- return;
- }
+ static void filterOut(IProgressMonitor monitor, Map<ValidatorMetaData, Set<IFileDelta>> enabledValidators,
+ IResource resource, int resourceDelta, boolean isFullBuild) {
+ if (monitor == null)return;
checkCanceled(monitor);
- Iterator iterator = enabledValidators.keySet().iterator();
boolean cannotLoad = false;
- while (iterator.hasNext()) {
+ for (ValidatorMetaData vmd : enabledValidators.keySet()) {
checkCanceled(monitor);
- ValidatorMetaData vmd = (ValidatorMetaData) iterator.next();
-
if (!filterOut(monitor, vmd, resource, resourceDelta)) {
try {
// Notify the helper that a resource is about to be filtered in
IWorkbenchContext helper = vmd.getHelper(resource.getProject());
addToFileList(enabledValidators, helper, vmd, resource, resourceDelta, isFullBuild);
- } catch (InstantiationException exc) {
+ } catch (InstantiationException e) {
cannotLoad = true;
// Remove the vmd from the reader's list
ValidationRegistryReader.getReader().disableValidator(vmd);
-
- // Log the reason for the disabled validator
- Logger logger = ValidationPlugin.getPlugin().getMsgLogger();
- if (logger.isLoggingLevel(Level.SEVERE)) {
- LogEntry entry = ValidationPlugin.getLogEntry();
- entry.setSourceID("FilterUtil::filterOut(IProgressMonitor, Map, IResource, int, boolean)"); //$NON-NLS-1$
- entry.setTargetException(exc);
- logger.write(Level.SEVERE, entry);
- }
+ ValidationPlugin.getPlugin().handleException(e);
}
}
}
@@ -487,12 +424,12 @@
* completion of the <code>validate</code>), increment the IProgressMonitor's status by one
* (i.e., one resource has been processed.)
*/
- static void filterOut(IProgressMonitor monitor, Map enabledValidators, IResource resource, IResourceDelta delta) {
+ static void filterOut(IProgressMonitor monitor, Map<ValidatorMetaData, Set<IFileDelta>> enabledValidators,
+ IResource resource, IResourceDelta delta) {
// filter in only resources which have been added, deleted, or its content changed.
// moves will be registered as an add & delete combination
- if (filterOut(delta)) {
- return;
- }
+ if (filterOut(delta))return;
+
filterOut(monitor, enabledValidators, resource, delta.getKind(), false); // false =
// incremental
// build
@@ -608,17 +545,17 @@
return true;
}
- private static VMDResourceVisitor getResourceVisitor(IProgressMonitor monitor, Set enabledValidators) {
+ private static VMDResourceVisitor getResourceVisitor(IProgressMonitor monitor, Set<ValidatorMetaData> enabledValidators) {
if (_resourceVisitor == null) {
_resourceVisitor = new VMDResourceVisitor() {
- private Map _vmdDeltas = null;
+ private Map<ValidatorMetaData, Set<IFileDelta>> _vmdDeltas = null;
private IProgressMonitor _progressMonitor = null;
- public Map getResult() {
+ public Map<ValidatorMetaData, Set<IFileDelta>> getResult() {
return _vmdDeltas;
}
- public void setEnabledValidators(Set validators) {
+ public void setEnabledValidators(Set<ValidatorMetaData> validators) {
_vmdDeltas = wrapInMap(validators);
}
@@ -635,12 +572,7 @@
// We don't need to filter out anything, because a full validation
// is about to be performed.
- filterOut(getProgressMonitor(), _vmdDeltas, res, IResourceDelta.CHANGED, true); // true
- // -
- // this
- // is a
- // full
- // build
+ filterOut(getProgressMonitor(), _vmdDeltas, res, IResourceDelta.CHANGED, true);
return true; // visit the resource's children as well
}
@@ -652,17 +584,17 @@
return _resourceVisitor;
}
- private static VMDDeltaVisitor getDeltaVisitor(IProgressMonitor monitor, Set enabledValidators) {
+ private static VMDDeltaVisitor getDeltaVisitor(IProgressMonitor monitor, Set<ValidatorMetaData> enabledValidators) {
if (_deltaVisitor == null) {
_deltaVisitor = new VMDDeltaVisitor() {
- private Map _vmdDeltas = null;
+ private Map<ValidatorMetaData, Set<IFileDelta>> _vmdDeltas = null;
private IProgressMonitor _progressMonitor = null;
- public Map getResult() {
+ public Map<ValidatorMetaData, Set<IFileDelta>> getResult() {
return _vmdDeltas;
}
- public void setEnabledValidators(Set validators) {
+ public void setEnabledValidators(Set<ValidatorMetaData> validators) {
_vmdDeltas = wrapInMap(validators);
}
@@ -681,24 +613,16 @@
IResource resource = subdelta.getResource();
- Logger logger = ValidationPlugin.getPlugin().getMsgLogger();
- if (logger.isLoggingLevel(Level.FINEST)) {
- StringBuffer buffer = new StringBuffer("subdelta of "); //$NON-NLS-1$
+ if (Tracing.isLogging(2)) {
+ StringBuffer buffer = new StringBuffer("FilterUtil-01: subdelta of "); //$NON-NLS-1$
buffer.append(resource.getName());
- buffer.append(" is "); //$NON-NLS-1$
+ buffer.append(" has resource delta kind: "); //$NON-NLS-1$
buffer.append(subdelta.getKind());
- buffer.append(" resource exists? "); //$NON-NLS-1$
+ buffer.append(" Does the resource exist? "); //$NON-NLS-1$
buffer.append(resource.exists());
- buffer.append(" resource.isPhantom?"); //$NON-NLS-1$
+ buffer.append(" Is it a phantom? "); //$NON-NLS-1$
buffer.append(resource.isPhantom());
-
- if (logger.isLoggingLevel(Level.FINEST)) {
- LogEntry entry = ValidationPlugin.getLogEntry();
- entry.setSourceID("FilterUtil::visit(IResourceDelta)"); //$NON-NLS-1$
- entry.setText(buffer.toString());
- logger.write(Level.FINEST, entry);
- }
-
+ Tracing.log(buffer);
}
// If the delta is an IProject, and the IProject is getting deleted or closed,
@@ -717,16 +641,18 @@
return _deltaVisitor;
}
- public static Map loadDeltas(final IProgressMonitor monitor, final Set enabledValidators, IResourceDelta delta) throws CoreException {
+ public static Map<ValidatorMetaData, Set<IFileDelta>> loadDeltas(final IProgressMonitor monitor,
+ final Set<ValidatorMetaData> enabledValidators, IResourceDelta delta) throws CoreException {
VMDDeltaVisitor visitor = getDeltaVisitor(monitor, enabledValidators);
delta.accept(visitor, true); // true means include phantom resources
return visitor.getResult();
}
- public static Map loadDeltas(final IProgressMonitor monitor, final Set enabledValidators, IProject project) throws CoreException {
+ public static Map<ValidatorMetaData, Set<IFileDelta>> loadDeltas(final IProgressMonitor monitor,
+ final Set<ValidatorMetaData> enabledValidators, IProject project) throws CoreException {
VMDResourceVisitor visitor = getResourceVisitor(monitor, enabledValidators);
project.accept(visitor, IResource.DEPTH_INFINITE, true); // true means include phantom
// resources
return visitor.getResult();
}
-}
\ No newline at end of file
+}
diff --git a/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/GlobalConfiguration.java b/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/GlobalConfiguration.java
index 3204d26..20c044f 100644
--- a/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/GlobalConfiguration.java
+++ b/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/GlobalConfiguration.java
@@ -1,25 +1,21 @@
/*******************************************************************************
- * Copyright (c) 2001, 2004 IBM Corporation and others.
+ * Copyright (c) 2001, 2008 IBM Corporation 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:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.wst.validation.internal;
import java.lang.reflect.InvocationTargetException;
-import java.util.logging.Level;
import org.eclipse.core.resources.IMarker;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.Preferences;
-import org.eclipse.jem.util.logger.LogEntry;
-import org.eclipse.jem.util.logger.proxy.Logger;
import org.eclipse.wst.validation.internal.plugin.ValidationPlugin;
@@ -27,7 +23,7 @@
* This class represents the global Preferences as set on the Validation Preferences page.
*/
public class GlobalConfiguration extends ValidationConfiguration {
- /* package */static final boolean PREF_PROJECTS_CAN_OVERRIDE_DEFAULT = true;
+ static final boolean PREF_PROJECTS_CAN_OVERRIDE_DEFAULT = true;
static final boolean PREF_SAVE_AUTOMATICALLY_DEFAULT = false;
private boolean _canProjectsOverride = getCanProjectsOverrideDefault();
@@ -39,14 +35,11 @@
public GlobalConfiguration(IWorkspaceRoot root) throws InvocationTargetException {
super(root, convertToArray(ValidationRegistryReader.getReader().getAllValidators()));
- // Can't put the call to load() and passivate() in the ValidationConfiguration constructor
- // due
+ // Can't put the call to load() and passivate() in the ValidationConfiguration constructor due
// to the order of initialization.
- // 1. First the ValidationConfiguration constructor is called, and that loads the stored
- // values.
+ // 1. First the ValidationConfiguration constructor is called, and that loads the stored values.
// 2. Then this class's <init> method is called, and that initializes the "override" field
- // to the default,
- // which may be different than the stored value.
+ // to the default, which may be different than the stored value.
}
/**
@@ -54,7 +47,7 @@
* without persisting them (i.e., if the user presses Cancel then nothing needs to be done.)
*/
public GlobalConfiguration(GlobalConfiguration original) throws InvocationTargetException {
- super();
+ super(original.getResource());
original.copyTo(this);
}
@@ -74,7 +67,7 @@
_saveAutomatically = save;
}
- public void resetToDefault() throws InvocationTargetException {
+ public void resetToDefault() throws InvocationTargetException {
setDisableAllValidation(getDisableValidationDefault());
setEnabledValidators(getEnabledValidatorsDefault());
setEnabledManualValidators(getManualEnabledValidators());
@@ -84,17 +77,6 @@
setDefaultDelegates(getValidators());
}
- public void restoreDefaults() throws InvocationTargetException
- {
- ValidationPlugin plugin = ValidationPlugin.getPlugin();
- Preferences pluginPreferences = plugin.getPluginPreferences();
- deserialize(pluginPreferences.getDefaultString(USER_PREFERENCE));
- deserializeManual(pluginPreferences.getDefaultString(USER_MANUAL_PREFERENCE));
- deserializeBuild(pluginPreferences.getDefaultString(USER_BUILD_PREFERENCE));
- deserializeDelegates(pluginPreferences.getDefaultString(DELEGATES_PREFERENCE));
- }
-
-
/**
* This method exists only for migration purposes. The root marker must be deleted after
* migration is complete.
@@ -110,15 +92,9 @@
// job is done. Nothing to migrate.
return null;
- } catch (CoreException exc) {
+ } catch (CoreException e) {
// Can't find the IMarker? Assume it's deleted.
- Logger logger = ValidationPlugin.getPlugin().getMsgLogger();
- if (logger.isLoggingLevel(Level.SEVERE)) {
- LogEntry entry = ValidationPlugin.getLogEntry();
- entry.setSourceIdentifier("GlobalConfiguration.getMarker()"); //$NON-NLS-1$
- entry.setTargetException(exc);
- logger.write(Level.SEVERE, entry);
- }
+ ValidationPlugin.getPlugin().handleException(e);
return null;
}
}
@@ -138,7 +114,7 @@
IMarker rootMarker = marker[0]; // getMarker() has already checked that there's a marker
// in the array
- ValidatorMetaData[] enabledValidators = null;
+// ValidatorMetaData[] enabledValidators = null;
// String enabledValidatorsString = (String) getValue(rootMarker, ConfigurationConstants.ENABLED_VALIDATORS);
// if (enabledValidatorsString == null) {
// enabledValidators = ConfigurationConstants.DEFAULT_ENABLED_VALIDATORS;
@@ -151,18 +127,12 @@
setEnabledManualValidators(getStringAsEnabledElementsArray(enabledManualValidators));
String enabledBuildValidators = (String) getValue(rootMarker, ConfigurationConstants.ENABLED_BUILD_VALIDATORS);
setEnabledManualValidators(getStringAsEnabledElementsArray(enabledBuildValidators));
- if (enabledManualValidators.equals(null) || enabledBuildValidators.equals(null))
- enabledValidators = ConfigurationConstants.DEFAULT_ENABLED_VALIDATORS;
+// if (enabledManualValidators.equals(null) || enabledBuildValidators.equals(null))
+// enabledValidators = ConfigurationConstants.DEFAULT_ENABLED_VALIDATORS;
setCanProjectsOverride(getValue(rootMarker, ConfigurationConstants.PREF_PROJECTS_CAN_OVERRIDE, PREF_PROJECTS_CAN_OVERRIDE_DEFAULT));
root.getWorkspace().deleteMarkers(marker);
- } catch (CoreException exc) {
- Logger logger = ValidationPlugin.getPlugin().getMsgLogger();
- if (logger.isLoggingLevel(Level.SEVERE)) {
- LogEntry entry = ValidationPlugin.getLogEntry();
- entry.setSourceIdentifier("GlobalConfiguration.loadV50"); //$NON-NLS-1$
- entry.setTargetException(exc);
- logger.write(Level.SEVERE, entry);
- }
+ } catch (CoreException e) {
+ ValidationPlugin.getPlugin().handleException(e);
}
}
@@ -224,4 +194,4 @@
}
-}
\ No newline at end of file
+}
diff --git a/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/IProjectValidationHelper.java b/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/IProjectValidationHelper.java
index f22df4f..959988e 100644
--- a/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/IProjectValidationHelper.java
+++ b/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/IProjectValidationHelper.java
@@ -1,10 +1,10 @@
/*******************************************************************************
- * Copyright (c) 2001, 2004 IBM Corporation and others.
+ * Copyright (c) 2001, 2007 IBM Corporation 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:
* IBM Corporation - initial API and implementation
*******************************************************************************/
@@ -13,6 +13,9 @@
import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IProject;
+/**
+ * ValidatorHelper extensions must implement this interface.
+ */
public interface IProjectValidationHelper {
public IContainer[] getOutputContainers(IProject project);
diff --git a/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/InternalValidatorManager.java b/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/InternalValidatorManager.java
index 07d3845..5f9dba8 100644
--- a/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/InternalValidatorManager.java
+++ b/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/InternalValidatorManager.java
@@ -1,10 +1,10 @@
/*******************************************************************************
- * Copyright (c) 2001, 2004 IBM Corporation and others.
+ * Copyright (c) 2001, 2008 IBM Corporation 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:
* IBM Corporation - initial API and implementation
*******************************************************************************/
@@ -14,24 +14,18 @@
import java.lang.reflect.InvocationTargetException;
import java.util.Collection;
import java.util.HashSet;
-import java.util.Iterator;
import java.util.Set;
-import java.util.logging.Level;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.Path;
-import org.eclipse.jem.util.logger.LogEntry;
-import org.eclipse.jem.util.logger.proxy.Logger;
import org.eclipse.wst.validation.internal.core.Message;
import org.eclipse.wst.validation.internal.operations.WorkbenchReporter;
import org.eclipse.wst.validation.internal.plugin.ValidationPlugin;
import org.eclipse.wst.validation.internal.provisional.core.IMessage;
-/**
- */
public final class InternalValidatorManager {
private static InternalValidatorManager _inst = null;
private static final String OP_GROUP = "ValidationOperation"; //$NON-NLS-1$ // when the ValidationOperation
@@ -59,15 +53,11 @@
/**
* Return a new Set that contains all of the elements from the array.
*/
- public static Set wrapInSet(Object[] obj) {
- Set result = new HashSet();
- if ((obj == null) || (obj.length == 0)) {
- return result;
- }
+ public static Set<ValidatorMetaData> wrapInSet(ValidatorMetaData[] vmds) {
+ Set<ValidatorMetaData> result = new HashSet<ValidatorMetaData>();
+ if ((vmds == null) || (vmds.length == 0))return result;
- for (int i = 0; i < obj.length; i++) {
- result.add(obj[i]);
- }
+ for (ValidatorMetaData vmd : vmds)result.add(vmd);
return result;
}
@@ -113,11 +103,10 @@
* Return an array of the fully-qualified names of the validator classes.
*/
public String[] getValidatorNames(ValidatorMetaData[] vmds) {
- Set temp = new HashSet();
- for (int i = 0; i < vmds.length; i++) {
- String[] names = vmds[i].getValidatorNames();
- for (int j = 0; j < names.length; j++) {
- temp.add(names[j]);
+ Set<String> temp = new HashSet<String>();
+ for (ValidatorMetaData vmd : vmds) {
+ for (String name : vmd.getValidatorNames()) {
+ temp.add(name);
}
}
@@ -129,14 +118,11 @@
/**
* Return an array of the fully-qualified names of the validator classes.
*/
- public String[] getValidatorNames(Collection vmds) {
- Set temp = new HashSet();
- Iterator iterator = vmds.iterator();
- while (iterator.hasNext()) {
- ValidatorMetaData vmd = (ValidatorMetaData) iterator.next();
- String[] names = vmd.getValidatorNames();
- for (int j = 0; j < names.length; j++) {
- temp.add(names[j]);
+ public String[] getValidatorNames(Collection<ValidatorMetaData> vmds) {
+ Set<String> temp = new HashSet<String>();
+ for (ValidatorMetaData vmd : vmds) {
+ for (String name : vmd.getValidatorNames()) {
+ temp.add(name);
}
}
@@ -174,19 +160,10 @@
ValidatorMetaData[] result = new ValidatorMetaData[count];
System.arraycopy(temp, 0, result, 0, count);
return result;
- } catch (InvocationTargetException exc) {
- Logger logger = ValidationPlugin.getPlugin().getMsgLogger();
- if (logger.isLoggingLevel(Level.SEVERE)) {
- LogEntry entry = ValidationPlugin.getLogEntry();
- entry.setSourceIdentifier("InternalValidatorManager::getValidatorsForExtension(" + project.getName() + ", " + fileExtension + ")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- entry.setTargetException(exc);
- logger.write(Level.SEVERE, entry);
-
- if (exc.getTargetException() != null) {
- entry.setTargetException(exc);
- logger.write(Level.SEVERE, entry);
- }
- }
+ } catch (InvocationTargetException e) {
+ ValidationPlugin.getPlugin().handleException(e);
+ if (e.getTargetException() != null)
+ ValidationPlugin.getPlugin().handleException(e.getTargetException());
return new ValidatorMetaData[0];
}
}
@@ -203,4 +180,4 @@
}
return names;
}
-}
\ No newline at end of file
+}
diff --git a/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/ProjectConfiguration.java b/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/ProjectConfiguration.java
index 105d838..5f39ecf 100644
--- a/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/ProjectConfiguration.java
+++ b/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/ProjectConfiguration.java
@@ -1,42 +1,40 @@
/*******************************************************************************
- * Copyright (c) 2001, 2004 IBM Corporation and others.
+ * Copyright (c) 2001, 2009 IBM Corporation 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:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.wst.validation.internal;
import java.lang.reflect.InvocationTargetException;
+import java.util.HashSet;
import java.util.Map;
-import java.util.logging.Level;
+import java.util.Set;
+import java.util.StringTokenizer;
import org.eclipse.core.resources.IMarker;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.ProjectScope;
import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.preferences.IEclipsePreferences;
-import org.eclipse.core.runtime.preferences.IScopeContext;
-import org.eclipse.jem.util.logger.LogEntry;
-import org.eclipse.jem.util.logger.proxy.Logger;
import org.eclipse.wst.validation.internal.delegates.ValidatorDelegateDescriptor;
import org.eclipse.wst.validation.internal.plugin.ValidationPlugin;
import org.osgi.service.prefs.BackingStoreException;
-
/**
* This class represents the Project Preferences as set on the Project's Validation Properties page.
*/
public class ProjectConfiguration extends ValidationConfiguration {
- /* package */static final boolean PRJ_OVERRIDEGLOBAL_DEFAULT = false; // If the user has never
- // set
- // a preference before, this
- // is the override default
- // (on)
+
+ /** false - If the user has never set a preference before, this is the override default */
+ static final boolean PRJ_OVERRIDEGLOBAL_DEFAULT = false;
+
+ /** default_value - the configuration is using the defaults. */
+ private static final String DefaultValue = "default_value"; //$NON-NLS-1$
+
private boolean _doesProjectOverride = getDoesProjectOverrideDefault();
/**
@@ -47,22 +45,21 @@
// global list.
super(project, extractProjectValidators(convertToArray(ValidationRegistryReader.getReader().getAllValidators()), project));
- // Can't put the call to load() and passivate() in the ValidationConfiguration constructor
- // due
+ // Can't put the call to load() and passivate() in the ValidationConfiguration constructor due
// to the order of initialization.
- // 1. First the ValidationConfiguration constructor is called, and that loads the stored
- // values.
+ // 1. First the ValidationConfiguration constructor is called, and that loads the stored values.
// 2. Then this class's <init> method is called, and that initializes the "override" field
- // to the default,
- // which may be different than the stored value.
+ // to the default, which may be different than the stored value.
}
/**
* This constructor is provided only for the Properties page, so that the page can store values
* without persisting them (i.e., if the user presses Cancel then nothing needs to be done.)
+ *
+ * @deprecated
*/
public ProjectConfiguration(ProjectConfiguration original) throws InvocationTargetException {
- super();
+ super(original.getResource());
original.copyTo(this);
}
@@ -84,17 +81,15 @@
// If the project overrides, then don't use the global.
// If the project does not override, use the global.
return !_doesProjectOverride;
- } catch (InvocationTargetException exc) {
- Logger logger = ValidationPlugin.getPlugin().getMsgLogger();
- if (logger.isLoggingLevel(Level.SEVERE)) {
- LogEntry entry = ValidationPlugin.getLogEntry();
- entry.setSourceIdentifier("ProjectConfiguration.userGlobalPreference"); //$NON-NLS-1$
- entry.setTargetException(exc);
- logger.write(Level.SEVERE, entry);
- }
+ } catch (InvocationTargetException e) {
+ ValidationPlugin.getPlugin().handleException(e);
return false;
}
}
+
+ public boolean getDoesProjectOverride(){
+ return _doesProjectOverride;
+ }
public boolean doesProjectOverride() {
// If the global preference doesn't allow projects to override, it doesn't matter what the
@@ -152,11 +147,7 @@
return super.getValidators();
}
- /*
- * (non-Javadoc)
- * @see org.eclipse.wst.validation.internal.ValidationConfiguration#getDelegatingValidators()
- */
- public Map getDelegatingValidators() throws InvocationTargetException {
+ public Map<String,String> getDelegatingValidators() throws InvocationTargetException {
if (useGlobalPreference()) {
return ConfigurationManager.getManager().getGlobalConfiguration().getDelegatingValidators();
}
@@ -283,7 +274,7 @@
setEnabledManualValidators(gp.getManualEnabledValidators());
setEnabledBuildValidators(gp.getBuildEnabledValidators());
- setDelegatingValidators(gp.getDelegatingValidators());
+ setDelegatingValidators(gp.getDelegatingValidators());
// except for this field, which is unique to the project preferences
setDoesProjectOverride(getDoesProjectOverrideDefault());
@@ -294,12 +285,14 @@
GlobalConfiguration gp = ConfigurationManager.getManager().getGlobalConfiguration();
setEnabledManualValidators(gp.getManualEnabledValidators());
setEnabledBuildValidators(gp.getBuildEnabledValidators());
- setDelegatingValidators(gp.getDelegatingValidators());
+ setDelegatingValidators(gp.getDelegatingValidators());
}
/**
* The project's nature has changed, so recalculate the validators that are configured on the
* project, and reset the values of the project to the default.
+ *
+ * @deprecated this method doesn't do anything
*/
public void resetProjectNature() {
/*
@@ -333,15 +326,8 @@
}
// Job is done. Nothing to migrate.
return null;
- } catch (CoreException exc) {
- // Can't find the IMarker? Assume it's deleted.
- Logger logger = ValidationPlugin.getPlugin().getMsgLogger();
- if (logger.isLoggingLevel(Level.SEVERE)) {
- LogEntry entry = ValidationPlugin.getLogEntry();
- entry.setSourceIdentifier("ProjectConfiguration::getMarker"); //$NON-NLS-1$
- entry.setTargetException(exc);
- logger.write(Level.SEVERE, entry);
- }
+ } catch (CoreException e) {
+ ValidationPlugin.getPlugin().handleException(e);
return null;
}
}
@@ -364,7 +350,7 @@
IMarker prjMarker = marker[0]; // getProjectMarker() has already checked that there's a
// marker in the array
- GlobalConfiguration gp = ConfigurationManager.getManager().getGlobalConfiguration();
+// GlobalConfiguration gp = ConfigurationManager.getManager().getGlobalConfiguration();
// String enabledValStr = (String) getValue(prjMarker, ConfigurationConstants.ENABLED_VALIDATORS);
// ValidatorMetaData[] enabledVal = null;
@@ -379,10 +365,11 @@
ValidatorMetaData[] enabledBuildVal = null;
String enabledManualValStr = (String) getValue(prjMarker, ConfigurationConstants.ENABLED_MANUAL_VALIDATORS);
String enabledBuildValStr = (String) getValue(prjMarker, ConfigurationConstants.ENABLED_BUILD_VALIDATORS);
- ValidatorMetaData[] enabledVal = null;
- if (enabledManualValStr.equals(null) || enabledBuildValStr.equals(null)) {
- enabledVal = gp.getEnabledValidators();
- } else {
+// ValidatorMetaData[] enabledVal = null;
+// if (enabledManualValStr.equals(null) || enabledBuildValStr.equals(null)) {
+// enabledVal = gp.getEnabledValidators();
+// } else {
+ if (!enabledManualValStr.equals(null) && !enabledBuildValStr.equals(null)) {
enabledManaualVal = getStringAsEnabledElementsArray(enabledManualValStr);
setEnabledManualValidators(enabledManaualVal);
enabledBuildVal = getStringAsEnabledElementsArray(enabledManualValStr);
@@ -402,25 +389,12 @@
} else {
setDoesProjectOverride(boolVal.booleanValue());
}
- boolean override = doesProjectOverride();
getResource().getWorkspace().deleteMarkers(marker);
- } catch (CoreException exc) {
- Logger logger = ValidationPlugin.getPlugin().getMsgLogger();
- if (logger.isLoggingLevel(Level.SEVERE)) {
- LogEntry entry = ValidationPlugin.getLogEntry();
- entry.setSourceIdentifier("ProjectConfiguration.loadMarker "); //$NON-NLS-1$
- entry.setTargetException(exc);
- logger.write(Level.SEVERE, entry);
- }
- } catch (InvocationTargetException exc) {
- Logger logger = ValidationPlugin.getPlugin().getMsgLogger();
- if (logger.isLoggingLevel(Level.SEVERE)) {
- LogEntry entry = ValidationPlugin.getLogEntry();
- entry.setSourceIdentifier("ProjectConfiguration.loadMarker InvocationTargetException"); //$NON-NLS-1$
- entry.setTargetException(exc);
- logger.write(Level.SEVERE, entry);
- }
+ } catch (CoreException e) {
+ ValidationPlugin.getPlugin().handleException(e);
+ } catch (InvocationTargetException e) {
+ ValidationPlugin.getPlugin().handleException(e);
}
}
@@ -472,10 +446,7 @@
if (allow) {
// "allow" has changed, so see if the preference and the project validators match.
ValidatorMetaData[] projEnabledVmd = super.getEnabledValidators(); // bypass the check
- // for whether the
- // global preferences
- // are to be used or
- // not
+ // for whether the global preferences are to be used or not
GlobalConfiguration gp = ConfigurationManager.getManager().getGlobalConfiguration();
return gp.hasEnabledValidatorsChanged(projEnabledVmd);
}
@@ -483,14 +454,14 @@
return false;
}
- public boolean haveDelegatesChanged(Map oldDelegates, boolean allow) throws InvocationTargetException {
+ public boolean haveDelegatesChanged(Map<String, String> oldDelegates, boolean allow) throws InvocationTargetException {
if (super.haveDelegatesChanged(oldDelegates)) {
return true;
}
if (allow) {
- Map projDelegates = super.getDelegatingValidators();
+ Map<String, String> projDelegates = super.getDelegatingValidators();
GlobalConfiguration gp = ConfigurationManager.getManager().getGlobalConfiguration();
return gp.haveDelegatesChanged(projDelegates);
}
@@ -499,11 +470,8 @@
}
- /**
- * @see org.eclipse.wst.validation.internal.operations.internal.attribute.ValidationConfiguration#deserialize(String)
- */
public void deserialize(String storedConfiguration) throws InvocationTargetException {
- if (storedConfiguration == null || storedConfiguration.length() == 0 || storedConfiguration.equals("default_value")) {
+ if (storedConfiguration == null || storedConfiguration.length() == 0 || storedConfiguration.equals(DefaultValue)) {
resetToDefault();
} else if (storedConfiguration != null) {
int prjOverrideIndex = storedConfiguration.indexOf(ConfigurationConstants.PRJ_OVERRIDEGLOBAL);
@@ -513,7 +481,7 @@
String disableAllValidation = storedConfiguration.substring(disableAllValidationIndex + ConfigurationConstants.DISABLE_ALL_VALIDATION_SETTING.length(), versionIndex);
setDisableAllValidation(Boolean.valueOf(disableAllValidation).booleanValue());
} else {
- setDisableAllValidation(false);;
+ setDisableAllValidation(false);
}
// project doesn't override the global
if (disableAllValidationIndex != -1) {
@@ -523,9 +491,6 @@
}
}
- /**
- * @see org.eclipse.wst.validation.internal.operations.internal.attribute.ValidationConfiguration#serialize()
- */
public String serialize() throws InvocationTargetException {
StringBuffer buffer = new StringBuffer();
buffer.append(ConfigurationConstants.PRJ_OVERRIDEGLOBAL);
@@ -537,11 +502,6 @@
return buffer.toString();
}
- /*
- * (non-Javadoc)
- *
- * @see org.eclipse.wst.validation.internal.operations.internal.attribute.ValidationConfiguration#getEnabledFullBuildValidators(boolean)
- */
public ValidatorMetaData[] getEnabledFullBuildValidators(boolean fullBuild) throws InvocationTargetException {
if (useGlobalPreference()) {
return extractProjectValidators(ConfigurationManager.getManager().getGlobalConfiguration().getEnabledFullBuildValidators(fullBuild), getResource());
@@ -625,35 +585,75 @@
public void store() throws InvocationTargetException {
IProject project = (IProject) getResource();
- IScopeContext projectContext = new ProjectScope((IProject) getResource());
- final IEclipsePreferences pref = projectContext.getNode(ValidationPlugin.PLUGIN_ID);
+ final PreferencesWrapper pref = PreferencesWrapper.getPreferences(project, null);
if (pref != null) {
try {
- pref.put(USER_PREFERENCE, serialize());
- pref.put(USER_MANUAL_PREFERENCE, serializeManualSetting());
- pref.put(USER_BUILD_PREFERENCE, serializeBuildSetting());
- pref.put(DELEGATES_PREFERENCE, serializeDelegatesSetting());
+ pref.put(ValidationConfiguration.UserPreference, serialize());
+ pref.put(ValidationConfiguration.UserManualPreference, serializeManualSetting());
+ pref.put(ValidationConfiguration.UserBuildPreference, serializeBuildSetting());
+ pref.put(ValidationConfiguration.DelegatesPreference, serializeDelegatesSetting());
pref.flush();
- } catch (BackingStoreException bse) {
- Logger.getLogger().log(bse);
+ } catch (BackingStoreException e) {
+ // A common error is that the project has been closed, in which case there
+ // is nothing that we can do.
+ if (project.isAccessible())ValidationPlugin.getPlugin().handleException(e);
}
}
}
protected void loadPreference() throws InvocationTargetException {
IProject project = (IProject) getResource();
- IScopeContext projectContext = new ProjectScope(project);
- final IEclipsePreferences prefs = projectContext.getNode(ValidationPlugin.PLUGIN_ID);
- if (prefs != null) {
- String projectName = project.getName();
- String storedConfig = prefs.get(USER_PREFERENCE,"default_value");
+ final PreferencesWrapper prefs = PreferencesWrapper.getPreferences(project, null);
+ if (prefs.nodeExists()) {
+ String storedConfig = prefs.get(ValidationConfiguration.UserPreference, DefaultValue);
deserialize(storedConfig);
- String storedManualConfig = prefs.get(USER_MANUAL_PREFERENCE,"default_value");
+ String storedManualConfig = prefs.get(ValidationConfiguration.UserManualPreference, DefaultValue);
deserializeManual(storedManualConfig);
- String storedBuildConfig = prefs.get(USER_BUILD_PREFERENCE,"default_value");
+ String storedBuildConfig = prefs.get(ValidationConfiguration.UserBuildPreference, DefaultValue);
deserializeBuild(storedBuildConfig);
- String storedDelegatesConfiguration = prefs.get(DELEGATES_PREFERENCE,"default_value");
+ String storedDelegatesConfiguration = prefs.get(ValidationConfiguration.DelegatesPreference, DefaultValue);
deserializeDelegates(storedDelegatesConfiguration);
}
}
-}
\ No newline at end of file
+
+ /**
+ * Answer the validator id's that have been enabled for manual validation.
+ * @return null if they are all enabled
+ */
+ Set<String> getEnabledManualValidators(){
+ return getIds(ValidationConfiguration.UserManualPreference, ConfigurationConstants.ENABLED_MANUAL_VALIDATORS);
+ }
+
+ /**
+ * Answer the validator id's that have been enabled for build validation.
+ * @return null if they are all enabled
+ */
+ Set<String> getEnabledBuildlValidators(){
+ return getIds(ValidationConfiguration.UserBuildPreference, ConfigurationConstants.ENABLED_BUILD_VALIDATORS);
+ }
+
+ /**
+ * A helper method to extract some validator id's from a preference store field.
+ *
+ * @return null if all the validators are enabled.
+ */
+ private Set<String> getIds(String prefKey, String enabledPhrase){
+ IProject project = (IProject) getResource();
+ final PreferencesWrapper prefs = PreferencesWrapper.getPreferences(project, null);
+ if (prefs == null)return null;
+
+ String storedConfig = prefs.get(prefKey, DefaultValue);
+ if (storedConfig == null || storedConfig.length() == 0 || storedConfig.equals(DefaultValue))return null;
+ int validationIndex = storedConfig.indexOf(enabledPhrase);
+
+ String ids = storedConfig.substring(validationIndex + enabledPhrase.length(),storedConfig.length());
+
+ StringTokenizer tokenizer = new StringTokenizer(ids, ConfigurationConstants.ELEMENT_SEPARATOR);
+ Set<String> set = new HashSet<String>(20);
+ while (tokenizer.hasMoreTokens())set.add(tokenizer.nextToken());
+ if (set.size() == 0)return null;
+
+ return set;
+
+ }
+}
diff --git a/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/ReferencialFileValidatorExtension.java b/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/ReferencialFileValidatorExtension.java
index 9927fd4..d638d0a 100644
--- a/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/ReferencialFileValidatorExtension.java
+++ b/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/ReferencialFileValidatorExtension.java
@@ -1,10 +1,10 @@
/*******************************************************************************
- * Copyright (c) 2001, 2004 IBM Corporation and others.
+ * Copyright (c) 2001, 2008 IBM Corporation 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:
* IBM Corporation - initial API and implementation
*******************************************************************************/
@@ -17,28 +17,30 @@
package org.eclipse.wst.validation.internal;
import org.eclipse.core.runtime.IConfigurationElement;
-import org.eclipse.jem.util.logger.proxy.Logger;
import org.eclipse.wst.validation.internal.operations.ReferencialFileValidator;
+import org.eclipse.wst.validation.internal.plugin.ValidationPlugin;
/**
* @author vijayb
- *
- * To change the template for this generated type comment go to Window - Preferences - Java - Code
- * Generation - Code and Comments
*/
public class ReferencialFileValidatorExtension {
private String id = null;
private ReferencialFileValidator instance;
private boolean errorCondition = false;
private IConfigurationElement element;
+
+ /** referencialFileValidator */
public static final String REF_FILE_VALIDATOR_EXTENSION = "referencialFileValidator"; //$NON-NLS-1$
+
+ /** run */
public static final String RUN = "run"; //$NON-NLS-1$
+
+ /** id */
public static final String ATT_ID = "id"; //$NON-NLS-1$
+
+ /** class */
public static final String ATT_CLASS = "class"; //$NON-NLS-1$
- /**
- *
- */
public ReferencialFileValidatorExtension() {
super();
}
@@ -46,9 +48,9 @@
public ReferencialFileValidator getInstance() {
try {
if (instance == null && !errorCondition)
- instance = (ReferencialFileValidator) element.createExecutableExtension("run"); //$NON-NLS-1$
- } catch (Throwable e) {
- Logger.getLogger().logError(e);
+ instance = (ReferencialFileValidator) element.createExecutableExtension(RUN);
+ } catch (Exception e) {
+ ValidationPlugin.getPlugin().handleException(e);
errorCondition = true;
}
return instance;
@@ -83,4 +85,4 @@
public void setId(String id) {
this.id = id;
}
-}
\ No newline at end of file
+}
diff --git a/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/ReferencialFileValidatorRegistryReader.java b/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/ReferencialFileValidatorRegistryReader.java
index 59f803a..c9233ef 100644
--- a/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/ReferencialFileValidatorRegistryReader.java
+++ b/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/ReferencialFileValidatorRegistryReader.java
@@ -1,10 +1,10 @@
/*******************************************************************************
- * Copyright (c) 2001, 2004 IBM Corporation and others.
+ * Copyright (c) 2001, 2008 IBM Corporation 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:
* IBM Corporation - initial API and implementation
*******************************************************************************/
@@ -17,32 +17,60 @@
package org.eclipse.wst.validation.internal;
import java.util.ArrayList;
-import java.util.Iterator;
import java.util.List;
import org.eclipse.core.runtime.IConfigurationElement;
-import org.eclipse.jem.util.RegistryReader;
+import org.eclipse.core.runtime.IExtension;
+import org.eclipse.core.runtime.IExtensionPoint;
+import org.eclipse.core.runtime.IStatus;
+import org.eclipse.core.runtime.Platform;
import org.eclipse.wst.validation.internal.operations.ReferencialFileValidator;
import org.eclipse.wst.validation.internal.plugin.ValidationPlugin;
/**
* @author vijayb
- *
- * To change the template for this generated type comment go to Window - Preferences - Java - Code
- * Generation - Code and Comments
*/
-public class ReferencialFileValidatorRegistryReader extends RegistryReader {
- static ReferencialFileValidatorRegistryReader instance = null;
- protected List referencialFileValidationExtensions;
+public class ReferencialFileValidatorRegistryReader {
+ static ReferencialFileValidatorRegistryReader instance;
+
+ private static final String Id = "id"; //$NON-NLS-1$
+ private static final String ExtensionPoint = "referencialFileValidator"; //$NON-NLS-1$
+
+ protected List<ReferencialFileValidatorExtension> referencialFileValidationExtensions;
- /**
- * @param arg0
- * @param arg1
- * @param arg2
- */
public ReferencialFileValidatorRegistryReader() {
- super(ValidationPlugin.PLUGIN_ID, "referencialFileValidator"); //$NON-NLS-1$
}
+
+ /**
+ * Read the extension point and parse it.
+ */
+ public void readRegistry() {
+ IExtensionPoint point = Platform.getExtensionRegistry().getExtensionPoint(Id, ExtensionPoint);
+ if (point == null)return;
+ IConfigurationElement[] elements = point.getConfigurationElements();
+ for (int i = 0; i < elements.length; i++) {
+ internalReadElement(elements[i]);
+ }
+ }
+
+ private void internalReadElement(IConfigurationElement element) {
+ boolean recognized = this.readElement(element);
+ if (!recognized) {
+ logError(element, "Error processing extension: " + element); //$NON-NLS-1$
+ }
+ }
+
+ /*
+ * Logs the error in the desktop log using the provided text and the information in the configuration element.
+ */
+ protected void logError(IConfigurationElement element, String text) {
+ IExtension extension = element.getDeclaringExtension();
+ StringBuffer buf = new StringBuffer();
+ buf.append("Plugin " + extension.getContributor().getName() + ", extension " + extension.getExtensionPointUniqueIdentifier()); //$NON-NLS-1$ //$NON-NLS-2$
+ buf.append("\n" + text); //$NON-NLS-1$
+ ValidationPlugin.getPlugin().logMessage(IStatus.ERROR, buf.toString());
+ }
+
/*
* (non-Javadoc)
@@ -60,19 +88,15 @@
/**
* Sets the extension point.
*
- * @param extensions
+ * @param newExtension
* The extensions to set
*/
protected void addExtension(IConfigurationElement newExtension) {
- //add to the list of post validator extesions only if the ext is not added yet
+ //add to the list of post validator extensions only if the extension is not added yet
boolean containsExt = true;
- List extensions = getReferencialFileValidationExtensions();
- Iterator it = extensions.iterator();
- while(it.hasNext()) {
- ReferencialFileValidatorExtension ext = (ReferencialFileValidatorExtension)it.next();
- if(!ext.getElement().getAttribute("id").equals(newExtension.getAttribute("id")))
- containsExt = false;
+ for(ReferencialFileValidatorExtension ext : getReferencialFileValidationExtensions()) {
+ if(!ext.getElement().getAttribute(Id).equals(newExtension.getAttribute(Id)))containsExt = false;
}
if(!containsExt ||getReferencialFileValidationExtensions().isEmpty())
getReferencialFileValidationExtensions().add(new ReferencialFileValidatorExtension(newExtension));
@@ -83,12 +107,12 @@
/**
* Sets the extension point.
*
- * @param extensions
+ * @param newExtension
* The extensions to set
*/
protected void addExtensionPoint(ReferencialFileValidatorExtension newExtension) {
if (referencialFileValidationExtensions == null)
- referencialFileValidationExtensions = new ArrayList();
+ referencialFileValidationExtensions = new ArrayList<ReferencialFileValidatorExtension>();
referencialFileValidationExtensions.add(newExtension);
}
@@ -97,18 +121,14 @@
* available and enabled
*/
public ReferencialFileValidator getReferencialFileValidator() {
- ReferencialFileValidatorExtension refFileValExt;
- for (Iterator refFileValItr = getReferencialFileValidationExtensions().iterator(); refFileValItr.hasNext();) {
- refFileValExt = (ReferencialFileValidatorExtension) refFileValItr.next();
+ for (ReferencialFileValidatorExtension refFileValExt: getReferencialFileValidationExtensions()) {
return refFileValExt.getInstance();
}
return null;
}
/**
- * Gets the instance.
- *
- * @return Returns a EJBCodegenHandlerExtensionReader
+ * Gets the singleton instance.
*/
public static ReferencialFileValidatorRegistryReader getInstance() {
if (instance == null) {
@@ -121,10 +141,10 @@
/**
* @return Returns the handlerExtensions.
*/
- protected List getReferencialFileValidationExtensions() {
+ protected List<ReferencialFileValidatorExtension> getReferencialFileValidationExtensions() {
if (referencialFileValidationExtensions == null)
- referencialFileValidationExtensions = new ArrayList();
+ referencialFileValidationExtensions = new ArrayList<ReferencialFileValidatorExtension>();
return referencialFileValidationExtensions;
}
-}
\ No newline at end of file
+}
diff --git a/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/RegistryConstants.java b/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/RegistryConstants.java
index ee6e106..81a78b4 100644
--- a/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/RegistryConstants.java
+++ b/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/RegistryConstants.java
@@ -1,10 +1,10 @@
/*******************************************************************************
- * Copyright (c) 2001, 2004 IBM Corporation and others.
+ * Copyright (c) 2001, 2007 IBM Corporation 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:
* IBM Corporation - initial API and implementation
*******************************************************************************/
@@ -19,55 +19,122 @@
* Validation constants needed to declare an extension point, and to implement an extension.
*/
public interface RegistryConstants {
- public static final String PLUGIN_ID = ValidationPlugin.PLUGIN_ID;
- public static final String VALIDATOR_EXT_PT_ID = "validator"; //$NON-NLS-1$ // extension point declaration of the validator
+ String PLUGIN_ID = ValidationPlugin.PLUGIN_ID;
+
+ /** validator - extension point declaration of the validator */
+ String VALIDATOR_EXT_PT_ID = "validator"; //$NON-NLS-1$
- /* package */static final String TAG_RUN_CLASS = "run"; //$NON-NLS-1$ // identifies the Validator class
- /* package */static final String TAG_FILTER = "filter"; //$NON-NLS-1$ // identifies a filter -- type and/or name -- used to filter out resources which are not to be validated. (i.e., if the resource doesn't pass this filter test, don't validate it.)
- /* package */static final String TAG_HELPER_CLASS = "helper"; //$NON-NLS-1$ // IValidationContext which loads the MOF model for the IValidator
- /* package */static final String TAG_PROJECT_NATURE = "projectNature"; //$NON-NLS-1$ // identifies the projects which the validator should run on
- /* package */static final String TAG_AGGREGATE_VALIDATORS = "aggregateValidator"; //$NON-NLS-1$ // identifies a validator(s) which this validator aggregates. This value is used to remove all messages owned by a particular validator. Aggregate validators cannot be shared. Only one validator may use an aggregate of that type.
+ /** run - identifies the Validator class */
+ String TAG_RUN_CLASS = "run"; //$NON-NLS-1$
+
+ /**
+ * filter - identifies a filter -- type and/or name -- used to filter out resources which are
+ * not to be validated. (i.e., if the resource doesn't pass this filter test, don't validate it.)
+ */
+ String TAG_FILTER = "filter"; //$NON-NLS-1$
+
+ /**
+ * identifies a filter -- type and/or name -- used to filter out resources which are not to be validated. (i.e., if the resource doesn't pass this filter test, don't validate it.)
+ */
+ String TAG_CONTENTTYPE = "contentTypeBinding"; //$NON-NLS-1$
+
+ /**
+ * identifies a type
+ */
+ String ATT_CONTENTTYPEID = "contentTypeId"; //$NON-NLS-1$
+ /** helper - IValidationContext which loads the MOF model for the IValidator */
+ String TAG_HELPER_CLASS = "helper"; //$NON-NLS-1$
+
+ /** projectNature - identifies the projects which the validator should run on */
+ String TAG_PROJECT_NATURE = "projectNature"; //$NON-NLS-1$
+
+ /**
+ * aggregateValidator - identifies a validator(s) which this validator aggregates. This value is used
+ * to remove all messages owned by a particular validator. Aggregate validators cannot be shared.
+ * only one validator may use an aggregate of that type. */
+ String TAG_AGGREGATE_VALIDATORS = "aggregateValidator"; //$NON-NLS-1$
- /* package */static final String ATT_OBJECT_CLASS = "objectClass"; //$NON-NLS-1$ // identifies a type
- /* package */static final String ATT_NAME_FILTER = "nameFilter"; //$NON-NLS-1$ // identifies a name (may include the '*' wildcard anywhere in the name)
- /* package */static final String ATT_ID = "id"; //$NON-NLS-1$ // identifies a unique id to filter on
- /* package */static final String ATT_CLASS = "class"; //$NON-NLS-1$ // identifies a class name of a tag, e.g. "helper class", or "run class"
- /* package */static final String ATT_ACTION_FILTER = "action"; //$NON-NLS-1$ // identifies the incremental validation actions for which a resource should be filtered in
- /* package */static final String ATT_INCREMENTAL = "incremental"; //$NON-NLS-1$ // identifies whether or not the validator supports incremental build validation. Default is true (i.e., incremental builds are supported).
- /* package */static final boolean ATT_INCREMENTAL_DEFAULT = true; // The incremental default.
- /* package */static final String ATT_FULLBUILD = "fullBuild"; //$NON-NLS-1$ // identifies whether or not the validator supports full build validation. Default is true (i.e., full build validation is supported).
- /* package */static final boolean ATT_FULLBUILD_DEFAULT = true; // The build default.
- /* package */static final String ATT_ENABLED = "enabled"; //$NON-NLS-1$ // identifies whether or not the validator is enabled by default. Default is "true" (enabled).
- /* package */static final boolean ATT_ENABLED_DEFAULT = true; // The "enabled" default.
- /* package */static final String ATT_INCLUDE = "include"; //$NON-NLS-1$ // Include projects with this nature
- /* package */static final boolean ATT_INCLUDE_DEFAULT = true; // By default, if "include" is not
- // specified in the projectNature
- // element, then assume that the
- // nature is included.
- /* package */static final String ATT_RULE_GROUP = "ruleGroup"; //$NON-NLS-1$ // identifies the different validation passes which this validator recognizes. The values are identified in IRuleGroup.
- /* package */static final int ATT_RULE_GROUP_DEFAULT = IRuleGroup.PASS_FAST; // the default pass
- // includes only the
- // FAST PASS. FULL
- // can be invoked
- // only explicitly by
- // an operation.
- /* package */static final String ATT_CASE_SENSITIVE = "caseSensitive"; //$NON-NLS-1$
- /* package */static final String ATT_ASYNC = "async"; //$NON-NLS-1$ // Is the validator thread-safe?
- /* package */static final boolean ATT_ASYNC_DEFAULT = false; // The "can validator run
- // asynchronously" default. Initially
- // set to false, but in future this
- // will be changed to true.
+ /** objectClass - identifies a type */
+ String ATT_OBJECT_CLASS = "objectClass"; //$NON-NLS-1$
+
+ /** nameFilter - identifies a name (may include the '*' wildcard anywhere in the name) */
+ String ATT_NAME_FILTER = "nameFilter"; //$NON-NLS-1$
+
+ /** id - identifies a unique id to filter on */
+ String ATT_ID = "id"; //$NON-NLS-1$
+
+ /** class - identifies a class name of a tag, e.g. "helper class", or "run class" */
+ String ATT_CLASS = "class"; //$NON-NLS-1$
+
+ /** action - identifies the incremental validation actions for which a resource should be filtered in */
+ String ATT_ACTION_FILTER = "action"; //$NON-NLS-1$
+
+ /**
+ * incremental - identifies whether or not the validator supports incremental build validation.
+ * Default is true (i.e., incremental builds are supported).
+ */
+ String ATT_INCREMENTAL = "incremental"; //$NON-NLS-1$
+
+ /** true - The incremental default. */
+ boolean ATT_INCREMENTAL_DEFAULT = true;
+
+ /**
+ * fullBuild - identifies whether or not the validator supports full build validation.
+ * Default is true (i.e., full build validation is supported).
+ */
+ String ATT_FULLBUILD = "fullBuild"; //$NON-NLS-1$
+
+ /** true - The build default. */
+ boolean ATT_FULLBUILD_DEFAULT = true;
+
+ /** enabled - identifies whether or not the validator is enabled by default. Default is "true" (enabled). */
+ String ATT_ENABLED = "enabled"; //$NON-NLS-1$
+
+ /** true - The "enabled" default. */
+ boolean ATT_ENABLED_DEFAULT = true;
+
+ /** include - Include projects with this nature */
+ String ATT_INCLUDE = "include"; //$NON-NLS-1$
+
+ /**
+ * true - By default, if "include" is not specified in the projectNature element,
+ * then assume that the nature is included. */
+ boolean ATT_INCLUDE_DEFAULT = true;
+
+ /**
+ * ruleGroup - identifies the different validation passes which this validator recognizes.
+ * The values are identified in IRuleGroup.
+ */
+ String ATT_RULE_GROUP = "ruleGroup"; //$NON-NLS-1$
+
+ /** the default pass includes only the FAST PASS. FULL can be invoked only explicitly by an operation. */
+ int ATT_RULE_GROUP_DEFAULT = IRuleGroup.PASS_FAST;
+
+ /** caseSensitive */
+ String ATT_CASE_SENSITIVE = "caseSensitive"; //$NON-NLS-1$
+
+ /** async - Is the validator thread-safe? */
+ String ATT_ASYNC = "async"; //$NON-NLS-1$
+
+ /** false - The "can validator run asynchronously" default. In the future this may be changed to true. */
+ boolean ATT_ASYNC_DEFAULT = false;
-
- /* package */static final String TAG_MIGRATE = "migrate"; //$NON-NLS-1$ // the "migrate" section of the validator
- /* package */static final String TAG_VALIDATOR = "validator"; //$NON-NLS-1$ // the "validator" element of the "migrate" section
- /* package */static final String ATT_FROM = "from"; //$NON-NLS-1$ // the fully-qualified class name of the former validator class
- /* package */static final String ATT_TO = "to"; //$NON-NLS-1$ // the fully-qualified class name of the current validator class
- static final String DEP_VALIDATOR = "dependentValidator"; //$NON-NLS-1$
- static final String DEP_VAL_VALUE = "depValValue"; //$NON-NLS-1$
- static final String MARKER_ID = "markerId"; //$NON-NLS-1$
- static final String MARKER_ID_VALUE = "markerIdValue"; //$NON-NLS-1$
- static final boolean DEP_VAL_VALUE_DEFAULT = false;
- static final String FACET = "facet"; //$NON-NLS-1$
- static final String FACET_ID ="facetId"; //$NON-NLS-1$
-}
\ No newline at end of file
+ /** migrate - the "migrate" section of the validator */
+ String TAG_MIGRATE = "migrate"; //$NON-NLS-1$
+
+ /** validator - the "validator" element of the "migrate" section */
+ String TAG_VALIDATOR = "validator"; //$NON-NLS-1$
+
+ /** from - the fully-qualified class name of the former validator class */
+ String ATT_FROM = "from"; //$NON-NLS-1$
+
+ /** to - the fully-qualified class name of the current validator class */
+ String ATT_TO = "to"; //$NON-NLS-1$
+ String DEP_VALIDATOR = "dependentValidator"; //$NON-NLS-1$
+ String DEP_VAL_VALUE = "depValValue"; //$NON-NLS-1$
+ String MARKER_ID = "markerId"; //$NON-NLS-1$
+ String MARKER_ID_VALUE = "markerIdValue"; //$NON-NLS-1$
+ boolean DEP_VAL_VALUE_DEFAULT = false;
+ String FACET = "facet"; //$NON-NLS-1$
+ String FACET_ID ="facetId"; //$NON-NLS-1$
+}
diff --git a/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/ResourceConstants.java b/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/ResourceConstants.java
index 515768e..62f8a08 100644
--- a/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/ResourceConstants.java
+++ b/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/ResourceConstants.java
@@ -1,10 +1,10 @@
/*******************************************************************************
- * Copyright (c) 2001, 2004 IBM Corporation and others.
+ * Copyright (c) 2001, 2008 IBM Corporation 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:
* IBM Corporation - initial API and implementation
*******************************************************************************/
@@ -13,111 +13,107 @@
/**
- * Constants used to access the string resources associated with the plugin.
+ * Constants used to access the string resources associated with the plug-in.
*
* See the plugin.properties file, in the plugin's directory, for the contents of the strings.
*/
public interface ResourceConstants {
// A marker cannot be added to the task list.
- public static final String VBF_EXC_CANNOT_ADD_MARKER = "VBF_EXC_CANNOT_ADD_MARKER"; //$NON-NLS-1$
+ String VBF_EXC_CANNOT_ADD_MARKER = "VBF_EXC_CANNOT_ADD_MARKER"; //$NON-NLS-1$
// A marker cannot be removed from the task list.
- public static final String VBF_EXC_CANNOT_REMOVE_MARKER = "VBF_EXC_CANNOT_REMOVE_MARKER"; //$NON-NLS-1$
+ String VBF_EXC_CANNOT_REMOVE_MARKER = "VBF_EXC_CANNOT_REMOVE_MARKER"; //$NON-NLS-1$
// Internal error has occurred.
- public static final String VBF_EXC_INTERNAL = "VBF_EXC_INTERNAL"; //$NON-NLS-1$
+ String VBF_EXC_INTERNAL = "VBF_EXC_INTERNAL"; //$NON-NLS-1$
// If the validator cannot be loaded because it didn't specify a helper
- public static final String VBF_EXC_HELPER_MISSING = "VBF_EXC_HELPER_MISSING"; //$NON-NLS-1$
+ String VBF_EXC_HELPER_MISSING = "VBF_EXC_HELPER_MISSING"; //$NON-NLS-1$
// If the validator cannot be loaded because its helper cannot be loaded
- public static final String VBF_EXC_HELPER_CANNOTLOAD = "VBF_EXC_HELPER_CANNOTLOAD"; //$NON-NLS-1$
+ String VBF_EXC_HELPER_CANNOTLOAD = "VBF_EXC_HELPER_CANNOTLOAD"; //$NON-NLS-1$
- // A java.lang.Runtime error has occured during the build.
- public static final String VBF_EXC_RUNTIME = "VBF_EXC_RUNTIME"; //$NON-NLS-1$
+ // A java.lang.Runtime error has occurred during the build.
+ String VBF_EXC_RUNTIME = "VBF_EXC_RUNTIME"; //$NON-NLS-1$
// If the "Validator" extension point has been removed from the plugin.xml file.
- public static final String VBF_EXC_MISSING_VALIDATOR_EP = "VBF_EXC_MISSING_VALIDATOR_EP"; //$NON-NLS-1$
+ String VBF_EXC_MISSING_VALIDATOR_EP = "VBF_EXC_MISSING_VALIDATOR_EP"; //$NON-NLS-1$
// If the user has specified an invalid type filter in their plugin.xml file.
// i.e., it isn't an instance of IResource.
- public static final String VBF_EXC_INVALID_TYPE_FILTER = "VBF_EXC_INVALID_TYPE_FILTER"; //$NON-NLS-1$
+ String VBF_EXC_INVALID_TYPE_FILTER = "VBF_EXC_INVALID_TYPE_FILTER"; //$NON-NLS-1$
// The validator extension has made a mistake in its plugin.xml's projectNature tag
- public static final String VBF_EXC_MISSING_PROJECTNATURE_ID = "VBF_EXC_MISSING_PROJECTNATURE_ID"; //$NON-NLS-1$
+ String VBF_EXC_MISSING_PROJECTNATURE_ID = "VBF_EXC_MISSING_PROJECTNATURE_ID"; //$NON-NLS-1$
// The validator extension has made a mistake in its plugin.xml's syntax.
- public static final String VBF_EXC_VALIDATORNAME_IS_NULL = "VBF_EXC_VALIDATORNAME_IS_NULL"; //$NON-NLS-1$
+ String VBF_EXC_VALIDATORNAME_IS_NULL = "VBF_EXC_VALIDATORNAME_IS_NULL"; //$NON-NLS-1$
// Title for the IProgressMonitor.
- public static final String VBF_STATUS_PROGRESSMONITOR_TITLE = "VBF_STATUS_PROGRESSMONITOR_TITLE"; //$NON-NLS-1$
+ String VBF_STATUS_PROGRESSMONITOR_TITLE = "VBF_STATUS_PROGRESSMONITOR_TITLE"; //$NON-NLS-1$
// Status line for the IProgressMonitor
- public static final String VBF_STATUS_INITIALIZING = "VBF_STATUS_INITIALIZING"; //$NON-NLS-1$
+ String VBF_STATUS_INITIALIZING = "VBF_STATUS_INITIALIZING"; //$NON-NLS-1$
// If the user has cancelled validation, each validator might have cleanup to do. This message
// is shown to tell the user which validator is being cleaned up at the moment.
- public static final String VBF_STATUS_VALIDATOR_CLEANUP = "VBF_STATUS_VALIDATOR_CLEANUP"; //$NON-NLS-1$
+ String VBF_STATUS_VALIDATOR_CLEANUP = "VBF_STATUS_VALIDATOR_CLEANUP"; //$NON-NLS-1$
// If the user cancelled validation, remove all of the validator's tasks from the task list, and
// put an entry saying that validation on {project} using {validator} was cancelled.
- public static final String VBF_STATUS_VALIDATOR_TERMINATED = "VBF_STATUS_VALIDATOR_TERMINATED"; //$NON-NLS-1$
+ String VBF_STATUS_VALIDATOR_TERMINATED = "VBF_STATUS_VALIDATOR_TERMINATED"; //$NON-NLS-1$
// Before a validator is begun, this message informs the user that validation, using a
// particular validator, has begun
- public static final String VBF_STATUS_STARTING_VALIDATION = "VBF_STATUS_STARTING_VALIDATION"; //$NON-NLS-1$
+ String VBF_STATUS_STARTING_VALIDATION = "VBF_STATUS_STARTING_VALIDATION"; //$NON-NLS-1$
- // After a validator is finished, this message informs the user that validtaion, using a
+ // After a validator is finished, this message informs the user that validation, using a
// particular validator, has completed.
- public static final String VBF_STATUS_ENDING_VALIDATION = "VBF_STATUS_ENDING_VALIDATION"; //$NON-NLS-1$
+ String VBF_STATUS_ENDING_VALIDATION = "VBF_STATUS_ENDING_VALIDATION"; //$NON-NLS-1$
// If a validator throws an unchecked exception, this message is displayed to the user.
- public static final String VBF_STATUS_ENDING_VALIDATION_ABNORMALLY = "VBF_STATUS_ENDING_VALIDATION_ABNORMALLY"; //$NON-NLS-1$
+ String VBF_STATUS_ENDING_VALIDATION_ABNORMALLY = "VBF_STATUS_ENDING_VALIDATION_ABNORMALLY"; //$NON-NLS-1$
// If the build's getDelta(getProject()) method returns null, let the user know that a full
// validation will be performed because there's no delta information.
- public static final String VBF_STATUS_NULL_DELTA = "VBF_STATUS_NULL_DELTA"; //$NON-NLS-1$
+ String VBF_STATUS_NULL_DELTA = "VBF_STATUS_NULL_DELTA"; //$NON-NLS-1$
- public static final String VBF_EXC_SYNTAX_NULL_NAME = "VBF_EXC_SYNTAX_NULL_NAME"; //$NON-NLS-1$
- public static final String VBF_EXC_SYNTAX_NO_HELPER = "VBF_EXC_SYNTAX_NO_HELPER"; //$NON-NLS-1$
- public static final String VBF_EXC_SYNTAX_NO_HELPER_CLASS = "VBF_EXC_SYNTAX_NO_HELPER_CLASS"; //$NON-NLS-1$
- public static final String VBF_EXC_SYNTAX_NO_HELPER_THROWABLE = "VBF_EXC_SYNTAX_NO_HELPER_THROWABLE"; //$NON-NLS-1$
- public static final String VBF_EXC_SYNTAX_NO_VAL_RUN = "VBF_EXC_SYNTAX_NO_VAL_RUN"; //$NON-NLS-1$
- public static final String VBF_EXC_SYNTAX_NO_VAL_CLASS = "VBF_EXC_SYNTAX_NO_VAL_CLASS"; //$NON-NLS-1$
- public static final String VBF_EXC_SYNTAX_NO_VAL_THROWABLE = "VBF_EXC_SYNTAX_NO_VAL_THROWABLE"; //$NON-NLS-1$
- public static final String VBF_EXC_SYNTAX_NO_VAL_NULL = "VBF_EXC_SYNTAX_NO_VAL_NULL"; //$NON-NLS-1$
- public static final String VBF_EXC_INVALID_RESOURCE = "VBF_EXC_INVALID_RESOURCE"; //$NON-NLS-1$
+ String VBF_EXC_SYNTAX_NO_HELPER = "VBF_EXC_SYNTAX_NO_HELPER"; //$NON-NLS-1$
+ String VBF_EXC_SYNTAX_NO_HELPER_CLASS = "VBF_EXC_SYNTAX_NO_HELPER_CLASS"; //$NON-NLS-1$
+ String VBF_EXC_SYNTAX_NO_HELPER_THROWABLE = "VBF_EXC_SYNTAX_NO_HELPER_THROWABLE"; //$NON-NLS-1$
+ String VBF_EXC_SYNTAX_NO_VAL_THROWABLE = "VBF_EXC_SYNTAX_NO_VAL_THROWABLE"; //$NON-NLS-1$
+ String VBF_EXC_INVALID_RESOURCE = "VBF_EXC_INVALID_RESOURCE"; //$NON-NLS-1$
- public static final String VBF_EXC_NULLCREATE = "VBF_EXC_NULLCREATE"; //$NON-NLS-1$
- public static final String VBF_EXC_NULLSAVE = "VBF_EXC_NULLSAVE"; //$NON-NLS-1$
- public static final String VBF_EXC_SAVE = "VBF_EXC_SAVE"; //$NON-NLS-1$
- public static final String VBF_EXC_NULLRETRIEVE = "VBF_EXC_NULLRETRIEVE"; //$NON-NLS-1$
- public static final String VBF_EXC_RETRIEVE = "VBF_EXC_RETRIEVE"; //$NON-NLS-1$
+ String VBF_EXC_NULLCREATE = "VBF_EXC_NULLCREATE"; //$NON-NLS-1$
+ String VBF_EXC_NULLSAVE = "VBF_EXC_NULLSAVE"; //$NON-NLS-1$
+ String VBF_EXC_SAVE = "VBF_EXC_SAVE"; //$NON-NLS-1$
+ String VBF_EXC_NULLRETRIEVE = "VBF_EXC_NULLRETRIEVE"; //$NON-NLS-1$
+ String VBF_EXC_RETRIEVE = "VBF_EXC_RETRIEVE"; //$NON-NLS-1$
- public static final String VBF_EXC_BADVMD = "VBF_EXC_BADVMD"; //$NON-NLS-1$
- public static final String VBF_EXC_OPENPRJ = "VBF_EXC_OPENPRJ"; //$NON-NLS-1$
- public static final String VBF_EXC_EXISTPRJ = "VBF_EXC_EXISTPRJ"; //$NON-NLS-1$
- public static final String VBF_EXC_BADPRJ = "VBF_EXC_BADPRJ"; //$NON-NLS-1$
- public static final String VBF_EXC_MULTIPRJ = "VBF_EXC_MULTIPRJ"; //$NON-NLS-1$
- public static final String VBF_EXC_BADVAL = "VBF_EXC_BADVAL"; //$NON-NLS-1$
+ String VBF_EXC_BADVMD = "VBF_EXC_BADVMD"; //$NON-NLS-1$
+ String VBF_EXC_OPENPRJ = "VBF_EXC_OPENPRJ"; //$NON-NLS-1$
+ String VBF_EXC_EXISTPRJ = "VBF_EXC_EXISTPRJ"; //$NON-NLS-1$
+ String VBF_EXC_BADPRJ = "VBF_EXC_BADPRJ"; //$NON-NLS-1$
+ String VBF_EXC_MULTIPRJ = "VBF_EXC_MULTIPRJ"; //$NON-NLS-1$
+ String VBF_EXC_BADVAL = "VBF_EXC_BADVAL"; //$NON-NLS-1$
- public static final String VBF_STATUS_START_REMOVING_OLD_MESSAGES = "VBF_STATUS_START_REMOVING_OLD_MESSAGES"; //$NON-NLS-1$
- public static final String VBF_STATUS_FINISH_REMOVING_OLD_MESSAGES = "VBF_STATUS_FINISH_REMOVING_OLD_MESSAGES"; //$NON-NLS-1$
+ String VBF_STATUS_START_REMOVING_OLD_MESSAGES = "VBF_STATUS_START_REMOVING_OLD_MESSAGES"; //$NON-NLS-1$
+ String VBF_STATUS_FINISH_REMOVING_OLD_MESSAGES = "VBF_STATUS_FINISH_REMOVING_OLD_MESSAGES"; //$NON-NLS-1$
- public static final String VBF_TASK_WARN_MESSAGE_LIMIT_VAL = "VBF_TASK_WARN_MESSAGE_LIMIT_VAL"; //$NON-NLS-1$
+ String VBF_TASK_WARN_MESSAGE_LIMIT_VAL = "VBF_TASK_WARN_MESSAGE_LIMIT_VAL"; //$NON-NLS-1$
- public static final String VBF_VALIDATION_JOB_MSG = "VBF_VALIDATION_JOB_MSG"; //$NON-NLS-1$
+ String VBF_VALIDATION_JOB_MSG = "VBF_VALIDATION_JOB_MSG"; //$NON-NLS-1$
- public static final String VBF_EXC_DISABLEV = "VBF_EXC_DISABLEV"; //$NON-NLS-1$
- public static final String VBF_EXC_DISABLEH = "VBF_EXC_DISABLEH"; //$NON-NLS-1$
- public static final String VBF_EXC_ORPHAN_IVALIDATOR = "VBF_EXC_ORPHAN_IVALIDATOR"; //$NON-NLS-1$
+ String VBF_EXC_DISABLEV = "VBF_EXC_DISABLEV"; //$NON-NLS-1$
+ String VBF_EXC_DISABLEH = "VBF_EXC_DISABLEH"; //$NON-NLS-1$
+ String VBF_EXC_ORPHAN_IVALIDATOR = "VBF_EXC_ORPHAN_IVALIDATOR"; //$NON-NLS-1$
- public static final String VBF_STATUS_LOOKING = "VBF_STATUS_LOOKING"; //$NON-NLS-1$
- public static final String VBF_STATUS_LOOKINGDONE = "VBF_STATUS_LOOKINGDONE"; //$NON-NLS-1$
- public static final String VBF_STATUS_REMOVING = "VBF_STATUS_REMOVING"; //$NON-NLS-1$
- public static final String VBF_STATUS_REMOVINGDONE = "VBF_STATUS_REMOVINGDONE"; //$NON-NLS-1$
+ String VBF_STATUS_LOOKING = "VBF_STATUS_LOOKING"; //$NON-NLS-1$
+ String VBF_STATUS_LOOKINGDONE = "VBF_STATUS_LOOKINGDONE"; //$NON-NLS-1$
+ String VBF_STATUS_REMOVING = "VBF_STATUS_REMOVING"; //$NON-NLS-1$
+ String VBF_STATUS_REMOVINGDONE = "VBF_STATUS_REMOVINGDONE"; //$NON-NLS-1$
- public static final String VBF_WRONG_CONTEXT_FOR_DELEGATE = "VBF_WRONG_CONTEXT_FOR_DELEGATE"; //$NON-NLS-1$
- public static final String VBF_NO_DELEGATE = "VBF_NO_DELEGATE"; //$NON-NLS-1$
- public static final String VBF_CANNOT_INSTANTIATE_DELEGATE = "VBF_CANNOT_INSTANTIATE_DELEGATE"; //$NON-NLS-1$
-}
\ No newline at end of file
+ String VBF_WRONG_CONTEXT_FOR_DELEGATE = "VBF_WRONG_CONTEXT_FOR_DELEGATE"; //$NON-NLS-1$
+ String VBF_NO_DELEGATE = "VBF_NO_DELEGATE"; //$NON-NLS-1$
+ String VBF_CANNOT_INSTANTIATE_DELEGATE = "VBF_CANNOT_INSTANTIATE_DELEGATE"; //$NON-NLS-1$
+}
diff --git a/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/ResourceHandler.java b/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/ResourceHandler.java
index 0cf1cd4..c3d2f7e 100644
--- a/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/ResourceHandler.java
+++ b/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/ResourceHandler.java
@@ -1,10 +1,10 @@
/*******************************************************************************
- * Copyright (c) 2001, 2004 IBM Corporation and others.
+ * Copyright (c) 2001, 2008 IBM Corporation 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:
* IBM Corporation - initial API and implementation
*******************************************************************************/
@@ -12,17 +12,12 @@
import java.util.MissingResourceException;
import java.util.ResourceBundle;
-import java.util.logging.Level;
-import org.eclipse.jem.util.logger.LogEntry;
-import org.eclipse.jem.util.logger.proxy.Logger;
import org.eclipse.wst.validation.internal.plugin.ValidationPlugin;
/**
* This class retrieves the Strings from the .properties file appropriate for the machine's Locale.
- *
- *
*/
public class ResourceHandler {
//TODO Make this class final once the public ResourceHandler has been deleted.
@@ -39,16 +34,11 @@
public static ResourceBundle getBundle() {
if (_bundle == null) {
try {
- _bundle = ResourceBundle.getBundle(ValidationPlugin.getBundleName());
+ _bundle = ResourceBundle.getBundle(ValidationPlugin.getBundlePropertyFileName());
} catch (MissingResourceException exc) {
_bundle = null;
- Logger logger = ValidationPlugin.getPlugin().getMsgLogger();
- if (logger.isLoggingLevel(Level.FINE)) {
- LogEntry entry = ValidationPlugin.getLogEntry();
- entry.setSourceID("org.eclipse.wst.validation.internal.operations.internal.ResourceHandler.getBundle()"); //$NON-NLS-1$
- entry.setText("Cannot find bundle " + ValidationPlugin.getBundleName()); //$NON-NLS-1$
- entry.setTargetException(exc);
- logger.write(Level.FINE, entry);
+ if (Tracing.isLogging()) {
+ Tracing.log("ResourceHandler-01", "Cannot find bundle " + ValidationPlugin.getBundlePropertyFileName()); //$NON-NLS-1$ //$NON-NLS-2$
}
}
}
@@ -59,26 +49,13 @@
try {
ResourceBundle bundle = getBundle();
if (bundle == null) {
- Logger logger = ValidationPlugin.getPlugin().getMsgLogger();
- if (logger.isLoggingLevel(Level.FINE)) {
- LogEntry entry = ValidationPlugin.getLogEntry();
- entry.setSourceID("org.eclipse.wst.validation.internal.operations.internal.ResourceHandler.getExternalizedMessage(String)"); //$NON-NLS-1$
- entry.setText("Resource bundle is null"); //$NON-NLS-1$
- logger.write(Level.FINE, entry);
- }
+ Tracing.log("ResourceHandler-02: ", "Resource bundle is null"); //$NON-NLS-1$ //$NON-NLS-2$
return key;
}
return bundle.getString(key);
} catch (NullPointerException exc) {
- Logger logger = ValidationPlugin.getPlugin().getMsgLogger();
- if (logger.isLoggingLevel(Level.FINE)) {
- LogEntry entry = ValidationPlugin.getLogEntry();
- entry.setSourceID("org.eclipse.wst.validation.internal.operations.ui.ResourceHandler.getExternalizedMessage(String)"); //$NON-NLS-1$
- entry.setText("Cannot find message id " + key); //$NON-NLS-1$
- entry.setTargetException(exc);
- logger.write(Level.FINE, entry);
- }
+ Tracing.log("ResourceHandler-03: ", "Cannot find message id ", key); //$NON-NLS-1$ //$NON-NLS-2$
}
return key;
}
@@ -86,26 +63,14 @@
public static String getExternalizedMessage(String key, String[] parms) {
String res = ""; //$NON-NLS-1$
try {
- res = java.text.MessageFormat.format(getExternalizedMessage(key), parms);
+ res = java.text.MessageFormat.format(getExternalizedMessage(key), (Object[])parms);
} catch (MissingResourceException exc) {
- Logger logger = ValidationPlugin.getPlugin().getMsgLogger();
- if (logger.isLoggingLevel(Level.FINE)) {
- LogEntry entry = ValidationPlugin.getLogEntry();
- entry.setSourceID("org.eclipse.wst.validation.internal.operations.internal.ResourceHandler.getExternalizedMessage(String, String[])"); //$NON-NLS-1$
- entry.setText("Cannot find message id " + key); //$NON-NLS-1$
- entry.setTargetException(exc);
- logger.write(Level.FINE, entry);
- }
+ Tracing.log("ResourceHandler-04: ", "Cannot find message id ", key); //$NON-NLS-1$ //$NON-NLS-2$
} catch (NullPointerException exc) {
- Logger logger = ValidationPlugin.getPlugin().getMsgLogger();
- if (logger.isLoggingLevel(Level.FINE)) {
- LogEntry entry = ValidationPlugin.getLogEntry();
- entry.setSourceID("org.eclipse.wst.validation.internal.operations.internal.ResourceHandler.getExternalizedMessage(String, String[])"); //$NON-NLS-1$
- entry.setText("Cannot format message id " + key + " with " + parms.length + " parameters."); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- entry.setTargetException(exc);
- logger.write(Level.FINE, entry);
+ if (Tracing.isLogging()) {
+ Tracing.log("ResourceHandler-05: Cannot format message id " + key + " with " + parms.length + " parameters."); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
}
}
return res;
}
-}
\ No newline at end of file
+}
diff --git a/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/TaskListUtility.java b/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/TaskListUtility.java
index cdbf991..1cae3c1 100644
--- a/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/TaskListUtility.java
+++ b/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/TaskListUtility.java
@@ -1,17 +1,16 @@
/*******************************************************************************
- * Copyright (c) 2001, 2004 IBM Corporation and others.
+ * Copyright (c) 2001, 2008 IBM Corporation 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:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.wst.validation.internal;
import java.util.Map;
-import java.util.logging.Level;
import org.eclipse.core.resources.IMarker;
import org.eclipse.core.resources.IProject;
@@ -19,8 +18,6 @@
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
-import org.eclipse.jem.util.logger.LogEntry;
-import org.eclipse.jem.util.logger.proxy.Logger;
import org.eclipse.wst.validation.internal.plugin.ValidationPlugin;
import org.eclipse.wst.validation.internal.provisional.core.IMessage;
@@ -48,6 +45,7 @@
* This method is here for use by the SABER validator's reporter instance ONLY. Do not use. See
* defect 260144 for details.
*/
+ @SuppressWarnings("unchecked")
public static IMarker setPriority(IMarker item, int priority) throws CoreException {
Map attrib = item.getAttributes();
attrib.put(IMarker.PRIORITY, new Integer(priority));
@@ -58,8 +56,11 @@
/**
* This method adds a message to a resource in the task list.
*/
- public static IMarker addTask(String pluginId, IResource resource, String location, String messageId, String message, int markerType, String markerName, String targetObjectName, String groupName, int offset, int length) throws CoreException {
- if ((message == null) || (resource == null)) {
+ public static IMarker addTask(String pluginId, IResource resource, String location,
+ String messageId, String message, int markerType, String markerName, String targetObjectName,
+ String groupName, int offset, int length) throws CoreException {
+
+ if ((message == null) || (resource == null) || (!resource.exists())) {
return null;
}
@@ -75,6 +76,7 @@
// in more than one place, and also to clear out any old messages which are not cleared
// by the validation framework.
IMarker item = null;
+ MarkerManager.getDefault().hook(resource);
if(markerName != null && markerName.length() >0 )
item = resource.createMarker(markerName); // add a validation marker
else
@@ -141,80 +143,12 @@
/**
* This method adds a message to a resource in the task list.
*/
- public static IMarker addTask(String pluginId, IResource resource, String location, String messageId, String message, int markerType, String targetObjectName, String groupName, int offset, int length) throws CoreException {
- if ((message == null) || (resource == null)) {
- return null;
- }
-
- int severity = getSeverity(markerType);
-
- // Allow duplicate entries in the task list.
- // Prior to a full validation, the validation framework will remove all messages owned
- // by a validator before it is executed.
- // Prior to an incremental validation, the validation framework will remove all messages,
- // on each of the changed resources, owned by a validator before it is invoked.
- //
- // It is up to the validator to make sure that it is not adding the same message
- // in more than one place, and also to clear out any old messages which are not cleared
- // by the validation framework.
- IMarker item = resource.createMarker(VALIDATION_MARKER); // add a validation marker
-
- // For performance reasons, replace the multiple setAttribute
- // calls above with a single setAttributes call.
- boolean offsetSet = ((offset != IMessage.OFFSET_UNSET) && (length != IMessage.OFFSET_UNSET));
- int size = (offsetSet) ? 10 : 8; // add CHAR_START, CHAR_END only if the offset is set. If
- // the offset is set, it takes precendence over the line
- // number. (eclipse's rule, not mine.)
- String[] attribNames = new String[size];
- Object[] attribValues = new Object[size];
-
- // Very first thing, add the owner. That way, if the code dies
- // before things are persisted, hopefully this marker will be persisted.
- // Hopefully, eclipse WILL persist this field, as requested.
- attribNames[0] = VALIDATION_MARKER_OWNER;
- attribValues[0] = pluginId;
- attribNames[1] = VALIDATION_MARKER_SEVERITY; // this validation severity is stored, in
- // addition to the marker severity, to enable
- // more than one severity of message to be
- // displayed. e.g. ERROR | WARNING (using
- // binary OR). The IMarker constants are
- // regular decimal constants.
- attribValues[1] = new Integer(markerType);
- attribNames[2] = VALIDATION_MARKER_TARGETOBJECT; // to distinguish between messages which
- // are registered on an IResource, but
- // against different target objects
- attribValues[2] = ((targetObjectName == null) ? "" : targetObjectName); //$NON-NLS-1$
- attribNames[3] = VALIDATION_MARKER_GROUP;
- attribValues[3] = ((groupName == null) ? "" : groupName); //$NON-NLS-1$
- attribNames[4] = IMarker.MESSAGE;
- attribValues[4] = message;
- attribNames[5] = VALIDATION_MARKER_MESSAGEID;
- attribValues[5] = messageId;
-
- attribNames[6] = IMarker.SEVERITY; // IMarker.SEVERITY_ERROR, IMarker.SEVERITY_WARNING,
- // IMarker.SEVERITY_INFO
- attribValues[6] = new Integer(severity);
- try {
- // If the location is a line number, store it as a line number
- Integer lineNumber = Integer.valueOf(location);
- attribNames[7] = IMarker.LINE_NUMBER;
- attribValues[7] = lineNumber;
- } catch (NumberFormatException exc) {
- // Otherwise, store it as a text location
- attribNames[7] = IMarker.LOCATION;
- attribValues[7] = location;
- }
-
- if (offsetSet) {
- attribNames[8] = IMarker.CHAR_START;
- attribValues[8] = new Integer(offset);
- attribNames[9] = IMarker.CHAR_END;
- attribValues[9] = new Integer(offset + length);
- }
-
- item.setAttributes(attribNames, attribValues);
-
- return item;
+ public static IMarker addTask(String pluginId, IResource resource, String location,
+ String messageId, String message, int markerType, String targetObjectName,
+ String groupName, int offset, int length) throws CoreException {
+
+ return addTask(pluginId, resource, location, messageId,
+ message, markerType, null, targetObjectName, groupName, offset, length);
}
/**
@@ -282,14 +216,8 @@
}
return ((String) owner).equals(ownerId);
- } catch (CoreException exc) {
- Logger logger = ValidationPlugin.getPlugin().getMsgLogger();
- if (logger.isLoggingLevel(Level.SEVERE)) {
- LogEntry entry = ValidationPlugin.getLogEntry();
- entry.setSourceID("TaskListUtility.isOwner(IMarker, ownerId)"); //$NON-NLS-1$
- entry.setTargetException(exc);
- logger.write(Level.SEVERE, entry);
- }
+ } catch (CoreException e) {
+ ValidationPlugin.getPlugin().handleException(e);
return false;
}
}
@@ -297,75 +225,42 @@
private static IMarker[] getValidationTasks(IResource resource, int severity, int depth) {
IMarker[] tempMarkers = null;
int validCount = 0;
+ IMarker[] allMarkers = null;
try {
- IMarker[] allMarkers = null;
- try {
- allMarkers = resource.findMarkers(VALIDATION_MARKER, true, depth); // false means
- // only consider
- // PROBLEM_MARKER,
- // not variants
- // of
- // PROBLEM_MARKER.
- // Since addTask
- // only adds
- // PROBLEM_MARKER,
- // we don't need
- // to consider
- // its subtypes.
- } catch (CoreException exc) {
- Logger logger = ValidationPlugin.getPlugin().getMsgLogger();
- if (logger.isLoggingLevel(Level.SEVERE)) {
- LogEntry entry = ValidationPlugin.getLogEntry();
- entry.setSourceID("TaskListUtility.getValidationTasks(IResource, int)"); //$NON-NLS-1$
- entry.setTargetException(exc);
- logger.write(Level.SEVERE, entry);
- }
- return NO_MARKERS;
- }
+ allMarkers = resource.findMarkers(VALIDATION_MARKER, true, depth);
+ } catch (CoreException e) {
+ if (Tracing.isLogging())ValidationPlugin.getPlugin().handleException(e);
+ return NO_MARKERS;
+ }
- // Now filter in the markers, based on severity type.
- if (allMarkers.length != 0) {
- tempMarkers = new IMarker[allMarkers.length];
- for (int i = 0; i < allMarkers.length; i++) {
- IMarker marker = allMarkers[i];
- Integer filterSeverity = (Integer) marker.getAttribute(VALIDATION_MARKER_SEVERITY);
- if (filterSeverity == null) {
- // odd...marker wasn't created correctly. How could this happen?
- // Default to the current severity and add it to the list.
- try {
+ // Now filter in the markers, based on severity type.
+ if (allMarkers.length != 0) {
+ tempMarkers = new IMarker[allMarkers.length];
+ for (IMarker marker : allMarkers) {
+ Integer filterSeverity = null;
+ try {
+ filterSeverity = (Integer) marker.getAttribute(VALIDATION_MARKER_SEVERITY);
+ }
+ catch (CoreException e){
+ // Someone may have deleted the marker on us. All we can do is skip it.
+ continue;
+ }
+ if (filterSeverity == null) {
+ // odd...marker wasn't created correctly. How could this happen?
+ // Default to the current severity and add it to the list.
+ try {
+ // 226541 - I was seeing markers with valid severities being reset, so I added this
+ // additional test.
+ if (marker.getAttribute(IMarker.SEVERITY, -1) == -1)
marker.setAttribute(IMarker.SEVERITY, getSeverity(severity));
- } catch (CoreException exc) {
- Logger logger = ValidationPlugin.getPlugin().getMsgLogger();
- if (logger.isLoggingLevel(Level.SEVERE)) {
- LogEntry entry = ValidationPlugin.getLogEntry();
- entry.setSourceID("TaskListUtility.getValidationTasks(int, IResource, int)"); //$NON-NLS-1$
- entry.setTargetException(exc);
- logger.write(Level.SEVERE, entry);
- }
- continue;
- } catch (Throwable exc) {
- Logger logger = ValidationPlugin.getPlugin().getMsgLogger();
- if (logger.isLoggingLevel(Level.SEVERE)) {
- LogEntry entry = ValidationPlugin.getLogEntry();
- entry.setSourceID("TaskListUtility.getValidationTasks(int, IResource, int)"); //$NON-NLS-1$
- entry.setTargetException(exc);
- logger.write(Level.SEVERE, entry);
- }
- continue;
- }
- } else if ((severity & filterSeverity.intValue()) == 0) {
+ } catch (Exception e) {
+ ValidationPlugin.getPlugin().handleException(e);
continue;
}
- tempMarkers[validCount++] = marker;
+ } else if ((severity & filterSeverity.intValue()) == 0) {
+ continue;
}
- }
- } catch (CoreException exc) {
- Logger logger = ValidationPlugin.getPlugin().getMsgLogger();
- if (logger.isLoggingLevel(Level.SEVERE)) {
- LogEntry entry = ValidationPlugin.getLogEntry();
- entry.setSourceID("TaskListUtility.getValidationTasks(int, IResource, int)"); //$NON-NLS-1$
- entry.setTargetException(exc);
- logger.write(Level.SEVERE, entry);
+ tempMarkers[validCount++] = marker;
}
}
@@ -388,40 +283,32 @@
private static IMarker[] getValidationTasks(IResource resource, String[] messageOwners, int depth) {
IMarker[] markers = getValidationTasks(resource, IMessage.ALL_MESSAGES, depth);
- if (markers.length == 0) {
- return NO_MARKERS;
- }
+ if (markers.length == 0)return NO_MARKERS;
IMarker[] temp = new IMarker[markers.length];
int validCount = 0;
- for (int i = 0; i < markers.length; i++) {
- IMarker marker = markers[i];
-
+ for (IMarker marker : markers) {
+ Object owner = null;
try {
- Object owner = marker.getAttribute(VALIDATION_MARKER_OWNER);
- if ((owner == null) || !(owner instanceof String)) {
- // The ValidationMigrator will remove any "unowned" validation markers.
- continue;
- }
+ owner = marker.getAttribute(VALIDATION_MARKER_OWNER);
+ } catch (CoreException e) {
+ // eat it -- if it no longer exists there is nothing we can do about it
+ }
+
+ if ((owner == null) || !(owner instanceof String)) {
+ // The ValidationMigrator will remove any "unowned" validation markers.
+ continue;
+ }
- for (int j = 0; j < messageOwners.length; j++) {
- String messageOwner = messageOwners[j];
- if (((String) owner).equals(messageOwner)) {
- temp[validCount++] = marker;
- break;
- }
+ for (String messageOwner : messageOwners) {
+ if (((String) owner).equals(messageOwner)) {
+ temp[validCount++] = marker;
+ break;
}
- } catch (CoreException exc) {
- Logger logger = ValidationPlugin.getPlugin().getMsgLogger();
- if (logger.isLoggingLevel(Level.SEVERE)) {
- LogEntry entry = ValidationPlugin.getLogEntry();
- entry.setSourceID("TaskListUtility.getValidationTasks(project, String[])"); //$NON-NLS-1$
- entry.setTargetException(exc);
- logger.write(Level.SEVERE, entry);
- }
- return NO_MARKERS;
}
}
+
+ if (validCount == 0)return NO_MARKERS;
IMarker[] result = new IMarker[validCount];
System.arraycopy(temp, 0, result, 0, validCount);
@@ -487,15 +374,8 @@
try {
IMarker[] markers = getValidationTasks(resource, IMessage.ALL_MESSAGES);
ResourcesPlugin.getWorkspace().deleteMarkers(markers);
- } catch (CoreException exc) {
- // Couldn't remove the task from the task list for some reason...
- Logger logger = ValidationPlugin.getPlugin().getMsgLogger();
- if (logger.isLoggingLevel(Level.SEVERE)) {
- LogEntry entry = ValidationPlugin.getLogEntry();
- entry.setSourceID("WorkbenchMonitor.removeAllMessages(String[], IResource, String)"); //$NON-NLS-1$
- entry.setTargetException(exc);
- logger.write(Level.SEVERE, entry);
- }
+ } catch (CoreException e) {
+ ValidationPlugin.getPlugin().handleException(e);
}
}
@@ -568,4 +448,4 @@
marker.setAttribute(VALIDATION_MARKER_OWNER, to);
}
}
-}
\ No newline at end of file
+}
diff --git a/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/TimeEntry.java b/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/TimeEntry.java
deleted file mode 100644
index d63ed17..0000000
--- a/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/TimeEntry.java
+++ /dev/null
@@ -1,102 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2001, 2004 IBM Corporation 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.validation.internal;
-
-import org.eclipse.jem.util.logger.LogEntry;
-
-
-/**
- * This class should be used when logging "elapsed time" information and nothing else. Instead of
- * creating a new instance of this class every time it is needed, for performance reasons, create an
- * instance and reuse it. The text in this class is never translated.
- */
-public class TimeEntry extends LogEntry {
- private String _toolName = null;
- private String _details = null;
- private String _projectName = null;
- private String _sourceId = null;
- private int _executionMap = 0x0;
-
- public TimeEntry() {
- super();
- }
-
- /**
- * The name of the tool (e.g., a validator, a builder) whose time is measured.
- */
- public String getToolName() {
- return _toolName;
- }
-
- public void setToolName(String name) {
- _toolName = name;
- }
-
-
- /**
- * If there are any details that need to be recorded about the tool, such as what input it runs
- * on, this field stores the value. This field is optional.
- */
- public String getDetails() {
- return _details;
- }
-
- public void setDetails(String d) {
- _details = d;
- }
-
- /**
- * The name of the project on which the tool ran.
- */
- public String getProjectName() {
- return _projectName;
- }
-
- public void setProjectName(String name) {
- _projectName = name;
- }
-
- /**
- * The id of the code that launched the tool.
- */
- public String getSourceID() {
- return _sourceId;
- }
-
- public void setSourceID(String id) {
- _sourceId = id;
- }
-
- /**
- * If, in addition to elapsed time, the tool needs to track the execution path of a method, this
- * field stores the hexadecimal number that tracks the path. See ValidationBuilder::build for an
- * example that uses an execution path.
- */
- public int getExcecutionMap() {
- return _executionMap;
- }
-
- public void setExecutionMap(int map) {
- _executionMap = map;
- }
-
- /**
- * Clear all of the fields back to their initial setting so that this TimeEntry instance can be
- * reused.
- */
- public void reset() {
- _toolName = null;
- _details = null;
- _projectName = null;
- _sourceId = null;
- _executionMap = 0;
- }
-}
\ No newline at end of file
diff --git a/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/VThreadManager.java b/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/VThreadManager.java
index 05b3891..e9d9b7e 100644
--- a/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/VThreadManager.java
+++ b/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/VThreadManager.java
@@ -1,10 +1,10 @@
/*******************************************************************************
- * Copyright (c) 2001, 2004 IBM Corporation and others.
+ * Copyright (c) 2001, 2008 IBM Corporation 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:
* IBM Corporation - initial API and implementation
*******************************************************************************/
@@ -12,10 +12,8 @@
import java.util.Vector;
-import java.util.logging.Level;
-import org.eclipse.jem.util.logger.LogEntry;
-import org.eclipse.jem.util.logger.proxy.Logger;
+import org.eclipse.core.runtime.IStatus;
import org.eclipse.wst.validation.internal.plugin.ValidationPlugin;
@@ -45,13 +43,8 @@
try {
if (restart > MAX_NUM_OF_RESTART) {
// something has gone seriously, seriously wrong
- Logger logger = ValidationPlugin.getPlugin().getMsgLogger();
- if (logger.isLoggingLevel(Level.SEVERE)) {
- LogEntry entry = ValidationPlugin.getLogEntry();
- entry.setSourceID("VThreadManager::validationRunnable"); //$NON-NLS-1$
- entry.setText("restart = " + restart); //$NON-NLS-1$
- logger.write(Level.SEVERE, entry);
- }
+ String message = "restart = " + restart; //$NON-NLS-1$
+ ValidationPlugin.getPlugin().logMessage(IStatus.ERROR, message);
break;
}
@@ -63,20 +56,10 @@
job.run();
getJobs().setActive(false);
}
- } catch (Throwable exc) {
- // This exception is added as FINE instead of SEVERE because it's not
- // improbable
- // that an exception will be thrown
+ } catch (Exception e) {
restart++;
getJobs().setActive(false);
-
- Logger logger = ValidationPlugin.getPlugin().getMsgLogger();
- if (logger.isLoggingLevel(Level.FINE)) {
- LogEntry entry = ValidationPlugin.getLogEntry();
- entry.setSourceID("VThreadManager::validationRunnable"); //$NON-NLS-1$
- entry.setTargetException(exc);
- logger.write(Level.FINE, entry);
- }
+ ValidationPlugin.getPlugin().handleException(e);
} finally {
//do nothing
}
@@ -111,11 +94,11 @@
}
private class Jobs {
- private Vector __jobs = null; // The queued Runnables that need to be run.
- private boolean _isActive = false; // Is a job being run in the validation thread?
+ private Vector<Runnable> _queuedJobs; // The queued Runnables that need to be run.
+ private boolean _isActive; // Is a job being run in the validation thread?
public Jobs() {
- __jobs = new Vector();
+ _queuedJobs = new Vector<Runnable>();
}
public synchronized void queue(Runnable runnable) {
@@ -125,7 +108,7 @@
// instead of the last state of changes.
// Have to wait for the current Runnable to finish, so add this to the end of the queue
- __jobs.add(runnable);
+ _queuedJobs.add(runnable);
notifyAll();
}
@@ -133,7 +116,7 @@
* Pop the Runnable off of the head of the queue.
*/
synchronized Runnable dequeue() {
- while (__jobs.size() == 0) {
+ while (_queuedJobs.size() == 0) {
try {
wait();
} catch (InterruptedException exc) {
@@ -142,10 +125,10 @@
} // Block on the semaphore; break when a job has been added to the queue.
Runnable job = null;
- if (__jobs.size() > 0) {
- job = (Runnable) __jobs.get(0);
+ if (_queuedJobs.size() > 0) {
+ job = _queuedJobs.get(0);
if (job != null) {
- __jobs.remove(0);
+ _queuedJobs.remove(0);
}
}
return job;
@@ -163,7 +146,7 @@
* Return true if all of the Runnables have been run.
*/
public synchronized boolean isDone() {
- return ((__jobs.size() == 0) && !isActive());
+ return ((_queuedJobs.size() == 0) && !isActive());
}
}
-}
\ No newline at end of file
+}
diff --git a/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/ValidationConfiguration.java b/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/ValidationConfiguration.java
index a052d95..3ddb087 100644
--- a/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/ValidationConfiguration.java
+++ b/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/ValidationConfiguration.java
@@ -1,30 +1,24 @@
/*******************************************************************************
- * Copyright (c) 2001, 2004 IBM Corporation and others.
+ * Copyright (c) 2001, 2009 IBM Corporation 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:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.wst.validation.internal;
-import java.io.ByteArrayOutputStream;
-import java.io.IOException;
-import java.io.OutputStream;
import java.lang.reflect.InvocationTargetException;
-import java.util.ArrayList;
-import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
-import java.util.Iterator;
+import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.StringTokenizer;
-import java.util.logging.Level;
import org.eclipse.core.resources.IMarker;
import org.eclipse.core.resources.IResource;
@@ -34,12 +28,10 @@
import org.eclipse.core.runtime.Preferences;
import org.eclipse.core.runtime.Preferences.IPropertyChangeListener;
import org.eclipse.core.runtime.Preferences.PropertyChangeEvent;
-import org.eclipse.jem.util.logger.LogEntry;
-import org.eclipse.jem.util.logger.proxy.Logger;
import org.eclipse.wst.validation.internal.delegates.ValidatorDelegateDescriptor;
import org.eclipse.wst.validation.internal.delegates.ValidatorDelegatesRegistry;
import org.eclipse.wst.validation.internal.plugin.ValidationPlugin;
-
+import org.osgi.service.prefs.BackingStoreException;
/**
* This class represents the user's preference or project settings.
@@ -48,31 +40,43 @@
* property while the resource is open.
*/
public abstract class ValidationConfiguration implements IPropertyChangeListener {
- private IResource _resource = null;
- private boolean disableAllValidation = getDisableAllValidation();
- private String _version = null;
- private Map _validators = null; // Map of all validators (ValidatorMetaData) configured on the
- // project or installed globally. The value is a Boolean; TRUE
- // means that the VMD is enabled, FALSE means that the VMD is
- // disabled.
- protected HashMap manualValidators = null;
- protected HashMap buildValidators = null;
- protected String USER_PREFERENCE = "USER_PREFERENCE";
- protected String USER_MANUAL_PREFERENCE = "USER_MANUAL_PREFERENCE";
- protected String USER_BUILD_PREFERENCE = "USER_BUILD_PREFERENCE";
- protected String DELEGATES_PREFERENCE = "DELEGATES_PREFERENCE";
+ private final IResource _resource;
+ private boolean disableAllValidation = getDisableAllValidation();
+ private String _version;
- private Map _delegatesByTarget = null;
+ /**
+ * Map of all validators configured on the project or installed globally. The value of true
+ * means that the VMD is enabled, and a value of false means that the VMD is disabled.
+ */
+ private Map<ValidatorMetaData, Boolean> _validators = new HashMap<ValidatorMetaData, Boolean>();
+ protected Map<ValidatorMetaData, Boolean> manualValidators;
+ protected Map<ValidatorMetaData, Boolean> buildValidators;
+
+ protected static final String UserPreference = "USER_PREFERENCE"; //$NON-NLS-1$
+ protected static final String UserBuildPreference = "USER_BUILD_PREFERENCE"; //$NON-NLS-1$
+ protected static final String UserManualPreference = "USER_MANUAL_PREFERENCE"; //$NON-NLS-1$
+ protected static final String DelegatesPreference = "DELEGATES_PREFERENCE"; //$NON-NLS-1$
+
+ // GRK - I am keeping these "constants" in the off chance that they were used somewhere outside the framework
+ protected String USER_PREFERENCE = UserPreference;
+ protected String USER_MANUAL_PREFERENCE = UserManualPreference;
+ protected String USER_BUILD_PREFERENCE = UserBuildPreference;
+ protected String DELEGATES_PREFERENCE = DelegatesPreference;
+
+ /**
+ * The key is the target id, that is the id of the place holder validator. The value is the id
+ * of the real validator.
+ */
+ private Map<String, String> _delegatesByTarget = new HashMap<String, String>();
+
+ private static final String DefaultValue = "default_value"; //$NON-NLS-1$
- public static String getEnabledElementsAsString(Set elements) {
- if (elements == null) {
- return null;
- }
+ public static String getEnabledElementsAsString(Set<ValidatorMetaData> elements) {
+ if (elements == null)return null;
StringBuffer buffer = new StringBuffer();
- Iterator iterator = elements.iterator();
- while (iterator.hasNext()) {
- buffer.append(((ValidatorMetaData) iterator.next()).getValidatorUniqueName());
+ for (ValidatorMetaData vmd : elements) {
+ buffer.append(vmd.getValidatorUniqueName());
buffer.append(ConfigurationConstants.ELEMENT_SEPARATOR);
}
return buffer.toString();
@@ -82,36 +86,30 @@
return false;
}
- public static String getEnabledElementsAsString(Object[] elements) {
+ public static String getEnabledElementsAsString(ValidatorMetaData[] elements) {
StringBuffer buffer = new StringBuffer();
- for (int i = 0; i < elements.length; i++) {
- buffer.append(((ValidatorMetaData) elements[i]).getValidatorUniqueName());
+ for (ValidatorMetaData vmd : elements) {
+ buffer.append(vmd.getValidatorUniqueName());
buffer.append(ConfigurationConstants.ELEMENT_SEPARATOR);
}
return buffer.toString();
}
- public static Set getStringAsEnabledElements(String elements) {
- if (elements == null) {
- return null;
- }
+ public static Set<ValidatorMetaData> getStringAsEnabledElements(String elements) {
+ if (elements == null)return null;
- HashSet result = new HashSet();
+ Set<ValidatorMetaData> result = new HashSet<ValidatorMetaData>();
StringTokenizer tokenizer = new StringTokenizer(elements, ConfigurationConstants.ELEMENT_SEPARATOR);
while (tokenizer.hasMoreTokens()) {
String elem = tokenizer.nextToken();
ValidatorMetaData vmd = ValidationRegistryReader.getReader().getValidatorMetaData(elem);
- if (vmd != null) {
- result.add(vmd);
- }
+ if (vmd != null)result.add(vmd);
}
return result;
}
public static ValidatorMetaData[] getStringAsEnabledElementsArray(String elements) {
- if (elements == null) {
- return null;
- }
+ if (elements == null)return null;
StringTokenizer tokenizer = new StringTokenizer(elements, ConfigurationConstants.ELEMENT_SEPARATOR);
ValidatorMetaData[] result = new ValidatorMetaData[tokenizer.countTokens()];
@@ -119,9 +117,7 @@
while (tokenizer.hasMoreTokens()) {
String elem = tokenizer.nextToken();
ValidatorMetaData vmd = ValidationRegistryReader.getReader().getValidatorMetaData(elem);
- if (vmd != null) {
- result[count++] = vmd;
- }
+ if (vmd != null)result[count++] = vmd;
}
if (count != result.length) {
@@ -132,29 +128,47 @@
return result;
}
+
+ /**
+ * Answer the validators
+ * @return
+ */
+ public static Set<String> getValidatorIdsManual(){
+ PreferencesWrapper prefs = PreferencesWrapper.getPreferences(null, null);
+ String config = prefs.get(UserManualPreference, null);
+ return getValidatorIds(config);
+ }
+
+ public static Set<String> getValidatorIdsBuild(){
+ PreferencesWrapper prefs = PreferencesWrapper.getPreferences(null, null);
+ String config = prefs.get(UserBuildPreference, null);
+ return getValidatorIds(config);
+ }
+
+ private static Set<String> getValidatorIds(String elements){
+ Set<String> set = new HashSet<String>(50);
+ if (elements != null){
+ StringTokenizer tokenizer = new StringTokenizer(elements, ConfigurationConstants.ELEMENT_SEPARATOR);
+ while (tokenizer.hasMoreTokens())set.add(tokenizer.nextToken());
+ }
+ return set;
+ }
public static IWorkspaceRoot getRoot() {
return ResourcesPlugin.getWorkspace().getRoot();
}
-
- protected ValidationConfiguration() throws InvocationTargetException {
- _validators = new HashMap();
- _delegatesByTarget = new HashMap();
+
+ protected ValidationConfiguration(IResource resource){
+ _resource = resource;
}
protected ValidationConfiguration(IResource resource, ValidatorMetaData[] validators) throws InvocationTargetException {
- this();
-
if (resource == null) {
throw new InvocationTargetException(null, ResourceHandler.getExternalizedMessage(ResourceConstants.VBF_EXC_NULLCREATE));
}
- setResource(resource);
- setValidators(validators);
- }
-
- private void setResource(IResource resource) {
_resource = resource;
+ setValidators(validators);
}
public boolean isDisableAllValidation() throws InvocationTargetException {
@@ -191,17 +205,13 @@
ValidatorMetaData[] result = null;
if( !isDisableAllValidation() ){
- ValidatorMetaData[] temp = new ValidatorMetaData[numberOfValidators()];
- Iterator iterator = getBuildEnabledValidatorsMap().keySet().iterator();
-
-
- while (iterator.hasNext()) {
- ValidatorMetaData vmd = (ValidatorMetaData) iterator.next();
- Boolean bvalue = (Boolean)(getBuildEnabledValidatorsMap().get(vmd));
- if (bvalue.booleanValue() == true) {
+ Set<ValidatorMetaData> set = getBuildEnabledValidatorsMap().keySet();
+ ValidatorMetaData[] temp = new ValidatorMetaData[set.size()];
+ for (ValidatorMetaData vmd : set) {
+ Boolean bvalue = getBuildEnabledValidatorsMap().get(vmd);
+ if (bvalue) {
// If the validator is enabled
- if (vmd == null)
- continue;
+ if (vmd == null)continue;
if ( vmd.isBuildValidation() ) {
if (!onlyReferenced || vmd.isDependentValidator())
temp[count++] = vmd;
@@ -210,7 +220,8 @@
}
result = new ValidatorMetaData[count];
System.arraycopy(temp, 0, result, 0, count);
- }else{
+ }
+ else {
result = new ValidatorMetaData[0];
}
return result;
@@ -218,49 +229,69 @@
public void setEnabledValidators(ValidatorMetaData[] vmds) {
// First, "disable" all validators
- Map all = getValidatorMetaData();
- Iterator iterator = all.keySet().iterator();
- while (iterator.hasNext()) {
- ValidatorMetaData vmd = (ValidatorMetaData) iterator.next();
+ Map<ValidatorMetaData, Boolean> all = getValidatorMetaData();
+ for (ValidatorMetaData vmd : all.keySet()) {
all.put(vmd, Boolean.FALSE);
}
// Then enable only the validators in the array
- if ((vmds == null) || (vmds.length == 0)) {
- return;
- }
- for (int i = 0; i < vmds.length; i++) {
- all.put(vmds[i], Boolean.TRUE);
+ if ((vmds == null) || (vmds.length == 0))return;
+
+ for (ValidatorMetaData vmd : vmds) {
+ all.put(vmd, Boolean.TRUE);
}
}
public void setEnabledManualValidators(ValidatorMetaData[] vmds) throws InvocationTargetException {
- List manualEnabledVMDList = Arrays.asList(vmds);
- List allValidators = Arrays.asList(getValidators());
- for(int i = 0; i < allValidators.size(); i++) {
- ValidatorMetaData data = (ValidatorMetaData) allValidators.get(i);
- if(manualEnabledVMDList.contains(data))
- getManualEnabledValidatorsMap().put(data, new Boolean(true));
+ Set<ValidatorMetaData> manualEnabledVMDs = new HashSet<ValidatorMetaData>(vmds.length);
+ for (ValidatorMetaData vmd : vmds)manualEnabledVMDs.add(vmd);
+
+ for(ValidatorMetaData data : getValidators()) {
+ if(manualEnabledVMDs.contains(data))
+ getManualEnabledValidatorsMap().put(data, Boolean.TRUE);
else
- getManualEnabledValidatorsMap().put(data, new Boolean(false));
-
+ getManualEnabledValidatorsMap().put(data, Boolean.FALSE);
+ }
+ }
+
+ /**
+ * Update the list of validators that have been enabled for manual validation.
+ *
+ * @param vmds the validators that are enabled for manual validation.
+ * @throws InvocationTargetException
+ */
+ public void setEnabledManualValidators(Set<ValidatorMetaData> vmds) throws InvocationTargetException {
+ for(ValidatorMetaData data : getValidators()) {
+ if(vmds.contains(data))getManualEnabledValidatorsMap().put(data, Boolean.TRUE);
+ else getManualEnabledValidatorsMap().put(data, Boolean.FALSE);
}
}
public void setEnabledBuildValidators(ValidatorMetaData[] vmds) throws InvocationTargetException {
- List buildEnabledVMDList = Arrays.asList(vmds);
- List allValidators = Arrays.asList(getValidators());
- for(int i = 0; i < allValidators.size(); i++) {
- ValidatorMetaData data = (ValidatorMetaData) allValidators.get(i);
- if(buildEnabledVMDList.contains(data))
- getBuildEnabledValidatorsMap().put(data, new Boolean(true));
+ Set<ValidatorMetaData> buildEnabledVMDs = new HashSet<ValidatorMetaData>(vmds.length);
+ for (ValidatorMetaData vmd : vmds)buildEnabledVMDs.add(vmd);
+ for(ValidatorMetaData data : getValidators()) {
+ if(buildEnabledVMDs.contains(data))
+ getBuildEnabledValidatorsMap().put(data, Boolean.TRUE);
else
- getBuildEnabledValidatorsMap().put(data, new Boolean(false));
-
+ getBuildEnabledValidatorsMap().put(data, Boolean.FALSE);
+ }
+ }
+
+ /**
+ * Update the list of validators that have been enabled for build validation.
+ *
+ * @param vmds the validators that are enabled for build validation.
+ * @throws InvocationTargetException
+ */
+ public void setEnabledBuildValidators(Set<ValidatorMetaData> vmds) throws InvocationTargetException {
+ for(ValidatorMetaData data : getValidators()) {
+ if(vmds.contains(data))getBuildEnabledValidatorsMap().put(data, Boolean.TRUE);
+ else getBuildEnabledValidatorsMap().put(data, Boolean.FALSE);
}
}
- private Map getValidatorMetaData() {
+ private Map<ValidatorMetaData, Boolean> getValidatorMetaData() {
return _validators;
}
@@ -275,11 +306,9 @@
*/
private ValidatorMetaData[] getValidators(boolean value) throws InvocationTargetException {
ValidatorMetaData[] temp = new ValidatorMetaData[numberOfValidators()];
- Iterator iterator = getValidatorMetaData().keySet().iterator();
int count = 0;
- while (iterator.hasNext()) {
- ValidatorMetaData vmd = (ValidatorMetaData) iterator.next();
- Boolean bvalue = (Boolean) getValidatorMetaData().get(vmd);
+ for (ValidatorMetaData vmd : getValidatorMetaData().keySet()) {
+ Boolean bvalue = getValidatorMetaData().get(vmd);
if (bvalue.booleanValue() == value) {
temp[count++] = vmd;
}
@@ -291,50 +320,46 @@
}
public ValidatorMetaData[] getManualEnabledValidators() throws InvocationTargetException {
- HashMap map = getManualEnabledValidatorsMap();
- Set set = getManualEnabledValidatorsMap().keySet();
- if (!set.isEmpty()) {
- Iterator it = set.iterator();
- List enabledManualValidators = new ArrayList();
- while (it.hasNext()) {
- ValidatorMetaData data = (ValidatorMetaData) it.next();
- Boolean obj = (Boolean) map.get(data);
- if (obj != null && obj.booleanValue() == true) {
- enabledManualValidators.add(data);
- }
+ Map<ValidatorMetaData, Boolean> map = getManualEnabledValidatorsMap();
+ if (!map.isEmpty()) {
+ List<ValidatorMetaData> list = new LinkedList<ValidatorMetaData>();
+ for (Map.Entry<ValidatorMetaData, Boolean> me : map.entrySet()) {
+ Boolean obj = me.getValue();
+ if (obj != null && obj)list.add(me.getKey());
}
- return (ValidatorMetaData[]) enabledManualValidators.toArray(new ValidatorMetaData[enabledManualValidators.size()]);
+ return (ValidatorMetaData[]) list.toArray(new ValidatorMetaData[list.size()]);
}
return getEnabledValidators();
}
public ValidatorMetaData[] getBuildEnabledValidators() throws InvocationTargetException {
- HashMap map = getBuildEnabledValidatorsMap();
- Set set = getBuildEnabledValidatorsMap().keySet();
- Iterator it = set.iterator();
- List enabledBuildValidators = new ArrayList();
- if (!set.isEmpty()) {
- while (it.hasNext()) {
- ValidatorMetaData data = (ValidatorMetaData) it.next();
- Boolean obj = (Boolean) map.get(data);
- if (obj != null && obj.booleanValue() == true) {
- enabledBuildValidators.add(data);
- }
+ Map<ValidatorMetaData, Boolean> map = getBuildEnabledValidatorsMap();
+ List<ValidatorMetaData> list = new LinkedList<ValidatorMetaData>();
+ if (!map.isEmpty()) {
+ for (Map.Entry<ValidatorMetaData, Boolean> me : map.entrySet()) {
+ Boolean obj = me.getValue();
+ if (obj != null && obj)list.add(me.getKey());
}
- return (ValidatorMetaData[]) enabledBuildValidators.toArray(new ValidatorMetaData[enabledBuildValidators.size()]);
+ return (ValidatorMetaData[]) list.toArray(new ValidatorMetaData[list.size()]);
}
return getEnabledValidators();
}
- protected HashMap getBuildEnabledValidatorsMap() {
- if(buildValidators == null)
- buildValidators = new HashMap();
+ /**
+ * Answer the map of the validators that have been enabled for build validation,
+ * creating it if necessary.
+ */
+ protected Map<ValidatorMetaData, Boolean> getBuildEnabledValidatorsMap() {
+ if(buildValidators == null)buildValidators = new HashMap<ValidatorMetaData, Boolean>();
return buildValidators;
}
- protected HashMap getManualEnabledValidatorsMap() {
- if(manualValidators == null)
- manualValidators = new HashMap();
+ /**
+ * Answer the map of the validators that have been enabled for manual validation,
+ * creating it if necessary.
+ */
+ protected Map<ValidatorMetaData, Boolean> getManualEnabledValidatorsMap() {
+ if(manualValidators == null)manualValidators = new HashMap<ValidatorMetaData, Boolean>();
return manualValidators;
}
@@ -344,17 +369,10 @@
*/
public ValidatorMetaData[] getIncrementalValidators() throws InvocationTargetException {
ValidatorMetaData[] temp = new ValidatorMetaData[numberOfValidators()];
- Iterator iterator = getValidatorMetaData().keySet().iterator();
int count = 0;
- while (iterator.hasNext()) {
- ValidatorMetaData vmd = (ValidatorMetaData) iterator.next();
- Boolean bvalue = (Boolean) getValidatorMetaData().get(vmd);
- if (bvalue.booleanValue() == true) {
- // If the validator is enabled
- if (vmd.isIncremental()) {
- temp[count++] = vmd;
- }
- }
+ for (ValidatorMetaData vmd : getValidatorMetaData().keySet()) {
+ Boolean bvalue = getValidatorMetaData().get(vmd);
+ if (bvalue && vmd.isIncremental())temp[count++] = vmd;
}
ValidatorMetaData[] result = new ValidatorMetaData[count];
@@ -372,25 +390,20 @@
public void setValidators(ValidatorMetaData[] vmds) {
_validators.clear();
- for (int i = 0; i < vmds.length; i++) {
- if (vmds[i] == null)
- continue;
- _validators.put(vmds[i], (vmds[i].isEnabledByDefault() ? Boolean.TRUE : Boolean.FALSE));
+ for (ValidatorMetaData vmd : vmds) {
+ if (vmd == null)continue;
+ _validators.put(vmd, (vmd.isEnabledByDefault() ? Boolean.TRUE : Boolean.FALSE));
}
}
public void setDefaultDelegates(ValidatorMetaData[] vmds) throws InvocationTargetException {
_delegatesByTarget.clear();
- for (int i = 0; i < vmds.length; i++) {
- ValidatorMetaData vmd = vmds[i];
- if (vmd == null) {
- continue;
- }
+ for (ValidatorMetaData vmd : vmds) {
+ if (vmd == null)continue;
+
String targetID = vmd.getValidatorUniqueName();
String delegateID = ValidatorDelegatesRegistry.getInstance().getDefaultDelegate(targetID);
- if (delegateID == null) {
- continue;
- }
+ if (delegateID == null)continue;
_delegatesByTarget.put(targetID, ValidatorDelegatesRegistry.getInstance().getDefaultDelegate(targetID));
}
}
@@ -413,11 +426,8 @@
private static int numberOfIncrementalValidators(ValidatorMetaData[] vmds) {
int count = 0;
- for (int i = 0; i < vmds.length; i++) {
- ValidatorMetaData vmd = vmds[i];
- if (vmd.isIncremental()) {
- count++;
- }
+ for (ValidatorMetaData vmd : vmds) {
+ if (vmd.isIncremental())count++;
}
return count;
}
@@ -436,21 +446,11 @@
return getDisabledValidators().length;
}
- /*public int getMaximumNumberOfMessages() throws InvocationTargetException {
- return _maxMessages;
- }
-
- public void setMaximumNumberOfMessages(int max) {
- _maxMessages = max;
- }*/
-
/**
* The value returned from this method is guaranteed to be non-null.
*/
public final String getVersion() throws InvocationTargetException {
- if (_version == null) {
- loadVersion();
- }
+ if (_version == null)loadVersion();
return _version;
}
@@ -460,6 +460,7 @@
/**
* This preference has been migrated; change the version to the current version.
+ * @deprecated dead code.
*/
public void markVersionCurrent() {
// The version should not be marked current until the migration is complete
@@ -493,14 +494,10 @@
* Return true if the validator is enabled on this preference.
*/
public boolean isEnabled(ValidatorMetaData vmd) throws InvocationTargetException {
- if (vmd == null) {
- return false;
- }
+ if (vmd == null)return false;
- Boolean value = (Boolean) getValidatorMetaData().get(vmd);
- if (value == null) {
- return false;
- }
+ Boolean value = getValidatorMetaData().get(vmd);
+ if (value == null)return false;
return value.booleanValue();
}
@@ -544,19 +541,13 @@
return t.intValue();
}
- public static ValidatorMetaData[] convertToArray(Collection c) {
+ public static ValidatorMetaData[] convertToArray(Collection<ValidatorMetaData> c) {
int length = (c == null) ? 0 : c.size();
ValidatorMetaData[] result = new ValidatorMetaData[length];
- if (length == 0) {
- return result;
- }
+ if (length == 0)return result;
- Iterator iterator = c.iterator();
int count = 0;
- while (iterator.hasNext()) {
- ValidatorMetaData vmd = (ValidatorMetaData) iterator.next();
- result[count++] = vmd;
- }
+ for (ValidatorMetaData vmd : c)result[count++] = vmd;
return result;
}
@@ -564,34 +555,33 @@
public static ValidatorMetaData[] convertToArray(Object[] c) {
int length = (c == null) ? 0 : c.length;
ValidatorMetaData[] result = new ValidatorMetaData[length];
- if (length == 0) {
- return result;
- }
+ if (length == 0)return result;
System.arraycopy(c, 0, result, 0, length);
return result;
}
+
+ /**
+ * Save the values of these fields before the project or workspace is closed.
+ */
+ public void store() throws InvocationTargetException {
+ store(null);
+ }
/**
* Save the values of these fields before the project or workspace is closed.
*/
- public void store() throws InvocationTargetException {
- Preferences pref = ValidationPlugin.getPlugin().getPluginPreferences();
- if (pref != null) {
- try {
- OutputStream os = new ByteArrayOutputStream();
- pref.setValue(USER_PREFERENCE, serialize());
- pref.store(os, USER_PREFERENCE);
- pref.setValue(USER_MANUAL_PREFERENCE, serializeManualSetting());
- pref.store(os, USER_MANUAL_PREFERENCE);
- pref.setValue(USER_BUILD_PREFERENCE, serializeBuildSetting());
- pref.store(os, USER_BUILD_PREFERENCE);
- pref.setValue(DELEGATES_PREFERENCE, serializeDelegatesSetting());
- pref.store(os, DELEGATES_PREFERENCE);
- } catch (IOException ie) {
- Logger.getLogger().log(ie);
- }
-
+ public void store(Boolean persist) throws InvocationTargetException {
+ PreferencesWrapper pref = PreferencesWrapper.getPreferences(null, persist);
+ pref.put(ValidationConfiguration.UserPreference, serialize());
+ pref.put(ValidationConfiguration.UserManualPreference, serializeManualSetting());
+ pref.put(ValidationConfiguration.UserBuildPreference, serializeBuildSetting());
+ pref.put(ValidationConfiguration.DelegatesPreference, serializeDelegatesSetting());
+ try {
+ pref.flush();
+ }
+ catch (BackingStoreException e){
+ throw new InvocationTargetException(e);
}
}
@@ -622,9 +612,7 @@
protected final String loadVersion(IMarker[] marker) throws InvocationTargetException {
String version = (String) getValue(marker[0], ConfigurationConstants.VERSION);
- if (version == null) {
- return ConfigurationConstants.VERSION4_03;
- }
+ if (version == null) return ConfigurationConstants.VERSION4_03;
return version;
}
@@ -674,7 +662,7 @@
}
} catch (InvocationTargetException exc) {
throw exc;
- } catch (Throwable exc) {
+ } catch (Exception exc) {
String resourceName = (getResource() == null) ? "null" : getResource().getName(); //$NON-NLS-1$
throw new InvocationTargetException(exc, ResourceHandler.getExternalizedMessage(ResourceConstants.VBF_EXC_RETRIEVE, new String[]{resourceName}));
}
@@ -689,47 +677,33 @@
protected abstract void load(IMarker[] marker) throws InvocationTargetException;
protected Object getValue(IMarker marker, String attribName) {
- if (marker == null) {
- return null;
- }
+ if (marker == null)return null;
try {
return marker.getAttribute(attribName);
- } catch (CoreException exc) {
- Logger logger = ValidationPlugin.getPlugin().getMsgLogger();
- if (logger.isLoggingLevel(Level.SEVERE)) {
- LogEntry entry = ValidationPlugin.getLogEntry();
- entry.setSourceIdentifier("ValidationConfiguration::getValue(" + attribName + ")"); //$NON-NLS-1$ //$NON-NLS-2$
- entry.setTargetException(exc);
- logger.write(Level.SEVERE, entry);
- }
+ } catch (CoreException e) {
+ ValidationPlugin.getPlugin().handleException(e);
return null;
}
}
protected boolean getValue(IMarker marker, String attribName, boolean defaultValue) {
Boolean bool = (Boolean) getValue(marker, attribName);
- if (bool == null) {
- return defaultValue;
- }
+ if (bool == null)return defaultValue;
return bool.booleanValue();
}
protected int getValue(IMarker marker, String attribName, int defaultValue) {
Integer integer = (Integer) getValue(marker, attribName);
- if (integer == null) {
- return defaultValue;
- }
+ if (integer == null)return defaultValue;
return integer.intValue();
}
protected String getValue(IMarker marker, String attribName, String defaultValue) {
String string = (String) getValue(marker, attribName);
- if (string == null) {
- return defaultValue;
- }
+ if (string == null)return defaultValue;
return string;
}
@@ -739,24 +713,22 @@
// 1. This is a new workspace and no preferences exist.
// 2. This is a migrated workspace and the old preferences have already been created as
// persistent properties.
- Preferences prefs = ValidationPlugin.getPlugin().getPluginPreferences();
- if (prefs != null) {
- deserializeAllPrefs(prefs);
- }
+ PreferencesWrapper prefs = PreferencesWrapper.getPreferences(null, null);
+ deserializeAllPrefs(prefs);
}
/**
* @param prefs
* @throws InvocationTargetException
*/
- private void deserializeAllPrefs(Preferences prefs) throws InvocationTargetException {
- String storedConfig = prefs.getString(USER_PREFERENCE);
+ private void deserializeAllPrefs(PreferencesWrapper prefs) throws InvocationTargetException {
+ String storedConfig = prefs.get(ValidationConfiguration.UserPreference, null);
deserialize(storedConfig);
- String storedManualConfig = prefs.getString(USER_MANUAL_PREFERENCE);
+ String storedManualConfig = prefs.get(ValidationConfiguration.UserManualPreference, null);
deserializeManual(storedManualConfig);
- String storedBuildConfig = prefs.getString(USER_BUILD_PREFERENCE);
+ String storedBuildConfig = prefs.get(ValidationConfiguration.UserBuildPreference, null);
deserializeBuild(storedBuildConfig);
- String storedDelegatesConfiguration = prefs.getString(DELEGATES_PREFERENCE);
+ String storedDelegatesConfiguration = prefs.get(ValidationConfiguration.DelegatesPreference, null);
deserializeDelegates(storedDelegatesConfiguration);
}
@@ -766,28 +738,28 @@
try {
deserializeAllPrefs(event);
passivate();
- } catch (InvocationTargetException ie) {
- Logger.getLogger().log(ie);
+ } catch (InvocationTargetException e) {
+ ValidationPlugin.getPlugin().handleException(e);
}
}
}
private void deserializeAllPrefs(PropertyChangeEvent event) throws InvocationTargetException {
String storedConfig = (String)event.getNewValue();
- if( event.getProperty().equals(USER_PREFERENCE) ){
+ if( event.getProperty().equals(ValidationConfiguration.UserPreference) ){
deserialize(storedConfig);
- }else if(event.getProperty().equals(USER_MANUAL_PREFERENCE)){
+ }else if(event.getProperty().equals(ValidationConfiguration.UserManualPreference)){
deserializeManual(storedConfig);
- }else if(event.getProperty().equals(USER_BUILD_PREFERENCE)){
+ }else if(event.getProperty().equals(ValidationConfiguration.UserBuildPreference)){
deserializeBuild(storedConfig);
- }else if(event.getProperty().equals(DELEGATES_PREFERENCE)){
+ }else if(event.getProperty().equals(ValidationConfiguration.DelegatesPreference)){
deserializeDelegates(storedConfig);
}
}
protected void deserializeBuild(String storedConfiguration) throws InvocationTargetException {
- if (storedConfiguration == null || storedConfiguration.length() == 0 || storedConfiguration.equals("default_value")) {
+ if (storedConfiguration == null || storedConfiguration.length() == 0 || storedConfiguration.equals(DefaultValue)) {
// Assume that the configuration has never been set (new workspace).
resetToDefault();
return;
@@ -799,7 +771,7 @@
}
protected void deserializeManual(String storedConfiguration) throws InvocationTargetException {
- if (storedConfiguration == null || storedConfiguration.length() == 0 || storedConfiguration.equals("default_value")) {
+ if (storedConfiguration == null || storedConfiguration.length() == 0 || storedConfiguration.equals(DefaultValue)) {
// Assume that the configuration has never been set (new workspace).
resetToDefault();
return;
@@ -812,7 +784,7 @@
protected void deserializeDelegates(String storedConfiguration) throws InvocationTargetException {
- if (storedConfiguration == null || storedConfiguration.length() == 0 || storedConfiguration.equals("default_value")) {
+ if (storedConfiguration == null || storedConfiguration.length() == 0 || storedConfiguration.equals(DefaultValue)) {
// Assume that the configuration has never been set (new workspace).
resetToDefault();
return;
@@ -838,7 +810,6 @@
protected void copyTo(ValidationConfiguration up) throws InvocationTargetException {
up.setVersion(getVersion());
- up.setResource(getResource());
up.setValidators(getValidators());
up.setDisableAllValidation(isDisableAllValidation());
up.setEnabledValidators(getEnabledValidators());
@@ -847,15 +818,19 @@
up.setDelegatingValidators(getDelegatingValidators());
}
- public Map getDelegatingValidators() throws InvocationTargetException {
- return _delegatesByTarget;
- }
+ /**
+ * The key is the id of the place holder validator, and the value is the id of validator
+ * that will perform the validation.
+ */
+ public Map<String, String> getDelegatingValidators() throws InvocationTargetException {
+ return _delegatesByTarget;
+ }
- public void setDelegatingValidators(Map source)
- {
- // It is safe to copy this map as it contains only immutable strings.
- _delegatesByTarget.putAll(source);
- }
+ public void setDelegatingValidators(Map<String, String> source)
+ {
+ // It is safe to copy this map as it contains only immutable strings.
+ _delegatesByTarget.putAll(source);
+ }
/**
* Return true if the enabled validators have not changed since this ValidationConfiguration was
@@ -893,32 +868,20 @@
* @return true if there has been a change, false otherwise.
* @throws InvocationTargetException
*/
- protected boolean haveDelegatesChanged(Map oldDelegates) throws InvocationTargetException {
+ protected boolean haveDelegatesChanged(Map<String, String> oldDelegates) throws InvocationTargetException {
- if (oldDelegates == null) {
- return true;
- }
+ if (oldDelegates == null)return true;
- Iterator iterator = oldDelegates.keySet().iterator();
-
- while (iterator.hasNext())
- {
- String targetID = (String) iterator.next();
- String oldDelegateID = (String) oldDelegates.get(targetID);
- String newDelegateID = (String) _delegatesByTarget.get(targetID);
+ for (String targetID : oldDelegates.keySet()) {
+ String oldDelegateID = oldDelegates.get(targetID);
+ String newDelegateID = _delegatesByTarget.get(targetID);
- if (oldDelegateID == null || newDelegateID == null) {
- return true;
- }
+ if (oldDelegateID == null || newDelegateID == null)return true;
- if (!newDelegateID.equals(oldDelegateID)) {
- return true;
- }
+ if (!newDelegateID.equals(oldDelegateID))return true;
}
- if (oldDelegates.size() != _delegatesByTarget.size()) {
- return true;
- }
+ if (oldDelegates.size() != _delegatesByTarget.size())return true;
return false;
}
@@ -958,20 +921,14 @@
* @param validatorMetaData a Map with the currently configured validators.
* @return a String.
*/
- private String getDelegatesAsString(Map validatorMetaData) {
+ private String getDelegatesAsString(Map<ValidatorMetaData, Boolean> validatorMetaData) {
StringBuffer buffer = new StringBuffer();
- Iterator iterator = validatorMetaData.keySet().iterator();
-
- while (iterator.hasNext()) {
-
- ValidatorMetaData vmd = (ValidatorMetaData) iterator.next();
+ for (ValidatorMetaData vmd : validatorMetaData.keySet()) {
String targetID = vmd.getValidatorUniqueName();
String delegateID = getDelegateUniqueName(vmd);
- if (delegateID == null) {
- continue;
- }
+ if (delegateID == null)continue;
// Write out pairs targetID=delegateID
@@ -986,14 +943,25 @@
/**
* Provides the delegate's ID of the validator delegate configured in this configuration for
- * a given delegating validator.
+ * a given delegating validator. That is answer the id of validator that is going to do the real work.
*
- * @param vmd the delegating validator's metadata. Must not be null.
- * @return a String with the unique name (ID) of the validator delegate, null if there isn't one.
+ * @param vmd the delegating validator's meta data. Must not be null.
+ * @return a String with the id of the validator delegate, null if there isn't one.
*/
public String getDelegateUniqueName(ValidatorMetaData vmd) {
String targetID = vmd.getValidatorUniqueName();
- return (String) _delegatesByTarget.get(targetID);
+ return _delegatesByTarget.get(targetID);
+ }
+
+ /**
+ * Provides the delegate's ID of the validator delegate configured in this configuration for
+ * a given delegating validator. That is answer the id of validator that is going to do the real work.
+ *
+ * @param targetId the id of the target (or place holder) validator. Must not be null.
+ * @return a String with the id of the validator delegate, null if there isn't one.
+ */
+ public String getDelegateForTarget(String targetId){
+ return _delegatesByTarget.get(targetId);
}
/**
@@ -1013,7 +981,7 @@
* loadVersion() method.
*/
protected void deserialize(String storedConfiguration) throws InvocationTargetException {
- if (storedConfiguration == null || storedConfiguration.length() == 0 || storedConfiguration.equals("default_value")) {
+ if (storedConfiguration == null || storedConfiguration.length() == 0 || storedConfiguration.equals(DefaultValue)) {
// Assume that the configuration has never been set (new workspace).
resetToDefault();
return;
@@ -1024,7 +992,7 @@
String disableAllValidation = storedConfiguration.substring(disableAllValidationIndex + ConfigurationConstants.DISABLE_ALL_VALIDATION_SETTING.length(),versionIndex);
setDisableAllValidation(Boolean.valueOf(disableAllValidation).booleanValue());
} else {
- setDisableAllValidation(false);;
+ setDisableAllValidation(false);
}
}
@@ -1047,32 +1015,53 @@
// method.)
return ConfigurationConstants.CURRENT_VERSION;
}
-
public boolean isManualEnabled(ValidatorMetaData vmd) {
- if (vmd == null) {
- return false;
- }
- Boolean value = (Boolean) getManualEnabledValidatorsMap().get(vmd);
- if (value == null)
- return false;
- return value.booleanValue();
+ if (vmd == null)return false;
+ Boolean value = getManualEnabledValidatorsMap().get(vmd);
+ if (value == null)return false;
+ return value;
}
public boolean isBuildEnabled(ValidatorMetaData vmd) {
- if (vmd == null) {
- return false;
- }
- Boolean value = (Boolean) getBuildEnabledValidatorsMap().get(vmd);
- if (value == null)
- return false;
- return value.booleanValue();
+ if (vmd == null)return false;
+ Boolean value = getBuildEnabledValidatorsMap().get(vmd);
+ if (value == null)return false;
+ return value;
}
public int numberOfManualEnabledValidators() throws InvocationTargetException {
return getManualEnabledValidators().length;
}
+
+ public void enableSingleValidator(ValidatorMetaData vmd){
+ getValidatorMetaData().put(vmd, Boolean.TRUE);
+ }
+
+
+ public void disableSingleValidator(ValidatorMetaData vmd){
+ getValidatorMetaData().put(vmd, Boolean.FALSE);
+ }
+
+ public void enableSingleManualValidator(ValidatorMetaData vmd){
+ getManualEnabledValidatorsMap().put(vmd, Boolean.TRUE);
+ }
+
+
+ public void disableSingleManualValidator(ValidatorMetaData vmd){
+ getManualEnabledValidatorsMap().put(vmd, Boolean.FALSE);
+ }
+
+ public void enableSingleBuildValidator(ValidatorMetaData vmd){
+ getBuildEnabledValidatorsMap().put(vmd, Boolean.TRUE);
+ }
+
+
+ public void disableSingleBuildValidator(ValidatorMetaData vmd){
+ getBuildEnabledValidatorsMap().put(vmd, Boolean.FALSE);
+ }
+
/**
* Provides the delegate validator descriptor of the validator delegate configured
* for the given delegating validator in the context of this configuration.
@@ -1086,4 +1075,4 @@
ValidatorDelegateDescriptor descriptor = ValidatorDelegatesRegistry.getInstance().getDescriptor(targetID, delegateID);
return descriptor;
}
-}
\ No newline at end of file
+}
diff --git a/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/ValidationFactoryImpl.java b/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/ValidationFactoryImpl.java
index b8ec7c3..1ba2ed1 100644
--- a/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/ValidationFactoryImpl.java
+++ b/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/ValidationFactoryImpl.java
@@ -1,10 +1,10 @@
/*******************************************************************************
- * Copyright (c) 2001, 2004 IBM Corporation and others.
+ * Copyright (c) 2001, 2006 IBM Corporation 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:
* IBM Corporation - initial API and implementation
*******************************************************************************/
diff --git a/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/ValidationRegistryReader.java b/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/ValidationRegistryReader.java
index 4d332d1..9766048 100644
--- a/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/ValidationRegistryReader.java
+++ b/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/ValidationRegistryReader.java
@@ -1,10 +1,10 @@
/*******************************************************************************
- * Copyright (c) 2001, 2004 IBM Corporation and others.
+ * Copyright (c) 2001, 2009 IBM Corporation 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:
* IBM Corporation - initial API and implementation
*******************************************************************************/
@@ -14,13 +14,12 @@
import java.text.MessageFormat;
import java.util.Arrays;
import java.util.Collection;
-import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
+import java.util.Map;
import java.util.Set;
import java.util.StringTokenizer;
-import java.util.logging.Level;
import org.eclipse.core.expressions.EvaluationContext;
import org.eclipse.core.expressions.EvaluationResult;
@@ -34,9 +33,9 @@
import org.eclipse.core.runtime.IExtension;
import org.eclipse.core.runtime.IExtensionPoint;
import org.eclipse.core.runtime.IExtensionRegistry;
+import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Platform;
-import org.eclipse.jem.util.logger.LogEntry;
-import org.eclipse.jem.util.logger.proxy.Logger;
+import org.eclipse.osgi.util.NLS;
import org.eclipse.wst.common.project.facet.core.IFacetedProject;
import org.eclipse.wst.common.project.facet.core.IProjectFacet;
import org.eclipse.wst.common.project.facet.core.IProjectFacetVersion;
@@ -55,32 +54,41 @@
* ValidatorManager's loadValidatorMetaData(IProject) method. ValidatorManager delegates the load
* call to this class, and if this class is null, the singleton is new'ed up, and the registry is
* read.
- *
+ * <p>
* No Validator should need to know about this class. The only class which should call
* ValidationRegistryReader is ValidatorManager.
- *
+ * </p>
+ * <p>
* The Validator itself is initialized in the "initializeValidator" method.
- *
- * <extension point="org.eclipse.wst.validation.internal.provisional.core.core.validator" id="EJBValidator" name="EJB
- * Validator"> <validator><projectNature id="com.ibm.etools.j2ee.EJBNature" include="false"/>
- * <filter objectClass="org.eclipse.core.resources.IFile" nameFilter = "ejb-jar.xml"/> <filter
- * objectClass="org.eclipse.core.resources.IFile" nameFilter = "*.java"/> <helper
- * class="org.eclipse.wst.validation.internal.provisional.core.core.ejb.workbenchimpl.EJBHelper"/> <run
- * class="org.eclipse.wst.validation.internal.provisional.core.core.ejb.EJBValidator" incremental="false" enabled="false"
- * pass="fast,full" async="false"/> <aggregateValidator class="my.aggregate.ValidatorClass"/>
- * <migrate><validator from="old.class.name" to="new.class.name"/> </migrate> </validator>
- * </extension>
+ * </p>
*/
public final class ValidationRegistryReader implements RegistryConstants {
- private static ValidationRegistryReader inst = null;
- private HashMap _validators; // list of all validators registered, with their associated
- // ValidatorMetaData, indexed by project nature id
- private HashMap _indexedValidators; // list of all validators, indexed by validator class name,
+
+ /* <extension point="org.eclipse.wst.validation.internal.provisional.core.core.validator" id="EJBValidator" name="EJB
+ * Validator"> <validator><projectNature id="com.ibm.etools.j2ee.EJBNature" include="false"/>
+ * <filter objectClass="org.eclipse.core.resources.IFile" nameFilter = "ejb-jar.xml"/> <filter
+ * objectClass="org.eclipse.core.resources.IFile" nameFilter = "*.java"/> <helper
+ * class="org.eclipse.wst.validation.internal.provisional.core.core.ejb.workbenchimpl.EJBHelper"/> <run
+ * class="org.eclipse.wst.validation.internal.provisional.core.core.ejb.EJBValidator" incremental="false" enabled="false"
+ * pass="fast,full" async="false"/> <aggregateValidator class="my.aggregate.ValidatorClass"/>
+ * <migrate><validator from="old.class.name" to="new.class.name"/> </migrate> </validator>
+ * </extension>
+ */
+
+ private static ValidationRegistryReader _inst = new ValidationRegistryReader();
+
+ /** list of all validators registered, with their associated ValidatorMetaData, indexed by project nature id */
+ private final Map<String,Set<ValidatorMetaData>> _validators;
+
+ // list of all validators, indexed by validator class name,
// with the validator's ValidatorMetaData as the value.
// Needed by the WorkbenchReporter, because sometimes the
// IValidator is not enough to remove all messages from the
// task list.
- private Set _defaultEnabledValidators;
+ private final Map<String, ValidatorMetaData> _indexedValidators;
+
+ private final Set<ValidatorMetaData> _defaultEnabledValidators;
+
// Since IProject's contents are all instances of IResource, every type filter for a validator
// must be an instance of IResource. This applies to both the rebuildCache pass and to the
// validation pass.
@@ -89,18 +97,18 @@
private static final String UNKNOWN_PROJECT = "UNKNOWN"; //$NON-NLS-1$ // This 'project nature id' is used as a key to get the validators which can run on a project type which hasn't been explicitly filtered in or out by any validator.
private static final String EXCLUDED_PROJECT = "EXCLUDED"; //$NON-NLS-1$ // This 'project nature id' is used as a key to get the validators which are excluded on certain projects.
- public HashMap projectValidationMetaData = null;
+ /** @deprecated this instance variable should not be public. */
+ public HashMap<IProject, Set<ValidatorMetaData>> projectValidationMetaData = new HashMap<IProject, Set<ValidatorMetaData>>();
/**
* The registry is read once - when this class is instantiated.
*/
private ValidationRegistryReader() {
- super();
+ _validators = new HashMap<String,Set<ValidatorMetaData>>();
+ _indexedValidators = new HashMap<String, ValidatorMetaData>();
+ _defaultEnabledValidators = new HashSet<ValidatorMetaData>();
try {
- _validators = new HashMap();
- _indexedValidators = new HashMap();
- _defaultEnabledValidators = new HashSet();
// Read the registry and build a map of validators. The key into
// the map is the IValidator instance and the value is the ValidatorMetaData
@@ -110,14 +118,8 @@
// Once all of the validators have been read, the caches of the
// validators need to be updated.
buildCache();
- } catch (Throwable exc) {
- Logger logger = ValidationPlugin.getPlugin().getMsgLogger();
- if (logger.isLoggingLevel(Level.SEVERE)) {
- LogEntry entry = ValidationPlugin.getLogEntry();
- entry.setSourceID("ValidationRegistryReader()"); //$NON-NLS-1$
- entry.setTargetException(exc);
- logger.write(Level.SEVERE, entry);
- }
+ } catch (Exception e) {
+ ValidationPlugin.getPlugin().handleException(e);
}
}
@@ -126,9 +128,7 @@
* created to increase runtime performance.
*/
private void buildCache() {
- Iterator iterator = _indexedValidators.values().iterator();
- while (iterator.hasNext()) {
- ValidatorMetaData vmd = (ValidatorMetaData) iterator.next();
+ for (ValidatorMetaData vmd : _indexedValidators.values()) {
buildProjectNatureCache(vmd);
buildDefaultEnabledCache(vmd);
}
@@ -138,17 +138,12 @@
addRemainder();
// this temporary list isn't needed any more. All of the excluded
- // projects have been added to the project natures which they don't exlcude.
+ // projects have been added to the project natures which they don't exclude.
_validators.remove(EXCLUDED_PROJECT);
- Logger logger = ValidationPlugin.getPlugin().getMsgLogger();
- if (logger.isLoggingLevel(Level.FINEST)) {
- LogEntry entry = ValidationPlugin.getLogEntry();
- entry.setSourceID("ValidationRegistryReader.buildCache()"); //$NON-NLS-1$
- entry.setText(debug());
- logger.write(Level.FINEST, entry);
+ if (Tracing.isTraceV1()) {
+ Tracing.log("ValidationRegistryReader-01: ", debug()); //$NON-NLS-1$
}
-
}
/**
@@ -189,13 +184,9 @@
* Build the list of validators which are enabled by default.
*/
private void buildDefaultEnabledCache(ValidatorMetaData vmd) {
- if (vmd == null) {
- return;
- }
+ if (vmd == null)return;
- if (vmd.isEnabledByDefault()) {
- _defaultEnabledValidators.add(vmd);
- }
+ if (vmd.isEnabledByDefault())_defaultEnabledValidators.add(vmd);
}
/**
@@ -229,23 +220,20 @@
}
private void addExcludedRemainder() {
- Set excludedProjVmds = (Set) _validators.get(EXCLUDED_PROJECT);
+ Set<ValidatorMetaData> excludedProjVmds = _validators.get(EXCLUDED_PROJECT);
if (excludedProjVmds == null) {
// no excluded project natures
return;
}
- Iterator exIterator = excludedProjVmds.iterator();
- while (exIterator.hasNext()) {
- ValidatorMetaData vmd = (ValidatorMetaData) exIterator.next();
+ for (ValidatorMetaData vmd : excludedProjVmds) {
- boolean noneIncluded = true; // assume that, by default, if someone explicitly excludes
- // a project nature then they don't include any project
- // natures
- Set keys = _validators.keySet();
- Iterator iterator = keys.iterator();
- while (iterator.hasNext()) {
- String projId = (String) iterator.next();
+ // assume that, by default, if someone explicitly excludes
+ // a project nature then they don't include any project natures
+ boolean noneIncluded = true;
+
+ // a project nature then they don't include any project natures
+ for (String projId : _validators.keySet()) {
if (projId.equals(UNKNOWN_PROJECT) || projId.equals(EXCLUDED_PROJECT)) {
// Don't add list to a project nature which is excluded or applicable to all.
continue;
@@ -278,16 +266,13 @@
}
private void addAnyRemainder() {
- Set anyProjVmds = (Set) _validators.get(UNKNOWN_PROJECT);
+ Set<ValidatorMetaData> anyProjVmds = _validators.get(UNKNOWN_PROJECT);
if (anyProjVmds == null) {
// no validators run on all projects
return;
}
- Set keys = _validators.keySet();
- Iterator iterator = keys.iterator();
- while (iterator.hasNext()) {
- String projId = (String) iterator.next();
+ for (String projId : _validators.keySet()) {
if (projId.equals(UNKNOWN_PROJECT) || projId.equals(EXCLUDED_PROJECT)) {
// Don't add list to itself or to a project nature which is excluded.
continue;
@@ -297,26 +282,22 @@
}
}
- private void add(String projectNatureId, Set vmdList) {
- if ((vmdList == null) || (vmdList.size() == 0)) {
- return;
- }
+ private void add(String projectNatureId, Set<ValidatorMetaData> vmdList) {
+ if ((vmdList == null) || (vmdList.size() == 0))return;
- Set pnVal = createSet(projectNatureId); // whether the validator includes or excludes this
- // project nature id, make sure that an entry is
- // created for it in the table
+ // whether the validator includes or excludes this
+ // project nature id, make sure that an entry is created for it in the table
+ Set<ValidatorMetaData> pnVal = createSet(projectNatureId);
pnVal.addAll(vmdList);
_validators.put(projectNatureId, pnVal);
}
private void add(String projectNatureId, ValidatorMetaData vmd) {
- if (vmd == null) {
- return;
- }
+ if (vmd == null)return;
- Set pnVal = createSet(projectNatureId); // whether the validator includes or excludes this
- // project nature id, make sure that an entry is
- // created for it in the table
+ // whether the validator includes or excludes this
+ // project nature id, make sure that an entry is created for it in the table
+ Set<ValidatorMetaData> pnVal = createSet(projectNatureId);
pnVal.add(vmd);
_validators.put(projectNatureId, pnVal);
}
@@ -334,25 +315,21 @@
// a lot of processing time... Instead, traverse the list of proj nature ids,
// and search the Set of that proj nature id, and remove the vmd if it's in the
// Set.
- Object[] keys = _validators.keySet().toArray();
- for (int i = 0; i < keys.length; i++) {
- Object key = keys[i];
- Set value = (Set) _validators.get(key);
- if (value == null) {
- continue;
- }
+ for (String projId : _validators.keySet()) {
+ Set<ValidatorMetaData> value = _validators.get(projId);
+ if (value == null)continue;
if (value.contains(vmd)) {
value.remove(vmd);
- _validators.put(key, value);
+ _validators.put(projId, value);
}
}
}
- private Set createSet(String projNature) {
- Set v = (Set) _validators.get(projNature);
+ private Set<ValidatorMetaData> createSet(String projNature) {
+ Set<ValidatorMetaData> v = _validators.get(projNature);
if (v == null) {
- v = new HashSet();
+ v = new HashSet<ValidatorMetaData>();
}
return v;
}
@@ -389,6 +366,20 @@
}
return names;
}
+
+ private String[] getContentTypeBindings(IConfigurationElement element){
+ IConfigurationElement[] bindings = element.getChildren(TAG_CONTENTTYPE);
+ if(bindings.length == 0)
+ return null;
+ String[] cTypeIDs = new String[bindings.length];
+ for (int i = 0; i < bindings.length; i ++){
+
+ cTypeIDs[i] = bindings[i].getAttribute(ATT_CONTENTTYPEID);
+ }
+
+ return cTypeIDs;
+
+ }
/**
* Given an IConfigurationElement from plugin.xml, if it has any filter tags, construct the
@@ -482,53 +473,36 @@
return helpers[0].getAttribute(ATT_CLASS);
}
- /* package */static IWorkbenchContext createHelper(IConfigurationElement element, String helperClassName) {
+ static IWorkbenchContext createHelper(IConfigurationElement element, String helperClassName) {
IWorkbenchContext wh = null;
try {
wh = (IWorkbenchContext) element.createExecutableExtension(TAG_HELPER_CLASS);
- } catch (Throwable exc) {
- Logger logger = ValidationPlugin.getPlugin().getMsgLogger();
- if (logger.isLoggingLevel(Level.SEVERE)) {
- LogEntry entry = ValidationPlugin.getLogEntry();
- entry.setSourceID("ValidationRegistryReader.createHelper(IConfigurationElement, String)"); //$NON-NLS-1$
- entry.setMessageTypeIdentifier(ResourceConstants.VBF_EXC_SYNTAX_NO_HELPER_THROWABLE);
- entry.setTargetException(exc);
- String result = MessageFormat.format(ResourceHandler.getExternalizedMessage(ResourceConstants.VBF_EXC_SYNTAX_NO_HELPER_THROWABLE), new String[]{helperClassName});
- entry.setText(result);
- //entry.setTokens(new String[]{helperClassName});
- logger.write(Level.SEVERE, entry);
- }
+ } catch (Exception exc) {
+ ValidationPlugin.getPlugin().handleException(exc);
+ String result = MessageFormat.format(
+ ResourceHandler.getExternalizedMessage(ResourceConstants.VBF_EXC_SYNTAX_NO_HELPER_THROWABLE),
+ new Object[]{helperClassName});
+ ValidationPlugin.getPlugin().logMessage(IStatus.ERROR, result);
return null;
}
return wh;
}
- /* package */static IValidator createValidator(IConfigurationElement element, String validatorClassName) {
+ static IValidator createValidator(IConfigurationElement element, String validatorClassName) {
IValidator validator = null;
try {
- validator = (IValidator) element.createExecutableExtension(TAG_RUN_CLASS);
- } catch (Throwable exc) {
- Logger logger = ValidationPlugin.getPlugin().getMsgLogger();
- if (logger.isLoggingLevel(Level.SEVERE)) {
- LogEntry entry = ValidationPlugin.getLogEntry();
- entry.setSourceID("ValidationRegistryReader.createValidator(IConfigurationElement, String, String)"); //$NON-NLS-1$
- entry.setMessageTypeID(ResourceConstants.VBF_EXC_SYNTAX_NO_VAL_THROWABLE);
- //entry.setTokens(new String[]{validatorClassName});
- String result = MessageFormat.format(ResourceHandler.getExternalizedMessage(ResourceConstants.VBF_EXC_SYNTAX_NO_VAL_THROWABLE), new String[]{validatorClassName});
- entry.setText(result);
- entry.setTargetException(exc);
- logger.write(Level.SEVERE, entry);
- }
+ validator = (IValidator) element.createExecutableExtension(ATT_CLASS);
+ } catch (Exception e) {
+ String result = MessageFormat.format(ResourceHandler.getExternalizedMessage(ResourceConstants.VBF_EXC_SYNTAX_NO_VAL_THROWABLE),
+ new Object[]{validatorClassName});
+ ValidationPlugin.getPlugin().logMessage(IStatus.ERROR, result);
+ ValidationPlugin.getPlugin().handleException(e);
}
if (validator == null) {
- Logger logger = ValidationPlugin.getPlugin().getMsgLogger();
- if (logger.isLoggingLevel(Level.FINE)) {
- LogEntry entry = ValidationPlugin.getLogEntry();
- entry.setSourceID("ValidationRegistryReader.createValidator(IConfigurationElement, String)"); //$NON-NLS-1$
- entry.setMessageTypeID(ResourceConstants.VBF_EXC_SYNTAX_NO_VAL_NULL);
- entry.setTokens(new String[]{validatorClassName});
- logger.write(Level.FINE, entry);
+ if (Tracing.isTraceV1()) {
+ Tracing.log("ValidationRegistryReader-02: ", //$NON-NLS-1$
+ NLS.bind(ValMessages.VbfExcSyntaxNoValNull, validatorClassName));
}
return null;
}
@@ -673,7 +647,7 @@
return result;
}
- private ValidatorMetaData.MigrationMetaData getMigrationMetaData(IConfigurationElement element, ValidatorMetaData vmd) {
+ private ValidatorMetaData.MigrationMetaData getMigrationMetaData(IConfigurationElement element) {
IConfigurationElement[] runChildren = element.getChildren(TAG_MIGRATE);
if ((runChildren == null) || (runChildren.length == 0)) {
return null;
@@ -688,7 +662,7 @@
return null;
}
- ValidatorMetaData.MigrationMetaData mmd = vmd.new MigrationMetaData();
+ ValidatorMetaData.MigrationMetaData mmd = new ValidatorMetaData.MigrationMetaData();
for (int i = 0; i < migrateChildren.length; i++) {
IConfigurationElement migrateChild = migrateChildren[i];
String from = migrateChild.getAttribute(ATT_FROM);
@@ -747,12 +721,7 @@
* Returns the singleton ValidationRegistryReader.
*/
public static ValidationRegistryReader getReader() {
- if (inst == null) {
- inst = new ValidationRegistryReader();
-
- EventManager.getManager().setActive(true);
- }
- return inst;
+ return _inst;
}
public static boolean isActivated() {
@@ -768,21 +737,14 @@
*/
private IExtensionPoint getValidatorExtensionPoint() {
IExtensionRegistry registry = Platform.getExtensionRegistry();
- IExtensionPoint extensionPoint = registry.getExtensionPoint(PLUGIN_ID, VALIDATOR_EXT_PT_ID);
+ IExtensionPoint extensionPoint = registry.getExtensionPoint(ValidationPlugin.PLUGIN_ID, VALIDATOR_EXT_PT_ID);
if (extensionPoint == null) {
// If this happens it means that someone removed the "validator" extension point
- // declaration
- // from our plugin.xml file.
- Logger logger = ValidationPlugin.getPlugin().getMsgLogger();
- if (logger.isLoggingLevel(Level.FINE)) {
- LogEntry entry = ValidationPlugin.getLogEntry();
- entry.setSourceID("ValidationRegistryReader.getValidatorExtensionPoint()"); //$NON-NLS-1$
- entry.setMessageTypeID(ResourceConstants.VBF_EXC_MISSING_VALIDATOR_EP);
- //entry.setTokens(new String[]{ValidationPlugin.PLUGIN_ID + "." + VALIDATOR_EXT_PT_ID}); //$NON-NLS-1$
+ // declaration from our plugin.xml file.
+ if (Tracing.isTraceV1()) {
String result = MessageFormat.format(ResourceHandler.getExternalizedMessage(ResourceConstants.VBF_EXC_MISSING_VALIDATOR_EP),
- new String[]{ValidationPlugin.PLUGIN_ID + "." + VALIDATOR_EXT_PT_ID});
- entry.setText(result);
- logger.write(Level.FINE, entry);
+ new Object[]{ValidationPlugin.PLUGIN_ID + "." + VALIDATOR_EXT_PT_ID}); //$NON-NLS-1$
+ Tracing.log("ValidationRegistryReader-03: ", result); //$NON-NLS-1$
}
}
return extensionPoint;
@@ -795,13 +757,9 @@
public ValidatorMetaData getValidatorMetaData(IValidator validator) {
// retrieval will be in log(n) time
if (validator == null) {
- Logger logger = ValidationPlugin.getPlugin().getMsgLogger();
- if (logger.isLoggingLevel(Level.SEVERE)) {
- LogEntry entry = ValidationPlugin.getLogEntry();
- entry.setSourceID("ValidationRegistryReader.getValidatorMetaData(IValidator)"); //$NON-NLS-1$
- entry.setText(ResourceHandler.getExternalizedMessage(ResourceConstants.VBF_EXC_ORPHAN_IVALIDATOR, new String[]{"null"})); //$NON-NLS-1$
- logger.write(Level.SEVERE, entry);
- }
+ String message = ResourceHandler.getExternalizedMessage(
+ ResourceConstants.VBF_EXC_ORPHAN_IVALIDATOR, new String[]{"null"}); //$NON-NLS-1$
+ ValidationPlugin.getPlugin().logMessage(IStatus.ERROR, message);
return null;
}
@@ -813,19 +771,15 @@
// If we got here, then vmd is neither a root nor an aggregate validator,
// yet the IValidator exists. Internal error.
- Logger logger = ValidationPlugin.getPlugin().getMsgLogger();
- if (logger.isLoggingLevel(Level.SEVERE)) {
- LogEntry entry = ValidationPlugin.getLogEntry();
- entry.setSourceID("ValidationRegistryReader.getValidatorMetaData(IValidator)"); //$NON-NLS-1$
- entry.setText(ResourceHandler.getExternalizedMessage(ResourceConstants.VBF_EXC_ORPHAN_IVALIDATOR, new String[]{validatorClassName}));
- logger.write(Level.SEVERE, entry);
- }
+ String message = ResourceHandler.getExternalizedMessage(
+ ResourceConstants.VBF_EXC_ORPHAN_IVALIDATOR, new String[]{validatorClassName});
+ ValidationPlugin.getPlugin().logMessage(IStatus.ERROR, message);
return null;
}
- public Set getValidatorMetaData(IWorkspaceRoot root) {
+ public Set<ValidatorMetaData> getValidatorMetaData(IWorkspaceRoot root) {
// Every validator on the Preferences page must be returned
- Set copy = new HashSet();
+ Set<ValidatorMetaData> copy = new HashSet<ValidatorMetaData>();
clone(_indexedValidators.values(), copy);
return copy;
}
@@ -836,8 +790,8 @@
*
* This is a long-running process. If you can, cache the result.
*/
- public Set getValidatorMetaData(IProject project) {
- Set copy = new HashSet();
+ public Set<ValidatorMetaData> getValidatorMetaData(IProject project) {
+ Set<ValidatorMetaData> copy = new HashSet<ValidatorMetaData>();
getValidatorMetaData(project, copy);
return copy;
}
@@ -845,19 +799,13 @@
/**
* Copy the set of configured validator metadata into the Set.
*/
- public void getValidatorMetaData(IProject project, Set vmds) {
- if (vmds == null) {
- return;
- }
+ public void getValidatorMetaData(IProject project, Set<ValidatorMetaData> vmds) {
+ if (vmds == null)return;
vmds.clear();
int executionMap = 0x0;
- Logger logger = ValidationPlugin.getPlugin().getMsgLogger();
try {
- if (logger.isLoggingLevel(Level.FINEST)) {
- LogEntry entry = ValidationPlugin.getLogEntry();
- entry.setSourceID("ValidationRegistryReader.getValidatorMetaData(IProject)"); //$NON-NLS-1$
- entry.setText("IProject is " + String.valueOf(project)); //$NON-NLS-1$
- logger.write(Level.FINEST, entry);
+ if (Tracing.isTraceV1()) {
+ Tracing.log("ValidationRegistryReader-04: IProject is " + String.valueOf(project)); //$NON-NLS-1$
}
if (project == null) {
executionMap |= 0x1;
@@ -867,23 +815,16 @@
String[] projectNatures = null;
try {
projectNatures = project.getDescription().getNatureIds();
- } catch (CoreException exc) {
+ } catch (CoreException e) {
executionMap |= 0x2;
// vmds is already clear
- if (logger.isLoggingLevel(Level.SEVERE)) {
- LogEntry entry = ValidationPlugin.getLogEntry();
- entry.setSourceID("ValidationRegistryReader.getValidatorMetaData(" + project.getName() + ")"); //$NON-NLS-1$ //$NON-NLS-2$
- entry.setTargetException(exc);
- entry.setExecutionMap(executionMap);
- logger.write(Level.SEVERE, entry);
- }
+ ValidationPlugin.getPlugin().handleException(e);
return;
}
// If there are no project natures on a particular project,
// or if this project nature has no validators configured
// on it, return the validators which are configured on all
// projects.
- Set projVmds = null;
if ((projectNatures == null) || (projectNatures.length == 0)) {
executionMap |= 0x4;
@@ -897,10 +838,8 @@
// <test forcePluginActivation="true" property="foo.testProperty"/>
// </enablement>
- Set validatorsWithEnablementExpression = new HashSet();
- Iterator allValidators = getAllValidators().iterator();
- while (allValidators.hasNext()) {
- ValidatorMetaData vmd = (ValidatorMetaData) allValidators.next();
+ Set<ValidatorMetaData> validatorsWithEnablementExpression = new HashSet<ValidatorMetaData>();
+ for (ValidatorMetaData vmd : getAllValidators()) {
if (isFacetEnabled(vmd, project)) {
validatorsWithEnablementExpression.add(vmd);
}
@@ -915,12 +854,8 @@
} else {
executionMap |= 0x8;
- if (logger.isLoggingLevel(Level.FINEST)) {
- LogEntry entry = ValidationPlugin.getLogEntry();
- entry.setSourceID("ValidationRegistryReader.getValidatorMetaData(IProject)"); //$NON-NLS-1$
- // entry.setTokens(projectNatures);
- entry.setText(projectNatures.toString());
- logger.write(Level.FINEST, entry);
+ if (Tracing.isTraceV1()) {
+ Tracing.log("ValidationRegistryReader-05: ", projectNatures.toString()); //$NON-NLS-1$
}
calculateVmdsForNatureAndFacets(vmds, projectNatures,project);
// Now filter out the validators which must not run on this project
@@ -931,20 +866,13 @@
}
}
} finally {
- if (logger.isLoggingLevel(Level.FINER)) {
- LogEntry entry = ValidationPlugin.getLogEntry();
- entry.setSourceID("ValidationRegistryReader.getValidatorMetaData(IProject)"); //$NON-NLS-1$
- entry.setExecutionMap(executionMap);
-
+ if (Tracing.isTraceV1()) {
StringBuffer buffer = new StringBuffer();
- Iterator iterator = vmds.iterator();
- while (iterator.hasNext()) {
- ValidatorMetaData vmd = (ValidatorMetaData) iterator.next();
+ for (ValidatorMetaData vmd : vmds) {
buffer.append(vmd.getValidatorUniqueName());
buffer.append("\n"); //$NON-NLS-1$
}
- entry.setText(buffer.toString());
- logger.write(Level.FINER, entry);
+ Tracing.log("ValidationRegistryReader-06: ", buffer.toString()); //$NON-NLS-1$
}
}
}
@@ -954,31 +882,22 @@
* @param vmds
* @param projectNatures
*/
- private void calculateVmdsForNatureAndFacets(Set vmds, String[] projectNatures, IProject project) {
- Set projVmds;
+ private void calculateVmdsForNatureAndFacets(Set<ValidatorMetaData> vmds, String[] projectNatures, IProject project) {
+ Set<ValidatorMetaData> projVmds;
String[] projectFacetIds = getProjectFacetIds(project);
- Iterator allValidators = getAllValidators().iterator();
- while (allValidators.hasNext()) {
- ValidatorMetaData vmd = (ValidatorMetaData) allValidators.next();
+ for (ValidatorMetaData vmd : getAllValidators()) {
if (containsProjectFacet(vmd, projectFacetIds) || isFacetEnabled(vmd, project)) {
vmds.add(vmd);
}
}
- for (int i = 0; i < projectNatures.length; i++) {
- String projectNatureId = projectNatures[i];
- projVmds = (Set) _validators.get(projectNatureId);
- if (projVmds == null)
- continue;
+ for (String projectNatureId : projectNatures) {
+ projVmds = _validators.get(projectNatureId);
+ if (projVmds == null)continue;
- Iterator iterator = projVmds.iterator();
- while (iterator.hasNext()) {
- ValidatorMetaData vmd = (ValidatorMetaData) iterator.next();
+ for (ValidatorMetaData vmd : projVmds) {
if (!vmds.contains(vmd) && (vmd.getFacetFilters() == null || vmd.getFacetFilters().length == 0)) {
- if (vmd.getEnablementExpresion() == null)
- vmds.add(vmd);
- else if (isFacetEnabled(vmd, project))
- vmds.add(vmd);
-
+ if (vmd.getEnablementExpresion() == null)vmds.add(vmd);
+ else if (isFacetEnabled(vmd, project))vmds.add(vmd);
}
}
}
@@ -1035,34 +954,21 @@
* instance of a java project, then the AValidator is included by the java nature and excluded
* by the J2EE nature. The AValidator would have to be removed from the set.
*/
- private void removeExcludedProjects(IProject project, Set vmds) {
- Logger logger = ValidationPlugin.getPlugin().getMsgLogger();
- if (logger.isLoggingLevel(Level.FINEST)) {
- LogEntry entry = ValidationPlugin.getLogEntry();
- entry.setSourceID("ValidationRegistryReader.removeExcludedProjects"); //$NON-NLS-1$
-
- StringBuffer buffer = new StringBuffer("\nBefore:\n"); //$NON-NLS-1$
- Iterator viterator = vmds.iterator();
- while (viterator.hasNext()) {
- ValidatorMetaData vmd = (ValidatorMetaData) viterator.next();
+ private void removeExcludedProjects(IProject project, Set<ValidatorMetaData> vmds) {
+ if (Tracing.isTraceV1()) {
+ StringBuffer buffer = new StringBuffer("\nValidationRegistryReader-12: before:\n"); //$NON-NLS-1$
+ for (ValidatorMetaData vmd : vmds) {
buffer.append(vmd.getValidatorUniqueName());
buffer.append("\n"); //$NON-NLS-1$
}
- entry.setText(buffer.toString());
- logger.write(Level.FINEST, entry);
+ Tracing.log(buffer);
}
String[] projectNatures = null;
try {
projectNatures = project.getDescription().getNatureIds();
- } catch (CoreException exc) {
- // if there's no natures, there's no list.
- if (logger.isLoggingLevel(Level.SEVERE)) {
- LogEntry entry = ValidationPlugin.getLogEntry();
- entry.setSourceID("ValidationRegistryReader.getValidatorMetaData(" + project.getName() + ")"); //$NON-NLS-1$ //$NON-NLS-2$
- entry.setTargetException(exc);
- logger.write(Level.SEVERE, entry);
- }
+ } catch (CoreException e) {
+ ValidationPlugin.getPlugin().handleException(e);
return;
}
if ((projectNatures == null) || (projectNatures.length == 0)) {
@@ -1071,17 +977,16 @@
}
for (int i = 0; i < projectNatures.length; i++) {
String nature = projectNatures[i];
- Iterator iterator = vmds.iterator();
+ Iterator<ValidatorMetaData> iterator = vmds.iterator();
while (iterator.hasNext()) {
- ValidatorMetaData vmd = (ValidatorMetaData) iterator.next();
+ ValidatorMetaData vmd = iterator.next();
ValidatorNameFilter[] natureFilters = vmd.getProjectNatureFilters();
if (natureFilters == null) {
// Can run on any project
continue;
}
- for (int j = 0; j < natureFilters.length; j++) {
- ValidatorNameFilter pn = natureFilters[j];
+ for (ValidatorNameFilter pn : natureFilters) {
if (nature.equals(pn.getNameFilter()) && !pn.isInclude()) {
iterator.remove();
break;
@@ -1090,30 +995,19 @@
}
}
- if (logger.isLoggingLevel(Level.FINEST)) {
- LogEntry entry = ValidationPlugin.getLogEntry();
- entry.setSourceID("ValidationRegistryReader.removeExcludedProjects"); //$NON-NLS-1$
-
- StringBuffer buffer = new StringBuffer("\nAfter:\n"); //$NON-NLS-1$
- Iterator viterator = vmds.iterator();
- while (viterator.hasNext()) {
- ValidatorMetaData vmd = (ValidatorMetaData) viterator.next();
+ if (Tracing.isTraceV1()) {
+ StringBuffer buffer = new StringBuffer("\nValidationRegistryReader-13: after:\n"); //$NON-NLS-1$
+ for (ValidatorMetaData vmd : vmds) {
buffer.append(vmd.getValidatorUniqueName());
buffer.append("\n"); //$NON-NLS-1$
}
- entry.setText(buffer.toString());
- logger.write(Level.FINEST, entry);
+ Tracing.log(buffer);
}
}
+ @SuppressWarnings("unchecked")
private Collection clone(Collection input, Collection copy) {
- if (input == null) {
- return null;
- }
-
- if (copy == null) {
- return null;
- }
+ if (input == null || copy == null)return null;
copy.clear();
copy.addAll(input);
return copy;
@@ -1123,16 +1017,12 @@
StringBuffer buffer = new StringBuffer();
buffer.append("Project nature => validators configured"); //$NON-NLS-1$
buffer.append("\n"); //$NON-NLS-1$
- Iterator viterator = _validators.keySet().iterator();
- while (viterator.hasNext()) {
- String projId = (String) viterator.next();
+ for (String projId : _validators.keySet()) {
buffer.append("projId: "); //$NON-NLS-1$
buffer.append(projId);
buffer.append("\n"); //$NON-NLS-1$
- Set validators = (Set) _validators.get(projId);
- Iterator innerIterator = validators.iterator();
- while (innerIterator.hasNext()) {
- ValidatorMetaData vmd = (ValidatorMetaData) innerIterator.next();
+ Set<ValidatorMetaData> validators = _validators.get(projId);
+ for (ValidatorMetaData vmd : validators) {
buffer.append("\t"); //$NON-NLS-1$
buffer.append(vmd.getValidatorUniqueName());
buffer.append("\n"); //$NON-NLS-1$
@@ -1142,9 +1032,7 @@
buffer.append("Enable/disable validator by default"); //$NON-NLS-1$
buffer.append("\n"); //$NON-NLS-1$
- viterator = _indexedValidators.values().iterator();
- while (viterator.hasNext()) {
- ValidatorMetaData vmd = (ValidatorMetaData) viterator.next();
+ for (ValidatorMetaData vmd : _indexedValidators.values()) {
buffer.append(vmd.getValidatorUniqueName());
buffer.append(" enabled? "); //$NON-NLS-1$
buffer.append(vmd.isEnabledByDefault());
@@ -1155,26 +1043,27 @@
}
public boolean isConfiguredOnProject(ValidatorMetaData vmd, IProject project) {
- if (projectValidationMetaData == null)
- projectValidationMetaData = new HashMap();
-
- Object vmds = projectValidationMetaData.get(project);
+ Set<ValidatorMetaData> vmds = null;
+ synchronized(projectValidationMetaData){
+ vmds = projectValidationMetaData.get(project);
+ }
if (vmds != null) {
- Set pvmds = (Set) vmds;
- return pvmds.contains(vmd);
+ return vmds.contains(vmd);
} else {
- Set prjVmds = getValidatorMetaData(project);
- if (prjVmds == null) {
- return false;
+ Set<ValidatorMetaData> prjVmds = getValidatorMetaData(project);
+ if (prjVmds == null || prjVmds.size() == 0)return false;
+ synchronized(projectValidationMetaData){
+ projectValidationMetaData.put(project, prjVmds);
}
-
- if (prjVmds.size() == 0) {
- return false;
- }
- projectValidationMetaData.put(project, prjVmds);
return prjVmds.contains(vmd);
}
}
+
+ public void clearCachedMaps(){
+ synchronized(projectValidationMetaData){
+ projectValidationMetaData.clear();
+ }
+ }
/**
* Return a set of ValidatorMetaData which are configured on all projects or which run on any
@@ -1184,10 +1073,10 @@
*
* @see addExcludedRemainder()
*/
- private Set getValidatorMetaDataUnknownProject() {
- Set projVmds = (Set) _validators.get(UNKNOWN_PROJECT);
+ private Set<ValidatorMetaData> getValidatorMetaDataUnknownProject() {
+ Set<ValidatorMetaData> projVmds = _validators.get(UNKNOWN_PROJECT);
if (projVmds == null) {
- projVmds = Collections.EMPTY_SET;
+ projVmds = new HashSet<ValidatorMetaData>();
}
return projVmds;
}
@@ -1195,8 +1084,8 @@
/**
* Return a set of ValidatorMetaData which are enabled by default.
*/
- public Set getValidatorMetaDataEnabledByDefault() {
- Set copy = new HashSet();
+ public Set<ValidatorMetaData> getValidatorMetaDataEnabledByDefault() {
+ Set<ValidatorMetaData> copy = new HashSet<ValidatorMetaData>();
clone(_defaultEnabledValidators, copy);
return copy;
}
@@ -1218,34 +1107,21 @@
* any code not in this package.
*/
public ValidatorMetaData getValidatorMetaData(String validatorClassName) {
- if (validatorClassName == null) {
- return null;
- }
+ if (validatorClassName == null)return null;
- ValidatorMetaData vmd = (ValidatorMetaData) _indexedValidators.get(validatorClassName);
- if (vmd != null) {
- return vmd;
- }
+ ValidatorMetaData vmd2 = _indexedValidators.get(validatorClassName);
+ if (vmd2 != null)return vmd2;
// Check for an aggregate validator
- Iterator iterator = _indexedValidators.values().iterator();
- while (iterator.hasNext()) {
- vmd = (ValidatorMetaData) iterator.next();
- if (vmd == null) {
- continue;
- }
+ for (ValidatorMetaData vmd : _indexedValidators.values()) {
+ if (vmd == null)continue;
- if (vmd.getValidatorUniqueName().equals(validatorClassName)) {
- return vmd;
- }
+ if (vmd.getValidatorUniqueName().equals(validatorClassName))return vmd;
String[] aggregateNames = vmd.getAggregatedValidatorNames();
if (aggregateNames != null) {
- for (int i = 0; i < aggregateNames.length; i++) {
- String aggregateName = aggregateNames[i];
- if (validatorClassName.equals(aggregateName)) {
- return vmd;
- }
+ for (String aggregateName : aggregateNames) {
+ if (validatorClassName.equals(aggregateName))return vmd;
}
}
@@ -1257,15 +1133,13 @@
continue;
}
- Set idList = mmd.getIds();
+ Set<String[]> idList = mmd.getIds();
if (idList == null) {
// Invalid <migrate> element.
continue;
}
- Iterator idIterator = idList.iterator();
- while (idIterator.hasNext()) {
- String[] ids = (String[]) idIterator.next();
+ for (String[] ids : idList) {
if (ids.length != 2) {
// log
continue;
@@ -1301,37 +1175,22 @@
private ValidatorMetaData initializeValidator(IConfigurationElement element, String validatorName, String pluginId) {
IConfigurationElement[] runChildren = element.getChildren(TAG_RUN_CLASS);
if ((runChildren == null) || (runChildren.length < 1)) {
- // How can an IValidatorImpl be created when there no class name to
- // instantiate?
- Logger logger = ValidationPlugin.getPlugin().getMsgLogger();
- if (logger.isLoggingLevel(Level.FINE)) {
- LogEntry entry = ValidationPlugin.getLogEntry();
- entry.setSourceID("ValidationRegistryReader.initializeValidator(IConfigurationElement, String, String)"); //$NON-NLS-1$
- entry.setMessageTypeID(ResourceConstants.VBF_EXC_SYNTAX_NO_VAL_RUN);
- //entry.setTokens(new String[]{validatorName});
- String result = MessageFormat.format(ResourceHandler.getExternalizedMessage(ResourceConstants.VBF_EXC_SYNTAX_NO_VAL_RUN),
- new String[]{validatorName});
- entry.setText(result);
-
- logger.write(Level.FINE, entry);
+ // How can an IValidatorImpl be created when there no class name to instantiate?
+ if (Tracing.isLogging()) {
+ Tracing.log("ValidationRegistryReader-07: ", NLS.bind(ValMessages.VbfExcSyntaxNoValRun, validatorName)); //$NON-NLS-1$
}
return null;
}
//WTP Bugzilla defect: 82338
- //Using the Unique Identifier give the flexibility of the same validator class used by other validator extentions without writing a new validation class
+ //Using the Unique Identifier give the flexibility of the same validator class used by other validator extensions without writing a new validation class
//Reverting the fix back as the class name defined in the ext is unique to this validator and has to be used for the unique id in the validation metadata
String validatorImplName = runChildren[0].getAttribute(ATT_CLASS);
if (validatorImplName == null) {
// Same as before; how can we instantiate when...
- Logger logger = ValidationPlugin.getPlugin().getMsgLogger();
- if (logger.isLoggingLevel(Level.FINE)) {
- LogEntry entry = ValidationPlugin.getLogEntry();
- entry.setSourceID("ValidationRegistryReader.initializeValidator(IConfigurationElement, String, String)"); //$NON-NLS-1$
- entry.setMessageTypeID(ResourceConstants.VBF_EXC_SYNTAX_NO_VAL_CLASS);
- entry.setTokens(new String[]{validatorName});
- logger.write(Level.FINE, entry);
+ if (Tracing.isLogging()) {
+ Tracing.log("ValidationRegistryReader-08: ", NLS.bind(ValMessages.VbfExcSyntaxNoValClass, validatorName)); //$NON-NLS-1$
}
return null;
}
@@ -1339,13 +1198,8 @@
String helperImplName = getHelperName(element);
if (helperImplName == null) {
// Same as before; how can we instantiate when...
- Logger logger = ValidationPlugin.getPlugin().getMsgLogger();
- if (logger.isLoggingLevel(Level.FINE)) {
- LogEntry entry = ValidationPlugin.getLogEntry();
- entry.setSourceID("ValidationRegistryReader.initializeValidator(IConfigurationElement, String, String)"); //$NON-NLS-1$
- entry.setMessageTypeID(ResourceConstants.VBF_EXC_SYNTAX_NO_VAL_RUN);
- entry.setTokens(new String[]{validatorImplName});
- logger.write(Level.FINE, entry);
+ if (Tracing.isLogging()) {
+ Tracing.log("ValidationRegistryReader-09: ", NLS.bind(ValMessages.VbfExcSyntaxNoValRun, validatorImplName)); //$NON-NLS-1$
}
return null;
}
@@ -1360,34 +1214,18 @@
//
// To load a String into the constants space, call intern() on the String.
//
- ValidatorMetaData vmd = new ValidatorMetaData();
- vmd.addFilters(getFilters(element)); // validator may, or may not, have filters
- vmd.addProjectNatureFilters(getProjectNatureFilters(element)); // validator may, or may not, specify a project nature
- vmd.addFacetFilters(getFacetIds(element));//validator may or may not specify the facet
- vmd.setEnablementElement(getEnablementElement(element));
- vmd.addAggregatedValidatorNames(getAggregateValidatorsNames(element)); // if a validator
- // aggregated another validator, it should identify
- // the sub-validator(s)' class name
- vmd.setValidatorDisplayName(validatorName.intern()); // validator must have a display name.
- vmd.setValidatorUniqueName(validatorImplName.intern());
- vmd.setPluginId(pluginId);
- vmd.setIncremental(getIncremental(element));
- vmd.setFullBuild(getFullBuild(element));
- vmd.setAsync(getAsync(element));
- vmd.setRuleGroup(getRuleGroup(element));
- vmd.setEnabledByDefault(getEnabledByDefault(element));
- vmd.setMigrationMetaData(getMigrationMetaData(element, vmd));
- vmd.setHelperClass(element, helperImplName);
- vmd.setValidatorClass(element); // associate the above attributes with the validator
- vmd.addDependentValidator(getDependentValidatorValue(element));
- initializeValidatorCustomMarkers(element, pluginId, vmd);
- Logger logger = ValidationPlugin.getPlugin().getMsgLogger();
- if (logger.isLoggingLevel(Level.FINEST)) {
- LogEntry entry = ValidationPlugin.getLogEntry();
- entry.setSourceID("ValidationRegistryReader.initializeValidator(IConfigurationElement, String, String)"); //$NON-NLS-1$
- entry.setText("validator loaded: " + validatorImplName); //$NON-NLS-1$
- logger.write(Level.FINEST, entry);
+ boolean async = getAsync(element);
+ String[] markerIds = initializeValidatorCustomMarkers(element, pluginId);
+ ValidatorMetaData vmd = new ValidatorMetaData(async, getAggregateValidatorsNames(element), getEnabledByDefault(element),
+ getIncremental(element), getFullBuild(element), element, helperImplName, getMigrationMetaData(element),
+ pluginId, getRuleGroup(element), runChildren[0], validatorName.intern(), validatorImplName.intern(),
+ getContentTypeBindings(element), getDependentValidatorValue(element), getEnablementElement(element),
+ getFacetIds(element), getFilters(element), getProjectNatureFilters(element), markerIds);
+
+
+ if (Tracing.isTraceV1()) {
+ Tracing.log("ValidationRegistryReader-10: validator loaded: " + validatorImplName); //$NON-NLS-1$
}
return vmd;
@@ -1398,24 +1236,25 @@
* @param pluginId
* @param vmd
*/
- private void initializeValidatorCustomMarkers(IConfigurationElement element, String pluginId, ValidatorMetaData vmd) {
+ private String[] initializeValidatorCustomMarkers(IConfigurationElement element, String pluginId) {
+ String[] qualifiedMarkerIds = null;
String[] customMarkerIds = getMarkerIdsValue(element);
if (customMarkerIds != null && customMarkerIds.length > 0) {
- String[] qualifiedMarkerIds = new String[customMarkerIds.length];
+ qualifiedMarkerIds = new String[customMarkerIds.length];
for (int i = 0; i < customMarkerIds.length; i++) {
String markerid = customMarkerIds[i];
- if (markerid.lastIndexOf(".") != -1) {
- String pluginID = markerid.substring(0, markerid.lastIndexOf("."));
+ if (markerid.lastIndexOf(".") != -1) { //$NON-NLS-1$
+ String pluginID = markerid.substring(0, markerid.lastIndexOf(".")); //$NON-NLS-1$
Bundle bundle = Platform.getBundle(pluginID);
if (bundle == null)
- qualifiedMarkerIds[i] = pluginId + "." + customMarkerIds[i];
+ qualifiedMarkerIds[i] = pluginId + "." + customMarkerIds[i]; //$NON-NLS-1$
else
qualifiedMarkerIds[i] = customMarkerIds[i];
} else
- qualifiedMarkerIds[i] = pluginId + "." + customMarkerIds[i];
+ qualifiedMarkerIds[i] = pluginId + "." + customMarkerIds[i]; //$NON-NLS-1$
}
- vmd.setMarkerIds(qualifiedMarkerIds); //$NON-NLS-1$
}
+ return qualifiedMarkerIds;
}
private Expression getEnablementElement(IConfigurationElement element) {
@@ -1424,8 +1263,8 @@
return null;
try {
return ExpressionConverter.getDefault().perform(enablements[0]);
- } catch (CoreException ce) {
- Logger.getLogger().log(ce);
+ } catch (CoreException e) {
+ ValidationPlugin.getPlugin().handleException(e);
}
return null;
}
@@ -1434,8 +1273,8 @@
* This method should be called ONLY BY THE VALIDATION FRAMEWORK! The value from this method is
* used to populate the validation preference page.
*/
- public Collection getAllValidators() {
- Set validators = new HashSet();
+ public Collection<ValidatorMetaData> getAllValidators() {
+ Set<ValidatorMetaData> validators = new HashSet<ValidatorMetaData>(50);
clone(_indexedValidators.values(), validators);
return validators;
}
@@ -1455,29 +1294,25 @@
String label = extension.getLabel();
if (label == null || label.equals("")) { //$NON-NLS-1$
- Logger logger = ValidationPlugin.getPlugin().getMsgLogger();
- if (logger.isLoggingLevel(Level.FINE)) {
+ if (Tracing.isTraceV1()) {
String[] msgParm = {extension.getUniqueIdentifier()};
- LogEntry entry = ValidationPlugin.getLogEntry();
- entry.setSourceID("ValidationRegistryReader.readExtension(IExtension)"); //$NON-NLS-1$
- entry.setMessageTypeID(ResourceConstants.VBF_EXC_VALIDATORNAME_IS_NULL);
- //entry.setTokens(msgParm);
String result = MessageFormat.format(ResourceHandler.getExternalizedMessage(ResourceConstants.VBF_EXC_VALIDATORNAME_IS_NULL),
- msgParm);
- entry.setText(result);
- logger.write(Level.FINE, entry);
+ (Object[])msgParm);
+ Tracing.log("ValidationRegistryReader-11: ", result); //$NON-NLS-1$
}
} else {
// If getLabel() returns an empty string, this is an illegal validator.
// The PropertyPage, and other status messages, need to have a displayable name for
// the validator.
- String pluginId = extension.getNamespace();
- ValidatorMetaData vmd = initializeValidator(element, label, pluginId);
-
- if (vmd != null) {
- // Add this validator to the list of validators; if vmd is null, the validator
- // couldn't be created.
- add(vmd);
+ String pluginId = extension.getContributor().getName();
+ if (Tracing.isEnabled(extension.getUniqueIdentifier())){
+ ValidatorMetaData vmd = initializeValidator(element, label, pluginId);
+
+ if (vmd != null) {
+ // Add this validator to the list of validators; if vmd is null, the validator
+ // couldn't be created.
+ add(vmd);
+ }
}
}
}
@@ -1509,10 +1344,10 @@
}
public IValidator getValidator(String validatorClassName) throws InstantiationException {
- ValidatorMetaData vmd = (ValidatorMetaData) _indexedValidators.get(validatorClassName);
+ ValidatorMetaData vmd = _indexedValidators.get(validatorClassName);
if(vmd != null)
return vmd.getValidator();
return null;
}
-}
\ No newline at end of file
+}
diff --git a/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/ValidationSelectionHandlerRegistryReader.java b/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/ValidationSelectionHandlerRegistryReader.java
index 3876c4e..cf3ce9a 100644
--- a/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/ValidationSelectionHandlerRegistryReader.java
+++ b/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/ValidationSelectionHandlerRegistryReader.java
@@ -1,42 +1,38 @@
-/*
- * Created on Nov 23, 2004
+/*******************************************************************************
+ * Copyright (c) 2001, 2008 IBM Corporation 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
*
- * TODO To change the template for this generated file go to
- * Window - Preferences - Java - Code Style - Code Templates
- */
+ * Contributors:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
package org.eclipse.wst.validation.internal;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.core.runtime.IConfigurationElement;
-import org.eclipse.jem.util.RegistryReader;
+import org.eclipse.core.runtime.IExtension;
+import org.eclipse.core.runtime.IExtensionPoint;
+import org.eclipse.core.runtime.IStatus;
+import org.eclipse.core.runtime.Platform;
import org.eclipse.wst.validation.internal.plugin.ValidationPlugin;
-/*******************************************************************************
- * Copyright (c) 2001, 2004 IBM Corporation 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-public class ValidationSelectionHandlerRegistryReader extends RegistryReader {
+public class ValidationSelectionHandlerRegistryReader {
public static final String VALIDATION_SELECTION_HANDLER = "validationSelectionHandler"; //$NON-NLS-1$
static final String ATT_ID = "id"; //$NON-NLS-1$
- static final String ATT_HANDLER_CLASS = "handlerClass"; //$NON-NLS-1$
- static final String ATT_SELECTION_TYPE = "selectionType"; //$NON-NLS-1$
- private static ValidationSelectionHandlerRegistryReader INSTANCE = null;
- private List validationSelectionHandlers = null;
- /**
- * Default constructor
- */
+ /** handlerClass - */
+ static final String ATT_HANDLER_CLASS = "handlerClass"; //$NON-NLS-1$
+
+ static final String ATT_SELECTION_TYPE = "selectionType"; //$NON-NLS-1$
+ private static ValidationSelectionHandlerRegistryReader INSTANCE;
+ private List<IValidationSelectionHandler> _validationSelectionHandlers;
+
public ValidationSelectionHandlerRegistryReader() {
- super(ValidationPlugin.PLUGIN_ID, VALIDATION_SELECTION_HANDLER);
}
public static ValidationSelectionHandlerRegistryReader getInstance() {
@@ -47,6 +43,36 @@
return INSTANCE;
}
+ /**
+ * Read the extension point and parse it.
+ */
+ public void readRegistry() {
+ IExtensionPoint point = Platform.getExtensionRegistry()
+ .getExtensionPoint(ValidationPlugin.PLUGIN_ID, VALIDATION_SELECTION_HANDLER);
+ if (point == null)return;
+ IConfigurationElement[] elements = point.getConfigurationElements();
+ for (int i = 0; i < elements.length; i++) {
+ internalReadElement(elements[i]);
+ }
+ }
+
+ private void internalReadElement(IConfigurationElement element) {
+ boolean recognized = this.readElement(element);
+ if (!recognized) {
+ logError(element, "Error processing extension: " + element); //$NON-NLS-1$
+ }
+ }
+
+ /*
+ * Logs the error in the desktop log using the provided text and the information in the configuration element.
+ */
+ protected void logError(IConfigurationElement element, String text) {
+ IExtension extension = element.getDeclaringExtension();
+ StringBuffer buf = new StringBuffer();
+ buf.append("Plugin " + extension.getContributor().getName() + ", extension " + extension.getExtensionPointUniqueIdentifier()); //$NON-NLS-1$ //$NON-NLS-2$
+ buf.append("\n" + text); //$NON-NLS-1$
+ ValidationPlugin.getPlugin().logMessage(IStatus.ERROR, buf.toString());
+ }
/* (non-Javadoc)
@@ -71,19 +97,17 @@
return false;
}
- private List getValidationSelectionHandlers() {
- if (validationSelectionHandlers == null)
- validationSelectionHandlers = new ArrayList();
- return validationSelectionHandlers;
+ private List<IValidationSelectionHandler> getValidationSelectionHandlers() {
+ if (_validationSelectionHandlers == null)
+ _validationSelectionHandlers = new ArrayList<IValidationSelectionHandler>();
+ return _validationSelectionHandlers;
}
public Object getExtendedType(Object selection) {
Object result = null;
- for (int i=0; i<getValidationSelectionHandlers().size(); i++ ) {
- IValidationSelectionHandler handler = (IValidationSelectionHandler) getValidationSelectionHandlers().get(i);
+ for (IValidationSelectionHandler handler : getValidationSelectionHandlers()) {
result = handler.getBaseValidationType(selection);
- if (result != null)
- break;
+ if (result != null)break;
}
return result;
}
diff --git a/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/ValidatorFilter.java b/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/ValidatorFilter.java
index 8035a0c..d51a217 100644
--- a/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/ValidatorFilter.java
+++ b/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/ValidatorFilter.java
@@ -1,10 +1,10 @@
/*******************************************************************************
- * Copyright (c) 2001, 2004 IBM Corporation and others.
+ * Copyright (c) 2001, 2007 IBM Corporation 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:
* IBM Corporation - initial API and implementation
*******************************************************************************/
@@ -12,26 +12,24 @@
import org.eclipse.core.resources.IResource;
-
-
/**
* This class represents the plugin.xml tags, for a validator, for both name filters and type
* filters. i.e., if an object has name filter and type filter specified, the filter filters out
* objects which are not both of that type and named like the filter.
*/
public class ValidatorFilter {
- private ValidatorNameFilter _nameFilter = null;
- private ValidatorTypeFilter _typeFilter = null;
- private ValidatorActionFilter _actionFilter = null;
+ private ValidatorNameFilter _nameFilter;
+ private ValidatorTypeFilter _typeFilter;
+ private ValidatorActionFilter _actionFilter;
- /* package */ValidatorFilter() {
+ ValidatorFilter() {
super();
_nameFilter = new ValidatorNameFilter();
_typeFilter = new ValidatorTypeFilter();
_actionFilter = new ValidatorActionFilter();
}
- /* package */ValidatorFilter(String mustImplementClass) {
+ ValidatorFilter(String mustImplementClass) {
this();
_nameFilter = new ValidatorNameFilter();
_typeFilter.setMustImplementClass(mustImplementClass);
@@ -48,7 +46,7 @@
* e.g. if the name filter is "*.java", and this resource is "readme.txt", this method will
* return false. If the resource is named "readme.java", this method will return true.
*/
- /* package */boolean isApplicableName(IResource resource) {
+ boolean isApplicableName(IResource resource) {
return _nameFilter.isApplicableName(resource);
}
@@ -58,7 +56,7 @@
* e.g. if the type filter is "IFile", and this resource is "IProject", this method will return
* false. If the resource is an IFile, this method will return true.
*/
- /* package */boolean isApplicableType(IResource resource) {
+ boolean isApplicableType(IResource resource) {
return _typeFilter.isApplicableType(resource);
}
@@ -69,7 +67,7 @@
/**
* Sets the name filter.
*/
- /* package */void setNameFilter(String filter, String isCaseSensitiveString) {
+ void setNameFilter(String filter, String isCaseSensitiveString) {
_nameFilter.setNameFilter(filter);
if(filter != null)
_nameFilter.setNameFilterExtension(getFilterExt(filter));
@@ -77,14 +75,14 @@
}
private String getFilterExt(String filter) {
- return filter.substring(filter.indexOf(".") + 1);
+ return filter.substring(filter.indexOf(".") + 1); //$NON-NLS-1$
}
/**
* Sets the type filter.
*/
- /* package */void setTypeFilter(String filter) {
+ void setTypeFilter(String filter) {
_typeFilter.setTypeFilter(filter);
}
@@ -108,4 +106,4 @@
public ValidatorNameFilter get_nameFilter() {
return _nameFilter;
}
-}
\ No newline at end of file
+}
diff --git a/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/ValidatorMetaData.java b/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/ValidatorMetaData.java
index d5a101d..90da739 100644
--- a/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/ValidatorMetaData.java
+++ b/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/ValidatorMetaData.java
@@ -1,10 +1,10 @@
/*******************************************************************************
- * Copyright (c) 2001, 2004 IBM Corporation and others.
+ * Copyright (c) 2001, 2008 IBM Corporation 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:
* IBM Corporation - initial API and implementation
*******************************************************************************/
@@ -18,19 +18,22 @@
import java.util.List;
import java.util.Map;
import java.util.Set;
+import java.util.concurrent.atomic.AtomicReference;
import org.eclipse.core.expressions.Expression;
import org.eclipse.core.resources.IContainer;
+import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
+import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IConfigurationElement;
import org.eclipse.core.runtime.Platform;
-import org.eclipse.jem.util.logger.proxy.Logger;
+import org.eclipse.core.runtime.content.IContentDescription;
+import org.eclipse.core.runtime.content.IContentType;
import org.eclipse.wst.validation.internal.delegates.ValidatorDelegatesRegistry;
import org.eclipse.wst.validation.internal.operations.IWorkbenchContext;
import org.eclipse.wst.validation.internal.operations.WorkbenchContext;
import org.eclipse.wst.validation.internal.plugin.ValidationHelperRegistryReader;
-import org.eclipse.wst.validation.internal.plugin.ValidationPlugin;
import org.eclipse.wst.validation.internal.provisional.core.IValidator;
import org.eclipse.wst.validation.internal.provisional.core.IValidatorJob;
import org.osgi.framework.Bundle;
@@ -41,82 +44,82 @@
* ValidatorMetaData; it is for use by the base framework only.
*/
public class ValidatorMetaData {
- private ValidatorFilter[] _filters = null;
- private ValidatorNameFilter[] _projectNatureFilters = null;
- private String[] facetFilters = null;
- private IValidator _validator = null;
- private IWorkbenchContext _helper = null;
- private String _validatorDisplayName = null;
- private String _validatorUniqueName = null;
- private String[] _aggregatedValidators = null;
- private String[] _validatorNames = null;
- private String _pluginId = null;
- private boolean _supportsIncremental = RegistryConstants.ATT_INCREMENTAL_DEFAULT;
- private boolean _supportsFullBuild = RegistryConstants.ATT_FULLBUILD_DEFAULT;
- private Logger _logger = null;
- private boolean _isEnabledByDefault = RegistryConstants.ATT_ENABLED_DEFAULT;
- private MigrationMetaData _migrationMetaData = null;
- private int _ruleGroup = RegistryConstants.ATT_RULE_GROUP_DEFAULT;
- private boolean _async = RegistryConstants.ATT_ASYNC_DEFAULT;
- private boolean dependentValidator = RegistryConstants.DEP_VAL_VALUE_DEFAULT;
- private String[] markerIds = null;
- private String _helperClassName = null;
- private IConfigurationElement _helperClassElement = null;
- private IConfigurationElement _validatorClassElement = null;
- private boolean _cannotLoad = false;
- private boolean manualValidation = true;
- private boolean buildValidation = true;
- private Map helpers = Collections.synchronizedMap( new HashMap() );
- private Expression enablementExpression = null;
-
- /* package */ValidatorMetaData() {
- //default
- }
-
+ private final ValidatorFilter[] _filters;
+ private final ValidatorNameFilter[] _projectNatureFilters;
+ private final String[] _facetFilters;
+ private final AtomicReference<IValidator> _validator = new AtomicReference<IValidator>();
+ private final AtomicReference<IWorkbenchContext> _helper = new AtomicReference<IWorkbenchContext>();
+ private final String _validatorDisplayName;
+ private final String _validatorUniqueName;
+
/**
- * Add to the list of class names of every validator which this validator aggregates. For
+ * The list of class names of every validator which this validator aggregates. For
* example, if the EJB Validator instantiated another validator, and started its validate
* method, then that instantiated class' name should be in this list.
*/
- /* package */void addAggregatedValidatorNames(String[] val) {
- _aggregatedValidators = val;
- }
+ private final String[] _aggregatedValidators;
+ private final String[] _contentTypeIds;
+ private final String[] _validatorNames;
+ private final String _pluginId;
+ private final boolean _supportsIncremental;
+ private final boolean _supportsFullBuild;
+ private final boolean _isEnabledByDefault;
+ private final MigrationMetaData _migrationMetaData;
+ private final int _ruleGroup;
+ private final boolean _async;
+ private final boolean _dependentValidator;
+ private final String[] _markerIds;
+ private final String _helperClassName;
+ private final IConfigurationElement _helperClassElement;
+ private final IConfigurationElement _validatorClassElement;
+ private volatile boolean _cannotLoad;
+ private volatile boolean _manualValidation = true;
+ private volatile boolean _buildValidation = true;
+ private final Map<IValidatorJob, IWorkbenchContext> _helpers =
+ Collections.synchronizedMap( new HashMap<IValidatorJob, IWorkbenchContext>() );
+ private final Expression _enablementExpression;
- /**
- * Add the name/type filter pair(s).
- */
- /* package */void addFilters(ValidatorFilter[] filters) {
+ ValidatorMetaData(boolean async, String[] aggregatedValidators, boolean isEnabledByDefault, boolean supportsIncremental,
+ boolean supportsFullBuild, IConfigurationElement helperClassElement, String helperClassName,
+ MigrationMetaData migrationMetaData, String pluginId, int ruleGroup, IConfigurationElement validatorClassElement,
+ String validatorDisplayName, String validatorUniqueName, String[] contentTypeIds, boolean dependentValidator,
+ Expression enablementExpression, String[] facetFilters, ValidatorFilter[] filters,
+ ValidatorNameFilter[] projectNatureFilters, String[] markerIds) {
+ _async = async;
+ _aggregatedValidators = aggregatedValidators;
+ _isEnabledByDefault = isEnabledByDefault;
+ _supportsIncremental = supportsIncremental;
+ _supportsFullBuild = supportsFullBuild;
+ _helperClassElement = helperClassElement;
+ _helperClassName = helperClassName;
+ _migrationMetaData = migrationMetaData;
+ _pluginId = pluginId;
+ _ruleGroup = ruleGroup;
+ _validatorClassElement = validatorClassElement;
+ _validatorDisplayName = validatorDisplayName;
+ _validatorUniqueName = validatorUniqueName;
+ _contentTypeIds = contentTypeIds;
+ _dependentValidator = dependentValidator;
+ _enablementExpression = enablementExpression;
+ _facetFilters = facetFilters;
_filters = filters;
+ _projectNatureFilters = projectNatureFilters;
+ _markerIds = markerIds;
+ _validatorNames = buildValidatorNames();
}
-
- /**
- * Add the project nature filter(s).
- */
- /* package */void addProjectNatureFilters(ValidatorNameFilter[] filters) {
- _projectNatureFilters = filters;
- }
-
- /**
- * Add the facet filter(s).
- */
- protected void addFacetFilters(String[] filters) {
- facetFilters = filters;
- }
-
+
protected String[] getFacetFilters() {
- return facetFilters;
+ return _facetFilters;
}
- public List getNameFilters() {
- List nameFilters = new ArrayList();
+ public List<String> getNameFilters() {
+ List<String> nameFilters = new ArrayList<String>();
if (_filters != null && _filters.length > 0) {
- for (int i = 0; i < _filters.length; i++) {
- ValidatorFilter filter = _filters[i];
+ for (ValidatorFilter filter : _filters) {
ValidatorNameFilter nameFilter = filter.get_nameFilter();
if (nameFilter != null) {
nameFilters.add(nameFilter.getNameFilter());
}
-
}
}
return nameFilters;
@@ -126,16 +129,18 @@
* Return the list of class names of the primary validator and its aggregates.
*/
public String[] getValidatorNames() {
- if (_validatorNames == null) {
- int aLength = (_aggregatedValidators == null) ? 0 : _aggregatedValidators.length;
- _validatorNames = new String[aLength + 1]; // add 1 for the primary validator name
- _validatorNames[0] = getValidatorUniqueName();
- if (_aggregatedValidators != null) {
- System.arraycopy(_aggregatedValidators, 0, _validatorNames, 1, aLength);
- }
- }
return _validatorNames;
}
+
+ private String[] buildValidatorNames() {
+ int aLength = (_aggregatedValidators == null) ? 0 : _aggregatedValidators.length;
+ String [] validatorNames = new String[aLength + 1]; // add 1 for the primary validator name
+ validatorNames[0] = getValidatorUniqueName();
+ if (_aggregatedValidators != null) {
+ System.arraycopy(_aggregatedValidators, 0, validatorNames, 1, aLength);
+ }
+ return validatorNames;
+ }
/**
* Return the list of class names of every validator which this validator aggregates. For
@@ -191,30 +196,25 @@
//TODO just want to remember to figure out the many-temporary-objects problem if this method
// continues to new an IValidationContext every time - Ruth
public IWorkbenchContext getHelper(IProject project) throws InstantiationException {
- if (_helper == null) {
- _helper = ValidationRegistryReader.createHelper(_helperClassElement, _helperClassName);
- if (_helper == null) {
- _helper = new WorkbenchContext();
- //setCannotLoad();
- //throw new InstantiationException(ResourceHandler.getExternalizedMessage(ResourceConstants.VBF_EXC_DISABLEH, new String[]{_helperClassName, getValidatorUniqueName()}));
- }
- // Won't be using the element & name again, so clear them.
- //_helperClassElement = null;
- //_helperClassName = null;
+ IWorkbenchContext helper = _helper.get();
+ if (helper != null){
+ IProject oldProject = helper.getProject();
+ if ((oldProject == null) || !(oldProject.equals(project)))helper.setProject(project);
+ return helper;
}
- if ((_helper.getProject() == null) || !(_helper.getProject().equals(project))) {
- // Initialize helper with the new project
- _helper.setProject(project);
+
+ helper = ValidationRegistryReader.createHelper(_helperClassElement, _helperClassName);
+ if (helper == null)helper = new WorkbenchContext();
+
+ if ((helper.getProject() == null) || !(helper.getProject().equals(project))) {
+ helper.setProject(project);
}
- return _helper;
+ if (_helper.compareAndSet(null, helper))return helper;
+ return _helper.get();
}
/**
* cannotLoad is false if both the IValidator and IWorkbenchContext instance can be instantiated.
- * This method should be called only by the validation framework, and only if an
- * InstantiationException was thrown.
- *
- * @param can
*/
private void setCannotLoad() {
_cannotLoad = true;
@@ -229,23 +229,6 @@
return _cannotLoad;
}
- /**
- * This method must not be called until the unique id of the validator has been initialized.
- */
- public Logger getMsgLogger() {
- if (_logger == null) {
- _logger = ValidationPlugin.getPlugin().getMsgLogger();
- /*
- * // Decided against having a logger for each validator because each validator // would
- * need to contribute an extension in their plugins for it to be recognized // by the
- * logging preference page. For now, just use the validation framework's logger. _logger =
- * (MsgLogger)MsgLogger.getFactory().getLogger(getValidatorUniqueName());
- * _logger.write(Level.CONFIG, getValidatorDisplayName());
- */
- }
- return _logger;
- }
-
public MigrationMetaData getMigrationMetaData() {
return _migrationMetaData;
}
@@ -260,7 +243,7 @@
/**
* Return the filters which identify which project(s) this validator may run on.
*/
- /* package */ValidatorNameFilter[] getProjectNatureFilters() {
+ ValidatorNameFilter[] getProjectNatureFilters() {
return _projectNatureFilters;
}
@@ -268,23 +251,19 @@
* This method returns the validator if it can be loaded; if the validator cannot be loaded,
* e.g., if its plugin is disabled for some reason, then this method throws an
* InstantiationException. Before the CoreException is thrown, this validator is disabled.
- *
- * @return IValidator
- * @throws InstantiationException
*/
public IValidator getValidator() throws InstantiationException {
- if (_validator == null) {
- _validator = ValidationRegistryReader.createValidator(_validatorClassElement, getValidatorUniqueName());
+ IValidator val = _validator.get();
+ if (val != null)return val;
+
+ val = ValidationRegistryReader.createValidator(_validatorClassElement, getValidatorUniqueName());
- // Since the element won't be used any more, clear it.
- //_validatorClassElement = null;
-
- if (_validator == null) {
- setCannotLoad();
- throw new InstantiationException(ResourceHandler.getExternalizedMessage(ResourceConstants.VBF_EXC_DISABLEV, new String[]{getValidatorUniqueName()}));
- }
+ if (val == null) {
+ setCannotLoad();
+ throw new InstantiationException(ResourceHandler.getExternalizedMessage(ResourceConstants.VBF_EXC_DISABLEV, new String[]{getValidatorUniqueName()}));
}
- return _validator;
+ if (_validator.compareAndSet(null, val))return val;
+ return _validator.get();
}
public String getValidatorDisplayName() {
@@ -314,9 +293,9 @@
*/
public boolean isApplicableTo(IResource resource, int resourceDelta) {
// If no filters are specified, then every type of resource should be validated/trigger a
- // rebuild of the model cache
- if (_filters == null)
- return true;
+ // rebuild of the model cache.
+ // Also make sure no content type id is specified (BUG 193816)
+ if (_filters == null && getContentTypeIds() == null)return true;
return isApplicableTo(resource, resourceDelta, _filters);
}
@@ -324,19 +303,29 @@
/**
* Return true if the resource passes the name/type filters for this validator.
*/
- /* package */boolean isApplicableTo(IResource resource, int resourceDelta, ValidatorFilter[] filters) {
+ boolean isApplicableTo(IResource resource, int resourceDelta, ValidatorFilter[] filters) {
// Are any of the filters satisfied? (i.e., OR them, not AND them.)
- if (checkIfValidSourceFile(resource)) {
- for (int i = 0; i < filters.length; i++) {
- ValidatorFilter filter = filters[i];
- if (filter.isApplicableType(resource) &&
- filter.isApplicableName(resource) &&
- filter.isApplicableAction(resourceDelta)){
+ // make sure filters is not null (BUG 193816)
+ if (filters != null && checkIfValidSourceFile(resource)) {
+ for (ValidatorFilter filter : filters) {
+ if (filter.isApplicableType(resource)
+ && filter.isApplicableName(resource)
+ && filter.isApplicableAction(resourceDelta)) {
return true;
- }
-
+ }
}
}
+ if (getContentTypeIds() != null) {
+ IContentDescription description = null;
+ try {
+ if (resource.getType() == IResource.FILE && resource.exists())
+ description = ((IFile) resource).getContentDescription();
+ } catch (CoreException e) {
+ //Resource exceptions
+ }
+ if (description == null)return false;
+ if (isApplicableContentType(description))return true;
+ }
return false;
}
@@ -420,129 +409,55 @@
return _async;
}
- /* package */void setHelperClass(IConfigurationElement element, String helperClassName) {
- _helperClassElement = element;
- _helperClassName = helperClassName;
- }
-
- /* package */void setEnabledByDefault(boolean enabledByDefault) {
- _isEnabledByDefault = enabledByDefault;
- }
-
- /* package */void setIncremental(boolean isIncremental) {
- _supportsIncremental = isIncremental;
- }
-
- /* package */void setFullBuild(boolean fullBuild) {
- _supportsFullBuild = fullBuild;
- }
-
- /* package */void setAsync(boolean isAsync) {
- _async = isAsync;
- }
-
- /* package */void setMigrationMetaData(MigrationMetaData mmd) {
- _migrationMetaData = mmd;
- }
-
- /* package */void setRuleGroup(int ruleGroup) {
- _ruleGroup = ruleGroup;
- }
-
- /* package */void setValidatorClass(IConfigurationElement element) {
- _validatorClassElement = element;
- // validator class name == validatorUniqueName
- }
-
- /* package */void setValidatorDisplayName(String validatorName) {
- _validatorDisplayName = validatorName;
- }
-
- /* package */void setValidatorUniqueName(String validatorUniqueName) {
- _validatorUniqueName = validatorUniqueName;
- }
-
- /* package */void setPluginId(String validatorPluginId) {
- _pluginId = validatorPluginId;
- }
-
public String toString() {
return getValidatorUniqueName();
}
- public class MigrationMetaData {
- private Set _ids = null;
+ public final static class MigrationMetaData {
+ private Set<String[]> _ids;
public MigrationMetaData() {
- //default
}
public void addId(String oldId, String newId) {
- if (oldId == null) {
- // log
- return;
- }
-
- if (newId == null) {
- // log
- return;
- }
+ if (oldId == null)return;
+ if (newId == null)return;
String[] ids = new String[]{oldId, newId};
getIds().add(ids);
}
- public Set getIds() {
- if (_ids == null) {
- _ids = new HashSet();
- }
+ public Set<String[]> getIds() {
+ if (_ids == null)_ids = new HashSet<String[]>();
return _ids;
}
}
- /**
- * @param b
- */
- public void addDependentValidator(boolean b) {
- dependentValidator = b;
- }
-
- /**
- * @param b
- */
public boolean isDependentValidator() {
- return dependentValidator;
+ return _dependentValidator;
}
/**
* @return Returns the markerId.
*/
public String[] getMarkerIds() {
- return markerIds;
- }
-
- /**
- * @param markerId
- * The markerId to set.
- */
- public void setMarkerIds(String[] markerId) {
- this.markerIds = markerId;
+ return _markerIds;
}
public boolean isBuildValidation() {
- return buildValidation;
+ return _buildValidation;
}
public void setBuildValidation(boolean buildValidation) {
- this.buildValidation = buildValidation;
+ _buildValidation = buildValidation;
}
public boolean isManualValidation() {
- return manualValidation;
+ return _manualValidation;
}
public void setManualValidation(boolean manualValidation) {
- this.manualValidation = manualValidation;
+ _manualValidation = manualValidation;
}
/**
@@ -569,15 +484,15 @@
}
public void addHelper( IValidatorJob validator, IWorkbenchContext helper ){
- helpers.put( validator, helper );
+ _helpers.put( validator, helper );
}
public void removeHelper( IValidatorJob validator ){
- helpers.remove( validator );
+ _helpers.remove( validator );
}
private IWorkbenchContext getHelper( IValidatorJob validator ){
- return (IWorkbenchContext)helpers.get( validator );
+ return _helpers.get( validator );
}
public IWorkbenchContext getHelper( IProject project, IValidator validator ){
@@ -607,12 +522,25 @@
}
public Expression getEnablementExpresion() {
- return enablementExpression;
+ return _enablementExpression;
}
- public void setEnablementElement(Expression enablementElement) {
- enablementExpression = enablementElement;
+public String[] getContentTypeIds() {
+ return _contentTypeIds;
+}
+
+
+private boolean isApplicableContentType(IContentDescription desc){
+
+ IContentType ct = desc.getContentType();
+ String[] applicableContentTypes = getContentTypeIds();
+ if (applicableContentTypes != null) {
+ for (int i = 0; i < applicableContentTypes.length; i ++){
+ if(applicableContentTypes[i].equals(ct.getId()))
+ return true;
+ }
}
+ return false;
+}
-
-}
\ No newline at end of file
+}
diff --git a/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/ValidatorNameFilter.java b/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/ValidatorNameFilter.java
index f80648c..946cfba 100644
--- a/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/ValidatorNameFilter.java
+++ b/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/ValidatorNameFilter.java
@@ -1,10 +1,10 @@
/*******************************************************************************
- * Copyright (c) 2001, 2004 IBM Corporation and others.
+ * Copyright (c) 2001, 2007 IBM Corporation 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:
* IBM Corporation - initial API and implementation
*******************************************************************************/
@@ -20,8 +20,8 @@
* this class would store the "*.*", and provide the wildcard matching functionality.
*/
public class ValidatorNameFilter {
- private String _nameFilter = null;
- private String nameFilterExtension = null;
+ private String _nameFilter;
+ private String nameFilterExtension;
private boolean _include = true; // by default, filter in the IFile specified
private final static String WILDCARD = "*"; //$NON-NLS-1$
private boolean _isCaseSensitive = true; // by default, the filter name is case-sensitive
@@ -29,29 +29,29 @@
/**
* Insert the method's description here. Creation date: (12/4/00 11:08:41 AM)
*/
- /* package */ValidatorNameFilter() {
+ ValidatorNameFilter() {
//default
}
/**
* Get the filter, as specified in plugin.xml
*/
- /* package */String getNameFilter() {
+ String getNameFilter() {
return _nameFilter;
}
- /* package */boolean isCaseSensitive() {
+ boolean isCaseSensitive() {
return _isCaseSensitive;
}
- /* package */boolean isInclude() {
+ boolean isInclude() {
return _include;
}
/**
* Return true if the given resource is both applicable and include="true".
*/
- /* package */boolean isApplicableTo(IResource resource) {
+ boolean isApplicableTo(IResource resource) {
return (isApplicableName(resource) && isInclude());
}
@@ -75,12 +75,12 @@
if (name.equalsIgnoreCase(_nameFilter))
return true;
- int indexOfStarDot = _nameFilter.indexOf("*.");
+ int indexOfStarDot = _nameFilter.indexOf("*."); //$NON-NLS-1$
- //return value if the fileter name extension matches the extension
+ //return value if the filter name extension matches the extension
//of the resource
if (indexOfStarDot != -1) {
- String nameExtension = name.substring(name.lastIndexOf(".") + 1);
+ String nameExtension = name.substring(name.lastIndexOf(".") + 1); //$NON-NLS-1$
return nameFilterExtension.equalsIgnoreCase(nameExtension);
}
@@ -91,7 +91,7 @@
return verifyNameMatch(_nameFilter, name);
}
- /* package */void setInclude(String includeValue) {
+ void setInclude(String includeValue) {
if (includeValue != null) {
setInclude(Boolean.valueOf(includeValue).booleanValue());
}
@@ -104,11 +104,11 @@
/**
* Set the filter, as specified in plugin.xml
*/
- /* package */void setNameFilter(String filter) {
+ void setNameFilter(String filter) {
_nameFilter = filter;
}
- /* package */void setCaseSensitive(String isCaseSensitiveString) {
+ void setCaseSensitive(String isCaseSensitiveString) {
if (isCaseSensitiveString != null) {
// only change the value from the default if the case-sensitive attribute is defined
_isCaseSensitive = Boolean.valueOf(isCaseSensitiveString).booleanValue();
@@ -127,7 +127,7 @@
*
* The only filter wildcard allowed is '*'.
*/
- /* package */static boolean verifyNameMatch(final String filter, String name) {
+ static boolean verifyNameMatch(final String filter, String name) {
/*
* There are eight possible wildcard combinations, given that a wildcard may, if present, be
* at the beginning, middle, or end of a name; or any combination of those positions. i.e.,
@@ -167,4 +167,4 @@
}
return true;
}
-}
\ No newline at end of file
+}
diff --git a/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/ValidatorTypeFilter.java b/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/ValidatorTypeFilter.java
index 0f00ce3..f495aa6 100644
--- a/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/ValidatorTypeFilter.java
+++ b/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/ValidatorTypeFilter.java
@@ -1,22 +1,18 @@
/*******************************************************************************
- * Copyright (c) 2001, 2004 IBM Corporation and others.
+ * Copyright (c) 2001, 2008 IBM Corporation 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:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.wst.validation.internal;
import java.text.MessageFormat;
-import java.util.logging.Level;
import org.eclipse.core.resources.IResource;
-import org.eclipse.jem.util.logger.LogEntry;
-import org.eclipse.jem.util.logger.proxy.Logger;
-import org.eclipse.wst.validation.internal.plugin.ValidationPlugin;
/**
* Represents a type filter tag in a validator's plugin.xml file. e.g. <filter
@@ -24,17 +20,17 @@
* provide the "instanceof" matching functionality.
*/
public class ValidatorTypeFilter {
- private Class _typeFilterClass = null;
- private String _mustImplementClass = null; // the type set in setTypeFilter must implement the
+ private Class _typeFilterClass;
+ private String _mustImplementClass; // the type set in setTypeFilter must implement the
// class/interface identified by this fully-qualified
// Java string.
- /* package */ValidatorTypeFilter() {
+ ValidatorTypeFilter() {
//default
}
- /* package */ValidatorTypeFilter(String mustImplementClass) {
+ ValidatorTypeFilter(String mustImplementClass) {
setMustImplementClass(mustImplementClass);
}
@@ -42,14 +38,14 @@
* Type filters are allowed only for certain types of classes. This method returns the name of
* the class which this type must implement before it can be a filter.
*/
- /* package */String getMustImplementClass() {
+ String getMustImplementClass() {
return _mustImplementClass;
}
/**
* Return the type filter as a java.lang.Class object.
*/
- /* package */Class getTypeFilterClass() {
+ Class getTypeFilterClass() {
return _typeFilterClass;
}
@@ -71,7 +67,7 @@
/**
* Checks if filterClass is a parent (interface or superclass) of objectClass.
*/
- /* package */boolean isInstance(Class objectClass, Class filterClass) {
+ boolean isInstance(Class objectClass, Class filterClass) {
// The java.lang.Class.isInstance call doesn't check interfaces fully.
// i.e., if I have two interfaces, A and B, and B extends A but
// doesn't implement A, then the isInstance call will return false.
@@ -96,7 +92,7 @@
* Type filters are allowed only for certain types of classes. This method sets the name of the
* class which this type must implement before it can be a filter.
*/
- /* package */void setMustImplementClass(String className) {
+ void setMustImplementClass(String className) {
_mustImplementClass = className;
}
@@ -104,7 +100,7 @@
* If the filter implements the mustImplementClass (in ValidatorFilter's case, IResource), then
* this is a valid filter, and store the filter value.
*/
- /* package */void setTypeFilter(String filter) {
+ void setTypeFilter(String filter) {
Class filterClass = null;
Class mustImplementClass = null;
@@ -121,26 +117,19 @@
// If the filter class is not an instance of mustImplementClass
if (!isInstance(filterClass, mustImplementClass)) {
_typeFilterClass = null;
- Logger logger = ValidationPlugin.getPlugin().getMsgLogger();
- if (logger.isLoggingLevel(Level.FINE)) {
- LogEntry entry = ValidationPlugin.getLogEntry();
- entry.setSourceID("ValidatorTypeFilter.setTypeFilter(String)"); //$NON-NLS-1$
- entry.setMessageTypeID(ResourceConstants.VBF_EXC_INVALID_TYPE_FILTER);
- String result = MessageFormat.format(ResourceHandler.getExternalizedMessage(ResourceConstants.VBF_EXC_INVALID_TYPE_FILTER), new String[]{filter, getMustImplementClass()});
- entry.setText(result);
- //entry.setTokens(new String[]{filter, getMustImplementClass()});
- logger.write(Level.FINE, entry);
+ if (Tracing.isLogging()) {
+ String result = MessageFormat.format(ResourceHandler.getExternalizedMessage(ResourceConstants.VBF_EXC_INVALID_TYPE_FILTER),
+ new Object[]{filter, getMustImplementClass()});
+ Tracing.log("ValidatorTypeFilter-01: ", result); //$NON-NLS-1$
}
}
}
} catch (ClassNotFoundException exc) {
_typeFilterClass = null;
- Logger logger = ValidationPlugin.getPlugin().getMsgLogger();
- if (logger.isLoggingLevel(Level.FINE)) {
- LogEntry entry = ValidationPlugin.getLogEntry();
- entry.setSourceID("ValidatorTypeFilter.setTypeFilter(String)"); //$NON-NLS-1$
- entry.setText("The class named " + filter + " cannot be instantiated because it does not exist. Check the spelling of the name, in the validator's plugin.xml contribution, and try restarting eclipse again."); //$NON-NLS-1$ //$NON-NLS-2$
- logger.write(Level.FINE, entry);
+ if (Tracing.isLogging()) {
+ Tracing.log("ValidatorTypeFilter-02: The class named " + filter + //$NON-NLS-1$
+ " cannot be instantiated because it does not exist. Check the spelling of the name, " + //$NON-NLS-1$
+ "in the validator's plugin.xml contribution, and try restarting eclipse again."); //$NON-NLS-1$
}
return;
}
@@ -154,4 +143,4 @@
buffer.append(" _mustImplementClass = " + _mustImplementClass); //$NON-NLS-1$
return buffer.toString();
}
-}
\ No newline at end of file
+}
diff --git a/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/delegates/DelegatingValidator.java b/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/delegates/DelegatingValidator.java
index 0daf071..d143f9b 100644
--- a/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/delegates/DelegatingValidator.java
+++ b/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/delegates/DelegatingValidator.java
@@ -1,5 +1,5 @@
/*******************************************************************************
- * Copyright (c) 2006 IBM Corporation and others.
+ * Copyright (c) 2006, 2008 IBM Corporation 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
@@ -15,8 +15,13 @@
import java.util.List;
import org.eclipse.core.resources.IProject;
+import org.eclipse.core.resources.IResource;
+import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.jobs.ISchedulingRule;
+import org.eclipse.wst.validation.AbstractValidator;
+import org.eclipse.wst.validation.ValidationResult;
+import org.eclipse.wst.validation.ValidationState;
import org.eclipse.wst.validation.internal.ConfigurationManager;
import org.eclipse.wst.validation.internal.ProjectConfiguration;
import org.eclipse.wst.validation.internal.ResourceConstants;
@@ -50,11 +55,8 @@
* API will almost certainly be broken (repeatedly) as the API evolves.
* </p>
*/
-public class DelegatingValidator implements IDelegatingValidator
+public class DelegatingValidator extends AbstractValidator implements IDelegatingValidator
{
- /**
- * Default constructor.
- */
public DelegatingValidator()
{
}
@@ -78,7 +80,7 @@
*/
public void validate(IValidationContext helper, IReporter reporter) throws ValidationException
{
- // Apparently this method will not be called on an IValidatorJob.
+ validateInJob(helper, reporter);
}
/**
@@ -260,4 +262,9 @@
{
return null;
}
+
+@Override
+public ValidationResult validate(IResource resource, int kind, ValidationState state, IProgressMonitor monitor) {
+ return null;
+}
}
diff --git a/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/delegates/ValidatorDelegateDescriptor.java b/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/delegates/ValidatorDelegateDescriptor.java
index d8ba0be..51910e0 100644
--- a/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/delegates/ValidatorDelegateDescriptor.java
+++ b/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/delegates/ValidatorDelegateDescriptor.java
@@ -1,5 +1,5 @@
/*******************************************************************************
- * Copyright (c) 2006 IBM Corporation and others.
+ * Copyright (c) 2006, 2008 IBM Corporation 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
@@ -13,114 +13,142 @@
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IConfigurationElement;
+import org.eclipse.wst.validation.AbstractValidator;
import org.eclipse.wst.validation.internal.ResourceConstants;
import org.eclipse.wst.validation.internal.ResourceHandler;
import org.eclipse.wst.validation.internal.ValidationRegistryReader;
+import org.eclipse.wst.validation.internal.ValidatorMetaData;
import org.eclipse.wst.validation.internal.core.ValidationException;
import org.eclipse.wst.validation.internal.operations.LocalizedMessage;
+import org.eclipse.wst.validation.internal.plugin.ValidationPlugin;
import org.eclipse.wst.validation.internal.provisional.core.IMessage;
import org.eclipse.wst.validation.internal.provisional.core.IValidator;
/**
* ValidatorDelegateDescriptor stores information about a delegate validator.
- *
+ * <p>
* It is also used to store the instance of the validator it describes. To
* obtain the instance call getValidator().
+ * </p>
*/
-public class ValidatorDelegateDescriptor
-{
- /**
- * The platform configuration element describing this delegate.
- */
- private IConfigurationElement delegateConfiguration;
+public class ValidatorDelegateDescriptor {
+ /**
+ * The platform configuration element describing this delegate.
+ */
+ private IConfigurationElement _delegateConfiguration;
- /**
- * The delegating validator's ID.
- */
- private String delegatingValidatorID;
+ /**
+ * The delegating validator's ID.
+ */
+ private String _delegatingValidatorID;
- /**
- * The delegate's ID.
- */
- private String id;
+ /**
+ * The delegate's ID.
+ */
+ private String _id;
- /**
- * The delegate's display name.
- */
- private String name;
+ /**
+ * The delegate's display name.
+ */
+ private String _name;
- /**
- * Constructs a descriptor.
- *
- * @param id
- * the delegate's uniques id. Must be unique in the context of a
- * delegating validator.
- * @param delegateConfiguration
- * the delegates configuration element
- * @param delegateName
- * the delegate's display name.
- * @param targetValidatorID
- * the target validator's unique id.
- */
- public ValidatorDelegateDescriptor(String id, IConfigurationElement delegateConfiguration, String delegateName, String targetValidatorID)
- {
- this.id = id;
- this.delegateConfiguration = delegateConfiguration;
- this.name = delegateName;
- this.delegatingValidatorID = targetValidatorID;
- }
+ /**
+ * Constructs a descriptor.
+ *
+ * @param id
+ * The delegate's unique id. Must be unique in the context of a
+ * delegating validator.
+ * @param delegateConfiguration
+ * The delegates configuration element
+ * @param delegateName
+ * The delegate's display name.
+ * @param targetValidatorID
+ * The target validator's unique id.
+ */
+ public ValidatorDelegateDescriptor(String id,
+ IConfigurationElement delegateConfiguration, String delegateName,
+ String targetValidatorID) {
- /**
- * Provides the delegate's ID.
- *
- * @return a string with the fully qualified class name of this validator
- * implementation.
- */
- public String getId()
- {
- return id;
- }
+ assert id != null;
+ assert delegateConfiguration != null;
+ assert targetValidatorID != null;
- /**
- * Provides the delegate's name.
- *
- * @return a String with the validator's display name.
- */
- public String getName()
- {
- return name;
- }
+ _id = id;
+ _delegateConfiguration = delegateConfiguration;
+ _name = delegateName;
+ _delegatingValidatorID = targetValidatorID;
+ }
- /**
- * Retrieves the target validator's ID.
- *
- * @return a String with the fully qualified class name of the delegating
- * validator who will delegate its implementation to the validator
- * described by this descriptor.
- */
- public String getTargetID()
- {
- return delegatingValidatorID;
- }
+ /**
+ * Provides the delegate's ID.
+ *
+ * @return a string with the fully qualified class name of this validator
+ * implementation.
+ */
+ public String getId() {
+ return _id;
+ }
- /**
- * Provides the instance of the validator delegate pointed to by this
- * descriptor.
- *
- * @return an IValidator instance.
- * @throws ValidationException
- */
- public IValidator getValidator() throws ValidationException
- {
- try
- {
- IValidator delegate = (IValidator) delegateConfiguration.createExecutableExtension(ValidatorDelegatesRegistryReader.CLASS_ATTRIBUTE);
- return delegate;
- }
- catch (CoreException e)
- {
- String delegatingValidatorName = ValidationRegistryReader.getReader().getValidatorMetaData(getTargetID()).getValidatorDisplayName();
- throw new ValidationException(new LocalizedMessage(IMessage.HIGH_SEVERITY, ResourceHandler.getExternalizedMessage(ResourceConstants.VBF_CANNOT_INSTANTIATE_DELEGATE, new String[] { getName(), delegatingValidatorName })));
- }
- }
+ /**
+ * Provides the delegate's name.
+ *
+ * @return a String with the validator's display name.
+ */
+ public String getName() {
+ return _name;
+ }
+
+ /**
+ * Retrieves the target validator's ID.
+ *
+ * @return a String with the fully qualified class name of the delegating
+ * validator who will delegate its implementation to the validator
+ * described by this descriptor.
+ */
+ public String getTargetID() {
+ return _delegatingValidatorID;
+ }
+
+ /**
+ * Provides the instance of the validator delegate pointed to by this descriptor.
+ *
+ * @return an IValidator instance.
+ * @throws ValidationException
+ */
+ public IValidator getValidator() throws ValidationException {
+ try {
+ IValidator delegate = (IValidator) _delegateConfiguration
+ .createExecutableExtension(ValidatorDelegatesRegistryReader.CLASS_ATTRIBUTE);
+ return delegate;
+ } catch (CoreException e) {
+ handleException(e);
+ }
+ return null;
+ }
+
+ /**
+ * Answer an AbstractValidator if one has been defined, otherwise answer null.
+ */
+ public AbstractValidator getValidator2() throws ValidationException {
+ try {
+ Object o = _delegateConfiguration
+ .createExecutableExtension(ValidatorDelegatesRegistryReader.CLASS_ATTRIBUTE);
+ if (o instanceof AbstractValidator)
+ return (AbstractValidator) o;
+ } catch (CoreException e) {
+ handleException(e);
+ }
+ return null;
+ }
+
+ private void handleException(CoreException e) throws ValidationException {
+ ValidationPlugin.getPlugin().handleException(e);
+ String delegatingValidatorName = getTargetID();
+ ValidatorMetaData vmd = ValidationRegistryReader.getReader()
+ .getValidatorMetaData(getTargetID());
+ if (vmd != null)delegatingValidatorName = vmd.getValidatorDisplayName();
+ throw new ValidationException(new LocalizedMessage(
+ IMessage.HIGH_SEVERITY, ResourceHandler.getExternalizedMessage(
+ ResourceConstants.VBF_CANNOT_INSTANTIATE_DELEGATE, new String[] { getName(), delegatingValidatorName })));
+ }
}
diff --git a/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/delegates/ValidatorDelegatesRegistry.java b/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/delegates/ValidatorDelegatesRegistry.java
index 5169850..3ea034f 100644
--- a/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/delegates/ValidatorDelegatesRegistry.java
+++ b/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/delegates/ValidatorDelegatesRegistry.java
@@ -1,5 +1,5 @@
/*******************************************************************************
- * Copyright (c) 2006 IBM Corporation and others.
+ * Copyright (c) 2008 IBM Corporation 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
@@ -12,22 +12,29 @@
package org.eclipse.wst.validation.internal.delegates;
import java.util.HashMap;
+import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
+import java.util.Set;
+import java.util.StringTokenizer;
+import org.eclipse.core.runtime.preferences.DefaultScope;
+import org.eclipse.core.runtime.preferences.IEclipsePreferences;
+import org.eclipse.wst.validation.internal.ConfigurationConstants;
import org.eclipse.wst.validation.internal.core.ValidationException;
+import org.eclipse.wst.validation.internal.plugin.ValidationPlugin;
import org.eclipse.wst.validation.internal.provisional.core.IValidator;
/**
* ValidatorDelegatesRegistry is a singleton used to store validator delegate
* descriptors for each delegating validator.
*/
-public class ValidatorDelegatesRegistry
-{
+public class ValidatorDelegatesRegistry {
+
/**
* The one and only instance of this registry.
*/
- private static ValidatorDelegatesRegistry instance;
+ private static ValidatorDelegatesRegistry _instance;
/**
* Provides the one and only instance of this class.
@@ -38,45 +45,76 @@
*
* @return the validator delegates registry singleton instance.
*/
- public static ValidatorDelegatesRegistry getInstance()
- {
- if (instance == null)
- {
- instance = new ValidatorDelegatesRegistry();
-
- ValidatorDelegatesRegistryReader reader = new ValidatorDelegatesRegistryReader(instance);
- reader.readRegistry();
+ public static ValidatorDelegatesRegistry getInstance() {
+ if (_instance == null) {
+ ValidatorDelegatesRegistry instance = new ValidatorDelegatesRegistry();
+ ValidatorDelegatesRegistryReader reader = new ValidatorDelegatesRegistryReader(instance);
+ reader.readRegistry();
+ instance.initDefaults();
+ _instance = instance;
}
- return instance;
+ return _instance;
}
/**
+ * Determine if the product defined any default delegate validators, by setting the old
+ * DELEGATES_PREFERENCE preference in the default preference scope. If they did, we remember
+ * them, so that if we every need to return a default for the delegating validator, we can return the one
+ * that the product requested.
+ */
+ private void initDefaults() {
+ // This code was copied from the ValidationConfiguration#deserializeDelegates() method. The code was copied because this
+ // change is part of a patch and I didn't want to disturb the ValidationConfiguration class.
+
+ IEclipsePreferences prefs = new DefaultScope().getNode(ValidationPlugin.PLUGIN_ID);
+ String delegatePref = prefs.get("DELEGATES_PREFERENCE", null); //$NON-NLS-1$
+ if (delegatePref == null)return;
+
+ int delegatesIndex = delegatePref.indexOf(ConfigurationConstants.DELEGATE_VALIDATORS);
+ String delegates = delegatePref.substring(delegatesIndex + ConfigurationConstants.DELEGATE_VALIDATORS.length(), delegatePref.length());
+
+ if (delegates == null)return;
+
+ _defaultDelegates = new HashSet<String>(10);
+ StringTokenizer tokenizer = new StringTokenizer(delegates, ConfigurationConstants.ELEMENT_SEPARATOR);
+ while (tokenizer.hasMoreTokens()) {
+ String delegateConfiguration = tokenizer.nextToken();
+ int separatorIndex = delegateConfiguration.indexOf(ConfigurationConstants.DELEGATES_SEPARATOR);
+// String targetID = delegateConfiguration.substring(0, separatorIndex);
+ String delegateID = delegateConfiguration.substring(separatorIndex + 1);
+ _defaultDelegates.add(delegateID);
+ }
+
+ }
+
+/**
* The map of target validator id to Map of delegates by id.
*/
- private Map delegatesByTarget = new HashMap();
+ private Map<String, Map<String,ValidatorDelegateDescriptor>> _delegatesByTarget =
+ new HashMap<String, Map<String,ValidatorDelegateDescriptor>>();
+
+ /**
+ * Validator ids that have been defined by the product to be the default validators, for some of the delegating validtors.
+ */
+ private Set<String> _defaultDelegates;
/**
* Adds a descriptor to the registry.
*
* @param descriptor
- * the descriptor to add. Must not be null.
+ * The descriptor to add. Must not be null.
*/
- void add(ValidatorDelegateDescriptor descriptor)
- {
- if (descriptor == null)
- {
- return;
- }
+ void add(ValidatorDelegateDescriptor descriptor) {
+ if (descriptor == null)return;
String targetID = descriptor.getTargetID();
- Map delegates = (Map) delegatesByTarget.get(targetID);
+ Map<String,ValidatorDelegateDescriptor> delegates = _delegatesByTarget.get(targetID);
- if (delegates == null)
- {
- delegates = new HashMap();
- delegatesByTarget.put(targetID, delegates);
+ if (delegates == null) {
+ delegates = new HashMap<String,ValidatorDelegateDescriptor>();
+ _delegatesByTarget.put(targetID, delegates);
}
delegates.put(descriptor.getId(), descriptor);
@@ -86,32 +124,31 @@
* Provides the default delegate ID for the given delegating validator ID.
*
* @param targetID
- * the delegating validator's ID.
+ * The delegating validator's ID.
* @return a String with the ID of the default delegate.
*/
public String getDefaultDelegate(String targetID)
{
- Map delegates = getDelegateDescriptors(targetID);
+ Map<String,ValidatorDelegateDescriptor> delegates = getDelegateDescriptors(targetID);
- if (delegates == null)
- {
- return null;
+ if (delegates == null)return null;
+
+ if (_defaultDelegates != null){
+ for (ValidatorDelegateDescriptor vdd : delegates.values()){
+ String id = vdd.getId();
+ if (_defaultDelegates.contains(id))return id;
+ }
}
-
+
// TODO: Implement a default attribute and use that to get the default?
// What happens if two or more delegates claim to be the default one?
// For now, just pick the first one in the list.
- Iterator delegatesIterator = delegates.values().iterator();
+ Iterator<ValidatorDelegateDescriptor> delegatesIterator = delegates.values().iterator();
+
+ if (!delegatesIterator.hasNext())return null;
- if (!delegatesIterator.hasNext())
- {
- return null;
- }
-
- ValidatorDelegateDescriptor descriptor = (ValidatorDelegateDescriptor) delegatesIterator.next();
-
- return descriptor.getId();
+ return delegatesIterator.next().getId();
}
/**
@@ -128,10 +165,7 @@
{
ValidatorDelegateDescriptor descriptor = getDescriptor(targetID, delegateID);
- if (descriptor == null)
- {
- return null;
- }
+ if (descriptor == null)return null;
IValidator delegate = descriptor.getValidator();
@@ -147,9 +181,8 @@
* @return a Map <string, ValidatorDelegateDescriptor>. May be null if the ID
* passed in is not a delegating validator.
*/
- public Map getDelegateDescriptors(String targetID)
- {
- return (Map) delegatesByTarget.get(targetID);
+ public Map<String,ValidatorDelegateDescriptor> getDelegateDescriptors(String targetID) {
+ return _delegatesByTarget.get(targetID);
}
/**
@@ -164,19 +197,9 @@
*/
public ValidatorDelegateDescriptor getDescriptor(String targetID, String delegateID)
{
- Map delegates = (Map) delegatesByTarget.get(targetID);
+ Map<String,ValidatorDelegateDescriptor> delegates = _delegatesByTarget.get(targetID);
- if (delegates == null)
- {
- // No delegates registered for this target.
-
- return null;
- }
-
- if (delegateID == null)
- {
- return null;
- }
+ if (delegates == null || delegateID == null)return null;
ValidatorDelegateDescriptor descriptor = (ValidatorDelegateDescriptor) delegates.get(delegateID);
@@ -192,7 +215,7 @@
*/
public boolean hasDelegates(String targetID)
{
- Map delegatesByID = (Map) delegatesByTarget.get(targetID);
+ Map<String,ValidatorDelegateDescriptor> delegatesByID = _delegatesByTarget.get(targetID);
boolean hasDelegates = (delegatesByID != null && !delegatesByID.isEmpty());
return hasDelegates;
diff --git a/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/delegates/ValidatorDelegatesRegistryReader.java b/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/delegates/ValidatorDelegatesRegistryReader.java
index e64f0e6..368f267 100644
--- a/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/delegates/ValidatorDelegatesRegistryReader.java
+++ b/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/delegates/ValidatorDelegatesRegistryReader.java
@@ -1,5 +1,5 @@
/*******************************************************************************
- * Copyright (c) 2006 IBM Corporation and others.
+ * Copyright (c) 2006, 2008 IBM Corporation 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
@@ -12,12 +12,15 @@
package org.eclipse.wst.validation.internal.delegates;
import org.eclipse.core.runtime.IConfigurationElement;
+import org.eclipse.core.runtime.IContributor;
import org.eclipse.core.runtime.IExtensionPoint;
import org.eclipse.core.runtime.IExtensionRegistry;
+import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Platform;
+import org.eclipse.wst.validation.internal.plugin.ValidationPlugin;
/**
- * This class reads the plugin extension registry and registers each delegating
+ * This class reads the plug-in extension registry and registers each delegating
* validator descriptor with the delegates registry.
*
* @see ValidatorDelegatesRegistry
@@ -83,9 +86,9 @@
if (elementName.equals(DELEGATE_ELEMENT))
{
- String delegateID = (String) element.getAttribute(CLASS_ATTRIBUTE);
- String delegateName = (String) element.getAttribute(NAME_ATTRIBUTE);
- String targetValidatorID = (String) element.getAttribute(TARGET_ATTRIBUTE);
+ String delegateID = element.getAttribute(CLASS_ATTRIBUTE);
+ String delegateName = element.getAttribute(NAME_ATTRIBUTE);
+ String targetValidatorID = element.getAttribute(TARGET_ATTRIBUTE);
ValidatorDelegateDescriptor descriptor = new ValidatorDelegateDescriptor(delegateID, element, delegateName, targetValidatorID);
@@ -103,12 +106,19 @@
if (point != null)
{
- IConfigurationElement[] elements = point.getConfigurationElements();
-
- for (int index = 0; index < elements.length; index++)
- {
- readElement(elements[index]);
- }
- }
+ IConfigurationElement[] elements = point.getConfigurationElements();
+ for (IConfigurationElement configurationElement : elements) {
+ try {
+ readElement(configurationElement);
+ }
+ catch (Exception e) {
+ // we don't want all the validators to be rendered helpless by some
+ // rogue contribution, so, we catch any exception that occurs during
+ // initialization, log it, and continue on.
+ IContributor contributor = configurationElement.getContributor();
+ ValidationPlugin.getPlugin().logMessage(IStatus.ERROR, "Rogue validator delegate from " + contributor);
+ }
+ }
+ }
}
}
diff --git a/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/operations/AllValidatorsOperation.java b/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/operations/AllValidatorsOperation.java
index f32ae59..66809bc 100644
--- a/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/operations/AllValidatorsOperation.java
+++ b/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/operations/AllValidatorsOperation.java
@@ -1,10 +1,10 @@
/*******************************************************************************
- * Copyright (c) 2001, 2004 IBM Corporation and others.
+ * Copyright (c) 2001, 2008 IBM Corporation 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:
* IBM Corporation - initial API and implementation
*******************************************************************************/
@@ -12,11 +12,8 @@
import java.lang.reflect.InvocationTargetException;
-import java.util.logging.Level;
import org.eclipse.core.resources.IProject;
-import org.eclipse.jem.util.logger.LogEntry;
-import org.eclipse.jem.util.logger.proxy.Logger;
import org.eclipse.wst.validation.internal.ConfigurationManager;
import org.eclipse.wst.validation.internal.InternalValidatorManager;
import org.eclipse.wst.validation.internal.ProjectConfiguration;
@@ -53,20 +50,12 @@
try {
ProjectConfiguration prjp = ConfigurationManager.getManager().getProjectConfiguration(project);
setEnabledValidators(InternalValidatorManager.wrapInSet(prjp.getValidators()));
- } catch (InvocationTargetException exc) {
- Logger logger = ValidationPlugin.getPlugin().getMsgLogger();
- if (logger.isLoggingLevel(Level.SEVERE)) {
- LogEntry entry = ValidationPlugin.getLogEntry();
- entry.setSourceID("EventManager::closing(" + project.getName() + ")"); //$NON-NLS-1$ //$NON-NLS-2$
- entry.setTargetException(exc);
- logger.write(Level.SEVERE, exc);
-
- if (exc.getTargetException() != null) {
- entry.setTargetException(exc);
- logger.write(Level.SEVERE, exc);
- }
+ } catch (InvocationTargetException e) {
+ ValidationPlugin.getPlugin().handleException(e);
+ if (e.getTargetException() != null) {
+ ValidationPlugin.getPlugin().handleException(e.getTargetException());
}
}
}
-}
\ No newline at end of file
+}
diff --git a/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/operations/EnabledIncrementalValidatorsOperation.java b/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/operations/EnabledIncrementalValidatorsOperation.java
index 7fcd3f4..df5a832 100644
--- a/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/operations/EnabledIncrementalValidatorsOperation.java
+++ b/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/operations/EnabledIncrementalValidatorsOperation.java
@@ -1,10 +1,10 @@
/*******************************************************************************
- * Copyright (c) 2001, 2004 IBM Corporation and others.
+ * Copyright (c) 2001, 2008 IBM Corporation 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:
* IBM Corporation - initial API and implementation
*******************************************************************************/
@@ -13,13 +13,10 @@
import java.lang.reflect.InvocationTargetException;
import java.util.Set;
-import java.util.logging.Level;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IResourceDelta;
-import org.eclipse.jem.util.logger.LogEntry;
-import org.eclipse.jem.util.logger.proxy.Logger;
import org.eclipse.wst.validation.internal.ConfigurationManager;
import org.eclipse.wst.validation.internal.FilterUtil;
import org.eclipse.wst.validation.internal.InternalValidatorManager;
@@ -111,19 +108,11 @@
try {
ProjectConfiguration prjp = ConfigurationManager.getManager().getProjectConfiguration(project);
setEnabledValidators(InternalValidatorManager.wrapInSet(prjp.getEnabledIncrementalValidators(true)));
- } catch (InvocationTargetException exc) {
- Logger logger = ValidationPlugin.getPlugin().getMsgLogger();
- if (logger.isLoggingLevel(Level.SEVERE)) {
- LogEntry entry = ValidationPlugin.getLogEntry();
- entry.setSourceID("EnabledIncrementalVAlidatorsOperation(IProject<" + project.getName() + ">, IResourceDelta, int, boolean)"); //$NON-NLS-1$ //$NON-NLS-2$
- entry.setTargetException(exc);
- logger.write(Level.SEVERE, exc);
+ } catch (InvocationTargetException e) {
+ ValidationPlugin.getPlugin().handleException(e);
+ if (e.getTargetException() != null)
+ ValidationPlugin.getPlugin().handleException(e.getTargetException());
- if (exc.getTargetException() != null) {
- entry.setTargetException(exc);
- logger.write(Level.SEVERE, exc);
- }
- }
}
setDelta(delta);
setContext(context);
@@ -145,19 +134,11 @@
try {
ProjectConfiguration prjp = ConfigurationManager.getManager().getProjectConfiguration(project);
setEnabledValidators(InternalValidatorManager.wrapInSet(prjp.getEnabledIncrementalValidators(true)));
- } catch (InvocationTargetException exc) {
- Logger logger = ValidationPlugin.getPlugin().getMsgLogger();
- if (logger.isLoggingLevel(Level.SEVERE)) {
- LogEntry entry = ValidationPlugin.getLogEntry();
- entry.setSourceID("EnabledIncrementalVAlidatorsOperation(IProject<" + project.getName() + ">, IResourceDelta, int, boolean)"); //$NON-NLS-1$ //$NON-NLS-2$
- entry.setTargetException(exc);
- logger.write(Level.SEVERE, exc);
+ } catch (InvocationTargetException e) {
+ ValidationPlugin.getPlugin().handleException(e);
+ if (e.getTargetException() != null)
+ ValidationPlugin.getPlugin().handleException(e.getTargetException());
- if (exc.getTargetException() != null) {
- entry.setTargetException(exc);
- logger.write(Level.SEVERE, exc);
- }
- }
}
setDelta(delta);
}
@@ -179,19 +160,11 @@
try {
ProjectConfiguration prjp = ConfigurationManager.getManager().getProjectConfiguration(project);
setEnabledValidators(InternalValidatorManager.wrapInSet(prjp.getEnabledIncrementalValidators(true)));
- } catch (InvocationTargetException exc) {
- Logger logger = ValidationPlugin.getPlugin().getMsgLogger();
- if (logger.isLoggingLevel(Level.SEVERE)) {
- LogEntry entry = ValidationPlugin.getLogEntry();
- entry.setSourceID("EnabledIncrementalValidatorsOperation(IResource[], IProject<" + project.getName() + ">, boolean)"); //$NON-NLS-1$ //$NON-NLS-2$
- entry.setTargetException(exc);
- logger.write(Level.SEVERE, exc);
+ } catch (InvocationTargetException e) {
+ ValidationPlugin.getPlugin().handleException(e);
+ if (e.getTargetException() != null)
+ ValidationPlugin.getPlugin().handleException(e.getTargetException());
- if (exc.getTargetException() != null) {
- entry.setTargetException(exc);
- logger.write(Level.SEVERE, entry);
- }
- }
}
//construct an array of IFileDelta[] to wrap the Object[]; one IFileDelta for each Object in the array
setFileDeltas(FilterUtil.getFileDeltas(getEnabledValidators(), changedResources, false));
@@ -215,22 +188,14 @@
try {
ProjectConfiguration prjp = ConfigurationManager.getManager().getProjectConfiguration(project);
setEnabledValidators(InternalValidatorManager.wrapInSet(prjp.getEnabledIncrementalValidators(true)));
- } catch (InvocationTargetException exc) {
- Logger logger = ValidationPlugin.getPlugin().getMsgLogger();
- if (logger.isLoggingLevel(Level.SEVERE)) {
- LogEntry entry = ValidationPlugin.getLogEntry();
- entry.setSourceID("EnabledIncrementalValidatorsOperation(IResource[], IProject<" + project.getName() + ">, boolean)"); //$NON-NLS-1$ //$NON-NLS-2$
- entry.setTargetException(exc);
- logger.write(Level.SEVERE, exc);
+ } catch (InvocationTargetException e) {
+ ValidationPlugin.getPlugin().handleException(e);
+ if (e.getTargetException() != null)
+ ValidationPlugin.getPlugin().handleException(e.getTargetException());
- if (exc.getTargetException() != null) {
- entry.setTargetException(exc);
- logger.write(Level.SEVERE, entry);
- }
- }
}
//construct an array of IFileDelta[] to wrap the Object[]; one IFileDelta for each Object in the array
setFileDeltas(FilterUtil.getFileDeltas(getEnabledValidators(), changedResources, false));
}
-}
\ No newline at end of file
+}
diff --git a/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/operations/EnabledValidatorsOperation.java b/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/operations/EnabledValidatorsOperation.java
index 9566a7b..9b8afb3 100644
--- a/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/operations/EnabledValidatorsOperation.java
+++ b/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/operations/EnabledValidatorsOperation.java
@@ -1,10 +1,10 @@
/*******************************************************************************
- * Copyright (c) 2001, 2004 IBM Corporation and others.
+ * Copyright (c) 2001, 2006 IBM Corporation 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:
* IBM Corporation - initial API and implementation
*******************************************************************************/
@@ -15,6 +15,7 @@
import org.eclipse.core.resources.IProject;
import org.eclipse.wst.validation.internal.RegistryConstants;
+import org.eclipse.wst.validation.internal.ValidatorMetaData;
/**
@@ -116,7 +117,7 @@
* in the background validation thread, if async is false, it would run in the main thread.
* All validators implementing IValidator interface will run in in the main thread regardless of this flag.
*/
- protected EnabledValidatorsOperation(IProject project, Set enabledValidators, boolean async) {
+ protected EnabledValidatorsOperation(IProject project, Set<ValidatorMetaData> enabledValidators, boolean async) {
this(project, enabledValidators, RegistryConstants.ATT_RULE_GROUP_DEFAULT, DEFAULT_FORCE, async);
// true = force validation to run whether or not auto-validate is on
}
@@ -130,7 +131,8 @@
* in the background validation thread, if async is false, it would run in the main thread.
* All validators implementing IValidator interface will run in in the main thread regardless of this flag.
*/
- protected EnabledValidatorsOperation(IProject project,IWorkbenchContext aWorkbenchContext, Set enabledValidators, boolean async) {
+ protected EnabledValidatorsOperation(IProject project,IWorkbenchContext aWorkbenchContext,
+ Set<ValidatorMetaData> enabledValidators, boolean async) {
this(project,aWorkbenchContext, enabledValidators, RegistryConstants.ATT_RULE_GROUP_DEFAULT, DEFAULT_FORCE, async);
// true = force validation to run whether or not auto-validate is on
}
@@ -144,7 +146,9 @@
* in the background validation thread, if async is false, it would run in the main thread.
* All validators implementing IValidator interface will run in in the main thread regardless of this flag.
*/
- protected EnabledValidatorsOperation(IProject project, Set enabledValidators, int ruleGroup, boolean force, boolean async) {
+ protected EnabledValidatorsOperation(IProject project, Set<ValidatorMetaData> enabledValidators,
+ int ruleGroup, boolean force, boolean async) {
+
super(project, force, ruleGroup, async);
setEnabledValidators(enabledValidators);
}
@@ -158,8 +162,9 @@
* in the background validation thread, if async is false, it would run in the main thread.
* All validators implementing IValidator interface will run in in the main thread regardless of this flag.
*/
- protected EnabledValidatorsOperation(IProject project, IWorkbenchContext aWorkbenchContext, Set enabledValidators, int ruleGroup, boolean force, boolean async) {
+ protected EnabledValidatorsOperation(IProject project, IWorkbenchContext aWorkbenchContext,
+ Set<ValidatorMetaData> enabledValidators, int ruleGroup, boolean force, boolean async) {
super(project,aWorkbenchContext,force, ruleGroup, async);
setEnabledValidators(enabledValidators);
}
-}
\ No newline at end of file
+}
diff --git a/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/operations/IRuleGroup.java b/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/operations/IRuleGroup.java
index dabcee8..1c2ad11 100644
--- a/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/operations/IRuleGroup.java
+++ b/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/operations/IRuleGroup.java
@@ -1,10 +1,10 @@
/*******************************************************************************
- * Copyright (c) 2001, 2004 IBM Corporation and others.
+ * Copyright (c) 2001, 2005 IBM Corporation 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:
* IBM Corporation - initial API and implementation
*******************************************************************************/
@@ -38,4 +38,4 @@
public static final int PASS_FULL = 0x2 | PASS_FAST;
public static final String PASS_FULL_NAME = "full"; //$NON-NLS-1$ // In plugin.xml, identify this pass by this constant
-}
\ No newline at end of file
+}
diff --git a/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/operations/IWorkbenchContext.java b/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/operations/IWorkbenchContext.java
index b3c8ec0..2ee4b60 100644
--- a/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/operations/IWorkbenchContext.java
+++ b/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/operations/IWorkbenchContext.java
@@ -1,10 +1,10 @@
/*******************************************************************************
- * Copyright (c) 2001, 2004 IBM Corporation and others.
+ * Copyright (c) 2001, 2007 IBM Corporation 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:
* IBM Corporation - initial API and implementation
*******************************************************************************/
@@ -15,9 +15,6 @@
import org.eclipse.core.resources.IResource;
import org.eclipse.wst.validation.internal.provisional.core.IProjectValidationContext;
-
-
-
/**
* In the eclipse environment, not only does the IValidationContext need to be able to load the MOF model, it
* also needs to load items from the eclipse workbench. This interface should be extended by
@@ -30,7 +27,7 @@
*
* If the cleanup is a long-running operation, subtask messages should be sent to the IReporter.
*/
- public void cleanup(WorkbenchReporter reporter);
+ void cleanup(WorkbenchReporter reporter);
/**
* When the IProject is closing, perform any cleanup that needs to be done. When this method is
@@ -38,7 +35,7 @@
* resources. If you do not allocate resources in your helper, then this method should be a
* no-op.
*/
- public void closing();
+ void closing();
/**
* When the IProject is being deleted, perform any cleanup that needs to be done. When this
@@ -46,7 +43,7 @@
* those resources. If you do not allocate resources in your helper, then this method should be
* a no-op.
*/
- public void deleting();
+ void deleting();
/**
* Given an Object, if the object has a corresponding IFile in the workbench, return the IFile.
@@ -68,7 +65,7 @@
*
* @deprecated Implement getResource(Object) instead.
*/
- public IFile getFile(Object object);
+ IFile getFile(Object object);
/**
* Given an Object, if the object has a corresponding IResource in the workbench, return the
@@ -88,7 +85,7 @@
* If this method returns null, then the WorkbenchReporter will add the message to the IProject
* instead of an IResource.
*/
- public IResource getResource(Object object);
+ IResource getResource(Object object);
/**
* Given an IMessage's target object, return the line number, of the IFile, which the target
@@ -99,18 +96,18 @@
* Line numbers are valid only for IFile types; if the resource is not an IFile, then a text
* description of the location must be returned.
*/
- public String getLocation(Object object);
+ String getLocation(Object object);
/**
* Return the name of the resource, without the project-specific information in front.
- *
+ * <p>
* This method is used by ValidationOperation to calculate the non-environment specific names of
* the files. Only the IWorkbenchContext implementation knows how much information to strip off
* of the IResource name. For example, if there is an EJB Project named "MyEJBProject", and it
* uses the default names for the source and output folders, "source" and "ejbModule",
* respectively, then the current implementation of EJB Helper knows how much of that structure
* is eclipse-specific.
- *
+ * </p><p>
* Since the "source" folder contains Java source files, a portable name would be the
* fully-qualified name of the Java class, without the eclipse-specific project and folder names
* in front of the file name. The EJBHelper knows that everything up to the "source" folder, for
@@ -119,20 +116,21 @@
* Project named "/MyEJBProject/source/com/ibm/myclasses/MyJavaFile.java", this method would
* make this name portable by stripping off the "/MyEJBProject/source", and returning
* "com/ibm/myclasses/MyJavaFile.java".
- *
+ * </p><p>
* The output of this method is used by the ValidationOperation, when it is calculating the list
* of added/changed/deleted file names for incremental validation. If getPortableName(IResource)
* returns null, that means that the IWorkbenchContext's implementation does not support that
* particular type of resource, and the resource should not be included in the array of
* IFileDelta objects in the IValidator's "validate" method.
+ * </p>
*/
- public String getPortableName(IResource resource);
+ String getPortableName(IResource resource);
/**
* Return the IProject which is about to be validated. Each IWorkbenchContext knows how to
* traverse a certain type of IProject, for example, an EJB project or a web project.
*/
- public IProject getProject();
+ IProject getProject();
/**
* When an IValidator associates a target object with an IMessage, the WorkbenchReporter
@@ -148,7 +146,7 @@
* identify a particular object must be returned. The id needs to be unique only within one
* particular IValidator.
*/
- public String getTargetObjectName(Object object);
+ String getTargetObjectName(Object object);
/**
* Whether full or incremental validation is running, this method will be called, by the
@@ -156,13 +154,13 @@
* IValidationContext can receive notification that one of the resources, which validation will run on, is
* being filtered in.
*/
- public void registerResource(IResource resource);
+ void registerResource(IResource resource);
/**
* This method is called by the Validation Framework, to initialize the IWorkbenchContext so that
* it can gather information from the current project.
*/
- public void setProject(IProject project);
+ void setProject(IProject project);
/**
* Notifies this IWorkbenchContext that the Validation Framework is shutting down. There will be
@@ -172,5 +170,5 @@
* shut down. This method will be called once for every IProject in the workbench. The IProject
* may, or may not, be closed.
*/
- public void shutdown();
-}
\ No newline at end of file
+ void shutdown();
+}
diff --git a/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/operations/LocalizedMessage.java b/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/operations/LocalizedMessage.java
index 2472f76..9b03057 100644
--- a/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/operations/LocalizedMessage.java
+++ b/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/operations/LocalizedMessage.java
@@ -1,10 +1,10 @@
/*******************************************************************************
- * Copyright (c) 2001, 2004 IBM Corporation and others.
+ * Copyright (c) 2001, 2007 IBM Corporation 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:
* IBM Corporation - initial API and implementation
*******************************************************************************/
@@ -15,14 +15,13 @@
import org.eclipse.core.resources.IResource;
import org.eclipse.wst.validation.internal.core.Message;
-
/**
* This class is provided for validators which run only in UI and whose messages, because they
* come from another tool, are already localized. LocalizedMessage cannot be used by any validator
* which needs to run in both WebSphere and WSAD.
*/
public class LocalizedMessage extends Message {
- private String _message = null;
+ private String _message;
public LocalizedMessage(int severity, String messageText) {
this(severity, messageText, null);
@@ -61,4 +60,4 @@
public String getText(Locale l, ClassLoader cl) {
return getLocalizedMessage();
}
-}
\ No newline at end of file
+}
diff --git a/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/operations/ManualIncrementalValidatorsOperation.java b/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/operations/ManualIncrementalValidatorsOperation.java
index e837ccb..59d5f0f 100644
--- a/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/operations/ManualIncrementalValidatorsOperation.java
+++ b/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/operations/ManualIncrementalValidatorsOperation.java
@@ -1,10 +1,10 @@
/*******************************************************************************
- * Copyright (c) 2001, 2004 IBM Corporation and others.
+ * Copyright (c) 2001, 2006 IBM Corporation 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:
* IBM Corporation - initial API and implementation
*******************************************************************************/
@@ -28,4 +28,4 @@
super( project, changedResources );
setFileDeltas( FilterUtil.getFileDeltas(getEnabledValidators(), changedResources, false) );
}
-}
\ No newline at end of file
+}
diff --git a/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/operations/ManualValidatorsOperation.java b/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/operations/ManualValidatorsOperation.java
index 35b85d0..03a0bf2 100644
--- a/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/operations/ManualValidatorsOperation.java
+++ b/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/operations/ManualValidatorsOperation.java
@@ -1,10 +1,10 @@
/*******************************************************************************
- * Copyright (c) 2001, 2004 IBM Corporation and others.
+ * Copyright (c) 2001, 2006 IBM Corporation 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:
* IBM Corporation - initial API and implementation
*******************************************************************************/
@@ -20,11 +20,13 @@
* ValidationOperation, because some initialization of the validator, and handling of error
* conditions, is done in the operation. The initialization is separated because some of the
* information needed to initialize the validator (i.e., the project) isn't known until runtime.
- *
+ * <p>
* Instances of this operation run every enabled validator (both full and incremental) on the
* project.
- *
+ * </p>
+ * <p>
* This operation is not intended to be subclassed outside of the validation framework.
+ * </p>
*/
public class ManualValidatorsOperation extends ValidatorSubsetOperation {
@@ -36,4 +38,4 @@
super(project, shouldForce(changedResources), RegistryConstants.ATT_RULE_GROUP_DEFAULT, true);
setEnabledValidators(ValidatorManager.getManager().getManualEnabledValidators(project));
}
-}
\ No newline at end of file
+}
diff --git a/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/operations/MessageInfo.java b/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/operations/MessageInfo.java
index 96d1771..16b93c0 100644
--- a/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/operations/MessageInfo.java
+++ b/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/operations/MessageInfo.java
@@ -1,10 +1,10 @@
/*******************************************************************************
- * Copyright (c) 2003, 2005 IBM Corporation and others.
+ * Copyright (c) 2003, 2008 IBM Corporation 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:
* IBM Corporation - initial API and implementation
*******************************************************************************/
@@ -23,20 +23,12 @@
private String targetObjectName;
private String markerId;
private IMessage msg;
-
-
- public MessageInfo(){
-
+ public MessageInfo(){
}
- public MessageInfo(String messageOwnerId,
- IResource resource,
- String location,
- String text,
- String targetObjectName,
- String markerId,
- IMessage msg){
+ public MessageInfo(String messageOwnerId, IResource resource, String location,
+ String text, String targetObjectName, String markerId, IMessage msg){
this.messageOwnerId = messageOwnerId;
this.resource = resource;
@@ -103,4 +95,10 @@
this.text = text;
}
+ @Override
+ public String toString() {
+ if (text != null)return "MessageInfo: " + text; //$NON-NLS-1$
+ return super.toString();
+ }
+
}
diff --git a/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/operations/OneValidatorOperation.java b/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/operations/OneValidatorOperation.java
index c11ec1d..99d359b 100644
--- a/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/operations/OneValidatorOperation.java
+++ b/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/operations/OneValidatorOperation.java
@@ -1,10 +1,10 @@
/*******************************************************************************
- * Copyright (c) 2001, 2004 IBM Corporation and others.
+ * Copyright (c) 2001, 2008 IBM Corporation 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:
* IBM Corporation - initial API and implementation
*******************************************************************************/
@@ -80,45 +80,46 @@
* OneValidatorOperation constructor comment.
*
* @param project
- * org.eclipse.core.resources.IProject
+ * The project to be validated. It must exist and be open.
* @param validatorId
- * The plugin id of the validator which you wish to run.
+ * The plug-in id of the validator which you wish to run.
* @param force
- * If the value is "true", the validator should be run regardless of what the
- * environment settings are; if the value is "false", this operation should be run
- * only if the validation builder will not run the validator.
+ * If the value is "true", the validator should be run regardless
+ * of what the environment settings are; if the value is "false",
+ * this operation should be run only if the validation builder
+ * will not run the validator.
* @param ruleGroup
* Whether a FULL or FAST pass should be invoked.
+ * @param async
+ * If async is true, the validation will run all thread-safe
+ * validators in the background validation thread, and all other
+ * validators in the main thread. If async is false, all
+ * validators will run in in the main thread.
*
- * IllegalArgumentException will be thrown if the named validator is not configured on the
- * project.
+ * IllegalArgumentException will be thrown if the named validator is not
+ * configured on the project.
*
- * IProject must exist and be open.
- *
- * If async is true, the validation will run all thread-safe validators in the background
- * validation thread, and all other validators in the main thread. If async is false, all
- * validators will run in in the main thread.
*/
public OneValidatorOperation(IProject project, String validatorId, boolean force, int ruleGroup, boolean async) throws IllegalArgumentException {
super(project, force, ruleGroup, async);
ValidatorMetaData vmd = ValidationRegistryReader.getReader().getValidatorMetaData(validatorId);
if (vmd == null) {
- // No validator, with that plugin id, can be run on that project.
+ // No validator, with that plug-in id, can be run on that project.
// Either the validator isn't installed, or the IProject passed in
// doesn't have the necessary nature.
throw new IllegalArgumentException(validatorId);
}
if (!vmd.isConfiguredOnProject(project)) {
- // No validator, with that plugin id, can be run on that project.
+ // No validator, with that plug-in id, can be run on that project.
// Either the validator isn't installed, or the IProject passed in
// doesn't have the necessary nature.
throw new IllegalArgumentException(validatorId);
}
- Set enabled = new HashSet();
+ Set<ValidatorMetaData> enabled = new HashSet<ValidatorMetaData>();
enabled.add(vmd);
setEnabledValidators(enabled);
}
-}
\ No newline at end of file
+}
diff --git a/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/operations/ReferencialFileValidator.java b/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/operations/ReferencialFileValidator.java
index a2e1fcc..c15609c 100644
--- a/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/operations/ReferencialFileValidator.java
+++ b/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/operations/ReferencialFileValidator.java
@@ -1,10 +1,10 @@
/*******************************************************************************
- * Copyright (c) 2001, 2004 IBM Corporation and others.
+ * Copyright (c) 2001, 2008 IBM Corporation 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:
* IBM Corporation - initial API and implementation
*******************************************************************************/
@@ -18,12 +18,18 @@
import java.util.List;
+import org.eclipse.core.resources.IFile;
+
/**
* @author vijayb
- *
- * To change the template for this generated type comment go to Window - Preferences - Java - Code
- * Generation - Code and Comments
*/
public interface ReferencialFileValidator {
- public List getReferencedFile(List inputFiles);
-}
\ No newline at end of file
+
+ /**
+ * Answer the referenced files.
+ *
+ * @param inputFiles
+ * @return a list of IFile's.
+ */
+ public List<IFile> getReferencedFile(List inputFiles);
+}
diff --git a/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/operations/ReferencialFileValidatorHelper.java b/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/operations/ReferencialFileValidatorHelper.java
index 1dbe0bd..99d66e1 100644
--- a/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/operations/ReferencialFileValidatorHelper.java
+++ b/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/operations/ReferencialFileValidatorHelper.java
@@ -1,10 +1,10 @@
/*******************************************************************************
- * Copyright (c) 2001, 2004 IBM Corporation and others.
+ * Copyright (c) 2001, 2008 IBM Corporation 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:
* IBM Corporation - initial API and implementation
*******************************************************************************/
@@ -27,25 +27,18 @@
/**
* @author vijayb
- *
- * To change the template for this generated type comment go to Window - Preferences - Java - Code
- * Generation - Code and Comments
*/
public class ReferencialFileValidatorHelper {
- /**
- *
- */
public ReferencialFileValidatorHelper() {
- super();
}
/**
- * return a list of all files contained in project to infinite depth
+ * Return a list of all files contained in project to infinite depth
*/
- public static List getAllProjectFiles(IProject project) {
- List result = new ArrayList();
- if (project == null)
- return result;
+ public static List<IFile> getAllProjectFiles(IProject project) {
+ List<IFile> result = new ArrayList<IFile>();
+ if (project == null)return result;
+
try {
result = collectFiles(project.members(), result);
} catch (CoreException e) {
@@ -54,16 +47,12 @@
return result;
}
- private static List collectFiles(IResource[] members, List result) throws CoreException {
+ private static List<IFile> collectFiles(IResource[] members, List<IFile> result) throws CoreException {
// recursively collect files for the given members
- for (int i = 0; i < members.length; i++) {
- IResource res = members[i];
- if (res instanceof IFolder) {
- collectFiles(((IFolder) res).members(), result);
- } else if (res instanceof IFile) {
- result.add(res);
- }
+ for (IResource res : members) {
+ if (res instanceof IFolder)collectFiles(((IFolder) res).members(), result);
+ else if (res instanceof IFile)result.add((IFile)res);
}
return result;
}
-}
\ No newline at end of file
+}
diff --git a/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/operations/ResourceHandler.java b/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/operations/ResourceHandler.java
index fe47c03..8e942ea 100644
--- a/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/operations/ResourceHandler.java
+++ b/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/operations/ResourceHandler.java
@@ -1,10 +1,10 @@
/*******************************************************************************
- * Copyright (c) 2001, 2004 IBM Corporation and others.
+ * Copyright (c) 2001, 2005 IBM Corporation 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:
* IBM Corporation - initial API and implementation
*******************************************************************************/
@@ -17,4 +17,4 @@
*/
public final class ResourceHandler extends org.eclipse.wst.validation.internal.ResourceHandler {
//Default
-}
\ No newline at end of file
+}
diff --git a/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/operations/ValidationBuilder.java b/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/operations/ValidationBuilder.java
index 01074b5..5bb1c28 100644
--- a/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/operations/ValidationBuilder.java
+++ b/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/operations/ValidationBuilder.java
@@ -1,10 +1,10 @@
/*******************************************************************************
- * Copyright (c) 2001, 2004 IBM Corporation and others.
+ * Copyright (c) 2001, 2009 IBM Corporation 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:
* IBM Corporation - initial API and implementation
*******************************************************************************/
@@ -12,70 +12,83 @@
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
+import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
-import java.util.logging.Level;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResourceDelta;
import org.eclipse.core.resources.IncrementalProjectBuilder;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.OperationCanceledException;
-import org.eclipse.jem.util.logger.LogEntry;
-import org.eclipse.jem.util.logger.proxy.Logger;
+import org.eclipse.core.runtime.IStatus;
+import org.eclipse.wst.validation.ValidationFramework;
import org.eclipse.wst.validation.internal.ConfigurationManager;
import org.eclipse.wst.validation.internal.InternalValidatorManager;
import org.eclipse.wst.validation.internal.ProjectConfiguration;
import org.eclipse.wst.validation.internal.ResourceConstants;
import org.eclipse.wst.validation.internal.ResourceHandler;
-import org.eclipse.wst.validation.internal.TimeEntry;
+import org.eclipse.wst.validation.internal.Tracing;
+import org.eclipse.wst.validation.internal.ValBuilderJob;
+import org.eclipse.wst.validation.internal.ValManager;
import org.eclipse.wst.validation.internal.ValidatorMetaData;
import org.eclipse.wst.validation.internal.plugin.ValidationPlugin;
/**
* Validation Framework Builder.
- *
- * This builder is configured on J2EE IProjects automatically, can be added to other types of
- * projects through the Properties page, and launches validation on the project if the project has
+ * <p>
+ * This builder is configured on J2EE IProjects automatically, and can be added to other types of
+ * projects through the Properties page. It launches validation on the project if the project has
* build validation enabled.
+ * </p>
+ * <p>
+ * This launches a Job for the new V2 validators and also a Job for each of the Job based V1
+ * validators. If there are any "in-line" V1 validations they are done as part of this builder.
+ * Because of all the jobs that this builder spawns, the build will usually be finished long before
+ * all the validation has finished.
+ * </p>
*/
public class ValidationBuilder extends IncrementalProjectBuilder {
- public static final int NO_DELTA_CHANGE = -1; // Since IResourceConstants
- protected List referencedProjects;
+ /*
+ * GRK - This class serves as a main entry point into the framework. There is one instance of this class for every
+ * project that has a validation builder configured for it. Typically if you had ten projects in your workspace you would have
+ * ten of these objects. They are created early in the life cycle of the workbench, and then are reused.
+ *
+ * My observation was that they are run serially by the same thread.
+ */
+ public static final int NO_DELTA_CHANGE = -1;
+ protected List<IProject> referencedProjects;
protected IWorkbenchContext workbenchContext = null;
-
- // doesn't have a "no delta"
- // flag, let this constant be
- // the flag.
+
+ /**
+ * All the jobs that the validation framework spawns will belong to this family.
+ */
+ public static final Object FAMILY_VALIDATION_JOB = new Object();
+
public ValidationBuilder() {
- super();
}
- private IProject[] getAllReferencedProjects(IProject project, Set visitedProjects) {
- if (visitedProjects == null)
- visitedProjects = new HashSet();
- else if (visitedProjects.contains(project))
- return getReferencedProjects();
- else
- visitedProjects.add(project);
- if (referencedProjects == null)
- referencedProjects = new ArrayList();
+ private IProject[] getAllReferencedProjects(IProject project, Set<IProject> visitedProjects) {
+ if (visitedProjects == null)visitedProjects = new HashSet<IProject>();
+ else if (visitedProjects.contains(project))return getReferencedProjects();
+ else visitedProjects.add(project);
+
+ if (referencedProjects == null)referencedProjects = new ArrayList<IProject>();
try {
if (project.isAccessible()) {
IProject[] refProjArray = project.getReferencedProjects();
collectReferecedProject(refProjArray);
- for (int i = 0; i < refProjArray.length; i++) {
- IProject refProject = refProjArray[i];
+ for (IProject refProject : refProjArray) {
getAllReferencedProjects(refProject, visitedProjects);
}
}
return getReferencedProjects();
- } catch (CoreException core) {
- return null;
+ } catch (CoreException e) {
+ ValidationPlugin.getPlugin().handleException(e);
}
+ return null;
}
public IWorkbenchContext getWorkbenchContext() {
@@ -86,28 +99,23 @@
return workbenchContext;
}
-
/**
- * @param referencedProjects2
+ * Add the projects from refProjArray to the list of referenced projects (if they are not
+ * already in the list).
* @param refProjArray
*/
private void collectReferecedProject(IProject[] refProjArray) {
- for (int i = 0; i < refProjArray.length; i++) {
- IProject project = refProjArray[i];
- if (!referencedProjects.contains(project))
- referencedProjects.add(project);
+ for (IProject project : refProjArray) {
+ if (!referencedProjects.contains(project))referencedProjects.add(project);
}
}
- /*
- * (non-Javadoc)
- *
- * @see org.eclipse.core.resources.IncrementalProjectBuilder#clean(org.eclipse.core.runtime.IProgressMonitor)
- */
protected void clean(IProgressMonitor monitor) throws CoreException {
IProject currentProject = getProject();
- if (currentProject == null || !currentProject.isAccessible())
- return;
+ Tracing.log("ValidationBuilder-02 clean ", currentProject); //$NON-NLS-1$
+
+ newClean(monitor);
+ if (currentProject == null || !currentProject.isAccessible())return;
try {
ProjectConfiguration prjp = ConfigurationManager.getManager().getProjectConfiguration(currentProject);
ValidatorMetaData[] vmds = prjp.getValidators();
@@ -118,64 +126,44 @@
// The uniqueness of each Validator is checked by the plugin registry.
WorkbenchReporter.removeAllMessages(currentProject, vmd.getValidatorNames(), null);
}
- } catch (InvocationTargetException exc) {
- Logger logger = ValidationPlugin.getPlugin().getMsgLogger();
- if (logger.isLoggingLevel(Level.SEVERE)) {
- LogEntry entry = ValidationPlugin.getLogEntry();
- entry.setSourceIdentifier("ValidatorManager.updateTaskList(" + currentProject.getName() + ")"); //$NON-NLS-1$ //$NON-NLS-2$
- entry.setTargetException(exc);
- logger.write(Level.SEVERE, entry);
- if (exc.getTargetException() != null) {
- entry.setTargetException(exc);
- logger.write(Level.SEVERE, entry);
- }
- }
+ } catch (InvocationTargetException e) {
+ ValidationPlugin.getPlugin().handleException(e);
+ ValidationPlugin.getPlugin().handleException(e.getTargetException());
}
}
- /**
- * @param referencedProjects
- * @return
- */
private IProject[] getReferencedProjects() {
IProject[] refProjArray = new IProject[referencedProjects.size()];
- for (int i = 0; i < referencedProjects.size(); i++) {
- refProjArray[i] = (IProject) referencedProjects.get(i);
- }
- return refProjArray;
+ return referencedProjects.toArray(refProjArray);
}
-
+
+ @SuppressWarnings("unchecked")
public IProject[] build(int kind, Map parameters, IProgressMonitor monitor) {
- long start = System.currentTimeMillis();
- int executionMap = 0x0;
- Logger logger = ValidationPlugin.getPlugin().getMsgLogger();
IResourceDelta delta = null;
IProject project = getProject();
+ Tracing.log("ValidationBuilder-01 build ", kind, project); //$NON-NLS-1$
+ if (Tracing.isLogging(1)){
+ Tracing.logResourceDeltas(getDelta(project), 50);
+ }
+
+ // GRK I wonder why this builder needs to know about all the other referenced projects?
+ // won't they have builders of their own.
IProject[] referenced = getAllReferencedProjects(project, null);
+ if (ValidationFramework.getDefault().isSuspended(project) ||
+ ValManager.getDefault().isDisabled(project))return referenced;
+
try {
- if (ValidatorManager.getManager().isSuspended(project)) {
- // Do not perform validation on this project
- executionMap |= 0x1;
- return referenced;
- }
+ newBuild(kind, monitor);
+
ProjectConfiguration prjp = ConfigurationManager.getManager().getProjectConfiguration(project);
delta = getDelta(project);
boolean doFullBuild = (kind == FULL_BUILD);
- boolean doAutoBuild = ((delta != null) && (kind == AUTO_BUILD));
- boolean doIncrementalBuild = ((delta != null) && (kind == INCREMENTAL_BUILD));
-// if ((doFullBuild || doIncrementalBuild) && !prjp.isBuildValidate()) {
-// // Is a build validation about to be invoked? If so, does the
-// // user want build validation to run?
-// executionMap |= 0x2;
-// return referenced;
-// }
+
// It is possible for kind to == AUTO_BUILD while delta is null
- // (saw this
- // when creating a project by copying another project.)
+ // (saw this when creating a project by copying another project.)
// However, a "Rebuild Project" will invoke this builder with
- // kind==FULL_BUILD
- // and a null delta, and validation should run in that case.
+ // kind==FULL_BUILD and a null delta, and validation should run in that case.
if (!doFullBuild && delta == null) {
if (isReferencedProjectInDelta(referenced)) {
performFullBuildForReferencedProjectChanged(monitor, prjp);
@@ -183,55 +171,72 @@
String[] msgParms = new String[]{project.getName()};
monitor.subTask(ResourceHandler.getExternalizedMessage(ResourceConstants.VBF_STATUS_NULL_DELTA, msgParms));
// A null delta means that a full build must be performed,
- // but this builder was invoked with an incremental or
- // automatic
- // build kind. Return without doing anything so that the
- // user
+ // but this builder was invoked with an incremental or automatic
+ // build kind. Return without doing anything so that the user
// doesn't have to wait forever.
- executionMap |= 0x4;
}
return referenced;
}
if (doFullBuild) {
+ cleanupReferencedProjectsMarkers(prjp, referenced);
performFullBuild(monitor, prjp);
} else {
-// if (doAutoBuild && !prjp.isAutoValidate()) {
-// executionMap |= 0x8;
-// return referenced;
-// }
if (delta.getAffectedChildren().length == 0) {
- if (isReferencedProjectInDelta(referenced))
+ if (isReferencedProjectInDelta(referenced)){
+ cleanupReferencedProjectsMarkers(prjp, referenced);
performFullBuildForReferencedProjectChanged(monitor, prjp);
- else
- executionMap |= 0x10;
+ }
return referenced;
}
EnabledIncrementalValidatorsOperation operation = new EnabledIncrementalValidatorsOperation(project, delta, true);
operation.run(monitor);
}
return referenced;
- } catch (InvocationTargetException exc) {
- logInvocationTargetException(logger, exc);
- executionMap |= 0x20;
+ } catch (InvocationTargetException e) {
+ ValidationPlugin.getPlugin().handleException(e);
+ ValidationPlugin.getPlugin().handleException(e.getTargetException());
return referenced;
- } catch (Throwable exc) {
- logBuildError(logger, exc);
- executionMap |= 0x40;
+ } catch (Exception e) {
+ ValidationPlugin.getPlugin().handleException(e);
return referenced;
} finally {
referencedProjects = null;
- // The builder's time needs to be FINE because the builder is
- // called often.
- if (logger.isLoggingLevel(Level.FINE)) {
- logBuilderTimeEntry(start, executionMap, logger, delta);
- }
}
}
+
+ private void cleanupReferencedProjectsMarkers(final ProjectConfiguration prjp, IProject[] referenced){
+ //When a project references one or more project, performing a clean build on referenced
+ //causes delta to be invoked on referencee, aka, parent. This causes following code to
+ //be invoked.
+ //The following code is trying to fix a case where Ejb project references a utility project,
+ //and the clean build on utility project causes the code to come here, the ejb validator runs
+ //on the ejb project due to performFullBuildForReferencedProjectChanged() below, but it also
+ //causes marker to be generated for the util project, but the markers for util project are not
+ //cleaned up.
+
+ if( referenced == null || referenced.length == 0 )return;
+
+ try{
+ ValidatorMetaData[] enabledValidators = prjp.getEnabledFullBuildValidators(true, false);
+
+ Set<ValidatorMetaData> set = new HashSet<ValidatorMetaData>();
+ set.addAll( Arrays.asList( enabledValidators ) );
+ for (IProject p : referenced) {
+ if (!p.isAccessible())continue;
+ ProjectConfiguration refProjectCfg = ConfigurationManager.getManager().getProjectConfiguration(p);
+
+ ValidatorMetaData[] refEnabledValidators = refProjectCfg.getEnabledFullBuildValidators(true, false);
+
+ //remove from the set the validators which are also in child
+ for(ValidatorMetaData vmd : refEnabledValidators)set.remove(vmd);
+
+ for(ValidatorMetaData vmd : set)WorkbenchReporter.removeAllMessages(p, vmd.getValidator());
+ }
+ }catch (Exception exc) {
+ ValidationPlugin.getPlugin().logMessage(IStatus.ERROR, exc.toString());
+ }
+}
- /**
- * @param referenced
- * @return
- */
private boolean isReferencedProjectInDelta(IProject[] referenced) {
IProject p = null;
for (int i = 0; i < referenced.length; i++) {
@@ -243,10 +248,6 @@
return false;
}
- /**
- * @param monitor
- * @param prjp
- */
private void performFullBuildForReferencedProjectChanged(IProgressMonitor monitor, ProjectConfiguration prjp) throws InvocationTargetException {
performFullBuild(monitor, prjp, true);
}
@@ -258,46 +259,45 @@
private void performFullBuild(IProgressMonitor monitor, ProjectConfiguration prjp, boolean onlyDependentValidators) throws InvocationTargetException {
ValidatorMetaData[] enabledValidators = prjp.getEnabledFullBuildValidators(true, onlyDependentValidators);
if ((enabledValidators != null) && (enabledValidators.length > 0)) {
- Set enabledValidatorsSet = InternalValidatorManager.wrapInSet(enabledValidators);
+ Set<ValidatorMetaData> enabledValidatorsSet = InternalValidatorManager.wrapInSet(enabledValidators);
EnabledValidatorsOperation op = new EnabledValidatorsOperation(getProject(), enabledValidatorsSet, true);
op.run(monitor);
}
}
+
+ /**
+ * Run the new validation builder. This is a transition method, while we continue to have
+ * the old and new validation builders.
+ *
+ * @param kind the kind of build
+ *
+ * @see IncrementalProjectBuilder#AUTO_BUILD
+ * @see IncrementalProjectBuilder#CLEAN_BUILD
+ * @see IncrementalProjectBuilder#FULL_BUILD
+ * @see IncrementalProjectBuilder#INCREMENTAL_BUILD
+ */
+ private void newBuild(int kind, IProgressMonitor monitor) throws CoreException {
- private void logInvocationTargetException(Logger logger, InvocationTargetException exc) {
- if (logger.isLoggingLevel(Level.SEVERE)) {
- LogEntry entry = ValidationPlugin.getLogEntry();
- entry.setSourceID("ValidationBuilder::build"); //$NON-NLS-1$
- entry.setTargetException(exc);
- logger.write(Level.SEVERE, entry);
- if (exc.getTargetException() != null) {
- entry.setTargetException(exc);
- logger.write(Level.SEVERE, entry);
- }
+ IResourceDelta delta = null;
+ IProject project = getProject();
+
+ switch (kind){
+ case AUTO_BUILD:
+ case INCREMENTAL_BUILD:
+ delta = getDelta(project);
+ break;
}
+
+ ValBuilderJob.validateProject(project, delta, kind);
}
-
- private void logBuildError(Logger logger, Throwable exc) {
- if (logger.isLoggingLevel(Level.SEVERE)) {
- if( ! (exc instanceof OperationCanceledException) ){
- LogEntry entry = ValidationPlugin.getLogEntry();
- entry.setSourceID("ValidationBuilder.build(int, Map, IProgressMonitor)"); //$NON-NLS-1$
- entry.setTargetException(exc);
- logger.write(Level.SEVERE, entry);
- }
- }
- }
-
- private void logBuilderTimeEntry(long start, int executionMap, Logger logger, IResourceDelta delta) {
- TimeEntry entry = ValidationPlugin.getTimeEntry();
- entry.setSourceID("ValidationBuilder.build(int, Map, IProgressMonitor)"); //$NON-NLS-1$
- entry.setProjectName(getProject().getName()); //$NON-NLS-1$ //$NON-NLS-2$
- entry.setExecutionMap(executionMap);
- entry.setElapsedTime(System.currentTimeMillis() - start);
- if (delta == null) {
- entry.setDetails("delta == null"); //$NON-NLS-1$
- }
- entry.setToolName("ValidationBuilder"); //$NON-NLS-1$
- logger.write(Level.FINE, entry);
- }
-}
\ No newline at end of file
+
+
+ /**
+ * Run the new clean method. This is a transition method, while we continue to have
+ * the old and new validation builders.
+ */
+ private void newClean(IProgressMonitor monitor) throws CoreException {
+ ValManager.getDefault().clean(getProject(), monitor);
+ }
+
+}
diff --git a/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/operations/ValidationConstants.java b/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/operations/ValidationConstants.java
index 1e37524..260fa72 100644
--- a/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/operations/ValidationConstants.java
+++ b/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/operations/ValidationConstants.java
@@ -1,10 +1,10 @@
/*******************************************************************************
- * Copyright (c) 2001, 2004 IBM Corporation and others.
+ * Copyright (c) 2001, 2005 IBM Corporation 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:
* IBM Corporation - initial API and implementation
*******************************************************************************/
@@ -22,4 +22,4 @@
*/
public interface ValidationConstants extends ResourceConstants {
//Default
-}
\ No newline at end of file
+}
diff --git a/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/operations/ValidationOperation.java b/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/operations/ValidationOperation.java
index a7d5a21..c9f7b53 100644
--- a/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/operations/ValidationOperation.java
+++ b/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/operations/ValidationOperation.java
@@ -1,25 +1,24 @@
/*******************************************************************************
- * Copyright (c) 2001, 2004 IBM Corporation and others.
+ * Copyright (c) 2001, 2009 IBM Corporation 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:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.wst.validation.internal.operations;
-
import java.text.MessageFormat;
import java.util.ArrayList;
-import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
+import java.util.LinkedList;
import java.util.List;
import java.util.Map;
+import java.util.Queue;
import java.util.Set;
-import java.util.logging.Level;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
@@ -32,7 +31,6 @@
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.OperationCanceledException;
import org.eclipse.core.runtime.QualifiedName;
import org.eclipse.core.runtime.Status;
@@ -40,9 +38,8 @@
import org.eclipse.core.runtime.jobs.ISchedulingRule;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.core.runtime.jobs.JobChangeAdapter;
-import org.eclipse.jem.util.logger.LogEntry;
-import org.eclipse.jem.util.logger.proxy.Logger;
import org.eclipse.wst.common.frameworks.internal.operations.IHeadlessRunnableWithProgress;
+import org.eclipse.wst.validation.ValidationFramework;
import org.eclipse.wst.validation.internal.FilterUtil;
import org.eclipse.wst.validation.internal.IProjectValidationHelper;
import org.eclipse.wst.validation.internal.InternalValidatorManager;
@@ -51,7 +48,8 @@
import org.eclipse.wst.validation.internal.ResourceConstants;
import org.eclipse.wst.validation.internal.ResourceHandler;
import org.eclipse.wst.validation.internal.TaskListUtility;
-import org.eclipse.wst.validation.internal.TimeEntry;
+import org.eclipse.wst.validation.internal.Tracing;
+import org.eclipse.wst.validation.internal.ValManager;
import org.eclipse.wst.validation.internal.ValidationRegistryReader;
import org.eclipse.wst.validation.internal.ValidatorMetaData;
import org.eclipse.wst.validation.internal.core.IFileDelta;
@@ -63,44 +61,86 @@
import org.eclipse.wst.validation.internal.provisional.core.IValidationContext;
import org.eclipse.wst.validation.internal.provisional.core.IValidator;
import org.eclipse.wst.validation.internal.provisional.core.IValidatorJob;
-import org.eclipse.wst.validation.internal.provisional.core.MessageLimitException;
/**
- * Implemented Validators methods must not be called directly by anyone other than this class, since
+ * Validators must not be called directly by anyone other than this class, since
* some initialization of the validator is done here (via the getProject() method). The
* initialization is separated because the IProject isn't known until runtime.
- *
+ * <p>
* This operation is not intended to be subclassed outside of the validation framework.
+ * </p>
*/
public abstract class ValidationOperation implements IWorkspaceRunnable, IHeadlessRunnableWithProgress {
- public static final int NO_DELTA_CHANGE = -1; // Since IResourceConstants
- // doesn't have a "no delta"
- // flag, let this constant be
- // the flag.
+ // Since IResourceConstants don't have a "no delta" flag, let this constant be the flag.
+ public static final int NO_DELTA_CHANGE = -1;
private static final String DELTA_AS_STRING = "IFileDelta[{0}] '{'{1}'}'"; //$NON-NLS-1$
private static final String COMMA = ", "; //$NON-NLS-1$
- protected static final boolean DEFAULT_ASYNC = true; // For the deprecated
- // constructors, by
- // default the
- // operation will not
- // fork.
- protected static final boolean DEFAULT_FORCE = true; // By default, run the
- protected static final String VALIDATIONLAUNCHERMSG = "Waiting for build"; // By default, run the
- // operation whether
- // or not it needs to
- class ValidationLauncherJob extends Job {
- private Job validationJob;
- public ValidationLauncherJob(Job validationJob) {
- super(ResourceHandler.getExternalizedMessage("VBF_VALIDATION_JOB_MSG"));
-
- setSystem(true);
- setRule(ResourcesPlugin.getWorkspace().getRoot());
- this.validationJob= validationJob;
+ // For the depreciated constructors, by default the operation will not fork.
+ protected static final boolean DEFAULT_ASYNC = true;
+
+ protected static final boolean DEFAULT_FORCE = true;
+
+ private static ValidationLauncherJob launcherJob = new ValidationLauncherJob();
+
+ private static final int jobsPerProcessor = 3;
+
+ private final static class ValidationLauncherJob extends Job {
+ private Queue<Job> _validationJobs = new LinkedList<Job>();
+
+ public ValidationLauncherJob() {
+ super(ResourceHandler.getExternalizedMessage(ResourceConstants.VBF_VALIDATION_JOB_MSG));
+ setSystem(true);
+ setRule(ResourcesPlugin.getWorkspace().getRoot());
}
+
protected IStatus run(IProgressMonitor monitor) {
- validationJob.schedule();
- return Status.OK_STATUS;
+ int processors = Runtime.getRuntime().availableProcessors();
+ int totalInitialJobs = processors * jobsPerProcessor;
+ synchronized (_validationJobs) {
+ // never schedule more than 3 validation jobs per processor at a time
+ for (int i=0; i< totalInitialJobs; i++) {
+ Job validationJob = _validationJobs.poll();
+ if (validationJob == null) break;
+ addJobChangeAdapter(validationJob);
+ validationJob.schedule();
+ }
+ }
+ return Status.OK_STATUS;
+ }
+
+ private void addJobChangeAdapter(Job job) {
+ job.addJobChangeListener(new JobChangeAdapter(){
+ // when done, see if there is another validation job to schedule
+ public void done(IJobChangeEvent event) {
+ synchronized (_validationJobs) {
+ Job validationJob = _validationJobs.poll();
+ if (validationJob != null) {
+ addJobChangeAdapter(validationJob);
+ validationJob.schedule();
+ }
+ }
+ }
+ });
+ }
+
+ @Override
+ public boolean belongsTo(Object family) {
+ if (family == ResourcesPlugin.FAMILY_MANUAL_BUILD)return true;
+ if (family == ValidationBuilder.FAMILY_VALIDATION_JOB){
+ return true;
+ }
+ return super.belongsTo(family);
+ }
+
+ public void addValidationJob(Job validationJob) {
+ synchronized (_validationJobs) {
+ _validationJobs.add(validationJob);
+ // schedule the job if we were empty
+ if (_validationJobs.size() == 1) {
+ this.schedule();
+ }
+ }
}
}
@@ -108,38 +148,29 @@
* @deprecated Will be removed in Milestone 3. Use DEFAULT_ASYNC
*/
protected static final boolean DEFAULT_FORK = false; // @deprecated
- private IProject _project = null; // project to be validated
- private int _ruleGroup = RegistryConstants.ATT_RULE_GROUP_DEFAULT; // which
- // pass
- // should
- // the
- // validation
- // invoke
+ private IProject _project; // project to be validated
+ private int _ruleGroup = RegistryConstants.ATT_RULE_GROUP_DEFAULT;
private boolean _fork = DEFAULT_ASYNC; // do not fork the validation into a
// different thread by default
- private Map _fileDeltas = null; // To reduce object creation,
- private IResourceDelta _delta = null;
+ private Map<ValidatorMetaData, Set<IFileDelta>> _fileDeltas; // To reduce object creation,
+ private IResourceDelta _delta;
+
// the resource delta tree to be processed, or null if a full build/menu
// option was triggered. This value is cached so that validation can be run
// either from a builder, or from a menu item. (The Operation interface
// doesn't allow any parameter on execute except the IProgressMonitor.)
- private Set _enabledValidators = null;
- private boolean _force = DEFAULT_FORCE; // force this operation to run even
- // if it doesn't need to?
- private boolean _isFullValidate = false; // Run a full validation or an
- // incremental? (true = full)
- private Boolean _isAutoBuild = null; // Is the global auto-build preference
- // enabled?
- private Set _launchedValidators = null; // A list of the validators that
+ private Set<ValidatorMetaData> _enabledValidators;
+
+ private boolean _force = DEFAULT_FORCE; // force this operation to run even if it doesn't need to?
+ private boolean _isFullValidate; // Run a full validation or an incremental? (true = full)
+ private Boolean _isAutoBuild; // Is the global auto-build preference enabled?
+ private Set<ValidatorMetaData> _launchedValidators;
protected IWorkbenchContext context;
- // are enabled and were launched
- // (i.e., that have input to
- // validate). For internal
+ // are enabled and were launched (i.e., that have input to validate). For internal
// validation framework use only;
- // it's needed for the automatic
- // tests.
+ // it's needed for the automatic tests.
/**
* This method is used for FINEST logging, to report exactly what deltas were about to be
* validated.
@@ -157,13 +188,12 @@
buffer.replace(0, 1, ""); //$NON-NLS-1$ // magic numbers 0 and 1 => Remove first COMMA from the list (hence index 0); length of COMMA is 2, hence index 0, 1.
args = buffer.toString();
}
- return MessageFormat.format(DELTA_AS_STRING, new String[]{String.valueOf(numArgs), args});
+ return MessageFormat.format(DELTA_AS_STRING, new Object[]{String.valueOf(numArgs), args});
}
protected static void checkCanceled(WorkbenchReporter reporter) throws OperationCanceledException {
- if (reporter == null) {
- return;
- } else if (reporter.getProgressMonitor().isCanceled()) {
+ if (reporter == null)return;
+ else if (reporter.getProgressMonitor().isCanceled()) {
throw new OperationCanceledException(""); //$NON-NLS-1$
}
}
@@ -216,7 +246,7 @@
_ruleGroup = ruleGroup;
_fork = fork;
_force = force;
- _enabledValidators = new HashSet();
+ _enabledValidators = new HashSet<ValidatorMetaData>();
}
/**
@@ -230,7 +260,7 @@
_ruleGroup = ruleGroup;
_fork = fork;
_force = force;
- _enabledValidators = new HashSet();
+ _enabledValidators = new HashSet<ValidatorMetaData>();
context = aContext;
}
@@ -238,26 +268,14 @@
* @deprecated Will be removed in Milestone 3.
*/
protected void terminateCleanup(WorkbenchReporter reporter) {
- Set enabledValidators = getEnabledValidators();
- Iterator iterator = enabledValidators.iterator();
- ValidatorMetaData vmd = null;
-
- while (iterator.hasNext()) {
- vmd = (ValidatorMetaData) iterator.next();
+ for (ValidatorMetaData vmd : getEnabledValidators()) {
reporter.displaySubtask(ResourceHandler.getExternalizedMessage(ResourceConstants.VBF_STATUS_VALIDATOR_CLEANUP, new String[]{vmd.getValidatorDisplayName()}));
try {
reporter.removeAllMessages(vmd.getValidator());
- } catch (InstantiationException exc) {
+ } catch (InstantiationException e) {
// Remove the vmd from the reader's list
ValidationRegistryReader.getReader().disableValidator(vmd);
- // Log the reason for the disabled validator
- final Logger logger = ValidationPlugin.getPlugin().getMsgLogger();
- if (logger.isLoggingLevel(Level.SEVERE)) {
- LogEntry entry = ValidationPlugin.getLogEntry();
- entry.setSourceID("ValidationOperation::terminateCleanup"); //$NON-NLS-1$
- entry.setTargetException(exc);
- logger.write(Level.SEVERE, entry);
- }
+ ValidationPlugin.getPlugin().handleException(e);
continue;
}
addCancelTask(vmd);
@@ -476,19 +494,8 @@
* run automatically.)
*/
private boolean isValidationNecessary(ValidatorMetaData vmd, IFileDelta[] delta) {
- // Validation is not necessary if:
- // 1. auto-validation has run and the validator is incremental,
- // 2. There are no files for the validator to validate.
- // There are files to validate if this is a full validation or if the
- // validator filtered in some of the deltas.
- boolean autoValidateRan = false;
- if (_isAutoBuild != null) {
- // User set the autoBuild default, so check if validation is
- // necessary or not.
- autoValidateRan = ValidatorManager.getManager().isAutoValidate(getProject(), _isAutoBuild.booleanValue()) && vmd.isIncremental();
- }
- boolean hasFiles = (isFullValidate() || (delta.length > 0));
- return (!autoValidateRan && hasFiles);
+ // Validation is not necessary if there are no files for the validator to validate.
+ return isFullValidate() || (delta.length > 0);
}
/**
@@ -496,35 +503,27 @@
* operation to do.
*/
public boolean isNecessary(IProgressMonitor monitor) throws CoreException, OperationCanceledException {
- Set enabledValidators = getEnabledValidators();
+ Set<ValidatorMetaData> enabledValidators = getEnabledValidators();
if ((enabledValidators == null) || (enabledValidators.size() == 0)) {
return false;
}
- if (isFullValidate()) {
- return true;
- }
- Iterator iterator = enabledValidators.iterator();
- while (iterator.hasNext()) {
- ValidatorMetaData vmd = (ValidatorMetaData) iterator.next();
- if (isValidationNecessary(vmd, getFileDeltas(monitor, vmd))) {
- return true;
- }
+ if (isFullValidate())return true;
+
+ for (ValidatorMetaData vmd : enabledValidators) {
+ if (isValidationNecessary(vmd, getFileDeltas(monitor, vmd)))return true;
}
return false;
}
- private Map getFileDeltas(IProgressMonitor monitor) throws CoreException {
- if (_fileDeltas == null) {
- loadFileDeltas(monitor);
- }
+ private Map<ValidatorMetaData, Set<IFileDelta>> getFileDeltas(IProgressMonitor monitor) throws CoreException {
+ if (_fileDeltas == null)loadFileDeltas(monitor);
return _fileDeltas;
}
private IFileDelta[] getFileDeltas(IProgressMonitor monitor, ValidatorMetaData vmd) throws CoreException {
- Set result = (Set) getFileDeltas(monitor).get(vmd);
- if (result == null) {
- return new IFileDelta[0];
- }
+ Set<IFileDelta> result = getFileDeltas(monitor).get(vmd);
+ if (result == null)return new IFileDelta[0];
+
IFileDelta[] temp = new IFileDelta[result.size()];
result.toArray(temp);
return temp;
@@ -550,7 +549,7 @@
}
}
- protected void setFileDeltas(Map deltas) {
+ protected void setFileDeltas(Map<ValidatorMetaData, Set<IFileDelta>> deltas) {
_fileDeltas = deltas;
}
@@ -570,7 +569,7 @@
* Return the validators which are both configured on this type of project, (as stored in
* getProject()), and enabled by the user on this project.
*/
- public Set getEnabledValidators() {
+ public Set<ValidatorMetaData> getEnabledValidators() {
return _enabledValidators;
}
@@ -578,21 +577,19 @@
* This is an internal method, subject to change without notice. It is provided only for the
* automated validation framework tests.
*/
- public Set getLaunchedValidators() {
+ public Set<ValidatorMetaData> getLaunchedValidators() {
if (_launchedValidators == null) {
- _launchedValidators = new HashSet();
+ _launchedValidators = new HashSet<ValidatorMetaData>();
}
return _launchedValidators;
}
- protected void setEnabledValidators(Set evmds) {
+ protected void setEnabledValidators(Set<ValidatorMetaData> evmds) {
// Check that every VMD in the set is configured on this project.
// Necessary because the user can manually choose which validators
// to launch, and the validator may not be installed.
_enabledValidators.clear();
- Iterator iterator = evmds.iterator();
- while (iterator.hasNext()) {
- ValidatorMetaData vmd = (ValidatorMetaData) iterator.next();
+ for (ValidatorMetaData vmd : evmds) {
if (ValidationRegistryReader.getReader().isConfiguredOnProject(vmd, getProject())) {
_enabledValidators.add(vmd);
}
@@ -608,10 +605,10 @@
protected int getUnitsOfWork() {
/*
- * // Let one unit of work equal one resource. number of enabled validators // i.e., each
+ * Let one unit of work equal one resource. number of enabled validators. i.e., each
* enabled validator must process (at most) each resource in the project; count each process
- * as one unit of work // Note that this is a ceiling number, because if we're doing an
- * incremental validation, not all resources will // be validated.
+ * as one unit of work. Note that this is a ceiling number, because if we're doing an
+ * incremental validation, not all resources will be validated.
* setNumResources(countResources(getProject())); getEnabledValidators().size();
*/
// Until the validators can report units-of-work complete,
@@ -636,17 +633,13 @@
* The IProgressMonitor passed in must not be null.
*/
public void run(IProgressMonitor progressMonitor) throws OperationCanceledException {
- long start = System.currentTimeMillis();
- final Logger logger = ValidationPlugin.getPlugin().getMsgLogger();
try {
- // In order to check whether or not the monitor has been cancelled,
- // the monitor must not be null.
- if (progressMonitor == null) {
- return;
- }
- if (ValidatorManager.getManager().isSuspended(getProject())) {
- return;
- }
+ // In order to check whether or not the monitor has been canceled, the monitor must not be null.
+ if (progressMonitor == null)return;
+ IProject project = getProject();
+ if (ValidationFramework.getDefault().isSuspended(project))return;
+ if (ValManager.getDefault().isDisabled(project))return;
+
if (!areValidatorsEnabled()) {
// save some processing time...
return;
@@ -655,35 +648,28 @@
final WorkbenchReporter reporter = new WorkbenchReporter(getProject(), progressMonitor);
try {
- // Periodically check if the user has cancelled the operation
+ // Periodically check if the user has canceled the operation
checkCanceled(reporter);
preValidate(reporter);
validate(reporter);
validateReferencialFiles(reporter);
- } catch (CoreException exc) {
- if (logger.isLoggingLevel(Level.SEVERE)) {
- LogEntry entry = ValidationPlugin.getLogEntry();
- entry.setSourceID("ValidationOperation.run"); //$NON-NLS-1$
- entry.setTargetException(exc);
- logger.write(Level.SEVERE, entry);
- }
+ } catch (CoreException e) {
+ ValidationPlugin.getPlugin().handleException(e);
}
} finally {
- if (logger.isLoggingLevel(Level.FINE)) {
- long finish = System.currentTimeMillis();
- TimeEntry entry = ValidationPlugin.getTimeEntry();
- entry.setSourceID("ValidationOperation.run(WorkbenchMonitor)"); //$NON-NLS-1$
- entry.setProjectName(getProject().getName());
- entry.setToolName("ValidationOperation"); //$NON-NLS-1$
- entry.setElapsedTime(finish - start);
- logger.write(Level.FINE, entry);
- }
+ //TODO GRK determine if timing info should be added here
+// if (logger.isLoggingLevel(Level.FINE)) {
+// long finish = System.currentTimeMillis();
+// TimeEntry entry = ValidationPlugin.getTimeEntry();
+// entry.setSourceID("ValidationOperation.run(WorkbenchMonitor)"); //$NON-NLS-1$
+// entry.setProjectName(getProject().getName());
+// entry.setToolName("ValidationOperation"); //$NON-NLS-1$
+// entry.setElapsedTime(finish - start);
+// logger.write(Level.FINE, entry);
+// }
}
}
- /**
- * @param reporter
- */
private void validateReferencialFiles(WorkbenchReporter reporter) {
ReferencialFileValidatorRegistryReader reader = ReferencialFileValidatorRegistryReader.getInstance();
if (reader != null) {
@@ -699,14 +685,11 @@
}
}
- /**
- * @param reporter
- * @param referencialFileValidator
- */
private void refFileValidateFileDelta(WorkbenchReporter reporter, ReferencialFileValidator refFileValidator) {
IResourceDelta[] resourceDelta = _delta.getAffectedChildren(IResourceDelta.ADDED | IResourceDelta.CHANGED | IResourceDelta.REMOVED);
- List inputFiles = new ArrayList();
- List referencingFiles = new ArrayList();
+ List<IResource> inputFiles = new ArrayList<IResource>();
+
+ List<IFile> referencingFiles = new ArrayList<IFile>();
if (resourceDelta != null && resourceDelta.length > 0) {
for (int i = 0; i < resourceDelta.length; i++) {
IResource resource = resourceDelta[i].getResource();
@@ -715,88 +698,66 @@
} else if (resource instanceof IFile)
inputFiles.add(resource);
}
- List rFilesToValidate = refFileValidator.getReferencedFile(inputFiles);
+ List<IFile> rFilesToValidate = refFileValidator.getReferencedFile(inputFiles);
if (rFilesToValidate != null && !rFilesToValidate.isEmpty())
referencingFiles.addAll(rFilesToValidate);
try {
if (!referencingFiles.isEmpty())
validateReferencingFiles(reporter, referencingFiles);
} catch (Exception e) {
- Logger.getLogger().log(e);
+ ValidationPlugin.getPlugin().handleException(e);
}
}
}
- /**
- * @param delta
- * @return
- */
- private void getFileResourceDeltaInFolder(IResourceDelta delta, List inputFiles) {
+ private void getFileResourceDeltaInFolder(IResourceDelta delta, List<IResource> inputFiles) {
IResourceDelta[] resourceDelta = delta.getAffectedChildren();
for (int i = 0; i < resourceDelta.length; i++) {
IResource resource = resourceDelta[i].getResource();
- if (resource instanceof IFile) {
- inputFiles.add(resource);
- } else if (resource instanceof IFolder)
- getFileResourceDeltaInFolder(resourceDelta[i], inputFiles);
+ if (resource instanceof IFile)inputFiles.add(resource);
+ else if (resource instanceof IFolder)getFileResourceDeltaInFolder(resourceDelta[i], inputFiles);
}
}
- /**
- * @param reporter
- * @param referencialFileValidator
- */
private void postValidateProject(WorkbenchReporter reporter, ReferencialFileValidator refFileValidator) {
- Set set = ValidationRegistryReader.getReader().getValidatorMetaData(_project);
- Iterator it = set.iterator();
- while (it.hasNext()) {
- ValidatorMetaData data = (ValidatorMetaData) it.next();
- List filters = data.getNameFilters();
- List files = getAllFilesForFilter(filters);
+ Set<ValidatorMetaData> set = ValidationRegistryReader.getReader().getValidatorMetaData(_project);
+ for (ValidatorMetaData data : set) {
+ List<String> filters = data.getNameFilters();
+ List<IFile> files = getAllFilesForFilter(filters);
if (!files.isEmpty()) {
- List fileForValidation = refFileValidator.getReferencedFile(files);
+ List<IFile> fileForValidation = refFileValidator.getReferencedFile(files);
try {
validateReferencingFiles(reporter, fileForValidation);
} catch (Exception e) {
- Logger.getLogger().log(e);
+ ValidationPlugin.getPlugin().handleException(e);
}
}
}
}
- /**
- * @param filters
- * @return
- */
- private List getAllFilesForFilter(List filters) {
+ private List<IFile> getAllFilesForFilter(List<String> filters) {
if (!filters.isEmpty()) {
- List allProjectFiles = ReferencialFileValidatorHelper.getAllProjectFiles(_project);
- List filterFiles = new ArrayList();
- for (int i = 0; i < filters.size(); i++) {
- String fileName = (String) filters.get(i);
- if (fileName == null)
- continue;
- for (int j = 0; j < allProjectFiles.size(); j++) {
- IFile projectFile = (IFile) allProjectFiles.get(j);
+ List<IFile> allProjectFiles = ReferencialFileValidatorHelper.getAllProjectFiles(_project);
+ List<IFile> filterFiles = new ArrayList<IFile>();
+ for (String fileName : filters) {
+ if (fileName == null)continue;
+
+ for (IFile projectFile : allProjectFiles) {
if (fileName.charAt(0) == '*') {
String extName = fileName.substring(2, fileName.length());
String ext = projectFile.getFileExtension();
- if (ext != null && ext.equals(extName))
- filterFiles.add(projectFile);
- } else if (fileName.equals(projectFile.getName()))
- filterFiles.add(projectFile);
+ if (ext != null && ext.equals(extName))filterFiles.add(projectFile);
+ } else if (fileName.equals(projectFile.getName()))filterFiles.add(projectFile);
}
-
}
return filterFiles;
}
- return Collections.EMPTY_LIST;
+ return new LinkedList<IFile>();
}
- private void validateReferencingFiles(IReporter reporter, List referencingFiles) throws Exception {
- HashSet validatedFiles = new HashSet();
- for (int i = 0; i < referencingFiles.size(); i++) {
- IFile refFile = (IFile) referencingFiles.get(i);
+ private void validateReferencingFiles(IReporter reporter, List<IFile> referencingFiles) throws Exception {
+ Set<IFile> validatedFiles = new HashSet<IFile>();
+ for (IFile refFile : referencingFiles) {
if (!validatedFiles.contains(refFile)) {
IResource resource = refFile.getParent();
IProject project = null;
@@ -805,13 +766,10 @@
else
project = (IProject) resource;
if (project != null) {
- Set set = ValidationRegistryReader.getReader().getValidatorMetaData(project);
-// IFileDelta[] changedfiles = new FileDelta[]{new WorkbenchFileDelta(refFile.getProjectRelativePath().toString(), IFileDelta.CHANGED, refFile)};
- Iterator it = set.iterator();
- while (it.hasNext()) {
- ValidatorMetaData data = (ValidatorMetaData) it.next();
+ Set<ValidatorMetaData> set = ValidationRegistryReader.getReader().getValidatorMetaData(project);
+ for (ValidatorMetaData data : set) {
if (data.isApplicableTo(refFile)) {
- IValidator validator = (IValidator)data.getValidator();
+ IValidator validator = data.getValidator();
validator.validate(data.getHelper(project),reporter);
validatedFiles.add(refFile);
}
@@ -838,83 +796,60 @@
* thread, and the not-thread-safe validators in this thread.
*/
protected void validate(WorkbenchReporter reporter) throws OperationCanceledException {
- if (reporter == null) {
- return;
- }
+ if (reporter == null)return;
checkCanceled(reporter);
reporter.getProgressMonitor().beginTask(ResourceHandler.getExternalizedMessage(ResourceConstants.VBF_STATUS_PROGRESSMONITOR_TITLE), getUnitsOfWork());
IValidator validator = null;
- ValidatorMetaData vmd = null;
- Iterator iterator = null;
- WorkbenchReporter nullReporter = new WorkbenchReporter(getProject(), new NullProgressMonitor());
- final Logger logger = ValidationPlugin.getPlugin().getMsgLogger();
+ Iterator<ValidatorMetaData> iterator = null;
IFileDelta[] delta = null;
- HashSet jobValidators = new HashSet();
- HashSet validators = new HashSet();
-
-
- iterator = getEnabledValidators().iterator();
-
- while( iterator.hasNext() ){
- vmd = (ValidatorMetaData) iterator.next();
- IValidator valInstance = null;
- try {
- valInstance = vmd.getValidator();
- } catch (InstantiationException e1) {
- if(!ValidatorManager.getManager().getProblemValidators().contains(vmd)) {
- ValidatorManager.getManager().getProblemValidators().add(vmd);
- System.out.println(e1.getMessage());
- }
- }
+ Set<ValidatorMetaData> jobValidators = new HashSet<ValidatorMetaData>();
+ Set<ValidatorMetaData> validators = new HashSet<ValidatorMetaData>();
- if( isFork() && (valInstance != null) && valInstance instanceof IValidatorJob ){
- try {
- delta = getFileDeltas(reporter.getProgressMonitor(), vmd);
- } catch (CoreException e) {
- e.printStackTrace();
- }
- boolean willRun = (isForce() || isValidationNecessary(vmd, delta));
- if( willRun ){
- jobValidators.add( vmd );
- }
- }else if (valInstance != null){
- validators.add( vmd );
+ for(ValidatorMetaData vmd : getEnabledValidators()){
+ IValidator valInstance = null;
+ try {
+ valInstance = vmd.getValidator();
+ }
+ catch (InstantiationException e1) {
+ if(!ValidatorManager.getManager().getProblemValidators().contains(vmd)) {
+ ValidatorManager.getManager().getProblemValidators().add(vmd);
+ System.out.println(e1.getMessage());
}
}
- if( jobValidators.size() > 0 ){
- launchJobs( jobValidators, reporter );
- }
-
-
- try {
- //iterator = getEnabledValidators().iterator();
- iterator = validators.iterator();
- // In order to allow validators to run, must first check if there's
- // space for new markers.
- // But we don't want the old markers to prevent validation from
- // running again, so delete all
- // of the old markers first, and then run validation.
- while (iterator.hasNext()) {
- vmd = (ValidatorMetaData) iterator.next();
+ if( isFork() && (valInstance != null) && valInstance instanceof IValidatorJob ){
+ try {
+ delta = getFileDeltas(reporter.getProgressMonitor(), vmd);
+ } catch (CoreException e) {
+ e.printStackTrace();
+ }
+ boolean willRun = (isForce() || isValidationNecessary(vmd, delta));
+ if( willRun )jobValidators.add( vmd );
+ }
+ else if (valInstance != null){
+ validators.add( vmd );
+ }
+ }
+ if( jobValidators.size() > 0 ){
+ launchJobs( jobValidators, reporter );
+ }
+
+ ValidatorMetaData currentVmd = null;
+ try {
+ for (ValidatorMetaData vmd : validators) {
+ currentVmd = vmd;
// Is validation about to be run on this validator?
- // Validation will run either if this operation forces
- // regardless
+ // Validation will run either if this operation forces regardless
// of need, or if the validator was not run automatically.
// If validation is not about to be run, then don't activate
- // the plugin
+ // the plug-in
try {
delta = getFileDeltas(reporter.getProgressMonitor(), vmd);
boolean willRun = (isForce() || isValidationNecessary(vmd, delta));
- if (logger.isLoggingLevel(Level.FINEST)) {
- TimeEntry entry = ValidationPlugin.getTimeEntry();
- entry.setSourceID("ValidationOperation.validate(WorkbenchReporter)"); //$NON-NLS-1$
- entry.setProjectName(getProject().getName());
- entry.setToolName(vmd.getValidatorUniqueName());
- entry.setElapsedTime(0);
+ if (Tracing.isTraceV1()) {
StringBuffer buffer = new StringBuffer();
- buffer.append("will run? "); //$NON-NLS-1$
+ buffer.append("ValidationOperation-01: will run? "); //$NON-NLS-1$
buffer.append(willRun);
buffer.append(" "); //$NON-NLS-1$
buffer.append("is force? "); //$NON-NLS-1$
@@ -924,8 +859,6 @@
buffer.append(_isAutoBuild);
buffer.append(" "); //$NON-NLS-1$
buffer.append("isAutoValidate? "); //$NON-NLS-1$
- boolean autoBuild = (_isAutoBuild == null) ? ValidatorManager.getManager().isGlobalAutoBuildEnabled() : _isAutoBuild.booleanValue();
- buffer.append(ValidatorManager.getManager().isAutoValidate(getProject(), autoBuild));
buffer.append(" "); //$NON-NLS-1$
buffer.append("isIncremental? "); //$NON-NLS-1$
buffer.append(vmd.isIncremental());
@@ -939,33 +872,15 @@
buffer.append(getDeltaAsString(delta));
}
}
- entry.setDetails(buffer.toString());
- logger.write(Level.FINEST, entry);
+ Tracing.log(buffer);
}
if (!willRun) {
continue;
}
- } catch (CoreException exc) {
- if (logger.isLoggingLevel(Level.SEVERE)) {
- LogEntry entry = ValidationPlugin.getLogEntry();
- entry.setSourceID("ValidationOperation.validate(WorkbenchReporter)"); //$NON-NLS-1$
- entry.setTargetException(exc);
- logger.write(Level.SEVERE, entry);
- }
+ } catch (CoreException e) {
+ ValidationPlugin.getPlugin().handleException(e);
String mssg = ResourceHandler.getExternalizedMessage(ResourceConstants.VBF_STATUS_ENDING_VALIDATION_ABNORMALLY, new String[]{getProject().getName(), vmd.getValidatorDisplayName()});
reporter.displaySubtask(mssg);
- /*
- The code below causes bundle not found exception since, the bundle here is
- validate_base and we are trying to load that bundle from the classloader of
- the Validator.
-
- String[] msgParm = {exc.getClass().getName(), vmd.getValidatorDisplayName(), (exc.getMessage() == null ? "" : exc.getMessage())}; //$NON-NLS-1$
- Message message = ValidationPlugin.getMessage();
- message.setSeverity(IMessage.NORMAL_SEVERITY);
- message.setId(ResourceConstants.VBF_EXC_RUNTIME);
- message.setParams(msgParm);
- reporter.addMessage(validator, message);
- */
continue;
}
try {
@@ -975,16 +890,10 @@
checkCanceled(reporter);
- } catch (InstantiationException exc) {
+ } catch (InstantiationException e) {
// Remove the vmd from the reader's list
ValidationRegistryReader.getReader().disableValidator(vmd);
- // Log the reason for the disabled validator
- if (logger.isLoggingLevel(Level.SEVERE)) {
- LogEntry entry = ValidationPlugin.getLogEntry();
- entry.setSourceID("ValidationOperation::validate(WorkbenchReporter)"); //$NON-NLS-1$
- entry.setTargetException(exc);
- logger.write(Level.SEVERE, entry);
- }
+ ValidationPlugin.getPlugin().handleException(e);
continue;
}
@@ -998,23 +907,19 @@
// } else {
// internalValidate(reporter, validator, vmd, context, delta);
// }
- internalValidate(reporter, (IValidator)validator, vmd, context, delta);
- }
- } catch (OperationCanceledException exc) {
- handleOperationCancelledValidateException(reporter, validator, vmd, iterator, logger, exc);
- } finally {
+ internalValidate(reporter, validator, vmd, context, delta);
+ }
+ }
+ catch (OperationCanceledException exc) {
+ handleOperationCancelledValidateException(reporter, validator, currentVmd, iterator, exc);
+ }
+ finally {
releaseCachedMaps();
}
}
- /**
- *
- */
private void releaseCachedMaps() {
- if (ValidationRegistryReader.getReader().projectValidationMetaData != null) {
- ValidationRegistryReader.getReader().projectValidationMetaData.clear();
- ValidationRegistryReader.getReader().projectValidationMetaData = null;
- }
+ ValidationRegistryReader.getReader().clearCachedMaps();
IProjectValidationHelper helper = ValidationHelperRegistryReader.getInstance().getValidationHelper();
if (helper != null)
helper.disposeInstance();
@@ -1022,9 +927,8 @@
private void initValidateContext(IFileDelta[] delta) {
if (context instanceof WorkbenchContext) {
- ((WorkbenchContext)context).setValidationFileURIs(new ArrayList());
- for(int i = 0; i < delta.length; i++) {
- IFileDelta file = delta[i];
+ ((WorkbenchContext)context).setValidationFileURIs(new ArrayList<String>());
+ for(IFileDelta file : delta) {
if(file.getDeltaType() != IFileDelta.DELETED ) {
((WorkbenchContext)context).getValidationFileURIs().add(file.getFileName());
}
@@ -1040,7 +944,8 @@
* @param logger
* @param exc
*/
- private void handleOperationCancelledValidateException(WorkbenchReporter reporter, IValidator validator, ValidatorMetaData vmd, Iterator iterator, final Logger logger, OperationCanceledException exc) {
+ private void handleOperationCancelledValidateException(WorkbenchReporter reporter, IValidator validator,
+ ValidatorMetaData vmd, Iterator<ValidatorMetaData> iterator, OperationCanceledException exc) {
/*
* If the user terminates validation (i.e., presses "cancel" on the progress monitor) before
* the validation completes, perform clean up on each configured enabled validator.
@@ -1069,13 +974,7 @@
} catch (InstantiationException exc2) {
// Remove the vmd from the reader's list
ValidationRegistryReader.getReader().disableValidator(vmd);
- // Log the reason for the disabled validator
- if (logger.isLoggingLevel(Level.SEVERE)) {
- LogEntry entry = ValidationPlugin.getLogEntry();
- entry.setSourceID("ValidationOperation::validate(WorkbenchReporter)"); //$NON-NLS-1$
- entry.setTargetException(exc2);
- logger.write(Level.SEVERE, entry);
- }
+ ValidationPlugin.getPlugin().handleException(exc2);
continue;
}
reporter.displaySubtask(ResourceHandler.getExternalizedMessage(ResourceConstants.VBF_STATUS_VALIDATOR_CLEANUP, new String[]{vmd.getValidatorDisplayName()}));
@@ -1084,14 +983,13 @@
reporter.displaySubtask(ResourceHandler.getExternalizedMessage(ResourceConstants.VBF_STATUS_VALIDATOR_TERMINATED, new String[]{getProject().getName(), vmd.getValidatorDisplayName()}));
}
throw exc; // propagate the exception up to the framework so that
- // the framework can display the correct "cancelled"
+ // the framework can display the correct "canceled"
// message in the dialog
}
/* package */
void internalValidate(final WorkbenchReporter reporter, final IValidator validator, final ValidatorMetaData vmd,final IWorkbenchContext aContext, final IFileDelta[] delta) throws OperationCanceledException {
- final Logger logger = ValidationPlugin.getPlugin().getMsgLogger();
try {
checkCanceled(reporter);
removeOldMessages(reporter, validator, vmd, delta);
@@ -1110,21 +1008,13 @@
} catch (OperationCanceledException exc) {
// This is handled in the validate(WorkbenchReporter) method.
throw exc;
- }catch (Throwable exc) {
+ }catch (Exception e) {
// If there is a problem with this particular validator, log the
- // error and continue
- // with the next validator.
- // If a runtime exception has occured, e.g. NullPointer or
- // ClassCast, display it with the "A runtime exception has occurred
- // " messsage.
- // This will provide more information to the user when he/she calls
- // IBM Service.
- if (logger.isLoggingLevel(Level.SEVERE)) {
- LogEntry entry = ValidationPlugin.getLogEntry();
- entry.setSourceID("ValidationOperation.internalValidate"); //$NON-NLS-1$
- entry.setTargetException(exc);
- logger.write(Level.SEVERE, entry);
- }
+ // error and continue with the next validator.
+ // If a runtime exception has occurred, e.g. NullPointer or
+ // ClassCast, display it with the "A runtime exception has occurred" message.
+ // This will provide more information to the user when he/she calls Service.
+ ValidationPlugin.getPlugin().handleException(e);
String mssg = ResourceHandler.getExternalizedMessage(ResourceConstants.VBF_STATUS_ENDING_VALIDATION_ABNORMALLY, new String[]{getProject().getName(), vmd.getValidatorDisplayName()});
reporter.displaySubtask(mssg);
@@ -1165,7 +1055,6 @@
// task.
InternalValidatorManager.getManager().removeOperationTasks(getProject(), vmd);
checkCanceled(reporter);
- Logger logger = ValidationPlugin.getPlugin().getMsgLogger();
try {
// Check to see if a full build must be performed, or if a delta
// build is to be performed, if there are files to verify for that
@@ -1197,11 +1086,6 @@
IResource resource = reporter.getMessageResource(validator, fd);
if (fd.getObject().equals(fd.getResource())) {
WorkbenchReporter.removeAllMessages(resource, validator); // remove
- // all
- // messages
- // from
- // this
- // resource
} else {
reporter.removeAllMessages(validator, fd.getObject());
}
@@ -1212,35 +1096,10 @@
}
} catch (OperationCanceledException exc) {
throw exc;
- } catch (Throwable exc) {
- // If there is a problem with this particular validator, log the
- // error and continue
- // with the next validator.
- // If a runtime exception has occured, e.g. NullPointer or
- // ClassCast, display it with the "A runtime exception has occurred
- // " messsage.
- // This will provide more information to the user when he/she calls
- // IBM Service.
- if (logger.isLoggingLevel(Level.SEVERE)) {
- LogEntry entry = ValidationPlugin.getLogEntry();
- entry.setSourceID("ValidationOperation.validate(WorkbenchMonitor)"); //$NON-NLS-1$
- entry.setTargetException(exc);
- logger.write(Level.SEVERE, entry);
- }
+ } catch (Exception e) {
+ ValidationPlugin.getPlugin().handleException(e);
String mssg = ResourceHandler.getExternalizedMessage(ResourceConstants.VBF_STATUS_ENDING_VALIDATION_ABNORMALLY, new String[]{getProject().getName(), vmd.getValidatorDisplayName()});
reporter.displaySubtask(mssg);
-
- /*
- The code below causes bundle not found exception since, the bundle here is
- validate_base and we are trying to load that bundle from the classloader of
- the Validator. *
- String[] msgParm = {exc.getClass().getName(), vmd.getValidatorDisplayName(), (exc.getMessage() == null ? "" : exc.getMessage())}; //$NON-NLS-1$
- Message message = ValidationPlugin.getMessage();
- message.setSeverity(IMessage.NORMAL_SEVERITY);
- message.setId(ResourceConstants.VBF_EXC_RUNTIME);
- message.setParams(msgParm);
- reporter.addMessage(validator, message);
- */
return;
}
}
@@ -1252,22 +1111,26 @@
* <code>process</code> also sends output to the <code>IProgressMonitor</code>, and calls
* the current Validator to validate the resource.
*
- * To process a resource, there are several steps: 1. check if the resource is registered for
+ * <p>To process a resource, there are several steps:</p>
+ * <p>1. check if the resource is registered for
* this validator (i.e., the validator has either specified it in a filter, or has not filtered
- * it out explicitly) 2. call <code>isValidationSource</code> on the current validator with
+ * it out explicitly)</p>
+ *
+ * <p>2. call <code>isValidationSource</code> on the current validator with
* the current resource. This method performs further filtering by the Validator itself, in
* addition to the static filtering done by the framework, based on the information in
- * plugin.xml. 3. If the resource passes both filters, call <code>validate</code> on the
- * validator, with the resource. 4. When complete (either by failing to pass a filter, or by the
+ * plugin.xml.</p>
+ *
+ * <p>3. If the resource passes both filters, call <code>validate</code> on the
+ * validator, with the resource.</p>
+ *
+ * <p>4. When complete (either by failing to pass a filter, or by the
* completion of the <code>validate</code>), increment the IProgressMonitor's status by one
- * (i.e., one resource has been processed.)
+ * (i.e., one resource has been processed.)</p>
*/
private final void launchValidator(WorkbenchReporter reporter, IValidator validator, ValidatorMetaData vmd, IWorkbenchContext helper, IFileDelta[] delta) {
- if (reporter == null) {
- return;
- }
+ if (reporter == null)return;
checkCanceled(reporter);
- Logger logger = ValidationPlugin.getPlugin().getMsgLogger();
// Check to see if a full build must be performed, or if a delta
// build is to be performed, if there are files to verify for that
// validator. (If it's delta, but there are no files, calling
@@ -1277,47 +1140,42 @@
// Validate the resource; this step will add errors/warnings to the
// task list, and remove errors/warnings from the task list.
if (helper instanceof WorkbenchContext) {
- // Initialize the "loadRuleGroup" method with the group of
- // rules
+ // Initialize the "loadRuleGroup" method with the group of rules
// which the validator should validate.
((WorkbenchContext) helper).setRuleGroup(getRuleGroup());
}
- long start = System.currentTimeMillis();
String message = ResourceHandler.getExternalizedMessage(ResourceConstants.VBF_STATUS_STARTING_VALIDATION, new String[]{getProject().getName(), vmd.getValidatorDisplayName()});
reporter.displaySubtask(message);
- if (logger.isLoggingLevel(Level.FINEST)) {
- // This internal "launched validators" value is used only in
- // tests.
+ if (Tracing.isLogging()) {
+ // This internal "launched validators" value is used only in tests.
getLaunchedValidators().add(vmd);
}
//initValidateContext(delta);
ValidatorLauncher.getLauncher().start(helper, validator, reporter);
- long finish = System.currentTimeMillis();
- if (logger.isLoggingLevel(Level.INFO)) {
- TimeEntry entry = ValidationPlugin.getTimeEntry();
- entry.setSourceID("ValidationOperation.launchValidator"); //$NON-NLS-1$
- entry.setProjectName(getProject().getName());
- entry.setToolName(vmd.getValidatorUniqueName());
- entry.setElapsedTime(finish - start);
- if (logger.isLoggingLevel(Level.FINE)) {
- StringBuffer buffer = new StringBuffer();
- if (isFullValidate()) {
- buffer.append("EVERYTHING"); //$NON-NLS-1$
- } else {
- if (delta.length == 0) {
- buffer.append("NOTHING"); //$NON-NLS-1$
- } else {
- buffer.append(getDeltaAsString(delta));
- }
- }
- entry.setDetails(buffer.toString());
- }
- logger.write(Level.INFO, entry);
- }
+ //TODO GRK determine if timing info should be added here
+// if (logger.isLoggingLevel(Level.INFO)) {
+// TimeEntry entry = ValidationPlugin.getTimeEntry();
+// entry.setSourceID("ValidationOperation.launchValidator"); //$NON-NLS-1$
+// entry.setProjectName(getProject().getName());
+// entry.setToolName(vmd.getValidatorUniqueName());
+// entry.setElapsedTime(finish - start);
+// if (logger.isLoggingLevel(Level.FINE)) {
+// StringBuffer buffer = new StringBuffer();
+// if (isFullValidate()) {
+// buffer.append("EVERYTHING"); //$NON-NLS-1$
+// } else {
+// if (delta.length == 0) {
+// buffer.append("NOTHING"); //$NON-NLS-1$
+// } else {
+// buffer.append(getDeltaAsString(delta));
+// }
+// }
+// entry.setDetails(buffer.toString());
+// }
+// logger.write(Level.INFO, entry);
+// }
message = ResourceHandler.getExternalizedMessage(ResourceConstants.VBF_STATUS_ENDING_VALIDATION, new String[]{getProject().getName(), vmd.getValidatorDisplayName()});
reporter.displaySubtask(message);
- } catch (MessageLimitException exc) {
- throw exc;
} catch (OperationCanceledException exc) {
throw exc;
} catch (ValidationException exc) {
@@ -1325,78 +1183,25 @@
// accidentally wrapped a MessageLimitException instead of
// propagating it.
if (exc.getAssociatedException() != null) {
- if (exc.getAssociatedException() instanceof MessageLimitException) {
- MessageLimitException mssgExc = (MessageLimitException) exc.getAssociatedException();
- throw mssgExc;
- } else if (exc.getAssociatedException() instanceof ValidationException) {
+ if (exc.getAssociatedException() instanceof ValidationException) {
ValidationException vexc = (ValidationException) exc.getAssociatedException();
vexc.setClassLoader(validator.getClass().getClassLoader()); // first,
- // set
- // the
- // class
- // loader,
- // so
- // that
- // the
- // exception's
- // getMessage()
- // method
- // can
- // retrieve
- // the
- // resource
- // bundle
+ // set the class loader, so that the exception's getMessage() method
+ // can retrieve the resource bundle
}
}
// If there is a problem with this particular validator, log the
- // error and continue
- // with the next validator.
+ // error and continue with the next validator.
exc.setClassLoader(validator.getClass().getClassLoader()); // first,
- // set
- // the
- // class
- // loader,
- // so
- // that
- // the
- // exception's
- // getMessage()
- // method
- // can
- // retrieve
- // the
- // resource
- // bundle
- if (logger.isLoggingLevel(Level.SEVERE)) {
- LogEntry entry = ValidationPlugin.getLogEntry();
- entry.setSourceID("ValidationOperation.validate(WorkbenchMonitor)"); //$NON-NLS-1$
- entry.setTargetException(exc);
- logger.write(Level.SEVERE, entry);
- if (exc.getAssociatedException() != null) {
- entry.setTargetException(exc.getAssociatedException());
- logger.write(Level.SEVERE, entry);
- }
- }
+ ValidationPlugin.getPlugin().handleException(exc);
+ ValidationPlugin.getPlugin().handleException(exc.getAssociatedException());
String message = ResourceHandler.getExternalizedMessage(ResourceConstants.VBF_STATUS_ENDING_VALIDATION_ABNORMALLY, new String[]{getProject().getName(), vmd.getValidatorDisplayName()});
reporter.displaySubtask(message);
if (exc.getAssociatedMessage() != null) {
reporter.addMessage(validator, exc.getAssociatedMessage());
}
- } catch (Throwable exc) {
- // If there is a problem with this particular validator, log the
- // error and continue
- // with the next validator.
- // If a runtime exception has occured, e.g. NullPointer or
- // ClassCast, display it with the "A runtime exception has occurred
- // " messsage.
- // This will provide more information to the user when he/she calls
- // IBM Service.
- if (logger.isLoggingLevel(Level.SEVERE)) {
- LogEntry entry = ValidationPlugin.getLogEntry();
- entry.setSourceID("ValidationOperation.validate(WorkbenchMonitor)"); //$NON-NLS-1$
- entry.setTargetException(exc);
- logger.write(Level.SEVERE, entry);
- }
+ } catch (Exception e) {
+ ValidationPlugin.getPlugin().handleException(e);
String mssg = ResourceHandler.getExternalizedMessage(ResourceConstants.VBF_STATUS_ENDING_VALIDATION_ABNORMALLY, new String[]{getProject().getName(), vmd.getValidatorDisplayName()});
reporter.displaySubtask(mssg);
@@ -1416,76 +1221,18 @@
} finally {
try {
validator.cleanup(reporter);
- } catch (MessageLimitException e) {
- throw e;
} catch (OperationCanceledException e) {
throw e;
- } catch (Throwable exc) {
- // If a runtime exception has occured, e.g. NullPointer or
- // ClassCast, display it with the "A runtime exception has
- // occurred " messsage.
- // This will provide more information to the user when he/she
- // calls IBM Service.
- if (logger.isLoggingLevel(Level.SEVERE)) {
- LogEntry entry = ValidationPlugin.getLogEntry();
- entry.setSourceID("ValidationOperation::launchValidator"); //$NON-NLS-1$
- entry.setTargetException(exc);
- logger.write(Level.SEVERE, entry);
- }
-
- /*
- The code below causes bundle not found exception since, the bundle here is
- validate_base and we are trying to load that bundle from the classloader of
- the Validator.
- String[] msgParm = {exc.getClass().getName(), vmd.getValidatorDisplayName(), (exc.getMessage() == null ? "" : exc.getMessage())}; //$NON-NLS-1$
- Message message = ValidationPlugin.getMessage();
- message.setSeverity(IMessage.NORMAL_SEVERITY);
- message.setId(ResourceConstants.VBF_EXC_RUNTIME);
- message.setParams(msgParm);
- try {
- reporter.addMessage(validator, message);
- } catch (MessageLimitException e) {
- throw e;
- }
-
- */
+ } catch (Exception e) {
+ ValidationPlugin.getPlugin().handleException(e);
return;
}
try {
helper.cleanup(reporter);
- } catch (MessageLimitException e) {
- throw e;
} catch (OperationCanceledException e) {
throw e;
- } catch (Throwable exc) {
- // If a runtime exception has occured, e.g. NullPointer or
- // ClassCast, display it with the "A runtime exception has
- // occurred " messsage.
- // This will provide more information to the user when he/she
- // calls IBM Service.
- if (logger.isLoggingLevel(Level.SEVERE)) {
- LogEntry entry = ValidationPlugin.getLogEntry();
- entry.setSourceID("ValidationOperation::launchValidator"); //$NON-NLS-1$
- entry.setTargetException(exc);
- logger.write(Level.SEVERE, entry);
- }
-
- /*
- The code below bundle not found exception since, the bundle here is
- validate_base and we are trying to load that bundle from the classloader of
- the Validator.
-
- String[] msgParm = {exc.getClass().getName(), vmd.getValidatorDisplayName(), (exc.getMessage() == null ? "" : exc.getMessage())}; //$NON-NLS-1$
- Message message = ValidationPlugin.getMessage();
- message.setSeverity(IMessage.NORMAL_SEVERITY);
- message.setId(ResourceConstants.VBF_EXC_RUNTIME);
- message.setParams(msgParm);
- try {
- reporter.addMessage(validator, message);
- } catch (MessageLimitException e) {
- throw e;
- }
- */
+ } catch (Exception e) {
+ ValidationPlugin.getPlugin().handleException(e);
return;
} finally {
// Now that cleanup has been called, set the project to null.
@@ -1502,23 +1249,16 @@
}
// Tell the progress monitor that we've completed n units of work
// (i.e., n resources validated by one validator).
- reporter.getProgressMonitor().worked(((delta == null) ? 1 : delta.length)); // One
- // unit
- // of
- // work
- // = 1
- // (i.e.,
- // 1
- // resource)
+ reporter.getProgressMonitor().worked(((delta == null) ? 1 : delta.length));
}
}
- private Runnable wrapInRunnable(final WorkbenchReporter reporter, final IValidator validator, final ValidatorMetaData vmd, final IWorkbenchContext helper, final IFileDelta[] delta, final Iterator iterator) {
- // Need to create a new Runnable each time because several Runnable
- // instances may exist at the same time.
- Runnable runnable = new ProjectRunnable(reporter, validator, vmd, helper, delta, iterator);
- return runnable;
- }
+// private Runnable wrapInRunnable(final WorkbenchReporter reporter, final IValidator validator, final ValidatorMetaData vmd, final IWorkbenchContext helper, final IFileDelta[] delta, final Iterator iterator) {
+// // Need to create a new Runnable each time because several Runnable
+// // instances may exist at the same time.
+// Runnable runnable = new ProjectRunnable(reporter, validator, vmd, helper, delta, iterator);
+// return runnable;
+// }
/*
* // For convenience, keep this method in the class but commented out. // When async needs to
@@ -1531,27 +1271,30 @@
* (hProject.getName().indexOf("fork") > -1)) { Thread.dumpStack(); } System.err.println(prefix +
* "End ValidationOperation"); }
*/
+
+ /**
+ * @deprecated This class is no longer used by the framework.
+ */
public class ProjectRunnable implements Runnable {
- private WorkbenchReporter _reporter = null;
- private IValidator _validator = null;
- private ValidatorMetaData _vmd = null;
-// private IValidationContext _helper = null;
- private IFileDelta[] __delta = null;
+ private WorkbenchReporter _reporter;
+ private IValidator _validator;
+ private ValidatorMetaData _vmd;
+ private IFileDelta[] _delta;
- public ProjectRunnable(WorkbenchReporter reporter, IValidator validator, ValidatorMetaData vmd, IWorkbenchContext helper, IFileDelta[] delta, Iterator iterator) {
+ @SuppressWarnings("unchecked")
+ public ProjectRunnable(WorkbenchReporter reporter, IValidator validator,
+ ValidatorMetaData vmd, IWorkbenchContext helper, IFileDelta[] delta, Iterator iterator) {
_reporter = reporter;
_validator = validator;
_vmd = vmd;
-// _helper = helper;
- __delta = delta;
+ _delta = delta;
}
public void run() {
try {
- internalValidate(_reporter, _validator, _vmd, context,__delta);
+ internalValidate(_reporter, _validator, _vmd, context,_delta);
} catch (OperationCanceledException exc) {
- // User can't cancel a job in a background thread, so ignore
- // this exception.
+ // User can't cancel a job in a background thread, so ignore this exception.
}
}
@@ -1574,49 +1317,24 @@
this.context = context;
}
- void launchJobs(HashSet validators, final WorkbenchReporter reporter) throws OperationCanceledException{
+ void launchJobs(Set<ValidatorMetaData> validators, final WorkbenchReporter reporter) throws OperationCanceledException{
- final Logger logger = ValidationPlugin.getPlugin().getMsgLogger();
- Iterator iterator = validators.iterator();
- ValidatorMetaData vmd = null;
IValidator validator = null;
IFileDelta[] delta = null;
IWorkbenchContext workbenchcontext = null;
- while (iterator.hasNext()) {
+ for (ValidatorMetaData vmd : validators) {
checkCanceled(reporter);
- vmd = (ValidatorMetaData) iterator.next();
-
try {
delta = getFileDeltas(reporter.getProgressMonitor(), vmd);
boolean willRun = (isForce() || isValidationNecessary(vmd, delta));
- if (!willRun) {
- continue;
- }
- } catch (CoreException exc) {
- if (logger.isLoggingLevel(Level.SEVERE)) {
- LogEntry entry = ValidationPlugin.getLogEntry();
- entry.setSourceID("ValidationOperation.launchJobs()"); //$NON-NLS-1$
- entry.setTargetException(exc);
- logger.write(Level.SEVERE, entry);
- }
+ if (!willRun)continue;
+
+ } catch (CoreException e) {
+ ValidationPlugin.getPlugin().handleException(e);
String mssg = ResourceHandler.getExternalizedMessage(ResourceConstants.VBF_STATUS_ENDING_VALIDATION_ABNORMALLY, new String[]{getProject().getName(), vmd.getValidatorDisplayName()});
reporter.displaySubtask(mssg);
-
- /*
- The code below causes bundle not found exception since, the bundle here is
- validate_base and we are trying to load that bundle from the classloader of
- the Validator.
-
- String[] msgParm = {exc.getClass().getName(), vmd.getValidatorDisplayName(), (exc.getMessage() == null ? "" : exc.getMessage())}; //$NON-NLS-1$
- Message message = ValidationPlugin.getMessage();
- message.setSeverity(IMessage.NORMAL_SEVERITY);
- message.setId(ResourceConstants.VBF_EXC_RUNTIME);
- message.setParams(msgParm);
- reporter.addMessage(validator, message);
- */
-
continue;
}
@@ -1627,16 +1345,10 @@
vmd.addHelper((IValidatorJob)validator, workbenchcontext);
checkCanceled(reporter);
- } catch (InstantiationException exc) {
+ } catch (InstantiationException e) {
// Remove the vmd from the reader's list
ValidationRegistryReader.getReader().disableValidator(vmd);
- // Log the reason for the disabled validator
- if (logger.isLoggingLevel(Level.SEVERE)) {
- LogEntry entry = ValidationPlugin.getLogEntry();
- entry.setSourceID("ValidationOperation.launchJobs()"); //$NON-NLS-1$
- entry.setTargetException(exc);
- logger.write(Level.SEVERE, entry);
- }
+ ValidationPlugin.getPlugin().handleException(e);
continue;
}
@@ -1652,142 +1364,97 @@
} catch (OperationCanceledException exc) {
throw exc;
- } catch (Throwable exc) {
- if (logger.isLoggingLevel(Level.SEVERE)) {
- LogEntry entry = ValidationPlugin.getLogEntry();
- entry.setSourceID("ValidationOperation.launchJobs()"); //$NON-NLS-1$
- entry.setTargetException(exc);
- logger.write(Level.SEVERE, entry);
- }
+ } catch (Exception e) {
+ ValidationPlugin.getPlugin().handleException(e);
String mssg = ResourceHandler.getExternalizedMessage(ResourceConstants.VBF_STATUS_ENDING_VALIDATION_ABNORMALLY, new String[]{getProject().getName(), vmd.getValidatorDisplayName()});
reporter.displaySubtask(mssg);
-
- /*
- The code below causes bundle not found exception since, the bundle here is
- validate_base and we are trying to load that bundle from the classloader of
- the Validator.
- */
-
-// String[] msgParm = {exc.getClass().getName(), vmd.getValidatorDisplayName(), (exc.getMessage() == null ? "" : exc.getMessage())}; //$NON-NLS-1$
-// Message message = ValidationPlugin.getMessage();
-// message.setSeverity(IMessage.NORMAL_SEVERITY);
-// message.setId(ResourceConstants.VBF_EXC_RUNTIME);
-// message.setParams(msgParm);
-// reporter.addMessage(validator, message);
+ } catch (Error e) {
+ ValidationPlugin.getPlugin().handleException(e);
+ String mssg = ResourceHandler.getExternalizedMessage(ResourceConstants.VBF_STATUS_ENDING_VALIDATION_ABNORMALLY, new String[]{getProject().getName(), vmd.getValidatorDisplayName()});
+ reporter.displaySubtask(mssg);
+ throw e;
} finally {
// If user fixes problem, and limit exceeded, add "exceeded"
- // message, or
- // if limit not exceeded any more, remove "exceeded" message.
+ // message, or if limit not exceeded any more, remove "exceeded" message.
reporter.getProgressMonitor().done();
}
}
-
-
-
-
-
}
-
-
-
-
+
private void initValidateContext(IFileDelta[] delta, IWorkbenchContext context ) {
if (context instanceof WorkbenchContext) {
- ((WorkbenchContext)context).setValidationFileURIs(new ArrayList());
- for(int i = 0; i < delta.length; i++) {
- IFileDelta file = delta[i];
+ ((WorkbenchContext)context).setValidationFileURIs(new ArrayList<String>());
+ for(IFileDelta file : delta) {
if(file.getDeltaType() != IFileDelta.DELETED ) {
((WorkbenchContext)context).getValidationFileURIs().add(file.getFileName());
}
}
}
}
-
-
+
private final void launchValidatorJob(WorkbenchReporter reporter,
- IValidatorJob validator, ValidatorMetaData vmd,
- IWorkbenchContext helper, IFileDelta[] delta) {
+ IValidatorJob validator, ValidatorMetaData vmd, IWorkbenchContext helper, IFileDelta[] delta) {
- if (reporter == null) {
- return;
- }
+ if (reporter == null)return;
checkCanceled(reporter);
- Logger logger = ValidationPlugin.getPlugin().getMsgLogger();
if (helper instanceof WorkbenchContext) {
((WorkbenchContext) helper).setRuleGroup(getRuleGroup());
}
- if (logger.isLoggingLevel(Level.FINEST)) {
- // This internal "launched validators" value is used only in
- // tests.
+ if (Tracing.isLogging()) {
+ // This internal "launched validators" value is used only in tests.
getLaunchedValidators().add(vmd);
}
- ValidatorJob validatorjob = new ValidatorJob( validator, vmd.getValidatorDisplayName(), vmd.getValidatorUniqueName(),
- helper.getProject(), helper );
-
+ ValidatorJob validatorjob = new ValidatorJob( validator, vmd.getValidatorDisplayName(),
+ vmd.getValidatorUniqueName(), helper.getProject(), helper );
ISchedulingRule schedulingRule = validator.getSchedulingRule(helper);
validatorjob.setRule( schedulingRule );
QualifiedName validatorKey = new QualifiedName(null, "Validator"); //$NON-NLS-1$
validatorjob.setProperty( validatorKey, validator );
validatorjob.addJobChangeListener(
- new JobChangeAdapter(){
-
- public void done(IJobChangeEvent event){
- Job job = event.getJob();
- QualifiedName validatorKey = new QualifiedName(null, "Validator"); //$NON-NLS-1$
- IValidatorJob validator = (IValidatorJob)job.getProperty( validatorKey );
- ValidatorManager mgr = ValidatorManager.getManager();
- final ArrayList list = mgr.getMessages(validator);
-
- IWorkspaceRunnable runnable = new IWorkspaceRunnable() {
- public void run(IProgressMonitor monitor) throws CoreException {
+ new JobChangeAdapter(){
+
+ public void done(IJobChangeEvent event){
+ Job job = event.getJob();
+ QualifiedName validatorKey = new QualifiedName(null, "Validator"); //$NON-NLS-1$
+ IValidatorJob validator = (IValidatorJob)job.getProperty( validatorKey );
+ ValidatorManager mgr = ValidatorManager.getManager();
+ final List<MessageInfo> list = mgr.getMessages(validator);
+
+ IWorkspaceRunnable runnable = new IWorkspaceRunnable() {
+ public void run(IProgressMonitor monitor) throws CoreException {
- Iterator it = list.iterator();
- while( it.hasNext() ){
- MessageInfo info = (MessageInfo)it.next();
- try {
-
- TaskListUtility.addTask( info.getMessageOwnerId(), info.getResource(),
- info.getLocation(), info.getMsg().getId(), info.getText(),
- info.getMsg().getSeverity(),
- info.getMarkerId(),
- info.getTargetObjectName(),
- info.getMsg().getGroupName(),
- info.getMsg().getOffset(),
- info.getMsg().getLength());
-
-
- } catch (CoreException exc) {
- Logger logger = ValidationPlugin.getPlugin().getMsgLogger();
- if (logger.isLoggingLevel(Level.SEVERE)) {
- LogEntry entry = ValidationPlugin.getLogEntry();
- entry.setTargetException(exc);
- logger.write(Level.SEVERE, entry);
- }
- }
- }
- }
- };
- try {
-
- ResourcesPlugin.getWorkspace().run(runnable, null, IWorkspace.AVOID_UPDATE, null);
- } catch (CoreException e) {
- e.printStackTrace();
+ for(MessageInfo info : list){
+ try {
+ TaskListUtility.addTask( info.getMessageOwnerId(), info.getResource(),
+ info.getLocation(), info.getMsg().getId(), info.getText(),
+ info.getMsg().getSeverity(),
+ info.getMarkerId(),
+ info.getTargetObjectName(),
+ info.getMsg().getGroupName(),
+ info.getMsg().getOffset(),
+ info.getMsg().getLength());
+ } catch (CoreException e) {
+ ValidationPlugin.getPlugin().handleException(e);
+ }
}
- mgr.clearMessages( validator );
- validator = null;
- }
+ }
+ };
+ try {
+
+ ResourcesPlugin.getWorkspace().run(runnable, null, IWorkspace.AVOID_UPDATE, null);
+ } catch (CoreException e) {
+ e.printStackTrace();
}
+ mgr.clearMessages( validator );
+ validator = null;
+ }
+ }
);
validatorjob.setPriority(Job.DECORATE);
-
- ValidationLauncherJob validationLauncherJob = new ValidationLauncherJob(validatorjob);
- validationLauncherJob.schedule();
-
- //validatorjob.schedule();
-
+ launcherJob.addValidationJob(validatorjob);
}
-}
\ No newline at end of file
+}
diff --git a/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/operations/ValidationUtility.java b/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/operations/ValidationUtility.java
index 0a29729..4e53471 100644
--- a/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/operations/ValidationUtility.java
+++ b/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/operations/ValidationUtility.java
@@ -1,10 +1,10 @@
/*******************************************************************************
- * Copyright (c) 2001, 2004 IBM Corporation and others.
+ * Copyright (c) 2001, 2008 IBM Corporation 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:
* IBM Corporation - initial API and implementation
*******************************************************************************/
@@ -13,14 +13,11 @@
import java.lang.reflect.InvocationTargetException;
import java.util.HashSet;
import java.util.Set;
-import java.util.logging.Level;
import org.eclipse.core.resources.IMarker;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.CoreException;
-import org.eclipse.jem.util.logger.LogEntry;
-import org.eclipse.jem.util.logger.proxy.Logger;
import org.eclipse.wst.validation.internal.ConfigurationConstants;
import org.eclipse.wst.validation.internal.ConfigurationManager;
import org.eclipse.wst.validation.internal.ProjectConfiguration;
@@ -45,7 +42,7 @@
return new String[0];
}
- Set tempSet = new HashSet();
+ Set<String> tempSet = new HashSet<String>();
for (int i = 0; i < markers.length; i++) {
IMarker marker = markers[i];
try {
@@ -54,15 +51,9 @@
// The ValidationMigrator will remove any "unowned" validation markers.
continue;
}
- tempSet.add(owner);
- } catch (CoreException exc) {
- Logger logger = ValidationPlugin.getPlugin().getMsgLogger();
- if (logger.isLoggingLevel(Level.SEVERE)) {
- LogEntry entry = ValidationPlugin.getLogEntry();
- entry.setSourceID("ValidationUtility.listValidatorClasses(" + resource.getName() + ", " + severity); //$NON-NLS-1$ //$NON-NLS-2$
- entry.setTargetException(exc);
- logger.write(Level.SEVERE, entry);
- }
+ tempSet.add((String)owner);
+ } catch (CoreException e) {
+ ValidationPlugin.getPlugin().handleException(e);
}
}
@@ -100,22 +91,12 @@
return false;
}
}
- } catch (InvocationTargetException exc) {
- Logger logger = ValidationPlugin.getPlugin().getMsgLogger();
- if (logger.isLoggingLevel(Level.SEVERE)) {
- LogEntry entry = ValidationPlugin.getLogEntry();
- entry.setSourceID("ValidationUtility::isEnabled(" + project.getName() + ", String[])"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- entry.setTargetException(exc);
- logger.write(Level.SEVERE, entry);
-
- if (exc.getTargetException() != null) {
- entry.setTargetException(exc);
- logger.write(Level.SEVERE, entry);
- }
- }
+ } catch (InvocationTargetException e) {
+ ValidationPlugin.getPlugin().handleException(e);
+ ValidationPlugin.getPlugin().handleException(e.getTargetException());
return false;
}
return true;
}
-}
\ No newline at end of file
+}
diff --git a/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/operations/ValidatorJob.java b/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/operations/ValidatorJob.java
index 473fea2..048dd39 100644
--- a/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/operations/ValidatorJob.java
+++ b/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/operations/ValidatorJob.java
@@ -1,16 +1,25 @@
+/*******************************************************************************
+ * Copyright (c) 2005, 2008 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
package org.eclipse.wst.validation.internal.operations;
-import java.util.logging.Level;
-
import org.eclipse.core.resources.IProject;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.OperationCanceledException;
-import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.Job;
-import org.eclipse.jem.util.logger.LogEntry;
-import org.eclipse.jem.util.logger.proxy.Logger;
import org.eclipse.wst.common.frameworks.internal.plugin.WTPCommonPlugin;
+import org.eclipse.wst.validation.IPerformanceMonitor;
+import org.eclipse.wst.validation.PerformanceCounters;
+import org.eclipse.wst.validation.ValidationFramework;
+import org.eclipse.wst.validation.internal.Misc;
import org.eclipse.wst.validation.internal.ResourceConstants;
import org.eclipse.wst.validation.internal.ResourceHandler;
import org.eclipse.wst.validation.internal.ValidationRegistryReader;
@@ -25,20 +34,15 @@
private IProject project;
- private String validatorUniqueName;
private IWorkbenchContext helper;
private IValidatorJob validator;
public ValidatorJob(String name) {
super(name);
}
-
-
-
public ValidatorJob( IValidatorJob validator, String displayName, String name, IProject project, IWorkbenchContext aHelper ){
super(displayName);
- validatorUniqueName = name;
this.project = project;
this.helper = aHelper;
this.validator = validator;
@@ -49,6 +53,14 @@
//error information is reported by the IReporter
protected IStatus run(IProgressMonitor monitor) {
+
+ IPerformanceMonitor pm = ValidationFramework.getDefault().getPerformanceMonitor();
+ long elapsed = -1;
+ long cpuTime = -1;
+ if (pm.isCollecting()){
+ elapsed = System.currentTimeMillis();
+ cpuTime = Misc.getCPUTime();
+ }
monitor.beginTask("Validating", IProgressMonitor.UNKNOWN); //$NON-NLS-1$
IStatus status = IValidatorJob.OK_STATUS;
@@ -56,28 +68,17 @@
ValidatorMetaData vmd = ValidationRegistryReader.getReader().getValidatorMetaData(validator);
- Logger logger = ValidationPlugin.getPlugin().getMsgLogger();
-
try {
String message = ResourceHandler.getExternalizedMessage(
ResourceConstants.VBF_STATUS_STARTING_VALIDATION,
new String[]{helper.getProject().getName(), vmd.getValidatorDisplayName()});
- monitor.subTask(message);
-
-
+ monitor.subTask(message);
status = validator.validateInJob(helper, reporter);
- //to remove, if error is returned from the validator, the job stays back in the UI...
- //should we even return error status if error is found in the validator
- //status = IValidatorJob.OK_STATUS;
-
-
-
- message = ResourceHandler.getExternalizedMessage(
- ResourceConstants.VBF_STATUS_ENDING_VALIDATION,
- new String[]{helper.getProject().getName(), vmd.getValidatorDisplayName()});
+ message = ResourceHandler.getExternalizedMessage(ResourceConstants.VBF_STATUS_ENDING_VALIDATION,
+ new String[]{helper.getProject().getName(), vmd.getValidatorDisplayName()});
monitor.subTask(message);
} catch (OperationCanceledException exc) {
@@ -93,42 +94,24 @@
}
}
// If there is a problem with this particular validator, log the
- // error and continue
- // with the next validator.
+ // error and continue with the next validator.
exc.setClassLoader(validator.getClass().getClassLoader());
- if (logger.isLoggingLevel(Level.SEVERE)) {
- LogEntry entry = ValidationPlugin.getLogEntry();
- entry.setSourceID("ValidatorJob.run()"); //$NON-NLS-1$
- entry.setTargetException(exc);
- logger.write(Level.SEVERE, entry);
- if (exc.getAssociatedException() != null) {
- entry.setTargetException(exc.getAssociatedException());
- logger.write(Level.SEVERE, entry);
- }
- }
+ ValidationPlugin.getPlugin().handleException(exc);
+ ValidationPlugin.getPlugin().handleException(exc.getAssociatedException());
String message = ResourceHandler.getExternalizedMessage(
- ResourceConstants.VBF_STATUS_ENDING_VALIDATION_ABNORMALLY,
- new String[]{helper.getProject().getName(), vmd.getValidatorDisplayName()});
+ ResourceConstants.VBF_STATUS_ENDING_VALIDATION_ABNORMALLY,
+ new String[]{helper.getProject().getName(), vmd.getValidatorDisplayName()});
monitor.subTask(message);
if (exc.getAssociatedMessage() != null) {
reporter.addMessage(validator, exc.getAssociatedMessage());
}
- } catch (Throwable exc) {
- if (logger.isLoggingLevel(Level.SEVERE)) {
- LogEntry entry = ValidationPlugin.getLogEntry();
- entry.setSourceID("ValidatorJob.run()"); //$NON-NLS-1$
- entry.setTargetException(exc);
- logger.write(Level.SEVERE, entry);
- IStatus stat = new Status(IStatus.ERROR,
- ValidationPlugin.getPlugin().PLUGIN_ID, 0, "", exc );
- logger.write(Level.SEVERE, stat);
-
- }
+ } catch (Exception e) {
+ ValidationPlugin.getPlugin().handleException(e);
String mssg = ResourceHandler.getExternalizedMessage(
- ResourceConstants.VBF_STATUS_ENDING_VALIDATION_ABNORMALLY,
- new String[]{helper.getProject().getName(), vmd.getValidatorDisplayName() });
+ ResourceConstants.VBF_STATUS_ENDING_VALIDATION_ABNORMALLY,
+ new String[]{helper.getProject().getName(), vmd.getValidatorDisplayName() });
monitor.subTask(mssg);
@@ -137,13 +120,8 @@
validator.cleanup(reporter);
} catch (OperationCanceledException e) {
throw e;
- } catch (Throwable exc) {
- if (logger.isLoggingLevel(Level.SEVERE)) {
- LogEntry entry = ValidationPlugin.getLogEntry();
- entry.setSourceID("ValidatorJob.run()"); //$NON-NLS-1$
- entry.setTargetException(exc);
- logger.write(Level.SEVERE, entry);
- }
+ } catch (Exception exc) {
+ ValidationPlugin.getPlugin().handleException(exc);
String[] msgParm = {exc.getClass().getName(), vmd.getValidatorDisplayName(), (exc.getMessage() == null ? "" : exc.getMessage())}; //$NON-NLS-1$
Message message = ValidationPlugin.getMessage();
@@ -158,13 +136,8 @@
vmd.removeHelper( validator );
}catch (OperationCanceledException e) {
throw e;
- } catch (Throwable exc) {
- if (logger.isLoggingLevel(Level.SEVERE)) {
- LogEntry entry = ValidationPlugin.getLogEntry();
- entry.setSourceID("ValidatorJob.run()"); //$NON-NLS-1$
- entry.setTargetException(exc);
- logger.write(Level.SEVERE, entry);
- }
+ } catch (Exception exc) {
+ ValidationPlugin.getPlugin().handleException(exc);
String[] msgParm = {exc.getClass().getName(), vmd.getValidatorDisplayName(), (exc.getMessage() == null ? "" : exc.getMessage())}; //$NON-NLS-1$
Message message = ValidationPlugin.getMessage();
message.setSeverity(IMessage.NORMAL_SEVERITY);
@@ -185,6 +158,16 @@
//monitor.worked(((delta == null) ? 1 : delta.length)); // One
monitor.done();
}
+ if (pm.isCollecting()){
+ if (cpuTime != -1){
+ cpuTime = Misc.getCPUTime() - cpuTime;
+ }
+ String projectName = null;
+ if (project != null)projectName = project.getName();
+ pm.add(new PerformanceCounters(vmd.getValidatorUniqueName(),
+ vmd.getValidatorDisplayName(),projectName, -1,
+ System.currentTimeMillis()-elapsed, cpuTime));
+ }
return status;
}
diff --git a/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/operations/ValidatorManager.java b/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/operations/ValidatorManager.java
index 68605e6..7cf398b 100644
--- a/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/operations/ValidatorManager.java
+++ b/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/operations/ValidatorManager.java
@@ -1,10 +1,10 @@
/*******************************************************************************
- * Copyright (c) 2001, 2004 IBM Corporation and others.
+ * Copyright (c) 2001, 2008 IBM Corporation 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:
* IBM Corporation - initial API and implementation
*******************************************************************************/
@@ -20,7 +20,6 @@
import java.util.List;
import java.util.Map;
import java.util.Set;
-import java.util.logging.Level;
import org.eclipse.core.resources.ICommand;
import org.eclipse.core.resources.IMarker;
@@ -30,8 +29,7 @@
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.jem.util.logger.LogEntry;
-import org.eclipse.jem.util.logger.proxy.Logger;
+import org.eclipse.wst.validation.ValidationFramework;
import org.eclipse.wst.validation.internal.ConfigurationManager;
import org.eclipse.wst.validation.internal.GlobalConfiguration;
import org.eclipse.wst.validation.internal.InternalValidatorManager;
@@ -40,40 +38,33 @@
import org.eclipse.wst.validation.internal.ValidationRegistryReader;
import org.eclipse.wst.validation.internal.ValidatorMetaData;
import org.eclipse.wst.validation.internal.plugin.ValidationPlugin;
-import org.eclipse.wst.validation.internal.provisional.core.IMessage;
import org.eclipse.wst.validation.internal.provisional.core.IValidator;
import org.eclipse.wst.validation.internal.provisional.core.IValidatorJob;
/**
- * A centralised class for accessing validation metadata.
+ * A centralized class for accessing validation metadata.
*
* This class is not intended to be subclassed outside of the validation framework.
*/
public final class ValidatorManager {
public static final String VALIDATOR_JOB_FAMILY = "validators"; //$NON-NLS-1$
- private static ValidatorManager inst = null;
- private static IResourceUtil _resourceUtil = null; // a common utility, different whether or not
- // WSAD is running in headless or UI mode,
- // which can retrieve the line number of some
- // MOF objects.
+ private static ValidatorManager inst;
+ private static IResourceUtil _resourceUtil; // a common utility, different whether or not
+ // WSAD is running in headless or UI mode, which can retrieve the line number of some MOF objects.
private static final Class RESOURCEUTIL_DEFAULTCLASS = org.eclipse.wst.validation.internal.operations.DefaultResourceUtil.class;
private static Class _resourceUtilClass = RESOURCEUTIL_DEFAULTCLASS;
- private static final Set EMPTY_SET = Collections.EMPTY_SET; // an empty set, provided for
- // convenience, so that we only
- // construct one empty set once.
- private Set _suspendedProjects = null;
- private boolean _suspendAllValidation = false;
- private static Class _messageLimitOwner = null;
- private String[] _internalOwners = null;
- private Map validatorMsgs = Collections.synchronizedMap( new HashMap() );
- private Set problemValidators = new HashSet();
+
+ // an empty set, provided for convenience, so that we only construct one empty set once.
+ private static final Set<ValidatorMetaData> EMPTY_SET = new HashSet<ValidatorMetaData>();
- /**
- * ValidatorManager constructor comment.
- */
+ private static Class _messageLimitOwner;
+ private String[] _internalOwners;
+ private Map<IValidatorJob, List<MessageInfo>> _validatorMsgs =
+ Collections.synchronizedMap( new HashMap<IValidatorJob, List<MessageInfo>>() );
+ private Set<ValidatorMetaData> _problemValidators = new HashSet<ValidatorMetaData>();
+
private ValidatorManager() {
super();
- _suspendedProjects = new HashSet();
_internalOwners = new String[0];
addInternalOwner(getMessageLimitOwner());
@@ -87,23 +78,81 @@
setEnabledValidators(currentProject, EMPTY_SET, monitor);
}
+ public void enableValidator(String validatorId) {
+
+ try {
+ ValidatorMetaData vmd = ValidationRegistryReader.getReader().getValidatorMetaData(validatorId);
+ GlobalConfiguration gf = ConfigurationManager.getManager().getGlobalConfiguration();
+ gf.enableSingleValidator(vmd);
+ } catch (InvocationTargetException e) {
+ e.printStackTrace();
+ }
+ }
+
+
+ public void disableValidator(String validatorId){
+
+ try {
+ ValidatorMetaData vmd = ValidationRegistryReader.getReader().getValidatorMetaData(validatorId);
+ GlobalConfiguration gf = ConfigurationManager.getManager().getGlobalConfiguration();
+ gf.disableSingleValidator(vmd);
+ } catch (InvocationTargetException e) {
+ e.printStackTrace();
+ }
+ }
+
+
+ public void enableValidator(String validatorId, IProject project, boolean manualValidation, boolean buildValidation) {
+ try {
+ ProjectConfiguration prjp = ConfigurationManager.getManager().getProjectConfiguration(project);
+ prjp.setDoesProjectOverride(true);
+ ValidatorMetaData vmd = ValidationRegistryReader.getReader().getValidatorMetaData(validatorId);
+
+ if(manualValidation)prjp.enableSingleManualValidator(vmd);
+ if (buildValidation)prjp.enableSingleBuildValidator(vmd);
+ prjp.store();
+ } catch (InvocationTargetException e) {
+ e.printStackTrace();
+ }
+ }
+
+ public void disableValidator(String validatorId, IProject project, boolean manualValidation, boolean buildValidation){
+
+ try {
+ ProjectConfiguration prjp = ConfigurationManager.getManager().getProjectConfiguration(project);
+ prjp.setDoesProjectOverride(true);
+ ValidatorMetaData vmd = ValidationRegistryReader.getReader().getValidatorMetaData(validatorId);
+
+ if(manualValidation)prjp.disableSingleManualValidator(vmd);
+ if (buildValidation)prjp.disableSingleBuildValidator(vmd);
+ prjp.store();
+
+ } catch (InvocationTargetException e) {
+ e.printStackTrace();
+ }
+
+ }
+
+
+
/**
* Given an IProject, if the IProject does not support build validation, add the validation
- * builder to the project description so that the project can support bulid validation.
+ * builder to the project description so that the project can support build validation.
*/
public static void addProjectBuildValidationSupport(IProject project) {
- if (project == null) {
- return;
- }
+ /*
+ * I'm working my way through the code to see where this gets called. One place was in ModuleCoreNature
+ * which had hard coded the builder id.
+ */
+ if (project == null)return;
boolean isBuilderAdded = false;
try {
IProjectDescription description = project.getDescription();
- ICommand[] commands = description.getBuildSpec(); // don't need to check if description
- // is null, because it's never null
+ ICommand[] commands = description.getBuildSpec();
if (commands != null) {
- for (int i = 0; i < commands.length; i++) {
- String builderName = commands[i].getBuilderName();
+ for (ICommand command : commands) {
+ String builderName = command.getBuilderName();
if (builderName == null) {
// builder name will be null if it has not been set
continue;
@@ -146,7 +195,7 @@
* incremental validation), and false otherwise. The test, to find out if the project supports
* build validation or not, is to see if the ValidationBuilder is configured on that type of
* project.
- *
+ * <p>
* This is a long-running process - is there any way that I can shorten the amount of time this
* takes?
*/
@@ -196,19 +245,9 @@
try {
ProjectConfiguration prjp = ConfigurationManager.getManager().getProjectConfiguration(project);
prjp.setEnabledValidators(prjp.getValidators());
- } catch (InvocationTargetException exc) {
- Logger logger = ValidationPlugin.getPlugin().getMsgLogger();
- if (logger.isLoggingLevel(Level.SEVERE)) {
- LogEntry entry = ValidationPlugin.getLogEntry();
- entry.setSourceID("ValidatorManager::enableAllValidators(" + project.getName() + ")"); //$NON-NLS-1$ //$NON-NLS-2$
- entry.setTargetException(exc);
- logger.write(Level.SEVERE, entry);
-
- if (exc.getTargetException() != null) {
- entry.setTargetException(exc);
- logger.write(Level.SEVERE, entry);
- }
- }
+ } catch (InvocationTargetException e) {
+ ValidationPlugin.getPlugin().handleException(e);
+ ValidationPlugin.getPlugin().handleException(e.getTargetException());
}
}
@@ -222,19 +261,9 @@
try {
ProjectConfiguration prjp = ConfigurationManager.getManager().getProjectConfiguration(project);
return InternalValidatorManager.wrapInSet(prjp.getIncrementalValidators());
- } catch (InvocationTargetException exc) {
- Logger logger = ValidationPlugin.getPlugin().getMsgLogger();
- if (logger.isLoggingLevel(Level.SEVERE)) {
- LogEntry entry = ValidationPlugin.getLogEntry();
- entry.setSourceID("ValidatorManager::getProjectConfiguredIncrementalValidators(" + project.getName() + ")"); //$NON-NLS-1$ //$NON-NLS-2$
- entry.setTargetException(exc);
- logger.write(Level.SEVERE, entry);
-
- if (exc.getTargetException() != null) {
- entry.setTargetException(exc);
- logger.write(Level.SEVERE, entry);
- }
- }
+ } catch (InvocationTargetException e) {
+ ValidationPlugin.getPlugin().handleException(e);
+ ValidationPlugin.getPlugin().handleException(e.getTargetException());
return Collections.EMPTY_SET;
}
}
@@ -251,19 +280,9 @@
try {
ProjectConfiguration prjp = ConfigurationManager.getManager().getProjectConfiguration(project);
return InternalValidatorManager.wrapInSet(prjp.getValidators());
- } catch (InvocationTargetException exc) {
- Logger logger = ValidationPlugin.getPlugin().getMsgLogger();
- if (logger.isLoggingLevel(Level.SEVERE)) {
- LogEntry entry = ValidationPlugin.getLogEntry();
- entry.setSourceID("ValidatorManager::getProjectConfiguredValidatorMetaData(" + project.getName() + ")"); //$NON-NLS-1$ //$NON-NLS-2$
- entry.setTargetException(exc);
- logger.write(Level.SEVERE, entry);
-
- if (exc.getTargetException() != null) {
- entry.setTargetException(exc);
- logger.write(Level.SEVERE, entry);
- }
- }
+ } catch (InvocationTargetException e) {
+ ValidationPlugin.getPlugin().handleException(e);
+ ValidationPlugin.getPlugin().handleException(e.getTargetException());
return Collections.EMPTY_SET;
}
}
@@ -281,19 +300,9 @@
try {
ProjectConfiguration prjp = ConfigurationManager.getManager().getProjectConfiguration(project);
return InternalValidatorManager.wrapInSet(prjp.getEnabledIncrementalValidators(true));
- } catch (InvocationTargetException exc) {
- Logger logger = ValidationPlugin.getPlugin().getMsgLogger();
- if (logger.isLoggingLevel(Level.SEVERE)) {
- LogEntry entry = ValidationPlugin.getLogEntry();
- entry.setSourceIdentifier("ValidatorManager::getProjectEnabledIncrementalValidators" + project.getName() + ")"); //$NON-NLS-1$ //$NON-NLS-2$
- entry.setTargetException(exc);
- logger.write(Level.SEVERE, entry);
-
- if (exc.getTargetException() != null) {
- entry.setTargetException(exc);
- logger.write(Level.SEVERE, entry);
- }
- }
+ } catch (InvocationTargetException e) {
+ ValidationPlugin.getPlugin().handleException(e);
+ ValidationPlugin.getPlugin().handleException(e.getTargetException());
return Collections.EMPTY_SET;
}
}
@@ -311,19 +320,9 @@
try {
ProjectConfiguration prjp = ConfigurationManager.getManager().getProjectConfiguration(project);
return InternalValidatorManager.wrapInSet(prjp.getEnabledIncrementalValidators(false));
- } catch (InvocationTargetException exc) {
- Logger logger = ValidationPlugin.getPlugin().getMsgLogger();
- if (logger.isLoggingLevel(Level.SEVERE)) {
- LogEntry entry = ValidationPlugin.getLogEntry();
- entry.setSourceIdentifier("ValidatorManager::getProjectEnabledNonIncrementalValidators" + project.getName() + ")"); //$NON-NLS-1$ //$NON-NLS-2$
- entry.setTargetException(exc);
- logger.write(Level.SEVERE, entry);
-
- if (exc.getTargetException() != null) {
- entry.setTargetException(exc);
- logger.write(Level.SEVERE, entry);
- }
- }
+ } catch (InvocationTargetException e) {
+ ValidationPlugin.getPlugin().handleException(e);
+ ValidationPlugin.getPlugin().handleException(e.getTargetException());
return Collections.EMPTY_SET;
}
}
@@ -401,12 +400,10 @@
/**
* @deprecated For use by the validation framework only.
*/
- public Set getIncrementalValidators(Collection vmds) {
- if (vmds == null) {
- return Collections.EMPTY_SET;
- }
+ public Set<ValidatorMetaData> getIncrementalValidators(Collection vmds) {
+ if (vmds == null)return new HashSet<ValidatorMetaData>();
- Set result = new HashSet();
+ Set<ValidatorMetaData> result = new HashSet<ValidatorMetaData>();
Iterator iterator = vmds.iterator();
while (iterator.hasNext()) {
ValidatorMetaData vmd = (ValidatorMetaData) iterator.next();
@@ -528,19 +525,9 @@
ProjectConfiguration prjp = ConfigurationManager.getManager().getProjectConfiguration(project);
ValidatorMetaData[] vmds = prjp.getEnabledIncrementalValidators(true);
return InternalValidatorManager.wrapInSet(vmds);
- } catch (InvocationTargetException exc) {
- Logger logger = ValidationPlugin.getPlugin().getMsgLogger();
- if (logger.isLoggingLevel(Level.SEVERE)) {
- LogEntry entry = ValidationPlugin.getLogEntry();
- entry.setSourceIdentifier("ValidatorManager::getEnabledIncrementalValidators" + project.getName() + ")"); //$NON-NLS-1$ //$NON-NLS-2$
- entry.setTargetException(exc);
- logger.write(Level.SEVERE, entry);
-
- if (exc.getTargetException() != null) {
- entry.setTargetException(exc);
- logger.write(Level.SEVERE, entry);
- }
- }
+ } catch (InvocationTargetException e) {
+ ValidationPlugin.getPlugin().handleException(e);
+ ValidationPlugin.getPlugin().handleException(e.getTargetException());
return Collections.EMPTY_SET;
}
}
@@ -551,21 +538,18 @@
* Given a checked list of enabled validators, return a set of the ones which are configured on
* the project and, if getIncremental is true, which also run incrementally.
*/
- public Set getProjectConfiguredValidators(IProject project, Object[] enabledVal, boolean getIncremental) {
+ public Set<ValidatorMetaData> getProjectConfiguredValidators(IProject project, Object[] enabledVal,
+ boolean getIncremental) {
if ((project == null) || (enabledVal == null) || (enabledVal.length == 0)) {
- return Collections.EMPTY_SET;
+ return new HashSet<ValidatorMetaData>();
}
- Set val = new HashSet();
+ Set<ValidatorMetaData> val = new HashSet<ValidatorMetaData>();
for (int i = 0; i < enabledVal.length; i++) {
ValidatorMetaData vmd = (ValidatorMetaData) enabledVal[i];
- if (!vmd.isConfiguredOnProject(project)) {
- continue;
- }
+ if (!vmd.isConfiguredOnProject(project))continue;
- if (!getIncremental || vmd.isIncremental()) {
- val.add(vmd);
- }
+ if (!getIncremental || vmd.isIncremental())val.add(vmd);
}
return val;
}
@@ -589,7 +573,7 @@
/**
* For use by the validation framework only.
*/
- protected Set getEnabledValidators(IProject project) {
+ protected Set<ValidatorMetaData> getEnabledValidators(IProject project) {
try {
ValidatorMetaData[] vmds = null;
ProjectConfiguration prjp = ConfigurationManager.getManager().getProjectConfiguration(project);
@@ -598,86 +582,55 @@
else
vmds = getStateOfProjectLevelValidatorsFromGlobal(prjp);
return InternalValidatorManager.wrapInSet(vmds);
- } catch (InvocationTargetException exc) {
- Logger logger = ValidationPlugin.getPlugin().getMsgLogger();
- if (logger.isLoggingLevel(Level.SEVERE)) {
- LogEntry entry = ValidationPlugin.getLogEntry();
- entry.setSourceIdentifier("ValidatorManager::getEnabledValidators" + project.getName() + ")"); //$NON-NLS-1$ //$NON-NLS-2$
- entry.setTargetException(exc);
- logger.write(Level.SEVERE, entry);
-
- if (exc.getTargetException() != null) {
- entry.setTargetException(exc);
- logger.write(Level.SEVERE, entry);
- }
- }
+ } catch (InvocationTargetException e) {
+ ValidationPlugin.getPlugin().handleException(e);
+ ValidationPlugin.getPlugin().handleException(e.getTargetException());
return Collections.EMPTY_SET;
}
}
private ValidatorMetaData[] getStateOfProjectLevelValidatorsFromGlobal(ProjectConfiguration prjp) throws InvocationTargetException {
- List enabledGlobalValidatorsForProject = new ArrayList();
+ List<ValidatorMetaData> enabledGlobalValidatorsForProject = new ArrayList<ValidatorMetaData>();
GlobalConfiguration gf = ConfigurationManager.getManager().getGlobalConfiguration();
List allProjectValidator = getAllValidatorUniqueNames(prjp.getValidators());
- ValidatorMetaData[] vmd = gf.getBuildEnabledValidators();
- for(int i = 0; i < vmd.length; i++) {
- if(allProjectValidator.contains(vmd[i].getValidatorUniqueName())) {
- enabledGlobalValidatorsForProject.add(vmd[i]);
+ for(ValidatorMetaData vmd : gf.getBuildEnabledValidators()) {
+ if(allProjectValidator.contains(vmd.getValidatorUniqueName())) {
+ enabledGlobalValidatorsForProject.add(vmd);
}
}
return (ValidatorMetaData[]) enabledGlobalValidatorsForProject.toArray(new ValidatorMetaData[enabledGlobalValidatorsForProject.size()]);
}
- private List getAllValidatorUniqueNames(ValidatorMetaData[] metaData) {
- List names = new ArrayList();
- for(int i = 0; i < metaData.length; i++) {
- names.add(metaData[i].getValidatorUniqueName());
+ private List<String> getAllValidatorUniqueNames(ValidatorMetaData[] metaData) {
+ List<String> names = new ArrayList<String>();
+ for(ValidatorMetaData vmd : metaData) {
+ names.add(vmd.getValidatorUniqueName());
}
return names;
}
- protected Set getManualEnabledValidators(IProject project) {
+ protected Set<ValidatorMetaData> getManualEnabledValidators(IProject project) {
try {
ProjectConfiguration prjp = ConfigurationManager.getManager().getProjectConfiguration(project);
ValidatorMetaData[] vmds = prjp.getManualEnabledValidators();
return InternalValidatorManager.wrapInSet(vmds);
- } catch (InvocationTargetException exc) {
- Logger logger = ValidationPlugin.getPlugin().getMsgLogger();
- if (logger.isLoggingLevel(Level.SEVERE)) {
- LogEntry entry = ValidationPlugin.getLogEntry();
- entry.setSourceIdentifier("ValidatorManager::getEnabledValidators" + project.getName() + ")"); //$NON-NLS-1$ //$NON-NLS-2$
- entry.setTargetException(exc);
- logger.write(Level.SEVERE, entry);
-
- if (exc.getTargetException() != null) {
- entry.setTargetException(exc);
- logger.write(Level.SEVERE, entry);
- }
- }
+ } catch (InvocationTargetException e) {
+ ValidationPlugin.getPlugin().handleException(e);
+ ValidationPlugin.getPlugin().handleException(e.getTargetException());
return Collections.EMPTY_SET;
}
}
- protected Set getBuildEnabledValidators(IProject project) {
+ protected Set<ValidatorMetaData> getBuildEnabledValidators(IProject project) {
try {
ProjectConfiguration prjp = ConfigurationManager.getManager().getProjectConfiguration(project);
ValidatorMetaData[] vmds = prjp.getBuildEnabledValidators();
return InternalValidatorManager.wrapInSet(vmds);
- } catch (InvocationTargetException exc) {
- Logger logger = ValidationPlugin.getPlugin().getMsgLogger();
- if (logger.isLoggingLevel(Level.SEVERE)) {
- LogEntry entry = ValidationPlugin.getLogEntry();
- entry.setSourceIdentifier("ValidatorManager::getEnabledValidators" + project.getName() + ")"); //$NON-NLS-1$ //$NON-NLS-2$
- entry.setTargetException(exc);
- logger.write(Level.SEVERE, entry);
-
- if (exc.getTargetException() != null) {
- entry.setTargetException(exc);
- logger.write(Level.SEVERE, entry);
- }
- }
+ } catch (InvocationTargetException e) {
+ ValidationPlugin.getPlugin().handleException(e);
+ ValidationPlugin.getPlugin().handleException(e.getTargetException());
return Collections.EMPTY_SET;
}
}
@@ -721,19 +674,9 @@
// Can't run validation, so remove the "exceeded" message
ValidatorManager.getManager().removeMessageLimitExceeded(project);
}*/
- } catch (InvocationTargetException exc) {
- Logger logger = ValidationPlugin.getPlugin().getMsgLogger();
- if (logger.isLoggingLevel(Level.SEVERE)) {
- LogEntry entry = ValidationPlugin.getLogEntry();
- entry.setSourceIdentifier("ValidatorManager.updateTaskList(" + project.getName() + ")"); //$NON-NLS-1$ //$NON-NLS-2$
- entry.setTargetException(exc);
- logger.write(Level.SEVERE, entry);
-
- if (exc.getTargetException() != null) {
- entry.setTargetException(exc);
- logger.write(Level.SEVERE, entry);
- }
- }
+ } catch (InvocationTargetException e) {
+ ValidationPlugin.getPlugin().handleException(e);
+ ValidationPlugin.getPlugin().handleException(e.getTargetException());
}
}
@@ -743,19 +686,9 @@
ProjectConfiguration prjp = ConfigurationManager.getManager().getProjectConfiguration(project);
boolean incrementalValEnabled = (prjp.numberOfEnabledIncrementalValidators() > 0);
return canAutoValidateButtonBeEnabled(project, isGlobalAutoBuildOn, incrementalValEnabled);
- } catch (InvocationTargetException exc) {
- Logger logger = ValidationPlugin.getPlugin().getMsgLogger();
- if (logger.isLoggingLevel(Level.SEVERE)) {
- LogEntry entry = ValidationPlugin.getLogEntry();
- entry.setSourceIdentifier("ValidatorManager::canAutoValidateButtonBeEnabled" + project.getName() + ")"); //$NON-NLS-1$ //$NON-NLS-2$
- entry.setTargetException(exc);
- logger.write(Level.SEVERE, entry);
-
- if (exc.getTargetException() != null) {
- entry.setTargetException(exc);
- logger.write(Level.SEVERE, entry);
- }
- }
+ } catch (InvocationTargetException e) {
+ ValidationPlugin.getPlugin().handleException(e);
+ ValidationPlugin.getPlugin().handleException(e.getTargetException());
return false;
}
}
@@ -773,19 +706,9 @@
try {
ProjectConfiguration prjp = ConfigurationManager.getManager().getProjectConfiguration(project);
return prjp.isEnabled(validatorName);
- } catch (InvocationTargetException exc) {
- Logger logger = ValidationPlugin.getPlugin().getMsgLogger();
- if (logger.isLoggingLevel(Level.SEVERE)) {
- LogEntry entry = ValidationPlugin.getLogEntry();
- entry.setSourceIdentifier("ValidatorManager.isEnabled(" + project.getName() + ", " + validatorName + ")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- entry.setTargetException(exc);
- logger.write(Level.SEVERE, entry);
-
- if (exc.getTargetException() != null) {
- entry.setTargetException(exc);
- logger.write(Level.SEVERE, entry);
- }
- }
+ } catch (InvocationTargetException e) {
+ ValidationPlugin.getPlugin().handleException(e);
+ ValidationPlugin.getPlugin().handleException(e.getTargetException());
return false;
}
}
@@ -798,19 +721,9 @@
try {
ProjectConfiguration prjp = ConfigurationManager.getManager().getProjectConfiguration(project);
return prjp.isEnabled(vmd);
- } catch (InvocationTargetException exc) {
- Logger logger = ValidationPlugin.getPlugin().getMsgLogger();
- if (logger.isLoggingLevel(Level.SEVERE)) {
- LogEntry entry = ValidationPlugin.getLogEntry();
- entry.setSourceIdentifier("ValidatorManager::isEnabled" + project.getName() + ")"); //$NON-NLS-1$ //$NON-NLS-2$
- entry.setTargetException(exc);
- logger.write(Level.SEVERE, entry);
-
- if (exc.getTargetException() != null) {
- entry.setTargetException(exc);
- logger.write(Level.SEVERE, entry);
- }
- }
+ } catch (InvocationTargetException e) {
+ ValidationPlugin.getPlugin().handleException(e);
+ ValidationPlugin.getPlugin().handleException(e.getTargetException());
return false;
}
}
@@ -840,112 +753,52 @@
try {
ProjectConfiguration prjp = ConfigurationManager.getManager().getProjectConfiguration(project);
return prjp.numberOfEnabledValidators();
- } catch (InvocationTargetException exc) {
- Logger logger = ValidationPlugin.getPlugin().getMsgLogger();
- if (logger.isLoggingLevel(Level.SEVERE)) {
- LogEntry entry = ValidationPlugin.getLogEntry();
- entry.setSourceIdentifier("ValidatorManager::numberProjectEnabledValidators" + project.getName() + ")"); //$NON-NLS-1$ //$NON-NLS-2$
- entry.setTargetException(exc);
- logger.write(Level.SEVERE, entry);
-
- if (exc.getTargetException() != null) {
- entry.setTargetException(exc);
- logger.write(Level.SEVERE, entry);
- }
- }
+ } catch (InvocationTargetException e) {
+ ValidationPlugin.getPlugin().handleException(e);
+ ValidationPlugin.getPlugin().handleException(e.getTargetException());
return 0;
}
}
/**
- * Suspends, or undoes the suspension of, validation on the current project. If "suspend" is
- * true then validation is suspended and if it's "false" then validation will run on the
- * project. The value of this variable is not persisted.
- *
- * Be VERY CAREFUL when you use this method! Turn validation back on in a finally block because
- * if the code which suspended validation crashes, the user has no way to unsuspend validation.
- * The user will have to shut down & restart WSAD to get validation to work again.
- *
- * If an operation is used to make changes that should not be validated, then use the technique
- * documented in the "Preventing Validation" topic of the "Validation Guide" (in the
- * org.eclipse.wst.validation.internal.provisional.core.core.prop plugin). If you don't, validation may not be suspended.
+ * @deprecated Use ValidationFramework.suspendValidation(project, suspend) directly.
+ * @see ValidationFramework#suspendValidation(IProject, boolean)
*/
public void suspendValidation(IProject project, boolean suspend) {
- if (project == null) {
- return;
- }
-
- if (!project.exists()) {
- return;
- }
-
- // Ignore whether or not the project is closed. If it's closed then it will not be built
- // and the "Run Validation" option will not be available.
- if (suspend) {
- _suspendedProjects.add(project);
- } else {
- _suspendedProjects.remove(project);
- }
+ ValidationFramework.getDefault().suspendValidation(project, suspend);
}
/**
- * Suspends, or undoes the suspension of, validation on all projects in the workbench. If
- * "suspend" is true then validation is suspended and if it's "false" then validation will run.
- * The value of this variable is not persisted.
- *
- * Be VERY CAREFUL when you use this method! Turn validation back on in a finally block because
- * if the code which suspended validation crashes, the user has no way to unsuspend validation.
- * The user will have to shut down & restart WSAD to get validation to work again.
- *
- * If an operation is used to make changes that should not be validated, then use the technique
- * documented in the "Preventing Validation" topic of the "Validation Guide" (in the
- * org.eclipse.wst.validation.internal.provisional.core.core.prop plugin). If you don't, validation may not be suspended.
+ * @deprecated Use ValidationFramework.getDefault().suspendAllValidation(suspend) directly.
+ * @see ValidationFramework#suspendAllValidation(boolean)
*/
public void suspendAllValidation(boolean suspend) {
- _suspendAllValidation = suspend;
+ ValidationFramework.getDefault().suspendAllValidation(suspend);
}
/**
- * Return true if "suspend all" is enabled, false otherwise.
+ * @deprecated Use ValidationFramework.getDefault().isSuspended() directly.
+ * @see ValidationFramework#isSuspended()
*/
public boolean isSuspended() {
- return _suspendAllValidation;
+ return ValidationFramework.getDefault().isSuspended();
}
/**
- * Returns true if validation will not run on the project because it's been suspended. This
- * method checks only the suspension status; if validation cannot run for some other reason (for
- * example, there are no enabled validators), yet the IProject is not suspended, this method
- * will return true even though validation will not run.
+ * @deprecated Use ValidationFramework.getDefault().isSuspended(project) directly.
+ * @see ValidationFramework#isSuspended(IProject)
*/
public boolean isSuspended(IProject project) {
- if (project == null) {
- return false;
- }
-
- if (_suspendAllValidation) {
- return true;
- }
-
- return _suspendedProjects.contains(project);
+ return ValidationFramework.getDefault().isSuspended(project);
}
/**
- * This method should be called by any code that is preparing to suspend validation on a
- * project. Rather than calling isSuspsend(IProject), which will return true if all validation
- * has been suspended, this method returns the state of the project itself. See the
- * ValidationMigrator::migrateProject for an example.
- *
- * @param project
- * @return boolean
+ * @deprecated Use ValidationFramework.getDefault().isProjectSuspended(project) directly.
+ * @see ValidationFramework#isProjectSuspended(IProject)
*/
public boolean isProjectSuspended(IProject project) {
- if (project == null) {
- return false;
- }
-
- return _suspendedProjects.contains(project);
+ return ValidationFramework.getDefault().isProjectSuspended(project);
}
/**
@@ -954,7 +807,7 @@
* Given a list of validators' plugin ids, make those validators enabled for this project. All
* others, disable for this project.
*/
- public void setEnabledValidators(IProject project, Set vmdsSet, IProgressMonitor monitor) {
+ public void setEnabledValidators(IProject project, Set<ValidatorMetaData> vmdsSet, IProgressMonitor monitor) {
try {
ProjectConfiguration prjp = ConfigurationManager.getManager().getProjectConfiguration(project);
ValidatorMetaData[] vmds = null;
@@ -968,19 +821,9 @@
prjp.setEnabledValidators(vmds);
updateTaskList(project);
- } catch (InvocationTargetException exc) {
- Logger logger = ValidationPlugin.getPlugin().getMsgLogger();
- if (logger.isLoggingLevel(Level.SEVERE)) {
- LogEntry entry = ValidationPlugin.getLogEntry();
- entry.setSourceIdentifier("ValidatorManager.setEnabledValidators(" + project.getName() + ", Set, IProgressMonitor)"); //$NON-NLS-1$ //$NON-NLS-2$
- entry.setTargetException(exc);
- logger.write(Level.SEVERE, entry);
-
- if (exc.getTargetException() != null) {
- entry.setTargetException(exc);
- logger.write(Level.SEVERE, entry);
- }
- }
+ } catch (InvocationTargetException e) {
+ ValidationPlugin.getPlugin().handleException(e);
+ ValidationPlugin.getPlugin().handleException(e.getTargetException());
}
}
@@ -989,7 +832,7 @@
}
/**
- * This method is for use by batch EJB deploy only. Only in batch mode is an infinitie number of
+ * This method is for use by batch EJB deploy only. Only in batch mode is an infinite number of
* messages allowed.
*
* Enable a project to have an infinite number of messages.
@@ -1012,45 +855,45 @@
return null;
}
- /**
- * Return true if the given IMarker is a "limit was exceeded" message, false otherwise.
- */
- private boolean isLimitMessage(IMarker marker) {
- if (marker == null) {
- return false;
- }
+// /**
+// * Return true if the given IMarker is a "limit was exceeded" message, false otherwise.
+// */
+// private boolean isLimitMessage(IMarker marker) {
+// if (marker == null) {
+// return false;
+// }
+//
+// return TaskListUtility.isOwner(marker, WorkbenchReporter.getUniqueId(getMessageLimitOwner()));
+// }
- return TaskListUtility.isOwner(marker, WorkbenchReporter.getUniqueId(getMessageLimitOwner()));
- }
-
- /**
- * Return all of the IMarkers on the IProject excluding the "limit was exceeded" message. If
- * there are no markers, return null.
- */
- private IMarker[] getValidationTasksWithoutLimitMessage(IProject project) {
- IMarker[] allTasks = TaskListUtility.getValidationTasks(project, IMessage.ALL_MESSAGES);
- if ((allTasks == null) || (allTasks.length == 0)) {
- return null;
- }
-
- // Don't check if the limit message exists because
- // any interaction with markers is costly. Since the
- // interaction has to be done at least once, make that
- // single occasion in the for loop below.
- IMarker[] validatorMessages = new IMarker[allTasks.length];
- int count = 0; // how many markers have been added to the result array?
- for (int i = 0; i < allTasks.length; i++) {
- IMarker marker = allTasks[i];
- if (isLimitMessage(marker)) {
- continue;
- }
- validatorMessages[count++] = marker;
- }
-
- IMarker[] result = new IMarker[count];
- System.arraycopy(validatorMessages, 0, result, 0, count);
- return result;
- }
+// /**
+// * Return all of the IMarkers on the IProject excluding the "limit was exceeded" message. If
+// * there are no markers, return null.
+// */
+// private IMarker[] getValidationTasksWithoutLimitMessage(IProject project) {
+// IMarker[] allTasks = TaskListUtility.getValidationTasks(project, IMessage.ALL_MESSAGES);
+// if ((allTasks == null) || (allTasks.length == 0)) {
+// return null;
+// }
+//
+// // Don't check if the limit message exists because
+// // any interaction with markers is costly. Since the
+// // interaction has to be done at least once, make that
+// // single occasion in the for loop below.
+// IMarker[] validatorMessages = new IMarker[allTasks.length];
+// int count = 0; // how many markers have been added to the result array?
+// for (int i = 0; i < allTasks.length; i++) {
+// IMarker marker = allTasks[i];
+// if (isLimitMessage(marker)) {
+// continue;
+// }
+// validatorMessages[count++] = marker;
+// }
+//
+// IMarker[] result = new IMarker[count];
+// System.arraycopy(validatorMessages, 0, result, 0, count);
+// return result;
+// }
/**
* This method should be called only by the validation framework. Return true if the message was
@@ -1064,14 +907,8 @@
try {
ResourcesPlugin.getWorkspace().deleteMarkers(exceededMessage);
return true;
- } catch (CoreException exc) {
- Logger logger = ValidationPlugin.getPlugin().getMsgLogger();
- if (logger.isLoggingLevel(Level.SEVERE)) {
- LogEntry entry = ValidationPlugin.getLogEntry();
- entry.setSourceID("ValidatorManager.removeMessageLimitExceeded(" + project.getName() + ")"); //$NON-NLS-1$ //$NON-NLS-2$
- entry.setTargetException(exc);
- logger.write(Level.SEVERE, entry);
- }
+ } catch (CoreException e) {
+ ValidationPlugin.getPlugin().handleException(e);
}
}
return false;
@@ -1134,32 +971,31 @@
}
public void cacheMessage(IValidatorJob validator, MessageInfo info){
- ArrayList list = (ArrayList) validatorMsgs.get(validator);
+ List<MessageInfo> list = _validatorMsgs.get(validator);
if( list == null ){
- list = new ArrayList();
- validatorMsgs.put(validator, list);
+ list = new ArrayList<MessageInfo>();
+ _validatorMsgs.put(validator, list);
}
list.add(info);
}
- public ArrayList getMessages(IValidatorJob validator){
- ArrayList list = (ArrayList) validatorMsgs.get(validator);
- if( list == null )
- list = new ArrayList();
+ public List<MessageInfo> getMessages(IValidatorJob validator){
+ List<MessageInfo> list = _validatorMsgs.get(validator);
+ if( list == null )list = new ArrayList<MessageInfo>();
return list;
}
public void clearMessages(IValidatorJob validator){
- ArrayList list = (ArrayList) validatorMsgs.get(validator);
+ List<MessageInfo> list = _validatorMsgs.get(validator);
if( list != null ){
list.clear();
}
- validatorMsgs.remove( validator );
+ _validatorMsgs.remove( validator );
}
- public Set getProblemValidators() {
- return problemValidators;
+ public Set<ValidatorMetaData> getProblemValidators() {
+ return _problemValidators;
}
}
diff --git a/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/operations/ValidatorSubsetOperation.java b/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/operations/ValidatorSubsetOperation.java
index 533bb70..274ddec 100644
--- a/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/operations/ValidatorSubsetOperation.java
+++ b/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/operations/ValidatorSubsetOperation.java
@@ -1,10 +1,10 @@
/*******************************************************************************
- * Copyright (c) 2001, 2004 IBM Corporation and others.
+ * Copyright (c) 2001, 2008 IBM Corporation 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:
* IBM Corporation - initial API and implementation
*******************************************************************************/
@@ -33,10 +33,8 @@
* This operation is not intended to be subclassed outside of the validation framework.
*/
public class ValidatorSubsetOperation extends ValidationOperation {
- protected static final String DEFAULT_DEFAULTEXTENSION = null; // By default, assume that there
-
- // is no default fallback
- // extension
+ // By default, assume that there is no default fallback extension
+ protected static final String DEFAULT_DEFAULTEXTENSION = null;
/**
* Create an operation that runs a full validation on the named validators either if validation
@@ -149,40 +147,12 @@
public ValidatorSubsetOperation(IProject project, String fileExtension, String defaultExtension, Object[] changedResources, boolean async) throws IllegalArgumentException {
super(project, shouldForce(changedResources), async);
- boolean filterIn = false; // force the resources to be filtered in even if the validator
- // doesn't normally take them?
- ValidatorMetaData[] vmds = InternalValidatorManager.getManager().getValidatorsForExtension(project, fileExtension); // return
- // a
- // list
- // of
- // validators
- // which
- // are
- // configured
- // to
- // run
- // on
- // files
- // with
- // that
- // extension.
- // A
- // validator
- // will
- // be
- // in
- // the
- // list
- // whether
- // it
- // has
- // been
- // enabled
- // or
- // disabled
- // by
- // the
- // user.
+ // force the resources to be filtered in even if the validator doesn't normally take them?
+ boolean filterIn = false;
+
+ // a list of validators which are configured to run on files with that extension.
+ // A validator will be in the list whether it has been enabled or disabled by the user.
+ ValidatorMetaData[] vmds = InternalValidatorManager.getManager().getValidatorsForExtension(project, fileExtension);
if ((defaultExtension != null) && ((vmds == null) || (vmds.length == 0))) {
filterIn = true;
vmds = InternalValidatorManager.getManager().getValidatorsForExtension(project, defaultExtension);
@@ -194,23 +164,9 @@
setEnabledValidators(InternalValidatorManager.wrapInSet(vmds));
- setFileDeltas(FilterUtil.getFileDeltas(getEnabledValidators(), changedResources, filterIn)); // construct
- // an
- // array
- // of
- // IFileDelta[]
- // to
- // wrap
- // the
- // Object[];
- // one
- // IFileDelta
- // for
- // each
- // Object
- // in
- // the
- // array
+ // construct an array of IFileDelta[] to wrap the Object[];
+ // one IFileDelta for each Object in the array
+ setFileDeltas(FilterUtil.getFileDeltas(getEnabledValidators(), changedResources, filterIn));
}
/**
@@ -249,7 +205,7 @@
}
if ((changedResources != null) && (changedResources.length > 0)) {
- Set tempSet = new HashSet();
+ Set<IProject> tempSet = new HashSet<IProject>();
for (int i = 0; i < changedResources.length; i++) {
IProject p = changedResources[i].getProject();
if (!p.isOpen()) {
@@ -266,9 +222,9 @@
}
if (tempSet.size() != 1) {
StringBuffer buffer = new StringBuffer("\n"); //$NON-NLS-1$
- Iterator iterator = tempSet.iterator();
+ Iterator<IProject> iterator = tempSet.iterator();
while (iterator.hasNext()) {
- IProject p = (IProject) iterator.next();
+ IProject p = iterator.next();
buffer.append("\t"); //$NON-NLS-1$
buffer.append(p.getName());
if (iterator.hasNext()) {
@@ -288,22 +244,7 @@
setEnabledValidators(InternalValidatorManager.wrapInSet(vmds));
setFileDeltas(FilterUtil.getFileDeltas(getEnabledValidators(), changedResources, ifileDeltaType)); // construct
- // an
- // array
- // of
- // IFileDelta[]
- // to
- // wrap
- // the
- // IResource[];
- // one
- // IFileDelta
- // for
- // each
- // IResource
- // in
- // the
- // array
+ // an array of IFileDelta[] to wrap the IResource[]; one IFileDelta for each IResource in the array
}
/**
@@ -313,14 +254,14 @@
* of IProject.)
*/
public void setValidators(String[] validatorNames) throws IllegalArgumentException {
- Set enabled = new HashSet();
- for (int i = 0; i < validatorNames.length; i++) {
- ValidatorMetaData vmd = ValidationRegistryReader.getReader().getValidatorMetaData(validatorNames[i]);
+ Set<ValidatorMetaData> enabled = new HashSet<ValidatorMetaData>();
+ for (String name : validatorNames) {
+ ValidatorMetaData vmd = ValidationRegistryReader.getReader().getValidatorMetaData(name);
if (vmd == null) {
- // No validator, with that plugin id, can be run on that project.
+ // No validator, with that plug-in id, can be run on that project.
// Either the validator isn't installed, or the IProject passed in
// doesn't have the necessary nature.
- throw new IllegalArgumentException(validatorNames[i]);
+ throw new IllegalArgumentException(name);
}
enabled.add(vmd);
}
@@ -333,4 +274,4 @@
public void setAlwaysRun(boolean force) {
setForce(force);
}
-}
\ No newline at end of file
+}
diff --git a/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/operations/WorkbenchContext.java b/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/operations/WorkbenchContext.java
index 58b281f..eea36c1 100644
--- a/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/operations/WorkbenchContext.java
+++ b/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/operations/WorkbenchContext.java
@@ -1,10 +1,10 @@
/*******************************************************************************
- * Copyright (c) 2001, 2004 IBM Corporation and others.
+ * Copyright (c) 2001, 2008 IBM Corporation 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:
* IBM Corporation - initial API and implementation
*******************************************************************************/
@@ -16,7 +16,6 @@
import java.util.Collection;
import java.util.Hashtable;
import java.util.List;
-import java.util.logging.Level;
import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IFile;
@@ -25,9 +24,8 @@
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.Path;
-import org.eclipse.jem.util.logger.LogEntry;
-import org.eclipse.jem.util.logger.proxy.Logger;
import org.eclipse.wst.validation.internal.RegistryConstants;
+import org.eclipse.wst.validation.internal.Tracing;
import org.eclipse.wst.validation.internal.plugin.ValidationPlugin;
import org.eclipse.wst.validation.internal.provisional.core.IMessage;
@@ -37,20 +35,18 @@
* symbolic model name.
*/
public class WorkbenchContext implements IWorkbenchContext {
- private IProject _project = null;
- private Hashtable _modelRegistry = null;
-// private static final IContainer[] NO_CONTAINERS = new IContainer[0];
- private int _ruleGroup = RegistryConstants.ATT_RULE_GROUP_DEFAULT;
- public List validationFileURIs = null;
+ private IProject _project;
+ private Hashtable<String,Method> _modelRegistry;
+ private int _ruleGroup = RegistryConstants.ATT_RULE_GROUP_DEFAULT;
+ public List<String> validationFileURIs;
public static final String GET_PROJECT_FILES = "getAllFiles"; //$NON-NLS-1$
public static final String GET_FILE = "getFile"; //$NON-NLS-1$
-// private static final IContainer[] NO_CONTAINERS = new IContainer[0];
public static final String VALIDATION_MARKER = "com.ibm.etools.validation.problemmarker"; //$NON-NLS-1$
public static final String VALIDATION_MARKER_OWNER = "owner"; //$NON-NLS-1$
public WorkbenchContext() {
super();
- _modelRegistry = new Hashtable();
+ _modelRegistry = new Hashtable<String, Method>();
registerModel(IRuleGroup.PASS_LEVEL, "loadRuleGroup"); //$NON-NLS-1$
@@ -157,16 +153,9 @@
foundResource = null;
}
}
- } catch (IllegalArgumentException exc) {
+ } catch (IllegalArgumentException e) {
foundResource = null;
-
- Logger logger = ValidationPlugin.getPlugin().getMsgLogger();
- if (logger.isLoggingLevel(Level.SEVERE)) {
- LogEntry entry = ValidationPlugin.getLogEntry();
- entry.setSourceID("WorkbenchContext::getContainerRelativePath(IResource, IContainer)"); //$NON-NLS-1$
- entry.setTargetException(exc);
- logger.write(Level.SEVERE, entry);
- }
+ ValidationPlugin.getPlugin().handleException(e);
}
}
@@ -292,14 +281,8 @@
}
try {
return util.getLineNo(object);
- } catch (Throwable exc) {
- Logger logger = ValidationPlugin.getPlugin().getMsgLogger();
- if (logger.isLoggingLevel(Level.SEVERE)) {
- LogEntry entry = ValidationPlugin.getLogEntry();
- entry.setSourceID("WorkbenchContext.getLineNo(Object)"); //$NON-NLS-1$
- entry.setTargetException(exc);
- logger.write(Level.SEVERE, entry);
- }
+ } catch (Exception e) {
+ ValidationPlugin.getPlugin().handleException(e);
return IMessage.LINENO_UNSET;
}
@@ -337,14 +320,8 @@
Method m = null;
try {
m = getClass().getMethod(methodName, parmTypes);
- } catch (NoSuchMethodException exc) {
- Logger logger = ValidationPlugin.getPlugin().getMsgLogger();
- if (logger.isLoggingLevel(Level.SEVERE)) {
- LogEntry entry = ValidationPlugin.getLogEntry();
- entry.setSourceID("WorkbenchContext::getMethod(String, Class[])"); //$NON-NLS-1$
- entry.setTargetException(exc);
- logger.write(Level.SEVERE, entry);
- }
+ } catch (NoSuchMethodException e) {
+ ValidationPlugin.getPlugin().handleException(e);
return null;
}
@@ -390,10 +367,10 @@
* @param validatorClassName The name of the validator class.
* @return The collection of files relevant for the validator class specified.
*/
- public Collection getFiles(String validatorClassName)
+ public Collection<IFile> getFiles(String validatorClassName)
{
IProject project = getProject();
- List files = new ArrayList();
+ List<IFile> files = new ArrayList<IFile>();
getFiles(files, project, validatorClassName);
return files;
}
@@ -406,7 +383,7 @@
* @param resource The resource to look for files in.
* @param validatorClassName The name of the validator class.
*/
- protected void getFiles(Collection files, IContainer resource, String validatorClassName)
+ protected void getFiles(Collection<IFile> files, IContainer resource, String validatorClassName)
{
try
{
@@ -416,7 +393,7 @@
if (ValidatorManager.getManager().isApplicableTo(validatorClassName, resourceArray[i]))
{
if (resourceArray[i] instanceof IFile)
- files.add(resourceArray[i]);
+ files.add((IFile)resourceArray[i]);
}
if (resourceArray[i].getType() == IResource.FOLDER)
getFiles(files,(IContainer)resourceArray[i], validatorClassName) ;
@@ -549,9 +526,7 @@
* "registerModel" method.
*/
public final boolean isRegistered(String symbolicName) {
- if (symbolicName == null) {
- return false;
- }
+ if (symbolicName == null)return false;
return _modelRegistry.containsKey(symbolicName);
}
@@ -577,52 +552,22 @@
*/
public Object loadModel(String symbolicName, Object[] parms) {
try {
- Method loader = (Method) _modelRegistry.get(symbolicName);
- if (loader == null) {
- return null;
- }
+ Method loader = _modelRegistry.get(symbolicName);
+ if (loader == null)return null;
return loader.invoke(this, parms);
- } catch (IllegalAccessException exc) {
- Logger logger = ValidationPlugin.getPlugin().getMsgLogger();
- if (logger.isLoggingLevel(Level.SEVERE)) {
- LogEntry entry = ValidationPlugin.getLogEntry();
- entry.setSourceID("WorkbenchContext::loadModel(String, Object[])"); //$NON-NLS-1$
- entry.setTargetException(exc);
- logger.write(Level.SEVERE, entry);
- }
+ } catch (IllegalAccessException e) {
+ ValidationPlugin.getPlugin().handleException(e);
return null;
- } catch (InvocationTargetException exc) {
- Logger logger = ValidationPlugin.getPlugin().getMsgLogger();
- if (logger.isLoggingLevel(Level.SEVERE)) {
- LogEntry entry = ValidationPlugin.getLogEntry();
- entry.setSourceID("WorkbenchContext::loadModel(String, Object[])"); //$NON-NLS-1$
- entry.setTargetException(exc);
- logger.write(Level.SEVERE, entry);
-
- if (exc.getTargetException() != null) {
- entry.setTargetException(exc.getTargetException());
- logger.write(Level.SEVERE, exc);
- }
- }
+ } catch (InvocationTargetException e) {
+ ValidationPlugin.getPlugin().handleException(e);
+ ValidationPlugin.getPlugin().handleException(e.getTargetException());
return null;
- } catch (NullPointerException exc) {
- Logger logger = ValidationPlugin.getPlugin().getMsgLogger();
- if (logger.isLoggingLevel(Level.SEVERE)) {
- LogEntry entry = ValidationPlugin.getLogEntry();
- entry.setSourceID("WorkbenchContext::loadModel(String, Object[])"); //$NON-NLS-1$
- entry.setTargetException(exc);
- logger.write(Level.SEVERE, entry);
- }
+ } catch (NullPointerException e) {
+ ValidationPlugin.getPlugin().handleException(e);
return null;
- } catch (ExceptionInInitializerError exc) {
- Logger logger = ValidationPlugin.getPlugin().getMsgLogger();
- if (logger.isLoggingLevel(Level.SEVERE)) {
- LogEntry entry = ValidationPlugin.getLogEntry();
- entry.setSourceID("WorkbenchContext::loadModel(String, Object[])"); //$NON-NLS-1$
- entry.setTargetException(exc);
- logger.write(Level.SEVERE, entry);
- }
+ } catch (ExceptionInInitializerError e) {
+ ValidationPlugin.getPlugin().handleException(e);
return null;
}
}
@@ -688,9 +633,8 @@
protected final void registerModel(String symbolicName, String loadMethodName, Class[] parms) {
Method method = getMethod(loadMethodName, parms);
if (method == null) {
- Logger logger = ValidationPlugin.getPlugin().getMsgLogger();
- if (logger.isLoggingLevel(Level.FINE)) {
- StringBuffer buffer = new StringBuffer("Load method "); //$NON-NLS-1$
+ if (Tracing.isLogging()) {
+ StringBuffer buffer = new StringBuffer("WorkbenchContext-01: load method "); //$NON-NLS-1$
buffer.append(loadMethodName);
buffer.append("("); //$NON-NLS-1$
for (int i = 0; (parms != null) && (i < parms.length); i++) {
@@ -698,10 +642,7 @@
}
buffer.append(") must exist. " + getClass().getName() + " cannot support model " + symbolicName); //$NON-NLS-1$ //$NON-NLS-2$
- LogEntry entry = ValidationPlugin.getLogEntry();
- entry.setSourceID("ValidationRegistryReader.readExtension(IExtension)"); //$NON-NLS-1$
- entry.setText(buffer.toString());
- logger.write(Level.FINE, entry);
+ Tracing.log(buffer);
}
} else {
_modelRegistry.put(symbolicName, method);
@@ -763,28 +704,26 @@
}
public String getTargetObjectName(Object object) {
- // TODO Auto-generated method stub
return null;
}
public String[] getURIs() {
String[] uris = new String[validationFileURIs.size()];
- for(int i = 0; i < validationFileURIs.size(); i++)
- uris[i] = (String) validationFileURIs.get(i);
+ validationFileURIs.toArray(uris);
return uris;
}
/**
* @return Returns the validationFileURIs.
*/
- public List getValidationFileURIs() {
+ public List<String> getValidationFileURIs() {
return validationFileURIs;
}
/**
* @param validationFileURIs The validationFileURIs to set.
*/
- public void setValidationFileURIs(List validationFileURIs) {
+ public void setValidationFileURIs(List<String> validationFileURIs) {
this.validationFileURIs = validationFileURIs;
}
-}
\ No newline at end of file
+}
diff --git a/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/operations/WorkbenchFileDelta.java b/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/operations/WorkbenchFileDelta.java
index 2871aff..0953e0a 100644
--- a/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/operations/WorkbenchFileDelta.java
+++ b/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/operations/WorkbenchFileDelta.java
@@ -1,10 +1,10 @@
/*******************************************************************************
- * Copyright (c) 2001, 2004 IBM Corporation and others.
+ * Copyright (c) 2001, 2007 IBM Corporation 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:
* IBM Corporation - initial API and implementation
*******************************************************************************/
@@ -20,8 +20,8 @@
* with the FileDelta.
*/
public class WorkbenchFileDelta extends FileDelta {
- private IResource _resource = null;
- private Object _changedResource = null;
+ private IResource _resource;
+ private Object _changedResource;
private static final String FILE_NAME = "FILE NAME:"; //$NON-NLS-1$
private static final String DELTA = " DELTA: "; //$NON-NLS-1$
@@ -75,4 +75,4 @@
buffer.append(String.valueOf(getObject()));
return buffer.toString();
}
-}
\ No newline at end of file
+}
diff --git a/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/operations/WorkbenchReporter.java b/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/operations/WorkbenchReporter.java
index db6d2aa..f9162f3 100644
--- a/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/operations/WorkbenchReporter.java
+++ b/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/operations/WorkbenchReporter.java
@@ -1,10 +1,10 @@
/*******************************************************************************
- * Copyright (c) 2001, 2004 IBM Corporation and others.
+ * Copyright (c) 2001, 2008 IBM Corporation 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:
* IBM Corporation - initial API and implementation
*******************************************************************************/
@@ -13,18 +13,16 @@
import java.text.MessageFormat;
import java.util.Arrays;
import java.util.List;
-import java.util.logging.Level;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.jem.util.logger.LogEntry;
-import org.eclipse.jem.util.logger.proxy.Logger;
import org.eclipse.wst.validation.internal.ResourceConstants;
import org.eclipse.wst.validation.internal.ResourceHandler;
import org.eclipse.wst.validation.internal.TaskListUtility;
+import org.eclipse.wst.validation.internal.Tracing;
import org.eclipse.wst.validation.internal.ValidationRegistryReader;
import org.eclipse.wst.validation.internal.ValidatorMetaData;
import org.eclipse.wst.validation.internal.plugin.ValidationPlugin;
@@ -35,70 +33,56 @@
/**
* IValidator instances will interact with an instance of this class, but should never cast that
- * IReporter instance to WorkbenchReporter. The WorkbenchReporter class will be moved in Milestone
- * 4.
- *
+ * IReporter instance to WorkbenchReporter.
+ * <p>
* This class handles interaction between the user and the IValidator in the eclipse workbench
* environment.
- *
+ * <p>
* This class must not be called outside of an IWorkspaceRunnable or IRunnableWithProgress. Many
* resource deltas can be generated by the methods in this class.
- *
+ * <p>
* Only the validation framework may instantiate or alter instances of this class.
*/
-public final class WorkbenchReporter implements IReporter {
+public class WorkbenchReporter implements IReporter {
public static final String DEFAULT_LOCATION = ""; //$NON-NLS-1$
public static final int NO_MESSAGE_LIMIT = -1;
- private IProject _project = null;
- private IProgressMonitor _monitor = null;
+ private IProject _project;
+ private IProgressMonitor _monitor;
public static void addMessage(IResource resource, Class messageOwner, IMessage message) {
- addMessage(resource, messageOwner, null, message); // null ClassLoader = use the default
- // (clazz.getClassLoader());
+ addMessage(resource, messageOwner, null, message);
}
public static void addMessage(IResource resource, Class messageOwner, ClassLoader cl, IMessage message) {
addMessage(resource, messageOwner, cl, message, null, ""); //$NON-NLS-1$
}
- public static void addMessage(IResource resource, Class clazz, IMessage message, String targetObjectName, String location) {
- addMessage(resource, clazz, null, message, targetObjectName, location); // null = use the
- // default
- // ClassLoader
- // (class.getClassLoader())
+ public static void addMessage(IResource resource, Class clazz, IMessage message,
+ String targetObjectName, String location) {
+ addMessage(resource, clazz, null, message, targetObjectName, location);
}
- public static void addMessage(IResource resource, Class clazz, IMessage message, String targetObjectName, String location,String markerId) {
- addMessage(resource, clazz, null, message, targetObjectName, location,markerId); // null = use the
- // default
- // ClassLoader
- // (class.getClassLoader())
+ public static void addMessage(IResource resource, Class clazz, IMessage message,
+ String targetObjectName, String location,String markerId) {
+ addMessage(resource, clazz, null, message, targetObjectName, location,markerId);
}
-
+ public static void addMessage(IResource resource, Class clazz, ClassLoader cl, IMessage message,
+ String targetObjectName, String location) {
+ if ((clazz == null) || (message == null) || (resource == null))return;
- public static void addMessage(IResource resource, Class clazz, ClassLoader cl, IMessage message, String targetObjectName, String location) {
- if ((clazz == null) || (message == null) || (resource == null)) {
- return;
- }
-
- if (cl == null) {
- cl = clazz.getClassLoader();
- }
+ if (cl == null)cl = clazz.getClassLoader();
addMessage(resource, getUniqueId(clazz), cl, message, targetObjectName, location);
}
- public static void addMessage(IResource resource, Class clazz, ClassLoader cl, IMessage message, String targetObjectName, String location, String markerId) {
- if ((clazz == null) || (message == null) || (resource == null)) {
- return;
- }
+ public static void addMessage(IResource resource, Class clazz, ClassLoader cl, IMessage message,
+ String targetObjectName, String location, String markerId) {
+ if ((clazz == null) || (message == null) || (resource == null))return;
- if (cl == null) {
- cl = clazz.getClassLoader();
- }
+ if (cl == null)cl = clazz.getClassLoader();
addMessage(resource, getUniqueId(clazz), cl, message, targetObjectName, location, markerId);
}
@@ -107,44 +91,32 @@
addMessage(resource, messageOwnerId, cl, message, null, ""); //$NON-NLS-1$
}
- public static void addMessage(IResource resource, String messageOwnerId, ClassLoader cl, IMessage message, String targetObjectName, String location) {
+ public static void addMessage(IResource resource, String messageOwnerId, ClassLoader cl,
+ IMessage message, String targetObjectName, String location) {
int severity = message.getSeverity();
try {
- TaskListUtility.addTask(messageOwnerId, resource, location, message.getId(), message.getText(cl), severity,targetObjectName, message.getGroupName(), message.getOffset(), message.getLength());
- } catch (CoreException exc) {
- // Couldn't add the task to the task list for some reason...
- Logger logger = ValidationPlugin.getPlugin().getMsgLogger();
- if (logger.isLoggingLevel(Level.SEVERE)) {
- LogEntry entry = ValidationPlugin.getLogEntry();
- entry.setSourceID("WorkbenchReporter.addMessage(Class,, IResource, IMessage, String, String"); //$NON-NLS-1$
- entry.setTargetException(exc);
- logger.write(Level.SEVERE, entry);
- }
+ TaskListUtility.addTask(messageOwnerId, resource, location, message.getId(),
+ message.getText(cl), severity,targetObjectName, message.getGroupName(),
+ message.getOffset(), message.getLength());
+ } catch (CoreException e) {
+ ValidationPlugin.getPlugin().handleException(e);
}
}
- public static void addMessage(IResource resource, String messageOwnerId, ClassLoader cl, IMessage message, String targetObjectName, String location, String markerId) {
+ public static void addMessage(IResource resource, String messageOwnerId, ClassLoader cl,
+ IMessage message, String targetObjectName, String location, String markerId) {
int severity = message.getSeverity();
try {
- TaskListUtility.addTask(messageOwnerId, resource, location, message.getId(), message.getText(cl), severity,markerId,targetObjectName, message.getGroupName(), message.getOffset(), message.getLength());
- } catch (CoreException exc) {
- // Couldn't add the task to the task list for some reason...
- Logger logger = ValidationPlugin.getPlugin().getMsgLogger();
- if (logger.isLoggingLevel(Level.SEVERE)) {
- LogEntry entry = ValidationPlugin.getLogEntry();
- entry.setSourceID("WorkbenchReporter.addMessage(Class,, IResource, IMessage, String, String"); //$NON-NLS-1$
- entry.setTargetException(exc);
- logger.write(Level.SEVERE, entry);
- }
+ TaskListUtility.addTask(messageOwnerId, resource, location, message.getId(),
+ message.getText(cl), severity,markerId,targetObjectName, message.getGroupName(),
+ message.getOffset(), message.getLength());
+ } catch (CoreException e) {
+ ValidationPlugin.getPlugin().handleException(e);
}
}
-
-
public static void removeAllMessages(IResource resource, IValidator validator) {
- if (resource == null) {
- return;
- }
+ if (resource == null)return;
ValidatorMetaData vmd = ValidationRegistryReader.getReader().getValidatorMetaData(validator);
if (vmd == null) {
@@ -155,15 +127,8 @@
String[] validatorNames = vmd.getValidatorNames();
try {
TaskListUtility.removeAllTasks(resource, validatorNames);
- } catch (CoreException exc) {
- // Couldn't remove the task from the task list for some reason...
- Logger logger = ValidationPlugin.getPlugin().getMsgLogger();
- if (logger.isLoggingLevel(Level.SEVERE)) {
- LogEntry entry = ValidationPlugin.getLogEntry();
- entry.setSourceID("WorkbenchReporter.removeAllMessages(String[], IResource, String)"); //$NON-NLS-1$
- entry.setTargetException(exc);
- logger.write(Level.SEVERE, entry);
- }
+ } catch (CoreException e) {
+ ValidationPlugin.getPlugin().handleException(e);
}
}
@@ -187,33 +152,18 @@
//String targetObjectName = getTargetObjectName(vmd.getHelper(resource.getProject()), object);
String targetObjectName = getTargetObjectName( getHelper( resource.getProject(), validator), object);
removeAllMessages(resource, validatorNames, targetObjectName);
- } catch (InstantiationException exc) {
+ } catch (InstantiationException e) {
// Remove the vmd from the reader's list
ValidationRegistryReader.getReader().disableValidator(vmd);
-
- // Log the reason for the disabled validator
- final Logger logger = ValidationPlugin.getPlugin().getMsgLogger();
- if (logger.isLoggingLevel(Level.SEVERE)) {
- LogEntry entry = ValidationPlugin.getLogEntry();
- entry.setSourceID("WorkbenchReporter::removeAllMessages(IResource, IValidator, Object)"); //$NON-NLS-1$
- entry.setTargetException(exc);
- logger.write(Level.SEVERE, entry);
- }
+ ValidationPlugin.getPlugin().handleException(e);
}
}
public static void removeAllMessages(IResource resource, String[] validatorNames, String targetObjectName) {
try {
TaskListUtility.removeAllTasks(resource, validatorNames, targetObjectName);
- } catch (CoreException exc) {
- // Couldn't remove the task from the task list for some reason...
- Logger logger = ValidationPlugin.getPlugin().getMsgLogger();
- if (logger.isLoggingLevel(Level.SEVERE)) {
- LogEntry entry = ValidationPlugin.getLogEntry();
- entry.setSourceID("WorkbenchReporter.removeAllMessages(String[], IResource, String)"); //$NON-NLS-1$
- entry.setTargetException(exc);
- logger.write(Level.SEVERE, entry);
- }
+ } catch (CoreException e) {
+ ValidationPlugin.getPlugin().handleException(e);
}
}
@@ -232,15 +182,8 @@
public static void removeMessageSubset(IResource resource, String[] ownerId, String targetObjectName, String groupName) {
try {
TaskListUtility.removeTaskSubset(resource, ownerId, targetObjectName, groupName);
- } catch (CoreException exc) {
- // Couldn't remove the task to the task list for some reason...
- Logger logger = ValidationPlugin.getPlugin().getMsgLogger();
- if (logger.isLoggingLevel(Level.SEVERE)) {
- LogEntry entry = ValidationPlugin.getLogEntry();
- entry.setSourceID("WorkbenchReporter.removeMessageSubset(String[], IResource, String, String)"); //$NON-NLS-1$
- entry.setTargetException(exc);
- logger.write(Level.SEVERE, entry);
- }
+ } catch (CoreException e) {
+ ValidationPlugin.getPlugin().handleException(e);
}
}
@@ -265,15 +208,6 @@
return getUniqueId(validator.getClass());
}
- public static Logger getMsgLogger(IValidator validator) {
- ValidatorMetaData vmd = ValidationRegistryReader.getReader().getValidatorMetaData(validator);
- if (vmd == null) {
- return ValidationPlugin.getPlugin().getMsgLogger();
- }
-
- return vmd.getMsgLogger();
- }
-
public static String getLocation(IWorkbenchContext helper, IMessage message) {
if (message == null) {
return getLocationText(helper, null);
@@ -289,14 +223,8 @@
String location = null;
try {
location = helper.getLocation(targetObject);
- } catch (Throwable exc) {
- Logger logger = ValidationPlugin.getPlugin().getMsgLogger();
- if (logger.isLoggingLevel(Level.SEVERE)) {
- LogEntry entry = ValidationPlugin.getLogEntry();
- entry.setSourceID("WorkbenchReporter.getLocationText(Object)"); //$NON-NLS-1$
- entry.setTargetException(exc);
- logger.write(Level.SEVERE, entry);
- }
+ } catch (Exception e) {
+ ValidationPlugin.getPlugin().handleException(e);
}
if ((location == null) || (location.trim().equals(""))) { //$NON-NLS-1$
location = DEFAULT_LOCATION;
@@ -317,14 +245,8 @@
String targetObjectName = null;
try {
targetObjectName = helper.getTargetObjectName(targetObject);
- } catch (Throwable exc) {
- Logger logger = ValidationPlugin.getPlugin().getMsgLogger();
- if (logger.isLoggingLevel(Level.SEVERE)) {
- LogEntry entry = ValidationPlugin.getLogEntry();
- entry.setSourceID("WorkbenchReporter.getTargetObjectName(Object)"); //$NON-NLS-1$
- entry.setTargetException(exc);
- logger.write(Level.SEVERE, entry);
- }
+ } catch (Exception e) {
+ ValidationPlugin.getPlugin().handleException(e);
}
return targetObjectName;
}
@@ -415,7 +337,7 @@
try {
IWorkbenchContext helper = getHelper(validator);
resource = helper.getResource(object);
- } catch (InstantiationException exc) {
+ } catch (InstantiationException e) {
try {
// Unlikely that an exception will be thrown, because this method is
// invoked by the validator, and if the validator is invoked, it's likely
@@ -425,45 +347,20 @@
// Remove the vmd from the reader's list
ValidationRegistryReader.getReader().disableValidator(vmd);
- // Log the reason for the disabled validator
- Logger logger = ValidationPlugin.getPlugin().getMsgLogger();
- if (logger.isLoggingLevel(Level.SEVERE)) {
- LogEntry entry = ValidationPlugin.getLogEntry();
- entry.setSourceID("WorkbenchReporter::getMessageResource(IValidator, Object)"); //$NON-NLS-1$
- entry.setTargetException(exc);
- logger.write(Level.SEVERE, entry);
- }
- } catch (IllegalArgumentException exc2) {
+ ValidationPlugin.getPlugin().handleException(e);
+ } catch (IllegalArgumentException e2) {
// Even the IValidator is invalid. Unfortunately, can't disable the
// validator because it can't be found by the registry reader.
// Log the reason for the disabled validator
- Logger logger = ValidationPlugin.getPlugin().getMsgLogger();
- if (logger.isLoggingLevel(Level.SEVERE)) {
- LogEntry entry = ValidationPlugin.getLogEntry();
- entry.setSourceID("WorkbenchReporter::getMessageResource(IValidator, Object)"); //$NON-NLS-1$
- entry.setTargetException(exc2);
- logger.write(Level.SEVERE, entry);
- }
+ ValidationPlugin.getPlugin().handleException(e2);
}
- } catch (IllegalArgumentException exc) {
+ } catch (IllegalArgumentException e) {
// Even the IValidator is invalid. Unfortunately, can't disable the
// validator because it can't be found by the registry reader.
// Log the reason for the disabled validator
- Logger logger = ValidationPlugin.getPlugin().getMsgLogger();
- if (logger.isLoggingLevel(Level.SEVERE)) {
- LogEntry entry = ValidationPlugin.getLogEntry();
- entry.setSourceID("WorkbenchReporter::getMessageResource(IValidator, Object)"); //$NON-NLS-1$
- entry.setTargetException(exc);
- logger.write(Level.SEVERE, entry);
- }
- } catch (Throwable exc) {
- Logger logger = ValidationPlugin.getPlugin().getMsgLogger();
- if (logger.isLoggingLevel(Level.SEVERE)) {
- LogEntry entry = ValidationPlugin.getLogEntry();
- entry.setSourceID("WorkbenchReporter.getMessageResource(IValidator, Object)"); //$NON-NLS-1$
- entry.setTargetException(exc);
- logger.write(Level.SEVERE, entry);
- }
+ ValidationPlugin.getPlugin().handleException(e);
+ } catch (Exception e) {
+ ValidationPlugin.getPlugin().handleException(e);
}
}
}
@@ -522,24 +419,15 @@
ValidatorMetaData vmd = getVMD(validator);
try {
helper = getHelper(validator);
- } catch (InstantiationException exc) {
+ } catch (InstantiationException e) {
try {
// Unlikely that an exception will be thrown, because this method is
// invoked by the validator, and if the validator is invoked, it's likely
// that the helper has been loaded too
-
-
+
// Remove the vmd from the reader's list
ValidationRegistryReader.getReader().disableValidator(vmd);
-
- // Log the reason for the disabled validator
- Logger logger = ValidationPlugin.getPlugin().getMsgLogger();
- if (logger.isLoggingLevel(Level.SEVERE)) {
- LogEntry entry = ValidationPlugin.getLogEntry();
- entry.setSourceID("WorkbenchReporter::addMessage(IValidator, IMessage)"); //$NON-NLS-1$
- entry.setTargetException(exc);
- logger.write(Level.SEVERE, entry);
- }
+ ValidationPlugin.getPlugin().handleException(e);
return;
} catch (IllegalArgumentException exc2) {
logDisabledValidator(exc2);
@@ -551,29 +439,23 @@
}
if (resource == null) {
- Logger logger = ValidationPlugin.getPlugin().getMsgLogger();
- if (logger.isLoggingLevel(Level.FINE)) {
- LogEntry entry = ValidationPlugin.getLogEntry();
- entry.setSourceID("WorkbenchReporter.addMessage(IValidator, Message)"); //$NON-NLS-1$
- entry.setMessageTypeIdentifier(ResourceConstants.VBF_EXC_INVALID_RESOURCE);
- String result = MessageFormat.format(ResourceHandler.getExternalizedMessage(ResourceConstants.VBF_EXC_INVALID_RESOURCE), new String[]{message.getText(), getTargetObjectName(helper, message)});
- entry.setText(result);
- //entry.setTokens(new String[]{message.getText(), getTargetObjectName(helper, message)});
- logger.write(Level.FINE, entry);
+ if (Tracing.isLogging()) {
+ String result = MessageFormat.format(ResourceHandler.getExternalizedMessage(
+ ResourceConstants.VBF_EXC_INVALID_RESOURCE),
+ new Object[]{message.getText(), getTargetObjectName(helper, message)});
+ Tracing.log("WorkbenchReporter-01: ", result); //$NON-NLS-1$
}
return;
}
- ValidatorManager mgr = ValidatorManager.getManager();
if( validator instanceof IValidatorJob ){
- cacheMessage( (IValidatorJob)validator, resource, validator.getClass(), message, getTargetObjectName(helper, message), getLocation(helper, message), getMarkerId(vmd, message) );
+ cacheMessage( (IValidatorJob)validator, resource, validator.getClass(), message,
+ getTargetObjectName(helper, message), getLocation(helper, message), getMarkerId(vmd, message) );
}else
- addMessage(resource, validator.getClass(), message, getTargetObjectName(helper, message), getLocation(helper, message),getMarkerId(vmd,message));
+ addMessage(resource, validator.getClass(), message, getTargetObjectName(helper, message),
+ getLocation(helper, message),getMarkerId(vmd,message));
}
- /**
- * @param vmd
- */
private String getMarkerId(ValidatorMetaData vmd, IMessage message) {
if (vmd.getMarkerIds() != null) {
if (vmd.getMarkerIds().length == 1)
@@ -582,10 +464,10 @@
String messageMarkerId = message.getMarkerId();
if (messageMarkerId != null && messageMarkerId.length() > 0) {
String firstMarkerId = vmd.getMarkerIds()[0];
- String pluginQualifier = firstMarkerId.substring(0, firstMarkerId.lastIndexOf("."));
+ String pluginQualifier = firstMarkerId.substring(0, firstMarkerId.lastIndexOf(".")); //$NON-NLS-1$
String qualifiedMessageMarkerId = null;
if (messageMarkerId.indexOf(pluginQualifier) == -1)
- qualifiedMessageMarkerId = pluginQualifier + "." + messageMarkerId;
+ qualifiedMessageMarkerId = pluginQualifier + "." + messageMarkerId; //$NON-NLS-1$
else
qualifiedMessageMarkerId = messageMarkerId;
if (Arrays.asList(vmd.getMarkerIds()).contains(qualifiedMessageMarkerId))
@@ -596,20 +478,11 @@
return null;
}
- /**
- * @param exc
- */
- private void logDisabledValidator(IllegalArgumentException exc) {
+ private void logDisabledValidator(IllegalArgumentException e) {
// Even the IValidator is invalid. Unfortunately, can't disable the
// validator because it can't be found by the registry reader.
// Log the reason for the disabled validator
- Logger logger = ValidationPlugin.getPlugin().getMsgLogger();
- if (logger.isLoggingLevel(Level.SEVERE)) {
- LogEntry entry = ValidationPlugin.getLogEntry();
- entry.setSourceID("WorkbenchReporter::addMessage(IValidator, IMessage)"); //$NON-NLS-1$
- entry.setTargetException(exc);
- logger.write(Level.SEVERE, entry);
- }
+ ValidationPlugin.getPlugin().handleException(e);
return;
}
@@ -654,22 +527,14 @@
try {
//helper = vmd.getHelper(resource.getProject());
helper = getHelper(validator);
- } catch (InstantiationException exc) {
+ } catch (InstantiationException e) {
// Unlikely that an exception will be thrown, because this method is
// invoked by the validator, and if the validator is invoked, it's likely
// that the helper has been loaded too.
// Remove the vmd from the reader's list
ValidationRegistryReader.getReader().disableValidator(vmd);
-
- // Log the reason for the disabled validator
- Logger logger = ValidationPlugin.getPlugin().getMsgLogger();
- if (logger.isLoggingLevel(Level.SEVERE)) {
- LogEntry entry = ValidationPlugin.getLogEntry();
- entry.setSourceID("WorkbenchReporter::removeAllMessages(IResource, IValidator, Object)"); //$NON-NLS-1$
- entry.setTargetException(exc);
- logger.write(Level.SEVERE, entry);
- }
+ ValidationPlugin.getPlugin().handleException(e);
return;
}
@@ -699,22 +564,14 @@
//helper = vmd.getHelper(resource.getProject());
helper = getHelper( resource.getProject(), validator );
}
- catch (InstantiationException exc) {
+ catch (InstantiationException e) {
// Unlikely that an exception will be thrown, because this method is
// invoked by the validator, and if the validator is invoked, it's likely
// that the helper has been loaded too.
// Remove the vmd from the reader's list
ValidationRegistryReader.getReader().disableValidator(vmd);
-
- // Log the reason for the disabled validator
- Logger logger = ValidationPlugin.getPlugin().getMsgLogger();
- if (logger.isLoggingLevel(Level.SEVERE)) {
- LogEntry entry = ValidationPlugin.getLogEntry();
- entry.setSourceID("WorkbenchReporter::removeAllMessages(IResource, IValidator, Object)"); //$NON-NLS-1$
- entry.setTargetException(exc);
- logger.write(Level.SEVERE, entry);
- }
+ ValidationPlugin.getPlugin().handleException(e);
return;
}
@@ -725,24 +582,16 @@
}
private static void cacheMessage( IValidatorJob validator,
- IResource resource,
- Class clazz, IMessage message,
- String targetObjectName,
- String location,
- String markerId ){
+ IResource resource, Class clazz, IMessage message,
+ String targetObjectName, String location, String markerId ){
- if ((clazz == null) || (message == null) || (resource == null)) {
- return;
- }
- ClassLoader cl = null;
- if (cl == null) {
- cl = clazz.getClassLoader();
- }
+ if ((clazz == null) || (message == null) || (resource == null))return;
+
+ ClassLoader cl = clazz.getClassLoader();
String text = message.getText(cl);
MessageInfo msgInfo = new MessageInfo(getUniqueId(clazz), resource, location,
- text, targetObjectName, markerId, message );
+ text, targetObjectName, markerId, message );
- ValidatorManager mgr = ValidatorManager.getManager();
- mgr.cacheMessage( validator, msgInfo );
+ ValidatorManager.getManager().cacheMessage( validator, msgInfo );
}
-}
\ No newline at end of file
+}
diff --git a/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/plugin/ValidationHelperRegistryReader.java b/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/plugin/ValidationHelperRegistryReader.java
index eef9e53..887f7cd 100644
--- a/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/plugin/ValidationHelperRegistryReader.java
+++ b/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/plugin/ValidationHelperRegistryReader.java
@@ -1,10 +1,10 @@
/*******************************************************************************
- * Copyright (c) 2001, 2004 IBM Corporation and others.
+ * Copyright (c) 2001, 2008 IBM Corporation 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:
* IBM Corporation - initial API and implementation
*******************************************************************************/
@@ -14,22 +14,26 @@
import java.util.List;
import org.eclipse.core.runtime.IConfigurationElement;
-import org.eclipse.jem.util.RegistryReader;
+import org.eclipse.core.runtime.IExtension;
+import org.eclipse.core.runtime.IExtensionPoint;
+import org.eclipse.core.runtime.IStatus;
+import org.eclipse.core.runtime.Platform;
import org.eclipse.wst.validation.internal.IProjectValidationHelper;
-public class ValidationHelperRegistryReader extends RegistryReader {
+public class ValidationHelperRegistryReader {
+ /** validationHelper - extension point name. */
public static final String VALIDATION_HELPER = "validationHelper"; //$NON-NLS-1$
- static final String ATT_ID = "id"; //$NON-NLS-1$
- static final String ATT_HELPER_CLASS = "helperClass"; //$NON-NLS-1$
- private static ValidationHelperRegistryReader INSTANCE = null;
- private List validationHelpers = null;
- /**
- * Default constructor
- */
+ static final String ATT_ID = "id"; //$NON-NLS-1$
+
+ /** helperClass - class that implements the extension. */
+ static final String ATT_HELPER_CLASS = "helperClass"; //$NON-NLS-1$
+
+ private static ValidationHelperRegistryReader INSTANCE = null;
+ private List<IProjectValidationHelper> _validationHelpers;
+
public ValidationHelperRegistryReader() {
- super(ValidationPlugin.PLUGIN_ID, VALIDATION_HELPER);
}
public static ValidationHelperRegistryReader getInstance() {
@@ -39,11 +43,42 @@
}
return INSTANCE;
}
+
+ /**
+ * Read the extension point and parse it.
+ */
+ public void readRegistry() {
+ IExtensionPoint point = Platform.getExtensionRegistry()
+ .getExtensionPoint(ValidationPlugin.PLUGIN_ID, VALIDATION_HELPER);
+ if (point == null)return;
+ IConfigurationElement[] elements = point.getConfigurationElements();
+ for (int i = 0; i < elements.length; i++) {
+ internalReadElement(elements[i]);
+ }
+ }
- private List getValidationHelpers() {
- if (validationHelpers == null)
- validationHelpers = new ArrayList();
- return validationHelpers;
+ private void internalReadElement(IConfigurationElement element) {
+ boolean recognized = this.readElement(element);
+ if (!recognized) {
+ logError(element, "Error processing extension: " + element); //$NON-NLS-1$
+ }
+ }
+
+ /*
+ * Logs the error in the desktop log using the provided text and the information in the configuration element.
+ */
+ protected void logError(IConfigurationElement element, String text) {
+ IExtension extension = element.getDeclaringExtension();
+ StringBuffer buf = new StringBuffer();
+ buf.append("Plugin " + extension.getContributor().getName() + ", extension " + extension.getExtensionPointUniqueIdentifier()); //$NON-NLS-1$ //$NON-NLS-2$
+ buf.append("\n" + text); //$NON-NLS-1$
+ ValidationPlugin.getPlugin().logMessage(IStatus.ERROR, buf.toString());
+ }
+
+ private List<IProjectValidationHelper> getValidationHelpers() {
+ if (_validationHelpers == null)
+ _validationHelpers = new ArrayList<IProjectValidationHelper>();
+ return _validationHelpers;
}
public boolean readElement(IConfigurationElement element) {
@@ -61,9 +96,8 @@
}
public IProjectValidationHelper getValidationHelper() {
- if (getValidationHelpers().isEmpty())
- return null;
- return (IProjectValidationHelper) getValidationHelpers().get(0);
+ if (getValidationHelpers().isEmpty())return null;
+ return getValidationHelpers().get(0);
}
}
diff --git a/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/plugin/ValidationPlugin.java b/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/plugin/ValidationPlugin.java
index 1bec1c0..2b8b8dd 100644
--- a/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/plugin/ValidationPlugin.java
+++ b/plugins/org.eclipse.wst.validation/validate/org/eclipse/wst/validation/internal/plugin/ValidationPlugin.java
@@ -1,83 +1,78 @@
-/***************************************************************************************************
- * Copyright (c) 2001, 2004 IBM Corporation and others. All rights reserved. This program and the
- * accompanying materials are made available under the terms of the Eclipse Public License v1.0
+/*******************************************************************************
+ * Copyright (c) 2001, 2008 IBM Corporation 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: IBM Corporation - initial API and implementation
- **************************************************************************************************/
+ *
+ * Contributors:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
package org.eclipse.wst.validation.internal.plugin;
-import java.util.Locale;
-
+import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResourceChangeEvent;
+import org.eclipse.core.resources.IWorkspace;
+import org.eclipse.core.resources.ProjectScope;
import org.eclipse.core.resources.ResourcesPlugin;
+import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Platform;
-import org.eclipse.jem.util.logger.LogEntry;
-import org.eclipse.wst.common.frameworks.internal.WTPPlugin;
+import org.eclipse.core.runtime.Plugin;
+import org.eclipse.core.runtime.Status;
+import org.eclipse.core.runtime.preferences.IEclipsePreferences;
+import org.eclipse.core.runtime.preferences.IScopeContext;
+import org.eclipse.wst.validation.ValidationFramework;
+import org.eclipse.wst.validation.internal.DependencyIndex;
import org.eclipse.wst.validation.internal.EventManager;
-import org.eclipse.wst.validation.internal.TimeEntry;
+import org.eclipse.wst.validation.internal.ProjectUnavailableError;
+import org.eclipse.wst.validation.internal.ResourceUnavailableError;
+import org.eclipse.wst.validation.internal.Tracing;
import org.eclipse.wst.validation.internal.core.Message;
import org.eclipse.wst.validation.internal.provisional.core.IMessage;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
-public class ValidationPlugin extends WTPPlugin {
- public static final String VALIDATION_PROP_FILE_NAME = "validate_base"; //$NON-NLS-1$
- public static final String PLUGIN_ID = "org.eclipse.wst.validation"; //$NON-NLS-1$
- private static ValidationPlugin _plugin = null;
- private static TimeEntry _tEntry = null;
- private static LogEntry _entry = null;
- private static Message _message = null;
+/**
+ * How does this plug-in get activated? There are many other plug-ins that depend on this plug-in, so there are
+ * many paths that will activate it. One common path is the J2EE perspective. If the J2EE plug-in start method, they
+ * reference a class in this plug-in, which activates the plug-in. For that case this plug-in will be active even before
+ * the workbench is up.
+ */
+public class ValidationPlugin extends Plugin {
+ public static final String VALIDATION_PROP_FILE_NAME = "validate_base"; //$NON-NLS-1$
+
+ /** org.eclipse.wst.validation - the plug-in id */
+ public static final String PLUGIN_ID = "org.eclipse.wst.validation"; //$NON-NLS-1$
+ private static ValidationPlugin _plugin;
+ private static Message _message;
public static final String VALIDATION_BUILDER_ID = PLUGIN_ID + ".validationbuilder"; //$NON-NLS-1$// plugin id of the validation builder
public static final String VALIDATOR_EXT_PT_ID = "validator"; //$NON-NLS-1$// extension point declaration of the validator
- /**
- * ValidationPlugin constructor comment.
- *
- * @param descriptor
- * org.eclipse.core.runtime.IPluginDescriptor
- */
public ValidationPlugin() {
super();
- if (_plugin == null) {
- _plugin = this;
- //Commenting off the following lines the Plugin is not activated and the
- //getMsgLogger tries to access the Plugin and the plugin is in a active pending state.
- //getMsgLogger();
- //logger.log(Level.CONFIG, null);
-
- }
+ if (_plugin == null)_plugin = this;
}
-
+
+ /**
+ * Answer the name of the bundle's property file.
+ *
+ * @deprecated Use getBundlePropertyFileName() instead.
+ */
public static String getBundleName() {
+ return getBundlePropertyFileName();
+ }
+
+ /**
+ * Answer the name of the bundle's property file.
+ */
+ public static String getBundlePropertyFileName() {
return VALIDATION_PROP_FILE_NAME;
}
- public static LogEntry getLogEntry() {
- if (_entry == null) {
- _entry = new LogEntry(VALIDATION_PROP_FILE_NAME);
- } else {
- _entry.reset();
- }
- // Always set the log entry's Locale before you use it
- // because the user can reset it on the fly.
- _entry.setLocaleOfOrigin(Locale.getDefault().toString());
- return _entry;
- }
-
- public static TimeEntry getTimeEntry() {
- if (_tEntry == null) {
- _tEntry = new TimeEntry();
- }
- _tEntry.reset();
- return _tEntry;
- }
-
public static Message getMessage() {
if (_message == null) {
_message = new Message();
- _message.setBundleName(getBundleName());
+ _message.setBundleName(getBundlePropertyFileName());
}
// clear the message for reuse
_message.setId(null);
@@ -88,41 +83,10 @@
return _message;
}
- /**
- * Retrieves a hashtable of a logger's preferences initially from the
- * com.ibm.etools.logging.util.loggingDefaults extension point if specified in the
- * com.ibm.etools.logging.util plugin.xml file. If specified, the
- * com.ibm.etools.logging.util.loggingOptions extension point preferences in the parameter
- * plugin's plugin.xml file are returned.
- *
- * The logger's preferences are stored in the return hashtable using the static instance
- * variables in LoggerStateHashKeys as keys.
- *
- * @param plugin
- * the Plugin polled for their logger's preferences in the plugin.xml file
- * @return hashtable of a logger's preferences
- */
- /*
- * public Hashtable getMsgLoggerConfig(Plugin plugin) { return (new
- * PluginHelperImpl().getMsgLoggerConfig(plugin));
- */
public static ValidationPlugin getPlugin() {
return _plugin;
}
- /**
- * Sets the logger's preferences based on values in the parameter hashtable.
- *
- * The logger's preferences are stored in the parameter hashtable using the static instance
- * variables in LoggerStateHashKeys as keys.
- *
- * @param msgLoggerConfig
- * hashtable of the logger's preferences
- */
- /*
- * public void setMsgLoggerConfig(Hashtable msgLoggerConfig) {
- * getMsgLogger().setMsgLoggerConfig(msgLoggerConfig); }
- */
public static boolean isActivated() {
Bundle bundle = Platform.getBundle(PLUGIN_ID);
if (bundle != null)
@@ -130,20 +94,24 @@
return false;
}
- /**
- * @see Plugin#startup()
- */
public void start(BundleContext context) throws Exception {
super.start(context);
- ResourcesPlugin.getWorkspace().addResourceChangeListener(EventManager.getManager(), IResourceChangeEvent.PRE_CLOSE | IResourceChangeEvent.PRE_DELETE | IResourceChangeEvent.POST_BUILD | IResourceChangeEvent.PRE_BUILD | IResourceChangeEvent.POST_CHANGE);
+ ResourcesPlugin.getWorkspace().addResourceChangeListener(EventManager.getManager(),
+ IResourceChangeEvent.PRE_CLOSE | IResourceChangeEvent.PRE_DELETE |
+ IResourceChangeEvent.POST_BUILD | IResourceChangeEvent.PRE_BUILD | IResourceChangeEvent.POST_CHANGE);
+
+ DependencyIndex di = (DependencyIndex)ValidationFramework.getDefault().getDependencyIndex();
+ IWorkspace ws = ResourcesPlugin.getWorkspace();
+ ws.addSaveParticipant(this, di);
+// ws.addResourceChangeListener(ValOperationManager.getDefault(),
+// IResourceChangeEvent.POST_BUILD | IResourceChangeEvent.PRE_BUILD);
+
}
- /**
- * @see org.eclipse.core.runtime.Plugin#stop(BundleContext context)
- */
public void stop(BundleContext context) throws Exception {
super.stop(context);
ResourcesPlugin.getWorkspace().removeResourceChangeListener( EventManager.getManager() );
+// ResourcesPlugin.getWorkspace().removeResourceChangeListener( ValOperationManager.getDefault() );
EventManager.getManager().shutdown();
}
@@ -156,5 +124,58 @@
return PLUGIN_ID;
}
+ public static IEclipsePreferences getPreferences(IProject project){
+ IScopeContext projectContext = new ProjectScope(project);
+ return projectContext.getNode(PLUGIN_ID);
+ }
-}
\ No newline at end of file
+ /**
+ * Write this exception to the log.
+ * <p>
+ * We are in the transition of moving to a new approach for localized messages. This is the new
+ * approach for exceptions.
+ *
+ * @param e the throwable, this can be null in which case it is a nop.
+ */
+ public void handleException(Throwable e){
+ handleException(e, IStatus.ERROR);
+ }
+
+ /**
+ * Write this exception to the log.
+ * <p>
+ * We are in the transition of moving to a new approach for localized messages. This is the new
+ * approach for exceptions.
+ *
+ * @param e the throwable, this can be null in which case it is a nop.
+ * @param severity the severity of the message. This must be one of the IStatus severities.
+ */
+ public void handleException(Throwable e, int severity){
+ if (e == null)return;
+ Status status = new Status(severity, PLUGIN_ID, e.getLocalizedMessage(), e);
+ getLog().log(status);
+ }
+
+ public void handleProjectUnavailableError(ProjectUnavailableError e){
+ if (Tracing.isLogging())handleException(e);
+ }
+
+ public void handleResourceUnavailableError(ResourceUnavailableError e){
+ if (Tracing.isLogging())handleException(e);
+ }
+
+ /**
+ * Write a message into the log.
+ *
+ * We are in the transition of moving to a new approach for localized messages. This is the new
+ * approach for exceptions.
+ *
+ * @param severity message severity, see IStaus
+ * @param message a localized message
+ */
+ public void logMessage(int severity, String message){
+ Status status = new Status(severity, PLUGIN_ID, message);
+ getLog().log(status);
+
+ }
+}
diff --git a/plugins/org.eclipse.wst.validation/validate_core/org/eclipse/wst/validation/internal/core/EmptySchedulingRule.java b/plugins/org.eclipse.wst.validation/validate_core/org/eclipse/wst/validation/internal/core/EmptySchedulingRule.java
index d59249a..dacb599 100644
--- a/plugins/org.eclipse.wst.validation/validate_core/org/eclipse/wst/validation/internal/core/EmptySchedulingRule.java
+++ b/plugins/org.eclipse.wst.validation/validate_core/org/eclipse/wst/validation/internal/core/EmptySchedulingRule.java
@@ -1,3 +1,13 @@
+/*******************************************************************************
+ * Copyright (c) 2005, 2007 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
package org.eclipse.wst.validation.internal.core;
import org.eclipse.core.runtime.jobs.ISchedulingRule;
@@ -12,11 +22,4 @@
public boolean isConflicting(ISchedulingRule rule) {
return rule == this;
}
-
-
-// public static ISchedulingRule getDefaultRule(){
-// IResourceRuleFactory ruleFactory = ResourcesPlugin.getWorkspace().getRuleFactory();
-// EmptySchedulingRule emptyRule = new EmptySchedulingRule();
-// ISchedulingRule rule = MultiRule.combine(ruleFactory.markerRule(fileResource), emptyRule);
-// }
}
diff --git a/plugins/org.eclipse.wst.validation/validate_core/org/eclipse/wst/validation/internal/core/FileDelta.java b/plugins/org.eclipse.wst.validation/validate_core/org/eclipse/wst/validation/internal/core/FileDelta.java
index a0229a5..04e6ba7 100644
--- a/plugins/org.eclipse.wst.validation/validate_core/org/eclipse/wst/validation/internal/core/FileDelta.java
+++ b/plugins/org.eclipse.wst.validation/validate_core/org/eclipse/wst/validation/internal/core/FileDelta.java
@@ -1,10 +1,10 @@
/*******************************************************************************
- * Copyright (c) 2001, 2004 IBM Corporation and others.
+ * Copyright (c) 2001, 2007 IBM Corporation 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:
* IBM Corporation - initial API and implementation
*******************************************************************************/
@@ -24,8 +24,8 @@
* a typical client would need to create one of these.]
*/
public class FileDelta implements IFileDelta {
- private int fileDelta = 0;
- private String fileName = null;
+ private int fileDelta;
+ private String fileName;
/**
* <p>
@@ -81,4 +81,4 @@
public void setFileName(String aFileName) {
fileName = aFileName;
}
-}
\ No newline at end of file
+}
diff --git a/plugins/org.eclipse.wst.validation/validate_core/org/eclipse/wst/validation/internal/core/IFileDelta.java b/plugins/org.eclipse.wst.validation/validate_core/org/eclipse/wst/validation/internal/core/IFileDelta.java
index 170a74b..b848eed 100644
--- a/plugins/org.eclipse.wst.validation/validate_core/org/eclipse/wst/validation/internal/core/IFileDelta.java
+++ b/plugins/org.eclipse.wst.validation/validate_core/org/eclipse/wst/validation/internal/core/IFileDelta.java
@@ -1,10 +1,10 @@
/*******************************************************************************
- * Copyright (c) 2001, 2004 IBM Corporation and others.
+ * Copyright (c) 2001, 2007 IBM Corporation 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:
* IBM Corporation - initial API and implementation
*******************************************************************************/
@@ -26,9 +26,15 @@
* or something along those lines to better capture its use. ]
*/
public interface IFileDelta {
- public static final int ADDED = 1; // the file has been added
- public static final int CHANGED = 2; // the file has been changed
- public static final int DELETED = 3; // the file has been deleted
+
+ /** 1 - the file has been added */
+ int ADDED = 1;
+
+ /** 2 - the file has been changed */
+ int CHANGED = 2;
+
+ /** 3 - the file has been deleted */
+ int DELETED = 3;
/**
* <p>
@@ -42,7 +48,7 @@
* to be validated. Can you provide a use case where the type of change is needed for
* validation? ]
*/
- public int getDeltaType();
+ int getDeltaType();
/**
* <p>
@@ -55,5 +61,5 @@
* [issue: LM - Following my comments above this method should be renamed to getArtifactName or
* something that follows along with the interface rename. ]
*/
- public String getFileName();
-}
\ No newline at end of file
+ String getFileName();
+}
diff --git a/plugins/org.eclipse.wst.validation/validate_core/org/eclipse/wst/validation/internal/core/IMessageAccess.java b/plugins/org.eclipse.wst.validation/validate_core/org/eclipse/wst/validation/internal/core/IMessageAccess.java
index 88d6eca..af85f64 100644
--- a/plugins/org.eclipse.wst.validation/validate_core/org/eclipse/wst/validation/internal/core/IMessageAccess.java
+++ b/plugins/org.eclipse.wst.validation/validate_core/org/eclipse/wst/validation/internal/core/IMessageAccess.java
@@ -1,10 +1,10 @@
/*******************************************************************************
- * Copyright (c) 2001, 2004 IBM Corporation and others.
+ * Copyright (c) 2001, 2007 IBM Corporation 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:
* IBM Corporation - initial API and implementation
*******************************************************************************/
@@ -31,7 +31,7 @@
* messages".
* @return List list of messages related to the target object
*/
- public abstract List getMessages(MessageFilter filter);
+ abstract List getMessages(MessageFilter filter);
/**
* @param filter
@@ -43,5 +43,5 @@
* @return List a list of messages related to the target object, translated into the specified
* locale.
*/
- public abstract List getMessagesAsText(MessageFilter filter, Locale targetLocale);
-}
\ No newline at end of file
+ abstract List getMessagesAsText(MessageFilter filter, Locale targetLocale);
+}
diff --git a/plugins/org.eclipse.wst.validation/validate_core/org/eclipse/wst/validation/internal/core/Message.java b/plugins/org.eclipse.wst.validation/validate_core/org/eclipse/wst/validation/internal/core/Message.java
index 99a9f46..8998112 100644
--- a/plugins/org.eclipse.wst.validation/validate_core/org/eclipse/wst/validation/internal/core/Message.java
+++ b/plugins/org.eclipse.wst.validation/validate_core/org/eclipse/wst/validation/internal/core/Message.java
@@ -1,10 +1,10 @@
/*******************************************************************************
- * Copyright (c) 2001, 2004 IBM Corporation and others.
+ * Copyright (c) 2001, 2007 IBM Corporation 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:
* IBM Corporation - initial API and implementation
*******************************************************************************/
@@ -59,17 +59,17 @@
* ]
*/
public class Message implements IMessage {
- private String id = null;
- private String[] params = null;
+ private String id;
+ private String[] params;
private int severity = MessageFilter.ANY_SEVERITY;
- private Object targetObject = null;
- private String bundleName = null;
- private String groupName = null;
+ private Object targetObject;
+ private String bundleName;
+ private String groupName;
private int lineNumber = IMessage.LINENO_UNSET;
private int length = IMessage.OFFSET_UNSET;
private int offset = IMessage.OFFSET_UNSET;
- private HashMap messageAttributes;
- private String markerId = null;
+ private HashMap<String, Object> messageAttributes;
+ private String markerId;
/**
* <p>
@@ -284,7 +284,7 @@
message = bundle.getString(getId());
if (getParams() != null) {
- message = java.text.MessageFormat.format(message, getParams());
+ message = java.text.MessageFormat.format(message, (Object[])getParams());
}
} catch (MissingResourceException exc) {
System.err.println(exc.getMessage());
@@ -379,12 +379,12 @@
public void setAttribute(String attributeName, Object value) {
if(messageAttributes == null) {
- messageAttributes = new HashMap();
+ messageAttributes = new HashMap<String, Object>();
}
messageAttributes.put(attributeName,value);
}
- public HashMap getAttributes() {
+ public HashMap<String,Object> getAttributes() {
return messageAttributes;
}
@@ -395,4 +395,4 @@
public void setMarkerId(String markerId) {
this.markerId = markerId;
}
-}
\ No newline at end of file
+}
diff --git a/plugins/org.eclipse.wst.validation/validate_core/org/eclipse/wst/validation/internal/core/MessageFilter.java b/plugins/org.eclipse.wst.validation/validate_core/org/eclipse/wst/validation/internal/core/MessageFilter.java
index a380061..a8e97a3 100644
--- a/plugins/org.eclipse.wst.validation/validate_core/org/eclipse/wst/validation/internal/core/MessageFilter.java
+++ b/plugins/org.eclipse.wst.validation/validate_core/org/eclipse/wst/validation/internal/core/MessageFilter.java
@@ -1,10 +1,10 @@
/*******************************************************************************
- * Copyright (c) 2001, 2004 IBM Corporation and others.
+ * Copyright (c) 2001, 2005 IBM Corporation 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:
* IBM Corporation - initial API and implementation
*******************************************************************************/
@@ -126,4 +126,4 @@
public void setValidator(IValidator validator) {
this.validator = validator;
}
-}
\ No newline at end of file
+}
diff --git a/plugins/org.eclipse.wst.validation/validate_core/org/eclipse/wst/validation/internal/core/ValidationException.java b/plugins/org.eclipse.wst.validation/validate_core/org/eclipse/wst/validation/internal/core/ValidationException.java
index e5fb20a..f8970a7 100644
--- a/plugins/org.eclipse.wst.validation/validate_core/org/eclipse/wst/validation/internal/core/ValidationException.java
+++ b/plugins/org.eclipse.wst.validation/validate_core/org/eclipse/wst/validation/internal/core/ValidationException.java
@@ -1,10 +1,10 @@
/*******************************************************************************
- * Copyright (c) 2001, 2004 IBM Corporation and others.
+ * Copyright (c) 2001, 2007 IBM Corporation 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:
* IBM Corporation - initial API and implementation
*******************************************************************************/
@@ -25,9 +25,9 @@
* </p>
*/
public class ValidationException extends Exception {
- private Throwable _lowLevelException = null;
- private IMessage _message = null;
- private ClassLoader _loader = null;
+ private Throwable _lowLevelException;
+ private IMessage _message;
+ private ClassLoader _loader;
private final static long serialVersionUID = -3387516993124229949L;
@@ -162,4 +162,4 @@
String message = getMessage(locale);
return (message != null) ? (s + ": " + message) : s; //$NON-NLS-1$
}
-}
\ No newline at end of file
+}
diff --git a/plugins/org.eclipse.wst.validation/validate_core/org/eclipse/wst/validation/internal/core/ValidatorLauncher.java b/plugins/org.eclipse.wst.validation/validate_core/org/eclipse/wst/validation/internal/core/ValidatorLauncher.java
index 8d90e0c..f053410 100644
--- a/plugins/org.eclipse.wst.validation/validate_core/org/eclipse/wst/validation/internal/core/ValidatorLauncher.java
+++ b/plugins/org.eclipse.wst.validation/validate_core/org/eclipse/wst/validation/internal/core/ValidatorLauncher.java
@@ -1,22 +1,19 @@
/*******************************************************************************
- * Copyright (c) 2001, 2004 IBM Corporation and others.
+ * Copyright (c) 2001, 2008 IBM Corporation 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:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.wst.validation.internal.core;
-import java.util.ArrayList;
import java.util.Iterator;
-import java.util.logging.Level;
+import java.util.List;
import org.eclipse.core.runtime.CoreException;
-import org.eclipse.jem.util.logger.LogEntry;
-import org.eclipse.jem.util.logger.proxy.Logger;
import org.eclipse.wst.validation.internal.TaskListUtility;
import org.eclipse.wst.validation.internal.operations.MessageInfo;
import org.eclipse.wst.validation.internal.operations.ValidatorManager;
@@ -26,23 +23,14 @@
import org.eclipse.wst.validation.internal.provisional.core.IValidator;
import org.eclipse.wst.validation.internal.provisional.core.IValidatorJob;
-
-
/**
- * <p>
* This singleton launches the validation on a single validator. Clients should call this class's
* <code>start</code> method to begin the validation.
- * </p>
*/
public class ValidatorLauncher {
- private static ValidatorLauncher _launcher = null;
+ private static ValidatorLauncher _launcher;
-
- /**
- * Default constructor
- */
private ValidatorLauncher() {
- //Default constructor
}
/**
@@ -60,9 +48,7 @@
* This method is the launch point of the validation. It runs validation on the validator
* accessed by the IValidationContext. When the validation is complete, each validator may perform resource
* cleanup, if necessary.
- *
- * <br>
- * <br>
+ * <p>
* If <code>helper</code>,<code>validator</code>, or <code>reporter</code> are null,
* validation is not performed. <code>changedFiles</code> may be null, or empty, if a full
* build should be done.
@@ -73,25 +59,15 @@
* @param validator
* validator object to launch validation.
* @param reporter
- * Is an instance of an IReporter interface, which is used for
- * interaction with the user.
- * @param changedFiles
- * Is an array of files which have been added, changed, or deleted
- * since the last validation. If <code>changedFiles</code> is null, or if it is an empty
- * array, then a full validation should be performed. Otherwise, validation on just the files
- * listed in the array should performed if the validator supports incremental validation.
+ * Is an instance of an IReporter interface, which is used for interaction with the user.
*/
public void start(final IValidationContext helper, final IValidator validator, final IReporter reporter) throws ValidationException {
- if ((helper == null) || (validator == null) || (reporter == null)) {
- return;
- }
+ if ((helper == null) || (validator == null) || (reporter == null))return;
// Can't force each validator to check if it's cancelled or not,
- // so check for cancellation here. Hopefully the user won't wait
- // too long.
- if (reporter.isCancelled()) {
- return;
- }
+ // so check for cancellation here. Hopefully the user won't wait too long.
+ if (reporter.isCancelled())return;
+
// If the validator is about to perform a full build, remove all of its previous validation
// messages.
@@ -107,7 +83,7 @@
//the validators who have implemented IValidatorJob but are running synchronously
//would log messages now ...
ValidatorManager mgr = ValidatorManager.getManager();
- final ArrayList list = mgr.getMessages((IValidatorJob)validator);
+ final List list = mgr.getMessages((IValidatorJob)validator);
Iterator it = list.iterator();
while( it.hasNext() ){
@@ -115,16 +91,12 @@
try {
TaskListUtility.addTask( info.getMessageOwnerId(), info.getResource(),
info.getLocation(), info.getMsg().getId(), info.getText(),
- info.getMsg().getSeverity(), info.getTargetObjectName(),
+ info.getMsg().getSeverity(), info.getMarkerId(),
+ info.getTargetObjectName(),
info.getMsg().getGroupName(), info.getMsg().getOffset(), info.getMsg().getLength());
- } catch (CoreException exc) {
- Logger logger = ValidationPlugin.getPlugin().getMsgLogger();
- if (logger.isLoggingLevel(Level.SEVERE)) {
- LogEntry entry = ValidationPlugin.getLogEntry();
- entry.setTargetException(exc);
- logger.write(Level.SEVERE, entry);
- }
+ } catch (CoreException e) {
+ ValidationPlugin.getPlugin().handleException(e);
}
}
mgr.clearMessages( (IValidatorJob)validator );
@@ -132,4 +104,4 @@
}
-}
\ No newline at end of file
+}
diff --git a/plugins/org.eclipse.wst.validation/validate_core/org/eclipse/wst/validation/internal/provisional/core/IMessage.java b/plugins/org.eclipse.wst.validation/validate_core/org/eclipse/wst/validation/internal/provisional/core/IMessage.java
index 28de1c3..5550942 100644
--- a/plugins/org.eclipse.wst.validation/validate_core/org/eclipse/wst/validation/internal/provisional/core/IMessage.java
+++ b/plugins/org.eclipse.wst.validation/validate_core/org/eclipse/wst/validation/internal/provisional/core/IMessage.java
@@ -1,10 +1,10 @@
/*******************************************************************************
- * Copyright (c) 2001, 2004 IBM Corporation and others.
+ * Copyright (c) 2001, 2008 IBM Corporation 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:
* IBM Corporation - initial API and implementation
*******************************************************************************/
@@ -22,9 +22,16 @@
* Given these three values as input, this interface can be queried for the final message string.
* (i.e., the message with the parameters already substituted in.) Either the default Locale can be
* used, or the caller can specify a Locale.
- *
- * @plannedfor 1.0
* </p>
+ * <p>
+ * <b>Provisional API:</b> This class/interface is part of an interim API that is still under development and expected to
+ * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
+ * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
+ * (repeatedly) as the API evolves.
+ * </p>
+ */
+public interface IMessage {
+ /*
*
* [issue: CS - The 'IMessage' interface would be simpler without the bundle related details. I'd like to understand
* why we can 'precompute' the translated message. Is there some benefit to perform 'late computation' of these messages?
@@ -46,57 +53,67 @@
* - void setAttribute(String attributeName, Object value)
* - Object getAttribute(String attributeName);
* ]
- */
-public interface IMessage {
- public static final int OFFSET_UNSET = -1; // see getLength(), getOffset()
- public static final int LINENO_UNSET = 0;
+ */
+ int OFFSET_UNSET = -1; // see getLength(), getOffset()
+ int LINENO_UNSET = 0;
+
/**
* Typically used to specify error messages.
*/
- public static final int HIGH_SEVERITY = 0x0001;
+ int HIGH_SEVERITY = 0x0001;
/**
* Typically used to specify warning messages.
*/
- public static final int NORMAL_SEVERITY = 0x0002;
+ int NORMAL_SEVERITY = 0x0002;
/**
* Typically used to specify information messages.
*/
- public static final int LOW_SEVERITY = 0x0004;
+ int LOW_SEVERITY = 0x0004;
/**
* Specify high (error) and normal (warning) messages. Typically used with a MessageFilter, to
* filter out information messages.
*/
- public static final int ERROR_AND_WARNING = HIGH_SEVERITY | NORMAL_SEVERITY;
+ int ERROR_AND_WARNING = HIGH_SEVERITY | NORMAL_SEVERITY;
/**
* Specify all types of messages. Typically used with a MessageFilter.
*/
- public static final int ALL_MESSAGES = ERROR_AND_WARNING | LOW_SEVERITY;
+ int ALL_MESSAGES = ERROR_AND_WARNING | LOW_SEVERITY;
+
+ /**
+ * TargetResource - The key to use when associating a resource with a message via an
+ * attribute.
+ * <p>
+ * Normally, the target is stored using the setTargetObject() method, but
+ * some of the legacy validators used this field for objects that where not IResources.
+ * In order to associate the message with the proper IResource the validator can store
+ * the IResource as an attribute and use this string as the key.
+ * </p>
+ */
+ String TargetResource = "TargetResource"; //$NON-NLS-1$
/**
* @return the name of the bundle which this message is contained in.
*/
- public String getBundleName();
+ String getBundleName();
/**
- * <p>
* To support removal of a subset of validation messages, an IValidator may assign group names
* to IMessages. An IMessage subset will be identified by the name of its group. Default (null)
* means no group.
- * </p>
+ *
* @return the name of the group to which the message belongs.
*/
- public String getGroupName();
+ String getGroupName();
/**
- * <p>
* Returns the id of the message. Message ids are used as the constants in property bundles
* which localize the description of the message in a locale-independent fashion. The id is the
* key, in the resource bundle, which identifies the string to be loaded. The id may not be null
* or the empty string.
- * </p>
+ *
* @return the id of the message
*/
- public java.lang.String getId();
+ String getId();
/**
* @return the length of the problem area, starting from the offset. If unset, value =
@@ -104,41 +121,35 @@
*
* @see #getOffset()
*/
- public int getLength();
+ int getLength();
/**
- * <p>
* If there is a target object associated with this IMessage, and that target object is a file,
* then an optional line number may be set. The line number identifies the location of the
* problem identified by this message. If no line number has been set, #LINENO_UNSET will be
* returned.
- * </p>
- * @return line number of the location of the problem.
*
+ * @return line number of the location of the problem.
*/
- public int getLineNumber();
+ int getLineNumber();
/**
- * <p>
* Returns the offset of the message. If unset, value = IMessage.OFFSET_UNSET. For example, if
* the java compiler were a validator, and it reported that a variable name was unknown, offset
- * would identify the position of the first character of the unknown variable. (The position is
- * identified by the number of characters from the start of the file.)
- * </p>
+ * would identify the position of the first character of the unknown variable. The position is
+ * identified by the number of characters from the start of the file.
*
* @return offset of the message
*/
- public int getOffset();
+ int getOffset();
/**
- * <p>
* Returns the parameters of the message. Message parameters are the values which are
- * substituted into parameter slots in localized message text ddscriptions.
- * </p>
+ * substituted into parameter slots in localized message text descriptions.
*
* @return parameters of the message
*/
- public java.lang.String[] getParams();
+ String[] getParams();
/**
* <p>
@@ -151,24 +162,22 @@
*
* @return the severity level of the message
*/
- public int getSeverity();
+ int getSeverity();
/**
- * <p>
* Return the object that this IMessage is reporting the problem against, if any. null will be
* returned if this is a general message which does not apply to a particular object; for
* example, "internal error".
- * </p>
*
* @return the target object for the message
*/
- public Object getTargetObject();
+ Object getTargetObject();
/**
* @return a text representation of this message formatted in the default Locale, with the
* bundle loaded by the default ClassLoader.
*/
- public java.lang.String getText();
+ String getText();
/**
* @param classLoader
@@ -177,7 +186,7 @@
* @return a text representation of this message formatted in the default locale, with the
* bundle loaded by the specified ClassLoader.
*/
- public java.lang.String getText(ClassLoader classLoader);
+ String getText(ClassLoader classLoader);
/**
* @param locale
@@ -186,7 +195,7 @@
* @return a text representation of this message formatted in the specified locale, with the
* bundle loaded by the default ClassLoader.
*/
- public java.lang.String getText(Locale locale);
+ String getText(Locale locale);
/**
* @param locale
@@ -197,21 +206,22 @@
* @return a text representation of this message formatted in the specified locale, with the
* bundle loaded by the specified ClassLoader.
*/
- public java.lang.String getText(Locale locale, ClassLoader classLoader);
+ String getText(Locale locale, ClassLoader classLoader);
/**
* Provides a way to store some additional attributes that a message would like to store
- * that can used by some other parties that are interested in those attribute values. Basically
- * a convienince to pass object values around that can consumed by other Objects it they need it
+ * that can used by some other parties that are interested in those attribute values.
+ *
* @param attributeName
* @return an Object basically the value associated with the object name.
*/
- public Object getAttribute(String attributeName);
+ Object getAttribute(String attributeName);
/**
- * Set the attributeName and value as key value pair
- * @see getAttribute(String attributeName).
+ * Set the attributeName and value as key value pair.
+ *
+ * @see #getAttribute(String attributeName)
* @param attributeName
*/
@@ -224,85 +234,77 @@
* @param bundleName
* Name of the bundle which contains the message.
*/
- public void setBundleName(String bundleName);
+ void setBundleName(String bundleName);
/**
- * <p>
* To support removal of a subset of validation messages, an IValidator may assign group names
* to IMessages. An IMessage subset will be identified by the name of its group. Default (null)
* means no group.
- * </p>
*
* @param name
* Name of the group.
*/
- public void setGroupName(String name);
+ void setGroupName(String name);
/**
- * <p>
* Set the id of the message. Message ids are used as the constants in property bundles which
* localize the description of the message in a locale-independent fashion. The id is the key,
* in the resource bundle, which identifies the string to be loaded. The id may not be null or
* the empty string.
- * </p>
*
* @param newId
* Id of the message.
*/
- public void setId(java.lang.String newId);
+ void setId(String newId);
/**
- * <p>
* Sets the length of the problem, starting from the offset. If unset, value =
* IMessage.OFFSET_UNSET.
*
* @see #setOffset(int)
- * </p>
*
* @param length
- * sets the length
+ * Sets the length.
*/
- public void setLength(int length);
+ void setLength(int length);
/**
- * <p>
* If there is a target object associated with this IMessage, and that target object is a file,
* then an optional line number may be set. The line number identifies the location of the
* problem identified by this message. To indicate no line number, use #LINENO_UNSET.
- * </p>
+ *
* @param lineNumber
- * sets the line no.
+ * Sets the line number.
*/
- public void setLineNo(int lineNumber);
+ void setLineNo(int lineNumber);
/**
- * <p>
* Sets the offset of the message. If unset, value = IMessage.OFFSET_UNSET. For example, if the
* java compiler were a validator, and it reported that a variable name was unknown, offset
- * would identify the position of the first character of the unknown variable. (The position is
- * identified by the number of characters from the start of the file.)
- * </p>
+ * would identify the position of the first character of the unknown variable. The position is
+ * identified by the number of characters from the start of the file.
+ *
* @param offset
- * sets the offset of the message.
+ * Sets the offset of the message.
*/
- public void setOffset(int offset);
+ void setOffset(int offset);
/**
- * <p>
* Sets the parameters of the message. Message parameters are the values which are substituted
* into parameter slots in localized message text descriptions.
- * </p>
* <p>
* For example, if getId() returns "MY_ID", then the ResourceBundle identified by
* getBundleName() is searched for the message named "MY_ID", and if found,
+ * has it's parameters set.
* </p>
*
* @see java.text.MessageFormat#format(String, Object[]) is invoked on the message, with
* <code>newParams</code> passed in as the Object[].
+ *
* @param newParams
- * parameters of the message.
+ * Parameters of the message.
*/
- public void setParams(java.lang.String[] newParams);
+ void setParams(String[] newParams);
/**
* Sets the severity level of the message. One of SeverityEnum constants.
@@ -312,36 +314,33 @@
* @see IMessage#LOW_SEVERITY
*
* @param newSeverity
- * severity level of the message
+ * Severity level of the message.
*/
- public void setSeverity(int newSeverity);
+ void setSeverity(int newSeverity);
/**
- * <p>
* Associate this IMessage with the object that has the problem. A null value is permitted. If a
* message is applicable to one object, then this value should be set. Otherwise, the default
* value (null) should be kept. Given this target object, it should be possible to calculate the
* exact location of the problem.
- * </p>
*
* @param obj
* The object that has the problem.
*/
- public void setTargetObject(Object obj);
+ void setTargetObject(Object obj);
/**
- * return all the attributes of a Message object
- * @return
+ * Return all the attributes of a Message object.
*/
- public HashMap getAttributes();
+ HashMap getAttributes();
/**
- * return the marker id if one is set on this object when created
+ * Return the marker id if one is set on this object when created.
*/
- public String getMarkerId();
+ String getMarkerId();
/**
- * set the marker id on a Message object
+ * Set the marker id on a Message object.
*/
- public void setMarkerId(String markerId);
-}
\ No newline at end of file
+ void setMarkerId(String markerId);
+}
diff --git a/plugins/org.eclipse.wst.validation/validate_core/org/eclipse/wst/validation/internal/provisional/core/IMetaModelContext.java b/plugins/org.eclipse.wst.validation/validate_core/org/eclipse/wst/validation/internal/provisional/core/IMetaModelContext.java
index 37a9cfe..1ffef39 100644
--- a/plugins/org.eclipse.wst.validation/validate_core/org/eclipse/wst/validation/internal/provisional/core/IMetaModelContext.java
+++ b/plugins/org.eclipse.wst.validation/validate_core/org/eclipse/wst/validation/internal/provisional/core/IMetaModelContext.java
@@ -10,6 +10,14 @@
*******************************************************************************/
package org.eclipse.wst.validation.internal.provisional.core;
+/**
+ * <p>
+ * <b>Provisional API:</b> This class/interface is part of an interim API that is still under development and expected to
+ * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
+ * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
+ * (repeatedly) as the API evolves.
+ * </p>
+ */
public interface IMetaModelContext extends IValidationContext {
public Object getModel(String URI);
diff --git a/plugins/org.eclipse.wst.validation/validate_core/org/eclipse/wst/validation/internal/provisional/core/IProjectValidationContext.java b/plugins/org.eclipse.wst.validation/validate_core/org/eclipse/wst/validation/internal/provisional/core/IProjectValidationContext.java
index 95533db..4210353 100644
--- a/plugins/org.eclipse.wst.validation/validate_core/org/eclipse/wst/validation/internal/provisional/core/IProjectValidationContext.java
+++ b/plugins/org.eclipse.wst.validation/validate_core/org/eclipse/wst/validation/internal/provisional/core/IProjectValidationContext.java
@@ -17,11 +17,10 @@
* IProjectValidationContext extends IValidationContext to provide access to a
* reference to the project on which a validator is being invoked.
* <p>
- * <b>Note:</b> This class/interface is part of an interim API that is still
- * under development and expected to change significantly before reaching
- * stability. It is being made available at this early stage to solicit feedback
- * from pioneering adopters on the understanding that any code that uses this
- * API will almost certainly be broken (repeatedly) as the API evolves.
+ * <b>Provisional API:</b> This class/interface is part of an interim API that is still under development and expected to
+ * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
+ * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
+ * (repeatedly) as the API evolves.
* </p>
*/
public interface IProjectValidationContext extends IValidationContext
diff --git a/plugins/org.eclipse.wst.validation/validate_core/org/eclipse/wst/validation/internal/provisional/core/IReporter.java b/plugins/org.eclipse.wst.validation/validate_core/org/eclipse/wst/validation/internal/provisional/core/IReporter.java
index a2cd946..3005139 100644
--- a/plugins/org.eclipse.wst.validation/validate_core/org/eclipse/wst/validation/internal/provisional/core/IReporter.java
+++ b/plugins/org.eclipse.wst.validation/validate_core/org/eclipse/wst/validation/internal/provisional/core/IReporter.java
@@ -1,10 +1,10 @@
/*******************************************************************************
- * Copyright (c) 2001, 2004 IBM Corporation and others.
+ * Copyright (c) 2001, 2008 IBM Corporation 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:
* IBM Corporation - initial API and implementation
*******************************************************************************/
@@ -12,9 +12,6 @@
import java.util.List;
-
-
-
/*
* CCM - Reporter is now passed locale-independent messages.
* Messages should only be translated to a locale upon access.
@@ -25,17 +22,24 @@
* The interface used by IValidator's to report messages. The implementation of the IReporter could
* simply log the messages to stdout, a file, or retain them in a buffer for later access by a user
* interface.
- *
- * Reporter implementations should keep non-localized versions of their messages
- *
+ * <p>
+ * Reporter implementations should keep non-localized versions of their messages.
+ * </p>
+ * <p>
* Any messages which need to be displayed to the user are done through this class, and if the user
* cancels the current function, this class is the one which registers the cancellation.
- *
+ * </p>
+ * <p>
* The IReporter instance is created at the time validation begins and ends when validation is complete.
* There is only one IReporter instance created for all validators that are run on a IResource. The IResource
* provides a way to get messages put out each validator and add and delete messages for one validator
* at a time.
- * ]
+ * <p>
+ * <b>Provisional API:</b> This class/interface is part of an interim API that is still under development and expected to
+ * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
+ * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
+ * (repeatedly) as the API evolves.
+ * </p>
*/
public interface IReporter {
/**
@@ -55,110 +59,104 @@
* @param origin
* The validator which is the source of the message.
* @param message
- * A message to be reported
- * @exception MessageLimitException
- * is thrown when the total number of messages reported exceeds the maximum
- * allowed.
- * [issue: LM - This exception seems questionable to me. Why do validators need to know how
- * to handle a MessageLimitException? Seems to me that this is a validation framework
- * specific issue and that client validators shouldn't know about this at all. ]
+ * A message to be reported.
*/
- public abstract void addMessage(IValidator origin, IMessage message);
+ void addMessage(IValidator origin, IMessage message);
/**
+ * Show a text representation of this message, formatted in the default
+ * Locale, to the user immediately. This message indicates which subtask is
+ * currently being processed. The message is not stored. The subtask message
+ * in this context is the subtask in a IProgressMontior
* <p>
- * Show a text representation of this message, formatted in the default Locale, to the user
- * immediately. This message indicates which subtask is currently being processed. The message
- * is not stored. The subtask message in this context is the subtask in a IProgressMontior
- *
- * @see subTask(String name) in IProgressMonitor
- * </p>
- * <p>
- * Both parameters must not be null.
+ * Both parameters must not be null.
* </p>
*
- * @param IValidator
- * validator The validator issuing the subtask message.
- * @param IMessage
- * message The message to be displayed to the user.
- *
+ * @param validator
+ * The validator issuing the subtask message.
+ * @param message
+ * The message to be displayed to the user.
+ *
*/
- public abstract void displaySubtask(IValidator validator, IMessage message);
+ void displaySubtask(IValidator validator, IMessage message);
/**
* @return the message access interface to this reporter, or null if message access is not
* supported.
*
*/
- public List getMessages();
+ List getMessages();
/**
- * <p>
- * Return true if the user cancelled validation, and false otherwise. This method should be
+ * Return true if the user canceled validation, and false otherwise. This method should be
* called by IValidators periodically, because no event is fired to notify IValidators that the
- * user cancelled validation. If a validator does not check this method, a cancellation request
+ * user canceled validation. If a validator does not check this method, a cancellation request
* is ignored.
- * </p>
*
- * @return true if the user cancelled validation, and false otherwise.
+ * @return true if the user canceled validation, and false otherwise.
*
*/
- public abstract boolean isCancelled();
+ boolean isCancelled();
/**
- * <p>
* Remove all validation messages entered by the identified validator. This method is provided
* for incremental validation.
- * </p>
* <p>
* The IValidator parameter must not be null.
* </p>
* @param origin
- * originator validator of the message.
+ * Originator validator of the message.
*/
- public abstract void removeAllMessages(IValidator origin);
+ void removeAllMessages(IValidator origin);
/**
- * Remove all validation messages, entered by the identified validator, pertaining to the Object
- * provided. This method is provided for incremental validation. <br>
+ * Remove all validation messages, entered by the identified validator,
+ * pertaining to the Object provided. This method is provided for
+ * incremental validation. <br>
* <br>
- * If <code>object</code> is null, then this method should remove all messages owned by the
- * validator. (i.e., the same behaviour as the removeAllMessages(IValidator) method.) <br>
+ * If <code>object</code> is null, then this method should remove all
+ * messages owned by the validator. (i.e., the same behaviour as the
+ * removeAllMessages(IValidator) method.) <br>
* <br>
* <p>
* The IValidator parameter must not be null.
* </p>
- * @param origin
- * originator validator of the message.
- * @param object
- * Object to which the message belongs. Object is the target object that was set on the IMessage
- * when adding the message as problem marker.
*
- */
- public abstract void removeAllMessages(IValidator origin, Object object);
+ * @param origin
+ * Originator validator of the message.
+ * @param object
+ * Object to which the message belongs. Object is the target object
+ * that was set on the IMessage when adding the message as problem
+ * marker.
+ *
+ */
+ void removeAllMessages(IValidator origin, Object object);
/**
- * To support removal of a subset of validation messages, an IValidator may assign group names
- * to IMessages. An IMessage subset will be identified by the name of its group. This method
- * will remove only the IMessage's that are in the group identified by groupName. <br>
- * <br>
- * <br>
+ * To support removal of a subset of validation messages, an IValidator may
+ * assign group names to IMessages. An IMessage subset will be identified by
+ * the name of its group. This method will remove only the IMessage's that
+ * are in the group identified by groupName.
+ * <p>
+ * The IValidator parameter must not be null.
+ * </p>
+ * <p>
+ * If <code>object</code> is null, then this method should remove all
+ * messages owned by the validator. (i.e., the same behaviour as the
+ * removeAllMessages(IValidator) method.)
+ * </p>
+ * <p>
+ * If groupName is null, that's the same as no group (i.e., the same
+ * behaviour as the <code>removeAllMessages(IValidator, Object)</code>
+ * method.)
+ * </p>
*
- * The IValidator parameter must not be null. <br>
- * <br>
- *
- * If <code>object</code> is null, then this method should remove all messages owned by the
- * validator. (i.e., the same behaviour as the removeAllMessages(IValidator) method.)
- *
- * If groupName is null, that's the same as no group (i.e., the same behaviour as the
- * <code>removeAllMessages(IValidator, Object)</code> method.) <br>
- *
- * @param origin
- * originator validator of the message.
- * @param object
- * Object to which the message belongs.
+ * @param validator
+ * Originator validator of the message.
+ * @param obj
+ * Object to which the message belongs.
* @param groupName
- * name of the group to which the message belongs.
+ * Name of the group to which the message belongs.
*/
- public void removeMessageSubset(IValidator validator, Object obj, String groupName);
-}
\ No newline at end of file
+ void removeMessageSubset(IValidator validator, Object obj, String groupName);
+}
diff --git a/plugins/org.eclipse.wst.validation/validate_core/org/eclipse/wst/validation/internal/provisional/core/IValidationContext.java b/plugins/org.eclipse.wst.validation/validate_core/org/eclipse/wst/validation/internal/provisional/core/IValidationContext.java
index 135a80f..54a8ce5 100644
--- a/plugins/org.eclipse.wst.validation/validate_core/org/eclipse/wst/validation/internal/provisional/core/IValidationContext.java
+++ b/plugins/org.eclipse.wst.validation/validate_core/org/eclipse/wst/validation/internal/provisional/core/IValidationContext.java
@@ -1,27 +1,23 @@
/*******************************************************************************
- * Copyright (c) 2001, 2004 IBM Corporation and others.
+ * Copyright (c) 2001, 2007 IBM Corporation 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:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.wst.validation.internal.provisional.core;
-
-
/**
- * <p>
* This class is used to to separate the IValidator from the model loading. A model
* is a group of object(s) that must follow some rules.
- * </p>
* <p>
* The model is loaded differently depending on whether the validator is running in
- * UI or headless context. If the <code>loadModel</code> method was a method on the IValidator,
- * then there would need to be two versions of validators, one for headless and one for
- * UI. Because <code>loadModel</code> is separate from the IValidator, we provide
+ * as-you-type or builder based context. If the <code>loadModel</code> method was a method on the IValidator,
+ * then there would need to be two versions of validators, one for as-you-type and one for
+ * builder based. Because <code>loadModel</code> is separate from the IValidator, we provide
* two different IHelpers instead, and ship the one specific to the environment.
* </p>
* <p>
@@ -32,30 +28,43 @@
* <code>loadModel</code> method. An IValidationContext can support more than one IValidator;
* the helper needs to support every model that each validator needs.
* </p>
+ * <p>
+ * <b>Provisional API:</b> This class/interface is part of an interim API that is still under development and expected to
+ * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
+ * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
+ * (repeatedly) as the API evolves.
+ * </p>
*/
public interface IValidationContext {
/**
* <p>
- * Load the model identified by <code>symbolicName</code>.<code>symbolicName</code>
+ * Load the model identified by <code>symbolicName</code>. <code>symbolicName</code>
* must not be null or the empty string if the validator needs to be run in both
- * Headless and UI.
- *
+ * as-you-type and builder based validation.
+ * </p>
+ * <p>
* The symbolicName is a string name that is registered in the implementation of the
* IValidatorContext. For an example our internal implementation of the loadModel use
* method names for symbolicNames to load the model object to be validated. Users can
* use their own model load mechanism.
- * @see <code>WorkbenchContext</code>
- *
* </p>
- * @plannedfor 1.0
+ *
+ * @see <code>WorkbenchContext</code>
*/
- public Object loadModel(String symbolicName);
+ Object loadModel(String symbolicName);
+ /*
+ *
+ * [issue : CS - It's not at all clear how these parameters would get passed into a helper. I'd suggest
+ * providing getProperty() and setProperty() methods on the class to allow contextual information to be
+ * supplied and queried in a generic manner.]
+ */
/**
* <p>
* Load the model identified by <code>symbolicName</code> and <code>parms</code>.
* <code>symbolicName</code> must not be null or the empty string if the validator
- * needs to be run in both Headless and UI. If <code>parms</code> is null then this
+ * needs to be run in both as-you-type and builder based validation.
+ * If <code>parms</code> is null then this
* method behaves the same as
*
* @link #loadModel(String).
@@ -65,20 +74,17 @@
* are available only at runtime. If you need to pass a live object to the IValidationContext,
* this is the loadModel method to use.
* </p>
- * @param symbolicName String identifier for model
- * @param parms parms list of parameters that the model takes for invocation
*
- * [issue : CS - It's not at all clear how these parameters would get passed into a helper. I'd suggest
- * providing getProperty() and setProperty() methods on the class to allow contextual information to be
- * supplied and queried in a generic manner.]
+ * @param symbolicName String identifier for model.
+ * @param parms List of parameters that the model takes for invocation.
*/
- public Object loadModel(String symbolicName, Object[] parms);
+ Object loadModel(String symbolicName, Object[] parms);
/**
* @return a string array with the list of URI's that need to be validated in the
- * case of Incremental build
+ * case of Incremental build.
*/
- public String[] getURIs();
+ String[] getURIs();
-}
\ No newline at end of file
+}
diff --git a/plugins/org.eclipse.wst.validation/validate_core/org/eclipse/wst/validation/internal/provisional/core/IValidator.java b/plugins/org.eclipse.wst.validation/validate_core/org/eclipse/wst/validation/internal/provisional/core/IValidator.java
index 366df5f..6fbd55e 100644
--- a/plugins/org.eclipse.wst.validation/validate_core/org/eclipse/wst/validation/internal/provisional/core/IValidator.java
+++ b/plugins/org.eclipse.wst.validation/validate_core/org/eclipse/wst/validation/internal/provisional/core/IValidator.java
@@ -1,10 +1,10 @@
/*******************************************************************************
- * Copyright (c) 2001, 2004 IBM Corporation and others.
+ * Copyright (c) 2001, 2007 IBM Corporation 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:
* IBM Corporation - initial API and implementation
*******************************************************************************/
@@ -15,57 +15,60 @@
/**
* This is the base interface for all Validators. A Validator is a class which verifies that objects
* follow some rules. For example, in a MOF model which represents an EJB jar, the EJB specification
- * determines the rules. <br>
- * <br>
+ * determines the rules.
+ * <p>
* A validator can perform full validation or incremental validation. All validators must implement
- * full validation but incremental validation is optional. <br>
- * <br>
- * Each validator must not be tied to any particular workbench implementation. <br>
- * <br>
+ * full validation but incremental validation is optional.
+ * </p>
+ * <p>
+ * Each validator must not be tied to any particular workbench implementation.
+ * </p>
+ * <p>
* A validator's verification starts when the ValidatorLauncher singleton calls
* <code>validate</code>.
- *
- * [issue: LM - This interface will be implemented by clients. This should be considered a candidate for
- * an abstract class. ]
+ * </p>
+ * <p>
+ * <b>Provisional API:</b> This class/interface is part of an interim API that is still under development and expected to
+ * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
+ * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
+ * (repeatedly) as the API evolves.
+ * </p>
*/
public interface IValidator{
- /**
- * <p>
- * Perform any resource cleanup once validation is complete. If cleanup will take some time, the
- * IValidator should report subtask information to the user through the IReporter parameter. The
- * IReporter parameter will not be null.
- * </p>
- * @param reporter used for the interaction with the user
- * @plannedfor WTP 1.0
- *
+
+ /*
* [issue : CS - Perhaps the IValidator should be required to provide a 'name' that can be used describe
* the running validation 'Job'. Then the framework could automatically say something like 'XYZ validator : cleanup'.
* Relying on the IValidator to provide subtask information seems error prone.]
* [issue: LM - Is the cleanup method necessary? Can the framework put a requirement that client validators 'clean up'
* before returning from the validate method? ]
*/
- public void cleanup(IReporter reporter);
-
+
/**
- * This is the method which performs the validation on the objects. <br>
- * <br>
- * <code>helper</code> and <code>reporter</code> may not be null. <code>changedFiles</code>
- * may be null, if a full build is desired. <br>
- * <br>
- * @param helper
- * loads an object.
- * @param reporter
- * Is an instance of an IReporter interface, which is used for
- * interaction with the user.
- * @param changedFiles
- * Is an array of files which have been added, changed, or deleted
- * since the last validation. If <code>changedFiles</code> is null, or if it is an empty
- * array, then a full validation should be performed. Otherwise, validation on just the files
- * listed in the array should performed if the validator supports incremental validation.
+ * Perform any resource cleanup once validation is complete. If cleanup will take some time, the
+ * IValidator should report subtask information to the user through the IReporter parameter. The
+ * IReporter parameter will not be null.
*
+ * @param reporter Used for the interaction with the user.
+ */
+ void cleanup(IReporter reporter);
+
+ /*
* [issue : CS - I'm curious to understand why the validator is not invoked directly on a file. It seems it should be the
* domain of another API to manage manage incremental file changes and triggering validations accordingly.
* Do we have a current use case in WTP where the validator does anything more validate a file from the changedFiles list?]
*/
- public void validate(IValidationContext helper, IReporter reporter) throws ValidationException;
-}
\ No newline at end of file
+ /**
+ * This is the method which performs the validation on the objects.
+ * <p>
+ * <code>helper</code> and <code>reporter</code> may not be null. <code>changedFiles</code>
+ * may be null, if a full build is desired. <br>
+ * </p>
+ * @param helper
+ * Loads an object.
+ * @param reporter
+ * Is an instance of an IReporter interface, which is used for interaction with the user.
+ *
+ */
+ void validate(IValidationContext helper, IReporter reporter) throws ValidationException;
+}
diff --git a/plugins/org.eclipse.wst.validation/validate_core/org/eclipse/wst/validation/internal/provisional/core/IValidatorJob.java b/plugins/org.eclipse.wst.validation/validate_core/org/eclipse/wst/validation/internal/provisional/core/IValidatorJob.java
index 595151b..a25e7bb 100644
--- a/plugins/org.eclipse.wst.validation/validate_core/org/eclipse/wst/validation/internal/provisional/core/IValidatorJob.java
+++ b/plugins/org.eclipse.wst.validation/validate_core/org/eclipse/wst/validation/internal/provisional/core/IValidatorJob.java
@@ -1,10 +1,10 @@
/*******************************************************************************
- * Copyright (c) 2001, 2004 IBM Corporation and others.
+ * Copyright (c) 2001, 2007 IBM Corporation 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:
* IBM Corporation - initial API and implementation
*******************************************************************************/
@@ -18,37 +18,36 @@
/**
* This is the Job interface for the validator. Validators implementing this interface are executed as
* background jobs.
- * Following is a sequence of call <br/>
- * validator.getSchedulingRule(helper) <br/>
- * validator.validate(reporter)
+ * Following is a sequence of calls:
+ * <ul>
+ * <li>validator.getSchedulingRule(helper)
+ * <li>validator.validate(reporter)
+ * </ul>
*/
-
public interface IValidatorJob extends IValidator{
- public static IStatus OK_STATUS = new Status(IStatus.OK, "org.eclipse.wst.validation", 0, "OK", null); //$NON-NLS-1$ //$NON-NLS-2$
+ IStatus OK_STATUS = new Status(IStatus.OK, "org.eclipse.wst.validation", 0, "OK", null); //$NON-NLS-1$ //$NON-NLS-2$
/**
- * This is the method which performs the validation on the objects. <br>
- * <br>
+ * This is the method which performs the validation on the objects.
+ * <p>
* <code>reporter</code> may not be null. <code>changedFiles</code>
* may be null, if a full build is desired. <br>
- * <br>
+ * </p>
*
* @param reporter
* Is an instance of an IReporter interface, which is used for interaction with the
* user.
- * @param helper will not be null,
- * loads an object.
+ * @param helper Will not be null, loads an object.
*/
- public IStatus validateInJob(IValidationContext helper, IReporter reporter) throws ValidationException;
+ IStatus validateInJob(IValidationContext helper, IReporter reporter) throws ValidationException;
/**
- * Get the scheduling rule, which the framework applies to the Validator job,
- * @param helper will not be null,
- * loads an object.
- * @return
+ * Get the scheduling rule, which the framework applies to the Validator job.
+ *
+ * @param helper Will not be null, loads an object.
*/
- public ISchedulingRule getSchedulingRule(IValidationContext helper);
-}
\ No newline at end of file
+ ISchedulingRule getSchedulingRule(IValidationContext helper);
+}
diff --git a/plugins/org.eclipse.wst.validation/validate_core/org/eclipse/wst/validation/internal/provisional/core/MessageLimitException.java b/plugins/org.eclipse.wst.validation/validate_core/org/eclipse/wst/validation/internal/provisional/core/MessageLimitException.java
index 4a9c63e..3a86bf4 100644
--- a/plugins/org.eclipse.wst.validation/validate_core/org/eclipse/wst/validation/internal/provisional/core/MessageLimitException.java
+++ b/plugins/org.eclipse.wst.validation/validate_core/org/eclipse/wst/validation/internal/provisional/core/MessageLimitException.java
@@ -1,29 +1,30 @@
/*******************************************************************************
- * Copyright (c) 2001, 2004 IBM Corporation and others.
+ * Copyright (c) 2001, 2006 IBM Corporation 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:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.wst.validation.internal.provisional.core;
-
-/**
- * This exception is thrown by
- *
- * @see IReporter#addMessage(IValidator, IMessage) method if no more messages can be reported
- * because the maximum number of messages has been reported.
+/*
* [issue: LM - Going along with my comment on the addMessage method in IReporter I
* think this class should be internal to the validation framework.
* I don't think there's a need for this class to be exposed to clients. If too many
* messages are added the framework should handle this without notifying the client
* validator. ]
+ */
+/**
+ * This exception is thrown by
+ *
+ * @see IReporter#addMessage(IValidator, IMessage) method if no more messages can be reported
+ * because the maximum number of messages has been reported.
* @deprecated This class is not longer used by the framework. The framework is
* not going to limit the number of messages displayed by a validator.
*/
public class MessageLimitException extends RuntimeException {
private final static long serialVersionUID = -7034897190745766940L;
-}
\ No newline at end of file
+}
diff --git a/plugins/org.eclipse.wst.validation/validate_core/org/eclipse/wst/validation/internal/provisional/core/package.html b/plugins/org.eclipse.wst.validation/validate_core/org/eclipse/wst/validation/internal/provisional/core/package.html
new file mode 100644
index 0000000..70bdb29
--- /dev/null
+++ b/plugins/org.eclipse.wst.validation/validate_core/org/eclipse/wst/validation/internal/provisional/core/package.html
@@ -0,0 +1,9 @@
+<html>
+<head>
+<title>Validation Framework (Version 1)</title>
+</head>
+<body>
+<p>An earlier framework for calling validators that are build based.</p>
+<p>This framework is being replaced by the <code>newer org.eclipse.wst.validation</code> framework.</p>
+</body>
+</html>
diff --git a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/AbstractValidator.java b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/AbstractValidator.java
new file mode 100644
index 0000000..83c1d55
--- /dev/null
+++ b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/AbstractValidator.java
@@ -0,0 +1,194 @@
+/*******************************************************************************
+ * Copyright (c) 2007, 2008 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.wst.validation;
+
+import org.eclipse.core.resources.IProject;
+import org.eclipse.core.resources.IResource;
+import org.eclipse.core.runtime.IProgressMonitor;
+import org.eclipse.wst.validation.Validator.V2;
+
+/**
+ * The class that all Validators that wish to use version two of the validation framework must subclass.
+ * <p>
+ * <b>Provisional API:</b> This class/interface is part of an interim API that is still under development and expected to
+ * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
+ * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
+ * (repeatedly) as the API evolves.
+ * </p>
+ * @author karasiuk
+ *
+ */
+public abstract class AbstractValidator {
+
+ private V2 _parent;
+
+ /**
+ * Validate the resource. The validator is called from a WorkspaceJob, so
+ * the validator itself does not need to establish it's own IWorkspaceRunnable.
+ * <p>
+ * If you override this method then you should not override the other validate method.
+ * </p>
+ *
+ * @param resource
+ * The resource to be validated.
+ *
+ * @param kind
+ * The way the resource changed. It uses the same values as the kind
+ * parameter in IResourceDelta.
+ *
+ * @param state
+ * A way to pass arbitrary, validator specific, data from one
+ * invocation of a validator to the next, during the validation phase.
+ * At the end of the validation phase, this object will be cleared,
+ * thereby allowing any of this state information to be garbaged
+ * collected.
+ *
+ * @param monitor
+ * A monitor that you can use to report your progress. To be a well
+ * behaved validator you need to check the isCancelled() method at
+ * appropriate times.
+ *
+ * @return the result of the validation. This may be, but usually isn't, null.
+ */
+ public ValidationResult validate(IResource resource, int kind, ValidationState state, IProgressMonitor monitor){
+ return null;
+ }
+
+ /**
+ * Validate the resource. The validator is called from a WorkspaceJob, so
+ * the validator itself does not need to establish it's own
+ * IWorkspaceRunnable.
+ * <p>
+ * If you override this method then you should not override the other
+ * validate method.
+ * </p>
+ *
+ * @param event
+ * An object that describes the resource to be validated and why
+ * it should be validated.
+ *
+ * @param state
+ * A way to pass arbitrary, validator specific, data from one
+ * invocation of a validator to the next, during the validation
+ * phase. At the end of the validation phase, this object will be
+ * cleared, thereby allowing any of this state information to be
+ * garbaged collected.
+ *
+ * @param monitor
+ * A monitor that you can use to report your progress. To be a
+ * well behaved validator you need to check the isCancelled()
+ * method at appropriate times.
+ *
+ * @return the result of the validation. Null should never be returned. If
+ * null is returned then the other validate method will be called as
+ * well.
+ */
+ public ValidationResult validate(ValidationEvent event, ValidationState state, IProgressMonitor monitor){
+ return null;
+ }
+
+
+ /**
+ * A call back method that lets the validator know that the project is being
+ * cleaned. This method gives the validator a chance to do any special
+ * cleanup. The default is to do nothing.
+ * <p>
+ * If the entire workspace is being cleaned, then the first call will have a
+ * null project, and then there will be subsequent calls for each open
+ * project in the workspace.</p>
+ *
+ * @param project
+ * The project being cleaned. This may be null, which is an indication
+ * that the workspace is being cleaned.
+ *
+ * @param state
+ * A way to pass arbitrary, validator specific, data from one
+ * invocation of a validator to the next, during the validation phase.
+ *
+ * @param monitor
+ * The monitor that should be used for reporting progress if the clean
+ * takes a long time.
+ */
+ public void clean(IProject project, ValidationState state, IProgressMonitor monitor){
+ }
+
+ /**
+ * This method is called before any validation takes place. It allows
+ * validators to perform any initialization that they might need.
+ *
+ * @param project
+ * The project that is being validated. For the very first call in the
+ * validation phase, this will be null. A null project is the signal
+ * that a top level validation is starting. Subsequently, the project
+ * will be set, as each of the individual projects are validated.
+ *
+ * @param state
+ * A way to pass arbitrary, validator specific, data from one
+ * invocation of a validator to the next, during the validation phase.
+ *
+ * @param monitor
+ * The monitor that should be used for reporting progress if the initialization
+ * takes a long time.
+ */
+ public void validationStarting(IProject project, ValidationState state, IProgressMonitor monitor){
+ }
+
+ /**
+ * This method will be called when validation is complete. It allows
+ * validators to perform any cleanup that they might need to do.
+ *
+ * @param project
+ * The project that was validated. The very last call in the validation
+ * sets this to null so that the validator knows that all the
+ * projects have now been validated.
+ *
+ * @param state
+ * A way to pass arbitrary, validator specific, data from one
+ * invocation of a validator to the next, during the validation phase.
+ *
+ * @param monitor
+ * The monitor that should be used for reporting progress if the cleanup
+ * takes a long time.
+ */
+ public void validationFinishing(IProject project, ValidationState state, IProgressMonitor monitor){
+ }
+
+ /**
+ * Should the validation framework first clear the markers that this
+ * validator has placed on this resource? This method can be overridden by
+ * validator implementors to provide a validator specific behavior.
+ *
+ * @param event
+ * The validation event that triggered the validation.
+ * @return true if the validation framework should first clear all the
+ * markers that this validator produced. This is the default
+ * behavior. Return false to leave the markers unchanged. It then
+ * becomes the responsibility of the validator to manage it's own
+ * markers for this resource, for this validation event.
+ */
+ public boolean shouldClearMarkers(ValidationEvent event){
+ return true;
+ }
+
+ /**
+ * Answer the validator that you belong to. The validator controls the
+ * filters and various other settings.
+ *
+ * @nooverride
+ */
+ public V2 getParent(){
+ return _parent;
+ }
+
+ void setParent(V2 parent){
+ _parent = parent;
+ }
+}
diff --git a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/DependentResource.java b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/DependentResource.java
new file mode 100644
index 0000000..3f1c67d
--- /dev/null
+++ b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/DependentResource.java
@@ -0,0 +1,55 @@
+/*******************************************************************************
+ * Copyright (c) 2007 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.wst.validation;
+
+import org.eclipse.core.resources.IResource;
+
+/**
+ * A resource that is dependent on another resource.
+ * <p>
+ * This is returned by the IDependencyIndex.
+ * <p>
+ * <b>Provisional API:</b> This class/interface is part of an interim API that is still under development and expected to
+ * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
+ * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
+ * (repeatedly) as the API evolves.
+ * </p>
+ * @noextend
+ * @see IDependencyIndex
+ * @author karasiuk
+ *
+ */
+public class DependentResource {
+ private IResource _resource;
+ private Validator _validator;
+
+ /**
+ * @noreference
+ */
+ public DependentResource(IResource resource, Validator validator){
+ _resource = resource;
+ _validator = validator;
+ }
+
+ /**
+ * Answer the resource that is depended on.
+ */
+ public IResource getResource() {
+ return _resource;
+ }
+
+ /**
+ * Answer the validator that asserted the dependency.
+ */
+ public Validator getValidator() {
+ return _validator;
+ }
+}
diff --git a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/Friend.java b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/Friend.java
new file mode 100644
index 0000000..4146636
--- /dev/null
+++ b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/Friend.java
@@ -0,0 +1,57 @@
+/*******************************************************************************
+ * Copyright (c) 2007, 2008 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.wst.validation;
+
+import java.util.Map;
+
+import org.eclipse.core.resources.IResource;
+import org.eclipse.wst.validation.internal.ContentTypeWrapper;
+import org.eclipse.wst.validation.internal.ValType;
+
+/**
+ * This class is only to be called by the validation framework and it's test cases.
+ * This class is NOT part of the API.
+ * <p>
+ * This class provides access to some internal methods.
+ * </p>
+ * @author karasiuk
+ *
+ */
+public class Friend {
+
+ public static void setMessages(Validator validator, Map<String, MessageSeveritySetting> map) {
+ validator.setMessages(map);
+ }
+
+ /**
+ * Has the validator's implementation been loaded yet? This is used by some test cases to ensure that
+ * plug-ins are not loaded too early.
+ */
+ public static boolean isLoaded(Validator validator){
+ return validator.isLoaded();
+ }
+
+ public static boolean shouldValidate(Validator validator, IResource resource, boolean isManual, boolean isBuild,
+ ContentTypeWrapper contentTypeWrapper){
+ return validator.shouldValidate(resource, isManual, isBuild, contentTypeWrapper);
+ }
+
+ public static boolean shouldValidate(Validator validator, IResource resource, ValType valType,
+ ContentTypeWrapper contentTypeWrapper){
+
+ return validator.shouldValidate(resource, valType, contentTypeWrapper);
+ }
+
+ public static void setMigrated(Validator validator, boolean migrated){
+ validator.setMigrated(migrated);
+ }
+
+}
diff --git a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/IDependencyIndex.java b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/IDependencyIndex.java
new file mode 100644
index 0000000..d9d494b
--- /dev/null
+++ b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/IDependencyIndex.java
@@ -0,0 +1,112 @@
+/*******************************************************************************
+ * Copyright (c) 2007, 2008 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.wst.validation;
+
+import java.util.List;
+
+import org.eclipse.core.resources.IProject;
+import org.eclipse.core.resources.IResource;
+
+/**
+ * This service is used to specify the resources that a particular resource depends on.
+ * <p>
+ * This is an optional service, validators do not need to use this Interface and can simply supply
+ * their dependency information through the ValidationResult return result.
+ * </p>
+ * <p>
+ * <b>Provisional API:</b> This class/interface is part of an interim API that is still under development and expected to
+ * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
+ * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
+ * (repeatedly) as the API evolves.
+ * </p>
+ * @noimplement
+ * @see ValidationResult
+ * @author karasiuk
+ *
+ */
+public interface IDependencyIndex {
+
+ /**
+ * Assert that one resource depends on another resource as part of it's validity.
+ * <p>
+ * For example, if an XML file is dependent on an XSD file to be valid, the
+ * resource that holds the XML file would be the dependent, and the resource
+ * that holds the XSD would be the dependsOn.
+ * </p>
+ *
+ * @param id
+ * The validator id that is asserting that the dependency exists.
+ * @param dependent
+ * The resource that is dependent on the other resource. For example a XML file.
+ * @param dependsOn
+ * The resource that this being depended on. For example a XSD file.
+ */
+ void add(String id, IResource dependent, IResource dependsOn);
+
+ /**
+ * Remove all the dependency assertions for this project.
+ *
+ * @param project
+ * The project that will have it's dependency assertions removed.
+ */
+ void clear(IProject project);
+
+ /**
+ * Answer all the resources that depend on this resource. For example, if
+ * this resource was a XSD, this could answer all the XML files that
+ * depended on it for their validity.
+ *
+ * @param resource
+ * A resource that other resources may depend on.
+ *
+ * @return the dependent resources.
+ */
+ List<DependentResource> get(IResource resource);
+
+ /**
+ * Answer all the resources that depend on this resource. For example, if
+ * this resource was a XSD, this could answer all the XML files that
+ * depended on it for their validity.
+ *
+ * @param id
+ * The validator id that asserted that the dependency exists.
+ * @param resource
+ * A resource that other resources may depend on.
+ *
+ * @return the dependent resources. This method can return null or an empty array, if
+ * there are no dependent resources.
+ */
+ IResource[] get(String id, IResource resource);
+
+ /**
+ * Answer true if other resources depend on this resource.
+ *
+ * @param resource
+ * The resource being tested.
+ *
+ * @return true if any of the validators asserted a dependency on this resource.
+ */
+ boolean isDependedOn(IResource resource);
+
+ /**
+ * Replace all the resources that the dependent depends on.
+ *
+ * @param id
+ * The validator id that is asserting that the dependency exists.
+ * @param dependent
+ * The resource that is dependent on the other resource.
+ * @param dependsOn
+ * All the resources that are depended on. This can be null or a zero
+ * length array. Null or a zero length array removes all the dependencies.
+ */
+ void set(String id, IResource dependent, IResource[] dependsOn);
+
+}
diff --git a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/IMutableValidator.java b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/IMutableValidator.java
new file mode 100644
index 0000000..90ebfb1
--- /dev/null
+++ b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/IMutableValidator.java
@@ -0,0 +1,75 @@
+/*******************************************************************************
+ * Copyright (c) 2009 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.wst.validation;
+
+/**
+ * A validator that has fields that can be updated.
+ * <p>
+ * The following procedure is used to change a Validator's settings.
+ * <ol>
+ * <li>An IMutableValidator is retrieved.</li>
+ * <li>The IMutableValidator is changed.</li>
+ * <li>The IMutableValidator is "activated".</li>
+ * </ol>
+ * </p>
+ * <p>The methods {@link ValidationFramework#getProjectSettings(org.eclipse.core.resources.IProject)} and
+ * {@link ValidationFramework#getWorkspaceSettings()} can be used to retrieve IMutableValidator's.
+ * <p>
+ * <b>Provisional API:</b> This class/interface is part of an interim API that is still under development and expected to
+ * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
+ * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
+ * (repeatedly) as the API evolves.
+ * </p>
+ * @noextend This interface is not intended to be extended by clients.
+ * @noimplement This interface is not intended to be implemented by clients.
+
+ * @author karasiuk
+ *
+ */
+public interface IMutableValidator {
+
+ /**
+ * Answer the validator's id.
+ */
+ String getId();
+
+ /**
+ * Answer the validator's name.
+ */
+ String getName();
+
+ /**
+ * Answer the validator's class name.
+ * @return
+ */
+ String getValidatorClassname();
+
+ /**
+ * Answer if the validator is enabled for build based validation.
+ */
+ boolean isBuildValidation();
+
+ /**
+ * Answer if the validator is enabled for manual based validation.
+ */
+ boolean isManualValidation();
+
+ /**
+ * Set whether the validator should be enabled for build based validation.
+ */
+ void setBuildValidation(boolean build);
+
+ /**
+ * Set whether the validator should be enabled for manual based validation.
+ */
+ void setManualValidation(boolean manual);
+
+}
diff --git a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/IPerformanceMonitor.java b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/IPerformanceMonitor.java
new file mode 100644
index 0000000..b951270
--- /dev/null
+++ b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/IPerformanceMonitor.java
@@ -0,0 +1,79 @@
+/*******************************************************************************
+ * Copyright (c) 2007, 2008 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.wst.validation;
+
+import java.util.List;
+
+/**
+ * A service that collects performance information on validation operations.
+ * <p>
+ * <b>Provisional API:</b> This class/interface is part of an interim API that is still under development and expected to
+ * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
+ * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
+ * (repeatedly) as the API evolves.
+ * </p>
+ * @noextend This interface is not intended to be extended by clients.
+ * @noimplement This interface is not intended to be implemented by clients.
+ * @author karasiuk
+ *
+ */
+public interface IPerformanceMonitor {
+
+ /**
+ * The level of information to collect.
+ */
+ public enum CollectionLevel {None, Default}
+
+ /**
+ * Add this performance counter to the monitor. The monitor will decide what to
+ * do with the results, it may log them to a file, or it may simply hold on to them.
+ *
+ * @param counters
+ */
+ public void add(PerformanceCounters counters);
+
+ /**
+ * Answer true if the performance monitor is collecting performance events.
+ */
+ public boolean isCollecting();
+
+ /** Answer true if only summary information is requested. */
+ public boolean isSummaryOnly();
+
+ /**
+ * Set the performance event collection level. This controls which
+ * performance events are collected, including none of them.
+ *
+ * @param level
+ * The level to collect. The default is to not collect anything.
+ */
+ public void setCollectionLevel(CollectionLevel level);
+
+ /**
+ * Answer the level of performance events that are being collected by the validation framework.
+ */
+ public CollectionLevel getCollectionLevel();
+
+ /**
+ * Answer the performance counters that have been collected so far. Some
+ * monitors do not save counters, and they will always return an empty list.
+ *
+ * @param asSummary
+ * If this parameter is true, only answer a summary of the counters.
+ */
+ public List<PerformanceCounters> getPerformanceCounters(boolean asSummary);
+
+ /**
+ * Delete the collected performance counters.
+ */
+ public void resetPerformanceCounters();
+
+}
diff --git a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/IValidatorGroupListener.java b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/IValidatorGroupListener.java
new file mode 100644
index 0000000..5f4feee
--- /dev/null
+++ b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/IValidatorGroupListener.java
@@ -0,0 +1,64 @@
+/*******************************************************************************
+ * Copyright (c) 2008 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.wst.validation;
+
+import org.eclipse.core.resources.IResource;
+import org.eclipse.core.runtime.IProgressMonitor;
+
+/**
+ * Validators may wish to join validator groups for performance or other
+ * reasons. That way expensive operations like creating and releasing models can
+ * be done in a common location, and be done only once per resource. Group listeners
+ * are declared via the <code>org.eclipse.wst.validation.validatorGroup</code> extension point.
+ * <p>
+ * As validation proceeds, the validation framework, on a resource by resource
+ * bases, determines if any validators that are members of a group are
+ * interested in the resource. If they are, before the first validator in the
+ * group is called, the <code>validationStarting</code> method is called. If this method was
+ * called, then the <code>validationFinishing</code> method will be called once all the
+ * validators have processed the resource.
+ * </p>
+ * <p>
+ * <b>Provisional API:</b> This class/interface is part of an interim API that is still under development and expected to
+ * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
+ * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
+ * (repeatedly) as the API evolves.
+ * </p>
+ */
+public interface IValidatorGroupListener {
+ /**
+ * This is called before the first validator in the group that is interested
+ * in the resource is called. If no validators in the group are interested
+ * in the resource, then this method is not called.
+ *
+ * @param resource
+ * The resource that is being validated.
+ * @param monitor
+ * A progress monitor that the method should use.
+ * @param state
+ * The validation state for the current operation.
+ */
+ void validationStarting(IResource resource, IProgressMonitor monitor, ValidationState state);
+
+ /**
+ * If the validationStarting method was called on the resource, then this
+ * method will be called after the last validator has processed the
+ * resource.
+ *
+ * @param resource
+ * The resource that is being validated.
+ * @param monitor
+ * A progress monitor that the method can use.
+ * @param state
+ * The validation state for the current operation.
+ */
+ void validationFinishing(IResource resource, IProgressMonitor monitor, ValidationState state);
+}
diff --git a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/MessageSeveritySetting.java b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/MessageSeveritySetting.java
new file mode 100644
index 0000000..4eaa3b7
--- /dev/null
+++ b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/MessageSeveritySetting.java
@@ -0,0 +1,140 @@
+/*******************************************************************************
+ * Copyright (c) 2008 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.wst.validation;
+
+import org.eclipse.core.resources.IMarker;
+import org.eclipse.wst.validation.internal.ValMessages;
+
+/**
+ * Associate a message severity with a message category.
+ * <p>
+ * <b>Provisional API:</b> This class/interface is part of an interim API that is still under development and expected to
+ * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
+ * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
+ * (repeatedly) as the API evolves.
+ * </p>
+ * @noextend
+ * @author karasiuk
+ *
+ */
+public class MessageSeveritySetting {
+ public enum Severity {
+ Error(ValMessages.SevError, IMarker.SEVERITY_ERROR),
+ Warning(ValMessages.SevWarning, IMarker.SEVERITY_WARNING),
+ Ignore(ValMessages.SevIgnore, IMarker.SEVERITY_INFO);
+
+ private String _severityLabel;
+ private Severity(String label, int markerSeverity){
+ _severityLabel = label;
+ _markerSeverity = markerSeverity;
+ }
+ private int _markerSeverity;
+
+ @Override
+ public String toString() {
+ return _severityLabel;
+ }
+
+ /**
+ * Answer the associated IMarker severity.
+ */
+ public int getMarkerSeverity() {
+ return _markerSeverity;
+ }
+
+ }
+
+ private String _id;
+ private String _label;
+ private Severity _default;
+ private Severity _current;
+
+ /**
+ * Create an association between a label and a message severity.
+ *
+ * @param id
+ * An id that is used to identify this particular setting. This must be
+ * unique within the scope of this particular validator.
+ *
+ * @param label
+ * An end user string, that can describe either an individual message
+ * or a message category.
+ *
+ * @param defaultSeverity
+ * The default severity for this label. If the end user doesn't change
+ * anything this is what the severity will be.
+ */
+ public MessageSeveritySetting(String id, String label, Severity defaultSeverity){
+ _id = id;
+ _label = label;
+ _default = defaultSeverity;
+ }
+
+ @Override
+ public int hashCode() {
+ int h = 0;
+ if (_current != null)h += _current.getMarkerSeverity()*1000;
+ if (_id != null)h += _id.hashCode();
+ return h;
+ }
+
+ public String getLabel() {
+ return _label;
+ }
+
+ /** Answer the default severity as defined by the validator owner. */
+ public Severity getDefault() {
+ return _default;
+ }
+
+ /**
+ * Answer the current severity for the message. The end user may have changed this through a
+ * preference dialog.
+ */
+ public Severity getCurrent() {
+ if (_current != null)return _current;
+ return _default;
+ }
+
+ /**
+ * The id that the validator owner assigned to the message.
+ */
+ public String getId() {
+ return _id;
+ }
+
+ /**
+ * Set the current message severity.
+ *
+ * @param severity
+ * @return true if the setting changed
+ */
+ public boolean setCurrent(Severity severity) {
+ if (_current == severity)return false;
+ _current = severity;
+ return true;
+ }
+
+ @Override
+ public String toString() {
+ return _id + " " + getCurrent().toString(); //$NON-NLS-1$
+ }
+
+ /**
+ * Answer a copy of this object.
+ */
+ public MessageSeveritySetting copy() {
+ MessageSeveritySetting ms = new MessageSeveritySetting(_id, _label, _default);
+ ms._current = _current;
+ return ms;
+ }
+
+}
diff --git a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/MutableProjectSettings.java b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/MutableProjectSettings.java
new file mode 100644
index 0000000..73bf21c
--- /dev/null
+++ b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/MutableProjectSettings.java
@@ -0,0 +1,96 @@
+/*******************************************************************************
+ * Copyright (c) 2009 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.wst.validation;
+
+import org.eclipse.core.resources.IProject;
+
+/**
+ * This class holds the overall project validation settings.
+ * <p>
+ * The following procedure is used to change a project's Validation settings.
+ * <ol>
+ * <li>The MutableProjectSettings are retrieved.</li>
+ * <li>The MutableProjectSettings are changed.</li>
+ * <li>The MutableProjectSettings are "applied".</li>
+ * </ol>
+ * </p>
+ * <p>In order for a project's validation setting to be effective, both
+ * {@link #getOverride()} and {@link MutableWorkspaceSettings#getOverride()}
+ * must be true.
+ * </p>
+ * <p>
+ * These settings can be retrieved with {@link ValidationFramework#getProjectSettings(IProject)}.
+ * </p>
+ * <p>
+ * <b>Provisional API:</b> This class/interface is part of an interim API that is still under development and expected to
+ * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
+ * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
+ * (repeatedly) as the API evolves.
+ * </p>
+
+ * @author karasiuk
+ *
+ */
+public final class MutableProjectSettings {
+ private final IProject _project;
+
+ private boolean _override;
+ private boolean _suspend;
+ private final IMutableValidator[] _validators;
+
+ public IMutableValidator[] getValidators() {
+ return _validators;
+ }
+
+ public MutableProjectSettings(IProject project, IMutableValidator[] validators){
+ _project = project;
+ _validators = validators;
+ }
+
+ /**
+ * Can this project override the workspace level validation settings?
+ */
+ public boolean getOverride() {
+ return _override;
+ }
+
+ /**
+ * Change whether this project can override workspace level validation settings.
+ * @param override Set to true if the project is allowed to override workspace level validation settings.
+ */
+ public void setOverride(boolean override) {
+ _override = override;
+ }
+
+ /**
+ * Is validation suspended for this project?
+ */
+ public boolean getSuspend() {
+ return _suspend;
+ }
+
+ /**
+ * Change whether this project is suspending it's validation.
+ * @param suspend Set to true, to suspend validation for this project.
+ */
+ public void setSuspend(boolean suspend) {
+ _suspend = suspend;
+ }
+
+ /**
+ * Answer the project that these settings are for.
+ */
+ public IProject getProject() {
+ return _project;
+ }
+
+
+}
diff --git a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/MutableWorkspaceSettings.java b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/MutableWorkspaceSettings.java
new file mode 100644
index 0000000..80d18f1
--- /dev/null
+++ b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/MutableWorkspaceSettings.java
@@ -0,0 +1,96 @@
+/*******************************************************************************
+ * Copyright (c) 2009 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.wst.validation;
+
+import org.eclipse.wst.validation.internal.model.GlobalPreferencesValues;
+
+
+/**
+ * This class holds the overall workspace validation settings.
+ * <p>
+ * The following procedure is used to change a project's Validation settings.
+ * <ol>
+ * <li>The MutableWorkspaceSettings are retrieved.</li>
+ * <li>The MutableWorkspaceSettings are changed.</li>
+ * <li>The MutableWorkspaceSettings are "applied".</li>
+ * </ol>
+ * </p>
+ * <p>
+ * These settings can be retrieved with {@link ValidationFramework#getWorkspaceSettings()}.
+ * </p>
+ * <p>
+ * <b>Provisional API:</b> This class/interface is part of an interim API that is still under development and expected to
+ * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
+ * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
+ * (repeatedly) as the API evolves.
+ * </p>
+
+ * @author karasiuk
+ *
+ */
+public final class MutableWorkspaceSettings {
+
+ private final GlobalPreferencesValues _values;
+
+ private final IMutableValidator[] _validators;
+
+ public IMutableValidator[] getValidators() {
+ return _validators;
+ }
+
+ public MutableWorkspaceSettings(IMutableValidator[] validators, GlobalPreferencesValues values){
+ _validators = validators;
+ _values = values;
+ }
+
+ public GlobalPreferencesValues getGlobalPreferencesValues(){
+ return _values;
+ }
+
+ public boolean getAutoSave() {
+ return _values.saveAutomatically;
+ }
+
+ public void setAutoSave(boolean autoSave) {
+ _values.saveAutomatically = autoSave;
+ }
+
+ /**
+ * Can this project override the workspace level validation settings?
+ */
+ public boolean getOverride() {
+ return _values.override;
+ }
+
+ /**
+ * Change whether this project can override workspace level validation settings.
+ * @param override Set to true if the project is allowed to override workspace level validation settings.
+ */
+ public void setOverride(boolean override) {
+ _values.override = override;
+ }
+
+ /**
+ * Is validation suspended for this project?
+ */
+ public boolean getSuspend() {
+ return _values.disableAllValidation;
+ }
+
+ /**
+ * Change whether this project is suspending it's validation.
+ * @param suspend Set to true, to suspend validation for this project.
+ */
+ public void setSuspend(boolean suspend) {
+ _values.disableAllValidation = suspend;
+ }
+
+}
diff --git a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/PerformanceCounters.java b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/PerformanceCounters.java
new file mode 100644
index 0000000..cf57721
--- /dev/null
+++ b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/PerformanceCounters.java
@@ -0,0 +1,116 @@
+/*******************************************************************************
+ * Copyright (c) 2007, 2008 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.wst.validation;
+
+import org.eclipse.osgi.util.NLS;
+import org.eclipse.wst.validation.internal.Misc;
+import org.eclipse.wst.validation.internal.ValMessages;
+
+/**
+ * Some performance information for a validation invocation. This object is immutable.
+ * <p>
+ * <b>Provisional API:</b> This class/interface is part of an interim API that is still under development and expected to
+ * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
+ * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
+ * (repeatedly) as the API evolves.
+ * </p>
+ * @noextend
+ * @author karasiuk
+ *
+ */
+public class PerformanceCounters {
+
+ private long _when;
+ private String _validatorId;
+ private String _validatorName;
+ private String _resourceName;
+ private int _numberInvocations;
+ private long _elapsedTime;
+ private long _cpuTime;
+
+ /**
+ * @param validatorId
+ * @param validatorName
+ * @param resourceName
+ * @param numberInvocations number of times the validator was invoked
+ * @param elapsedTime elapsed time in milliseconds
+ * @param cpuTime CPU time in nanoseconds
+ */
+ public PerformanceCounters(String validatorId, String validatorName, String resourceName,
+ int numberInvocations, long elapsedTime, long cpuTime){
+
+ _when = System.currentTimeMillis();
+ _validatorId = validatorId;
+ _validatorName = validatorName;
+ _resourceName = resourceName;
+ _numberInvocations = numberInvocations;
+ _elapsedTime = elapsedTime;
+ _cpuTime = cpuTime;
+ }
+
+ public String getValidatorId() {
+ return _validatorId;
+ }
+ public int getNumberInvocations() {
+ return _numberInvocations;
+ }
+
+ /**
+ * Answer the elapsed time in milliseconds.
+ */
+ public long getElapsedTime() {
+ return _elapsedTime;
+ }
+
+ /**
+ * Answer the amount of CPU time in nanoseconds. If this can not be determined,
+ * answer -1.
+ */
+ public long getCpuTime() {
+ return _cpuTime;
+ }
+
+ @Override
+ public String toString() {
+ return NLS.bind(ValMessages.LogValEndTime,
+ new Object[]{_validatorName, _validatorId, _resourceName, Misc.getTimeMS(_elapsedTime)});
+ }
+
+ public String toString(boolean asSummary){
+ if (asSummary){
+ if (_cpuTime != -1)return NLS.bind(ValMessages.LogValSummary2,
+ new Object[]{_validatorName, _validatorId, _numberInvocations,
+ Misc.getTimeMS(_elapsedTime), Misc.getTimeNano(_cpuTime)});
+
+ return NLS.bind(ValMessages.LogValSummary,
+ new Object[]{_validatorName, _validatorId, _numberInvocations, Misc.getTimeMS(_elapsedTime)});
+ }
+ return toString();
+ }
+
+ public String getValidatorName() {
+ return _validatorName;
+ }
+
+ /**
+ * Answer when was the event logged.
+ *
+ * @see System#currentTimeMillis()
+ */
+ public long getWhen() {
+ return _when;
+ }
+
+ public String getResourceName() {
+ return _resourceName;
+ }
+
+}
diff --git a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/ReporterHelper.java b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/ReporterHelper.java
new file mode 100644
index 0000000..20876bf
--- /dev/null
+++ b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/ReporterHelper.java
@@ -0,0 +1,70 @@
+/*******************************************************************************
+ * Copyright (c) 2007, 2008 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.wst.validation;
+
+import java.util.LinkedList;
+import java.util.List;
+
+import org.eclipse.core.runtime.IProgressMonitor;
+import org.eclipse.wst.validation.internal.MarkerManager;
+import org.eclipse.wst.validation.internal.provisional.core.IMessage;
+import org.eclipse.wst.validation.internal.provisional.core.IReporter;
+import org.eclipse.wst.validation.internal.provisional.core.IValidator;
+
+
+/**
+ * This is a temporary class to ease the transition from the previous validation framework.
+ * <p>
+ * This is not API.
+ * @author karasiuk
+ *
+ */
+public class ReporterHelper implements IReporter {
+ private IProgressMonitor _monitor;
+ private List<IMessage> _list = new LinkedList<IMessage>();
+
+ public ReporterHelper(IProgressMonitor monitor){
+ _monitor = monitor;
+ }
+
+ public void addMessage(IValidator origin, IMessage message) {
+ _list.add(message);
+ }
+
+ public void displaySubtask(IValidator validator, IMessage message) {
+ _monitor.subTask(message.getText(validator.getClass().getClassLoader()));
+ }
+
+ public List<IMessage> getMessages() {
+ return _list;
+ }
+
+ public boolean isCancelled() {
+ return _monitor.isCanceled();
+ }
+
+ public void removeAllMessages(IValidator origin) {
+ _list.clear();
+ }
+
+ public void removeAllMessages(IValidator origin, Object object) {
+ _list.clear();
+ }
+
+ public void removeMessageSubset(IValidator validator, Object obj, String groupName) {
+ _list.clear();
+ }
+
+ public void makeMarkers(){
+ MarkerManager.getDefault().makeMarkers(_list);
+ }
+
+}
diff --git a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/ValidationEvent.java b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/ValidationEvent.java
new file mode 100644
index 0000000..528e58e
--- /dev/null
+++ b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/ValidationEvent.java
@@ -0,0 +1,75 @@
+/*******************************************************************************
+ * Copyright (c) 2008 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.wst.validation;
+
+import org.eclipse.core.resources.IResource;
+import org.eclipse.core.resources.IResourceDelta;
+
+/**
+ * An object that describes which object should be validated and what triggered its validation.
+ * <p>
+ * <b>Provisional API:</b> This class/interface is part of an interim API that is still under development and expected to
+ * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
+ * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
+ * (repeatedly) as the API evolves.
+ * </p>
+ * @author karasiuk
+ *
+ */
+
+public final class ValidationEvent {
+
+ private IResource _resource;
+ private int _kind;
+ private IResourceDelta _dependsOn;
+
+ /**
+ * Create an object that describes what should be validated.
+ *
+ * @param resource
+ * The resource to be validated.
+ * @param kind
+ * The way the resource changed. It uses the same values as the
+ * kind parameter in IResourceDelta.
+ * @param dependsOn
+ * If the resource is being validated because one of it's
+ * dependencies has changed, that change is described here. This
+ * can be null.
+ */
+ public ValidationEvent(IResource resource, int kind, IResourceDelta dependsOn){
+ _resource = resource;
+ _kind = kind;
+ _dependsOn = dependsOn;
+ }
+
+ /**
+ * The resource to be validated.
+ */
+ public IResource getResource() {
+ return _resource;
+ }
+
+ /**
+ * The way the resource changed. It uses the same values as the kind
+ * parameter in IResourceDelta.
+ */
+ public int getKind() {
+ return _kind;
+ }
+
+ /**
+ * If the resource is being validated because one of it's dependencies has changed, that change is described here.
+ * This method will return null when the trigger is not because of a dependency change.
+ */
+ public IResourceDelta getDependsOn() {
+ return _dependsOn;
+ }
+}
diff --git a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/ValidationFramework.java b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/ValidationFramework.java
new file mode 100644
index 0000000..17cc455
--- /dev/null
+++ b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/ValidationFramework.java
@@ -0,0 +1,683 @@
+/*******************************************************************************
+ * Copyright (c) 2007, 2009 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.wst.validation;
+
+import java.lang.reflect.InvocationTargetException;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import org.eclipse.core.resources.IFile;
+import org.eclipse.core.resources.IProject;
+import org.eclipse.core.resources.IResource;
+import org.eclipse.core.resources.IResourceVisitor;
+import org.eclipse.core.resources.ResourcesPlugin;
+import org.eclipse.core.runtime.CoreException;
+import org.eclipse.core.runtime.IProgressMonitor;
+import org.eclipse.core.runtime.OperationCanceledException;
+import org.eclipse.core.runtime.Platform;
+import org.eclipse.core.runtime.jobs.Job;
+import org.eclipse.core.runtime.preferences.IEclipsePreferences;
+import org.eclipse.core.runtime.preferences.InstanceScope;
+import org.eclipse.wst.validation.Validator.V1;
+import org.eclipse.wst.validation.internal.ConfigurationManager;
+import org.eclipse.wst.validation.internal.ContentTypeWrapper;
+import org.eclipse.wst.validation.internal.DebugConstants;
+import org.eclipse.wst.validation.internal.DependencyIndex;
+import org.eclipse.wst.validation.internal.DisabledResourceManager;
+import org.eclipse.wst.validation.internal.DisabledValidatorManager;
+import org.eclipse.wst.validation.internal.GlobalConfiguration;
+import org.eclipse.wst.validation.internal.MarkerManager;
+import org.eclipse.wst.validation.internal.Misc;
+import org.eclipse.wst.validation.internal.PerformanceMonitor;
+import org.eclipse.wst.validation.internal.ProjectUnavailableError;
+import org.eclipse.wst.validation.internal.ValManager;
+import org.eclipse.wst.validation.internal.ValOperation;
+import org.eclipse.wst.validation.internal.ValPrefManagerGlobal;
+import org.eclipse.wst.validation.internal.ValPrefManagerProject;
+import org.eclipse.wst.validation.internal.ValType;
+import org.eclipse.wst.validation.internal.ValidationRunner;
+import org.eclipse.wst.validation.internal.ValidatorMetaData;
+import org.eclipse.wst.validation.internal.ValidatorMutable;
+import org.eclipse.wst.validation.internal.ValManager.UseProjectPreferences;
+import org.eclipse.wst.validation.internal.model.GlobalPreferences;
+import org.eclipse.wst.validation.internal.model.GlobalPreferencesValues;
+import org.eclipse.wst.validation.internal.model.ProjectPreferences;
+import org.eclipse.wst.validation.internal.operations.ValidationBuilder;
+import org.eclipse.wst.validation.internal.operations.ValidatorManager;
+import org.eclipse.wst.validation.internal.operations.WorkbenchReporter;
+import org.eclipse.wst.validation.internal.plugin.ValidationPlugin;
+import org.eclipse.wst.validation.internal.provisional.core.IReporter;
+
+
+/**
+ * The central class of the Validation Framework.
+ * <p>
+ * This is a singleton class that is accessed through the getDefault() method.
+ * <p>
+ * <b>Provisional API:</b> This class/interface is part of an interim API that is still under development and expected to
+ * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
+ * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
+ * (repeatedly) as the API evolves.
+ * </p>
+ * @author karasiuk
+ *
+ */
+public final class ValidationFramework {
+
+ private volatile IDependencyIndex _dependencyIndex;
+ private IPerformanceMonitor _performanceMonitor;
+
+ private Set<IProject> _suspendedProjects;
+ private boolean _suspendAllValidation;
+
+ /**
+ * Answer the singleton, default instance of this class.
+ */
+ public static ValidationFramework getDefault(){
+ return Singleton.vf;
+ }
+
+ private ValidationFramework(){}
+
+ /**
+ * Add the validation builder to the project, so that the project can support
+ * build time validation. It is safe to call this method, if the builder was
+ * previously added to the project. It will not be added more than once.
+ *
+ * @param project The project that the builder is added to.
+ */
+ public void addValidationBuilder(IProject project){
+ ValidatorManager.addProjectBuildValidationSupport(project);
+ }
+
+ /**
+ * Clear any validation markers that may have been set by this validator.
+ *
+ * @param resource
+ * The resource that may have it's markers cleared.
+ * @param validatorId
+ * The id of validator that created the marker.
+ */
+ public void clearMessages(IResource resource, String validatorId) throws CoreException {
+ Validator v = getValidator(validatorId, null);
+ if (v != null)MarkerManager.getDefault().clearMarker(resource, v);
+ }
+
+ /**
+ * Disable all validation for the given resource. This method instructs
+ * the framework to not run any validators on the given resource or any of
+ * it's children. This setting is persistent. Currently this only works with version 2
+ * validators.
+ * <p>
+ * Use the enableValidation method to restore validation.
+ * </p>
+ *
+ * @param resource
+ * The resource that is having validation disabled. It must be an IFolder or an IFile.
+ *
+ * @see #enableValidation(IResource)
+ */
+ public void disableValidation(IResource resource){
+ assert resource != null;
+ DisabledResourceManager.getDefault().disableValidation(resource);
+ }
+
+ /**
+ * Enable validation for the given resource. If the resource was not
+ * previously disabled this method call has no effect. Currently this only
+ * works with version 2 validators.
+ *
+ * @param resource
+ * The resource that is having validation re-enabled.
+ *
+ * @see #disableValidation(IResource)
+ */
+ public void enableValidation(IResource resource){
+ DisabledResourceManager.getDefault().enableValidation(resource);
+ }
+
+ /**
+ * Answer the dependency index. Validators can use this to determine which resources depend on which
+ * other resources.
+ */
+ public IDependencyIndex getDependencyIndex(){
+ // note how the _dependencyIndex is volatile so that this double checking approach can be used.
+ if (_dependencyIndex == null){
+ synchronized(this){
+ if (_dependencyIndex == null)_dependencyIndex = new DependencyIndex();
+ }
+ }
+ return _dependencyIndex;
+ }
+
+ /**
+ * Answer a performance monitor for the validators.
+ */
+ public synchronized IPerformanceMonitor getPerformanceMonitor(){
+ if (_performanceMonitor == null){
+ boolean traceTimes = Misc.debugOptionAsBoolean(DebugConstants.TraceTimes);
+ String traceFile = Platform.getDebugOption(DebugConstants.TraceTimesFile);
+ boolean useDoubles = Misc.debugOptionAsBoolean(DebugConstants.TraceTimesUseDoubles);
+
+ _performanceMonitor = PerformanceMonitor.create(traceTimes, traceFile, useDoubles);
+ }
+ return _performanceMonitor;
+ }
+
+ /**
+ * Answer the preference store that holds the persisted global validation settings.
+ */
+ public IEclipsePreferences getPreferenceStore(){
+ return new InstanceScope().getNode(ValidationPlugin.PLUGIN_ID);
+ }
+
+ public IReporter getReporter(IProject project, IProgressMonitor monitor){
+ return new WorkbenchReporter(project, monitor);
+ }
+
+ /**
+ * Answer all the validators that are applicable for the given resource. A validator is
+ * still returned even if it has been turned off by the user.
+ * <p>
+ * The caller may still need to test if the validator has been turned off by
+ * the user, by using the isBuildValidation() and isManualValidation()
+ * methods.
+ * </p>
+ *
+ * @param resource
+ * The resource that determines which validators are applicable.
+ *
+ * @param isManual
+ * If true then the validator must be turned on for manual validation.
+ * If false then the isManualValidation setting isn't used to filter
+ * out validators.
+ *
+ * @param isBuild
+ * If true then the validator must be turned on for build based
+ * validation. If false then the isBuildValidation setting isn't used
+ * to filter out validators.
+ *
+ * @see Validator#isBuildValidation()
+ * @see Validator#isManualValidation()
+ */
+ public Validator[] getValidatorsFor(IResource resource, boolean isManual, boolean isBuild){
+ IProject project = resource.getProject();
+ List<Validator> list = new LinkedList<Validator>();
+ ContentTypeWrapper ctw = new ContentTypeWrapper();
+ for (Validator val : ValManager.getDefault().getValidators(project)){
+ if (val.shouldValidate(resource, isManual, isBuild, ctw))list.add(val);
+ }
+
+ Validator[] result = new Validator[list.size()];
+ list.toArray(result);
+ return result;
+ }
+
+ /**
+ * Answer all the validators that should not validate the resource, either
+ * because their filters don't support the resource, or the validator has
+ * been disabled for both build validation and manual validation.
+ *
+ * @param resource
+ * The resource this is being tested.
+ */
+ public Set<Validator> getDisabledValidatorsFor(IResource resource){
+ return DisabledValidatorManager.getDefault().getDisabledValidatorsFor(resource);
+ }
+
+ /**
+ * Answer the global validator with the given id.
+ *
+ * @deprecated Use getValidator(String id, IProject project) with a null project instead.
+ *
+ * @param id
+ * @return null if the validator is not found
+ */
+ public Validator getValidator(String id){
+ return ValManager.getDefault().getValidatorWithId(id, null);
+ }
+
+ /**
+ * Answer the validator with the given id that is in effect for the given
+ * project.
+ * <p>
+ * Individual projects may override the global validation preference
+ * settings. If this is allowed and if the project has it's own settings,
+ * then those validators are returned via this method.
+ * </p>
+ * <p>
+ * The following approach is used. For version 1 validators, the validator
+ * is only returned if it is defined to operate on this project type. This
+ * is the way that the previous version of the framework did it. For version
+ * 2 validators, they are all returned.
+ * </p>
+ *
+ * @param id
+ * Validator id.
+ * @param project
+ * This can be null, in which case all the registered validators are
+ * checked.
+ * @return null if the validator is not found
+ */
+ public Validator getValidator(String id, IProject project){
+ return ValManager.getDefault().getValidatorWithId(id, project);
+ }
+
+ /**
+ * Answer copies of all the registered validators.
+ *
+ * @return Answer an empty array if there are no validators.
+ */
+ public Validator[] getValidators(){
+ return ValManager.getDefault().getValidatorsCopy();
+ }
+
+ /**
+ * Answer the validation settings that have been defined on the
+ * project. To "activate" any changes to these settings, the
+ * {@link #applyChanges(MutableProjectSettings, boolean)} method needs to be
+ * called.
+ *
+ * @param project The project who's settings you wish to examine or change.
+ * @return Validation settings that apply to the given project.
+ */
+ public MutableProjectSettings getProjectSettings(IProject project){
+ ProjectPreferences pp = ValManager.getDefault().getProjectPreferences(project);
+ Validator[] vals = pp.getValidators();
+ ValidatorMutable[] vms = new ValidatorMutable[vals.length];
+ for (int i=0; i<vals.length; i++)vms[i] = new ValidatorMutable(vals[i]);
+
+ MutableProjectSettings mps = new MutableProjectSettings(project, vms);
+ mps.setOverride(pp.getOverride());
+ mps.setSuspend(pp.getSuspend());
+ return mps;
+ }
+
+ /**
+ * Answer the validation settings that have been defined at the workspace level.
+ * To "activate" any changes to these settings, the
+ * {@link #applyChanges(MutableWorkspaceSettings, boolean)} method needs to be
+ * called.
+ *
+ * @return Validation settings that apply to the entire workspace.
+ */
+ public MutableWorkspaceSettings getWorkspaceSettings() throws InvocationTargetException{
+
+ ValManager vm = ValManager.getDefault();
+ GlobalPreferences gp = vm.getGlobalPreferences();
+
+ Validator[] vals = vm.getValidators();
+ ValidatorMutable[] vms = new ValidatorMutable[vals.length];
+ for (int i=0; i<vals.length; i++)vms[i] = new ValidatorMutable(vals[i]);
+
+ MutableWorkspaceSettings mws = new MutableWorkspaceSettings(vms, gp.asValues());
+ return mws;
+ }
+
+ /**
+ * Apply the changes that have been been to the validation settings.
+ *
+ * @param settings
+ * The project settings.
+ * @param persist
+ * If true then the changes are persisted to the property files.
+ * If false the changes are applied to the validators, but are
+ * not persisted.
+ */
+ public void applyChanges(MutableProjectSettings settings, boolean persist){
+ ValPrefManagerProject vpm = new ValPrefManagerProject(settings.getProject());
+ vpm.savePreferences(settings, persist);
+ }
+
+ /**
+ * Apply the changes that have been been to the validation settings.
+ *
+ * @param settings
+ * The workspace settings.
+ * @param persist
+ * If true then the changes are persisted to the property files.
+ * If false the changes are applied to the validators, but are
+ * not persisted.
+ */
+ public void applyChanges(MutableWorkspaceSettings settings, boolean persist){
+
+ ValManager vm = ValManager.getDefault();
+ GlobalPreferencesValues gpv = settings.getGlobalPreferencesValues();
+ vm.replace(gpv);
+
+ IMutableValidator[] mvs = settings.getValidators();
+ ValidatorMutable[] vals = new ValidatorMutable[mvs.length];
+ for (int i=0; i<mvs.length; i++)vals[i] = (ValidatorMutable)mvs[i];
+ ValPrefManagerGlobal.getDefault().savePreferences(vm.getGlobalPreferences(), vals, persist);
+ ValPrefManagerGlobal.saveV1Preferences(vals, persist);
+ }
+
+ /**
+ * Validators can use project level settings (Project natures and facets) to
+ * determine if they are applicable to the project or not.
+ *
+ * @param project
+ * The project that the configuration is based on.
+ * @return The copies of the validators that are configured to run on this project based
+ * on the project level settings.
+ * @throws ProjectUnavailableError
+ */
+ public Validator[] getValidatorsConfiguredForProject(IProject project) throws ProjectUnavailableError {
+ Validator[] orig = ValManager.getDefault().getValidatorsConfiguredForProject(project, UseProjectPreferences.Normal);
+ Validator[] copy = new Validator[orig.length];
+ for (int i=0; i<orig.length; i++)copy[i] = orig[i].copy();
+ return copy;
+ }
+
+ /**
+ * Answer all the validators that are applicable for the given resource.
+ *
+ * @param resource the resource that determines which validators are applicable.
+ */
+ public Validator[] getValidatorsFor(IResource resource){
+ List<Validator> list = new LinkedList<Validator>();
+ for (Validator v : getValidatorsFor(resource, false, false)){
+ if (v.isBuildValidation() || v.isManualValidation())list.add(v);
+ }
+ Validator[] vals = new Validator[list.size()];
+ return list.toArray(vals);
+ }
+
+ /**
+ * Answer true if the resource has any enabled validators.
+ *
+ * @param resource
+ * A file, folder or project.
+ *
+ * @param isManual
+ * If true then the validator must be turned on for manual validation.
+ * If false then the isManualValidation setting isn't used to filter
+ * out validators.
+ *
+ * @param isBuild
+ * If true then the validator must be turned on for build based
+ * validation. If false then the isBuildValidation setting isn't used
+ * to filter out validators.
+ */
+ public boolean hasValidators(IResource resource, boolean isManual, boolean isBuild){
+ return ValManager.getDefault().hasValidators(resource, isManual, isBuild);
+ }
+
+ /**
+ * Answer whether or not the validator has been activated, i.e. has the
+ * bundle that defines the validator been loaded. We do not want to cause
+ * unnecessary bundle loading, so this check can be performed by third party
+ * callers, to prevent making other calls that will force the validator to
+ * be loaded.
+ *
+ * @param validator
+ * The validator that is being tested.
+ * @return true if the validator has already been loaded.
+ */
+ public boolean isLoaded(Validator validator){
+ return validator.isLoaded();
+ }
+
+ /**
+ * Waits until all validation jobs are finished. This method will block the
+ * calling thread until all such jobs have finished executing, or until this
+ * thread is interrupted. If there are no validation jobs that are
+ * currently waiting, running, or sleeping, this method returns immediately.
+ * Feedback on how the join is progressing is provided to the progress
+ * monitor.
+ * <p>
+ * If this method is called while the job manager is suspended, only jobs
+ * that are currently running will be joined. Once there are no jobs in the
+ * family in the {@link Job#RUNNING} state, this method returns.
+ * </p>
+ * <p>
+ * Note that there is a deadlock risk when using join. If the calling thread
+ * owns a lock or object monitor that the joined thread is waiting for,
+ * deadlock will occur. This method can also result in starvation of the
+ * current thread if another thread continues to add jobs of the given
+ * family, or if a job in the given family reschedules itself in an infinite
+ * loop.
+ * </p>
+ *
+ * @param monitor
+ * Progress monitor for reporting progress on how the wait is
+ * progressing, or <code>null</code> if no progress monitoring is
+ * required.
+ * @exception InterruptedException
+ * if this thread is interrupted while waiting
+ * @exception OperationCanceledException
+ * if the progress monitor is canceled while waiting
+ */
+ public void join(IProgressMonitor monitor) throws InterruptedException, OperationCanceledException {
+ Job.getJobManager().join(ResourcesPlugin.FAMILY_AUTO_BUILD, monitor);
+ Job.getJobManager().join(ValidationBuilder.FAMILY_VALIDATION_JOB, monitor);
+ }
+
+ /**
+ * Suspends, or undoes the suspension of, validation on the current project.
+ * If <b>suspend</b> is true then validation is suspended and if it's false
+ * then validation is not suspended on the project. The value of this
+ * variable is not persisted.
+ * <p>
+ * Be <b>very careful</b> when you use this method! Turn validation back on in a
+ * finally block because if the code which suspended validation crashes, the
+ * user has no way to reset the suspension. The user will have to shut down
+ * and restart the workbench to get validation to work again.
+ * </p>
+ *
+ * @param project
+ * The project that is to be suspended or unsuspended.
+ * @param suspend
+ * If true, validation on the project will be suspend. If false it will
+ * not be suspended.
+ */
+ public void suspendValidation(IProject project, boolean suspend) {
+ if (project == null)return;
+ if (suspend)getSuspendedProjects().add(project);
+ else getSuspendedProjects().remove(project);
+ }
+
+ private synchronized Set<IProject> getSuspendedProjects(){
+ if (_suspendedProjects == null)_suspendedProjects = Collections.synchronizedSet(new HashSet<IProject>(20));
+ return _suspendedProjects;
+ }
+
+ /**
+ * Save the validators settings into the persistent store, there by making their settings the active settings.
+ * <p>
+ * A common use of this method would be to change whether particular validators are enabled or not. For example
+ * if you only wanted the JSP validator enabled, you could use code similar to this:
+ * <pre>
+ * ValidationFramework vf = ValidationFramework.getDefault();
+ * Validator[] vals = vf.getValidators();
+ * for (Validator v : vals){
+ * boolean enabled = false;
+ * if (v.getValidatorClassname().equals("org.eclipse.jst.jsp.core.internal.validation.JSPBatchValidator"))enabled = true;
+ * v.setBuildValidation(enabled);
+ * v.setManualValidation(enabled);
+ * }
+ * vf.saveValidators(vals);
+ * </pre>
+ * </p>
+ *
+ * @param validators The validators that you are saving.
+ *
+ * @throws InvocationTargetException
+ */
+ public void saveValidators(Validator[] validators) throws InvocationTargetException{
+
+
+ ValPrefManagerGlobal gp = ValPrefManagerGlobal.getDefault();
+ gp.saveAsPrefs(validators);
+
+ GlobalConfiguration gc = ConfigurationManager.getManager().getGlobalConfiguration();
+
+ List<ValidatorMetaData> manual = new LinkedList<ValidatorMetaData>();
+ List<ValidatorMetaData> build = new LinkedList<ValidatorMetaData>();
+ for (Validator v : validators){
+ V1 v1 = v.asV1Validator();
+ if (v1 == null)continue;
+ if (v1.isManualValidation())manual.add(v1.getVmd());
+ if (v1.isBuildValidation())build.add(v1.getVmd());
+ }
+
+ ValidatorMetaData[] array = new ValidatorMetaData[manual.size()];
+ gc.setEnabledManualValidators(manual.toArray(array));
+
+ array = new ValidatorMetaData[build.size()];
+ gc.setEnabledBuildValidators(build.toArray(array));
+
+ gc.passivate();
+ gc.store();
+ }
+
+ /**
+ * Suspends, or undoes the suspension of, validation on all projects in the
+ * workbench. If "suspend" is true then validation is suspended and if it's
+ * "false" then validation is not suspended. The value of this variable is
+ * not persisted.
+ * <p>
+ * Be <b>very careful</b> when you use this method! Turn validation back on in a
+ * finally block because if the code which suspended validation crashes, the
+ * user has no way to reset the suspension. The user will have to shut down
+ * and restart the workbench to get validation to work again.
+ * </p>
+ */
+ public void suspendAllValidation(boolean suspend) {
+ _suspendAllValidation = suspend;
+ }
+
+ /**
+ * Return true if "suspend all" is enabled, false otherwise.
+ */
+ public boolean isSuspended() {
+ return _suspendAllValidation;
+ }
+
+ /**
+ * Returns true if validation will not run on the project because it's been suspended. This
+ * method checks only the suspension status; if validation cannot run for some other reason (for
+ * example, there are no enabled validators), yet the IProject is not suspended, this method
+ * will return true even though validation will not run.
+ */
+ public boolean isSuspended(IProject project) {
+ if (_suspendAllValidation)return true;
+ if (project == null)return false;
+ return getSuspendedProjects().contains(project);
+ }
+
+ /**
+ * This method should be called by any code that is preparing to suspend validation on a
+ * project. Rather than calling isSuspended(IProject), which will also return true if all validation
+ * has been suspended.
+ *
+ * @param project the project that is being tested
+ * @return boolean true if the project has been suspended
+ */
+ public boolean isProjectSuspended(IProject project) {
+ if (project == null)return false;
+ return getSuspendedProjects().contains(project);
+ }
+
+ /**
+ * Validate the projects. Exactly one of isManual or isBuild needs to be true.
+ *
+ * @param projects
+ * The projects to be validated.
+ *
+ * @param isManual
+ * Is this being done as part of a manual validation? i.e. did
+ * the user select the Validate menu item?
+ *
+ * @param isBuild
+ * Is this being done as part of a build?
+ *
+ * @param monitor
+ *
+ * @return the validation result which is the combined result for all the
+ * resources that were validated.
+ */
+ public ValidationResults validate(IProject[] projects, final boolean isManual, final boolean isBuild,
+ IProgressMonitor monitor) throws CoreException{
+ ValType type = ValType.Build;
+ if (isManual)type = ValType.Manual;
+ ValOperation vo = ValidationRunner.validate(createMap(projects), type, monitor, true);
+ return vo.getResults();
+ }
+
+ /**
+ * Validate a specific file resource.
+ *
+ * @param file
+ * The file to be validated.
+ * @param monitor
+ * Progress monitor.
+ * @return the result of validating the file.
+ */
+ public ValidationResults validate(IFile file, IProgressMonitor monitor) throws CoreException{
+ ValOperation vo = ValidationRunner.validate(file, ValType.Manual, monitor, true);
+ return vo.getResults();
+ }
+
+ /**
+ * Answer all the resources in the projects as a map.
+ * @param projects
+ */
+ private Map<IProject, Set<IResource>> createMap(IProject[] projects) throws CoreException{
+ final HashMap<IProject, Set<IResource>> map = new HashMap<IProject, Set<IResource>>(1000);
+
+ for (IProject p : projects){
+ Set<IResource> set = new HashSet<IResource>(1000);
+ ResourceAdder ra = new ResourceAdder(set);
+ p.accept(ra);
+ map.put(p, set);
+ }
+ return map;
+ }
+
+ public static class ResourceAdder implements IResourceVisitor {
+
+ private Set<IResource> _set;
+
+ /**
+ * A class that knows how to add resources to a set.
+ * @param set the set where the resources are added.
+ */
+ public ResourceAdder(Set<IResource> set){
+ _set = set;
+ }
+
+ public boolean visit(IResource resource) throws CoreException {
+ // [225839] the older validators only expect files and folders.
+ int type = resource.getType();
+ if (type == IResource.FILE || type == IResource.FOLDER)_set.add(resource);
+ return true;
+ }
+
+ }
+
+ /**
+ * Store the singleton for the ValidationFramework. This approach is used to avoid having to synchronize the
+ * ValidationFramework.getDefault() method.
+ *
+ * @author karasiuk
+ *
+ */
+ private static class Singleton {
+ static ValidationFramework vf = new ValidationFramework();
+ }
+
+}
diff --git a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/ValidationResult.java b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/ValidationResult.java
new file mode 100644
index 0000000..c1714e1
--- /dev/null
+++ b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/ValidationResult.java
@@ -0,0 +1,385 @@
+/*******************************************************************************
+ * Copyright (c) 2007, 2009 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.wst.validation;
+
+import java.util.LinkedList;
+import java.util.List;
+
+import org.eclipse.core.resources.IMarker;
+import org.eclipse.core.resources.IProject;
+import org.eclipse.core.resources.IResource;
+import org.eclipse.core.runtime.IProgressMonitor;
+import org.eclipse.wst.validation.internal.core.ValidationException;
+import org.eclipse.wst.validation.internal.provisional.core.IReporter;
+
+/**
+ * The result of running a validate operation. Validators create and return this objects as part of
+ * performing their validation.
+ * <p>
+ * <b>Provisional API:</b> This class/interface is part of an interim API that is still under development and expected to
+ * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
+ * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
+ * (repeatedly) as the API evolves.
+ * </p>
+ * @author karasiuk
+ *
+ */
+public final class ValidationResult {
+
+ private final List<ValidatorMessage> _messages = new LinkedList<ValidatorMessage>();
+
+ private final static ValidatorMessage[] _noMessages = new ValidatorMessage[0];
+
+ private boolean _canceled;
+
+ /**
+ * The resources that the validated resource depends on. This can be left null.
+ * For example, an XML file may depend on a XSD in order to know if it is valid or not.
+ * It would pass back the XSD file.
+ */
+ private IResource[] _dependsOn;
+
+ /**
+ * The objects that you validated as a side effect of validating this object. The framework will not
+ * call you with any of these objects (in this validation run). This can be left null.
+ */
+ private IResource[] _validated;
+
+ private int _severityError;
+ private int _severityWarning;
+ private int _severityInfo;
+
+ private IProject _suspendValidation;
+
+ /** A count of the number of resources that were validated. */
+ private int _numberOfValidatedResources = 1;
+
+ private ReporterHelper _reporter;
+ private ValidationException _validationException;
+
+ /**
+ * This is an optional method, that a validator can use to return error
+ * messages. The validation framework converts these into IMarkers.
+ * <p>
+ * The scenario that motivated this method, is when a validator is used both
+ * for <b>as you type</b> validation and <b>build</b> validation. When
+ * called in as you type mode, the validator doesn't want to directly create IMarkers,
+ * because the resource hasn't been saved yet. It needs to return something
+ * other than an IMarker. But when called in build mode, it does ultimately
+ * want IMarkers. By returning ValidatorMessages, it only needs to return
+ * one type of message, and those messages can be either be directly used by
+ * the caller, or automatically converted into IMarkers by the validation
+ * framework.
+ * </p>
+ * <p>
+ * To make matters even more complicated there is a third way to return
+ * messages. To make it easier for old validators to port to the new
+ * framework, they can continue to use an IReporter. If a validator calls
+ * the getReporter() method then it is assumed by the framework that that is
+ * the approach that they have chosen.
+ * </p>
+ *
+ * @see #getReporter(IProgressMonitor)
+ *
+ * @param message
+ * A validation message.
+ */
+ public void add(ValidatorMessage message){
+ _messages.add(message);
+ }
+
+ /**
+ * Answer an IReporter for handing error messages.
+ * <p>
+ * This is a transition method, to help old validators port to the new validation framework. If this method
+ * is called it is assumed by the framework, that this IReporter will be used as the only way of passing messages
+ * back to the framework.
+ *
+ * @see #add(ValidatorMessage)
+ * @param monitor
+ */
+ public IReporter getReporter(IProgressMonitor monitor){
+ if (_reporter == null)_reporter = new ReporterHelper(monitor);
+ return _reporter;
+ }
+
+ ReporterHelper getReporterHelper(){
+ return _reporter;
+ }
+
+ /**
+ * Merge the message counts and messages from an individual validator into this result.
+ * @param result it can be null, in which case it is ignored.
+ */
+ public void mergeResults(ValidationResult result){
+ if (result == null)return;
+
+ ValidatorMessage[] msgs = result.getMessages();
+ for (ValidatorMessage m : msgs){
+ add(m);
+ int severity = m.getAttribute(IMarker.SEVERITY, 0);
+ switch (severity){
+ case IMarker.SEVERITY_ERROR:
+ incrementError(1);
+ break;
+ case IMarker.SEVERITY_WARNING:
+ incrementWarning(1);
+ break;
+ case IMarker.SEVERITY_INFO:
+ incrementInfo(1);
+ break;
+
+ }
+ }
+
+ incrementError(result.getSeverityError());
+ incrementWarning(result.getSeverityWarning());
+ incrementInfo(result.getSeverityInfo());
+
+ _numberOfValidatedResources += result.getNumberOfValidatedResources();
+
+ }
+
+ /**
+ * Answer the resources that the validated resource depends on.
+ */
+ public IResource[] getDependsOn() {
+ return _dependsOn;
+ }
+
+ /**
+ * Answer any validation messages that were added by the validator.
+ * @return an array is returned even if there are no messages.
+ */
+ public ValidatorMessage[] getMessages(){
+ if (_messages == null)return _noMessages;
+ ValidatorMessage[] msgs = new ValidatorMessage[_messages.size()];
+ _messages.toArray(msgs);
+ return msgs;
+ }
+
+ /**
+ * Answer a copy of any validation messages that were added by the validator. The array is a new
+ * array, and each message is a copy.
+ * @return an array is returned even if there are no messages.
+ */
+ public synchronized ValidatorMessage[] getMessagesAsCopy(){
+ if (_messages == null)return _noMessages;
+ ValidatorMessage[] msgs = new ValidatorMessage[_messages.size()];
+ int i = 0;
+ for (ValidatorMessage msg : _messages)msgs[i++] = msg.asCopy();
+ return msgs;
+ }
+
+ /**
+ * Update the resources that the validated resource depends on. This can be
+ * left null. For example, a XML file may depend on a XSD file in order to
+ * know if it is valid or not. It would pass back that XSD file.
+ *
+ * @param dependsOn
+ * If this is null then the dependency information is not updated. To
+ * remove the dependency information, an empty array needs to be
+ * supplied. A non null parameter, <b>replaces</b> all the dependency
+ * information for this resource, for this validator.
+ */
+ public void setDependsOn(IResource[] dependsOn) {
+ _dependsOn = dependsOn;
+ }
+
+ /**
+ * @return All the resources that were validated as a side-effect of
+ * validating the main resource, or null if none were.
+ */
+ public IResource[] getValidated() {
+ return _validated;
+ }
+
+ /**
+ * Indicate that additional resources have been validated as part of this
+ * validate operation. Sometimes in the course of performing a validation on
+ * one resource it is necessary to validate other resources as well. This
+ * method is used to let the framework know about these additional validated
+ * resources, to possibly save them being validated redundantly.
+ *
+ * @param validated
+ * Any additional resources that were validated.
+ */
+ public void setValidated(IResource[] validated) {
+ _validated = validated;
+ }
+
+ /**
+ * Answer the number of error messages that were generated as part of this validation operation.
+ */
+ public int getSeverityError() {
+ return _severityError;
+ }
+
+ /**
+ * Set the number of error messages that were generated as part of this validation operation.
+ * <p>
+ * Messages added through the add(ValidationMessage) method should not be included here, as this
+ * information will be determined from the ValidationMessage.
+ * </p>
+ */
+ public void setSeverityError(int severityError) {
+ _severityError = severityError;
+ }
+
+
+ /**
+ * Increment the number of error messages that were generated as part of this validation operation.
+ * <p>
+ * Messages added through the add(ValidationMessage) method should not be included here, as this
+ * information will be determined from the ValidationMessage.
+ * </p>
+ *
+ * @return the current number of errors.
+ */
+ public int incrementError(int errors){
+ _severityError += errors;
+ return _severityError;
+ }
+
+ /**
+ * Answer the number of warning messages that were generated as part of this validation operation.
+ */
+ public int getSeverityWarning() {
+ return _severityWarning;
+ }
+
+ /**
+ * Set the number of warning messages that were generated as part of this validation operation.
+ * <p>
+ * Messages added through the add(ValidationMessage) method should not be included here, as this
+ * information will be determined from the ValidationMessage.
+ * </p>
+ */
+ public void setSeverityWarning(int severityWarning) {
+ _severityWarning = severityWarning;
+ }
+
+ /**
+ * Increment the number of warning messages that were generated as part of this validation operation.
+ * <p>
+ * Messages added through the add(ValidationMessage) method should not be included here, as this
+ * information will be determined from the ValidationMessage.
+ * </p>
+ *
+ * @return the current number of warnings.
+ */
+ public int incrementWarning(int warnings){
+ _severityWarning += warnings;
+ return _severityWarning;
+ }
+
+ /**
+ * Answer the number of informational messages that were generated as part of this validation operation.
+ */
+ public int getSeverityInfo() {
+ return _severityInfo;
+ }
+
+ /**
+ * Set the number of informational messages that were generated as part of this validation operation.
+ * <p>
+ * Messages added through the add(ValidationMessage) method should not be included here, as this
+ * information will be determined from the ValidationMessage.
+ * </p>
+ */
+ public void setSeverityInfo(int severityInfo) {
+ _severityInfo = severityInfo;
+ }
+
+ /**
+ * Increment the number of informational messages that were generated as part of this validation operation.
+ * <p>
+ * Messages added through the add(ValidationMessage) method should not be included here, as this
+ * information will be determined from the ValidationMessage.
+ * </p>
+ *
+ * @return the current number of informational message.
+ */
+ public int incrementInfo(int info){
+ _severityInfo += info;
+ return _severityInfo;
+ }
+
+ /**
+ * Was the operation canceled before it completed? For example if the validation is being run through the
+ * user interface, the end user can cancel the operation through the progress monitor.
+ *
+ * @return true if the operation was canceled
+ */
+ public boolean isCanceled() {
+ return _canceled;
+ }
+
+ /**
+ * Indicate if the operation was canceled.
+ *
+ * @param canceled
+ * Set to true if it was canceled and false if it was not canceled.
+ */
+ public void setCanceled(boolean canceled) {
+ _canceled = canceled;
+ }
+
+ /**
+ * Answer the number of resources that have been validated.
+ */
+ public int getNumberOfValidatedResources() {
+ if (_validated == null)return _numberOfValidatedResources;
+ return _numberOfValidatedResources + _validated.length;
+ }
+
+ /**
+ * If the validation ended with an exception, answer it.
+ * @return null if the validator did not finish with an exception.
+ */
+ public ValidationException getValidationException() {
+ return _validationException;
+ }
+
+ /**
+ * If the validation failed with an exception, it can be recorded here.
+ * <p>
+ * This method is provided for old validators to ease their transition to the new framework.
+ * </p>
+ * @param validationException
+ */
+ public void setValidationException(ValidationException validationException) {
+ _validationException = validationException;
+ }
+
+ /**
+ * Answer the project that the validator would like to have suspended.
+ *
+ * @return the project to suspend or null. The normal result is null, which means that
+ * the validator wishes to receive normal validation requests.
+ */
+ public IProject getSuspendValidation(){
+ return _suspendValidation;
+ }
+
+ /**
+ * Calling this method will inform the framework, that this validator does not wish to be
+ * called again for any resources in this project, for the duration of this validation operation.
+ * <p>
+ * Some validators may have a rich set of triggers, but once they have been invoked once,
+ * do not need to be invoked again during the course of the current validation.
+ * </p>
+ * @param project The project that this validator no longer wants to be notified on.
+ */
+ public void setSuspendValidation(IProject project) {
+ _suspendValidation = project;
+ }
+}
diff --git a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/ValidationResults.java b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/ValidationResults.java
new file mode 100644
index 0000000..ba947f8
--- /dev/null
+++ b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/ValidationResults.java
@@ -0,0 +1,76 @@
+/*******************************************************************************
+ * Copyright (c) 2007, 2009 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.wst.validation;
+
+
+/**
+ * The combined results of validating multiple resources.
+ * <p>
+ * <b>Provisional API:</b> This class/interface is part of an interim API that is still under development and expected to
+ * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
+ * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
+ * (repeatedly) as the API evolves.
+ * </p>
+ * @author karasiuk
+ *
+ */
+public final class ValidationResults {
+
+ private final ValidatorMessage[] _messages;
+ private final int _error;
+ private final int _warn;
+ private final int _info;
+
+ public ValidationResults(ValidationResult result){
+ if (result == null){
+ _messages = new ValidatorMessage[0];
+ _error = 0;
+ _warn = 0;
+ _info = 0;
+ }
+ else {
+ _messages = result.getMessagesAsCopy();
+ _error = result.getSeverityError();
+ _warn = result.getSeverityWarning();
+ _info = result.getSeverityInfo();
+ }
+ }
+
+ /**
+ * Answer any validation messages that were added by the validation operation.
+ * @return an array is returned even if there are no messages.
+ */
+ public ValidatorMessage[] getMessages(){
+ return _messages;
+ }
+
+ /**
+ * Answer the number of error messages that were generated as part of this validation operation.
+ */
+ public int getSeverityError() {
+ return _error;
+ }
+
+ /**
+ * Answer the number of informational messages that were generated as part of this validation operation.
+ */
+ public int getSeverityInfo() {
+ return _info;
+ }
+
+ /**
+ * Answer the number of warning messages that were generated as part of this validation operation.
+ */
+ public int getSeverityWarning() {
+ return _warn;
+ }
+
+}
diff --git a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/ValidationState.java b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/ValidationState.java
new file mode 100644
index 0000000..8097de4
--- /dev/null
+++ b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/ValidationState.java
@@ -0,0 +1,90 @@
+/*******************************************************************************
+ * Copyright (c) 2007, 2008 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.wst.validation;
+
+import java.util.HashMap;
+import java.util.Map;
+
+import org.eclipse.wst.validation.internal.plugin.ValidationPlugin;
+
+/**
+ * Keep track of arbitrary validation data, during the course of a validation.
+ * <p>
+ * To enable more efficient caching, the validation framework, allows individual validators to cache
+ * arbitrary data during the validation process. Use of this object is completely optional.
+ * <p>
+ * Since some validators wish to share data with other validators, any validator can see the state data for
+ * any other validator, since the id is simply the validator's extension id.
+ * <p>
+ * This object is freed at the end of the validation process.
+ * <p>
+ * <b>Provisional API:</b> This class/interface is part of an interim API that is still under development and expected to
+ * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
+ * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
+ * (repeatedly) as the API evolves.
+ * </p>
+ * @noextend
+ * @author karasiuk
+ *
+ */
+public final class ValidationState {
+
+ /**
+ * This is a special id.
+ * <p>
+ * If a resource that is depended on by others is changed, then the
+ * dependent resources are validated. The depended on resource, which is the
+ * resource that actually changed, is placed into the ValidationState using
+ * this id.
+ * </p>
+ * @deprecated This approach is not thread safe, the longer form of the AbstractValidator validate method should be used instead.
+ * @see AbstractValidator#validate(ValidationEvent, ValidationState, org.eclipse.core.runtime.IProgressMonitor)
+ */
+ public static final String TriggerResource = ValidationPlugin.PLUGIN_ID + ".Trigger"; //$NON-NLS-1$
+
+ // I can't use a ConncurrentHashMap because some of the clients store nulls.
+ private final Map<String, Object> _map = new HashMap<String, Object>(50);
+
+ public ValidationState(){
+ }
+
+ /**
+ * Save some state information.
+ *
+ * @param id
+ * By convention this is the fully qualified validator extension id.
+ * For example: org.eclipse.wst.html.ui.HTMLValidator
+ *
+ * @param value
+ * Any arbitrary data that the validator might find useful. The
+ * validation framework doesn't do anything with this object except
+ * pass it along during the validation process.
+ */
+ public synchronized void put(String id, Object value){
+ _map.put(id, value);
+ }
+
+ /**
+ * Answer the state data for the given validator.
+ *
+ * @param id
+ * By convention this is the fully qualified validator extension point
+ * id. For example org.eclipse.wst.html.ui.HTMLValidator
+ *
+ * @return any arbitrary data that the validator might find useful,
+ * including null.
+ */
+ public synchronized Object get(String id){
+ return _map.get(id);
+ }
+
+
+}
diff --git a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/Validator.java b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/Validator.java
new file mode 100644
index 0000000..2adb3bb
--- /dev/null
+++ b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/Validator.java
@@ -0,0 +1,1353 @@
+/*******************************************************************************
+ * Copyright (c) 2007, 2008 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.wst.validation;
+
+import java.lang.reflect.InvocationTargetException;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+import org.eclipse.core.resources.IMarker;
+import org.eclipse.core.resources.IProject;
+import org.eclipse.core.resources.IResource;
+import org.eclipse.core.runtime.IAdaptable;
+import org.eclipse.core.runtime.IConfigurationElement;
+import org.eclipse.core.runtime.IContributor;
+import org.eclipse.core.runtime.IProgressMonitor;
+import org.eclipse.core.runtime.IStatus;
+import org.eclipse.core.runtime.NullProgressMonitor;
+import org.eclipse.core.runtime.Platform;
+import org.eclipse.osgi.util.NLS;
+import org.eclipse.wst.validation.internal.ConfigurationConstants;
+import org.eclipse.wst.validation.internal.ConfigurationManager;
+import org.eclipse.wst.validation.internal.ContentTypeWrapper;
+import org.eclipse.wst.validation.internal.ExtensionConstants;
+import org.eclipse.wst.validation.internal.MarkerManager;
+import org.eclipse.wst.validation.internal.Misc;
+import org.eclipse.wst.validation.internal.NullValidator;
+import org.eclipse.wst.validation.internal.SummaryReporter;
+import org.eclipse.wst.validation.internal.Tracing;
+import org.eclipse.wst.validation.internal.ValManager;
+import org.eclipse.wst.validation.internal.ValMessages;
+import org.eclipse.wst.validation.internal.ValOperation;
+import org.eclipse.wst.validation.internal.ValPrefManagerGlobal;
+import org.eclipse.wst.validation.internal.ValPrefManagerProject;
+import org.eclipse.wst.validation.internal.ValType;
+import org.eclipse.wst.validation.internal.ValidationConfiguration;
+import org.eclipse.wst.validation.internal.ValidatorExtensionReader;
+import org.eclipse.wst.validation.internal.ValidatorMetaData;
+import org.eclipse.wst.validation.internal.core.ValidatorLauncher;
+import org.eclipse.wst.validation.internal.delegates.ValidatorDelegateDescriptor;
+import org.eclipse.wst.validation.internal.delegates.ValidatorDelegatesRegistry;
+import org.eclipse.wst.validation.internal.model.FilterGroup;
+import org.eclipse.wst.validation.internal.operations.IWorkbenchContext;
+import org.eclipse.wst.validation.internal.operations.WorkbenchContext;
+import org.eclipse.wst.validation.internal.plugin.ValidationPlugin;
+import org.eclipse.wst.validation.internal.provisional.core.IMessage;
+import org.eclipse.wst.validation.internal.provisional.core.IValidator;
+
+/**
+ * Represents a validator. This gets instantiated through one of the validator extension points.
+ * <p>
+ * <b>This class is not API</b>.
+ * </p>
+ *
+ * @author karasiuk
+ *
+ */
+public abstract class Validator implements Comparable<Validator> {
+ // Remember if you add a new instance variable, make sure that you update the copy and become methods
+
+ /**
+ * The level of configuration for the validator.
+ * <ul>
+ * <li>Extension - Defined by an extension point.</li>
+ * <li>Global - Defined by a global preference.</li>
+ * <li>Project - Defined by a project property.</li>
+ * </ul>
+ */
+ public enum Level {Extension, Global, Project};
+
+ protected boolean _buildValidation = true;
+
+ /** If this is a delegating validator, then this field holds the validator that will be delegated to. */
+ private String _delegatingId;
+
+ /**
+ * If this validator is also used to control an ISource validator, the id of the ISource validator is
+ * registered here.
+ */
+ private String _sourceId;
+
+ protected boolean _manualValidation = true;
+
+ /** An optional customized marker id for this validator. */
+ private String _markerId;
+
+ /**
+ * Version of the filter definition. By increasing this number the framework can know that a plug-in has
+ * changed it's filters.
+ */
+ private int _version = 1;
+
+ /** Map simple message id's to message settings. */
+ private Map<String, MessageSeveritySetting> _messageSettings;
+
+ /** The project that you are defined in. This can be null which means that you are a global validator. */
+ protected IProject _project;
+
+ /** How many times has a global field in this validator been changed since it was created (or copied)? */
+ protected transient int _changeCountGlobal;
+
+ /** How many times has a message field in this validator been changed since it was created (or copied)? */
+ protected transient int _changeCountMessages;
+
+ /** Has the validator been migrated from an earlier version in this session, but not yet saved? */
+ private boolean _migrated;
+
+ public Validator(IProject project){
+ _project = project;
+ }
+
+ void setMigrated(boolean migrated){
+ _migrated = migrated;
+ }
+
+ /**
+ * Create a new validator based on a abstract validator.
+ *
+ * @param validator
+ * The validator that is being wrapped.
+ *
+ * @param project
+ * The project that you are defined in. This can be null which
+ * means that you are a global validator.
+ */
+ public static Validator create(IConfigurationElement validator, IProject project) {
+ V2 v2 = new V2(validator, project);
+ return v2;
+ }
+
+ /**
+ * Create a new validator based on validator meta data.
+ *
+ * @param project
+ * The project that you are defined in. This can be null which
+ * means that you are a global validator.
+ */
+ public static Validator create(ValidatorMetaData vmd, ValidationConfiguration config, IProject project){
+ V1 v1 = new V1(vmd, config, project);
+ return v1;
+ }
+
+ /**
+ * If you are a version 1 validator, answer yourself as one, otherwise answer null.
+ */
+ public V1 asV1Validator(){
+ return null;
+ }
+
+ /**
+ * If you are a version 2 validator, answer yourself as one, otherwise answer null.
+ */
+ public V2 asV2Validator() {
+ return null;
+ }
+
+ /**
+ * The project is being cleaned, this method gives the validator a chance to do any special cleanup.
+ * The default is to do nothing.
+ *
+ * @param project the project being built.
+ * @param monitor the monitor that should be used for reporting progress if the clean takes a long time.
+ */
+ public void clean(IProject project, ValOperation operation, IProgressMonitor monitor){
+ }
+
+ /**
+ * Compare yourself based on Validator name.
+ */
+ public int compareTo(Validator validator) {
+ return getName().compareTo(validator.getName());
+ }
+
+ /** Answer a deep copy of yourself. */
+ public Validator copy(){
+ return copy(false);
+ }
+
+ public abstract Validator copy(boolean includeChangeCounts);
+
+ /**
+ * Update your direct, non transient fields from the fields in v.
+ */
+ protected void copyLocal(Validator v, boolean includeChangeCounts){
+ _buildValidation = v._buildValidation;
+ _delegatingId = v._delegatingId;
+ _manualValidation = v._manualValidation;
+ _markerId = v._markerId;
+ _messageSettings = v._messageSettings;
+ _sourceId = v._sourceId;
+ _version = v._version;
+ _migrated = v._migrated;
+
+ if (includeChangeCounts){
+ _changeCountGlobal = v._changeCountGlobal;
+ _changeCountMessages = v._changeCountMessages;
+ }
+ }
+
+ /**
+ * Should the validation framework first clear the markers that this
+ * validator has placed on this resource? This method can be overridden by
+ * validator implementors to provide a validator specific behavior.
+ *
+ * @param event
+ * The validation event that triggered the validation.
+ * @return true if the validation framework should first clear all the
+ * markers that this validator produced. This is the default
+ * behavior. Return false to leave the markers unchanged. It then
+ * becomes the responsibility of the validator to manage it's own
+ * markers for this resource, for this validation event.
+ */
+ public boolean shouldClearMarkers(ValidationEvent event){
+ return true;
+ }
+
+ /**
+ * Answer true if this validator, based on it's filters, should validate
+ * this resource. This method does not check to see if global validation or
+ * project validation has been suspended or not.
+ *
+ * @param resource
+ * The resource to be checked.
+ * @param isManual
+ * If true then this validator must also be enabled for manual
+ * validation.
+ * @param isBuild
+ * If true then this validator must also be enabled for builder
+ * based validation.
+ *
+ * @return true if the resource should be validated.
+ */
+ public boolean shouldValidate(IResource resource, boolean isManual, boolean isBuild){
+ return shouldValidate(resource, isManual, isBuild, new ContentTypeWrapper());
+ }
+
+ /**
+ * Answer true if this validator, based on it's filters, should validate
+ * this resource. This method does not check to see if global validation or
+ * project validation has been suspended or not.
+ *
+ * @param resource
+ * The resource to be checked.
+ * @param isManual
+ * If true then this validator must also be enabled for manual
+ * validation.
+ * @param isBuild
+ * If true then this validator must also be enabled for builder
+ * based validation.
+ * @param contentTypeWrapper
+ * For repeated calls on the same resource, it is more efficient
+ * to remember the content type.
+ * @return true if the resource should be validated.
+ * @see Friend#shouldValidate(Validator, IResource, boolean, boolean, ContentTypeWrapper)
+ */
+ boolean shouldValidate(IResource resource, boolean isManual, boolean isBuild,
+ ContentTypeWrapper contentTypeWrapper){
+
+ if (isManual && !_manualValidation)return false;
+ if (isBuild && !_buildValidation)return false;
+
+ return shouldValidate(resource, contentTypeWrapper);
+ }
+
+ /**
+ * Answer true if this validator, based on it's filters, should validate
+ * this resource. This method does not check to see if global validation or
+ * project validation has been suspended or not.
+ *
+ * @param resource
+ * The resource to be checked.
+ * @param valType
+ * The context to use when performing the check.
+ *
+ * @return true if the resource should be validated.
+ */
+ public boolean shouldValidate(IResource resource, ValType valType){
+ return shouldValidate(resource, valType, new ContentTypeWrapper());
+ }
+
+ /**
+ * Answer true if this validator, based on it's filters, should validate
+ * this resource. This method does not check to see if global validation or
+ * project validation has been suspended or not.
+ *
+ * @param resource
+ * The resource to be checked.
+ * @param valType
+ * The context to use when performing the check.
+ * @param contentTypeWrapper
+ * For repeated calls on the same resource, it is more efficient
+ * to remember the content type.
+ *
+ * @return true if the resource should be validated.
+ *
+ * @see Friend#shouldValidate(Validator, IResource, ValType, ContentTypeWrapper)
+ */
+ boolean shouldValidate(IResource resource, ValType valType, ContentTypeWrapper contentTypeWrapper){
+ if (Tracing.matchesExtraDetail(getId())){
+ Tracing.log("Validator-01: checking if " + getId() + " should validate " + resource); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+ if (valType == ValType.Manual && !_manualValidation)return false;
+ if (valType == ValType.Build && !_buildValidation)return false;
+
+ boolean result = shouldValidate(resource, contentTypeWrapper);
+ if (Tracing.matchesExtraDetail(getId())){
+ Tracing.log("Validator-02: result = " + result); //$NON-NLS-1$
+ }
+
+ return result;
+ }
+
+ /**
+ * Answer true if this validator, based on it's filters, should validate this project. This method
+ * does not check to see if global validation or project validation has been suspended or not.
+ *
+ * @param project the project to be checked
+ * @param type The type of validation request
+ *
+ * @return true if the project should be validated.
+ */
+ public boolean shouldValidateProject(IProject project, ValType type){
+ return shouldValidateProject(project, type == ValType.Manual, type == ValType.Build);
+ }
+
+ /**
+ * Answer true if this validator, based on it's filters, should validate this project. This method
+ * does not check to see if global validation or project validation has been suspended or not.
+ *
+ * @param project the project to be checked
+ * @param isManual if true then this validator must also be enabled for manual validation.
+ * @param isBuild if true then this validator must also be enabled for builder based validation.
+ *
+ * @return true if the project should be validated.
+ */
+ public boolean shouldValidateProject(IProject project, boolean isManual, boolean isBuild){
+ if (Tracing.matchesExtraDetail(getId())){
+ Tracing.log("Validator-03: checking if " + getId() + " should validate " + project); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+ if (isManual && !_manualValidation)return false;
+ if (isBuild && !_buildValidation)return false;
+ if (project == null || !project.isOpen())return false;
+ boolean result = shouldValidateProject(project);
+ if (Tracing.matchesExtraDetail(getId())){
+ Tracing.log("Validator-04: result " + result); //$NON-NLS-1$
+ }
+ return result;
+ }
+
+ /**
+ * Validate the resource.
+ *
+ * @param resource
+ * The resource to be validated.
+ * @param kind
+ * The kind of resource change, see IResourceDelta for values.
+ * @param operation
+ * The operation that this validation is running under. This can
+ * be null.
+ * @param monitor
+ * A way to report progress. This can be null.
+ *
+ * @return the result of doing the validation, it can be, but usually isn't
+ * null.
+ */
+ public abstract ValidationResult validate(IResource resource, int kind, ValOperation operation, IProgressMonitor monitor);
+
+ /**
+ * Validate the resource.
+ *
+ * @param resource
+ * The resource to be validated.
+ * @param kind
+ * The kind of resource change, see IResourceDelta for values.
+ * @param operation
+ * The operation that this validation is running under. This can
+ * be null.
+ * @param monitor
+ * A way to report progress. This can be null.
+ * @param event
+ * An event that describes in more detail what should be
+ * validated and why it should be validated. This can be null.
+ *
+ * @return the result of doing the validation, it can be, but usually isn't
+ * null.
+ */
+ public ValidationResult validate(IResource resource, int kind, ValOperation operation, IProgressMonitor monitor, ValidationEvent event){
+ // The reason that the resource and kind are still specified, is that I didn't want to remove a public method in the service
+ // stream.
+ return validate(resource, kind, operation, monitor);
+ }
+
+ /**
+ * This method will be called before any validation takes place. It allows validators to perform any
+ * initialization that they might need.
+ *
+ * @param project the project that is being validated. For the very first call in the validation phase,
+ * this will be null. That is the signal to the validator that a top level validation is starting.
+ * Subsequently, the project will be set, as each of the individual projects are validated.
+ *
+ * @param state a way to pass arbitrary, validator specific, data from one invocation of a validator to
+ * the next, during the validation phase.
+ *
+ * @param monitor the monitor that should be used for reporting progress if the clean takes a long time.
+ */
+ public void validationStarting(IProject project, ValidationState state, IProgressMonitor monitor){
+ // subclasses need to override this, if they wish to let their validators know about this event
+ }
+
+ /**
+ * This method will be called when validation is complete. It allows validators to perform any
+ * cleanup that they might need to do.
+ *
+ * @param project the project that was validated. The very last call in the validation will set this to
+ * null so that the validator knows that all the projects have now been validated.
+ *
+ * @param state a way to pass arbitrary, validator specific, data from one invocation of a validator to
+ * the next, during the validation phase.
+ *
+ * @param monitor the monitor that should be used for reporting progress if the clean takes a long time.
+ */
+ public void validationFinishing(IProject project, ValidationState state, IProgressMonitor monitor){
+ // subclasses need to override this, if they wish to let their validators know about this event
+ }
+
+ void add(MessageSeveritySetting message){
+ // I can't use getMessageSettings() here, as that will put us into an infinite loop
+ if (_messageSettings == null){
+ _messageSettings = new HashMap<String, MessageSeveritySetting>(10);
+ }
+ _messageSettings.put(message.getId(), message);
+ bumpChangeCountMessages();
+ }
+
+ public IValidator asIValidator(){
+ return null;
+ }
+
+ protected abstract boolean shouldValidate(IResource resource, ContentTypeWrapper contentTypeWrapper);
+ protected abstract boolean shouldValidateProject(IProject project);
+
+ public abstract String getId();
+
+ public MessageSeveritySetting getMessage(String id){
+ return getMessageSettings().get(id);
+ }
+
+ /**
+ * Answer all the message settings that this validator has defined.
+ *
+ * @return an empty map if the validator did not define any message settings.
+ */
+ public Map<String, MessageSeveritySetting> getMessageSettings(){
+ Map<String, MessageSeveritySetting> settings = _messageSettings;
+ if (settings == null){
+ settings = new HashMap<String, MessageSeveritySetting>(10);
+ init(settings);
+ if (ValManager.getDefault().mustUseGlobalValidators(getProject())){
+ ValPrefManagerGlobal gp = ValPrefManagerGlobal.getDefault();
+ gp.loadMessages(this, settings);
+ }
+ else {
+ ValPrefManagerProject vp = new ValPrefManagerProject(getProject());
+ vp.loadMessages(this, settings);
+ }
+ _messageSettings = settings;
+ }
+ return settings;
+ }
+
+ /**
+ * Answer a hash code for the configurable fields so that we can quickly determine if two
+ * validators are the same.
+ */
+ public int hashCodeForConfig(){
+ int h = 0;
+ if (_buildValidation)h += 101;
+ if (_delegatingId != null)h += _delegatingId.hashCode();
+ if (_manualValidation)h += 201;
+ if (_messageSettings != null){
+ for (MessageSeveritySetting ms : _messageSettings.values())h += ms.hashCode();
+ }
+ if (_sourceId != null)h += _sourceId.hashCode();
+ h += _version;
+ return h;
+ }
+
+ private void init(Map<String, MessageSeveritySetting> settings) {
+ for (MessageSeveritySetting ms : ValidatorExtensionReader.getDefault().addMessages(this)){
+ settings.put(ms.getId(), ms);
+ }
+ }
+
+ public abstract String getName();
+
+ /**
+ * Answer the project that you were enabled on.
+ *
+ * @return null if you are a global (i.e. workspace level) validator.
+ */
+ public IProject getProject(){
+ return _project;
+ }
+
+ /**
+ * Answer the name of the class that implements the validator.
+ */
+ public abstract String getValidatorClassname();
+
+ /**
+ * Is this validator currently enabled for validations that are triggered manually?
+ */
+ public boolean isManualValidation() {
+ return _manualValidation;
+ }
+
+ /**
+ * Set whether this validator should be triggered as part of a manual validation.
+ *
+ * @param manualValidation
+ * @return true if the setting changed.
+ */
+ public boolean setManualValidation(boolean manualValidation) {
+ return setManualValidation2(manualValidation);
+ }
+
+ protected final boolean setManualValidation2(boolean manualValidation) {
+ boolean changed = false;
+ if (_manualValidation != manualValidation){
+ bumpChangeCountGlobal();
+ changed = true;
+ _manualValidation = manualValidation;
+ }
+ return changed;
+ }
+
+ /**
+ * Is this validator currently enabled for validations that are triggered by builds?
+ */
+ public boolean isBuildValidation() {
+ return _buildValidation;
+ }
+
+ /**
+ * Has the validator changed since it was last created or copied? Or was it migrated from an earlier version.
+ */
+ public boolean isChanged(){
+ if (_changeCountGlobal > 0 || _changeCountMessages > 0 || _migrated)return true;
+ return false;
+ }
+
+ /**
+ * Has the validator's implementation been loaded yet? This is used by some test cases to ensure that
+ * plug-ins are not loaded too early.
+ */
+ abstract boolean isLoaded();
+
+
+ /**
+ * Set whether this validator should be triggered by the build process.
+ *
+ * @param buildValidation
+ * @return true if the setting changed.
+ */
+ public boolean setBuildValidation(boolean buildValidation) {
+ return setBuildValidation2(buildValidation);
+ }
+
+ protected final boolean setBuildValidation2(boolean buildValidation) {
+ boolean changed = false;
+ if (_buildValidation != buildValidation){
+ bumpChangeCountGlobal();
+ changed = true;
+ _buildValidation = buildValidation;
+ }
+ return changed;
+ }
+
+ /**
+ * Get the id of the "real" validator, that is the validator that will be called when this delegating
+ * validator is asked to validate something. If this isn't a delegating validator answer null.
+ */
+ public String getDelegatingId() {
+ return _delegatingId;
+ }
+
+ /**
+ * Set the id of the "real" validator, that is the validator that will be called when this delegating
+ * validator is asked to validate something.
+ *
+ * @param delegating the id of the validator that is actually going to perform the validation.
+ */
+ public void setDelegatingId(String delegating) {
+ if (!Misc.same(_delegatingId, delegating)){
+ _delegatingId = delegating;
+ bumpChangeCountGlobal();
+ }
+ }
+
+ public int getVersion() {
+ return _version;
+ }
+
+ public void setVersion(int version) {
+ if (_version != version){
+ _version = version;
+ bumpChangeCountGlobal();
+ }
+ }
+
+ @Override
+ public String toString() {
+ return getName();
+ }
+
+/**
+ * A validator that uses version 1 of the validation framework.
+ * @author karasiuk
+ *
+ */
+public static class V1 extends Validator {
+ private ValidatorMetaData _vmd;
+
+ /**
+ * Create a new version 1 validator.
+ * @param vmd
+ * @param config this is used to set the global enablement options. In some case this can be null.
+ */
+ public V1(ValidatorMetaData vmd, ValidationConfiguration config, IProject project){
+ super(project);
+ _vmd = vmd;
+ if (config != null){
+ setBuildValidation(config.isBuildEnabled(vmd));
+ setManualValidation(config.isManualEnabled(vmd));
+ }
+ setDelegatingId(ValidatorDelegatesRegistry.getInstance().getDefaultDelegate(_vmd.getValidatorUniqueName()));
+ if (_vmd.getMarkerIds() != null && _vmd.getMarkerIds().length > 0)setMarkerId(_vmd.getMarkerIds()[0]);
+ resetChangeCounters();
+ }
+
+ @Override
+ public IValidator asIValidator() {
+ IValidator v = null;
+ try {
+ v = _vmd.getValidator();
+ }
+ catch (InstantiationException e){
+ ValidationPlugin.getPlugin().handleException(e);
+ return null;
+ }
+ return v;
+ }
+
+ public V1 asV1Validator() {
+ return this;
+ }
+
+ public Validator copy(boolean includeChangeCounts) {
+ V1 v = new V1Copy(_vmd, null, _project);
+ v.copyLocal(this, includeChangeCounts);
+
+ return v;
+ }
+
+ public String getName() {
+ return _vmd.getValidatorDisplayName();
+ }
+
+ public ValidatorMetaData getVmd(){
+ return _vmd;
+ }
+
+ public String getValidatorClassname(){
+ String name = ""; //$NON-NLS-1$
+ try {
+ name = _vmd.getValidator().getClass().getName();
+ }
+ catch (Exception e){
+ // eat it
+ }
+ return name;
+ }
+ public String getId() {
+ return _vmd.getValidatorUniqueName();
+ }
+
+ @Override
+ boolean isLoaded() {
+ return _vmd.isActive();
+ }
+
+ @Override
+ public boolean setBuildValidation(boolean buildValidation) {
+ boolean changed = super.setBuildValidation(buildValidation);
+ _vmd.setBuildValidation(buildValidation);
+ return changed;
+ }
+
+ @Override
+ public boolean setManualValidation(boolean manualValidation) {
+ boolean changed = super.setManualValidation(manualValidation);
+ _vmd.setManualValidation(manualValidation);
+ return changed;
+ }
+
+ @Override
+ protected boolean shouldValidate(IResource resource, ContentTypeWrapper contentTypeWrapper) {
+ return _vmd.isApplicableTo(resource);
+ }
+
+ @Override
+ protected boolean shouldValidateProject(IProject project) {
+ // TODO determine if this can be optimized
+ return true;
+ }
+
+ @Override
+ public ValidationResult validate(IResource resource, int kind, ValOperation operation,
+ IProgressMonitor monitor) {
+
+ if (monitor == null)monitor = new NullProgressMonitor();
+
+ ValidationResult vr = new ValidationResult();
+ IValidator v = asIValidator();
+ if (v == null)return null;
+
+ try {
+ IProject project = resource.getProject();
+ SummaryReporter reporter = new SummaryReporter(project, monitor);
+ IWorkbenchContext helper = _vmd.getHelper(project);
+ if (helper instanceof WorkbenchContext){
+ WorkbenchContext wc = (WorkbenchContext)helper;
+ List<String> files = new LinkedList<String>();
+ // [213631] The JSP validator expects full paths not relative paths, but the XML validator
+ // expects relative paths.
+ files.add(wc.getPortableName(resource));
+ wc.setValidationFileURIs(files);
+ }
+ try {
+ ValidatorLauncher.getLauncher().start(helper, v, reporter);
+ }
+ finally {
+ try {
+ v.cleanup(reporter);
+ }
+ finally {
+ helper.cleanup(reporter);
+ }
+ }
+
+ vr.incrementError(reporter.getSeverityHigh());
+ vr.incrementWarning(reporter.getSeverityNormal());
+ vr.incrementInfo(reporter.getSeverityLow());
+
+ }
+ catch (Exception e){
+ ValidationPlugin.getPlugin().handleException(e);
+ }
+ return vr;
+ }
+
+ /*
+ * GRK - Because I didn't want to try to make a true copy of the V1 validator, (because I didn't
+ * want to copy the vmd object), I came up with this approach to only copy the fields that
+ * the preference page was worried about.
+ */
+ public final static class V1Copy extends V1 {
+ public V1Copy(ValidatorMetaData vmd, ValidationConfiguration vc, IProject project){
+ super(vmd, vc, project);
+ }
+
+ @Override
+ public boolean setManualValidation(boolean bool) {
+ return setManualValidation2(bool);
+ }
+
+ @Override
+ public boolean setBuildValidation(boolean bool) {
+ return setBuildValidation2(bool);
+ }
+
+ }
+
+}
+
+/**
+ * A validator that uses version 2 of the validation framework.
+ * @author karasiuk
+ *
+ */
+public final static class V2 extends Validator implements IAdaptable {
+ private AbstractValidator _validator;
+
+ private List<FilterGroup> _groups = new LinkedList<FilterGroup>();
+ private FilterGroup[] _groupsArray;
+
+ /** The full id of the extension. */
+ private String _id;
+
+ /** Name of the validator. */
+ private String _name;
+
+ /**
+ * We don't want to create the validator too early, as it may trigger new plug-ins to be loaded.
+ * We delay that as long as possible, by starting with just the config element.
+ */
+ private IConfigurationElement _validatorConfigElement;
+
+ private String _validatorClassName;
+
+ /**
+ * An array containing the validator group IDs for which this validator is a member.
+ */
+ private String[] _validatorGroupIds;
+
+ /**
+ * If this validator is a delegating validator, then this is the "real" validator (i.e. the one that
+ * does the work).
+ */
+ private AbstractValidator _delegated;
+
+ /** How many times has a group field in this validator been changed since it was created (or copied)? */
+ protected transient int _changeCountGroups;
+
+ private Level _level;
+
+ /**
+ * Do we still need to invoke the validateStarting method for this validator, for the null project?
+ *
+ * Because we do not want to activate a validator's plug-in too soon, we do not activate the validator
+ * as a reaction to the global validation starting event. Instead we mark it pending, and wait until
+ * we are sure that we have something to validate.
+ *
+ * If this flag is true, it means that the validateStarting method still needs to be called for this validator.
+ */
+ private AtomicBoolean _pendingValidationStarted = new AtomicBoolean();
+
+ V2(IConfigurationElement configElement, IProject project){
+ super(project);
+ assert configElement != null;
+ _validatorConfigElement = configElement;
+ _validatorClassName = configElement.getAttribute(ExtensionConstants.AttribClass);
+
+ IConfigurationElement[] groupReferenceElements = configElement.getChildren(ExtensionConstants.Group.elementGroup);
+ List<String> validatorGroupIDs = new ArrayList<String>();
+ for (IConfigurationElement groupElement : groupReferenceElements) {
+ String id = groupElement.getAttribute(ExtensionConstants.Group.attId);
+ if (id != null)validatorGroupIDs.add(id);
+ }
+ _validatorGroupIds = validatorGroupIDs.toArray(new String[validatorGroupIDs.size()]);
+
+ init();
+ }
+
+ private V2(IProject project, String validatorClassName, AbstractValidator validator){
+ super(project);
+ assert validator != null;
+
+ _validatorClassName = validatorClassName;
+ _validator = validator;
+ init();
+ }
+
+ private void init(){
+ try {
+ String id = ConfigurationManager.getManager().getConfiguration(_project).getDelegateForTarget(_validatorClassName);
+ if (id == null) id = ValidatorDelegatesRegistry.getInstance().getDefaultDelegate(_validatorClassName);
+ setDelegatingId(id);
+ }
+ catch (InvocationTargetException e){
+ ValidationPlugin.getPlugin().handleException(e);
+ }
+ resetChangeCounters();
+ }
+
+ public synchronized void add(FilterGroup fg) {
+ assert fg != null;
+ _groupsArray = null;
+ _groups.add(fg);
+ bumpChangeCountGroups();
+ }
+
+ @Override
+ public IValidator asIValidator() {
+ AbstractValidator av = getDelegatedValidator();
+ if (av instanceof IValidator)return (IValidator)av;
+ return super.asIValidator();
+ }
+
+ @Override
+ public V2 asV2Validator() {
+ return this;
+ }
+
+ /**
+ * Let the validator know that a clean is about to happen.
+ *
+ * @param project the project that is being cleaned. This can be null which means that the workspace
+ * is being cleaned (in which case a separate call will be made for each open project).
+ *
+ */
+ @Override
+ public void clean(IProject project, ValOperation operation, IProgressMonitor monitor) {
+ getDelegatedValidator().clean(project, operation.getState(), monitor);
+ }
+
+ @Override
+ public Validator copy(boolean includeChangeCounts) {
+ V2 v = null;
+ if (_validatorConfigElement != null)v = new V2(_validatorConfigElement, _project);
+ else v = new V2(_project, _validatorClassName, _validator);
+ v.copyLocal(this, includeChangeCounts);
+
+ if (includeChangeCounts)v._changeCountGroups = _changeCountGroups;
+
+ FilterGroup[] groups = getGroups();
+ v._groupsArray = new FilterGroup[groups.length];
+ for (int i=0; i<groups.length; i++){
+ v._groupsArray[i] = groups[i];
+ v._groups.add(groups[i]);
+ }
+
+ v._id = _id;
+ v._name = _name;
+ v._validatorGroupIds = _validatorGroupIds;
+ v._pendingValidationStarted = _pendingValidationStarted;
+
+ return v;
+ }
+
+ public int getChangeCountGroups(){
+ return _changeCountGroups;
+ }
+
+ public void bumpChangeCountGroups(){
+ _changeCountGroups++;
+ }
+
+ public Level getLevel() {
+ return _level;
+ }
+
+ public void setLevel(Level level) {
+ assert _level == null;
+ _level = level;
+ }
+
+ /**
+ * Answer the actual validator that is going to perform the validation. If this is a normal validator this
+ * method will simply answer itself. However if this is a delegating validator, then this will answer the
+ * "real" validator.
+ */
+ public AbstractValidator getDelegatedValidator(){
+ AbstractValidator delegated = _delegated;
+ if (delegated != null)return delegated;
+ else if (getDelegatingId() == null)return getValidator();
+ try {
+ ValidatorDelegateDescriptor vdd = ValidatorDelegatesRegistry.getInstance()
+ .getDescriptor(getValidatorClassname(), getDelegatingId());
+ if (vdd == null)return getValidator();
+ delegated = vdd.getValidator2();
+ }
+ catch (Exception e){
+ ValidationPlugin.getPlugin().handleException(e);
+ delegated = new NullValidator();
+ }
+ delegated.setParent(this);
+ _delegated = delegated;
+ return delegated;
+ }
+
+ @Override
+ public String getId() {
+ return _id;
+ }
+
+ /**
+ * Answer the validator's filter groups.
+ * @return an empty array if the validator does not have any filter groups.
+ */
+ public synchronized FilterGroup[] getGroups(){
+ FilterGroup[] groups = _groupsArray;
+ if (groups == null){
+ groups = new FilterGroup[_groups.size()];
+ _groups.toArray(groups);
+ _groupsArray = groups;
+ }
+ return groups;
+ }
+
+ @Override
+ public String getName() {
+ return _name;
+ }
+
+ public AbstractValidator getValidator() {
+ if (_validator == null){
+ try {
+ _validator = (AbstractValidator)_validatorConfigElement.createExecutableExtension(ExtensionConstants.AttribClass);
+ }
+ catch (Exception e){
+ ValidationPlugin.getPlugin().handleException(e);
+ IContributor contrib = _validatorConfigElement.getContributor();
+ String message = NLS.bind(ValMessages.ErrConfig, contrib.getName());
+ ValidationPlugin.getPlugin().logMessage(IStatus.ERROR, message);
+ _validator = new NullValidator();
+ }
+ _validator.setParent(this);
+ _validatorConfigElement = null;
+
+ }
+ return _validator;
+ }
+
+ @Override
+ public String getValidatorClassname(){
+ return _validatorClassName;
+ }
+
+ public String[] getValidatorGroups(){
+ return _validatorGroupIds;
+ }
+
+ @Override
+ public int hashCodeForConfig() {
+ int h = super.hashCodeForConfig();
+ if (_id != null)h += _id.hashCode();
+ if (_groups != null){
+ for (FilterGroup fg : _groups)h += fg.hashCodeForConfig();
+ }
+ return h;
+ }
+
+ @Override
+ public boolean isChanged() {
+ if (_changeCountGroups > 0)return true;
+ return super.isChanged();
+ }
+
+ @Override
+ boolean isLoaded() {
+ return _validator != null;
+ }
+
+ @Override
+ public boolean shouldClearMarkers(ValidationEvent event) {
+ return getValidator().shouldClearMarkers(event);
+ }
+
+ /**
+ * Answer true if this validator, based on it's filters, should validate this resource.
+ *
+ * @return true if the resource should be validated.
+ */
+ @Override
+ protected boolean shouldValidate(IResource resource, ContentTypeWrapper contentTypeWrapper) {
+ FilterGroup[] groups = getGroups();
+ IProject project = resource.getProject();
+ for (FilterGroup group : groups){
+ if (!group.shouldValidate(project, resource, contentTypeWrapper))return false;
+ }
+ return true;
+ }
+
+
+ @Override
+ public void setDelegatingId(String delegating) {
+ super.setDelegatingId(delegating);
+ _delegated = null;
+ }
+
+ public synchronized void setGroups(List<FilterGroup> groups){
+ _groups = groups;
+ _groupsArray = null;
+ bumpChangeCountGroups();
+ }
+
+ public void setId(String id) {
+ if (!Misc.same(_id, id)){
+ _id = id;
+ bumpChangeCountGlobal();
+ }
+ }
+
+ public void setName(String name) {
+ if (!Misc.same(_name, name)){
+ _name = name;
+ bumpChangeCountGlobal();
+ }
+ }
+
+ @Override
+ public ValidationResult validate(IResource resource, int kind, ValOperation operation, IProgressMonitor monitor){
+ return validate(resource, kind, operation, monitor, null);
+ }
+
+ @Override
+ public ValidationResult validate(IResource resource, int kind, ValOperation operation, IProgressMonitor monitor, ValidationEvent event) {
+ ValidationResult vr = null;
+ if (operation == null)operation = new ValOperation();
+ if (monitor == null)monitor = new NullProgressMonitor();
+ try {
+ if (event == null)event = new ValidationEvent(resource, kind, null);
+ vr = getDelegatedValidator().validate(event, operation.getState(), monitor);
+ if (vr == null)vr = getDelegatedValidator().validate(resource, kind, operation.getState(), monitor);
+ }
+ catch (Exception e){
+ try {
+ String msg = NLS.bind(ValMessages.LogValEnd, getName(), resource.getLocationURI());
+ ValidationPlugin.getPlugin().logMessage(IStatus.ERROR, msg);
+ }
+ catch (Exception e2 ){
+ // ignore it
+ }
+ ValidationPlugin.getPlugin().handleException(e);
+ }
+
+ if (vr != null){
+ if (vr.getValidationException() != null){
+ ValidationPlugin.getPlugin().handleException(vr.getValidationException());
+ }
+ updateResults(vr);
+ if (vr.getDependsOn() != null){
+ ValidationFramework.getDefault().getDependencyIndex().set(getId(), resource, vr.getDependsOn());
+ }
+ IResource[] validated = vr.getValidated();
+ if (validated != null){
+ for (int i=0; i<validated.length; i++){
+ operation.addValidated(getId(), validated[i]);
+ }
+ }
+
+ ValidatorMessage[] msgs = vr.getMessages();
+// if (sanityTest(msgs.length, resource)){
+ MarkerManager mm = MarkerManager.getDefault();
+ for (ValidatorMessage m : msgs){
+ mm.createMarker(m, getId());
+ }
+// }
+// else {
+// setBuildValidation(false);
+// setManualValidation(false);
+// }
+ }
+ return vr;
+ }
+
+ /**
+ * Perform a simple sanity test to ensure that the validator is configured correctly.
+ * @param numberofMessages number of messages that the validator produced.
+ * @return true if the test passed
+ */
+// private boolean sanityTest(int numberofMessages, IResource resource) {
+// if (numberofMessages < 201)return true;
+//
+// String resName = ""; //$NON-NLS-1$
+// if (resource != null)resName = resource.getName();
+// String message = NLS.bind(ValMessages.ConfigError, new Object[]{
+// getName(), getId(), String.valueOf(numberofMessages), resName});
+// ValidationPlugin.getPlugin().logMessage(IStatus.ERROR, message);
+//
+// return false;
+// }
+
+ /**
+ * If the validator is using a report helper then update it with any of the messages that were
+ * added directly to the validation result.
+ * @param vr
+ */
+ private void updateResults(ValidationResult vr) {
+ ReporterHelper rh = vr.getReporterHelper();
+ if (rh == null)return;
+ ClassLoader classloader = getDelegatedValidator().getClass().getClassLoader();
+ for (IMessage message : rh.getMessages()){
+ Object target = message.getTargetObject();
+ if (target != null){
+ IResource res = null;
+ if (target instanceof IResource)res = (IResource)target;
+ if (res == null){
+ target = message.getAttribute(IMessage.TargetResource);
+ if (target != null && target instanceof IResource)res = (IResource)target;
+ }
+ if (res != null){
+
+ ValidatorMessage vm = ValidatorMessage.create(message.getText(classloader), res);
+ if (getMarkerId() != null)vm.setType(getMarkerId());
+ vr.add(vm);
+ int markerSeverity = IMarker.SEVERITY_INFO;
+ int sev = message.getSeverity();
+ if ((sev & IMessage.HIGH_SEVERITY) != 0)markerSeverity = IMarker.SEVERITY_ERROR;
+ else if ((sev & IMessage.NORMAL_SEVERITY) != 0)markerSeverity = IMarker.SEVERITY_WARNING;
+ vm.setAttribute(IMarker.SEVERITY, markerSeverity);
+ vm.setAttribute(IMarker.LINE_NUMBER, message.getLineNumber());
+ int offset = message.getOffset();
+ if (offset != IMessage.OFFSET_UNSET){
+ vm.setAttribute(IMarker.CHAR_START, offset);
+ int len = message.getLength();
+ if (len != IMessage.OFFSET_UNSET){
+ vm.setAttribute(IMarker.CHAR_START, offset);
+ vm.setAttribute(IMarker.CHAR_END, offset+len);
+ }
+ }
+ String groupName = message.getGroupName();
+ if (groupName != null){
+ vm.setAttribute(ConfigurationConstants.VALIDATION_MARKER_GROUP, groupName);
+ }
+
+ copyAttributes(message, vm);
+ }
+ }
+ }
+ }
+
+ @SuppressWarnings("unchecked")
+ private void copyAttributes(IMessage message, ValidatorMessage vm) {
+ // I made this a separate method, so that I could localize the suppression of unchecked warnings.
+ Map attributes = message.getAttributes();
+ if (attributes != null){
+ for (Iterator it = attributes.entrySet().iterator(); it.hasNext();){
+ Map.Entry me = (Map.Entry)it.next();
+ String key = (String)me.getKey();
+ vm.setAttribute(key, me.getValue());
+ }
+ }
+ }
+
+ @Override
+ public void validationStarting(IProject project, ValidationState state, IProgressMonitor monitor) {
+ if (project == null)_pendingValidationStarted.set(true);
+ else {
+ AbstractValidator val = getDelegatedValidator();
+ if (_pendingValidationStarted.getAndSet(false)){
+ val.validationStarting(null, state, monitor);
+ }
+ val.validationStarting(project, state, monitor);
+ }
+ }
+
+ @Override
+ public void validationFinishing(IProject project, ValidationState state, IProgressMonitor monitor) {
+ if (project == null){
+ if (!_pendingValidationStarted.getAndSet(false))getDelegatedValidator().validationFinishing(null, state, monitor);
+ }
+ else getDelegatedValidator().validationFinishing(project, state, monitor);
+ }
+
+ @SuppressWarnings("unchecked")
+ public Object getAdapter(Class adapter) {
+ return Platform.getAdapterManager().getAdapter(this, adapter);
+ }
+
+ public synchronized void remove(FilterGroup group) {
+ _groups.remove(group);
+ _groupsArray = null;
+ bumpChangeCountGroups();
+ }
+
+ @Override
+ public void resetChangeCounters() {
+ super.resetChangeCounters();
+ _changeCountGroups = 0;
+ }
+
+ @Override
+ protected boolean shouldValidateProject(IProject project) {
+ FilterGroup[] groups = getGroups();
+ ContentTypeWrapper ctw = new ContentTypeWrapper();
+ for (FilterGroup group : groups){
+ if (!group.shouldValidate(project, null, ctw))return false;
+ }
+ return true;
+ }
+
+ public synchronized void replaceFilterGroup(FilterGroup existing, FilterGroup merged) {
+ remove(existing);
+ add(merged);
+ }
+
+}
+
+public String getSourceId() {
+ return _sourceId;
+}
+
+public void setSourceId(String sourceId) {
+ if (!Misc.same(_sourceId, sourceId)){
+ _sourceId = sourceId;
+ bumpChangeCountGlobal();
+ }
+}
+
+
+void setMessages(Map<String, MessageSeveritySetting> map) {
+ _messageSettings = map;
+ bumpChangeCountMessages();
+}
+
+public int getChangeCountGlobal() {
+ return _changeCountGlobal;
+}
+
+public boolean hasGlobalChanges(){
+ return _migrated || _changeCountGlobal > 0;
+}
+
+public int getChangeCountMessages() {
+ return _changeCountMessages;
+}
+
+public void bumpChangeCountMessages(){
+ _changeCountMessages++;
+}
+
+public void resetChangeCounters() {
+ _changeCountGlobal = 0;
+ _changeCountMessages = 0;
+}
+
+public void bumpChangeCountGlobal(){
+ _changeCountGlobal++;
+}
+
+/**
+ * Answer true if you have the same configuration settings as validator.
+ * @param validator this can be null.
+ */
+public boolean sameConfig(Validator validator) {
+ if (validator == null)return false;
+ return hashCodeForConfig() == validator.hashCodeForConfig();
+}
+
+public String getMarkerId() {
+ return _markerId;
+}
+
+public void setMarkerId(String markerId) {
+ _markerId = markerId;
+ if (markerId != null)MarkerManager.getDefault().getMarkers().add(markerId);
+}
+
+}
diff --git a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/ValidatorMessage.java b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/ValidatorMessage.java
new file mode 100644
index 0000000..b8146dc
--- /dev/null
+++ b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/ValidatorMessage.java
@@ -0,0 +1,295 @@
+/*******************************************************************************
+ * Copyright (c) 2007, 2008 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.wst.validation;
+
+
+import java.util.HashMap;
+import java.util.Map;
+
+import org.eclipse.core.resources.IMarker;
+import org.eclipse.core.resources.IResource;
+import org.eclipse.core.runtime.Assert;
+import org.eclipse.wst.validation.internal.Tracing;
+import org.eclipse.wst.validation.internal.ValConstants;
+import org.eclipse.wst.validation.internal.plugin.ValidationPlugin;
+
+/**
+ * This class provides a way for a validator to return messages, that are easily
+ * converted into IMarkers.
+ * <p>
+ * This class is completely optional for validators. A validator can choose to
+ * directly manage IMarkers. However, some validators want to be used in
+ * multiple contexts, for example as-you-type validation and build based
+ * validation. For these types of validators it is not possible for them to use
+ * only IMarkers, because often the Resource has not been saved yet.
+ * </p>
+ * <p>
+ * <b>Provisional API:</b> This class/interface is part of an interim API that
+ * is still under development and expected to change significantly before
+ * reaching stability. It is being made available at this early stage to solicit
+ * feedback from pioneering adopters on the understanding that any code that
+ * uses this API will almost certainly be broken (repeatedly) as the API
+ * evolves.
+ * </p>
+ */
+public class ValidatorMessage {
+
+ public static final String ValidationId = "ValidationId"; //$NON-NLS-1$
+
+ /** Associate some arbitrary attributes with a message. */
+ private final Map<String, Object> _map = new HashMap<String, Object>(5);
+
+ private IResource _resource;
+
+ /** The type of marker. */
+ private String _type;
+
+ /**
+ * Create a new validation message.
+ *
+ * @param message
+ * The localized message that will be displayed to the user.
+ *
+ * @param resource
+ * The resource that the message is associated with.
+ */
+ public static ValidatorMessage create(String message, IResource resource){
+ ValidatorMessage msg = new ValidatorMessage();
+ msg._type = ValConstants.ProblemMarker;
+ msg._resource = resource;
+ msg.setAttribute(IMarker.MESSAGE, ValidationPlugin.getPlugin().isDebugging() ?
+ Tracing.timestampIt(message): message);
+ return msg;
+ }
+
+ private ValidatorMessage(){}
+
+ /**
+ * Answer a copy of yourself.
+ */
+ public ValidatorMessage asCopy(){
+ ValidatorMessage msg = new ValidatorMessage();
+ msg._resource = _resource;
+ msg._type = _type;
+ msg._map.putAll(_map);
+ return msg;
+ }
+
+ /**
+ * Returns the attribute with the given name. The result is an instance of
+ * one of the following classes: <code>String</code>, <code>Integer</code>,
+ * or <code>Boolean</code>. Returns <code>null</code> if the attribute is
+ * undefined.
+ *
+ * @param attributeName
+ * The name of the attribute.
+ * @return the value, or <code>null</code> if the attribute is undefined.
+ */
+ public Object getAttribute(String attributeName){
+ return _map.get(attributeName);
+ }
+
+ /**
+ * Returns the integer valued attribute with the given name. Returns the
+ * given default value if the attribute is undefined or the marker does not
+ * exist or is not an integer value.
+ *
+ * @param attributeName
+ * The name of the attribute.
+ * @param defaultValue
+ * The value to use if no integer value is found.
+ * @return the value or the default value if no integer value was found.
+ */
+ public int getAttribute(String attributeName, int defaultValue){
+ Integer value = null;
+ try {
+ value = (Integer)_map.get(attributeName);
+ }
+ catch (Exception e){
+ // eat it
+ }
+ if (value == null)return defaultValue;
+ return value.intValue();
+ }
+
+ /**
+ * Returns the string valued attribute with the given name. Returns the
+ * given default value if the attribute is undefined or the marker does not
+ * exist or is not a string value.
+ *
+ * @param attributeName
+ * The name of the attribute.
+ * @param defaultValue
+ * The value to use if no value is found.
+ * @return the value or the default value if no value was found.
+ */
+ public String getAttribute(String attributeName, String defaultValue){
+ String value = null;
+ try {
+ value = (String)_map.get(attributeName);
+ }
+ catch (Exception e){
+ // eat it
+ }
+ if (value == null)return defaultValue;
+ return value;
+
+ }
+
+ /**
+ * Returns the boolean valued attribute with the given name. Returns the
+ * given default value if the attribute is undefined or the marker does not
+ * exist or is not a boolean value.
+ *
+ * @param attributeName
+ * The name of the attribute.
+ * @param defaultValue
+ * The value to use if no value is found.
+ * @return the value or the default value if no value was found.
+ */
+ public boolean getAttribute(String attributeName, boolean defaultValue){
+ Boolean value = null;
+ try {
+ value = (Boolean)_map.get(attributeName);
+ }
+ catch (Exception e){
+ // eat it
+ }
+ if (value == null)return defaultValue;
+ return value.booleanValue();
+
+ }
+
+ /**
+ * Returns a map with all the attributes for the marker. If the marker has
+ * no attributes then <code>null</code> is returned.
+ *
+ * @return a map of attribute keys and values (key type :
+ * <code>String</code> value type : <code>String</code>,
+ * <code>Integer</code>, or <code>Boolean</code>) or <code>null</code>.
+ */
+ @SuppressWarnings("unchecked")
+ public Map getAttributes() {
+ return _map;
+ }
+
+ /**
+ * Returns the resource with which this marker is associated.
+ *
+ * @return the resource with which this marker is associated
+ */
+ public IResource getResource(){
+ return _resource;
+ }
+
+ /**
+ * Returns the type of this marker. The returned marker type will not be
+ * <code>null</code>.
+ *
+ * @return the type of this marker
+ */
+ public String getType() {
+ return _type;
+ }
+
+ /**
+ * Sets the marker type.
+ *
+ * @param type The marker id to use when creating new markers.
+ */
+ public void setType(String type){
+ assert type != null;
+ _type = type;
+ }
+
+ /**
+ * Sets the integer valued attribute with the given name.
+ * <p>
+ * This method changes resources; these changes will be reported in a
+ * subsequent resource change event, including an indication that this
+ * marker has been modified.
+ * </p>
+ *
+ * @param attributeName
+ * The name of the attribute.
+ * @param value
+ * The value.
+ */
+ public void setAttribute(String attributeName, int value){
+ _map.put(attributeName, new Integer(value));
+
+ }
+
+ /**
+ * Sets the attribute with the given name. The value must be
+ * <code>null</code> or an instance of one of the following classes:
+ * <code>String</code>, <code>Integer</code>, or <code>Boolean</code>.
+ *
+ * @param attributeName
+ * The name of the attribute.
+ * @param value
+ * The value, or <code>null</code> if the attribute is to be undefined.
+ */
+ public void setAttribute(String attributeName, Object value){
+ _map.put(attributeName, value);
+ }
+
+ /**
+ * Sets the boolean valued attribute with the given name.
+ *
+ * @param attributeName
+ * The name of the attribute.
+ * @param value
+ * The value.
+ */
+ public void setAttribute(String attributeName, boolean value){
+ _map.put(attributeName, value ? Boolean.TRUE : Boolean.FALSE);
+ }
+
+ /**
+ * Sets the given attribute key-value pairs on this marker. The values must
+ * be <code>null</code> or an instance of one of the following classes:
+ * <code>String</code>, <code>Integer</code>, or <code>Boolean</code>. If a
+ * value is <code>null</code>, the new value of the attribute is considered
+ * to be undefined.
+ *
+ * @param attributeNames
+ * An array of attribute names.
+ * @param values
+ * An array of attribute values.
+ */
+ public void setAttributes(String[] attributeNames, Object[] values){
+ Assert.isTrue(attributeNames.length == values.length);
+ for (int i=0; i<attributeNames.length; i++){
+ setAttribute(attributeNames[i], values[i]);
+ }
+ }
+
+ /**
+ * Sets the attributes for this marker to be the ones contained in the given
+ * table. The values must be an instance of one of the following classes:
+ * <code>String</code>, <code>Integer</code>, or <code>Boolean</code>.
+ * Attributes previously set on the marker but not included in the given map
+ * are considered to be removals. Setting the given map to be
+ * <code>null</code> is equivalent to removing all marker attributes.
+ *
+ * @param attributes
+ * A map of attribute names to attribute values (key type :
+ * <code>String</code> value type : <code>String</code>,
+ * <code>Integer</code>, or <code>Boolean</code>) or <code>null</code>.
+ */
+ public void setAttributes(Map<String, Object> attributes) {
+ _map.clear();
+ _map.putAll(attributes);
+
+ }
+
+}
diff --git a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/ContentTypeWrapper.java b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/ContentTypeWrapper.java
new file mode 100644
index 0000000..2436c84
--- /dev/null
+++ b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/ContentTypeWrapper.java
@@ -0,0 +1,43 @@
+package org.eclipse.wst.validation.internal;
+
+import org.eclipse.core.resources.IFile;
+import org.eclipse.core.resources.IResource;
+import org.eclipse.core.runtime.CoreException;
+import org.eclipse.core.runtime.content.IContentDescription;
+import org.eclipse.core.runtime.content.IContentType;
+import org.eclipse.wst.validation.internal.plugin.ValidationPlugin;
+
+/**
+ * Since it can be expense to determine a content type, we provide a wrapper so that we only
+ * need to get it once, as we validate a resource.
+ * @author karasiuk
+ *
+ */
+public class ContentTypeWrapper {
+
+ private IContentType _type;
+ private boolean _initialized;
+
+ public IContentType getContentType(IFile file){
+ if (_initialized)return _type;
+
+ IContentDescription cd = null;
+ try {
+ cd = file.getContentDescription();
+ }
+ catch (CoreException e){
+ try {
+ file.refreshLocal(IResource.DEPTH_ZERO, null);
+ cd = file.getContentDescription();
+ }
+ catch (CoreException e2){
+ if (Tracing.isLogging())ValidationPlugin.getPlugin().handleException(e2);
+ }
+ }
+ if (cd == null)return null;
+ _type = cd.getContentType();
+ _initialized = true;
+ return _type;
+ }
+
+}
diff --git a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/DebugConstants.java b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/DebugConstants.java
new file mode 100644
index 0000000..a466241
--- /dev/null
+++ b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/DebugConstants.java
@@ -0,0 +1,55 @@
+/*******************************************************************************
+ * Copyright (c) 2007, 2009 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.wst.validation.internal;
+
+import org.eclipse.wst.validation.internal.plugin.ValidationPlugin;
+
+public interface DebugConstants {
+
+ /** matches - trace filter matches. */
+ String TraceMatches = ValidationPlugin.PLUGIN_ID+"/matches"; //$NON-NLS-1$
+
+ /** timings - trace the times of the validators. */
+ String TraceTimes = ValidationPlugin.PLUGIN_ID+"/timings"; //$NON-NLS-1$
+
+ /** v1 - trace the v1 validators. */
+ String TraceV1 = ValidationPlugin.PLUGIN_ID+"/v1"; //$NON-NLS-1$
+
+ /** timings/tracefile - file that stores the trace events */
+ String TraceTimesFile = ValidationPlugin.PLUGIN_ID+"/timings/tracefile"; //$NON-NLS-1$
+
+ /**
+ * timings/useDoubles - By default times that are written to the trace file are
+ * in milliseconds for elapsed time and nanoseconds for cpu time.
+ * If you find these times easier to read as seconds as expressed by a double,
+ * the following flag can be turned on.
+ */
+ String TraceTimesUseDoubles = ValidationPlugin.PLUGIN_ID+"/timings/useDoubles"; //$NON-NLS-1$
+
+ /**
+ * extraValDetail - If extra detail is needed for a particular validator it's id can be specified here.
+ * For example, if you wanted more detail on the XML validator you would use org.eclipse.wst.xml.core.xml
+ */
+ String ExtraValDetail = ValidationPlugin.PLUGIN_ID+"/extraValDetail"; //$NON-NLS-1$
+
+ /**
+ * filter/allExcept - If supplied, it is as if this is the only validator that gets defined via
+ * the extension point. All the other validators are ignored.
+ */
+ String FilterAllExcept = ValidationPlugin.PLUGIN_ID+"/filter/allExcept"; //$NON-NLS-1$
+
+ /**
+ * trace/level - The tracing level. If not supplied a default of zero is used. The higher the number the
+ * more verbose the tracing.
+ */
+ String TraceLevel = ValidationPlugin.PLUGIN_ID+"/trace/level"; //$NON-NLS-1$
+
+}
diff --git a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/DependencyIndex.java b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/DependencyIndex.java
new file mode 100644
index 0000000..388738c
--- /dev/null
+++ b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/DependencyIndex.java
@@ -0,0 +1,370 @@
+/*******************************************************************************
+ * Copyright (c) 2007, 2008 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.wst.validation.internal;
+
+import java.io.DataInputStream;
+import java.io.DataOutputStream;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import org.eclipse.core.resources.IProject;
+import org.eclipse.core.resources.IResource;
+import org.eclipse.core.resources.ISaveContext;
+import org.eclipse.core.resources.ISaveParticipant;
+import org.eclipse.core.resources.IWorkspaceRoot;
+import org.eclipse.core.resources.ResourcesPlugin;
+import org.eclipse.core.runtime.CoreException;
+import org.eclipse.core.runtime.IPath;
+import org.eclipse.osgi.util.NLS;
+import org.eclipse.wst.validation.DependentResource;
+import org.eclipse.wst.validation.IDependencyIndex;
+import org.eclipse.wst.validation.Validator;
+import org.eclipse.wst.validation.internal.plugin.ValidationPlugin;
+
+/**
+ * A simple implementation of the IDependencyIndex. This will probably be
+ * replaced with a higher performance, more robust index, at some point in the
+ * future.
+ * <p>
+ * The format of the index is:
+ *
+ * <pre>
+ * Version number
+ * Number of depends on entries
+ * depends on file name
+ * number of dependent entries
+ * dependent file name
+ * number of validators
+ * validator id
+ * </pre>
+ *
+ * @author karasiuk
+ */
+public class DependencyIndex implements IDependencyIndex, ISaveParticipant {
+
+ /**
+ * An index so that we can determine which things depend on this resource.
+ */
+ private Map<IResource,Set<Depends>> _dependsOn;
+
+ /**
+ * An index so that we can determine who the resource depends on.
+ */
+ private Map<IResource,Set<Depends>> _dependents;
+ private boolean _dirty;
+
+ private static IResource[] EmptyResources = new IResource[0];
+
+ /** Version of the persistent index. */
+ private static final int CurrentVersion = 1;
+
+ public synchronized void add(String id, IResource dependent, IResource dependsOn) {
+ init();
+ if (dependsOn == null || dependent == null)return;
+ Depends d = getOrCreateDepends(dependent, dependsOn);
+ if (d.getValidators().add(id))_dirty = true;
+ }
+
+ private Depends getOrCreateDepends(IResource dependent, IResource dependsOn) {
+ Set<Depends> set = getSet(_dependents, dependent);
+ for (Depends d : set){
+ if (d.getDependsOn() != null && d.getDependsOn().equals(dependsOn)) return d;
+ }
+ Depends d = new Depends(dependent, dependsOn);
+ _dirty = true;
+ set.add(d);
+
+ getSet(_dependsOn, dependsOn).add(d);
+ return d;
+ }
+
+ /**
+ * Answer the set for the resource, creating it if you need to.
+ */
+ private Set<Depends> getSet(Map<IResource, Set<Depends>> map, IResource resource) {
+ Set<Depends> set = map.get(resource);
+ if (set == null){
+ set = new HashSet<Depends>(5);
+ map.put(resource, set);
+ }
+ return set;
+ }
+
+ /**
+ * Restore the dependency index. See the class comment for the structure.
+ */
+ private void init() {
+ if (_dependsOn != null)return;
+
+ boolean error = false;
+ File f = getIndexLocation();
+ if (!f.exists()){
+ _dependsOn = new HashMap<IResource,Set<Depends>>(100);
+ _dependents = new HashMap<IResource,Set<Depends>>(100);
+ }
+ else {
+ String errorMessage = "The following dependency could not be restored " +
+ "because the following resource {0} could no longer be found.";
+ DataInputStream in = null;
+ try {
+ IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
+ in = new DataInputStream(new FileInputStream(f));
+
+ int version = in.readInt();
+ if (version != CurrentVersion){
+ error = true;
+ String msg = NLS.bind(ValMessages.ErrDependencyVersion, CurrentVersion);
+ throw new IllegalStateException(msg);
+ }
+ int numDependsOn = in.readInt();
+ _dependsOn = new HashMap<IResource,Set<Depends>>(numDependsOn+100);
+ _dependents = new HashMap<IResource,Set<Depends>>(numDependsOn+100);
+ for (int i=0; i<numDependsOn; i++){
+ String v = in.readUTF();
+ IResource dependsOn = root.findMember(v);
+ if (dependsOn == null){
+ Tracing.log(NLS.bind(errorMessage, v));
+ }
+ int numDependents = in.readInt();
+ for (int j=0; j<numDependents; j++){
+ v = in.readUTF();
+ IResource dependent = root.findMember(v);
+ if (dependent == null){
+ Tracing.log(NLS.bind(errorMessage, v));
+ }
+ int numVal = in.readInt();
+ for (int k=0; k<numVal; k++){
+ String id = in.readUTF();
+ if (dependent != null && dependsOn != null)add(id, dependent, dependsOn);
+ }
+ }
+ }
+ }
+ catch (IOException e){
+ error = true;
+ ValidationPlugin.getPlugin().handleException(e);
+ }
+ finally {
+ Misc.close(in);
+ if (error){
+ _dependsOn = new HashMap<IResource,Set<Depends>>(100);
+ _dependents = new HashMap<IResource,Set<Depends>>(100);
+ f.delete();
+ }
+ }
+ }
+ }
+
+ public synchronized void clear(IProject project) {
+ init();
+ for (Map.Entry<IResource,Set<Depends>> me : _dependents.entrySet()){
+ if (me.getKey().getProject() == project){
+ for (Depends d : me.getValue()){
+ if (d.delete())_dirty = true;
+ }
+ }
+ }
+ }
+
+ public synchronized IResource[] get(String validatorId, IResource dependsOn) {
+ init();
+ List<IResource> list = new LinkedList<IResource>();
+ Set<Depends> set = getSet(_dependsOn, dependsOn);
+ for (Depends d : set){
+ for (String id : d.getValidators()){
+ if (validatorId.equals(id))list.add(d.getDependent());
+ }
+ }
+
+ if (list.size() == 0)return EmptyResources;
+ IResource[] resources = new IResource[list.size()];
+ list.toArray(resources);
+ return resources;
+ }
+
+
+ public synchronized List<DependentResource> get(IResource dependsOn) {
+ init();
+ List<DependentResource> list = new LinkedList<DependentResource>();
+ Set<Depends> set = getSet(_dependsOn, dependsOn);
+ ValManager vm = ValManager.getDefault();
+ for (Depends d : set){
+ for (String id : d.getValidators()){
+ Validator v = vm.getValidator(id, d.getDependent().getProject());
+ if (v != null)list.add(new DependentResource(d.getDependent(), v));
+ }
+ }
+ return list;
+ }
+
+
+ public synchronized void set(String id, IResource dependent, IResource[] dependsOn) {
+ init();
+ Set<Depends> set = getSet(_dependents, dependent);
+ for (Depends d : set){
+ if (d.delete(id))_dirty = true;
+ }
+ if (dependsOn != null){
+ for (IResource d : dependsOn)add(id, dependent, d);
+ }
+ }
+
+ public boolean isDependedOn(IResource resource) {
+ init();
+ Set<Depends> set = _dependsOn.get(resource);
+ if (set == null || set.size() == 0)return false;
+ return true;
+ }
+
+ public void doneSaving(ISaveContext context) {
+ }
+
+ public void prepareToSave(ISaveContext context) throws CoreException {
+ }
+
+ public void rollback(ISaveContext context) {
+ }
+
+ /**
+ * Persist the dependency index. See the class comment for the structure.
+ */
+ public synchronized void saving(ISaveContext context) throws CoreException {
+ if (!_dirty)return;
+ _dirty = false;
+
+ DataOutputStream out = null;
+ try {
+ File f = getIndexLocation();
+ out = new DataOutputStream(new FileOutputStream(f));
+ out.writeInt(CurrentVersion);
+ Map<String, Set<DependsResolved>> map = compress(_dependsOn);
+ out.writeInt(map.size());
+ for (Map.Entry<String, Set<DependsResolved>> me : map.entrySet()){
+ out.writeUTF(me.getKey());
+ Set<DependsResolved> set = me.getValue();
+ out.writeInt(set.size());
+ for (DependsResolved d : set){
+ out.writeUTF(d.resource);
+ out.writeInt(d.validators.size());
+ for (String id : d.validators){
+ out.writeUTF(id);
+ }
+ }
+ }
+ }
+ catch (IOException e){
+ ValidationPlugin.getPlugin().handleException(e);
+ }
+ finally {
+ Misc.close(out);
+ }
+ }
+
+ private Map<String, Set<DependsResolved>> compress(Map<IResource, Set<Depends>> dependsOn) {
+ Map<String, Set<DependsResolved>> map = new HashMap<String, Set<DependsResolved>>(dependsOn.size());
+ for (Map.Entry<IResource, Set<Depends>> me : dependsOn.entrySet()){
+ Set<DependsResolved> set = new HashSet<DependsResolved>(me.getValue().size());
+ for (Depends d : me.getValue()){
+ IPath path = d.getDependent().getFullPath();
+ if (path != null){
+ DependsResolved dr = new DependsResolved();
+ dr.resource = path.toPortableString();
+ if (d.getValidators().size() > 0){
+ dr.validators = d.getValidators();
+ set.add(dr);
+ }
+ }
+ }
+ if (set.size() > 0){
+ IResource res = me.getKey();
+ if (res != null){
+ IPath path = res.getFullPath();
+ if (path != null)map.put(path.toPortableString(), set);
+ }
+ }
+ }
+ return map;
+ }
+
+ private File getIndexLocation() {
+ IPath path = ValidationPlugin.getPlugin().getStateLocation().append("dep.index"); //$NON-NLS-1$
+ return path.toFile();
+ }
+
+ /**
+ * Keep track of a relationship between a dependent and the thing that it
+ * depends on.
+ *
+ * @author karasiuk
+ *
+ */
+ private static class Depends {
+
+ /** The resource that is being depended on, for example a.xsd */
+ private IResource _dependsOn;
+
+ /** The resource that is dependent, for example a.xml */
+ private IResource _dependent;
+
+ /** The id's of the validators that have asserted the dependency. */
+ private Set<String> _validators;
+
+ public Depends(IResource dependent, IResource dependsOn) {
+ _dependent = dependent;
+ _dependsOn = dependsOn;
+ _validators = new HashSet<String>(5);
+ }
+
+ /**
+ * Answer true if the id was deleted.
+ */
+ public boolean delete(String id) {
+ return _validators.remove(id);
+ }
+
+ /**
+ * Delete all the dependency assertions for all of your validators.
+ * @return false if there was nothing to delete
+ */
+ public boolean delete() {
+ boolean deleted = _validators.size() > 0;
+ if (deleted)_validators.clear();
+ return deleted;
+ }
+
+ public IResource getDependsOn() {
+ return _dependsOn;
+ }
+
+ public IResource getDependent() {
+ return _dependent;
+ }
+
+ public Set<String> getValidators() {
+ return _validators;
+ }
+}
+
+ private static class DependsResolved {
+ String resource;
+ Set<String> validators;
+ }
+
+
+}
diff --git a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/Deserializer.java b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/Deserializer.java
new file mode 100644
index 0000000..b1af963
--- /dev/null
+++ b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/Deserializer.java
@@ -0,0 +1,63 @@
+/*******************************************************************************
+ * Copyright (c) 2008 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.wst.validation.internal;
+
+/**
+ * A simple deserializer that knows how to retrieve booleans, integers and strings, from a string
+ * that was encoded by the Serializer class.
+ *
+ * @see Serializer
+ * @author karasiuk
+ *
+ */
+public class Deserializer {
+ private char[] _buffer;
+ private int _posn;
+
+ public Deserializer(String value){
+ _buffer = value.toCharArray();
+ }
+
+ public boolean getBoolean(){
+ boolean result = false;
+ if (_buffer[_posn] == 'T')result = true;
+ else if (_buffer[_posn] == 'F')result = false;
+ else throw new IllegalStateException(ValMessages.DecodeError1);
+
+ _posn++;
+ return result;
+ }
+
+ public String getString(){
+ int len = getInt();
+ String result = new String(_buffer, _posn, len);
+ _posn += len;
+ return result;
+ }
+
+ public int getInt(){
+ Integer len = new Integer(String.valueOf(_buffer[_posn]));
+ _posn++;
+
+ String s = String.valueOf(_buffer, _posn, len+1);
+ _posn += len+1;
+ return Integer.parseInt(s);
+ }
+
+ /**
+ * Are there any more items?
+ * @return
+ */
+ public boolean hasNext() {
+ if (_posn >= _buffer.length)return false;
+ return true;
+ }
+}
diff --git a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/DisabledResourceManager.java b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/DisabledResourceManager.java
new file mode 100644
index 0000000..120180f
--- /dev/null
+++ b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/DisabledResourceManager.java
@@ -0,0 +1,158 @@
+/*******************************************************************************
+ * Copyright (c) 2008 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.wst.validation.internal;
+
+import java.util.HashSet;
+import java.util.Set;
+
+import org.eclipse.core.resources.IProject;
+import org.eclipse.core.resources.IResource;
+import org.eclipse.core.runtime.IPath;
+import org.eclipse.core.runtime.Path;
+import org.eclipse.wst.validation.internal.plugin.ValidationPlugin;
+import org.osgi.service.prefs.BackingStoreException;
+
+/**
+ * Validators can assert that certain resources (usually folders) are not validated. This class keeps track of those
+ * assertions.
+ * @author karasiuk
+ *
+ */
+public class DisabledResourceManager implements IProjectChangeListener {
+
+ public static DisabledResourceManager getDefault(){
+ return Singleton.disabledResourceManager;
+ }
+
+ private Set<IResource> _disabled = new HashSet<IResource>(100);
+ private Set<IProject> _loadedProjects = new HashSet<IProject>(40);
+
+ private DisabledResourceManager(){
+ EventManager.getManager().addProjectChangeListener(this);
+ }
+
+ public void disableValidation(IResource resource){
+ // We check for two reasons, 1) we may save some work, 2) we force the project to be loaded
+ if (isDisabled(resource))return;
+
+ Set<IResource> copy = new HashSet<IResource>(_disabled.size()+2);
+ copy.addAll(_disabled);
+ copy.add(resource);
+ save(copy, resource.getProject());
+ _disabled = copy;
+ }
+
+ public void enableValidation(IResource resource){
+ // We check for two reasons, 1) we may save some work, 2) we force the project to be loaded
+ if (!isDisabled(resource))return;
+
+ Set<IResource> copy = new HashSet<IResource>(_disabled.size()+2);
+ copy.addAll(_disabled);
+ copy.remove(resource);
+ save(copy, resource.getProject());
+ _disabled = copy;
+ }
+
+ private void save(Set<IResource> disabled, IProject project) {
+ Serializer ser = new Serializer(200);
+ for (IResource resource : disabled){
+ if (project == resource.getProject()){
+ ser.put(resource.getProjectRelativePath().toPortableString());
+ }
+ }
+ PreferencesWrapper prefs = PreferencesWrapper.getPreferences(project, null);
+ prefs.put(PrefConstants.disabled, ser.toString());
+ try {
+ prefs.flush();
+ }
+ catch (BackingStoreException e){
+ ValidationPlugin.getPlugin().handleException(e);
+ }
+ }
+
+ private void load(IProject project){
+ Set<IResource> copy = new HashSet<IResource>(_disabled.size()+10);
+ copy.addAll(_disabled);
+ PreferencesWrapper prefs = PreferencesWrapper.getPreferences(project, null);
+ String disabled = prefs.get(PrefConstants.disabled, ""); //$NON-NLS-1$
+ if (disabled.length() > 0){
+ Deserializer des = new Deserializer(disabled);
+ while(des.hasNext()){
+ String pathString = des.getString();
+ IPath path = Path.fromPortableString(pathString);
+ IResource resource = project.findMember(path);
+ copy.add(resource);
+ }
+ }
+ _disabled = copy;
+ }
+
+ public void dispose(){
+ EventManager.getManager().removeProjectChangeListener(this);
+ }
+
+ /**
+ * Answer true if this resource should not be validated.
+ *
+ * @param resource the resource that is being tested.
+ * @return true if the resource should not be validated.
+ */
+ public boolean isDisabled(IResource resource){
+ IProject project = resource.getProject();
+ if (_loadedProjects.contains(project))return _disabled.contains(resource);
+ return isDisabled(resource, project);
+ }
+
+ private synchronized boolean isDisabled(IResource resource, IProject project){
+ if (!_loadedProjects.contains(project)){
+ load(project);
+ _loadedProjects.add(project);
+ }
+ return _disabled.contains(resource);
+ }
+
+ public void addDisabled(IResource resource){
+ _disabled.add(resource);
+ }
+
+ public void projectChanged(IProject project, int type) {
+ switch (type) {
+ case IProjectChangeListener.ProjectDeleted:
+ case IProjectChangeListener.ProjectClosed:
+ projectRemoved(project);
+ break;
+
+ }
+
+ }
+
+ private synchronized void projectRemoved(IProject project) {
+ _loadedProjects.remove(project);
+ Set<IResource> copy = new HashSet<IResource>(100);
+ for (IResource resource : _disabled){
+ if (resource.getProject() != project)copy.add(resource);
+ }
+ _disabled = copy;
+ }
+
+ /**
+ * Store the singleton for the DisabledResourceManager. This approach is used to avoid having to synchronize the
+ * DisabledResourceManager.getDefault() method.
+ *
+ * @author karasiuk
+ *
+ */
+ private static class Singleton {
+ static DisabledResourceManager disabledResourceManager = new DisabledResourceManager();
+ }
+
+
+}
diff --git a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/DisabledValidatorManager.java b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/DisabledValidatorManager.java
new file mode 100644
index 0000000..7505e88
--- /dev/null
+++ b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/DisabledValidatorManager.java
@@ -0,0 +1,125 @@
+package org.eclipse.wst.validation.internal;
+
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.atomic.AtomicInteger;
+
+import org.eclipse.core.resources.IProject;
+import org.eclipse.core.resources.IResource;
+import org.eclipse.core.runtime.IProgressMonitor;
+import org.eclipse.core.runtime.NullProgressMonitor;
+import org.eclipse.wst.validation.Validator;
+import org.eclipse.wst.validation.internal.model.IValidatorVisitor;
+
+/**
+ * Keep track of the disabled validators.
+ * @author karasiuk
+ *
+ */
+public final class DisabledValidatorManager implements IValChangedListener {
+
+ private static final AtomicInteger _counter = new AtomicInteger();
+ private static final int CacheSize = 5;
+
+ private final Map<IResource, LRUSet> _map = Collections.synchronizedMap(new HashMap<IResource, LRUSet>(5));
+
+ public static DisabledValidatorManager getDefault(){
+ return Singleton.disabledValidatorManager;
+ }
+
+ private DisabledValidatorManager(){
+ ValPrefManagerProject.addListener(this);
+ }
+
+ /*
+ * Although this is currently not called, it should be if this ever stops being a singleton.
+ */
+ public void dispose(){
+ ValPrefManagerProject.removeListener(this);
+ }
+
+ public Set<Validator> getDisabledValidatorsFor(IResource resource) {
+ LRUSet set = _map.get(resource);
+ if (set != null){
+ set.counter = _counter.getAndIncrement();
+ return set.validators;
+ }
+
+ DisabledValidationFinder dvf = new DisabledValidationFinder();
+ Set<Validator> vset = dvf.findDisabledValidatorsFor(resource);
+ insert(resource, vset);
+ return vset;
+ }
+
+ private synchronized void insert(IResource resource, Set<Validator> vset) {
+ if (_map.size() >= CacheSize ){
+ IResource oldest = null;
+ int current = Integer.MAX_VALUE;
+ for (Map.Entry<IResource, LRUSet> me : _map.entrySet()){
+ if (me.getValue().counter < current){
+ oldest = me.getKey();
+ current = me.getValue().counter;
+ }
+ }
+ _map.remove(oldest);
+ }
+ LRUSet set = new LRUSet();
+ set.counter = _counter.getAndIncrement();
+ set.validators = vset;
+ _map.put(resource, set);
+ }
+
+
+ private final static class LRUSet {
+ int counter;
+ Set<Validator> validators;
+ }
+
+ private final static class DisabledValidationFinder implements IValidatorVisitor {
+
+ private Map<String, Validator> _validators;
+
+ public void visit(Validator validator, IProject project, ValType valType, ValOperation operation,
+ IProgressMonitor monitor) {
+
+ _validators.remove(validator.getId());
+
+ }
+
+ public Set<Validator> findDisabledValidatorsFor(IResource resource) {
+ ValManager vm = ValManager.getDefault();
+ Validator[] vals = vm.getValidatorsCopy();
+ _validators = new HashMap<String, Validator>(100);
+ for (Validator v : vals)_validators.put(v.getId(), v);
+
+ IProject project = resource.getProject();
+ vm.accept(this, project, resource, ValType.Build, new ValOperation(), new NullProgressMonitor());
+ Set<Validator> set = new HashSet<Validator>(_validators.size());
+ set.addAll(_validators.values());
+ return set;
+ }
+
+
+ }
+
+ public void validatorsForProjectChanged(IProject project, boolean configSettingChanged) {
+ _map.clear();
+ }
+
+
+ /**
+ * Store the singleton for the DisabledValidatorManager. This approach is used to avoid having to synchronize the
+ * DisabledValidatorManager.getDefault() method.
+ *
+ * @author karasiuk
+ *
+ */
+ private final static class Singleton {
+ final static DisabledValidatorManager disabledValidatorManager = new DisabledValidatorManager();
+ }
+
+
+}
diff --git a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/ExtensionConstants.java b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/ExtensionConstants.java
new file mode 100644
index 0000000..e702471
--- /dev/null
+++ b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/ExtensionConstants.java
@@ -0,0 +1,183 @@
+/*******************************************************************************
+ * Copyright (c) 2005, 2008 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.wst.validation.internal;
+
+/**
+ * Constants used in the extension points.
+ * @author karasiuk
+ *
+ */
+public interface ExtensionConstants {
+
+ /** validatorV2 - extension point for registering validators that use version 2 of the validation framework. */
+ String validator = "validatorV2"; //$NON-NLS-1$
+
+ /** exclude - extension point for adding extra exclusion filters to a validator. */
+ String excludeExtension = "exclude"; //$NON-NLS-1$
+
+ /** build - is the validator enabled by default for build based validations? true or false */
+ String build = "build"; //$NON-NLS-1$
+
+ /** class - name of the attribute that holds the validator class. */
+ String AttribClass = "class"; //$NON-NLS-1$
+
+ /** manual - is the validator enabled by default for manual based validations? true or false */
+ String manual = "manual"; //$NON-NLS-1$
+
+ /**
+ * markerId - the marker id that the framework should use when creating customized markers for this validator.
+ * This is an optional attribute. If it is not supplied than the standard validation marker type will be used.
+ */
+ String markerId = "markerId"; //$NON-NLS-1$
+
+ /**
+ * sourceid - If this validator also serves as an as-you-type validator (also know as an ISourceValidator)
+ * then it's source id is specified here, so that the two validators can be associated with one
+ * another. By source id, we mean the id that is used in the org.eclipse.wst.sse.ui.sourceValidation
+ * extension point.
+ */
+ String sourceId = "sourceid"; //$NON-NLS-1$
+
+ /**
+ * version - the version of this definition. The attribute is a simple integer, and if not specified it
+ * is assumed to be 1. This allows the filter settings to be changed in the future.
+ */
+ String version = "version"; //$NON-NLS-1$
+
+ /**
+ * include - a group of inclusion rules. At least one rule in this group needs to match in order for the resource
+ * to to considered to be validated.
+ */
+ String include = "include"; //$NON-NLS-1$
+
+ /** exclude - a group of exclusion rules. If any of these rules match the resource is not validated. */
+ String exclude = "exclude"; //$NON-NLS-1$
+
+ /** rules - a group of inclusion or exclusion rules. */
+ String rules = "rules"; //$NON-NLS-1$
+
+ /** rules - extension point to declare a validator group */
+ String group = "validatorGroup"; //$NON-NLS-1$
+
+ interface Group {
+ /*
+ * The group sub-element for either the validatorGroup or validator
+ * extension points.
+ */
+ String elementGroup = "group"; //$NON-NLS-1$
+ // a validator group identifier
+ String attId = "id"; //$NON-NLS-1$
+ // the listener sub-element
+ String elementListener = "listener"; //$NON-NLS-1$
+ // the group listener class name
+ String attClass = "class"; //$NON-NLS-1$
+ }
+
+ /** Different types of rules for filtering validation. */
+ interface Rule {
+
+ /** projectNature - filter by project nature. */
+ String projectNature = "projectNature"; //$NON-NLS-1$
+
+ /** fileext - filter by file extension. */
+ String fileext = "fileext"; //$NON-NLS-1$
+
+ /** file - a file name, it can include path information as well. */
+ String file = "file"; //$NON-NLS-1$
+
+ /** facet - filter by facet id. */
+ String facet = "facet"; //$NON-NLS-1$
+
+ /** contentType - filter by content type. */
+ String contentType = "contentType"; //$NON-NLS-1$
+
+ /** pattern - filter paths by regular expression. */
+ String pattern = "pattern"; //$NON-NLS-1$
+ }
+
+ /** Rule attributes */
+ interface RuleAttrib {
+
+ /** caseSensitive - true or false. */
+ String caseSensitive = "caseSensitive"; //$NON-NLS-1$
+
+ /**
+ * exactMatch - true or false, default is true. It is used to decide whether content types need to match
+ * exactly, or whether sub types should also be considered.
+ */
+ String exactMatch = "exactMatch"; //$NON-NLS-1$
+
+ /** ext - a file extension, for example "html". */
+ String ext = "ext"; //$NON-NLS-1$
+
+ /** id - an identifier. */
+ String id = "id"; //$NON-NLS-1$
+
+ /** name - a file name. */
+ String name = "name"; //$NON-NLS-1$
+
+ /** regex - a Java regular expression. */
+ String regex = "regex"; //$NON-NLS-1$
+
+ /**
+ * type - the type of file to be matched:
+ * <ul>
+ * <li>folder - project relative folder name
+ * <li>file - simple file name
+ * <li>full - fully qualified, project relative file name
+ * </ul>
+ */
+ String fileType = "type"; //$NON-NLS-1$
+
+ /** version - facet version expression. See the facet framework for the exact syntax of this expression. */
+ String version = "version"; //$NON-NLS-1$
+ }
+
+ interface FileType {
+ /** folder - project relative folder name */
+ String folder = "folder"; //$NON-NLS-1$
+
+ /** file - simple file name */
+ String file = "file"; //$NON-NLS-1$
+
+ /** full - fully qualified, project relative file name */
+ String full = "full"; //$NON-NLS-1$
+ }
+
+ interface MessageCategory {
+ /** messageCategory - name of the message category element. */
+ String name = "messageCategory"; //$NON-NLS-1$
+
+ /** id - simple id of the message. */
+ String id = "id"; //$NON-NLS-1$
+
+ /** label = human readable label of the message category. */
+ String label = "label"; //$NON-NLS-1$
+
+ /** severity - message severity, it must be one of error, warning or ignore. */
+ String severity = "severity"; //$NON-NLS-1$
+
+ String sevError = "error"; //$NON-NLS-1$
+ String sevWarning = "warning"; //$NON-NLS-1$
+ String sevIgnore = "ignore"; //$NON-NLS-1$
+ }
+
+ interface Exclude {
+ /** id - fully qualified id of the validator that is being extended. */
+ String id = "id"; //$NON-NLS-1$
+ }
+
+ /** true */
+ String True = "true"; //$NON-NLS-1$
+
+ /** false */
+ String False = "false"; //$NON-NLS-1$
+}
diff --git a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/ExtensionValidators.java b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/ExtensionValidators.java
new file mode 100644
index 0000000..090f4af
--- /dev/null
+++ b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/ExtensionValidators.java
@@ -0,0 +1,110 @@
+/*******************************************************************************
+ * Copyright (c) 2008 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.wst.validation.internal;
+
+import java.lang.reflect.InvocationTargetException;
+import java.util.HashMap;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+
+import org.eclipse.core.resources.IProject;
+import org.eclipse.wst.validation.Validator;
+import org.eclipse.wst.validation.internal.plugin.ValidationPlugin;
+
+/**
+ * The validators that have been defined by the validator extension points.
+ * @author karasiuk
+ *
+ */
+public final class ExtensionValidators {
+ private static ExtensionValidators _me;
+
+ /** All the registered validators. The key is the validator id and the value is the validator. */
+ private final Map<String, Validator> _map;
+
+ public synchronized static ExtensionValidators instance(){
+ if (_me == null){
+ _me = new ExtensionValidators();
+ }
+ return _me;
+ }
+
+ private ExtensionValidators(){
+ _map = new HashMap<String, Validator>(100);
+ for (Validator v : ValidatorExtensionReader.getDefault().process()){
+ _map.put(v.getId(), v);
+ }
+ }
+
+ /**
+ * Answer all the v2 validators that have been defined by the extension point. This is the real
+ * map (not a copy).
+ *
+ * @return The key is the validator id and the value is the validator.
+ */
+ public Map<String, Validator> getMapV2() {
+ return _map;
+ }
+
+ /**
+ * Answer all the v2 validators that have been defined by the extension point. This is a copy of
+ * the map, but not a copy of the validators.
+ *
+ * @return The key is the validator id and the value is the validator.
+ */
+ public Map<String, Validator> getMapV2Copy() {
+ HashMap<String, Validator> map = new HashMap<String, Validator>(_map.size());
+ map.putAll(_map);
+ return map;
+ }
+
+
+ /**
+ * Answer all the validators that have been defined by extension points. This includes all
+ * the v2 validators, and all of the v1 validators that have been defined just on this project.
+ *
+ * @return The key is the validator id and the value is the validator.
+ */
+ public Map<String, Validator> getMap(IProject project) {
+ //TODO I may want to consider caching this, but then again if the v1 validators are going away
+ // it may not be worth it.
+ Map<String, Validator> map = new HashMap<String, Validator>();
+ map.putAll(_map);
+
+ for (Validator v : getV1Validators(project))map.put(v.getId(), v);
+
+ return map;
+ }
+
+ /**
+ * Answer the v1 validators that have been defined just on this project.
+ * @param project
+ * @return
+ */
+ List<Validator> getV1Validators(IProject project){
+ List<Validator> list = new LinkedList<Validator>();
+ try {
+ ProjectConfiguration pc = new ProjectConfiguration(project);
+ pc.resetToDefault();
+ for (ValidatorMetaData vmd : pc.getValidators()){
+ Validator v = Validator.create(vmd, pc, project);
+ list.add(v);
+ }
+ }
+ catch (InvocationTargetException e){
+ ValidationPlugin.getPlugin().handleException(e);
+ }
+
+ return list;
+ }
+
+}
diff --git a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/FullBuildJob.java b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/FullBuildJob.java
new file mode 100644
index 0000000..332a2c7
--- /dev/null
+++ b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/FullBuildJob.java
@@ -0,0 +1,29 @@
+package org.eclipse.wst.validation.internal;
+
+import org.eclipse.core.resources.IncrementalProjectBuilder;
+import org.eclipse.core.resources.ResourcesPlugin;
+import org.eclipse.core.resources.WorkspaceJob;
+import org.eclipse.core.runtime.CoreException;
+import org.eclipse.core.runtime.IProgressMonitor;
+import org.eclipse.core.runtime.IStatus;
+import org.eclipse.core.runtime.Status;
+import org.eclipse.wst.validation.internal.plugin.ValidationPlugin;
+
+public class FullBuildJob extends WorkspaceJob {
+
+ public FullBuildJob(){
+ super(ValMessages.JobName);
+ }
+
+ @Override
+ public IStatus runInWorkspace(IProgressMonitor monitor) throws CoreException {
+ try {
+ ResourcesPlugin.getWorkspace().build(IncrementalProjectBuilder.FULL_BUILD, monitor);
+ }
+ catch (Exception e){
+ return new Status(IStatus.ERROR,ValidationPlugin.PLUGIN_ID, e.toString(), e);
+ }
+ return Status.OK_STATUS;
+ }
+
+}
diff --git a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/IProjectChangeListener.java b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/IProjectChangeListener.java
new file mode 100644
index 0000000..6788534
--- /dev/null
+++ b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/IProjectChangeListener.java
@@ -0,0 +1,39 @@
+/*******************************************************************************
+ * Copyright (c) 2008 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.wst.validation.internal;
+
+import org.eclipse.core.resources.IProject;
+
+/**
+ * A call back for listeners that are interested when a project changes.
+ * @author karasiuk
+ *
+ */
+public interface IProjectChangeListener {
+
+ int ProjectOpened = 1;
+ int ProjectClosed = 2;
+ int ProjectDeleted = 4;
+
+ /** 8 - Something in the project description has changed. For example, a Nature was added. */
+ int ProjectChanged = 8;
+
+ /** 16 - The project has been added. */
+ int ProjectAdded = 16;
+
+ /**
+ * The project has changed in some way.
+ *
+ * @param project The project that has changed.
+ * @param type The type of change. This will be one of the Project constants;
+ */
+ void projectChanged(IProject project, int type);
+}
diff --git a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/IValChangedListener.java b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/IValChangedListener.java
new file mode 100644
index 0000000..a2d26d8
--- /dev/null
+++ b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/IValChangedListener.java
@@ -0,0 +1,31 @@
+/*******************************************************************************
+ * Copyright (c) 2007, 2008 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.wst.validation.internal;
+
+/**
+ * A class that wants to be notified when the validator preferences change.
+ * @author karasiuk
+ *
+ */
+public interface IValChangedListener {
+
+ /**
+ * The validators for the project have changed.
+ *
+ * @param project the project can be null, which means that the global validation preferences have
+ * changed.
+ *
+ * @param configSettingChanged If true a setting that could effect what gets validated has changed.
+ * If false, then only other types of settings (like whether to show a results dialog or not) have
+ * changed.
+ */
+ public void validatorsForProjectChanged(org.eclipse.core.resources.IProject project, boolean configSettingChanged);
+}
diff --git a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/MarkerManager.java b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/MarkerManager.java
new file mode 100644
index 0000000..8776525
--- /dev/null
+++ b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/MarkerManager.java
@@ -0,0 +1,205 @@
+/*******************************************************************************
+ * Copyright (c) 2007, 2008 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.wst.validation.internal;
+
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import org.eclipse.core.resources.IMarker;
+import org.eclipse.core.resources.IProject;
+import org.eclipse.core.resources.IResource;
+import org.eclipse.core.runtime.CoreException;
+import org.eclipse.wst.validation.Validator;
+import org.eclipse.wst.validation.ValidatorMessage;
+import org.eclipse.wst.validation.internal.plugin.ValidationPlugin;
+import org.eclipse.wst.validation.internal.provisional.core.IMessage;
+
+/**
+ * A central place to manage all of the V2 validation markers.
+ * @author karasiuk
+ *
+ */
+public class MarkerManager {
+
+ private Set<String> _markers = new HashSet<String>(50);
+
+ public static MarkerManager getDefault(){
+ return Singleton.markerManager;
+ }
+
+ private MarkerManager(){
+ _markers.add(ValConstants.ProblemMarker);
+ _markers.add(ConfigurationConstants.VALIDATION_MARKER);
+ }
+
+ /**
+ * Clear any validation markers that may have been set by this validator.
+ *
+ * @param resource
+ * The resource that may have it's markers cleared. It can be
+ * null, in which case the operation is a no-op.
+ * @param validator
+ * The validator that created the marker.
+ */
+ public void clearMarker(IResource resource, Validator validator) throws CoreException {
+ if (resource == null)return;
+ hook(resource);
+
+ String id = validator.getMarkerId();
+ if (id != null){
+ try {
+ resource.deleteMarkers(id, true, IResource.DEPTH_ZERO);
+ }
+ catch (CoreException e){
+ // Nothing that we can do. This is not worth logging.
+ }
+ return;
+ }
+
+ IMarker[] markers = resource.findMarkers(ValConstants.ProblemMarker, true, IResource.DEPTH_ZERO);
+ String valId = validator.getId();
+ for (IMarker marker : markers){
+ id = marker.getAttribute(ValidatorMessage.ValidationId, null);
+ if (valId.equals(id))marker.delete();
+ }
+ }
+
+ @SuppressWarnings("unchecked")
+ public void createMarker(ValidatorMessage m, String id){
+ try {
+ IResource resource = m.getResource();
+ hook(resource);
+ IMarker marker = resource.createMarker(m.getType());
+ Map map = m.getAttributes();
+ if (map.get(ValidatorMessage.ValidationId) == null)
+ map.put(ValidatorMessage.ValidationId, id);
+ marker.setAttributes(map);
+ }
+ catch (CoreException e){
+ if (!m.getResource().exists())throw new ResourceUnavailableError(m.getResource());
+ ValidationPlugin.getPlugin().handleException(e);
+ }
+
+ }
+
+ /**
+ * Delete all the markers on this resource that were created before the
+ * operation start time.
+ *
+ * @param resource
+ * The resource that is having it's markers deleted.
+ * @param operationStartTime
+ * The time as returned by System.currentTimeMillis().
+ * @param depth
+ * The depth of the markers to clear. It is one of the
+ * IResource.DEPTH_XXX constants.
+ */
+ public void deleteMarkers(IResource resource, long operationStartTime, int depth){
+ try {
+ hook(resource);
+ IMarker[] markers = resource.findMarkers(null, true, depth);
+ String markerType;
+ for (IMarker marker : markers){
+ try {
+ markerType = marker.getType();
+ }
+ catch (CoreException e)
+ {
+ //ignore the marker
+ return;
+ }
+ if (_markers.contains(markerType)){
+ long createTime = marker.getCreationTime();
+ if (createTime < operationStartTime){
+ try {
+ marker.delete();
+ }
+ catch (CoreException e){
+ // eat it - there is nothing we can do about this.
+ }
+ }
+ }
+ }
+ }
+ catch (CoreException e){
+ IProject project = resource.getProject();
+ if (!project.exists() || !project.isOpen())throw new ProjectUnavailableError(project);
+ if (!resource.exists())throw new ResourceUnavailableError(resource);
+ ValidationPlugin.getPlugin().handleException(e);
+ }
+ }
+
+ public void makeMarkers(List<IMessage> list){
+ for (IMessage message : list){
+ IResource res = null;
+ Object target = message.getTargetObject();
+ if (target != null && target instanceof IResource)res = (IResource)target;
+ if (res == null){
+ target = message.getAttribute(IMessage.TargetResource);
+ if (target != null && target instanceof IResource)res = (IResource)target;
+ }
+ if (res != null){
+ try {
+ hook(res);
+ String id = message.getMarkerId();
+ if (id == null)id = ConfigurationConstants.VALIDATION_MARKER;
+ IMarker marker = res.createMarker(id);
+ marker.setAttributes(message.getAttributes());
+ marker.setAttribute(IMarker.MESSAGE, message.getText());
+ int markerSeverity = IMarker.SEVERITY_INFO;
+ int sev = message.getSeverity();
+ if ((sev & IMessage.HIGH_SEVERITY) != 0)markerSeverity = IMarker.SEVERITY_ERROR;
+ else if ((sev & IMessage.NORMAL_SEVERITY) != 0)markerSeverity = IMarker.SEVERITY_WARNING;
+ marker.setAttribute(IMarker.SEVERITY, markerSeverity);
+ marker.setAttribute(IMarker.LINE_NUMBER, message.getLineNumber());
+ }
+ catch (CoreException e){
+ ValidationPlugin.getPlugin().handleException(e);
+ }
+ }
+ }
+ }
+
+ /**
+ * A debugging method. A place to put break points, so that you can figure out what sort of marker
+ * changes are happening.
+ *
+ * @param resource
+ */
+ public void hook(IResource resource){
+// String name = "first.test2x";
+// if (resource.getName().equals(name)){
+// String markers = Misc.listMarkers(resource);
+// Tracing.log("MarkerManager has hooked: ", name); //$NON-NLS-1$
+// RuntimeException rt = new RuntimeException("hooking " + name);
+// rt.printStackTrace();
+// }
+ }
+
+ public Set<String> getMarkers() {
+ return _markers;
+ }
+
+ /**
+ * Store the singleton for the MarkerManager. This approach is used to avoid having to synchronize the
+ * MarkerManager.getDefault() method.
+ *
+ * @author karasiuk
+ *
+ */
+ private static class Singleton {
+ static MarkerManager markerManager = new MarkerManager();
+ }
+
+
+}
diff --git a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/Misc.java b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/Misc.java
new file mode 100644
index 0000000..ceafc41
--- /dev/null
+++ b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/Misc.java
@@ -0,0 +1,155 @@
+/*******************************************************************************
+ * Copyright (c) 2008 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+
+package org.eclipse.wst.validation.internal;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.lang.management.ManagementFactory;
+import java.lang.management.ThreadMXBean;
+
+import org.eclipse.core.resources.IMarker;
+import org.eclipse.core.resources.IResource;
+import org.eclipse.core.resources.IResourceChangeEvent;
+import org.eclipse.core.runtime.CoreException;
+import org.eclipse.core.runtime.Platform;
+import org.eclipse.osgi.util.NLS;
+
+/**
+ * Some miscellaneous helper methods.
+ * @author karasiuk
+ *
+ */
+public final class Misc {
+
+ public static void close(InputStream in){
+ if (in == null)return;
+ try {
+ in.close();
+ }
+ catch (IOException e){
+ // eat it
+ }
+ }
+
+ public static void close(OutputStream out) {
+ if (out == null)return;
+ try {
+ out.close();
+ }
+ catch (IOException e){
+ // eat it
+ }
+ }
+
+ public static boolean debugOptionAsBoolean(String option){
+ String opt = Platform.getDebugOption(option);
+ if (opt == null)return false;
+ opt = opt.toLowerCase();
+ if ("true".equals(opt))return true; //$NON-NLS-1$
+ if ("yes".equals(opt))return true; //$NON-NLS-1$
+ return false;
+ }
+
+
+ /**
+ * Answer a units appropriate string for the time.
+ * @param time time in nano seconds
+ */
+ public static String getTimeNano(long time){
+ if (time <= 1000)return NLS.bind(ValMessages.TimeNano, time);
+ if (time <= 1000000)return NLS.bind(ValMessages.TimeMicro, time/1000);
+ return getTimeMS(time/1000000);
+ }
+
+ /**
+ * Answer the CPU time consumed by this thread in nano seconds.
+ * @return -1 if the time can not be determined.
+ */
+ public static long getCPUTime(){
+ long cpuTime = -1;
+ ThreadMXBean tb = ManagementFactory.getThreadMXBean();
+ if (tb.isCurrentThreadCpuTimeSupported()){
+ cpuTime = tb.getCurrentThreadCpuTime();
+ }
+ return cpuTime;
+ }
+
+ /**
+ * Answer a units appropriate string for the time.
+ * @param time time in milliseconds
+ */
+ public static String getTimeMS(long time) {
+ if (time <= 1000)return ValMessages.TimeUnder;
+ if (time <= 60000)return NLS.bind(ValMessages.TimeSec, time/1000);
+ return NLS.bind(ValMessages.TimeMin, time/60000);
+ }
+
+ /**
+ * Used in debugging so we can see what types of markers there are.
+ * @param resource
+ */
+ public static String listMarkers(IResource resource){
+ StringBuffer b = new StringBuffer(2000);
+ try {
+ IMarker[] markers = resource.findMarkers(null, true, IResource.DEPTH_ZERO);
+ for (IMarker m : markers){
+ Object o = m.getAttribute(IMarker.MESSAGE);
+ if (o != null){
+ b.append(o);
+ }
+ o = m.getAttribute(IMarker.SEVERITY);
+ if (o != null){
+ b.append(", Severity="); //$NON-NLS-1$
+ b.append(o);
+ }
+ b.append("; "); //$NON-NLS-1$
+ }
+ }
+ catch (CoreException e){
+
+ }
+ return b.toString();
+ }
+
+ /**
+ * Answer true if they are the same. If they are both null then they are the same.
+ * @param s1 the string to compare. It can be null.
+ * @param s2 the string to compare. It can be null.
+ */
+ public static boolean same(String s1, String s2){
+ if (s1 == null && s2 == null)return true;
+ if (s1 == null)return false;
+ return s1.equals(s2);
+ }
+
+ public static void niy(String msg){
+ if (msg == null)msg = "Sorry, this function is not implemented yet"; //$NON-NLS-1$
+ throw new RuntimeException(msg);
+ }
+
+ /**
+ * Answer the type as a human readable string. This is only used for debugging.
+ * @param type
+ * @return
+ */
+ public static String resourceChangeEventType(int type){
+ StringBuffer b = new StringBuffer(200);
+ if ((type & IResourceChangeEvent.POST_BUILD) != 0)b.append("post_build "); //$NON-NLS-1$
+ if ((type & IResourceChangeEvent.POST_CHANGE) != 0)b.append("post_change "); //$NON-NLS-1$
+ if ((type & IResourceChangeEvent.PRE_BUILD) != 0)b.append("pre_build "); //$NON-NLS-1$
+ if ((type & IResourceChangeEvent.PRE_CLOSE) != 0)b.append("pre_close "); //$NON-NLS-1$
+ if ((type & IResourceChangeEvent.PRE_DELETE) != 0)b.append("pre_delete "); //$NON-NLS-1$
+ return b.toString();
+ }
+
+}
diff --git a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/NullValidator.java b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/NullValidator.java
new file mode 100644
index 0000000..9f057aa
--- /dev/null
+++ b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/NullValidator.java
@@ -0,0 +1,32 @@
+/*******************************************************************************
+ * Copyright (c) 2008 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+
+package org.eclipse.wst.validation.internal;
+
+import org.eclipse.core.resources.IResource;
+import org.eclipse.core.runtime.IProgressMonitor;
+import org.eclipse.wst.validation.AbstractValidator;
+import org.eclipse.wst.validation.ValidationResult;
+import org.eclipse.wst.validation.ValidationState;
+
+/**
+ * A null validator that is used in error cases. It simply no-ops.
+ * @author karasiuk
+ *
+ */
+public class NullValidator extends AbstractValidator {
+
+ @Override
+ public ValidationResult validate(IResource resource, int kind, ValidationState state, IProgressMonitor monitor) {
+ return null;
+ }
+
+}
diff --git a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/PerformanceMonitor.java b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/PerformanceMonitor.java
new file mode 100644
index 0000000..f00e93d
--- /dev/null
+++ b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/PerformanceMonitor.java
@@ -0,0 +1,192 @@
+/*******************************************************************************
+ * Copyright (c) 2007, 2008 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.wst.validation.internal;
+
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.PrintWriter;
+import java.text.DateFormat;
+import java.text.SimpleDateFormat;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+
+import org.eclipse.osgi.util.NLS;
+import org.eclipse.wst.validation.IPerformanceMonitor;
+import org.eclipse.wst.validation.PerformanceCounters;
+import org.eclipse.wst.validation.internal.plugin.ValidationPlugin;
+
+public class PerformanceMonitor implements IPerformanceMonitor {
+
+ private CollectionLevel _level = CollectionLevel.None;
+ private boolean _summaryOnly;
+
+ /**
+ * Create a performance monitor.
+ *
+ * @param traceTimes
+ * Should the monitor be turned on?
+ * @param file
+ * Should the events be logged to a file. If this is null or the
+ * empty string the events will be written to stderr. Otherwise
+ * the events are appended to a file with this name.
+ *
+ * @param logInSeconds
+ * Set this to true if you want the times that are logged in the
+ * trace file normalized to seconds. Otherwise the default units are used,
+ * milliseconds for elapsed time and nanoseconds for cpu time.
+ */
+ public static PerformanceMonitor create(boolean traceTimes, String file, boolean logInSeconds){
+ PerformanceMonitor pm = null;
+ if (file == null || file.length() == 0)pm = new PerformanceMonitor();
+ else pm = new ToFile(file, logInSeconds);
+
+ if (traceTimes)pm.setCollectionLevel(CollectionLevel.Default);
+
+ return pm;
+ }
+
+ private PerformanceMonitor(){};
+
+ public CollectionLevel getCollectionLevel() {
+ return _level;
+ }
+
+ public void setCollectionLevel(CollectionLevel level) {
+ _level = level;
+ }
+
+ public List<PerformanceCounters> getPerformanceCounters(boolean asSummary) {
+ return new LinkedList<PerformanceCounters>();
+ }
+
+
+ public void resetPerformanceCounters() {
+ }
+
+ public boolean isCollecting() {
+ return _level != CollectionLevel.None;
+ }
+
+ public boolean isSummaryOnly() {
+ return _summaryOnly;
+ }
+
+ public void add(PerformanceCounters counters){
+ Tracing.write(counters.toString());
+ }
+
+ public static class Counters{
+ String name;
+ int numberInvocations;
+
+ /** Elapsed time in milliseconds. */
+ long elapsedTime;
+
+ /** CPU time in nanoseconds, or -1 if unknown. */
+ long cpuTime;
+ }
+
+ public static class ToFile extends PerformanceMonitor {
+
+ private String _fileName;
+ private boolean _logInSeconds;
+
+ private PrintWriter _pw;
+ private static final String Comma=","; //$NON-NLS-1$
+ private static DateFormat _df = new SimpleDateFormat("HH:mm:ss.SSSS"); //$NON-NLS-1$
+
+ private ToFile(String fileName, boolean logInSeconds){
+ _fileName = fileName;
+ _logInSeconds = logInSeconds;
+ }
+
+ @Override
+ public synchronized void add(PerformanceCounters pc) {
+ try {
+ PrintWriter pw = getWriter();
+ pw.print(_df.format(pc.getWhen()) + Comma +
+ pc.getValidatorId() + Comma + pc.getNumberInvocations() + Comma);
+ if (_logInSeconds){
+ double sec = ((double)pc.getElapsedTime()) / 1000.0;
+ pw.print(sec);
+ pw.print(Comma);
+ sec = ((double)pc.getCpuTime()) / 1000000000.0;
+ pw.print(sec);
+ }
+ else {
+ pw.print(pc.getElapsedTime()+Comma+pc.getCpuTime());
+ }
+ pw.println(Comma + pc.getResourceName());
+ pw.flush();
+ }
+ catch (IOException e){
+ ValidationPlugin.getPlugin().handleException(e);
+ }
+ }
+
+ private PrintWriter getWriter() throws IOException {
+ if (_pw == null){
+ _pw = new PrintWriter(new FileOutputStream(_fileName, true));
+ DateFormat df = DateFormat.getDateTimeInstance();
+ _pw.println("# " + NLS.bind(ValMessages.LogSession, //$NON-NLS-1$
+ df.format(new Date(System.currentTimeMillis()))));
+ if (_logInSeconds)
+ _pw.println("# when, id, invocation count, elapsed time (seconds), cpu time (seconds), resource"); //$NON-NLS-1$
+ else
+ _pw.println("# when, id, invocation count, elapsed time (ms), cpu time (ns), resource"); //$NON-NLS-1$
+ }
+ return _pw;
+
+ }
+ }
+
+ public static class Collecting extends PerformanceMonitor {
+ private List<PerformanceCounters> _counters = new LinkedList<PerformanceCounters>();
+
+ public void add(PerformanceCounters counters){
+ _counters.add(counters);
+ }
+
+ public List<PerformanceCounters> getPerformanceCounters(boolean asSummary) {
+ if (asSummary){
+ Map<String, Counters> map = new HashMap<String, Counters>(40);
+ for (PerformanceCounters pc : _counters){
+ Counters c = map.get(pc.getValidatorId());
+ if (c == null){
+ c = new Counters();
+ c.name = pc.getValidatorName();
+ map.put(pc.getValidatorId(), c);
+ }
+ c.numberInvocations += pc.getNumberInvocations();
+ c.elapsedTime += pc.getElapsedTime();
+ if (pc.getCpuTime() != -1)c.cpuTime += pc.getCpuTime();
+ else c.cpuTime = -1;
+ }
+ List<PerformanceCounters> list = new LinkedList<PerformanceCounters>();
+ for (Map.Entry<String, Counters> me : map.entrySet()){
+ Counters c = me.getValue();
+ list.add(new PerformanceCounters(me.getKey(), c.name, null, c.numberInvocations, c.elapsedTime, c.cpuTime));
+ }
+ return list;
+ }
+ return _counters;
+ }
+
+ public void resetPerformanceCounters() {
+ _counters.clear();
+ }
+
+ }
+
+}
diff --git a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/PrefConstants.java b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/PrefConstants.java
new file mode 100644
index 0000000..3bac075
--- /dev/null
+++ b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/PrefConstants.java
@@ -0,0 +1,116 @@
+/*******************************************************************************
+ * Copyright (c) 2007, 2008 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.wst.validation.internal;
+
+/**
+ * The constants that are used in the preference store so save the validator configurations.
+ * <p>
+ * The entries in the preference hierarchy are organized something like this:
+ * <pre>
+ * /instance/frame-work-id/saveAuto=true|false
+ * /instance/frame-work-id/suspend=true|false
+ * /instance/frame-work-id/vf.version=2
+ * /instance/frame-work-id/filters/val-id/build=true|false
+ * /instance/frame-work-id/filters/val-id/manual=true|false
+ * /instance/frame-work-id/filters/val-id/version=someNumber
+ * /instance/frame-work-id/filters/val-id/groups/0/type=include|exclude
+ * /instance/frame-work-id/filters/val-id/groups/0/rules/0/type=file|fileext|projectNature|...
+ * /instance/frame-work-id/filters/val-id/groups/0/rules/0/pattern=...
+ * /instance/frame-work-id/filters/val-id/groups/0/rules/1/type=file|fileext|projectNature|...
+ * /instance/frame-work-id/filters/val-id/groups/0/rules/1/pattern=...
+ * </pre>
+ * <p>
+ * New approach
+ * <pre>
+ * vals/val-id/global=TF[version][len]delegate-id
+ * vals/val-id/groups=[groups]
+ * </pre>
+ *
+ *
+ * @author karasiuk
+ *
+ */
+public interface PrefConstants {
+
+ /** filters - node where all the filters are saved. */
+ String filters = "filters"; //$NON-NLS-1$
+
+ /** build - is the validator enabled for builds? */
+ String build = "build"; //$NON-NLS-1$
+
+ /** delegate - the delegating implementation to use */
+ String delegate = "delegate"; //$NON-NLS-1$
+
+ /** disabled - the list of disabled resources in the project. */
+ String disabled = "disabled"; //$NON-NLS-1$
+
+ /** exactMatch - must the content type match exactly? */
+ String exactMatch = "exactMatch"; //$NON-NLS-1$
+
+ /** manual - is the validator enabled for manual validation? */
+ String manual = "manual"; //$NON-NLS-1$
+
+ /** msgs - node where all the message severity mappings are stored. */
+ String msgs = "msgs"; //$NON-NLS-1$
+
+ /**
+ * version - version of the filter definition. This is something that a client can use to keep track
+ * of changes that they might make to their validation extension.
+ */
+ String version = "version"; //$NON-NLS-1$
+
+ /** vf.version - version of the validation framework. */
+ String frameworkVersion = "vf.version"; //$NON-NLS-1$
+
+ /** groups - filter group. */
+ String groups = "groups"; //$NON-NLS-1$
+
+ /** type - type of group, either include or exclude. */
+ String type = "type"; //$NON-NLS-1$
+
+ /** type - the type of rule. */
+ String ruleType = "type"; //$NON-NLS-1$
+
+ /** rules - a filter rule. */
+ String rules = "rules"; //$NON-NLS-1$
+
+ /** pattern - the pattern part of the rule. */
+ String pattern = "pattern"; //$NON-NLS-1$
+
+ /** saveAuto - can we save all the resources automatically? true/false */
+ String saveAuto = "saveAuto"; //$NON-NLS-1$
+
+ /** stateTS - plug-in state time stamp */
+ String stateTS = "stateTS"; //$NON-NLS-1$
+
+ /** suspend - suspend all validation? true/false */
+ String suspend = "suspend"; //$NON-NLS-1$
+
+ /** case - is this case sensitive? */
+ String caseSensitive = "case"; //$NON-NLS-1$
+
+ /** fileType - the type of file, see FilterRule.File */
+ String fileType = "fileType"; //$NON-NLS-1$
+
+ /** confirmDialog - should we show a confirmation dialog when doing a manual validation? */
+ String confirmDialog = "confirmDialog"; //$NON-NLS-1$
+
+ /** override - should we show projects to override the global preferences? */
+ String override = "override"; //$NON-NLS-1$
+
+ /** vals - the validators are grouped under this node. */
+ String vals = "vals"; //$NON-NLS-1$
+
+ /** global - some global validation settings. */
+ String global = "global"; //$NON-NLS-1$
+
+
+}
diff --git a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/PreferencesWrapper.java b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/PreferencesWrapper.java
new file mode 100644
index 0000000..0f3a5e7
--- /dev/null
+++ b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/PreferencesWrapper.java
@@ -0,0 +1,431 @@
+/*******************************************************************************
+ * Copyright (c) 2009 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.wst.validation.internal;
+
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.atomic.AtomicReference;
+
+import org.eclipse.core.resources.IProject;
+import org.eclipse.wst.validation.ValidationFramework;
+import org.eclipse.wst.validation.internal.plugin.ValidationPlugin;
+import org.osgi.service.prefs.BackingStoreException;
+import org.osgi.service.prefs.Preferences;
+
+/**
+ * The subset of the IEclipsePreferences interface that the framework needs to
+ * be able to persist preferences.
+ * @author karasiuk
+ *
+ */
+public abstract class PreferencesWrapper {
+
+ private static final WrapperManger _manager = new WrapperManger();
+
+ /**
+ * Answer the preferences for the project. If project is null answer the global preferences.
+ * @param project
+ * @param persistent if null the default preferences are returned, if True the persisted
+ * preferences are return and if False the transient preferences are returned.
+ * @return
+ */
+ public static PreferencesWrapper getPreferences(IProject project, Boolean persistent){
+ return _manager.get(project, persistent);
+ }
+
+ /**
+ * These are the names of the node entries.
+ * @return
+ * @throws BackingStoreException
+ */
+ public abstract String[] childrenNames() throws BackingStoreException;
+
+ public void flush() throws BackingStoreException {
+ }
+
+ public abstract boolean getBoolean(String key, boolean def);
+
+ public abstract String get(String key, String def);
+
+ public abstract int getInt(String key, int def);
+
+ public abstract long getLong(String key, long def);
+
+ public abstract String[] keys() throws BackingStoreException;
+
+ public boolean isPersistent(){
+ return false;
+ }
+
+ public boolean isTransient(){
+ return false;
+ }
+
+ public abstract void put(String key, String value);
+
+ public abstract void putBoolean(String key, boolean value);
+
+ public abstract void putLong(String key, long value);
+
+ public abstract void putInt(String key, int value);
+
+ /**
+ * Unlike the more sophisticated org.osgi.service.prefs.Preferences support,
+ * this is currently limited to simple node names.
+ */
+ public abstract PreferencesWrapper node(String nodeName);
+
+ public abstract boolean nodeExists();
+
+ public abstract boolean nodeExists(String pathName) throws BackingStoreException;
+
+ public abstract void removeNode() throws BackingStoreException;
+
+
+public final static class PreferencesWrapperPersistent extends PreferencesWrapper {
+
+ private final Preferences _preferences;
+
+ public PreferencesWrapperPersistent(Preferences preferences){
+ _preferences = preferences;
+ }
+
+ @Override
+ public String[] childrenNames() throws BackingStoreException {
+ return _preferences.childrenNames();
+ }
+
+ public void flush() throws BackingStoreException {
+ _preferences.flush();
+ }
+
+ @Override
+ public String get(String key, String def) {
+ return _preferences.get(key, def);
+ }
+
+ @Override
+ public boolean getBoolean(String key, boolean def) {
+ return _preferences.getBoolean(key, def);
+ }
+
+ @Override
+ public int getInt(String key, int def) {
+ return _preferences.getInt(key, def);
+ }
+
+ @Override
+ public long getLong(String key, long def) {
+ return _preferences.getLong(key, def);
+ }
+
+ @Override
+ public String[] keys() throws BackingStoreException {
+ return _preferences.keys();
+ }
+
+ @Override
+ public boolean isPersistent() {
+ return true;
+ }
+
+ @Override
+ public void put(String key, String value) {
+ _preferences.put(key, value);
+ }
+
+ @Override
+ public PreferencesWrapper node(String path) {
+ Preferences prefs = _preferences.node(path);
+ return new PreferencesWrapperPersistent(prefs);
+ }
+
+ @Override
+ public boolean nodeExists() {
+ try {
+ return nodeExists(""); //$NON-NLS-1$
+ }
+ catch (BackingStoreException e){
+
+ }
+ return false;
+ }
+
+ @Override
+ public boolean nodeExists(String pathName) throws BackingStoreException {
+ return _preferences.nodeExists(pathName);
+ }
+
+ public void putBoolean(String key, boolean value) {
+ _preferences.putBoolean(key, value);
+ }
+
+ public void putLong(String key, long value){
+ _preferences.putLong(key, value);
+ }
+
+ @Override
+ public void putInt(String key, int value) {
+ _preferences.putInt(key, value);
+ }
+
+ @Override
+ public void removeNode() throws BackingStoreException {
+ _preferences.removeNode();
+ }
+}
+
+public final static class PreferencesWrapperTransient extends PreferencesWrapper {
+
+ private final PreferencesWrapperTransient _parent;
+ private final Map<String, String> _children = Collections.synchronizedMap(new HashMap<String, String>(10));
+ private final Map<String, PreferencesWrapperTransient> _nodes = Collections.synchronizedMap(new HashMap<String, PreferencesWrapperTransient>(10));
+
+ public PreferencesWrapperTransient(PreferencesWrapperTransient parent){
+ _parent = parent;
+ }
+
+ public PreferencesWrapperTransient(PreferencesWrapper pw, PreferencesWrapperTransient parent) {
+ _parent = parent;
+ try {
+ for (String key : pw.keys()){
+ put(key, pw.get(key, null));
+ }
+
+
+ for (String nodeName : pw.childrenNames()){
+ PreferencesWrapper p = pw.node(nodeName);
+ PreferencesWrapperTransient pwt = new PreferencesWrapperTransient(p, this);
+ _nodes.put(nodeName, pwt);
+ }
+ }
+ catch (BackingStoreException e){
+
+ }
+ }
+
+ @Override
+ public String[] childrenNames() throws BackingStoreException {
+ Set<String> keys = _nodes.keySet();
+ String names[] = new String[keys.size()];
+ keys.toArray(names);
+ return names;
+ }
+
+ @Override
+ public String get(String key, String def) {
+ String value = _children.get(key);
+ if (value != null)return value;
+ return def;
+ }
+
+ @Override
+ public boolean getBoolean(String key, boolean def) {
+ String value = _children.get(key);
+ if (value == null)return def;
+ value = value.toLowerCase();
+ if ("true".equals(value))return true; //$NON-NLS-1$
+ if ("false".equals(value))return false; //$NON-NLS-1$
+ return def;
+ }
+
+ @Override
+ public int getInt(String key, int def) {
+ String value = _children.get(key);
+ if (value == null)return def;
+ try {
+ return Integer.parseInt(value);
+ }
+ catch (NumberFormatException e){
+ }
+ return def;
+ }
+
+ @Override
+ public long getLong(String key, long def) {
+ String value = _children.get(key);
+ if (value == null)return def;
+ try {
+ return Long.parseLong(value);
+ }
+ catch (NumberFormatException e){
+ }
+ return def;
+ }
+
+ @Override
+ public boolean isTransient() {
+ return true;
+ }
+
+ @Override
+ public synchronized String[] keys() throws BackingStoreException {
+ String[] keys = new String[_children.size()];
+ _children.keySet().toArray(keys);
+ return keys;
+ }
+
+ @Override
+ public synchronized PreferencesWrapper node(String name) {
+ PreferencesWrapperTransient pw = _nodes.get(name);
+ if (pw != null)return pw;
+ pw = new PreferencesWrapperTransient(this);
+ _nodes.put(name, pw);
+ return pw;
+ }
+
+ @Override
+ public boolean nodeExists() {
+ return true;
+ }
+
+ @Override
+ public boolean nodeExists(String key) throws BackingStoreException {
+ PreferencesWrapperTransient pw = _nodes.get(key);
+ if (pw != null)return true;
+ return false;
+ }
+
+ @Override
+ public void put(String key, String value) {
+ _children.put(key, value);
+ }
+
+ @Override
+ public void putBoolean(String key, boolean bool) {
+ String value = bool ? "true" : "false"; //$NON-NLS-1$//$NON-NLS-2$
+ _children.put(key, value);
+ }
+
+ @Override
+ public void putInt(String key, int value) {
+ _children.put(key, String.valueOf(value));
+ }
+
+ @Override
+ public void putLong(String key, long value) {
+ _children.put(key, String.valueOf(value));
+ }
+
+ @Override
+ public void removeNode() throws BackingStoreException {
+ if (_parent == null)return;
+ _parent.removeNode(this);
+ }
+
+ private synchronized void removeNode(PreferencesWrapperTransient node){
+ String key = null;
+ for (Map.Entry<String, PreferencesWrapperTransient> me : _nodes.entrySet()){
+ if (me.getValue().equals(node)){
+ key = me.getKey();
+ break;
+ }
+ }
+ if (key != null)_nodes.remove(key);
+ }
+}
+
+private final static class WrapperManger implements IProjectChangeListener {
+
+ private final Map<IProject, PreferencesWrapper> _map = new HashMap<IProject, PreferencesWrapper>(20);
+ private final AtomicReference<PreferencesWrapper> _global = new AtomicReference<PreferencesWrapper>();
+
+ private WrapperManger(){
+ EventManager.getManager().addProjectChangeListener(this);
+ }
+
+ /**
+ * Currently this object never goes away, but if that was ever to change then we would need to dispose it.
+ */
+ @Override
+ protected void finalize() throws Throwable {
+ dispose();
+ }
+
+ public void dispose(){
+ EventManager.getManager().removeProjectChangeListener(this);
+ }
+
+ public PreferencesWrapper get(IProject project, Boolean persistent) {
+ if (project == null)return globalPreferences(persistent);
+ PreferencesWrapper pw = null;
+ synchronized(_map){
+ pw = _map.get(project);
+ }
+
+ if (pw != null && (persistent == null || persistent == pw.isPersistent()))return pw;
+
+ if (pw == null)pw = new PreferencesWrapperPersistent(ValidationPlugin.getPreferences(project));
+ if (persistent != null && persistent && pw.isTransient())pw = new PreferencesWrapperPersistent(ValidationPlugin.getPreferences(project));
+ if (persistent != null && !persistent && pw.isPersistent())pw = new PreferencesWrapperTransient(pw, null);
+
+ synchronized(_map){
+ _map.put(project, pw);
+ }
+
+ return pw;
+ }
+
+ /**
+ * Answer the appropriate global preferences.
+ *
+ * @param persistent
+ * If null then answer the current saved global preferences,
+ * creating a new persistent one if there is none. If True,
+ * then ensure that the preferences are persistent. If False,
+ * ensure that the preferences are transient.
+ * @return
+ */
+ private PreferencesWrapper globalPreferences(Boolean persistent) {
+ PreferencesWrapper pw = _global.get();
+
+ while(pw == null){
+ PreferencesWrapper newPW = createGlobal(persistent);
+ if (_global.compareAndSet(null, newPW))pw = newPW;
+ else pw = _global.get();
+ }
+
+ while (persistent != null && !persistent && !pw.isTransient()){
+ PreferencesWrapper newPW = new PreferencesWrapperTransient(pw, null);
+ if (_global.compareAndSet(pw, newPW))pw = newPW;
+ else pw = _global.get();
+ }
+
+ while (persistent != null && persistent && !pw.isPersistent()){
+ PreferencesWrapper newPW = new PreferencesWrapperPersistent(ValidationFramework.getDefault().getPreferenceStore());
+ if (_global.compareAndSet(pw, newPW))pw = newPW;
+ else pw = _global.get();
+ }
+ return pw;
+ }
+
+ private PreferencesWrapper createGlobal(Boolean persistent){
+ PreferencesWrapper pw = new PreferencesWrapperPersistent(ValidationFramework.getDefault().getPreferenceStore());
+ if (persistent == null || persistent)return pw;
+ return new PreferencesWrapperTransient(pw, null);
+ }
+
+ public void projectChanged(IProject project, int type) {
+ int interested = IProjectChangeListener.ProjectClosed | IProjectChangeListener.ProjectDeleted;
+ if ((type & interested) != 0){
+ synchronized (_map) {
+ _map.remove(project);
+ }
+ }
+
+ }
+
+}
+
+
+}
diff --git a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/ProjectUnavailableError.java b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/ProjectUnavailableError.java
new file mode 100644
index 0000000..03e2b65
--- /dev/null
+++ b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/ProjectUnavailableError.java
@@ -0,0 +1,41 @@
+/*******************************************************************************
+ * Copyright (c) 2005, 2008 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.wst.validation.internal;
+
+import org.eclipse.core.resources.IProject;
+
+/**
+ * This internal error is used to signal that a project is now unavailable.
+ * <p>
+ * We could be in the middle of validating a large project, and the project could be closed.
+ * This error is used to "exit" the validation framework.
+ * <p>
+ * This is an error rather than a runtime exception, because some parts of Eclipse like to
+ * trap RuntimeExceptions and log them.
+ * @author karasiuk
+ *
+ */
+public class ProjectUnavailableError extends Error {
+
+ private IProject _project;
+
+ private static final long serialVersionUID = 200801281118L;
+
+ public ProjectUnavailableError(IProject project){
+ super();
+ _project = project;
+ }
+
+ public IProject getProject() {
+ return _project;
+ }
+
+}
diff --git a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/ResourceUnavailableError.java b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/ResourceUnavailableError.java
new file mode 100644
index 0000000..9543670
--- /dev/null
+++ b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/ResourceUnavailableError.java
@@ -0,0 +1,40 @@
+/*******************************************************************************
+ * Copyright (c) 2005, 2008 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.wst.validation.internal;
+
+import org.eclipse.core.resources.IResource;
+
+/**
+ * This internal error is used to signal that a resource is now unavailable.
+ * <p>
+ * This error is used to "exit" the validation framework.
+ * <p>
+ * This is an error rather than a runtime exception, because some parts of Eclipse like to
+ * trap RuntimeExceptions and log them.
+ * @author karasiuk
+ *
+ */
+public class ResourceUnavailableError extends Error {
+
+ private static final long serialVersionUID = 200801290853L;
+
+ private IResource _resource;
+
+ public ResourceUnavailableError(IResource resource){
+ super();
+ _resource = resource;
+ }
+
+ public IResource getResource() {
+ return _resource;
+ }
+
+}
diff --git a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/Serializer.java b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/Serializer.java
new file mode 100644
index 0000000..22da768
--- /dev/null
+++ b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/Serializer.java
@@ -0,0 +1,48 @@
+/*******************************************************************************
+ * Copyright (c) 2008 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.wst.validation.internal;
+
+/**
+ * A simple encoder that knows how to convert booleans, integers and strings, into a single string.
+ *
+ * @see Deserializer
+ * @author karasiuk
+ *
+ */
+public class Serializer {
+ private StringBuffer _buffer;
+
+ public Serializer(int size){
+ _buffer = new StringBuffer(size);
+ }
+
+ public void put(boolean bool){
+ _buffer.append(bool ? 'T' : 'F');
+ }
+
+ public void put(String string){
+ put(string.length());
+ _buffer.append(string);
+ }
+
+ public void put(int anInt){
+ String s = String.valueOf(anInt);
+ int len = s.length();
+ _buffer.append(len-1);
+ _buffer.append(s);
+ }
+
+ @Override
+ public String toString() {
+ return _buffer.toString();
+ }
+
+}
diff --git a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/SummaryReporter.java b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/SummaryReporter.java
new file mode 100644
index 0000000..5a19332
--- /dev/null
+++ b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/SummaryReporter.java
@@ -0,0 +1,63 @@
+/*******************************************************************************
+ * Copyright (c) 2005, 2007 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.wst.validation.internal;
+
+import org.eclipse.core.resources.IProject;
+import org.eclipse.core.runtime.IProgressMonitor;
+import org.eclipse.wst.validation.internal.operations.WorkbenchReporter;
+import org.eclipse.wst.validation.internal.provisional.core.IMessage;
+import org.eclipse.wst.validation.internal.provisional.core.IValidator;
+
+/**
+ * This class extends the workbench reporter by capturing some summary information about any added
+ * messages.
+ * @author karasiuk
+ *
+ */
+public class SummaryReporter extends WorkbenchReporter {
+
+ private int _severityHigh;
+ private int _severityNormal;
+ private int _severityLow;
+
+ public SummaryReporter(IProject project, IProgressMonitor monitor) {
+ super(project, monitor);
+ }
+
+ @Override
+ public void addMessage(IValidator validator, IMessage message) {
+ super.addMessage(validator, message);
+ switch (message.getSeverity()){
+ case IMessage.HIGH_SEVERITY:
+ _severityHigh++;
+ break;
+ case IMessage.NORMAL_SEVERITY:
+ _severityNormal++;
+ break;
+ case IMessage.LOW_SEVERITY:
+ _severityLow++;
+ break;
+ }
+ }
+
+ public int getSeverityHigh() {
+ return _severityHigh;
+ }
+
+ public int getSeverityNormal() {
+ return _severityNormal;
+ }
+
+ public int getSeverityLow() {
+ return _severityLow;
+ }
+
+}
diff --git a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/Tracing.java b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/Tracing.java
new file mode 100644
index 0000000..77e49cb
--- /dev/null
+++ b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/Tracing.java
@@ -0,0 +1,208 @@
+/*******************************************************************************
+ * Copyright (c) 2005, 2009 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.wst.validation.internal;
+
+import java.text.DateFormat;
+import java.text.SimpleDateFormat;
+import java.util.Date;
+
+import org.eclipse.core.resources.IResourceDelta;
+import org.eclipse.core.resources.IResourceDeltaVisitor;
+import org.eclipse.core.runtime.CoreException;
+import org.eclipse.core.runtime.Platform;
+import org.eclipse.wst.validation.internal.plugin.ValidationPlugin;
+
+/**
+ * Control the tracing that this plug-in performs. This is used for service.
+ * @author karasiuk
+ *
+ */
+public final class Tracing {
+
+ private final static DateFormat _df = new SimpleDateFormat("HH:mm:ss.SSSS"); //$NON-NLS-1$
+ private final static boolean _isLogging = ValidationPlugin.getPlugin().isDebugging();
+ private final static boolean _traceMatches = Misc.debugOptionAsBoolean(DebugConstants.TraceMatches);
+ private final static boolean _traceV1 = Misc.debugOptionAsBoolean(DebugConstants.TraceV1);
+ private final static String _extraValDetail = Platform.getDebugOption(DebugConstants.ExtraValDetail);
+ private final static int _tracingLevel;
+
+ private final static String _filter = Platform.getDebugOption(DebugConstants.FilterAllExcept);
+
+ static {
+ String traceLevel = Platform.getDebugOption(DebugConstants.TraceLevel);
+ int level = 0;
+ if (traceLevel != null){
+ try {
+ level = Integer.parseInt(traceLevel);
+ }
+ catch (Exception e){
+ }
+ }
+ _tracingLevel = level;
+ }
+
+ /**
+ * Answer true if the filters allow this validator to be enabled. Normally this method will answer true.
+ * It is only when filters are activated via the debugging options, that this method might return false.
+ * This is used to aid in debugging by making it look like only one validator has been registered.
+ *
+ * @param validatorId the validator id.
+ * @return true if the validator should be registered via an extension point.
+ */
+ public static boolean isEnabled(String validatorId){
+ if (_filter == null || _filter.length() == 0)return true;
+ return (_filter.equals(validatorId));
+ }
+
+ /**
+ * Are we in logging/debugging mode?
+ */
+ public static boolean isLogging(){
+ return _isLogging;
+ }
+
+ /**
+ * Answer true if we are in logging mode, and if the current logging level is greater than or
+ * equal to level.
+ * @param level The logging level that we are testing. The higher the level the more verbose
+ * the tracing.
+ */
+ public static boolean isLogging(int level){
+ if (_isLogging){
+ return _tracingLevel >= level;
+ }
+ return false;
+ }
+
+ public static boolean isTraceMatches(){
+ return _traceMatches;
+ }
+
+ public static boolean isTraceV1(){
+ return _traceV1;
+ }
+
+ public static boolean matchesExtraDetail(String validatorId){
+ if (_extraValDetail == null)return false;
+ return _extraValDetail.equals(validatorId);
+ }
+
+ /**
+ * Write a line to the console for debugging, if in debugging mode.
+ * @param line
+ */
+ public static void log(String line){
+ if (isLogging())write(line);
+ }
+
+ public static void log(Object... parts){
+ if (isLogging()){
+ StringBuffer b = new StringBuffer(200);
+ for (Object p : parts)b.append(p);
+ write(b.toString());
+ }
+ }
+
+ /**
+ * Write a line to the log. Include a time stamp with the line.
+ * @param line
+ */
+ public static void write(String line){
+ System.err.println(timestampIt(line));
+ }
+
+ public static String timestampIt(String line){
+ Date date = new Date();
+ String thread = Thread.currentThread().getName();
+ return _df.format(date) + " " + thread + " " + line; //$NON-NLS-1$//$NON-NLS-2$
+ }
+
+ /**
+ * If we are in logging mode, log the item, and then reset the string buffer.
+ */
+ public static void log(StringBuffer b){
+ log(b.toString());
+ b.setLength(0);
+ }
+
+ /**
+ * This method doesn't do anything, and will be removed.
+ *
+ * @deprecated
+ */
+ public static void setForceLogging(boolean forceLogging) {
+ }
+
+ /**
+ * Log up to maxNumber deltas to the log.
+ * @param delta The deltas to log.
+ * @param maxNumber The maximum number of deltas to log.
+ */
+ public static void logResourceDeltas(IResourceDelta delta, int maxNumber){
+ if (!isLogging())return;
+ if (delta == null)Tracing.log(" ResourceDelta: null"); //$NON-NLS-1$
+ else {
+ DeltaLogger logger = new DeltaLogger(maxNumber);
+ try {
+ delta.accept(logger);
+ if (logger.getCount() == 0)Tracing.log(" ResourceDelta: no deltas"); //$NON-NLS-1$
+ }
+ catch (CoreException e){
+ // eat it
+ }
+ }
+ }
+
+ /**
+ * A debugging class that prints out some resource delta's.
+ * @author karasiuk
+ *
+ */
+ private final static class DeltaLogger implements IResourceDeltaVisitor {
+
+ private final int _max;
+ private int _count;
+ public int getCount() {
+ return _count;
+ }
+
+ private StringBuffer _b = new StringBuffer(200);
+
+ public DeltaLogger(int max){
+ _max = max;
+ }
+
+ public boolean visit(IResourceDelta delta) throws CoreException {
+ if (_count++ > _max)return false;
+ int kind = delta.getKind();
+ String type = "unknown"; //$NON-NLS-1$
+ switch (kind){
+ case IResourceDelta.ADDED:
+ type = "Added"; //$NON-NLS-1$
+ break;
+ case IResourceDelta.CHANGED:
+ type = "Changed"; //$NON-NLS-1$
+ break;
+ case IResourceDelta.REMOVED:
+ type = "Removed"; //$NON-NLS-1$
+ break;
+ }
+ _b.append(" ResourceDelta "); //$NON-NLS-1$
+ _b.append(type);
+ _b.append(' ');
+ _b.append(delta.getResource());
+ Tracing.log(_b);
+ return true;
+ }
+
+ }
+
+}
diff --git a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/ValBuilderJob.java b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/ValBuilderJob.java
new file mode 100644
index 0000000..5aafeee
--- /dev/null
+++ b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/ValBuilderJob.java
@@ -0,0 +1,345 @@
+/*******************************************************************************
+ * Copyright (c) 2007, 2008 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.wst.validation.internal;
+
+import java.util.LinkedList;
+import java.util.Queue;
+
+import org.eclipse.core.resources.IProject;
+import org.eclipse.core.resources.IResource;
+import org.eclipse.core.resources.IResourceDelta;
+import org.eclipse.core.resources.IResourceDeltaVisitor;
+import org.eclipse.core.resources.IResourceProxy;
+import org.eclipse.core.resources.IResourceProxyVisitor;
+import org.eclipse.core.resources.IResourceVisitor;
+import org.eclipse.core.resources.ResourcesPlugin;
+import org.eclipse.core.resources.WorkspaceJob;
+import org.eclipse.core.runtime.CoreException;
+import org.eclipse.core.runtime.IProgressMonitor;
+import org.eclipse.core.runtime.IStatus;
+import org.eclipse.core.runtime.Status;
+import org.eclipse.core.runtime.SubMonitor;
+import org.eclipse.wst.validation.DependentResource;
+import org.eclipse.wst.validation.Friend;
+import org.eclipse.wst.validation.IDependencyIndex;
+import org.eclipse.wst.validation.ValidationEvent;
+import org.eclipse.wst.validation.ValidationFramework;
+import org.eclipse.wst.validation.ValidationState;
+import org.eclipse.wst.validation.Validator;
+import org.eclipse.wst.validation.internal.model.IValidatorVisitor;
+import org.eclipse.wst.validation.internal.operations.ValidationBuilder;
+import org.eclipse.wst.validation.internal.plugin.ValidationPlugin;
+
+
+/**
+ * Run all the v2 validators through this job.
+ * <p>
+ * This is the main class for supporting build based validation. When triggered it looks at all of the
+ * resource changes and determines what needs to be validated.
+ * </p>
+ * @author karasiuk
+ *
+ */
+public final class ValBuilderJob extends WorkspaceJob {
+
+ private static ValBuilderJob _job;
+ private static Queue<ValidationRequest> _work = new LinkedList<ValidationRequest>();
+
+ private final ValOperation _operation = new ValOperation();
+
+ /** The types of changes we are interested in. */
+ private final static int InterestedFlags = IResourceDelta.CONTENT | IResourceDelta.ENCODING |
+ IResourceDelta.MOVED_FROM | IResourceDelta.MOVED_TO;
+
+ public static synchronized void validateProject(IProject project, IResourceDelta delta, int buildKind){
+ ValidationRequest request = new ValidationRequest(project, delta, buildKind);
+ if (_job == null){
+ _job = new ValBuilderJob();
+ _job.add(request);
+ _job.schedule();
+ }
+ else {
+ _job.add(request);
+ }
+ }
+
+ private static synchronized ValidationRequest getRequest(){
+ ValidationRequest request = _work.poll();
+ if (request == null){
+ _job = null;
+ }
+ return request;
+ }
+
+ /**
+ * Each validation run is done in it's own job.
+ *
+ * @param project the project that is being validated
+ * @param delta the delta that is being validated. This may be null, in which case we do a
+ * full validation of the project.
+ *
+ * @param buildKind the kind of build.
+ * @see org.eclipse.core.resources.IncrementalProjectBuilder#AUTO_BUILD
+ * @see org.eclipse.core.resources.IncrementalProjectBuilder#CLEAN_BUILD
+ * @see org.eclipse.core.resources.IncrementalProjectBuilder#FULL_BUILD
+ * @see org.eclipse.core.resources.IncrementalProjectBuilder#INCREMENTAL_BUILD
+ *
+ * @param operation some global context for the validation operation
+ *
+ */
+ private ValBuilderJob(){
+ super(ValMessages.JobName);
+ }
+
+ private void add(ValidationRequest request){
+ _work.add(request);
+ }
+
+ @Override
+ public boolean belongsTo(Object family) {
+ if (family == ResourcesPlugin.FAMILY_MANUAL_BUILD)return true;
+ if (family == ValidationBuilder.FAMILY_VALIDATION_JOB){
+ return true;
+ }
+
+ return super.belongsTo(family);
+ }
+
+ @Override
+ public IStatus runInWorkspace(IProgressMonitor monitor) {
+ Tracing.log("ValBuilderJob-01: Starting"); //$NON-NLS-1$
+
+ try {
+ startingValidation(monitor);
+
+ ValidationRequest request = getRequest();
+ while(request != null){
+ run(request, monitor);
+ request = getRequest();
+ }
+ }
+ finally {
+ finishingValidation(monitor);
+ }
+
+ Tracing.log("ValBuilderJob-02: Finished"); //$NON-NLS-1$
+ return Status.OK_STATUS;
+ }
+
+ private void startingValidation(IProgressMonitor monitor) {
+ IValidatorVisitor startingVisitor = new IValidatorVisitor(){
+
+ public void visit(Validator validator, IProject project, ValType valType,
+ ValOperation operation, IProgressMonitor monitor) {
+
+ validator.validationStarting(project, operation.getState(), monitor);
+ }
+ };
+
+ ValManager.getDefault().accept(startingVisitor, null, ValType.Build, getOperation(), monitor);
+ }
+
+ private void finishingValidation(IProgressMonitor monitor) {
+
+ IValidatorVisitor finishedVisitor = new IValidatorVisitor(){
+
+ public void visit(Validator validator, IProject project, ValType valType,
+ ValOperation operation, IProgressMonitor monitor) {
+
+ validator.validationFinishing(project, operation.getState(), monitor);
+ }
+ };
+ ValManager.getDefault().accept(finishedVisitor, null, ValType.Build, getOperation(), monitor);
+ }
+
+ private void run(ValidationRequest request, IProgressMonitor monitor){
+ setName(ValMessages.JobName + " " + request.getProject().getName()); //$NON-NLS-1$
+ try {
+ IValidatorVisitor startingVisitor = new IValidatorVisitor(){
+
+ public void visit(Validator validator, IProject project, ValType valType,
+ ValOperation operation, IProgressMonitor monitor) {
+
+ validator.validationStarting(project, operation.getState(), monitor);
+ }
+ };
+
+ ValManager.getDefault().accept(startingVisitor, request.getProject(), ValType.Build, getOperation(), monitor);
+
+ if (request.getDelta() == null)fullBuild(request, monitor);
+ else deltaBuild(request, monitor);
+
+
+ }
+ catch (ProjectUnavailableError e){
+ ValidationPlugin.getPlugin().handleProjectUnavailableError(e);
+ }
+ catch (ResourceUnavailableError e){
+ ValidationPlugin.getPlugin().handleResourceUnavailableError(e);
+ }
+ catch (CoreException e){
+ ValidationPlugin.getPlugin().handleException(e);
+ }
+ finally {
+ IValidatorVisitor finishedVisitor = new IValidatorVisitor(){
+
+ public void visit(Validator validator, IProject project, ValType valType,
+ ValOperation operation, IProgressMonitor monitor) {
+
+ validator.validationFinishing(project, operation.getState(), monitor);
+ }
+ };
+ ValManager.getDefault().accept(finishedVisitor, request.getProject(), ValType.Build, getOperation(), monitor);
+ }
+
+ }
+
+ private void deltaBuild(ValidationRequest request, IProgressMonitor monitor) throws CoreException {
+ ResourceCounter counter = new ResourceCounter();
+ request.getDelta().accept(counter);
+ SubMonitor subMonitor = SubMonitor.convert(monitor, counter.getCount());
+ Visitor vistitor = new Visitor(request, subMonitor, monitor, getOperation());
+ request.getDelta().accept(vistitor);
+ }
+
+ private void fullBuild(ValidationRequest request, IProgressMonitor monitor) throws CoreException {
+ ResourceCounter counter = new ResourceCounter();
+ request.getProject().accept(counter, 0);
+ SubMonitor subMonitor = SubMonitor.convert(monitor, counter.getCount());
+ Visitor vistitor = new Visitor(request, subMonitor, monitor, getOperation());
+ request.getProject().accept(vistitor);
+
+ }
+
+ private ValOperation getOperation(){
+ return _operation;
+ }
+
+ static final class ResourceCounter implements IResourceProxyVisitor, IResourceDeltaVisitor {
+
+ private int _count;
+
+ public int getCount() {
+ return _count;
+ }
+
+ public boolean visit(IResourceProxy proxy) throws CoreException {
+ _count++;
+ return true;
+ }
+
+ public boolean visit(IResourceDelta delta) throws CoreException {
+ _count++;
+ return true;
+ }
+ }
+
+ static final class ValidationRequest {
+ /** The project that is being built. */
+ private final IProject _project;
+
+ /** The resource delta that triggered the build, it will be null for a full build. */
+ private final IResourceDelta _delta;
+
+ /**
+ * The kind of build.
+ *
+ * @see org.eclipse.core.resources.IncrementalProjectBuilder
+ */
+ private final int _buildKind;
+
+ public ValidationRequest(IProject project, IResourceDelta delta, int buildKind){
+ _project = project;
+ _delta = delta;
+ _buildKind = buildKind;
+ }
+
+ public IProject getProject() {
+ return _project;
+ }
+
+ public IResourceDelta getDelta() {
+ return _delta;
+ }
+
+ public int getBuildKind() {
+ return _buildKind;
+ }
+ }
+
+ private final static class Visitor implements IResourceDeltaVisitor, IResourceVisitor{
+
+ private final ValidationRequest _request;
+ private final SubMonitor _subMonitor;
+ private final IProgressMonitor _monitor;
+ private final ValOperation _operation;
+
+ public Visitor(ValidationRequest request, SubMonitor subMonitor, IProgressMonitor monitor, ValOperation operation){
+ _request = request;
+ _subMonitor = subMonitor;
+ _monitor = monitor;
+ _operation = operation;
+ }
+
+ public boolean visit(IResource resource) throws CoreException {
+ try {
+ if (DisabledResourceManager.getDefault().isDisabled(resource)){
+ MarkerManager.getDefault().deleteMarkers(resource, _operation.getStarted(), IResource.DEPTH_INFINITE);
+ return false;
+ }
+ ValManager.getDefault().validate(_request.getProject(), resource, IResourceDelta.NO_CHANGE, ValType.Build,
+ _request.getBuildKind(), _operation, _subMonitor.newChild(1));
+ }
+ catch (ResourceUnavailableError e){
+ if (Tracing.isLogging())Tracing.log("ValBuilderJob-02: " + e.toString()); //$NON-NLS-1$
+ return false;
+ }
+ return true;
+ }
+
+ @SuppressWarnings("deprecation")
+ public boolean visit(IResourceDelta delta) throws CoreException {
+ IResource resource = delta.getResource();
+ if (DisabledResourceManager.getDefault().isDisabled(resource)){
+ MarkerManager.getDefault().deleteMarkers(resource, _operation.getStarted(), IResource.DEPTH_INFINITE);
+ return false;
+ }
+ int kind = delta.getKind();
+ boolean isChanged = (kind & IResourceDelta.CHANGED) != 0;
+ if (isChanged && (delta.getFlags() & InterestedFlags) == 0)return true;
+
+ if ((kind & (IResourceDelta.ADDED | IResourceDelta.CHANGED)) != 0){
+ ValManager.getDefault().validate(_request.getProject(), resource, delta.getKind(), ValType.Build,
+ _request.getBuildKind(), _operation, _subMonitor.newChild(1));
+ }
+
+ IDependencyIndex index = ValidationFramework.getDefault().getDependencyIndex();
+ if (index.isDependedOn(resource)){
+ MarkerManager mm = MarkerManager.getDefault();
+ for (DependentResource dr : index.get(resource)){
+ Validator val = dr.getValidator();
+ if (Friend.shouldValidate(val, dr.getResource(), ValType.Build, new ContentTypeWrapper())){
+ _operation.getState().put(ValidationState.TriggerResource, resource);
+ ValidationEvent event = new ValidationEvent(dr.getResource(), IResourceDelta.NO_CHANGE, delta);
+ if (val.shouldClearMarkers(event))mm.clearMarker(dr.getResource(), val);
+ ValManager.getDefault().validate(val, _operation, dr.getResource(),
+ IResourceDelta.NO_CHANGE, _monitor, event);
+ }
+ }
+ }
+
+ return true;
+ }
+
+
+ }
+
+}
diff --git a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/ValConstants.java b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/ValConstants.java
new file mode 100644
index 0000000..ab2aebf
--- /dev/null
+++ b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/ValConstants.java
@@ -0,0 +1,19 @@
+/*******************************************************************************
+ * Copyright (c) 2005, 2007 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.wst.validation.internal;
+
+import org.eclipse.wst.validation.internal.plugin.ValidationPlugin;
+
+public interface ValConstants {
+ /** problem marker for version 2 of the validation framework. */
+ String ProblemMarker = ValidationPlugin.PLUGIN_ID +".problemmarker2"; //$NON-NLS-1$
+
+}
diff --git a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/ValManager.java b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/ValManager.java
new file mode 100644
index 0000000..9214a19
--- /dev/null
+++ b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/ValManager.java
@@ -0,0 +1,1291 @@
+/*******************************************************************************
+ * Copyright (c) 2007, 2008 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.wst.validation.internal;
+
+import java.lang.reflect.InvocationTargetException;
+import java.util.BitSet;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.TreeSet;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ConcurrentMap;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.atomic.AtomicReference;
+
+import org.eclipse.core.resources.IFolder;
+import org.eclipse.core.resources.IProject;
+import org.eclipse.core.resources.IResource;
+import org.eclipse.core.resources.IResourceStatus;
+import org.eclipse.core.resources.IResourceVisitor;
+import org.eclipse.core.resources.IWorkspaceRoot;
+import org.eclipse.core.resources.ResourcesPlugin;
+import org.eclipse.core.runtime.CoreException;
+import org.eclipse.core.runtime.IProgressMonitor;
+import org.eclipse.core.runtime.ISafeRunnable;
+import org.eclipse.core.runtime.IStatus;
+import org.eclipse.core.runtime.QualifiedName;
+import org.eclipse.core.runtime.SafeRunner;
+import org.eclipse.core.runtime.Status;
+import org.eclipse.core.runtime.SubMonitor;
+import org.eclipse.osgi.util.NLS;
+import org.eclipse.wst.common.project.facet.core.FacetedProjectFramework;
+import org.eclipse.wst.common.project.facet.core.events.IFacetedProjectEvent;
+import org.eclipse.wst.common.project.facet.core.events.IFacetedProjectListener;
+import org.eclipse.wst.validation.Friend;
+import org.eclipse.wst.validation.IPerformanceMonitor;
+import org.eclipse.wst.validation.IValidatorGroupListener;
+import org.eclipse.wst.validation.PerformanceCounters;
+import org.eclipse.wst.validation.ValidationEvent;
+import org.eclipse.wst.validation.ValidationFramework;
+import org.eclipse.wst.validation.ValidationResult;
+import org.eclipse.wst.validation.ValidationState;
+import org.eclipse.wst.validation.Validator;
+import org.eclipse.wst.validation.internal.model.GlobalPreferences;
+import org.eclipse.wst.validation.internal.model.GlobalPreferencesValues;
+import org.eclipse.wst.validation.internal.model.IValidatorVisitor;
+import org.eclipse.wst.validation.internal.model.ProjectPreferences;
+import org.eclipse.wst.validation.internal.operations.ManualValidatorsOperation;
+import org.eclipse.wst.validation.internal.plugin.ValidationPlugin;
+import org.osgi.service.prefs.BackingStoreException;
+
+/**
+ * A central place to keep track of all the validators.
+ * @author karasiuk
+ *
+ */
+public final class ValManager implements IValChangedListener, IFacetedProjectListener, IProjectChangeListener {
+
+ /**
+ * Projects may be allowed to override the global validation settings. If that is the case then those
+ * project specific settings are saved here. If the key exists, but the value is null, then that
+ * means that the project has been checked and it does not have any specific settings.
+ */
+ private final Map<IProject, ProjectPreferences> _projectPreferences =
+ Collections.synchronizedMap(new HashMap<IProject, ProjectPreferences>(50));
+
+ private final AtomicReference<GlobalPreferences> _globalPreferences = new AtomicReference<GlobalPreferences>();
+
+ /**
+ * This number increases each time any of the validation configurations change. It is used to determine
+ * if information that we have cached in the ValProperty is stale or not. This starts off at zero, each time
+ * the workbench is started.
+ */
+ private final AtomicInteger _configNumber = new AtomicInteger();
+
+ private final ValidatorIdManager _idManager = new ValidatorIdManager();
+ private final ValidatorCache _cache = new ValidatorCache();
+
+ private static final QualifiedName StatusBuild = new QualifiedName(ValidationPlugin.PLUGIN_ID, "sb"); //$NON-NLS-1$
+ private static final QualifiedName StatusManual = new QualifiedName(ValidationPlugin.PLUGIN_ID, "sm"); //$NON-NLS-1$
+
+
+ public static ValManager getDefault(){
+ return Singleton.valManager;
+ }
+
+ private ValManager(){
+ ValPrefManagerGlobal.getDefault().addListener(this);
+ ValPrefManagerProject.addListener(this);
+ FacetedProjectFramework.addListener(this, IFacetedProjectEvent.Type.PROJECT_MODIFIED);
+ EventManager.getManager().addProjectChangeListener(this);
+ }
+
+ /**
+ * This needs to be called if the ValManager is ever deleted.
+ */
+ public void dispose(){
+ // currently nobody calls this method, because this instance is never removed, but the method is
+ // here for completeness none the less.
+ ValPrefManagerGlobal.getDefault().removeListener(this);
+ ValPrefManagerProject.removeListener(this);
+ FacetedProjectFramework.removeListener(this);
+ EventManager.getManager().removeProjectChangeListener(this);
+ }
+
+ /**
+ * Answer all the registered validators. If you are planning on making changes to the validators,
+ * and then saving them in a preference store then you probably want the getValidatorsCopy method.
+ * Because if you make changes to the original validators, and since we only save differences,
+ * there won't be any differences.
+ *
+ * @return Answer the validators in name sorted order. Answer an empty array if there are no validators.
+ *
+ * @see #getValidatorsCopy()
+ */
+ public Validator[] getValidators(){
+ return getValidators(null);
+ }
+
+ /**
+ * Answer copies of all the registered validators. If you are going to be making changes to the validators
+ * and then saving them backing into the preference store, then this is the method to use.
+ *
+ * @return Answer an empty array if there are no validators.
+ */
+ public Validator[] getValidatorsCopy(){
+ Validator[] orig = getValidators();
+ Validator[] copy = new Validator[orig.length];
+ for (int i=0; i<orig.length; i++)copy[i] = orig[i].copy();
+ return copy;
+ }
+
+ /**
+ * Answer all the validators for the given project.
+ * <p>
+ * Individual projects may override the global validation preference
+ * settings. If the project has it's own settings, then those validators are
+ * returned via this method.
+ * </p>
+ * <p>
+ * The following approach is used. For version 1 validators, the validator
+ * is only returned if it is defined to operate on this project type. This
+ * is the way that the previous version of the framework did it. For version
+ * 2 validators, they are all returned.
+ * </p>
+ *
+ * @param project
+ * this may be null, in which case the global preferences are
+ * returned.
+ * @param respectOverrideSettings
+ * if this is true then the validators that get returned are
+ * based on the override settings. So for example, if the global
+ * preferences do not allow project overrides then none of the
+ * project settings are used. Normal validation would set this to true.
+ * The properties page would set this to false.
+ *
+ * @deprecated Use {@link #getValidatorsNotCached(IProject)} instead
+ */
+ public Validator[] getValidators(IProject project, boolean respectOverrideSettings) throws ProjectUnavailableError {
+ return getValidators(project);
+ }
+
+ /**
+ * Answer a cached copy of the the validators for a given project. This is a front end method,
+ * for the getValidatorsNotCached() method.
+ * <p>
+ * Individual projects may override the global validation preference
+ * settings. If the project has it's own settings, then those validators are
+ * returned via this method.
+ * </p>
+ * <p>
+ * The following approach is used. For version 1 validators, the validator
+ * is only returned if it is defined to operate on this project type. This
+ * is the way that the previous version of the framework did it. For version
+ * 2 validators, they are all returned.
+ * </p>
+ *
+ * @param project
+ * This may be null, in which case the global preferences are
+ * returned.
+ *
+ * @return The validators in name sorted order.
+ */
+ public Validator[] getValidators(IProject project) throws ProjectUnavailableError {
+ return _cache.getValidatorsCached(project);
+ }
+
+ /**
+ * Answer all the validators for the given project.
+ * <p>
+ * Individual projects may override the global validation preference
+ * settings. If the project has it's own settings, then those validators are
+ * returned via this method.
+ * </p>
+ * <p>
+ * The following approach is used. For version 1 validators, the validator
+ * is only returned if it is defined to operate on this project type. This
+ * is the way that the previous version of the framework did it. For version
+ * 2 validators, they are all returned.
+ * </p>
+ *
+ * @param project
+ * This may be null, in which case the global preferences are
+ * returned.
+ *
+ * @return The validators in name sorted order.
+ */
+ private Validator[] getValidatorsNotCached(IProject project) throws ProjectUnavailableError {
+ Map<String,Validator> v2Vals = getV2Validators(project, UseProjectPreferences.Normal);
+ TreeSet<Validator> sorted = new TreeSet<Validator>();
+ sorted.addAll(v2Vals.values());
+
+ try {
+ ValidationConfiguration vc = ConfigurationManager.getManager().getConfiguration(project);
+ if (project == null){
+ // If the project is null we need to use this approach, since you can not use new ManualValidatorsOperation(null)
+ ValidatorMetaData[] vmds = vc.getValidators();
+ for (ValidatorMetaData vmd : vmds){
+ Validator v = Validator.create(vmd, vc, project);
+ sorted.add(v);
+ }
+ }
+ else {
+ ManualValidatorsOperation mvo = new ManualValidatorsOperation(project);
+ Set<ValidatorMetaData> vmds = mvo.getEnabledValidators();
+ for (ValidatorMetaData vmd : vmds){
+ Validator v = Validator.create(vmd, vc, project);
+ sorted.add(v);
+ }
+ }
+ }
+ catch (InvocationTargetException e){
+ ValidationPlugin.getPlugin().handleException(e);
+ }
+
+ Validator[] vals = new Validator[sorted.size()];
+ sorted.toArray(vals);
+ return vals;
+ }
+ /**
+ * Validators can use project level settings (Project natures and facets) to
+ * determine if they are applicable to the project or not.
+ *
+ * @param project
+ * The project that the configuration is based on.
+ * @param mustUseProjectSettings
+ * Force the project properties to be used. There is a case where the user has toggled the
+ * Enable project specific settings checkbox in the dialog, but has not yet committed the
+ * changes. This allows that setting to be passed through.
+ * @return The validators that are configured to run on this project based
+ * on the project level settings. These are the "live" validators, they are not copies.
+ * @throws ProjectUnavailableError
+ *
+ * @deprecated Use getValidatorsConfiguredForProject(IProject project, UseProjectPreferences useProject)
+ */
+ public Validator[] getValidatorsConfiguredForProject(IProject project, boolean mustUseProjectSettings) throws ProjectUnavailableError {
+ UseProjectPreferences useProject = UseProjectPreferences.Normal;
+ return getValidatorsConfiguredForProject(project, useProject);
+ }
+
+ /**
+ * Validators can use project level settings (Project natures and facets) to
+ * determine if they are applicable to the project or not.
+ *
+ * @param project
+ * The project that the configuration is based on.
+ * @param useProject
+ * Specifies how to use the project preferences. This can be used
+ * to force the project properties to be used. There is a case
+ * where the user has toggled the Enable project specific
+ * settings checkbox in the dialog, but has not yet committed the
+ * changes. This allows that setting to be passed through.
+ * @return The validators that are configured to run on this project based
+ * on the project level settings. These are the "live" validators,
+ * they are not copies.
+ * @throws ProjectUnavailableError
+ */
+ public Validator[] getValidatorsConfiguredForProject(IProject project, UseProjectPreferences useProject) throws ProjectUnavailableError {
+ Map<String,Validator> v2Vals = getV2Validators(project, useProject);
+ TreeSet<Validator> sorted = new TreeSet<Validator>();
+ sorted.addAll(v2Vals.values());
+
+ if (useProject == UseProjectPreferences.MustNotUse){
+ sorted.addAll(ExtensionValidators.instance().getV1Validators(project));
+ }
+ else {
+ try {
+ ValidationConfiguration vc = ConfigurationManager.getManager().getProjectConfiguration(project);
+ ValidatorMetaData[] vmds = vc.getValidators();
+ for (ValidatorMetaData vmd : vmds) {
+ Validator v = Validator.create(vmd, vc, project);
+ sorted.add(v);
+ }
+ }
+ catch (InvocationTargetException e){
+ ValidationPlugin.getPlugin().handleException(e);
+ }
+ }
+
+ List<Validator> list = new LinkedList<Validator>();
+ for (Validator v : sorted){
+ if (v.shouldValidateProject(project, false, false))list.add(v);
+ }
+
+ Validator[]vals = new Validator[list.size()];
+ list.toArray(vals);
+ return vals;
+ }
+
+ /**
+ * Answer the V2 validators that are in effect for this project. The
+ * following approach is used:
+ * <ol>
+ * <li>The validators that are defined by the extension point are loaded.</li>
+ * <li>They are customized by any global preferences.</li>
+ * <li>If project customizations are allowed, they are customized by the
+ * project preferences.
+ * </ol>
+ *
+ * @param project
+ * This may be null, in which case only the global preferences
+ * are used.
+ * @param useProject
+ * Specifies how to use the project preferences. This can be used
+ * to force the project properties to be used. There is a case
+ * where the user has toggled the Enable project specific
+ * settings checkbox in the dialog, but has not yet committed the
+ * changes. This allows that setting to be passed through.
+ *
+ * @return
+ */
+ private Map<String,Validator> getV2Validators(IProject project, UseProjectPreferences useProject){
+ Map<String,Validator> extVals = ExtensionValidators.instance().getMapV2Copy();
+ try {
+ List<Validator> vals = ValPrefManagerGlobal.getDefault().getValidators();
+ for (Validator v : vals)extVals.put(v.getId(), v);
+
+ if (useProject != UseProjectPreferences.MustNotUse){
+ if (useProject == UseProjectPreferences.MustUse || !mustUseGlobalValidators(project)){
+ //TODO should probably cache this vpm
+ ValPrefManagerProject vpm = new ValPrefManagerProject(project);
+ vals = vpm.getValidators(extVals);
+ for (Validator v : vals)extVals.put(v.getId(), v);
+
+ for (Validator v : getProjectPreferences(project).getValidators())extVals.put(v.getId(), v);
+ }
+ }
+ }
+ catch (BackingStoreException e){
+ ValidationPlugin.getPlugin().handleException(e);
+ }
+ return extVals;
+ }
+
+
+ /**
+ * Answer true if we must use the global settings for this project. If the global preferences do not
+ * allow overrides, or if this project does not allow overrides then the global preferences must be used.
+ *
+ * @param project project that is being tested. It can be null, in which case the global preferences must be used.
+ * @return true if the global preferences must be used.
+ */
+ public boolean mustUseGlobalValidators(IProject project){
+ if (project == null)return true;
+ if (!getGlobalPreferences().getOverride())return true;
+ ProjectPreferences pp = _projectPreferences.get(project);
+ if (pp != null)return !pp.getOverride();
+
+ ValPrefManagerProject vpm = new ValPrefManagerProject(project);
+ return !vpm.getOverride();
+ }
+
+ /**
+ * Answer the validator with the given id that is in effect for the given project.
+ *
+ * @param id The validator id.
+ * @param project
+ * @return null if the validator is not found
+ */
+ public Validator getValidator(String id, IProject project){
+ Validator[] vals = getValidators(project);
+ for (Validator v : vals){
+ if (v.getId().equals(id))return v;
+ }
+ return null;
+ }
+
+ /**
+ * @see ValidationFramework#getValidator(String, IProject)
+ */
+ public Validator getValidatorWithId(String id, IProject project){
+ Validator[] vals = getValidators(project);
+ for (Validator v : vals){
+ if (v.getId().equals(id))return v;
+ }
+ return null;
+ }
+
+ /**
+ * Answer true if the resource has any enabled validators.
+ *
+ * @param resource a file, folder or project.
+ *
+ * @param isManual if true then the validator must be turned on for manual validation.
+ * If false then the isManualValidation setting isn't used to filter out validators.
+ *
+ * @param isBuild if true then the validator must be turned on for build based validation.
+ * If false then the isBuildValidation setting isn't used to filter out validators.
+ */
+ public boolean hasValidators(IResource resource, boolean isManual, boolean isBuild){
+ if (resource instanceof IProject){
+ IProject project = (IProject)resource;
+ return ValManager.getDefault().getValidators(project).length > 0;
+ }
+ else if (resource instanceof IFolder){
+ IFolder folder = (IFolder)resource;
+ HasValidatorVisitor v = new HasValidatorVisitor(isManual, isBuild);
+ return v.hasValidator(folder);
+ }
+ else {
+ ContentTypeWrapper ctw = new ContentTypeWrapper();
+ for (Validator val : ValManager.getDefault().getValidators(resource.getProject())){
+ if (Friend.shouldValidate(val, resource, isManual, isBuild, ctw))return true;
+ }
+ }
+ return false;
+ }
+
+ /**
+ * Answer true if the project has disabled all of it's validators, or if project overrides are not
+ * allowed if global validation has been disabled.
+ *
+ * @param project the project that is being consulted, or null if only the global settings are to be
+ * checked.
+ */
+ public boolean isDisabled(IProject project){
+ GlobalPreferences gp = getGlobalPreferences();
+ if (!gp.getOverride() || project == null)return gp.getDisableAllValidation();
+
+ ProjectPreferences pp = _projectPreferences.get(project);
+ if (pp == null)return gp.getDisableAllValidation();
+ return pp.getSuspend();
+ }
+
+ /**
+ * Answer all the registered validators as they were defined by the extension points. That is
+ * answer the validators as if the user has never applied any customizations.
+ *
+ * @return Answer an empty array if there are no validators.
+ */
+ public static Validator[] getDefaultValidators() throws InvocationTargetException {
+ Map<String,Validator> extVals = ExtensionValidators.instance().getMapV2();
+ TreeSet<Validator> sorted = new TreeSet<Validator>();
+ for (Validator v : extVals.values())sorted.add(v);
+
+ IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
+ GlobalConfiguration gc = new GlobalConfiguration(root);
+ gc.resetToDefault();
+ for (ValidatorMetaData vmd : gc.getValidators()){
+ Validator v = Validator.create(vmd, gc, null);
+ v.setBuildValidation(vmd.isBuildValidation());
+ v.setManualValidation(vmd.isManualValidation());
+ sorted.add(v);
+ }
+
+ Validator[] val = new Validator[sorted.size()];
+ sorted.toArray(val);
+ return val;
+ }
+
+ public static Validator[] getDefaultValidators(IProject project) throws InvocationTargetException {
+ Map<String,Validator> extVals = ExtensionValidators.instance().getMap(project);
+ Validator[] val = new Validator[extVals.size()];
+ extVals.values().toArray(val);
+ return val;
+ }
+
+ /**
+ * Answer all the registered validators.
+ *
+ * @param project the project to use for getting the version 1 validator settings. This can
+ * be null in which case the global preferences are used.
+ *
+ * @return Answer an empty array if there are no validators.
+ */
+// Validator[] getValidators2(IProject project) throws ProjectUnavailableError {
+// // If I use a local variable I don't need to synchronize the method.
+//
+// Validator[] validators = _validators;
+// if (project == null && validators != null)return validators;
+//
+// Validator[] val = loadExtensions(false, project);
+// ValPrefManagerGlobal vpm = ValPrefManagerGlobal.getDefault();
+// if (!vpm.loadPreferences(val)){
+// val = restoreDefaults2(project);
+// saveStateTimestamp();
+// }
+// else {
+// if (getGlobalPreferences().getStateTimeStamp() != Platform.getStateStamp())
+// val = migrateSettings(val, project);
+// }
+//
+// TreeSet<Validator> set = new TreeSet<Validator>();
+// for (Validator v : val)set.add(v);
+//
+// List<Validator> list = new LinkedList<Validator>();
+// try {
+// ValidationConfiguration vc = ConfigurationManager.getManager().getConfiguration(project);
+// for (ValidatorMetaData vmd : vc.getValidators()){
+// list.add(Validator.create(vmd, vc, project));
+// }
+//
+// }
+// catch (InvocationTargetException e){
+// if (project != null && (!project.exists() || !project.isOpen()))
+// throw new ProjectUnavailableError(project);
+// ValidationPlugin.getPlugin().handleException(e);
+// }
+//
+// set.addAll(list);
+// val = new Validator[set.size()];
+// set.toArray(val);
+// if (project == null)_validators = val;
+// return val;
+// }
+
+ /**
+ * This method needs to be called whenever the validation configuration has changed.
+ */
+ private void configHasChanged(){
+ _configNumber.incrementAndGet();
+ ValidatorProjectManager.reset();
+ _cache.reset();
+ }
+
+ /**
+ * Answer the global validation preferences.
+ */
+ public GlobalPreferences getGlobalPreferences(){
+ GlobalPreferences gp = _globalPreferences.get();
+ if (gp == null){
+ ValPrefManagerGlobal vpm = ValPrefManagerGlobal.getDefault();
+ gp = vpm.loadGlobalPreferences();
+ if (!_globalPreferences.compareAndSet(null, gp))gp = _globalPreferences.get();
+ }
+ return gp;
+ }
+
+ /**
+ * Update the global preferences, but only if something has actually changed.
+ * @param values The global settings.
+ * @return a bit mask of the changes between the old values and the new values. See the GlobalPreferences
+ * constants for the bit mask values. If a zero is return there were no changes.
+ */
+ public int replace(GlobalPreferencesValues values){
+ GlobalPreferences gp = new GlobalPreferences(values);
+ GlobalPreferences old = getGlobalPreferences();
+ int changes = old.compare(gp);
+ if (changes != 0){
+ _globalPreferences.set(gp);
+ }
+ return changes;
+ }
+
+ /**
+ * Answer the project preferences for this project.
+ * @param project The project, this may be null.
+ */
+ public ProjectPreferences getProjectPreferences(IProject project) {
+ ProjectPreferences pp = _projectPreferences.get(project);
+ if (pp != null)return pp;
+
+ /* hopefully we rarely get this far */
+
+ Map<String,Validator> extVals = ExtensionValidators.instance().getMapV2Copy();
+ try {
+ List<Validator> vals = ValPrefManagerGlobal.getDefault().getValidators();
+ for (Validator v : vals)extVals.put(v.getId(), v);
+
+ pp = getProjectPreferences(project, extVals);
+ }
+ catch (BackingStoreException e){
+ ValidationPlugin.getPlugin().handleException(e);
+ }
+ return pp;
+ }
+
+ /**
+ *
+ * @param project The project, this may be null.
+ * @param baseValidators
+ */
+ private ProjectPreferences getProjectPreferences(IProject project, Map<String, Validator> baseValidators)
+ throws BackingStoreException {
+ ProjectPreferences pp = _projectPreferences.get(project);
+ if (pp != null)return pp;
+
+ ValPrefManagerProject vpm = new ValPrefManagerProject(project);
+ pp = vpm.loadProjectPreferences(project, baseValidators);
+ _projectPreferences.put(project, pp);
+ return pp;
+ }
+
+ /**
+ * Restore all the validation defaults, as defined by the individual validators via the
+ * validation extension point.
+ */
+// public synchronized void restoreDefaults() {
+// getGlobalPreferences().resetToDefault();
+// _validators = null;
+// getValidators(true);
+// }
+
+
+ /**
+ * Run all the validators that are applicable to this resource.
+ * <p>
+ * If this is a manual validation both the version 1 and version 2 validators are run. If it
+ * is a build validation, then only the version 2 validators are run, because the old framework handles
+ * the running of the old validators.
+ * </p>
+ *
+ * @param project project that is being validated
+ *
+ * @param resource the resource that is being validated
+ *
+ * @param kind the kind of resource delta. It will be one of the IResourceDelta constants, like
+ * IResourceDelta.CHANGED for example.
+ *
+ * @param valType The type of validation request.
+ * @param buildKind the kind of build that triggered this validation. See IncrementalProjectBuilder for values.
+ * @param operation the operation that this validation is running under
+ * @param monitor the monitor to use to report progress
+ */
+ public void validate(IProject project, final IResource resource, final int kind, ValType valType,
+ int buildKind, ValOperation operation, final IProgressMonitor monitor) {
+
+ MarkerManager.getDefault().deleteMarkers(resource, operation.getStarted(), IResource.DEPTH_ZERO);
+
+ IValidatorVisitor visitor = new IValidatorVisitor(){
+
+ public void visit(Validator validator, IProject project, ValType vt,
+ ValOperation operation, IProgressMonitor monitor) {
+
+ Validator.V1 v1 = validator.asV1Validator();
+ if (vt == ValType.Build && v1 != null)return;
+
+ SubMonitor subMonitor = SubMonitor.convert(monitor);
+ String task = NLS.bind(ValMessages.LogValStart, validator.getName(), resource.getName());
+ subMonitor.beginTask(task, 1);
+ validate(validator, operation, resource, kind, subMonitor.newChild(1), null);
+ }
+ };
+ SubMonitor sm = SubMonitor.convert(monitor, getValidators(project).length);
+ accept(visitor, project, resource, valType, operation, sm);
+
+ }
+
+ /**
+ * Validate a single resource with a single validator. This will call the validator whether the validator
+ * is enabled or not.
+ * <p>
+ * Callers of this method should ensure that the shouldValidate was tested before making this call.
+ *
+ * @param validator the validator
+ * @param operation the operation that the validation is running in.
+ * @param resource the resource to validate
+ * @param kind the kind of resource change. See IResourceDelta.
+ * @param monitor
+ */
+ public void validate(Validator validator, ValOperation operation, IResource resource, int kind,
+ IProgressMonitor monitor, ValidationEvent event){
+ if (operation.isValidated(validator.getId(), resource))return;
+ long time = 0;
+ long cpuTime = -1;
+ String msg1 = NLS.bind(ValMessages.LogValStart, validator.getName(), resource.getName());
+ monitor.subTask(msg1);
+ IPerformanceMonitor pm = ValidationFramework.getDefault().getPerformanceMonitor();
+ if (pm.isCollecting()){
+ time = System.currentTimeMillis();
+ cpuTime = Misc.getCPUTime();
+ }
+
+ if (Tracing.matchesExtraDetail(validator.getId())){
+ Tracing.log("ValManager-03: validating ", resource); //$NON-NLS-1$
+ }
+ ValidationResult vr = validator.validate(resource, kind, operation, monitor, event);
+ if (pm.isCollecting()){
+ if (cpuTime != -1){
+ cpuTime = Misc.getCPUTime() - cpuTime;
+ }
+ int num = 0;
+ if (vr != null)num = vr.getNumberOfValidatedResources();
+ PerformanceCounters pc = new PerformanceCounters(validator.getId(),
+ validator.getName(), resource.getName(),
+ num, System.currentTimeMillis()-time, cpuTime);
+ pm.add(pc);
+ }
+ if (ValidationPlugin.getPlugin().isDebugging() && !pm.isCollecting()){
+ String msg = time != 0 ?
+ NLS.bind(ValMessages.LogValEndTime, new Object[]{validator.getName(),
+ validator.getId(), resource, Misc.getTimeMS(System.currentTimeMillis()-time)}) :
+ NLS.bind(ValMessages.LogValEnd, validator.getName(), resource);
+ Tracing.log("ValManager-01: " + msg); //$NON-NLS-1$
+ }
+ if (vr != null){
+ operation.mergeResults(vr);
+ if (vr.getSuspendValidation() != null)operation.suspendValidation(vr.getSuspendValidation(), validator);
+ }
+ }
+
+ /**
+ * Accept a visitor for all the validators that are enabled for the given project.
+ *
+ * @param visitor
+ * @param project
+ * @param valType the type of validation
+ * @param operation
+ * @param monitor
+ */
+ public void accept(IValidatorVisitor visitor, IProject project, ValType valType,
+ ValOperation operation, IProgressMonitor monitor){
+
+ if (isDisabled(project))return;
+
+ for (Validator val : getValidators(project)){
+ if (monitor.isCanceled())return;
+ if (!ValidatorProjectManager.get().shouldValidate(val, project, valType))continue;
+ if (operation.isSuspended(val, project))continue;
+ try {
+ visitor.visit(val, project, valType, operation, monitor);
+ }
+ catch (Exception e){
+ ValidationPlugin.getPlugin().handleException(e);
+ }
+ }
+ }
+
+ /**
+ * Accept a visitor for all the validators that are enabled for the given project, resource,
+ * and validation mode.
+ *
+ * @param valType the type of validation request
+ */
+ public void accept(IValidatorVisitor visitor, IProject project, IResource resource,
+ ValType valType, ValOperation operation, IProgressMonitor monitor){
+
+ if (isDisabled(project))return;
+
+ Map<String,IValidatorGroupListener[]> groupListeners = new HashMap<String,IValidatorGroupListener[]>();
+
+ ValProperty vp = getValProperty(resource, valType, _configNumber.get());
+ if (vp != null){
+ BitSet bs = vp.getConfigSet();
+ for (Validator val : getValidators(project)){
+ if (!monitor.isCanceled()) {
+ if (!bs.get(_idManager.getIndex(val.getId())))continue;
+ if (operation.isSuspended(val, project))continue;
+ Validator.V2 v2 = val.asV2Validator();
+ if (v2 != null) {
+ notifyGroupListenersStarting(resource, operation.getState(), monitor, groupListeners, v2);
+ }
+ try {
+ visitor.visit(val, project, valType, operation, monitor);
+ }
+ catch (Exception e){
+ ValidationPlugin.getPlugin().handleException(e);
+ }
+ }
+ }
+ notifyGroupFinishing(resource, operation.getState(), monitor, groupListeners);
+ return;
+ }
+
+ vp = new ValProperty();
+ vp.setConfigNumber(_configNumber.get());
+ ContentTypeWrapper ctw = new ContentTypeWrapper();
+ for (Validator val : getValidators(project)){
+ if (!monitor.isCanceled()) {
+ if (!ValidatorProjectManager.get().shouldValidate(val, project, valType))continue;
+ if (Friend.shouldValidate(val, resource, valType, ctw)){
+ vp.getConfigSet().set(_idManager.getIndex(val.getId()));
+ // we do the suspend check after figuring out if it needs to be validated, because we save
+ // this information for the session.
+ if (operation.isSuspended(val, project))continue;
+ Validator.V2 v2 = val.asV2Validator();
+ if (v2 != null) {
+ notifyGroupListenersStarting(resource, operation.getState(), monitor, groupListeners, v2);
+ }
+ try {
+ visitor.visit(val, project, valType, operation, monitor);
+ }
+ catch (Exception e){
+ ValidationPlugin.getPlugin().handleException(e);
+ }
+ }
+ }
+ }
+ notifyGroupFinishing(resource, operation.getState(), monitor, groupListeners);
+ putValProperty(vp, resource, valType);
+ }
+
+ /**
+ * Let the group listeners know that validation might be starting for the group of validators.
+ */
+ private void notifyGroupListenersStarting(final IResource resource,
+ final ValidationState state, final IProgressMonitor monitor,
+ Map<String, IValidatorGroupListener[]> groupListeners, Validator.V2 v2) {
+
+ String[] groups = v2.getValidatorGroups();
+ for (String group : groups) {
+ if (!groupListeners.containsKey(group)) {
+ IValidatorGroupListener[] createdListeners = null;
+ try {
+ createdListeners = ValidatorGroupExtensionReader.getDefault().createListeners(group);
+ }
+ catch (CoreException e){
+ String msg = NLS.bind(ValMessages.ErrConfig, v2.getId());
+ Status status = new Status(IStatus.ERROR, ValidationPlugin.PLUGIN_ID, msg);
+ CoreException core = new CoreException(status);
+ ValidationPlugin.getPlugin().handleException(core);
+ ValidationPlugin.getPlugin().handleException(e);
+
+ // we create this to ensure that we don't signal the same exception over and over.
+ createdListeners = new IValidatorGroupListener[0];
+ }
+
+ // create and notify just this once
+ final IValidatorGroupListener[] listeners = createdListeners;
+
+ groupListeners.put(group, listeners);
+ for (final IValidatorGroupListener listener : listeners) {
+ SafeRunner.run(new ISafeRunnable() {
+ public void run() throws Exception {
+ listener.validationStarting(resource, monitor, state);
+ }
+
+ public void handleException(Throwable exception) {
+ ValidationPlugin.getPlugin().handleException(exception);
+ }
+ });
+ }
+ }
+ }
+ }
+
+ /**
+ * Let the group listeners know that validation is finished for the group of validators.
+ */
+ private void notifyGroupFinishing(final IResource resource,
+ final ValidationState state, final IProgressMonitor monitor,
+ Map<String, IValidatorGroupListener[]> groupListeners) {
+ for (final IValidatorGroupListener[] listeners : groupListeners.values()) {
+ for (final IValidatorGroupListener listener : listeners) {
+ SafeRunner.run(new ISafeRunnable() {
+ public void run() throws Exception {
+ listener.validationFinishing(resource, monitor, state);
+ }
+
+ public void handleException(Throwable exception) {
+ ValidationPlugin.getPlugin().handleException(exception);
+ }
+ });
+ }
+ }
+ }
+
+ private ValProperty getValProperty(IResource resource, ValType valType, int configNumber) {
+ ValProperty vp = null;
+ try {
+ if (valType == ValType.Build)vp = (ValProperty)resource.getSessionProperty(StatusBuild);
+ else if (valType == ValType.Manual)vp = (ValProperty)resource.getSessionProperty(StatusManual);
+ }
+ catch (CoreException e){
+ // don't care about this one
+ }
+ if (vp == null)return null;
+ if (vp.getConfigNumber() != _configNumber.get())return null;
+ return vp;
+ }
+
+ /**
+ * Let the validation manager know that a project has been changed.
+ *
+ * @param project The project that has been opened, created, or had it's description change.
+ */
+ public void projectChanged(IProject project){
+ ValidatorProjectManager.reset();
+ _projectPreferences.remove(project);
+ _cache.reset(project);
+ }
+
+ /**
+ * Let the validation manager know that a project has been removed.
+ *
+ * @param project The project that has been closed or deleted.
+ *
+ */
+ public void projectRemoved(IProject project){
+ ValidatorProjectManager.reset();
+ _projectPreferences.remove(project);
+ _cache.reset(project);
+ }
+
+ private void putValProperty(ValProperty vp, IResource resource, ValType valType) {
+ try {
+ if (valType == ValType.Build)resource.setSessionProperty(StatusBuild, vp);
+ else if (valType == ValType.Manual)resource.setSessionProperty(StatusManual, vp);
+ }
+ catch (CoreException e) {
+ // If the resource is not found, it is likely just been deleted
+ // and there is no need to do anything.
+ // See https://bugs.eclipse.org/bugs/show_bug.cgi?id=269022
+ if (!e.getStatus().equals(IResourceStatus.RESOURCE_NOT_FOUND)) {
+ ValidationPlugin.getPlugin().handleException(e, IStatus.WARNING);
+ }
+ }
+ }
+
+ /**
+ * Let each of the enabled validators know that a clean has been requested.
+ *
+ * @param project the project that is being cleaned, or null if the entire workspace is being cleaned.
+ * @param monitor
+ */
+ void clean(final IProject project, final ValOperation operation, final IProgressMonitor monitor) {
+ IValidatorVisitor visitor = new IValidatorVisitor(){
+
+ public void visit(Validator validator, IProject project, ValType valType,
+ ValOperation operation, IProgressMonitor monitor) {
+ validator.clean(project, operation, monitor);
+ }
+
+ };
+ accept(visitor, project, ValType.Build, operation, monitor);
+ }
+
+ /**
+ * Let each of the enabled validators know that a clean has been requested.
+ *
+ * @param project the project that is being cleaned, or null if the entire workspace is being cleaned.
+ * @param monitor
+ */
+ public void clean(IProject project, IProgressMonitor monitor){
+ IValidatorVisitor visitor = new IValidatorVisitor(){
+
+ public void visit(Validator validator, IProject project, ValType valType,
+ ValOperation operation, IProgressMonitor monitor) {
+ validator.clean(project, operation, monitor);
+ }
+
+ };
+ ValidationFramework.getDefault().getDependencyIndex().clear(project);
+ ValOperation operation = new ValOperation();
+ accept(visitor, project, ValType.Build, operation, monitor);
+ }
+
+ public void validatorsForProjectChanged(IProject project, boolean validationSettingChanged) {
+ if (validationSettingChanged){
+ if (project != null)_projectPreferences.remove(project);
+ configHasChanged();
+ }
+ }
+
+ private final class HasValidatorVisitor implements IResourceVisitor {
+
+ private boolean _hasValidator;
+ private final boolean _isManual;
+ private final boolean _isBuild;
+
+ public HasValidatorVisitor(boolean isManual, boolean isBuild){
+ _isManual = isManual;
+ _isBuild = isBuild;
+ }
+
+ public boolean hasValidator(IFolder folder){
+ try {
+ folder.accept(this);
+ }
+ catch (CoreException e){
+ ValidationPlugin.getPlugin().handleException(e);
+ }
+ return _hasValidator;
+ }
+
+ public boolean visit(IResource resource) throws CoreException {
+ if (resource instanceof IFolder)return true;
+ if (hasValidators(resource, _isManual, _isBuild)){
+ _hasValidator = true;
+ return false;
+ }
+ return true;
+ }
+ }
+
+ /**
+ * Map validator id's to an index number on a bit set, so that we can quickly determine if a
+ * particular validator needs to validate a particular resource.
+ * @author karasiuk
+ *
+ */
+ private final static class ValidatorIdManager {
+
+ /**
+ * Map validator id's to Integers. The integers correspond to bits in the ValProperty instances.
+ */
+ private final Map<String, Integer> _map = new HashMap<String, Integer>(100);
+ private final Map<Integer, String> _reverseMap = new HashMap<Integer, String>(100);
+
+ /** Next available bit. */
+ private int _next;
+
+ /**
+ * Answer the index number for this validator. If we haven't seen it yet allocate a new index number.
+ * @param id validator id.
+ * @return index into the validator bit mask.
+ */
+ public synchronized int getIndex(String id){
+ Integer i = _map.get(id);
+ if (i != null)return i;
+
+ i = _next++;
+ _map.put(id, i);
+ _reverseMap.put(i, id);
+
+ return i;
+ }
+
+ /**
+ * Answer the validator id for the index.
+ * @param index
+ * @return null if the index number has not been set.
+ */
+ public synchronized String getId(Integer index){
+ return _reverseMap.get(index);
+ }
+
+ public synchronized void reset(){
+ _map.clear();
+ _reverseMap.clear();
+ _next = 0;
+ }
+
+ /**
+ * Answer the ids for the bit in the bitset. This is used for debugging.
+ * @param bs
+ */
+ public synchronized String[] getIds(BitSet bs){
+ List<String> list = new LinkedList<String>();
+ for(int i=bs.nextSetBit(0); i>=0; i=bs.nextSetBit(i+1)) {
+ String id = getId(i);
+ if (id != null)list.add(id);
+ }
+ String[] s = new String[list.size()];
+ return list.toArray(s);
+ }
+ }
+
+ /**
+ * This is used to keep track of which validators are enabled with which projects. We want to ensure
+ * that we don't activate a validator (and it's plug-in) if it has nothing to validate in the workspace.
+ * This is an immutable object.
+ * @author karasiuk
+ *
+ */
+ private final static class ValidatorProjectManager {
+
+ private final static AtomicReference<ValidatorProjectManager> _me = new AtomicReference<ValidatorProjectManager>();
+ private final static AtomicInteger _counter = new AtomicInteger();
+
+ private final ValProjectMap _manual = new ValProjectMap(ValType.Manual);
+ private final ValProjectMap _build = new ValProjectMap(ValType.Build);
+ private final int _sequence;
+
+ /**
+ * Answer the most current ValidatorProjectManager creating a new one if you have to.
+ * @return
+ */
+ public static ValidatorProjectManager get(){
+ ValidatorProjectManager vpm = _me.get();
+ if (vpm != null)return vpm;
+
+ int next = _counter.incrementAndGet();
+ ValidatorProjectManager newVpm = null;
+ boolean looking = true;
+ while(looking){
+ vpm = _me.get();
+ if (vpm == null || next > vpm.getSequence()){
+ if (newVpm == null)newVpm = new ValidatorProjectManager(next);
+ if (_me.compareAndSet(vpm, newVpm))return newVpm;
+ }
+ else looking = false;
+ }
+ return vpm;
+ }
+
+ /**
+ * Reset the ValidatorProjectManager to null, which will force a newer one to be created the next time
+ * that it is requested.
+ */
+ public static void reset(){
+ int next = _counter.incrementAndGet();
+ ValidatorProjectManager vpm = _me.get();
+ if ( vpm == null)return;
+ if (next > vpm.getSequence())_me.compareAndSet(vpm, null);
+ }
+
+ private ValidatorProjectManager(int sequence){
+ _sequence = sequence;
+ }
+
+ int getSequence(){
+ return _sequence;
+ }
+
+ /**
+ * Should this validator attempt to validate any resources in this project?
+ *
+ * @param validator
+ * The validator that is being tested.
+ * @param project
+ * The project that is being tested. This can be null, which
+ * means that all projects will be tested.
+ * @param type
+ * The type of validation operation.
+ * @return true if the validator should attempt to validate.
+ */
+ public boolean shouldValidate(Validator validator, IProject project, ValType type){
+ if (type == ValType.Build)return _build.shouldValidate(validator, project);
+ if (type == ValType.Manual)return _manual.shouldValidate(validator, project);
+
+ return false;
+ }
+
+ /**
+ * This is used to keep track of which validators are enabled for which projects. We want to ensure
+ * that we don't activate a validator (and it's plug-in) if it has nothing to validate in the workspace.
+ * <p>
+ * There are two reasons why a validator may not be enabled. It's current project level filters may not match
+ * the project. Or the entire validator may have been turned off for the project.
+ * </p>
+ * @author karasiuk
+ *
+ */
+ private final static class ValProjectMap {
+ /**
+ * Map a validator to the projects that it validates. This is an immutable object.
+ * <p>
+ * I've gone back and forth on whether the key should
+ * be a Validator or the validator id. I'm back to it being the id because I was
+ * running into cases where because of copying I wasn't getting the matches that I expected and I
+ * want to ensure that I don't leak validators. If I run into
+ * false matches, it is probably because reset isn't being called when it should be.
+ * </p>
+ */
+ private final Map<String, Set<IProject>> _map;
+
+ private final ValType _type;
+
+ public ValProjectMap(ValType type){
+ _type = type;
+ _map = load();
+ }
+
+ /**
+ * Should this validator attempt to validate any resources in this project?
+ *
+ * @param validator
+ * The validator that is being tested.
+ * @param project
+ * The project that is being tested. This can be null, which
+ * means that all projects will be tested, and if any of them return true,
+ * then true is answered for this method.
+ *
+ * @return true if the validator should attempt to validate.
+ */
+ public boolean shouldValidate(Validator validator, IProject project){
+ String vid = validator.getId();
+ Set<IProject> projects = _map.get(vid);
+ if (projects == null)return false;
+ if (project == null)return projects.size() > 0;
+ return projects.contains(project);
+ }
+
+ /**
+ * For each of the projects in the workspace, load which validators are currently prepared to validate things.
+ */
+ private Map<String, Set<IProject>> load() {
+ Map<String, Set<IProject>> map = new HashMap<String, Set<IProject>>(50);
+ ValManager vm = ValManager.getDefault();
+ IProject[] projects = ResourcesPlugin.getWorkspace().getRoot().getProjects();
+ Tracing.log("ValManager-02: loading " + projects.length + " projects"); //$NON-NLS-1$//$NON-NLS-2$
+ for (IProject project : projects){
+ if (!project.isOpen())continue;
+ Validator[] vals = vm.getValidators(project);
+ for (Validator v : vals){
+ String vid = v.getId();
+ Set<IProject> set = map.get(vid);
+ if (set == null){
+ set = new HashSet<IProject>(50);
+ map.put(vid, set);
+ }
+
+ if (v.shouldValidateProject(project, _type))set.add(project);
+ }
+ }
+ return map;
+ }
+
+ }
+
+ }
+
+ public void handleEvent(IFacetedProjectEvent event) {
+ projectChanged(event.getProject().getProject());
+ }
+
+ public void projectChanged(IProject project, int type) {
+ switch (type){
+ case IProjectChangeListener.ProjectClosed:
+ case IProjectChangeListener.ProjectDeleted:
+ projectRemoved(project);
+ break;
+ case IProjectChangeListener.ProjectOpened:
+ case IProjectChangeListener.ProjectChanged:
+ case IProjectChangeListener.ProjectAdded:
+ projectChanged(project);
+ break;
+ }
+ }
+
+ /**
+ * Store the singleton for the ValManager. This approach is used to avoid having to synchronize the
+ * ValManager.getDefault() method.
+ *
+ * @author karasiuk
+ *
+ */
+ private static class Singleton {
+ static ValManager valManager = new ValManager();
+ }
+
+ private final class ValidatorCache {
+ private final ConcurrentMap<IProject, Validator[]> _cache = new ConcurrentHashMap<IProject, Validator[]>(50);
+ private final AtomicReference<Validator[]> _global = new AtomicReference<Validator[]>();
+
+ public Validator[] getValidatorsCached(IProject project) throws ProjectUnavailableError {
+ Validator[] vals = null;
+ if (project == null){
+ vals = _global.get();
+ if (vals == null){
+ vals = getValidatorsNotCached(project);
+ _global.set(vals);
+ }
+ }
+ else {
+ vals = _cache.get(project);
+ if (vals == null){
+ vals = getValidatorsNotCached(project);
+ _cache.put(project, vals);
+ }
+ }
+ return vals;
+ }
+
+ public void reset(){
+ _cache.clear();
+ _global.set(null);
+ }
+
+ public void reset(IProject project){
+ if (project != null)_cache.remove(project);
+ }
+
+ }
+
+ public enum UseProjectPreferences {Normal, MustUse, MustNotUse}
+
+}
diff --git a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/ValMessages.java b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/ValMessages.java
new file mode 100644
index 0000000..02aabe1
--- /dev/null
+++ b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/ValMessages.java
@@ -0,0 +1,89 @@
+/*******************************************************************************
+ * Copyright (c) 2007, 2008 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.wst.validation.internal;
+
+import org.eclipse.osgi.util.NLS;
+
+public class ValMessages extends NLS {
+
+ private static final String BUNDLE_NAME = "org.eclipse.wst.validation.internal.messages"; //$NON-NLS-1$
+
+ public static String ConfigError;
+
+ public static String DecodeError1;
+ public static String Error20;
+
+ public static String ErrConfig;
+ public static String ErrFilterRule;
+ public static String ErrGroupName;
+ public static String ErrDependencyVersion;
+
+ public static String ErrGroupNoType;
+ public static String ErrGroupInvalidType;
+
+ public static String ErrPatternAttrib;
+ public static String ErrTypeReq;
+ public static String ErrType;
+
+ public static String VbfExcSyntaxNoValClass;
+ public static String VbfExcSyntaxNoValRun;
+ public static String VbfExcSyntaxNoValNull;
+
+ public static String GroupInclude;
+
+ public static String GroupExclude;
+
+ public static String JobName;
+ public static String JobNameMonitor;
+
+ public static String JobIndexSave;
+
+ public static String LogValStart;
+ public static String LogValEnd;
+ public static String LogValEndTime;
+ public static String LogValSummary;
+ public static String LogValSummary2;
+ public static String LogSession;
+
+ public static String MigrationJobName;
+
+ public static String RuleProjectNature;
+ public static String RuleFileExt;
+ public static String RuleFile;
+ public static String RuleFolder;
+ public static String RuleFull;
+ public static String RuleContentType;
+ public static String RuleFacet;
+
+ public static String ContentTypeExact;
+ public static String ContentTypeNotExact;
+
+ public static String FileExtWithCase;
+ public static String FileExtWithoutCase;
+
+ public static String SevError;
+ public static String SevWarning;
+ public static String SevIgnore;
+
+ public static String TimeUnder;
+ public static String TimeNano;
+ public static String TimeMicro;
+ public static String TimeSec;
+ public static String TimeMin;
+
+ public static String TypeInclude;
+ public static String TypeExclude;
+
+ static {
+ NLS.initializeMessages(BUNDLE_NAME, ValMessages.class);
+ }
+
+}
diff --git a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/ValOperation.java b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/ValOperation.java
new file mode 100644
index 0000000..44c78ec
--- /dev/null
+++ b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/ValOperation.java
@@ -0,0 +1,205 @@
+/*******************************************************************************
+ * Copyright (c) 2007, 2008 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.wst.validation.internal;
+
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Set;
+
+import org.eclipse.core.resources.IProject;
+import org.eclipse.core.resources.IResource;
+import org.eclipse.wst.validation.ValidationResult;
+import org.eclipse.wst.validation.ValidationResults;
+import org.eclipse.wst.validation.ValidationState;
+import org.eclipse.wst.validation.Validator;
+
+/**
+ * This represents a validation operation, i.e. the running of a set of validators in response to some change.
+ * It may be a large operation, as would happen on a clean build, or it may be the validation of just a single
+ * resource.
+ * <p>
+ * The operation can, but doesn't need to, span multiple projects.
+ * </p>
+ * <p>
+ * Once the operation has finished, this object goes away.
+ * </p>
+ * @author karasiuk
+ *
+ */
+public final class ValOperation {
+
+ private final ValidationState _state = new ValidationState();
+ private final ValidationResult _result = new ValidationResult();
+
+ /**
+ * Each project can have a set of validators that are suspended for the duration of the validation operation.
+ * The set contains the validator's id.
+ */
+ private final Map<IProject, Set<String>> _suspended = new HashMap<IProject, Set<String>>(40);
+
+ /** The time that the operation started. */
+ private final long _started = System.currentTimeMillis();
+
+ /**
+ * Are we in a multi project validation? That is, could we be validating several
+ * projects at the same time? This can be triggered by either clean all or
+ * if auto build is turned off, a build all.
+ */
+ private final boolean _multiProject;
+
+ /**
+ * Holds all the resources that have been validated as a side-effect of running other validations.
+ * The key is the validator id and the value is a Set of IResources.
+ */
+ private final Map<String, Set<IResource>> _validated = new HashMap<String, Set<IResource>>(20);
+
+ public ValOperation(){
+ _multiProject = false;
+ }
+
+ /**
+ *
+ * @param multiProject Set to true if we could be validating several projects at the same time.
+ */
+ public ValOperation(boolean multiProject){
+ _multiProject = multiProject;
+ }
+
+ public ValidationState getState() {
+ return _state;
+ }
+
+ /**
+ * Answer a summary of the validation results.
+ * @return
+ */
+ public ValidationResultSummary getResult() {
+ synchronized(_result){
+ ValidationResultSummary vrs = new ValidationResultSummary(_result.getSeverityError(),
+ _result.getSeverityWarning(), _result.getSeverityInfo());
+ return vrs;
+ }
+ }
+
+ /**
+ * Answer a copy of the ValidationResult.
+ * @return
+ */
+ public ValidationResults getResults(){
+ return new ValidationResults(_result);
+ }
+
+ /**
+ * Remember that this resource has already been validated as a side-effect.
+ *
+ * @param id id of the validator
+ * @param resource resource that has been validated.
+ */
+ public void addValidated(String id, IResource resource){
+ synchronized(_validated){
+ Set<IResource> set = _validated.get(id);
+ if (set == null){
+ set = new HashSet<IResource>(20);
+ _validated.put(id, set);
+ }
+ set.add(resource);
+ }
+ }
+
+ /**
+ * Answer if this resource has already been validated as a side-effect of some other validation by the
+ * given validator.
+ *
+ * @param id
+ * @param resource
+ */
+ public boolean isValidated(String id, IResource resource){
+ synchronized(_validated){
+ Set<IResource> set = _validated.get(id);
+ if (set == null)return false;
+
+ return set.contains(resource);
+ }
+ }
+
+ /**
+ * Has this validator been suspended for the duration of this operation on this project?
+ *
+ * @param val
+ * The validator that is being checked.
+ * @param project
+ * Can be null, in which case we return false.
+ *
+ * @return true if this validator should not run on this project.
+ */
+ public boolean isSuspended(Validator val, IProject project) {
+ if (project == null)return false;
+ synchronized(_suspended){
+ Set<String> set = getSuspended(project);
+ return set.contains(val.getId());
+ }
+ }
+
+ private Set<String> getSuspended(IProject project){
+ Set<String> set = _suspended.get(project);
+ if (set == null){
+ set = new HashSet<String>(5);
+ _suspended.put(project, set);
+ }
+ return set;
+ }
+
+ void suspendValidation(IProject project, Validator validator) {
+ if (project == null)return;
+ if (validator == null)return;
+ getSuspended(project).add(validator.getId());
+ }
+
+ public long getStarted() {
+ return _started;
+ }
+
+ public boolean isMultiProject() {
+ return _multiProject;
+ }
+
+ /**
+ * Indicate if the operation was canceled.
+ *
+ * @param canceled
+ * Set to true if it was canceled and false if it was not canceled.
+ */
+ public void setCanceled(boolean canceled) {
+ synchronized (_result) {
+ _result.setCanceled(canceled);
+ }
+
+ }
+
+ /**
+ * Was the operation canceled before it completed? For example if the validation is being run through the
+ * user interface, the end user can cancel the operation through the progress monitor.
+ *
+ * @return true if the operation was canceled
+ */
+ public boolean isCanceled() {
+ synchronized (_result) {
+ return _result.isCanceled();
+ }
+ }
+
+ public void mergeResults(ValidationResult vr) {
+ synchronized (_result) {
+ _result.mergeResults(vr);
+ }
+ }
+}
diff --git a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/ValPrefManagerGlobal.java b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/ValPrefManagerGlobal.java
new file mode 100644
index 0000000..5fcbaf3
--- /dev/null
+++ b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/ValPrefManagerGlobal.java
@@ -0,0 +1,653 @@
+/*******************************************************************************
+ * Copyright (c) 2007, 2008 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.wst.validation.internal;
+
+import java.lang.reflect.InvocationTargetException;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.CopyOnWriteArraySet;
+import java.util.concurrent.atomic.AtomicReference;
+
+import org.eclipse.wst.validation.Friend;
+import org.eclipse.wst.validation.MessageSeveritySetting;
+import org.eclipse.wst.validation.Validator;
+import org.eclipse.wst.validation.Validator.V2;
+import org.eclipse.wst.validation.internal.model.FilterGroup;
+import org.eclipse.wst.validation.internal.model.GlobalPreferences;
+import org.eclipse.wst.validation.internal.model.GlobalPreferencesValues;
+import org.eclipse.wst.validation.internal.plugin.ValidationPlugin;
+import org.osgi.service.prefs.BackingStoreException;
+
+/**
+ * A class that knows how to manage the global persisted validation settings.
+ * @author karasiuk
+ */
+public final class ValPrefManagerGlobal {
+
+ /**
+ * Version of the framework properties.
+ * <ul>
+ * <li>Version 2 - used the filter approach
+ * <li>Version 3 - switched to a difference based approach. (See Bugzilla 224179)
+ * </ul>
+ *
+ */
+ public final static int frameworkVersion = 3;
+
+ private final Set<IValChangedListener> _listeners = new CopyOnWriteArraySet<IValChangedListener>();
+
+ private final AtomicReference<List<Validator>> _validators = new AtomicReference<List<Validator>>();
+
+ private ValPrefManagerGlobal(){}
+
+ public static ValPrefManagerGlobal getDefault(){
+ return Singleton.valPrefManagerGlobal;
+ }
+
+ public void addListener(IValChangedListener listener){
+ _listeners.add(listener);
+ }
+
+ public void removeListener(IValChangedListener listener){
+ _listeners.remove(listener);
+ }
+
+ private void updateListeners(boolean validationSettingChanged){
+ for (IValChangedListener cl : _listeners)cl.validatorsForProjectChanged(null, validationSettingChanged);
+ }
+
+ /**
+ * Update the validator filters from the preference store.
+ *
+ * @param val
+ *
+ * @return false if there are no preferences, that means that the user has never changed any
+ * of the default settings. Also answer false if there was some sort of error, which essentially
+ * means that the preferences aren't valid for whatever reason.
+ *
+ * @deprecated
+ */
+// public boolean loadPreferences(Validator[] val) {
+//
+// try {
+// IEclipsePreferences pref = ValidationFramework.getDefault().getPreferenceStore();
+// if (!pref.nodeExists(PrefConstants.filters))return false;
+//
+// Preferences filters = pref.node(PrefConstants.filters);
+// for (Validator v : val){
+// String id = v.getId();
+// if (filters.nodeExists(id)){
+// Preferences vp = filters.node(id);
+// loadPreferences(v, vp);
+// }
+// }
+// }
+// catch (Exception e){
+// ValidationPlugin.getPlugin().handleException(e);
+// return false;
+// }
+//
+// return true;
+// }
+
+ /**
+ * Answer the v2 validators that have been overridden by the global preferences.
+ */
+ public List<Validator> getValidators() throws BackingStoreException {
+ List<Validator> vals = _validators.get();
+ while (vals == null){
+ vals = loadValidators();
+ if (!_validators.compareAndSet(null, vals))vals = _validators.get();
+ }
+ return vals;
+ }
+
+ /**
+ * Load the validators from the preference store.
+ * @return the validators that have been overridden by the global references.
+ */
+ private List<Validator> loadValidators() throws BackingStoreException {
+ LinkedList<Validator> list = new LinkedList<Validator>();
+ PreferencesWrapper pref = PreferencesWrapper.getPreferences(null, null);
+ if (pref.nodeExists(PrefConstants.vals)){
+ PreferencesWrapper vals = pref.node(PrefConstants.vals);
+ for (String id : vals.childrenNames()){
+ Validator base = ExtensionValidators.instance().getMapV2().get(id);
+ Validator v = loadValidator(id, vals, base);
+ if (v != null){
+ V2 v2 = v.asV2Validator();
+ if (v2 != null)v2.setLevel(Validator.Level.Global);
+ list.add(v);
+ }
+ }
+ }
+ return list;
+ }
+
+ /**
+ * Answer a copy of the validator that has been updated with the given preferences.
+ *
+ * @param id
+ * Validator id.
+ * @param valsNode
+ * The /vals node in the preference store.
+ * @param base
+ * The base validator that is being customized. This can be null,
+ * in which case null will be returned.
+ *
+ * @return A new validator that is a copy of the extension point validator
+ * with the updates from the preference store.
+ */
+ static Validator loadValidator(String id, PreferencesWrapper valsNode, Validator base) {
+ if (base == null)return null;
+
+ PreferencesWrapper vp = valsNode.node(id);
+ base = base.copy();
+ V2 v2 = base.asV2Validator();
+
+ String global = vp.get(PrefConstants.global, ""); //$NON-NLS-1$
+ if (global.length() > 0){
+ Global g = new Global(global);
+ base.setBuildValidation(g.isBuild());
+ base.setManualValidation(g.isManual());
+ base.setDelegatingId(g.getDelegating());
+ }
+
+ if (v2 != null){
+ String groups = vp.get(PrefConstants.groups, ""); //$NON-NLS-1$
+ if (groups.length() > 0){
+ List<FilterGroup> list = new LinkedList<FilterGroup>();
+ Deserializer des = new Deserializer(groups);
+ while(des.hasNext())list.add(FilterGroup.create(des));
+ v2.setGroups(list);
+ }
+ }
+ return base;
+ }
+
+ /**
+ * The only valid way to get the global preferences is through the ValManager.
+ *
+ * @see ValManager#getGlobalPreferences()
+ */
+ public GlobalPreferences loadGlobalPreferences() {
+ PreferencesWrapper pref = PreferencesWrapper.getPreferences(null, null);
+ GlobalPreferencesValues gp = new GlobalPreferencesValues();
+ gp.saveAutomatically = pref.getBoolean(PrefConstants.saveAuto, GlobalPreferences.DefaultAutoSave);
+ gp.disableAllValidation = pref.getBoolean(PrefConstants.suspend, GlobalPreferences.DefaultSuspend);
+ gp.confirmDialog = pref.getBoolean(PrefConstants.confirmDialog, GlobalPreferences.DefaultConfirm);
+ gp.override = pref.getBoolean(PrefConstants.override, GlobalPreferences.DefaultOverride);
+ gp.version = pref.getInt(PrefConstants.frameworkVersion, GlobalPreferences.DefaultFrameworkVersion);
+ gp.stateTimeStamp = pref.getLong(PrefConstants.stateTS, 0);
+
+ if (gp.version != frameworkVersion)migrate(gp.version, pref);
+ return new GlobalPreferences(gp);
+ }
+
+ /**
+ * If necessary migrate the preferences.
+ * @param version The incoming version of the preferences.
+ * @param pref the root of the preference store
+ */
+ static void migrate(int version, PreferencesWrapper pref) {
+ try {
+ boolean update = false;
+ if (version == 2){
+ if (pref.nodeExists(PrefConstants.filters)){
+ pref.node(PrefConstants.filters).removeNode();
+ update = true;
+ }
+ if (pref.nodeExists(PrefConstants.msgs)){
+ pref.node(PrefConstants.msgs).removeNode();
+ update = true;
+ }
+ }
+ if (update){
+ pref.putInt(PrefConstants.frameworkVersion, frameworkVersion);
+ pref.flush();
+ }
+ }
+ catch (BackingStoreException e){
+ ValidationPlugin.getPlugin().handleException(e);
+ }
+ }
+
+ /**
+ * Load the preferences for a validator.
+ *
+ * @param v the validator that is being built up
+ * @param p the node in the preference tree for the validator,
+ * e.g. /instance/validator-framework-id/filters/validator-id
+ *
+ * @deprecated
+ */
+// static void loadPreferences(Validator v, Preferences p) throws BackingStoreException {
+// v.setBuildValidation(p.getBoolean(PrefConstants.build, true));
+// v.setManualValidation(p.getBoolean(PrefConstants.manual, true));
+// v.setVersion(p.getInt(PrefConstants.version, 1));
+// v.setDelegatingId(p.get(PrefConstants.delegate, null));
+//
+// Validator.V2 v2 = v.asV2Validator();
+// if (v2 == null)return;
+// if (!p.nodeExists(PrefConstants.groups))return;
+//
+// Preferences groupNode = p.node(PrefConstants.groups);
+// for (String groupName : groupNode.childrenNames()){
+// Preferences group = groupNode.node(groupName);
+// String type = group.get(PrefConstants.type, null);
+// if (type == null)throw new IllegalStateException(ValMessages.ErrGroupNoType);
+// FilterGroup fg = FilterGroup.create(type);
+// if (fg == null)throw new IllegalStateException(NLS.bind(ValMessages.ErrGroupInvalidType, type));
+// v2.add(fg);
+//
+// if (group.nodeExists(PrefConstants.rules)){
+// Preferences ruleNode = group.node(PrefConstants.rules);
+// for (String ruleName : ruleNode.childrenNames()){
+// Preferences rule = ruleNode.node(ruleName);
+// FilterRule fr = FilterRule.create(rule.get(PrefConstants.ruleType, null));
+// if (fr != null){
+// fr.load(rule);
+// fg.add(fr);
+// }
+// }
+// }
+// }
+// }
+
+ /**
+ * Save the validator into the preference store.
+ *
+ * @param validator
+ * The validator being saved.
+ *
+ * @param root
+ * The top of the preference tree for validators, i.e.
+ * /instance/validator-framework-id/vals for workspace validators
+ * and /vals for project validators.
+ *
+ * @param baseValidators
+ * A map of the validators that are one level higher in the
+ * storage hierarchy. So if we are updating the preference page
+ * validators, then this map would be the extension point
+ * validators. If we are updating a project's validators, then
+ * this map would be the preference page validators.
+ */
+ static void save(Validator validator, PreferencesWrapper root, Map<String, Validator> baseValidators) throws BackingStoreException {
+ Validator.V2 v2 = validator.asV2Validator();
+ if (v2 == null)return;
+
+ final String id = validator.getId();
+ boolean hasNode = root.nodeExists(id);
+
+ if (validator.sameConfig(baseValidators.get(id))){
+ if (hasNode){
+ PreferencesWrapper vp = root.node(id);
+ vp.removeNode();
+ }
+ return;
+ }
+ if (!validator.isChanged())return;
+ PreferencesWrapper vp = root.node(id);
+ if (validator.hasGlobalChanges()){
+ Global g = new Global(validator.isManualValidation(), validator.isBuildValidation(), validator.getVersion(),
+ validator.getDelegatingId());
+ vp.put(PrefConstants.global, g.serialize());
+ Friend.setMigrated(validator, false);
+ }
+
+ if (validator.getChangeCountMessages() > 0){
+ Collection<MessageSeveritySetting> msgs = validator.getMessageSettings().values();
+ if (msgs.size() > 0){
+ vp.put(PrefConstants.msgs, Msgs.serialize(msgs));
+ }
+ }
+
+ if (v2.getChangeCountGroups() > 0){
+ FilterGroup[] groups = v2.getGroups();
+ if (groups.length > 0){
+ Serializer ser = new Serializer(500);
+ for (FilterGroup group : groups)group.save(ser);
+ vp.put(PrefConstants.groups, ser.toString());
+ }
+ }
+ }
+ /**
+ * Save the validator into the preference store.
+ *
+ * @param validator
+ * The validator being saved.
+ *
+ * @param root
+ * The top of the preference tree for validators, i.e.
+ * /instance/validator-framework-id/vals for workspace validators
+ * and /vals for project validators.
+ *
+ * @param baseValidators
+ * A map of the validators that are one level higher in the
+ * storage hierarchy. So if we are updating the preference page
+ * validators, then this map would be the extension point
+ * validators. If we are updating a project's validators, then
+ * this map would be the preference page validators.
+ */
+ static void save(ValidatorMutable validator, PreferencesWrapper root, Map<String, Validator> baseValidators) throws BackingStoreException {
+ if (!validator.isV2Validator())return;
+
+ PreferencesWrapper vp = root.node(validator.getId());
+ if (validator.sameConfig(baseValidators.get(validator.getId()))){
+ vp.removeNode();
+ return;
+ }
+ if (!validator.isChanged())return;
+ if (validator.hasGlobalChanges()){
+ Global g = new Global(validator.isManualValidation(), validator.isBuildValidation(), validator.getVersion(),
+ validator.getDelegatingId());
+ vp.put(PrefConstants.global, g.serialize());
+// Friend.setMigrated(validator, false);
+ }
+
+ if (validator.getChangeCountGroups() > 0){
+ FilterGroup[] groups = validator.getGroups();
+ if (groups.length > 0){
+ Serializer ser = new Serializer(500);
+ for (FilterGroup group : groups)group.save(ser);
+ vp.put(PrefConstants.groups, ser.toString());
+ }
+ }
+ }
+
+ public void saveAsPrefs(Validator[] val) {
+ try {
+ PreferencesWrapper pref = PreferencesWrapper.getPreferences(null, null);
+ PreferencesWrapper vals = pref.node(PrefConstants.vals);
+ Map<String, Validator> base = ExtensionValidators.instance().getMapV2();
+ for (Validator v : val)save(v, vals, base);
+ pref.flush();
+ _validators.set(null);
+ updateListeners(true);
+ }
+ catch (BackingStoreException e){
+ throw new RuntimeException(e);
+ }
+ }
+
+
+ /**
+ * Save the global preferences and the validators.
+ */
+ public synchronized void savePreferences(GlobalPreferences gp, Validator[] validators){
+ try {
+ PreferencesWrapper prefs = PreferencesWrapper.getPreferences(null, null);
+ savePreferences(prefs, gp);
+ PreferencesWrapper vals = prefs.node(PrefConstants.vals);
+
+ Map<String, Validator> base = ExtensionValidators.instance().getMapV2();
+ for (Validator v : validators)save(v, vals, base);
+ prefs.flush();
+ _validators.set(null);
+ updateListeners(true);
+ }
+ catch (BackingStoreException e){
+ ValidationPlugin.getPlugin().handleException(e);
+ }
+ }
+
+ /**
+ * Save the global preferences and the validators.
+ */
+ public synchronized void savePreferences(GlobalPreferences gp, ValidatorMutable[] validators, Boolean persist){
+ try {
+ PreferencesWrapper prefs = PreferencesWrapper.getPreferences(null, persist);
+ savePreferences(prefs, gp);
+ PreferencesWrapper vals = prefs.node(PrefConstants.vals);
+ Map<String, Validator> base = ExtensionValidators.instance().getMapV2();
+ for (ValidatorMutable v : validators)save(v, vals, base);
+
+ prefs.flush();
+ _validators.set(null);
+ updateListeners(true);
+ }
+ catch (BackingStoreException e){
+ ValidationPlugin.getPlugin().handleException(e);
+ }
+ }
+
+ /**
+ * Save the V1 preferences, so that the old validators continue to work.
+ */
+ public static void saveV1Preferences(ValidatorMutable[] validators, Boolean persistent){
+ try {
+ GlobalConfiguration gc = ConfigurationManager.getManager().getGlobalConfiguration();
+ gc.setEnabledManualValidators(getEnabledManualValidators(validators));
+ gc.setEnabledBuildValidators(getEnabledBuildValidators(validators));
+
+ gc.passivate();
+ gc.store(persistent);
+ }
+ catch (InvocationTargetException e){
+ ValidationPlugin.getPlugin().handleException(e);
+ }
+ }
+
+ /**
+ * Answer all the V1 validators that are manually enabled.
+ * @return
+ */
+ private static ValidatorMetaData[] getEnabledManualValidators(ValidatorMutable[] validators) {
+ List<ValidatorMetaData> list = new LinkedList<ValidatorMetaData>();
+ for (ValidatorMutable v : validators){
+ if (v.isManualValidation() && v.isV1Validator())list.add(v.getVmd());
+ }
+ ValidatorMetaData[] result = new ValidatorMetaData[list.size()];
+ list.toArray(result);
+ return result;
+ }
+
+ /**
+ * Answer all the V1 validators that are enabled for build.
+ * @return
+ */
+ private static ValidatorMetaData[] getEnabledBuildValidators(ValidatorMutable[] validators) {
+ List<ValidatorMetaData> list = new LinkedList<ValidatorMetaData>();
+ for (ValidatorMutable v : validators){
+ if (v.isBuildValidation() && v.isV1Validator())list.add(v.getVmd());
+ }
+ ValidatorMetaData[] result = new ValidatorMetaData[list.size()];
+ list.toArray(result);
+ return result;
+ }
+
+
+ /**
+ * Save the global preferences and the validators.
+ */
+ public synchronized void savePreferences(){
+ try {
+ GlobalPreferences gp = ValManager.getDefault().getGlobalPreferences();
+ PreferencesWrapper prefs = PreferencesWrapper.getPreferences(null, null);
+ savePreferences(prefs, gp);
+ prefs.flush();
+ updateListeners(true);
+ }
+ catch (BackingStoreException e){
+ ValidationPlugin.getPlugin().handleException(e);
+ }
+ }
+
+ /**
+ * Save the global preferences and the validators.
+ */
+ private void savePreferences(PreferencesWrapper prefs, GlobalPreferences gp){
+ prefs.putBoolean(PrefConstants.saveAuto, gp.getSaveAutomatically());
+ prefs.putBoolean(PrefConstants.suspend, gp.getDisableAllValidation());
+ prefs.putLong(PrefConstants.stateTS, gp.getStateTimeStamp());
+ prefs.putBoolean(PrefConstants.confirmDialog, gp.getConfirmDialog());
+ prefs.putBoolean(PrefConstants.override, gp.getOverride());
+ prefs.putInt(PrefConstants.frameworkVersion, ValPrefManagerGlobal.frameworkVersion);
+ }
+
+ /**
+ * Update any message preferences in the map.
+ * @param validator
+ * @param settings
+ */
+ public void loadMessages(Validator validator, Map<String, MessageSeveritySetting> settings) {
+ PreferencesWrapper pref = PreferencesWrapper.getPreferences(null, null);
+ try {
+ loadMessageSettings(validator, settings, pref);
+ }
+ catch (BackingStoreException e){
+ ValidationPlugin.getPlugin().handleException(e);
+ }
+ }
+
+ /**
+ * Load the message preferences for the validator into the map.
+ *
+ * @param val
+ * @param settings
+ * @param root the root of the preference store
+ */
+ static void loadMessageSettings(Validator val, Map<String, MessageSeveritySetting> settings, PreferencesWrapper root)
+ throws BackingStoreException {
+ if (!root.nodeExists(PrefConstants.vals))return;
+
+ PreferencesWrapper vals = root.node(PrefConstants.vals);
+ if (!vals.nodeExists(val.getId()))return;
+
+ PreferencesWrapper valPrefs = vals.node(val.getId());
+ String msgs = valPrefs.get(PrefConstants.msgs, ""); //$NON-NLS-1$
+ if (msgs.length() == 0)return;
+
+ Map<String, MessageSeveritySetting.Severity> map = Msgs.deserialize(msgs);
+
+ for (Map.Entry<String, MessageSeveritySetting.Severity> me : map.entrySet()){
+ MessageSeveritySetting ms = settings.get(me.getKey());
+ if (ms != null)ms.setCurrent(me.getValue());
+ }
+ }
+
+ /**
+ * Save whether the validator is enabled or not.
+ * @param validator
+ * @param prefs up to the filter part of the preference tree
+ */
+// private void saveShallowPreference(Validator validator, Preferences prefs) {
+// if (validator.asV2Validator() == null)return;
+// Preferences val = prefs.node(validator.getId());
+// val.putBoolean(PrefConstants.build, validator.isBuildValidation());
+// val.putBoolean(PrefConstants.manual, validator.isManualValidation());
+// val.putInt(PrefConstants.version, validator.getVersion());
+// }
+
+// /**
+// * Load the customized message settings from the preference store.
+// * @param messageSettings
+// */
+// public void loadMessageSettings(Validator val, MessageCategory[] messageSettings) {
+// try {
+// loadMessageSettings(val, messageSettings, ValidationFramework.getDefault().getPreferenceStore());
+// }
+// catch (Exception e){
+// ValidationPlugin.getPlugin().handleException(e);
+// }
+// }
+
+ private final static class Global {
+ private final boolean _manual;
+ private final boolean _build;
+ private final int _version;
+ private final String _delegating;
+
+ public Global(String value){
+ Deserializer d = new Deserializer(value);
+ _manual = d.getBoolean();
+ _build = d.getBoolean();
+ _version = d.getInt();
+ _delegating = d.hasNext() ? d.getString() : null;
+ }
+
+ public Global(boolean manual, boolean build, int version, String delegating){
+ _manual = manual;
+ _build = build;
+ _version = version;
+ _delegating = delegating;
+ }
+
+ public String serialize(){
+ Serializer s = new Serializer(50);
+ s.put(_manual);
+ s.put(_build);
+ s.put(_version);
+ if (_delegating != null)s.put(_delegating);
+ return s.toString();
+ }
+
+ public boolean isManual() {
+ return _manual;
+ }
+
+ public boolean isBuild() {
+ return _build;
+ }
+
+ public int getVersion() {
+ return _version;
+ }
+
+ public String getDelegating() {
+ return _delegating;
+ }
+ }
+
+ private final static class Msgs {
+ public static String serialize(Collection<MessageSeveritySetting> messages){
+ Serializer s = new Serializer(100);
+ for (MessageSeveritySetting ms : messages){
+ s.put(ms.getId());
+ s.put(ms.getCurrent().ordinal());
+ }
+ return s.toString();
+ }
+
+ /**
+ * Answer a map for all the messages.
+ * The key is the message id and the value is the current setting for that message
+ * @param v
+ * @return
+ */
+ public static Map<String, MessageSeveritySetting.Severity> deserialize(String v){
+ Map<String, MessageSeveritySetting.Severity> map = new HashMap<String, MessageSeveritySetting.Severity>(10);
+ Deserializer d = new Deserializer(v);
+ while(d.hasNext()){
+ String id = d.getString();
+ int sev = d.getInt();
+ map.put(id, MessageSeveritySetting.Severity.values()[sev]);
+ }
+ return map;
+ }
+ }
+
+ /**
+ * Store the singleton for the ValPrefManagerGlobal. This approach is used to avoid having to synchronize the
+ * ValPrefManagerGlobal.getDefault() method.
+ *
+ * @author karasiuk
+ *
+ */
+ private final static class Singleton {
+ final static ValPrefManagerGlobal valPrefManagerGlobal = new ValPrefManagerGlobal();
+ }
+
+}
diff --git a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/ValPrefManagerProject.java b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/ValPrefManagerProject.java
new file mode 100644
index 0000000..c28b031
--- /dev/null
+++ b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/ValPrefManagerProject.java
@@ -0,0 +1,388 @@
+/*******************************************************************************
+ * Copyright (c) 2007, 2008 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.wst.validation.internal;
+
+import java.lang.reflect.InvocationTargetException;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import org.eclipse.core.resources.IProject;
+import org.eclipse.wst.validation.Friend;
+import org.eclipse.wst.validation.IMutableValidator;
+import org.eclipse.wst.validation.MessageSeveritySetting;
+import org.eclipse.wst.validation.MutableProjectSettings;
+import org.eclipse.wst.validation.Validator;
+import org.eclipse.wst.validation.Validator.V2;
+import org.eclipse.wst.validation.internal.model.ProjectPreferences;
+import org.eclipse.wst.validation.internal.plugin.ValidationPlugin;
+import org.osgi.service.prefs.BackingStoreException;
+
+/**
+ * A class that knows how to manage the project level persisted validation settings.
+ * @author karasiuk
+ *
+ */
+public final class ValPrefManagerProject {
+
+ private final IProject _project;
+ private final static List<IValChangedListener> _listeners = new LinkedList<IValChangedListener>();
+
+ /**
+ * The validators that are in the project preference file, but have
+ * only been configured to the global preference level. That is they have not had
+ * any project level customizations applied yet.
+ */
+ private List<Validator> _validators;
+
+ public ValPrefManagerProject(IProject project){
+ assert project != null;
+ _project = project;
+ }
+
+ public static void addListener(IValChangedListener listener){
+ if (_listeners.contains(listener))return;
+ _listeners.add(listener);
+ }
+
+ public static void removeListener(IValChangedListener listener){
+ _listeners.remove(listener);
+ }
+
+ private static void updateListeners(IProject project){
+ for (IValChangedListener cl : _listeners)cl.validatorsForProjectChanged(project, true);
+ }
+
+
+ /**
+ * Answer whether or not this project has validation settings.
+ *
+ * @return true if it has settings. This does not mean that the settings are enabled, only that it
+ * has settings.
+ *
+ * @deprecated
+ */
+ public boolean hasProjectSpecificSettings(){
+ PreferencesWrapper pref = getPreferences(null);
+
+ if (pref == null)return false;
+ return true;
+ }
+
+ /**
+ * Answer the v2 validators that have been overridden by the project
+ * preferences. The validators will not have the preference store's
+ * customizations applied yet. The purpose of this method, is to identify the subset of validators
+ * that may later be configured.
+ *
+ * @param baseValidators
+ * V2 validators from the extension points, and customized by any
+ * global preferences.
+ */
+ public List<Validator> getValidators(Map<String, Validator> baseValidators) throws BackingStoreException {
+ List<Validator> vals = _validators;
+ if (vals == null){
+ vals = loadValidators(baseValidators);
+ _validators = vals;
+ }
+ return vals;
+ }
+
+ /**
+ * Load the validators from the preference store. The validators will not have the preference store's
+ * customizations applied yet. The purpose of this method, is to identify the subset of validators
+ * that may later be configured.
+ *
+ * @param baseValidators
+ * V2 validators from the extension points, and customized by any
+ * global preferences.
+ * @return the validators that are in the project preference file, but have
+ * only been configured to the global preference level. That is they have not had
+ * any project level customizations applied yet.
+ */
+ private List<Validator> loadValidators(Map<String, Validator> baseValidators) throws BackingStoreException {
+ List<Validator> list = new LinkedList<Validator>();
+ PreferencesWrapper pref = getPreferences(null);
+ if (pref.nodeExists(PrefConstants.vals)){
+ PreferencesWrapper vals = pref.node(PrefConstants.vals);
+ for (String id : vals.childrenNames()){
+ Validator base = baseValidators.get(id);
+ Validator v = ValPrefManagerGlobal.loadValidator(id, vals, base);
+ if (v != null){
+ V2 v2 = v.asV2Validator();
+ if (v2 != null)v2.setLevel(Validator.Level.Project);
+ list.add(v);
+ }
+ }
+ }
+ return list;
+ }
+
+ /**
+ * Answer the setting of the getOverride field.
+ */
+ public boolean getOverride(){
+ PreferencesWrapper pref = getPreferences(null);
+
+ if (!pref.nodeExists())return ProjectPreferences.DefaultOverride;
+
+ int version = pref.getInt(PrefConstants.frameworkVersion, 0);
+ if (version == 0){
+ try {
+ ProjectConfiguration pc = ConfigurationManager.getManager().getProjectConfiguration(_project);
+ return pc.getDoesProjectOverride();
+ }
+ catch (InvocationTargetException e){
+ // eat it, if it fails we just go with the defaults
+ }
+ }
+ return pref.getBoolean(PrefConstants.override, ProjectPreferences.DefaultOverride);
+ }
+
+ private ProjectPreferences migrateFromBeforeWTP30(IProject project, Map<String, Validator> baseValidators) {
+ try {
+ ProjectConfiguration pc = ConfigurationManager.getManager().getProjectConfiguration(project);
+
+ List<Validator> list = migrateFromBeforeWTP30(baseValidators, pc);
+ Validator[] vals = new Validator[list.size()];
+ list.toArray(vals);
+ return new ProjectPreferences(project, pc.getDoesProjectOverride(), pc.isDisableAllValidation(), vals);
+ }
+ catch (InvocationTargetException e){
+ // eat it, if it fails we just go with the defaults
+ }
+ return new ProjectPreferences(project);
+ }
+
+ private List<Validator> migrateFromBeforeWTP30(Map<String, Validator> baseValidators, ProjectConfiguration pc)
+ throws InvocationTargetException {
+
+ Set<String> build = pc.getEnabledBuildlValidators();
+ Set<String> manual = pc.getEnabledManualValidators();
+
+ List<Validator> list = new LinkedList<Validator>();
+ for (Validator v : baseValidators.values()){
+ V2 v2 = v.asV2Validator();
+ if (v2 != null){
+ boolean isBuild = build == null || build.contains(v2.getValidatorClassname());
+ boolean isManual = manual == null || manual.contains(v2.getValidatorClassname());
+ if ((v.isBuildValidation() != isBuild) || (v.isManualValidation() != isManual)){
+ V2 copy = v2.copy().asV2Validator();
+ copy.setBuildValidation(isBuild);
+ copy.setManualValidation(isManual);
+ copy.setLevel(Validator.Level.Project);
+ Friend.setMigrated(copy, true);
+ list.add(copy);
+ }
+ }
+ }
+ return list;
+ }
+
+
+ /**
+ * Answer the project preferences from the preference store.
+ * @return null if the project does not have any specific preferences.
+ */
+ public ProjectPreferences loadProjectPreferences(IProject project, Map<String, Validator> baseValidators)
+ throws BackingStoreException {
+
+ PreferencesWrapper pref = getPreferences(null);
+
+ if (pref == null)return null;
+ int version = pref.getInt(PrefConstants.frameworkVersion, 0);
+ if (version == 0){
+ // This means that we have a project that is before WTP 3.0
+ return migrateFromBeforeWTP30(project, baseValidators);
+ }
+
+ if (version != ValPrefManagerGlobal.frameworkVersion)ValPrefManagerGlobal.migrate(version, pref);
+
+ if (!pref.nodeExists(PrefConstants.vals)){
+ return new ProjectPreferences(project, pref.getBoolean(PrefConstants.override, ProjectPreferences.DefaultOverride),
+ pref.getBoolean(PrefConstants.suspend, ProjectPreferences.DefaultSuspend), new Validator[0]);
+ }
+
+ PreferencesWrapper vp = pref.node(PrefConstants.vals);
+ List<Validator> list = new LinkedList<Validator>();
+ for (String id : vp.childrenNames()){
+ Validator base = baseValidators.get(id);
+ Validator v = ValPrefManagerGlobal.loadValidator(id, vp, base);
+ if (v != null){
+ V2 v2 = v.asV2Validator();
+ if (v2 != null)v2.setLevel(Validator.Level.Project);
+ list.add(v);
+ }
+ }
+ Validator[] vals = new Validator[list.size()];
+ list.toArray(vals);
+ return new ProjectPreferences(project, pref.getBoolean(PrefConstants.override, ProjectPreferences.DefaultOverride),
+ pref.getBoolean(PrefConstants.suspend, ProjectPreferences.DefaultSuspend), vals);
+ }
+
+ private PreferencesWrapper getPreferences(Boolean persist) {
+ return PreferencesWrapper.getPreferences(_project, persist);
+ }
+
+ public void savePreferences(ProjectPreferences projectPreferences) {
+ Validator[] validators = projectPreferences.getValidators();
+ PreferencesWrapper pref = getPreferences(null);
+ pref.putBoolean(PrefConstants.suspend, projectPreferences.getSuspend());
+ pref.putBoolean(PrefConstants.override, projectPreferences.getOverride());
+ pref.putInt(PrefConstants.frameworkVersion, ValPrefManagerGlobal.frameworkVersion);
+ PreferencesWrapper vals = pref.node(PrefConstants.vals);
+ try {
+ Validator[] workspaceVals = ValManager.getDefault().getValidators();
+ Map<String, Validator> base = new HashMap<String, Validator>(workspaceVals.length);
+ for (Validator v : workspaceVals)base.put(v.getId(), v);
+ for (Validator v : validators)ValPrefManagerGlobal.save(v, vals, base);
+ pref.flush();
+ ProjectConfiguration pc = ConfigurationManager.getManager()
+ .getProjectConfiguration(projectPreferences.getProject());
+ pc.setEnabledBuildValidators(getEnabledBuildValidators(validators));
+ pc.setEnabledManualValidators(getEnabledManualValidators(validators));
+ pc.passivate();
+ pc.store();
+ updateListeners(_project);
+ }
+ catch (Exception e){
+ ValidationPlugin.getPlugin().handleException(e);
+ }
+ }
+
+ public void savePreferences(ProjectPreferences projectPreferences, ValidatorMutable[] validators) {
+ PreferencesWrapper pref = getPreferences(null);
+ pref.putBoolean(PrefConstants.suspend, projectPreferences.getSuspend());
+ pref.putBoolean(PrefConstants.override, projectPreferences.getOverride());
+ pref.putInt(PrefConstants.frameworkVersion, ValPrefManagerGlobal.frameworkVersion);
+ try {
+ savePreferences(validators, false, null);
+ pref.flush();
+ updateListeners(_project);
+ }
+ catch (Exception e){
+ ValidationPlugin.getPlugin().handleException(e);
+ }
+ }
+
+ public void savePreferences(MutableProjectSettings settings, Boolean persist){
+ IProject project = settings.getProject();
+ PreferencesWrapper pref = PreferencesWrapper.getPreferences(project, persist);
+ pref.putBoolean(PrefConstants.suspend, settings.getSuspend());
+ pref.putBoolean(PrefConstants.override, settings.getOverride());
+ pref.putInt(PrefConstants.frameworkVersion, ValPrefManagerGlobal.frameworkVersion);
+
+ IMutableValidator[] vms = settings.getValidators();
+ ValidatorMutable[] validators = new ValidatorMutable[vms.length];
+ for (int i=0; i<vms.length;i++)validators[i] = (ValidatorMutable)vms[i];
+
+ try {
+ savePreferences(validators, false, persist);
+ pref.flush();
+ updateListeners(project);
+ }
+ catch (Exception e){
+ if (project.isAccessible())ValidationPlugin.getPlugin().handleException(e);
+ }
+ }
+
+ public void savePreferences(ValidatorMutable[] validators, boolean flush, Boolean persist){
+ PreferencesWrapper pref = getPreferences(persist);
+ pref.putInt(PrefConstants.frameworkVersion, ValPrefManagerGlobal.frameworkVersion);
+ PreferencesWrapper vals = pref.node(PrefConstants.vals);
+ try {
+ Validator[] workspaceVals = ValManager.getDefault().getValidators();
+ Map<String, Validator> base = new HashMap<String, Validator>(workspaceVals.length);
+ for (Validator v : workspaceVals)base.put(v.getId(), v);
+ for (ValidatorMutable v : validators)ValPrefManagerGlobal.save(v, vals, base);
+ ProjectConfiguration pc = ConfigurationManager.getManager().getProjectConfiguration(_project);
+ pc.setEnabledBuildValidators(getEnabledBuildValidators(validators));
+ pc.setEnabledManualValidators(getEnabledManualValidators(validators));
+ pc.passivate();
+ pc.store();
+ if (flush){
+ pref.flush();
+ updateListeners(_project);
+ }
+ }
+ catch (Exception e){
+ ValidationPlugin.getPlugin().handleException(e);
+ }
+
+ }
+
+ /**
+ * Answer all the V1 validators that are enabled for build.
+ * @return
+ */
+ private Set<ValidatorMetaData> getEnabledBuildValidators(Validator[] validators) {
+ Set<ValidatorMetaData> set = new HashSet<ValidatorMetaData>(50);
+ for (Validator v : validators){
+ if (v.isBuildValidation()){
+ Validator.V1 v1 = v.asV1Validator();
+ if (v1 != null)set.add(v1.getVmd());
+ }
+ }
+ return set;
+ }
+
+ /**
+ * Answer all the V1 validators that are enabled for build.
+ * @return
+ */
+ private Set<ValidatorMetaData> getEnabledBuildValidators(ValidatorMutable[] validators) {
+ Set<ValidatorMetaData> set = new HashSet<ValidatorMetaData>(50);
+ for (ValidatorMutable v : validators){
+ if (v.isBuildValidation() && v.isV1Validator())set.add(v.getVmd());
+ }
+ return set;
+ }
+
+ /**
+ * Answer all the V1 validators that are enabled for manual validation.
+ * @return
+ */
+ private Set<ValidatorMetaData> getEnabledManualValidators(Validator[] validators) {
+ Set<ValidatorMetaData> set = new HashSet<ValidatorMetaData>(50);
+ for (Validator v : validators){
+ if (v.isManualValidation()){
+ Validator.V1 v1 = v.asV1Validator();
+ if (v1 != null)set.add(v1.getVmd());
+ }
+ }
+ return set;
+ }
+
+ /**
+ * Answer all the V1 validators that are enabled for manual validation.
+ * @return
+ */
+ private Set<ValidatorMetaData> getEnabledManualValidators(ValidatorMutable[] validators) {
+ Set<ValidatorMetaData> set = new HashSet<ValidatorMetaData>(50);
+ for (ValidatorMutable v : validators){
+ if (v.isManualValidation() && v.isV1Validator())set.add(v.getVmd());
+ }
+ return set;
+ }
+
+ public void loadMessages(Validator validator, Map<String, MessageSeveritySetting> settings) {
+ try {
+ ValPrefManagerGlobal.loadMessageSettings(validator, settings, getPreferences(null));
+ }
+ catch (BackingStoreException e){
+ ValidationPlugin.getPlugin().handleException(e);
+ }
+ }
+
+}
diff --git a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/ValProperty.java b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/ValProperty.java
new file mode 100644
index 0000000..fd001dc
--- /dev/null
+++ b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/ValProperty.java
@@ -0,0 +1,53 @@
+/*******************************************************************************
+ * Copyright (c) 2007, 2008 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.wst.validation.internal;
+
+import java.util.BitSet;
+
+/**
+ * A resource session property, that is used to improve the performance of the validation framework. This is placed
+ * on each resource and it enables the framework to quickly determine if the resource needs to be processed.
+ * @author karasiuk
+ *
+ */
+public class ValProperty {
+/*
+ * I did some performance measurements on the IResource#setSessionProperty() and IResource#getSessionProperty()
+ * methods, and they were very fast. I used a very large workspace (over 17,000) resources, and you could set (or get)
+ * a property on all the resources in under 100ms.
+ */
+
+ private int _configNumber;
+ private BitSet _configSet = new BitSet(100);
+
+ private int _validationNumber;
+ private BitSet _validationSet = new BitSet(100);
+
+ public int getConfigNumber() {
+ return _configNumber;
+ }
+ public void setConfigNumber(int configNumber) {
+ _configNumber = configNumber;
+ }
+ public BitSet getConfigSet() {
+ return _configSet;
+ }
+ public int getValidationNumber() {
+ return _validationNumber;
+ }
+ public void setValidationNumber(int validationNumber) {
+ _validationNumber = validationNumber;
+ }
+ public BitSet getValidationSet() {
+ return _validationSet;
+ }
+
+}
diff --git a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/ValType.java b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/ValType.java
new file mode 100644
index 0000000..8a97136
--- /dev/null
+++ b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/ValType.java
@@ -0,0 +1,24 @@
+/*******************************************************************************
+ * Copyright (c) 2008 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.wst.validation.internal;
+
+/**
+ * Type of validation. Build or Manual?
+ * @author karasiuk
+ *
+ */
+public enum ValType {
+ /** The validation is triggered via a resource change and the build process. */
+ Build,
+
+ /** The user manually requested the validation. */
+ Manual,
+}
diff --git a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/ValidationResultSummary.java b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/ValidationResultSummary.java
new file mode 100644
index 0000000..9e91217
--- /dev/null
+++ b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/ValidationResultSummary.java
@@ -0,0 +1,42 @@
+/*******************************************************************************
+ * Copyright (c) 2008, 2009 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.wst.validation.internal;
+
+/**
+ * An immutable object that holds a summary of the validation.
+ * @author karasiuk
+ *
+ */
+public final class ValidationResultSummary {
+
+ private final int _error;
+ private final int _warning;
+ private final int _info;
+
+ public ValidationResultSummary(int error, int warning, int info){
+ _error = error;
+ _warning = warning;
+ _info = info;
+ }
+
+ public int getSeverityError() {
+ return _error;
+ }
+
+ public int getSeverityWarning() {
+ return _warning;
+ }
+
+ public int getSeverityInfo() {
+ return _info;
+ }
+
+}
diff --git a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/ValidationRunner.java b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/ValidationRunner.java
new file mode 100644
index 0000000..01bf297
--- /dev/null
+++ b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/ValidationRunner.java
@@ -0,0 +1,151 @@
+/*******************************************************************************
+ * Copyright (c) 2007, 2009 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.wst.validation.internal;
+
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Set;
+
+import org.eclipse.core.resources.IFile;
+import org.eclipse.core.resources.IProject;
+import org.eclipse.core.resources.IResource;
+import org.eclipse.core.resources.IResourceDelta;
+import org.eclipse.core.resources.IWorkspace;
+import org.eclipse.core.resources.IWorkspaceRunnable;
+import org.eclipse.core.resources.IncrementalProjectBuilder;
+import org.eclipse.core.resources.ResourcesPlugin;
+import org.eclipse.core.runtime.CoreException;
+import org.eclipse.core.runtime.IProgressMonitor;
+import org.eclipse.wst.validation.Validator;
+import org.eclipse.wst.validation.internal.model.IValidatorVisitor;
+
+/**
+ * Run the validators on a selected set of resources.
+ * <p>
+ * This is used to run manual validations (i.e. the user selects the Validate menu item),
+ * or it is invoked programmatically by a third party through the ValidationFramework API.
+ * It is not used for the build based invocation.
+ * </p>
+ * @author karasiuk
+ *
+ */
+public final class ValidationRunner implements IWorkspaceRunnable {
+
+ private Map<IProject, Set<IResource>> _projects;
+ private ValType _valType;
+ private ValOperation _valOperation;
+
+ /**
+ * Validate the selected projects and/or resources.
+ *
+ * @param projects
+ * The selected projects. The key is an IProject and the value is
+ * the Set of IResources that were selected. Often this will be
+ * every resource in the project.
+ *
+ * @param valType
+ * The type of validation that has been requested.
+ *
+ * @param monitor
+ * Progress monitor.
+ *
+ * @param atomic
+ * Run as an atomic workspace operation?
+ */
+ public static ValOperation validate(Map<IProject, Set<IResource>> projects, ValType valType,
+ IProgressMonitor monitor, boolean atomic) throws CoreException{
+ ValidationRunner me = new ValidationRunner(projects, valType);
+ if (atomic)ResourcesPlugin.getWorkspace().run(me, null, IWorkspace.AVOID_UPDATE, monitor);
+ else me.execute(monitor);
+ return me._valOperation;
+ }
+
+ /**
+ * Validate the selected file. This is a convenience method, it simply calls the more flexible
+ * validate with Map method.
+ *
+ * @param file
+ * The file to be validated.
+ *
+ * @param valType
+ * The type of validation that has been requested.
+ *
+ * @param monitor
+ * Progress monitor.
+ *
+ * @param atomic
+ * Run as an atomic workspace operation?
+ */
+ public static ValOperation validate(IFile file, ValType valType, IProgressMonitor monitor, boolean atomic) throws CoreException{
+ final Map<IProject, Set<IResource>> map = new HashMap<IProject, Set<IResource>>(1);
+
+ Set<IResource> set = new HashSet<IResource>(1);
+ set.add(file);
+ map.put(file.getProject(), set);
+ return validate(map, valType, monitor, atomic);
+ }
+
+ private ValidationRunner(Map<IProject, Set<IResource>> projects, ValType valType){
+ _projects = projects;
+ _valType = valType;
+
+ }
+
+ private ValOperation execute(IProgressMonitor monitor){
+ _valOperation = new ValOperation();
+ ValManager manager = ValManager.getDefault();
+
+ IValidatorVisitor startingVisitor = new IValidatorVisitor(){
+ public void visit(Validator validator, IProject project, ValType valType,
+ ValOperation operation, IProgressMonitor monitor) {
+ validator.validationStarting(project, operation.getState(), monitor);
+ }
+ };
+
+ IValidatorVisitor finishedVisitor = new IValidatorVisitor(){
+
+ public void visit(Validator validator, IProject project, ValType valType,
+ ValOperation operation, IProgressMonitor monitor) {
+
+ validator.validationFinishing(project, operation.getState(), monitor);
+ }
+ };
+
+ manager.accept(startingVisitor, null, _valType, _valOperation, monitor);
+
+ for (Map.Entry<IProject, Set<IResource>> me : _projects.entrySet()){
+ if (monitor.isCanceled()){
+ _valOperation.setCanceled(true);
+ return _valOperation;
+ }
+ IProject project = me.getKey();
+ manager.accept(startingVisitor, project, _valType, _valOperation, monitor);
+ for (IResource resource : me.getValue()){
+ try {
+ manager.validate(project, resource, IResourceDelta.NO_CHANGE, _valType,
+ IncrementalProjectBuilder.AUTO_BUILD, _valOperation, monitor);
+ }
+ catch (ResourceUnavailableError error){
+ // if the resource is no longer available, we can't validate it, so we should just move on.
+ }
+ }
+ manager.accept(finishedVisitor, project, _valType, _valOperation, monitor);
+ }
+ manager.accept(finishedVisitor, null, _valType, _valOperation, monitor);
+ return _valOperation;
+ }
+
+ public void run(IProgressMonitor monitor) throws CoreException {
+ execute(monitor);
+ }
+
+}
diff --git a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/ValidatorExtensionReader.java b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/ValidatorExtensionReader.java
new file mode 100644
index 0000000..c897cfc
--- /dev/null
+++ b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/ValidatorExtensionReader.java
@@ -0,0 +1,374 @@
+/*******************************************************************************
+ * Copyright (c) 2007, 2009 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.wst.validation.internal;
+
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+
+import org.eclipse.core.resources.IProject;
+import org.eclipse.core.runtime.CoreException;
+import org.eclipse.core.runtime.IConfigurationElement;
+import org.eclipse.core.runtime.IContributor;
+import org.eclipse.core.runtime.IExtension;
+import org.eclipse.core.runtime.IExtensionPoint;
+import org.eclipse.core.runtime.IExtensionRegistry;
+import org.eclipse.core.runtime.IStatus;
+import org.eclipse.core.runtime.Platform;
+import org.eclipse.core.runtime.Status;
+import org.eclipse.osgi.util.NLS;
+import org.eclipse.wst.validation.MessageSeveritySetting;
+import org.eclipse.wst.validation.Validator;
+import org.eclipse.wst.validation.Validator.V2;
+import org.eclipse.wst.validation.internal.model.FilterGroup;
+import org.eclipse.wst.validation.internal.model.FilterRule;
+import org.eclipse.wst.validation.internal.plugin.ValidationPlugin;
+
+/**
+ * Process the validator (version 2) extension point.
+ *
+ * @author karasiuk
+ *
+ */
+public class ValidatorExtensionReader {
+
+ private static ValidatorExtensionReader _me = new ValidatorExtensionReader();
+
+ public static ValidatorExtensionReader getDefault(){
+ return _me;
+ }
+
+ private ValidatorExtensionReader(){}
+
+ /**
+ * Process the v2 extensions, returning all the v2 validators.
+ */
+ Collection<Validator> process() {
+ Map<String,Validator> map = new HashMap<String, Validator>(100);
+ IExtensionPoint extensionPoint = getExtensionPoint();
+ if (extensionPoint == null)return map.values();
+
+ for (IExtension ext : extensionPoint.getExtensions()){
+ for (IConfigurationElement validator : ext.getConfigurationElements()){
+ String id = ext.getUniqueIdentifier();
+ if (Tracing.isEnabled(id)){
+ Validator v = processValidator(validator, id, ext.getLabel(), null);
+ if (v != null)map.put(v.getId(),v);
+ }
+ }
+ }
+
+ extensionPoint = getExtensionPointExclude();
+ if (extensionPoint != null){
+ for (IExtension ext : extensionPoint.getExtensions()){
+ for (IConfigurationElement validator : ext.getConfigurationElements()){
+ String id = validator.getAttribute(ExtensionConstants.Exclude.id);
+ Validator v = map.get(id);
+ V2 v2 = null;
+ if (v != null)v2 = v.asV2Validator();
+
+ if (v2 == null){
+ String msg = NLS.bind("Plug-in configuration error, extension {0} references validator id {1} but this id does not exist.", //$NON-NLS-1$
+ extensionPoint.getUniqueIdentifier(), id);
+ CoreException ex = new CoreException(new Status(IStatus.ERROR, ValidationPlugin.PLUGIN_ID, msg));
+ ValidationPlugin.getPlugin().handleException(ex);
+ }
+ else {
+ for (IConfigurationElement exclude : validator.getChildren()){
+ FilterGroup fg = null;
+ try {
+ fg = createFilterGroup(exclude);
+ }
+ catch (Exception e){
+ ValidationPlugin.getPlugin().handleException(e);
+ IContributor contrib = validator.getContributor();
+ String message = NLS.bind(ValMessages.ErrConfig, contrib.getName());
+ ValidationPlugin.getPlugin().logMessage(IStatus.ERROR, message);
+ }
+ if (fg != null && fg.isExclude()){
+ mergeExcludeGroup(v2, fg);
+ }
+ }
+ }
+ }
+ }
+
+ }
+ return map.values();
+
+ }
+
+ /**
+ * Merge the rules from the filter group into the current exclude group, creating a current exclude
+ * group if need be.
+ * @param v2
+ * @param fg
+ */
+ private void mergeExcludeGroup(V2 v2, FilterGroup fg){
+ FilterGroup existing = null;
+ for (FilterGroup group : v2.getGroups()){
+ if (group.isExclude()){
+ existing = group;
+ break;
+ }
+ }
+ if (existing == null)v2.add(fg);
+ else {
+ List<FilterRule> rules = new LinkedList<FilterRule>();
+ for (FilterRule rule : existing.getRules())rules.add(rule);
+
+ for (FilterRule rule : fg.getRules())rules.add(rule);
+
+ FilterRule[] filterRules = new FilterRule[rules.size()];
+ rules.toArray(filterRules);
+ FilterGroup merged = FilterGroup.create(existing.isExclude(), filterRules);
+
+ v2.replaceFilterGroup(existing, merged);
+ }
+ }
+
+ /**
+ * Process the validator element in a validator extension.
+ *
+ * @param validator
+ * The validator element.
+ *
+ * @param deep
+ * If true load all the configuration elements for each
+ * validator, if false do a shallow load, where only the
+ * validator class, id and name's are loaded.
+ *
+ * @param project
+ * The project that you are defined in. This can be null which
+ * means that you are a global validator.
+ *
+ * @return a configured validator or null if there was an error.
+ */
+ private Validator processValidator(IConfigurationElement validator, String id, String label, IProject project) {
+ Validator.V2 v = null;
+ try {
+ v = Validator.create(validator, project).asV2Validator();
+ v.setLevel(Validator.Level.Extension);
+ v.setId(id);
+ v.setName(label);
+ v.setBuildValidation(getAttribute(validator, ExtensionConstants.build, true));
+ v.setManualValidation(getAttribute(validator, ExtensionConstants.manual, true));
+ v.setMarkerId(validator.getAttribute(ExtensionConstants.markerId));
+ v.setVersion(getAttribute(validator, ExtensionConstants.version, 1));
+ v.setSourceId(validator.getAttribute(ExtensionConstants.sourceId));
+ IConfigurationElement[] children = validator.getChildren();
+ for (IConfigurationElement child : children)processIncludeAndExcludeElement(v, child);
+ }
+ catch (Exception e){
+ ValidationPlugin.getPlugin().handleException(e);
+ IContributor contrib = validator.getContributor();
+ String message = NLS.bind(ValMessages.ErrConfig, contrib.getName());
+ ValidationPlugin.getPlugin().logMessage(IStatus.ERROR, message);
+ }
+ return v;
+ }
+
+ /**
+ * Answer all the messages that this validator has defined.
+ * @param v
+ * @return an empty list if the validator did not define any messages.
+ */
+ public List<MessageSeveritySetting> addMessages(Validator v){
+ List<MessageSeveritySetting> list = new LinkedList<MessageSeveritySetting>();
+ IExtensionPoint extensionPoint = getExtensionPoint();
+ if (extensionPoint == null)return list;
+ IExtension ext = extensionPoint.getExtension(v.getId());
+ if (ext == null)return list;
+
+ for (IConfigurationElement elem : ext.getConfigurationElements()){
+ for (IConfigurationElement ce : elem.getChildren(ExtensionConstants.MessageCategory.name)){
+ list.add(processMessage(ce));
+ }
+ }
+
+ return list;
+ }
+
+ /**
+ * Answer the extension point for the v2 validators.
+ *
+ * @return null if there is a problem or no extensions.
+ */
+ private IExtensionPoint getExtensionPoint() {
+ IExtensionRegistry registry = Platform.getExtensionRegistry();
+ return registry.getExtensionPoint(ValidationPlugin.PLUGIN_ID, ExtensionConstants.validator);
+ }
+
+ /**
+ * Answer the extension point for adding exclusion filters. This is where another validator can
+ * further restrict an existing validator.
+ *
+ * @return null if there is a problem or no extensions.
+ */
+ private IExtensionPoint getExtensionPointExclude() {
+ IExtensionRegistry registry = Platform.getExtensionRegistry();
+ return registry.getExtensionPoint(ValidationPlugin.PLUGIN_ID, ExtensionConstants.excludeExtension);
+ }
+
+ /**
+ * Process a message element for the validator, by creating a MessageCategory for it.
+ *
+ * @param ce a MessageCategory element.
+ */
+ private MessageSeveritySetting processMessage(IConfigurationElement ce) {
+ String s = ce.getAttribute(ExtensionConstants.MessageCategory.severity);
+ MessageSeveritySetting.Severity sev = null;
+ if (ExtensionConstants.MessageCategory.sevError.equals(s))sev = MessageSeveritySetting.Severity.Error;
+ else if (ExtensionConstants.MessageCategory.sevWarning.equals(s))sev = MessageSeveritySetting.Severity.Warning;
+ else if (ExtensionConstants.MessageCategory.sevIgnore.equals(s))sev = MessageSeveritySetting.Severity.Ignore;
+
+ return new MessageSeveritySetting(ce.getAttribute(ExtensionConstants.MessageCategory.id),
+ ce.getAttribute(ExtensionConstants.MessageCategory.label), sev);
+ }
+
+ /**
+ * Process the include and exclude elements.
+ *
+ * @param v The validator that we are building up.
+ * @param group The children of the validator tag. This may included include and exclude elements.
+ * Other elements are ignored.
+ */
+ private void processIncludeAndExcludeElement(Validator.V2 v, IConfigurationElement group) {
+ FilterGroup fg = createFilterGroup(group);
+ if (fg != null)v.add(fg);
+ }
+
+ /**
+ * Process an include or exclude element, returning a filter group for it.
+ *
+ * @param group
+ * An include, exclude or some other element. Only include and
+ * exclude elements are processed, other types are ignored.
+ *
+ * @return a filter group that corresponds to the include or exclude
+ * element, or null if the element was not an include or exclude
+ * element.
+ */
+ private FilterGroup createFilterGroup(IConfigurationElement group){
+ String name = group.getName();
+ if (!FilterGroup.isKnownName(name))return null;
+
+
+ IConfigurationElement[] rules = group.getChildren(ExtensionConstants.rules);
+ // there should only be one
+ List<FilterRule> list = new LinkedList<FilterRule>();
+ for (int i=0; i<rules.length; i++){
+ IConfigurationElement[] r = rules[i].getChildren();
+ for(int j=0; j<r.length; j++){
+ list.add(processRule(r[j]));
+ }
+ }
+ FilterRule[] filterRules = new FilterRule[list.size()];
+ list.toArray(filterRules);
+ return FilterGroup.create(name, filterRules);
+ }
+
+ /**
+ * Process a rule in one of the rule groups.
+ *
+ * @param rule a rule in the group, like fileext.
+ */
+ private FilterRule processRule(IConfigurationElement rule) {
+ FilterRule fr = FilterRule.create(rule);
+ if (fr == null){
+ String contributor = ""; //$NON-NLS-1$
+ String name = ""; //$NON-NLS-1$
+ try {
+ contributor = rule.getDeclaringExtension().getContributor().getName();
+ name = rule.getName();
+ }
+ catch (Exception e){
+ // eat it
+ }
+ throw new IllegalStateException(ValMessages.ErrFilterRule + " : " + //$NON-NLS-1$
+ contributor + " : " + name); //$NON-NLS-1$
+ }
+ return fr;
+ }
+
+ /**
+ * Determine if any of the validators need to be migrated, and if so answer a new
+ * Validator array.
+ *
+ * @param validators the existing validators (from the preferences).
+ *
+ * @return null if no validators needed to be migrated.
+ */
+ Validator[] migrate(Validator[] validators, IProject project) {
+ int count = 0;
+ Map<String, Validator> map = new HashMap<String, Validator>(validators.length);
+ for (Validator v : validators)map.put(v.getId(), v);
+
+ IExtensionPoint extensionPoint = getExtensionPoint();
+ if (extensionPoint == null)return null;
+
+ for (IExtension ext : extensionPoint.getExtensions()){
+ for (IConfigurationElement validator : ext.getConfigurationElements()){
+ Validator v = processValidator(validator, ext.getUniqueIdentifier(), ext.getLabel(), project);
+ if (v == null)continue;
+ Validator old = map.get(v.getId());
+ if (old == null || old.getVersion() < v.getVersion()){
+ //TODO we may be replacing user preferences, at some point we may want to do a real migration.
+ map.put(v.getId(), v);
+ count++;
+ }
+ }
+ }
+
+ if (count > 0){
+ Validator[] vals = new Validator[map.size()];
+ map.values().toArray(vals);
+ return vals;
+ }
+ return null;
+ }
+
+ private boolean getAttribute(IConfigurationElement element, String name, boolean dft){
+ String v = element.getAttribute(name);
+ if (v == null)return dft;
+ if ("true".equalsIgnoreCase(v))return true; //$NON-NLS-1$
+ if ("false".equalsIgnoreCase(v))return false; //$NON-NLS-1$
+ return dft;
+ }
+
+ private int getAttribute(IConfigurationElement element, String name, int dft){
+ String v = element.getAttribute(name);
+ if (v == null)return dft;
+ try {
+ return Integer.parseInt(v);
+ }
+ catch (Exception e){
+ // eat it.
+ }
+ return dft;
+ }
+
+// /**
+// * This method is only used for debugging.
+// * @param elem
+// */
+// private static void dump(IConfigurationElement elem){
+// String name = elem.getName();
+// String[] attribs = elem.getAttributeNames();
+// String[] vals = new String[attribs.length];
+// for (int i=0; i<vals.length; i++)vals[i] = elem.getAttribute(attribs[i]);
+// String v = elem.getValue();
+// IConfigurationElement[] children = elem.getChildren();
+// for (int i=0; i<children.length; i++)dump(children[i]);
+// }
+}
diff --git a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/ValidatorGroupExtensionReader.java b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/ValidatorGroupExtensionReader.java
new file mode 100644
index 0000000..62543f7
--- /dev/null
+++ b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/ValidatorGroupExtensionReader.java
@@ -0,0 +1,140 @@
+/*******************************************************************************
+ * Copyright (c) 2008 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.wst.validation.internal;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.eclipse.core.runtime.CoreException;
+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.IStatus;
+import org.eclipse.core.runtime.Platform;
+import org.eclipse.core.runtime.Status;
+import org.eclipse.osgi.util.NLS;
+import org.eclipse.wst.validation.IValidatorGroupListener;
+import org.eclipse.wst.validation.internal.plugin.ValidationPlugin;
+
+/**
+ * Process the validator group (for use with validator version 2 only) extension point.
+ *
+ * @author nitin
+ *
+ */
+public class ValidatorGroupExtensionReader {
+
+ private static final String DOT = "."; //$NON-NLS-1$
+ private static ValidatorGroupExtensionReader _instance;
+
+ public static ValidatorGroupExtensionReader getDefault() {
+ if (_instance == null)_instance = new ValidatorGroupExtensionReader();
+ return _instance;
+ }
+
+ /**
+ * Map of group IDs to configuration elements
+ */
+ private Map<String, List<IConfigurationElement>> _map;
+
+ /**
+ * Map of group ID's to resolved configuration elements.
+ */
+ private Map<String, IValidatorGroupListener[]> _resolved;
+
+ private ValidatorGroupExtensionReader() {
+ init();
+ }
+
+ /**
+ * Answer the listeners with this group id.
+ * @param groupID
+ * @return an empty array there are no listeners for this group id.
+ */
+ IValidatorGroupListener[] createListeners(String groupID) throws CoreException {
+ IValidatorGroupListener[] result = _resolved.get(groupID);
+ if (result != null)return result;
+
+ List<IConfigurationElement> elements = _map.get(groupID);
+ if (elements == null){
+ _resolved.put(groupID, new IValidatorGroupListener[0]);
+ String msg = NLS.bind("Configuration error, there is no validation listener group with id: {0}", groupID); //$NON-NLS-1$
+ Status status = new Status(IStatus.ERROR, ValidationPlugin.PLUGIN_ID, msg);
+ throw new CoreException(status);
+ }
+
+ List<IValidatorGroupListener> listeners = new ArrayList<IValidatorGroupListener>(elements.size());
+ for (IConfigurationElement element : elements) {
+ IValidatorGroupListener listener;
+ try {
+ listener = (IValidatorGroupListener) element.createExecutableExtension(ExtensionConstants.Group.attClass);
+ listeners.add(listener);
+ }
+ catch (Exception e) {
+ ValidationPlugin.getPlugin().handleException(e);
+ listeners = new ArrayList<IValidatorGroupListener>();
+ }
+ }
+
+ result = listeners.toArray(new IValidatorGroupListener[listeners.size()]);
+ _resolved.put(groupID, result);
+ return result;
+ }
+
+ /**
+ * Answer the extension point for the validatorGroups.
+ *
+ * @return null if there is a problem or no extensions.
+ */
+ private IExtensionPoint getExtensionPoint() {
+ IExtensionRegistry registry = Platform.getExtensionRegistry();
+ return registry.getExtensionPoint(ValidationPlugin.PLUGIN_ID, ExtensionConstants.group);
+ }
+
+ private void init() {
+ _map = new HashMap<String, List<IConfigurationElement>>(4);
+ _resolved = new HashMap<String, IValidatorGroupListener[]>(4);
+
+ IExtensionPoint extensionPoint = getExtensionPoint();
+ if (extensionPoint != null) {
+ for (IExtension ext : extensionPoint.getExtensions()) {
+ for (IConfigurationElement group : ext.getConfigurationElements()) {
+ processGroupElement(group);
+ }
+ }
+ }
+ }
+
+ private void processGroupElement(IConfigurationElement element) {
+ if (!ExtensionConstants.Group.elementGroup.equals(element.getName()))return;
+
+ String id = element.getAttribute(ExtensionConstants.Group.attId);
+ if (id == null)throw new IllegalStateException("Configuration error, the " + //$NON-NLS-1$
+ ExtensionConstants.Group.attId + " is required"); //$NON-NLS-1$
+ // force the use of a qualified ID
+ if (id.indexOf(DOT) < 0) {
+ id = element.getContributor().getName() + DOT + id;
+ }
+ IConfigurationElement[] newElements = element.getChildren(ExtensionConstants.Group.elementListener);
+ if (newElements.length > 0) {
+ List<IConfigurationElement> elements = _map.get(id);
+ if (elements == null) {
+ elements = new ArrayList<IConfigurationElement>();
+ _map.put(id, elements);
+ }
+ elements.addAll(Arrays.asList(newElements));
+ }
+ }
+}
diff --git a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/ValidatorMutable.java b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/ValidatorMutable.java
new file mode 100644
index 0000000..d18b0c5
--- /dev/null
+++ b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/ValidatorMutable.java
@@ -0,0 +1,258 @@
+package org.eclipse.wst.validation.internal;
+
+import java.util.HashMap;
+import java.util.Map;
+
+import org.eclipse.core.runtime.IAdaptable;
+import org.eclipse.core.runtime.Platform;
+import org.eclipse.wst.validation.IMutableValidator;
+import org.eclipse.wst.validation.MessageSeveritySetting;
+import org.eclipse.wst.validation.Validator;
+import org.eclipse.wst.validation.Validator.V1;
+import org.eclipse.wst.validation.Validator.V2;
+import org.eclipse.wst.validation.internal.model.FilterGroup;
+
+/**
+ * The mutable fields that a user can change through the preference or property page.
+ * @author karasiuk
+ *
+ */
+public final class ValidatorMutable implements IAdaptable, IMutableValidator {
+
+ private boolean _build;
+ private boolean _manual;
+ private String _delegatingId;
+
+ private int _changeCountGroups;
+ private int _changeCountMessages;
+
+ private final String _name;
+ private final String _sourceId;
+ private final boolean _isV1;
+ private final boolean _isV2;
+ private final ValidatorMetaData _vmd;
+ private final String _id;
+ private final int _version;
+
+ private FilterGroup[] _groups;
+ private final Map<String, MessageSeveritySetting> _messageSettings;
+ private final String _validatorClassname;
+
+ private final boolean _origBuild;
+ private final boolean _origManual;
+ private final String _origDelegating;
+
+ public ValidatorMutable(Validator validator) {
+ _name = validator.getName();
+ _sourceId = validator.getSourceId();
+ _manual = validator.isManualValidation();
+ _build = validator.isBuildValidation();
+ V2 v2 = validator.asV2Validator();
+ _isV2 = v2 != null;
+ _delegatingId = validator.getDelegatingId();
+
+ V1 v1 = validator.asV1Validator();
+ _isV1 = v1 != null;
+ _vmd = _isV1 ? v1.getVmd() : null;
+ _id = validator.getId();
+
+ _origBuild = _build;
+ _origDelegating = _delegatingId;
+ _origManual = _manual;
+ _version = validator.getVersion();
+ _validatorClassname = validator.getValidatorClassname();
+ _messageSettings = new HashMap<String, MessageSeveritySetting>(10);
+ for (Map.Entry<String, MessageSeveritySetting> me : validator.getMessageSettings().entrySet()){
+ _messageSettings.put(me.getKey(), me.getValue().copy());
+ }
+
+ if (v2 != null){
+ FilterGroup[] groups = v2.getGroups();
+ _groups = new FilterGroup[groups.length];
+ System.arraycopy(groups, 0, _groups, 0, groups.length);
+ }
+ }
+
+ public ValidatorMutable(ValidatorMutable val) {
+ _build = val._build;
+ _delegatingId = val._delegatingId;
+ FilterGroup[] groups = val.getGroups();
+ _groups = new FilterGroup[groups.length];
+ System.arraycopy(groups, 0, _groups, 0, groups.length);
+
+ _id = val._id;
+ _isV1 = val._isV1;
+ _isV2 = val._isV2;
+ _manual = val._manual;
+ _messageSettings = new HashMap<String, MessageSeveritySetting>(10);
+ for (Map.Entry<String, MessageSeveritySetting> me : val.getMessageSettings().entrySet()){
+ _messageSettings.put(me.getKey(), me.getValue().copy());
+ }
+
+ _name = val._name;
+ _origBuild = val._origBuild;
+ _origDelegating = val._origDelegating;
+ _origManual = val._origManual;
+ _sourceId = val._sourceId;
+ _validatorClassname = val._validatorClassname;
+ _version = val._version;
+ _vmd = val._vmd;
+ }
+
+ public void setBuildValidation(boolean build) {
+ _build = build;
+ }
+
+ public void setManualValidation(boolean manual) {
+ _manual = manual;
+ }
+
+ public String getName() {
+ return _name;
+ }
+
+ public boolean isManualValidation() {
+ return _manual;
+ }
+
+ public boolean isBuildValidation() {
+ return _build;
+ }
+
+ public boolean isV2Validator() {
+ return _isV2;
+ }
+
+ public String getDelegatingId() {
+ return _delegatingId;
+ }
+
+ /**
+ * The caller of this method must not change the ValidatorMetaData.
+ */
+ public ValidatorMetaData getVmd() {
+ return _vmd;
+ }
+
+ public boolean isV1Validator() {
+ return _isV1;
+ }
+
+ public String getId() {
+ return _id;
+ }
+
+ /**
+ * Answer true if any of your settings have changed.
+ */
+ public boolean isChanged() {
+ if (hasGlobalChanges())return true;
+ if (_changeCountGroups > 0 || _changeCountMessages > 0)return true;
+ return false;
+ }
+
+ public boolean hasGlobalChanges() {
+ if (_origBuild != _build)return true;
+ if (_origManual != _manual)return true;
+ if (!Misc.same(_origDelegating, _delegatingId))return true;
+ return false;
+ }
+
+ public int getVersion() {
+ return _version;
+ }
+
+ public void replaceFilterGroup(FilterGroup existing, FilterGroup merged) {
+ int i = find(existing);
+ if (i == -1)add(merged); // this should never happen
+ else {
+ _groups[i] = merged;
+ bumpChangeCountGroups();
+ }
+ }
+
+ public void remove(FilterGroup group) {
+ int i = find(group);
+ if (i == -1)return;
+
+ FilterGroup[] groups = new FilterGroup[_groups.length-1];
+ if (i > 0)System.arraycopy(_groups, 0, groups, 0, i);
+ if (i < groups.length)System.arraycopy(_groups, i+1, groups, i, groups.length-i);
+ _groups = groups;
+ bumpChangeCountGroups();
+ }
+
+ private int find(FilterGroup group) {
+ for (int i=0; i<_groups.length; i++)if (group == _groups[i])return i;
+ return -1;
+ }
+
+ public void add(FilterGroup fg) {
+ assert fg != null;
+ FilterGroup[] groups = new FilterGroup[_groups.length+1];
+ System.arraycopy(_groups, 0, groups, 0, _groups.length);
+ groups[_groups.length] = fg;
+ _groups = groups;
+ bumpChangeCountGroups();
+ }
+
+ private void bumpChangeCountGroups(){
+ _changeCountGroups++;
+ }
+
+ public int getChangeCountGroups() {
+ return _changeCountGroups;
+ }
+
+ public FilterGroup[] getGroups(){
+ return _groups;
+ }
+
+ public void setDelegatingId(String id) {
+ _delegatingId = id;
+ }
+
+ public Map<String, MessageSeveritySetting> getMessageSettings() {
+ return _messageSettings;
+ }
+
+ public void bumpChangeCountMessages(){
+ _changeCountMessages++;
+ }
+
+ public String getValidatorClassname() {
+ return _validatorClassname;
+ }
+
+ @SuppressWarnings("unchecked")
+ public Object getAdapter(Class adapter) {
+ return Platform.getAdapterManager().getAdapter(this, adapter);
+ }
+
+ public boolean sameConfig(Validator validator) {
+ if (validator == null)return false;
+ return hashCodeForConfig() == validator.hashCodeForConfig();
+ }
+
+ private int hashCodeForConfig() {
+ int h = 0;
+ if (_build)h += 101;
+ if (_delegatingId != null)h += _delegatingId.hashCode();
+ if (_manual)h += 201;
+ if (_messageSettings != null){
+ for (MessageSeveritySetting ms : _messageSettings.values())h += ms.hashCode();
+ }
+ if (_sourceId != null)h += _sourceId.hashCode();
+ h += _version;
+ if (_id != null)h += _id.hashCode();
+ for (FilterGroup fg : _groups)h += fg.hashCodeForConfig();
+ return h;
+ }
+
+ @Override
+ public String toString() {
+ return _name;
+ }
+
+
+}
diff --git a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/model/FilterGroup.java b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/model/FilterGroup.java
new file mode 100644
index 0000000..6d20dd5
--- /dev/null
+++ b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/model/FilterGroup.java
@@ -0,0 +1,253 @@
+/*******************************************************************************
+ * Copyright (c) 2005, 2009 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.wst.validation.internal.model;
+
+import java.util.LinkedList;
+import java.util.List;
+
+import org.eclipse.core.resources.IProject;
+import org.eclipse.core.resources.IResource;
+import org.eclipse.core.runtime.IAdaptable;
+import org.eclipse.core.runtime.Platform;
+import org.eclipse.wst.validation.internal.ContentTypeWrapper;
+import org.eclipse.wst.validation.internal.Deserializer;
+import org.eclipse.wst.validation.internal.ExtensionConstants;
+import org.eclipse.wst.validation.internal.Serializer;
+import org.eclipse.wst.validation.internal.ValMessages;
+
+/**
+ * An immutable group of filter rules.
+ * @author karasiuk
+ *
+ */
+public abstract class FilterGroup implements IAdaptable {
+
+ private final FilterRule[] _rules;
+
+ /** The version number of the serialization (in case we ever need to change this) */
+ private static final int SerializationVersion = 1;
+
+ /**
+ * Answer a filter group based on the type of the group.
+ *
+ * @param name either "include" or "exclude"
+ *
+ * @return null if the name parameter isn't correct.
+ */
+ public static FilterGroup create(String name, FilterRule[] rules) {
+ if (ExtensionConstants.include.equals(name))return new FilterIncludeGroup(rules);
+ if (ExtensionConstants.exclude.equals(name))return new FilterExcludeGroup(rules);
+ return null;
+ }
+
+ /**
+ * Answer a filter group from a deserializer.
+ * @param des
+ *
+ * @see FilterGroup#save(Serializer)
+ */
+ public static FilterGroup create(Deserializer des){
+ des.getInt(); // get the version
+ String type = des.getString();
+
+ int numberRules = des.getInt();
+ List<FilterRule> list = new LinkedList<FilterRule>();
+ for (int i=0; i<numberRules; i++)list.add(FilterRule.create(des));
+ FilterRule[] rules = new FilterRule[list.size()];
+ list.toArray(rules);
+
+ return create(type, rules);
+ }
+
+ /**
+ * Answer a new filter group.
+ *
+ * @param exclude if true an exclusion group is returned, otherwise an inclusion group is returned.
+ */
+ public static FilterGroup create(boolean exclude, FilterRule[] rules){
+ if (exclude) return new FilterExcludeGroup(rules);
+ return new FilterIncludeGroup(rules);
+ }
+
+ /**
+ * Answer true if this is a supported type of group.
+ * @param name Type of group that is being tested.
+ * @return
+ */
+ public static boolean isKnownName(String name) {
+ if (ExtensionConstants.include.equals(name))return true;
+ if (ExtensionConstants.exclude.equals(name))return true;
+ return false;
+ }
+
+
+ private FilterGroup(FilterRule[] rules){
+ _rules = rules;
+ }
+
+ /**
+ * The rules in the group.
+ */
+ public final FilterRule[] getRules(){
+ FilterRule[] rules = new FilterRule[_rules.length];
+ System.arraycopy(_rules, 0, rules, 0, _rules.length);
+ return rules;
+ }
+
+ /**
+ * Answer the internal type of group, e.g. "include" or "exclude".
+ */
+ public abstract String getType();
+
+ /** Answer the type as a type that can be displayed to a user, that is it has been localized. */
+ public abstract String getDisplayableType();
+
+ @SuppressWarnings("unchecked")
+ public Object getAdapter(Class adapter) {
+ return Platform.getAdapterManager().getAdapter(this, adapter);
+ }
+
+ public static final class FilterIncludeGroup extends FilterGroup {
+
+ private FilterIncludeGroup(FilterRule[] rules){
+ super(rules);
+ }
+
+ public String getType() {
+ return ExtensionConstants.include;
+ }
+
+ public String getDisplayableType() {
+ return ValMessages.GroupInclude;
+ }
+
+ public boolean isInclude() {
+ return true;
+ }
+
+ }
+
+
+ public static final class FilterExcludeGroup extends FilterGroup {
+
+ private FilterExcludeGroup(FilterRule[] rules){
+ super(rules);
+ }
+ public String getType() {
+ return ExtensionConstants.exclude;
+ }
+
+ public String getDisplayableType() {
+ return ValMessages.GroupExclude;
+ }
+
+ public boolean isExclude() {
+ return true;
+ }
+ }
+
+ /**
+ * Save your settings into the serializer.
+ * @param ser
+ */
+ public void save(Serializer ser){
+ ser.put(SerializationVersion);
+ ser.put(getType());
+ ser.put(_rules.length);
+ for (FilterRule rule : _rules)rule.save(ser);
+ }
+
+ /**
+ * Answer whether or not we should validate the resource based on the filters in this group.
+ *
+ * @param project the project that is being validated.
+ * @param resource the resource that is being validated. This can be null, in which case
+ * only the project level checks are performed.
+ */
+ public boolean shouldValidate(IProject project, IResource resource, ContentTypeWrapper contentTypeWrapper) {
+ boolean exclude = isExclude();
+ boolean include = isInclude();
+ int count = 0;
+ for (FilterRule rule : _rules){
+ if (resource != null){
+ Boolean match = rule.matchesResource(resource, contentTypeWrapper);
+ if (match != null)count++;
+ if (exclude && match != null && match)return false;
+ if (include && match != null && match)return true;
+ }
+
+ Boolean match = rule.matchesProject(project);
+ if (match != null)count++;
+ if (exclude && match != null && match)return false;
+ if (include && match != null && match)return true;
+ }
+ if (exclude)return true;
+ if (count == 0)return true;
+ return false;
+ }
+
+ /**
+ * Answer true if this is an inclusion filter, that is at least one of the rules must
+ * match in order to validate the resource.
+ */
+ public boolean isInclude() {
+ return false;
+ }
+
+ /**
+ * Answer true if this is an exclusion filter, that is if any of the rules match the
+ * resource is not validated.
+ */
+ public boolean isExclude() {
+ return false;
+ }
+
+ public int hashCodeForConfig() {
+ int h = 0;
+ if (isExclude())h += 13;
+ for (FilterRule fr : _rules)h += fr.hashCodeForConfig();
+ return h;
+ }
+
+ /**
+ * Create a new group by adding a rule to an existing group.
+ * @param baseGroup The group that holds the existing rules.
+ * @param rule The new rule that is being added
+ * @return
+ */
+ public static FilterGroup addRule(FilterGroup baseGroup, FilterRule rule) {
+ List<FilterRule> list = new LinkedList<FilterRule>();
+ for (FilterRule r : baseGroup._rules)list.add(r);
+ list.add(rule);
+
+ FilterRule[] rules = new FilterRule[list.size()];
+ list.toArray(rules);
+ return FilterGroup.create(baseGroup.isExclude(), rules);
+ }
+
+ /**
+ * Create a new group by removing a rule from an existing group.
+ * @param baseGroup The group that holds the existing rules.
+ * @param rule The rule that is being removed
+ * @return
+ */
+ public static FilterGroup removeRule(FilterGroup baseGroup, FilterRule rule) {
+ List<FilterRule> list = new LinkedList<FilterRule>();
+ for (FilterRule r : baseGroup._rules){
+ if (!r.equals(rule))list.add(r);
+ }
+
+ FilterRule[] rules = new FilterRule[list.size()];
+ list.toArray(rules);
+ return FilterGroup.create(baseGroup.isExclude(), rules);
+ }
+
+}
diff --git a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/model/FilterRule.java b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/model/FilterRule.java
new file mode 100644
index 0000000..04cf0c2
--- /dev/null
+++ b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/model/FilterRule.java
@@ -0,0 +1,536 @@
+/*******************************************************************************
+ * Copyright (c) 2007, 2009 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.wst.validation.internal.model;
+
+import java.util.regex.Pattern;
+
+import org.eclipse.core.resources.IFile;
+import org.eclipse.core.resources.IProject;
+import org.eclipse.core.resources.IResource;
+import org.eclipse.core.runtime.CoreException;
+import org.eclipse.core.runtime.IAdaptable;
+import org.eclipse.core.runtime.IConfigurationElement;
+import org.eclipse.core.runtime.Platform;
+import org.eclipse.core.runtime.content.IContentType;
+import org.eclipse.osgi.util.NLS;
+import org.eclipse.wst.common.project.facet.core.FacetedProjectFramework;
+import org.eclipse.wst.validation.internal.ContentTypeWrapper;
+import org.eclipse.wst.validation.internal.Deserializer;
+import org.eclipse.wst.validation.internal.ExtensionConstants;
+import org.eclipse.wst.validation.internal.Serializer;
+import org.eclipse.wst.validation.internal.Tracing;
+import org.eclipse.wst.validation.internal.ValMessages;
+import org.eclipse.wst.validation.internal.plugin.ValidationPlugin;
+
+/**
+ * A rule that is used to filter out (or in) validation on a resource.
+ * The concrete classes are all immutable.
+ * @author karasiuk
+ *
+ */
+public abstract class FilterRule implements IAdaptable {
+
+ protected final String _pattern;
+
+ protected static final String PortableFileDelim = "/"; //$NON-NLS-1$
+
+ /**
+ * Create a rule based on a configuration element.
+ *
+ * @param rule
+ * The configuration element, see the extension point for details.
+ * @return null if there is a problem.
+ */
+ public static FilterRule create(IConfigurationElement rule){
+ String name = rule.getName();
+ if (ExtensionConstants.Rule.fileext.equals(name))return new FileExt(rule);
+ if (ExtensionConstants.Rule.projectNature.equals(name))return new ProjectNature(rule);
+ if (ExtensionConstants.Rule.file.equals(name))return File.createFile(rule);
+ if (ExtensionConstants.Rule.contentType.equals(name))return ContentType.createContentType(rule);
+ if (ExtensionConstants.Rule.facet.equals(name))return new Facet(rule);
+ if (ExtensionConstants.Rule.pattern.equals(name))return FilePattern.createFilePattern(rule);
+ return null;
+ }
+
+ static FilterRule create(Deserializer des) {
+ String type = des.getString();
+ if (ExtensionConstants.Rule.fileext.equals(type)){
+ String pattern = des.getString();
+ boolean caseSensitive = des.getBoolean();
+ return new FileExt(pattern, caseSensitive);
+ }
+
+ if (ExtensionConstants.Rule.projectNature.equals(type)){
+ String pattern = des.getString();
+ return new ProjectNature(pattern);
+ }
+
+ if (ExtensionConstants.Rule.file.equals(type)){
+ String pattern = des.getString();
+ boolean caseSensitive = des.getBoolean();
+ int fileType = des.getInt();
+ return new File(pattern, caseSensitive, fileType);
+ }
+
+ if (ExtensionConstants.Rule.contentType.equals(type)){
+ String pattern = des.getString();
+ boolean exactMatch = des.getBoolean();
+ return new ContentType(pattern, exactMatch);
+ }
+
+ if (ExtensionConstants.Rule.facet.equals(type)){
+ String pattern = des.getString();
+ return new Facet(pattern, null);
+ }
+
+ if (ExtensionConstants.Rule.pattern.equals(type)){
+ String pattern = des.getString();
+ boolean caseSensitive = des.getBoolean();
+ return new FilePattern(pattern, caseSensitive);
+ }
+ return null;
+ }
+
+
+ public static FilterRule createFile(String pattern, boolean caseSensitive, int type){
+ return new File(pattern, caseSensitive, type);
+ }
+
+ public static FilterRule createFileExt(String pattern, boolean caseSensitive){
+ FileExt ext = new FileExt(pattern, caseSensitive);
+ return ext;
+ }
+
+ public static FilterRule createFacet(String facetId){
+ return new Facet(facetId, null);
+ }
+
+ public static FilterRule createProject(String projectNature){
+ return new ProjectNature(projectNature);
+ }
+
+ public static FilterRule createContentType(String contentType, boolean exactMatch){
+ return new ContentType(contentType, exactMatch);
+ }
+
+ protected FilterRule(String pattern){
+ _pattern = pattern;
+ }
+
+ /**
+ * Answer true if the rule matches the resource, false if it doesn't, and
+ * null if the rule does not apply to resources.
+ *
+ * @param resource the resource that is being validated.
+ */
+ public Boolean matchesResource(IResource resource, ContentTypeWrapper contentTypeWrapper){
+ return null;
+ }
+
+ /**
+ * Answer true if the rule matches the project, false if it doesn't, and null if the
+ * rule does not apply.
+ *
+ * @param project the project that is being validated.
+ */
+ public Boolean matchesProject(IProject project){
+ return null;
+ }
+
+ public String toString() {
+ return getDisplayableType() + ": " + _pattern; //$NON-NLS-1$
+ }
+
+ /** Answer a name of the rule, that can be displayed to a user. */
+ public String getName(){
+ return toString();
+ }
+
+ public String getPattern(){
+ return _pattern;
+ }
+
+ /** Answer the type of rule. */
+ public abstract String getType();
+
+ /** Answer a type that can be displayed to an end user. */
+ public abstract String getDisplayableType();
+
+ public static boolean asBoolean(String value, boolean aDefault){
+ if (value == null)return aDefault;
+ if (value.equals(ExtensionConstants.True))return true;
+ if (value.equals(ExtensionConstants.False))return false;
+ return aDefault;
+ }
+
+ @SuppressWarnings("unchecked")
+ public Object getAdapter(Class adapter) {
+ return Platform.getAdapterManager().getAdapter(this, adapter);
+ }
+
+ public static abstract class FilterRuleCaseSensitive extends FilterRule {
+
+ public FilterRuleCaseSensitive(String pattern, boolean caseSensitive) {
+ super(pattern);
+ _caseSensitive = caseSensitive;
+ }
+
+ private final boolean _caseSensitive;
+
+ @Override
+ public int hashCodeForConfig() {
+ int h = super.hashCodeForConfig();
+ if (_caseSensitive)h += 401;
+ return h;
+ }
+
+ @Override
+ public void save(Serializer ser) {
+ super.save(ser);
+ ser.put(_caseSensitive);
+ }
+
+ public boolean isCaseSensitive() {
+ return _caseSensitive;
+ }
+
+ }
+
+ public static final class ProjectNature extends FilterRule {
+
+ private ProjectNature(IConfigurationElement rule) {
+ super(rule.getAttribute(ExtensionConstants.RuleAttrib.id));
+
+ }
+
+ public ProjectNature(String projectNature) {
+ super(projectNature);
+ }
+
+ public String getDisplayableType() {
+ return ValMessages.RuleProjectNature;
+ }
+
+ public String getType() {
+ return ExtensionConstants.Rule.projectNature;
+ }
+
+ public Boolean matchesProject(IProject project) {
+ try {
+ return project.hasNature(_pattern);
+ }
+ catch (CoreException e){
+ }
+ return Boolean.FALSE;
+ }
+
+ }
+
+ public static final class FileExt extends FilterRuleCaseSensitive {
+
+ private FileExt(IConfigurationElement rule){
+ super(rule.getAttribute(ExtensionConstants.RuleAttrib.ext),
+ asBoolean(rule.getAttribute(ExtensionConstants.RuleAttrib.caseSensitive), false));
+ }
+
+ private FileExt(String pattern, boolean caseSensitive) {
+ super(pattern, caseSensitive);
+ }
+
+ public String getType() {
+ return ExtensionConstants.Rule.fileext;
+ }
+
+ public String getDisplayableType() {
+ return ValMessages.RuleFileExt;
+ }
+
+ public String getName() {
+ return toString();
+ }
+
+ public String toString() {
+ if (isCaseSensitive())return NLS.bind(ValMessages.FileExtWithCase, getDisplayableType(), _pattern);
+ return NLS.bind(ValMessages.FileExtWithoutCase, getDisplayableType(), _pattern);
+ }
+
+ public Boolean matchesResource(IResource resource, ContentTypeWrapper contentTypeWrapper) {
+ String ext = resource.getFileExtension();
+ if (isCaseSensitive())return _pattern.equals(ext);
+ return _pattern.equalsIgnoreCase(ext);
+ }
+ }
+
+ /**
+ * A rule that is used to filter based on file or folder names.
+ * @author karasiuk
+ *
+ */
+ public static final class File extends FilterRuleCaseSensitive {
+
+ private final String _patternAsLowercase;
+
+ /** One of the FileTypeXX constants. */
+ private final int _type;
+
+ public static final int FileTypeFile = 1;
+ public static final int FileTypeFolder = 2;
+ public static final int FileTypeFull = 3;
+
+ private static File createFile(IConfigurationElement rule){
+ String pattern = rule.getAttribute(ExtensionConstants.RuleAttrib.name);
+ if (pattern == null)throw new IllegalStateException(ValMessages.ErrPatternAttrib);
+ String type = rule.getAttribute(ExtensionConstants.RuleAttrib.fileType);
+ if (type == null)throw new IllegalStateException(ValMessages.ErrTypeReq);
+
+ int myType = -1;
+ if (ExtensionConstants.FileType.file.equals(type))myType = FileTypeFile;
+ else if (ExtensionConstants.FileType.folder.equals(type)){
+ myType = FileTypeFolder;
+ if (!pattern.endsWith(PortableFileDelim))pattern += PortableFileDelim;
+ }
+ else if (ExtensionConstants.FileType.full.equals(type))myType = FileTypeFull;
+ else {
+ Object[] parms = {type, ExtensionConstants.FileType.file, ExtensionConstants.FileType.folder,
+ ExtensionConstants.FileType.full};
+ throw new IllegalStateException(NLS.bind(ValMessages.ErrType, parms));
+ }
+ boolean caseSensitive = asBoolean(rule.getAttribute(ExtensionConstants.RuleAttrib.caseSensitive), false);
+ return new File(pattern, caseSensitive, myType);
+ }
+
+ private File(String pattern, boolean caseSensitive, int type){
+ super(pattern, caseSensitive);
+ _type = type;
+ _patternAsLowercase = pattern == null ? null : pattern.toLowerCase();
+ }
+
+ public String getType() {
+ return ExtensionConstants.Rule.file;
+ }
+
+ public String getDisplayableType() {
+ if (_type == FileTypeFolder)return ValMessages.RuleFolder;
+ if (_type == FileTypeFull)return ValMessages.RuleFull;
+ return ValMessages.RuleFile;
+ }
+
+ public void setData(IConfigurationElement rule) {
+ }
+
+ public String toString() {
+ if (isCaseSensitive())return NLS.bind(ValMessages.FileExtWithCase, getDisplayableType(), _pattern);
+ return NLS.bind(ValMessages.FileExtWithoutCase, getDisplayableType(), _pattern);
+ }
+
+ public Boolean matchesResource(IResource resource, ContentTypeWrapper contentTypeWrapper) {
+ String name = null;
+ switch (_type){
+ case FileTypeFile:
+ name = resource.getName();
+ break;
+
+ case FileTypeFolder:
+ name = resource.getProjectRelativePath().removeLastSegments(1).toString() + PortableFileDelim;
+ break;
+
+ case FileTypeFull:
+ name = resource.getProjectRelativePath().toPortableString();
+ break;
+ }
+
+ if (name == null)return Boolean.FALSE;
+ if (isCaseSensitive())return name.startsWith(_pattern);
+ return name.toLowerCase().startsWith(_patternAsLowercase);
+ }
+
+ @Override
+ public void save(Serializer ser) {
+ super.save(ser);
+ ser.put(_type);
+ }
+
+ }
+
+ public static final class Facet extends FilterRule {
+
+ private final String _versionExpression;
+
+ private Facet(IConfigurationElement rule){
+ super(rule.getAttribute(ExtensionConstants.RuleAttrib.id));
+ _versionExpression = rule.getAttribute(ExtensionConstants.RuleAttrib.version);
+
+ }
+
+ public Facet(String facetId, String versionExpression) {
+ super(facetId);
+ _versionExpression = versionExpression;
+ }
+
+ public String getType() {
+ return ExtensionConstants.Rule.facet;
+ }
+
+ public String getDisplayableType() {
+ return ValMessages.RuleFacet;
+ }
+
+ @Override
+ public Boolean matchesProject(IProject project) {
+ try {
+ if (_versionExpression == null)return FacetedProjectFramework.hasProjectFacet(project, _pattern);
+ return FacetedProjectFramework.hasProjectFacet(project, _pattern, _versionExpression);
+ }
+ catch (CoreException e){
+ if (Tracing.isLogging())ValidationPlugin.getPlugin().handleException(e);
+ }
+ return Boolean.FALSE;
+ }
+
+ @Override
+ public String toString() {
+ StringBuffer b = new StringBuffer(200);
+ b.append(getDisplayableType());
+ b.append(": "); //$NON-NLS-1$
+ b.append(_pattern);
+
+ if (_versionExpression != null){
+ b.append(" ("); //$NON-NLS-1$
+ b.append(_versionExpression);
+ b.append(")"); //$NON-NLS-1$
+ }
+ return b.toString();
+ }
+
+ }
+
+ public static final class ContentType extends FilterRule {
+
+ private final IContentType _type;
+ private final boolean _exactMatch;
+
+ private ContentType(String pattern, boolean exactMatch){
+ super(pattern);
+ _type = Platform.getContentTypeManager().getContentType(pattern);
+ _exactMatch = exactMatch;
+ }
+
+ private static ContentType createContentType(IConfigurationElement rule){
+ String pattern = rule.getAttribute(ExtensionConstants.RuleAttrib.id);
+ boolean exactMatch = true;
+ String exact = rule.getAttribute(ExtensionConstants.RuleAttrib.exactMatch);
+ if (ExtensionConstants.False.equals(exact)) exactMatch = false;
+
+ return new ContentType(pattern, exactMatch);
+ }
+
+ public String getType() {
+ return ExtensionConstants.Rule.contentType;
+ }
+
+ @Override
+ public int hashCodeForConfig() {
+ int h = super.hashCodeForConfig();
+ if (_exactMatch)h += 301;
+ return h;
+ }
+
+ public String getDisplayableType() {
+ return ValMessages.RuleContentType;
+ }
+
+ @Override
+ public void save(Serializer ser) {
+ super.save(ser);
+ ser.put(_exactMatch);
+ }
+
+ public void setData(IConfigurationElement rule) {
+ }
+
+ public Boolean matchesResource(IResource resource, ContentTypeWrapper contentTypeWrapper) {
+ if (_type == null)return Boolean.FALSE;
+ if (resource instanceof IFile) {
+ IFile file = (IFile) resource;
+ IContentType ct = contentTypeWrapper.getContentType(file);
+ if (ct == null)return Boolean.FALSE;
+ boolean match = false;
+ if (_exactMatch)match = ct.getId().equals(_type.getId());
+ else match = ct.isKindOf(_type);
+
+ if (match && Tracing.isTraceMatches())
+ Tracing.log("FilterRule-01: ", toString() + " has matched " + resource); //$NON-NLS-1$ //$NON-NLS-2$
+ return match;
+ }
+ return Boolean.FALSE;
+ }
+
+ @Override
+ public String toString() {
+ if (_exactMatch)return NLS.bind(ValMessages.ContentTypeExact, getDisplayableType(), _pattern);
+ return NLS.bind(ValMessages.ContentTypeNotExact, getDisplayableType(), _pattern);
+ }
+
+ }
+
+ public static final class FilePattern extends FilterRuleCaseSensitive {
+
+ private final Pattern _compiledPattern;
+
+ private static FilePattern createFilePattern(IConfigurationElement rule){
+ String pattern = rule.getAttribute(ExtensionConstants.RuleAttrib.regex);
+ boolean caseSensitive = asBoolean(rule.getAttribute(ExtensionConstants.RuleAttrib.caseSensitive), false);
+ return new FilePattern(pattern, caseSensitive);
+ }
+
+ private FilePattern(String pattern, boolean caseSensitive){
+ super(pattern, caseSensitive);
+ int flags = 0;
+ if (caseSensitive)flags = Pattern.CASE_INSENSITIVE;
+ Pattern compiledPattern = Pattern.compile(pattern, flags);
+ _compiledPattern = compiledPattern;
+ }
+
+ @Override
+ public String getDisplayableType() {
+ // FIXME this should be replaced as soon as we are allowed to change the UI.
+ return ValMessages.RuleFile;
+ }
+
+ @Override
+ public String getType() {
+ return ExtensionConstants.Rule.pattern;
+ }
+
+ @Override
+ public Boolean matchesResource(IResource resource, ContentTypeWrapper wrapper) {
+ String name = PortableFileDelim + resource.getProjectRelativePath().toPortableString();
+ if (name == null)return Boolean.FALSE;
+ return _compiledPattern.matcher(name).matches();
+ }
+ }
+
+ /**
+ * Save your settings into the serializer.
+ * @param ser
+ */
+ public void save(Serializer ser) {
+ ser.put(getType());
+ ser.put(getPattern());
+ }
+
+ public int hashCodeForConfig() {
+ int h = getType().hashCode();
+ if (_pattern != null)h += _pattern.hashCode();
+ return h;
+ }
+
+}
diff --git a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/model/GlobalPreferences.java b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/model/GlobalPreferences.java
new file mode 100644
index 0000000..2989c2c
--- /dev/null
+++ b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/model/GlobalPreferences.java
@@ -0,0 +1,133 @@
+/*******************************************************************************
+ * Copyright (c) 2007, 2009 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.wst.validation.internal.model;
+
+/**
+ * This class represents the global Preferences as set on the Validation Preferences page. It doesn't
+ * hold any of the individual validator settings, just the global check boxes. It is an immutable object.
+ */
+public final class GlobalPreferences {
+
+ /** false - Default setting for the should all the validation be suspended setting. */
+ public static final boolean DefaultSuspend = false;
+
+ /** false - Default setting for the auto save setting. */
+ public static final boolean DefaultAutoSave = false;
+
+ /** false - Default setting for the confirm dialog setting. */
+ public static final boolean DefaultConfirm = true;
+
+ /** false - Default setting for letting projects override the global settings. */
+ public static final boolean DefaultOverride = true;
+
+ /** 2 - The version of the framework meta data, if an explicit version isn't found. */
+ public static final int DefaultFrameworkVersion = 2;
+
+ /** Bit masks for what has changed. */
+ public final static int ConfirmDialogMask = 1;
+ public final static int DisableAllValidationMask = 2;
+ public final static int OverrideMask = 4;
+ public final static int SaveAutomaticallyMask = 8;
+ public final static int StateTimeStampMask = 16;
+ public final static int VersionMask = 32;
+
+ /**
+ * The changes that could affect what gets validated.
+ */
+ public final static int BuildChangeMask = DisableAllValidationMask | OverrideMask;
+
+
+ private final boolean _confirmDialog;
+ private final boolean _disableAllValidation;
+ private final boolean _override;
+ private final boolean _saveAutomatically;
+
+ /** The plug-in state time stamp. */
+ private final long _stateTimeStamp;
+
+ /** The incoming version of the framework. This is used to determine if a migration is needed.*/
+ private final int _version;
+
+ /**
+ * The only valid way to get the global preferences is through the ValManager.
+ *
+ * @see org.eclipse.wst.validation.internal.ValManager#getGlobalPreferences()
+ */
+ public GlobalPreferences(GlobalPreferencesValues gp) {
+ _confirmDialog = gp.confirmDialog;
+ _disableAllValidation = gp.disableAllValidation;
+ _override = gp.override;
+ _saveAutomatically = gp.saveAutomatically;
+ _stateTimeStamp = gp.stateTimeStamp;
+ _version = gp.version;
+ }
+
+ /**
+ * Answer a copy of the values.
+ * @return
+ */
+ public GlobalPreferencesValues asValues(){
+ GlobalPreferencesValues gp = new GlobalPreferencesValues();
+ gp.confirmDialog = _confirmDialog;
+ gp.disableAllValidation = _disableAllValidation;
+ gp.override = _override;
+ gp.saveAutomatically = _saveAutomatically;
+ gp.stateTimeStamp = _stateTimeStamp;
+ gp.version = _version;
+ return gp;
+ }
+
+ public boolean getSaveAutomatically() {
+ return _saveAutomatically;
+ }
+
+
+ /**
+ * Answer if all validation has been disabled.
+ */
+ public boolean getDisableAllValidation() {
+ return _disableAllValidation;
+ }
+
+ public boolean getConfirmDialog() {
+ return _confirmDialog;
+ }
+
+ public long getStateTimeStamp() {
+ return _stateTimeStamp;
+ }
+
+ /** Answer whether or not projects are allowed to override the global preferences. */
+ public boolean getOverride() {
+ return _override;
+ }
+
+ public int getVersion() {
+ return _version;
+ }
+
+ /**
+ * Compare yourself to the other global preferences and answer a bitmask with the differences.
+ * @param gp
+ * @return bit mask of the changes. See the xxxMask constants for the values of the bits. A zero means that they are the same.
+ */
+ public int compare(GlobalPreferences gp) {
+ int changes = 0;
+ if (_confirmDialog != gp.getConfirmDialog())changes |= ConfirmDialogMask;
+ if (_disableAllValidation != gp.getDisableAllValidation())changes |= DisableAllValidationMask;
+ if (_override != gp.getOverride())changes |= OverrideMask;
+ if (_saveAutomatically != gp.getSaveAutomatically())changes |= SaveAutomaticallyMask;
+ if (_stateTimeStamp != gp.getStateTimeStamp())changes |= StateTimeStampMask;
+ if (_version != gp.getVersion())changes |= VersionMask;
+ return changes;
+ }
+
+}
diff --git a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/model/GlobalPreferencesValues.java b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/model/GlobalPreferencesValues.java
new file mode 100644
index 0000000..cdf8345
--- /dev/null
+++ b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/model/GlobalPreferencesValues.java
@@ -0,0 +1,35 @@
+/*******************************************************************************
+ * Copyright (c) 2009 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+
+package org.eclipse.wst.validation.internal.model;
+
+/**
+ * A mutable object that is used to initialize a GlobalPreference.
+ * @author karasiuk
+ *
+ */
+public class GlobalPreferencesValues {
+ public boolean disableAllValidation = GlobalPreferences.DefaultSuspend;
+ public boolean saveAutomatically = GlobalPreferences.DefaultAutoSave;
+ public boolean confirmDialog = GlobalPreferences.DefaultConfirm;
+ public boolean override = GlobalPreferences.DefaultOverride;
+
+ /** The plug-in state time stamp. */
+ public long stateTimeStamp;
+
+ /** The incoming version of the framework. This is used to determine if a migration is needed.*/
+ public int version;
+
+ public GlobalPreferencesValues(){
+
+ }
+
+}
diff --git a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/model/IValidatorVisitor.java b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/model/IValidatorVisitor.java
new file mode 100644
index 0000000..8c74736
--- /dev/null
+++ b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/model/IValidatorVisitor.java
@@ -0,0 +1,46 @@
+/*******************************************************************************
+ * Copyright (c) 2007, 2008 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.wst.validation.internal.model;
+
+import org.eclipse.core.resources.IProject;
+import org.eclipse.core.runtime.IProgressMonitor;
+import org.eclipse.wst.validation.Validator;
+import org.eclipse.wst.validation.internal.ValOperation;
+import org.eclipse.wst.validation.internal.ValType;
+
+/**
+ * This interface is implemented by objects that visit enabled validators.
+ * <p>
+ * Usage:
+ * <pre>
+ * class Visitor implements IValidatorVisitor {
+ * public void visit(Validator validator, IProgressMonitor monitor) {
+ * // your code here
+ * }
+ * }
+ * ValidatorManager vm = ValidatorManager.getDefault();
+ * vm.accept(new Visitor(), ...);
+ * </pre>
+ * </p>
+ * <p>
+ * Clients may implement this interface.
+ * </p>
+ */
+public interface IValidatorVisitor {
+
+ /**
+ * Visits the given validator.
+ * @param validator
+ */
+ void visit(Validator validator, IProject project, ValType valType,
+ ValOperation operation, IProgressMonitor monitor);
+
+}
diff --git a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/model/ProjectPreferences.java b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/model/ProjectPreferences.java
new file mode 100644
index 0000000..dd26add
--- /dev/null
+++ b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/model/ProjectPreferences.java
@@ -0,0 +1,71 @@
+/*******************************************************************************
+ * Copyright (c) 2007, 2009 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.wst.validation.internal.model;
+
+import org.eclipse.core.resources.IProject;
+import org.eclipse.wst.validation.Validator;
+
+/**
+ * Validation preferences for a particular project.
+ * @author karasiuk
+ *
+ */
+public final class ProjectPreferences {
+ /*
+ * Before this object can be considered immutable, the mutable validators need to be addressed.
+ */
+ /** false - Default setting for the "should all the validation be suspended" setting. */
+ public static final boolean DefaultSuspend = false;
+
+ /** false - Default setting for letting projects override the global settings. */
+ public static final boolean DefaultOverride = false;
+
+ private final IProject _project;
+
+ private final boolean _override;
+ private final boolean _suspend;
+
+ private final Validator[] _validators;
+
+ public ProjectPreferences(IProject project){
+ _project = project;
+ _override = DefaultOverride;
+ _suspend = DefaultSuspend;
+ _validators = new Validator[0];
+ }
+
+ public ProjectPreferences(IProject project, boolean override, boolean suspend, Validator[] validators){
+ _project = project;
+ _override = override;
+ _suspend = suspend;
+ _validators = validators;
+ }
+
+ public boolean getOverride() {
+ return _override;
+ }
+ public boolean getSuspend() {
+ return _suspend;
+ }
+
+ /**
+ * Answer the validators that have been registered for this project.
+ * @return an empty array if there are no validators.
+ */
+ public Validator[] getValidators() {
+ return _validators;
+ }
+
+ public IProject getProject() {
+ return _project;
+ }
+
+}
diff --git a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/model/ValidatorHelper.java b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/model/ValidatorHelper.java
new file mode 100644
index 0000000..288f226
--- /dev/null
+++ b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/model/ValidatorHelper.java
@@ -0,0 +1,30 @@
+/*******************************************************************************
+ * Copyright (c) 2005, 2009 IBM Corporation 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:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.wst.validation.internal.model;
+
+import org.eclipse.wst.validation.internal.ValidatorMutable;
+
+/**
+ * Implement some common validator methods, that don't need to be part of the API.
+ *
+ * @author karasiuk
+ *
+ */
+public final class ValidatorHelper {
+
+ /**
+ * Answer true if this validator already has an exclude filter.
+ */
+ public static boolean hasExcludeGroup(ValidatorMutable v){
+ for (FilterGroup group : v.getGroups())if (group.isExclude())return true;
+ return false;
+ }
+}
diff --git a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/package.html b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/package.html
new file mode 100644
index 0000000..4b88f6b
--- /dev/null
+++ b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/package.html
@@ -0,0 +1,10 @@
+<html>
+<body>
+<h1>Validation Framework</h1>
+<h3>Build Based Validation</h3>
+The main class for build based validation is the
+<a href="ValBuilderJob.html">ValBuilderJob</a>. This gets triggered as part of the
+build mechanism. It reacts to resource change events, and from that determines what needs to be
+validated.
+</body>
+</html>
diff --git a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/package.html b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/package.html
new file mode 100644
index 0000000..caa9b25
--- /dev/null
+++ b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/package.html
@@ -0,0 +1,51 @@
+<html>
+<head>
+<title>Validation Framework</title>
+</head>
+<body>
+<p>A framework for calling validators that are build based.</p>
+<p>
+There are two main types of validation, <b>build based</b> and
+<b>as you type</b>. This framework supports build based
+validation. If auto build is turned on then the validators are called
+when the user saves their file. If auto build is not turned on then
+the validators are called when the user starts a build.</p>
+<p>This framework was added to WTP in version 3.0.</p>
+<h3>Dependency Support</h3>
+<p>Sometimes resources depend on other resources, to determine whether they are
+valid or not. An example would be that an XML resource could depend on a DTD. If at some
+point in the future the DTD changes, then the dependent XML resource should be
+revalidated to ensure that it still meets the requirements of the changed DTD
+file. In order to do this efficiently, there needs to be an association between
+the DTD and all the resources that depend on it.<p>To be as efficient as possible, the validation framework allows
+this dependency information to be returned as part of a
+<a href="AbstractValidator.html#validate(org.eclipse.core.resources.IResource, int, ValidationState, org.eclipse.core.runtime.IProgressMonitor)">
+validate operation</a>. Since the validator needed to figure this out anyways,
+why not pass this information back to the framework, so that it can be saved.
+This saves the cost of having to parse the file at some later point in time
+(when the file is probably sitting cold on disk). The fewer times that we need
+to open, read and/or parse the same file, will improve the performance of the
+product.
+<p>In particular when the validate method returns, a
+<a href="ValidationResult.html">ValidationResult</a> must be returned, inside of
+this result, all your dependencies need to be specified with the
+<a href="ValidationResult.html#setDependsOn(org.eclipse.core.resources.IResource[])">
+setDependsOn</a> method.<p>In addition to keeping the dependency information
+up-to-date through the normal course of validation, direct access is also
+provided to the dependency support through the
+<a href="ValidationFramework.html#getDependencyIndex()">getDependencyIndex</a>
+method. The <a href="IDependencyIndex.html">IDependencyIndex</a> allows you to
+directly manipulate the dependency information for a validator.
+<h3>Entry Points into the Validation Framework</h3>
+<p>Here are some of the points where the platform calls into the framework:</p>
+<ul>
+<li><b>Builder</b> - ValidationBuilder</li>
+<li><b>IFacetedProjectListener</b> - ValManager</li>
+<li><b>IJobChangeListener</b> - ValidationOperation, ValidationOperation.ValidationLauncherJob</li>
+<li><b>IProjectChangeListener</b> - ValManager</li>
+<li><b>IPropertyChangeListener</b> - ValidationConfiguration, DisabledResourceManager</li>
+<li><b>IResourceChangeListener</b> - EventManger</li>
+<li><b>IValChangedListener</b> - ValManager, DisabledValidatorManager</li>
+</ul>
+</body>
+</html>
diff --git a/plugins/org.eclipse.wst.validation/xsds/exclude.exsd b/plugins/org.eclipse.wst.validation/xsds/exclude.exsd
new file mode 100644
index 0000000..92d7647
--- /dev/null
+++ b/plugins/org.eclipse.wst.validation/xsds/exclude.exsd
@@ -0,0 +1,281 @@
+<?xml version='1.0' encoding='UTF-8'?>
+<!-- Schema file written by PDE -->
+<schema targetNamespace="org.eclipse.wst.validation" xmlns="http://www.w3.org/2001/XMLSchema">
+<annotation>
+ <appinfo>
+ <meta.schema plugin="org.eclipse.wst.validation" id="exclude" name="Validator Exclusion"/>
+ </appinfo>
+ <documentation>
+ A way to add additional exclusion filters to a V2 validator.
+ </documentation>
+ </annotation>
+
+ <element name="extension">
+ <complexType>
+ <sequence>
+ <element ref="validator" minOccurs="1" maxOccurs="unbounded"/>
+ </sequence>
+ <attribute name="point" type="string" use="required">
+ <annotation>
+ <documentation>
+
+ </documentation>
+ </annotation>
+ </attribute>
+ <attribute name="id" type="string" use="required">
+ <annotation>
+ <documentation>
+ A short id that is unique within the plug-in, so that this set of extra exclusion filters can be identified.
+ </documentation>
+ </annotation>
+ </attribute>
+ <attribute name="name" type="string">
+ <annotation>
+ <documentation>
+ The short user friendly name for the exclusion.
+ </documentation>
+ <appinfo>
+ <meta.attribute translatable="true"/>
+ </appinfo>
+ </annotation>
+ </attribute>
+ </complexType>
+ </element>
+
+ <element name="validator">
+ <annotation>
+ <documentation>
+ Identifies the validator that is being extended.
+ </documentation>
+ </annotation>
+ <complexType>
+ <sequence>
+ <element ref="exclude"/>
+ </sequence>
+ <attribute name="id" type="string" use="required">
+ <annotation>
+ <documentation>
+ The fully qualifed validator id that is being extended.
+ </documentation>
+ <appinfo>
+ <meta.attribute kind="identifier"/>
+ </appinfo>
+ </annotation>
+ </attribute>
+ </complexType>
+ </element>
+
+ <element name="exclude">
+ <annotation>
+ <documentation>
+ This contains a set of exclusion rules, used in filtering which resources get validated. If any of these rules are matched, then the validator is not called on this resource.
+ </documentation>
+ </annotation>
+ <complexType>
+ <sequence>
+ <element ref="rules"/>
+ </sequence>
+ </complexType>
+ </element>
+
+ <element name="fileext">
+ <annotation>
+ <documentation>
+ A file extension, for example html.
+ </documentation>
+ </annotation>
+ <complexType>
+ <attribute name="ext" type="string" use="required">
+ <annotation>
+ <documentation>
+ The file extension, for example html.
+ </documentation>
+ </annotation>
+ </attribute>
+ <attribute name="caseSensitive" type="boolean">
+ <annotation>
+ <documentation>
+ If the file extension is case sensitive, then this needs to be set to true.
+ </documentation>
+ </annotation>
+ </attribute>
+ </complexType>
+ </element>
+
+ <element name="projectNature">
+ <annotation>
+ <documentation>
+ Used to filter on project natures.
+ </documentation>
+ </annotation>
+ <complexType>
+ <attribute name="id" type="string" use="required">
+ <annotation>
+ <documentation>
+ The fully qualified project nature id, for example "org.eclipse.jdt.core.javanature".
+ </documentation>
+ </annotation>
+ </attribute>
+ </complexType>
+ </element>
+
+ <element name="file">
+ <complexType>
+ <attribute name="name" type="string" use="required">
+ <annotation>
+ <documentation>
+ The file or folder name. The file name can be fully qualified, that is it starts with a leading slash ("/"), or it can be a relative name. Folder names are separated with the forward slash ("/") character.
+ </documentation>
+ </annotation>
+ </attribute>
+ <attribute name="caseSensitive" type="boolean">
+ <annotation>
+ <documentation>
+ If the file name is not case senstitive, then this needs to be set to false.
+ </documentation>
+ </annotation>
+ </attribute>
+ <attribute name="type" use="required">
+ <annotation>
+ <documentation>
+ Type of name, there are three choices. <ul><li>folder - specifies a project relative folder name.</li><li>file - a simple file name (i.e. no path information).</li><li>full - a fully qualified (project relative) file name.</li></ul>
+ </documentation>
+ </annotation>
+ <simpleType>
+ <restriction base="string">
+ <enumeration value="folder">
+ </enumeration>
+ <enumeration value="file">
+ </enumeration>
+ <enumeration value="full">
+ </enumeration>
+ </restriction>
+ </simpleType>
+ </attribute>
+ </complexType>
+ </element>
+
+ <element name="rules">
+ <annotation>
+ <documentation>
+ A set of rules for determining if a resource is passed to this validator or not. The rules are OR'ed together.
+ </documentation>
+ </annotation>
+ <complexType>
+ <sequence>
+ <element ref="fileext" minOccurs="0" maxOccurs="unbounded"/>
+ <element ref="file" minOccurs="0" maxOccurs="unbounded"/>
+ <element ref="projectNature" minOccurs="0" maxOccurs="unbounded"/>
+ <element ref="facet" minOccurs="0" maxOccurs="unbounded"/>
+ <element ref="contentType" minOccurs="0" maxOccurs="unbounded"/>
+ <element ref="pattern" minOccurs="0" maxOccurs="unbounded"/>
+ </sequence>
+ </complexType>
+ </element>
+
+ <element name="facet">
+ <complexType>
+ <attribute name="id" type="string" use="required">
+ <annotation>
+ <documentation>
+ The facet id.
+ </documentation>
+ </annotation>
+ </attribute>
+ </complexType>
+ </element>
+
+ <element name="contentType">
+ <annotation>
+ <documentation>
+ Used to filter based on content types.
+ </documentation>
+ </annotation>
+ <complexType>
+ <attribute name="id" type="string" use="required">
+ <annotation>
+ <documentation>
+ The content type id.
+ </documentation>
+ </annotation>
+ </attribute>
+ <attribute name="exactMatch" type="boolean">
+ <annotation>
+ <documentation>
+ Set to true if the content type needs to match exactly. Set to false if sub types are considered matches as well.
+ </documentation>
+ </annotation>
+ </attribute>
+ </complexType>
+ </element>
+ <element name="pattern">
+ <annotation>
+ <documentation>
+ Holds a regualr expression, that matches the resource's project relative name.
+ </documentation>
+ </annotation>
+ <complexType>
+ <attribute name="regex" type="string" use="required">
+ <annotation>
+ <documentation>
+ Holds a Java regular expression. See the class java.util.regex.Pattern for more details. This regular expression is matched against a resource's project relative path, after that path has been converted into a portable path.
+<p>The path will always start with a forward slash (/) so that folder names can be more easily matched.
+ </documentation>
+ </annotation>
+ </attribute>
+ <attribute name="caseSensitive" type="boolean">
+ <annotation>
+ <documentation>
+ If the file name is not case senstitive, then this needs to be set to false.
+ </documentation>
+ </annotation>
+ </attribute>
+ </complexType>
+ </element>
+
+ <annotation>
+ <appinfo>
+ <meta.section type="since"/>
+ </appinfo>
+ <documentation>
+ WebTools 3.0
+ </documentation>
+ </annotation>
+
+ <annotation>
+ <appinfo>
+ <meta.section type="examples"/>
+ </appinfo>
+ <documentation>
+ <!-- A plug-in is turning off the T1A validator for projects that have the ModuleCoreNature -->
+ <extension
+ id="exclude1"
+ point="org.eclipse.wst.validation.exclude">
+ <validator
+ id="org.eclipse.wst.common.tests.validation.T1A">
+ <exclude>
+ <rules>
+ <projectNature
+ id="org.eclipse.jst.j2ee.ModuleCoreNature">
+ </projectNature>
+ </rules>
+ </exclude>
+ </validator>
+ </extension>
+
+ </documentation>
+ </annotation>
+
+ <annotation>
+ <appinfo>
+ <meta.section type="apiInfo"/>
+ </appinfo>
+ <documentation>
+ Provisional API.
+ </documentation>
+ </annotation>
+
+
+
+
+</schema>
diff --git a/plugins/org.eclipse.wst.validation/xsds/referencialFileExtSchema.exsd b/plugins/org.eclipse.wst.validation/xsds/referencialFileExtSchema.exsd
index a30b719..fcfe873 100644
--- a/plugins/org.eclipse.wst.validation/xsds/referencialFileExtSchema.exsd
+++ b/plugins/org.eclipse.wst.validation/xsds/referencialFileExtSchema.exsd
@@ -59,7 +59,7 @@
<attribute name="class" type="string" use="required">
<annotation>
<documentation>
-
+ This class must implement org.eclipse.wst.validation.internal.operations.ReferencialFileValidator.
</documentation>
</annotation>
</attribute>
diff --git a/plugins/org.eclipse.wst.validation/xsds/validationHelper.exsd b/plugins/org.eclipse.wst.validation/xsds/validationHelper.exsd
index d6aece6..fd854dc 100644
--- a/plugins/org.eclipse.wst.validation/xsds/validationHelper.exsd
+++ b/plugins/org.eclipse.wst.validation/xsds/validationHelper.exsd
@@ -47,7 +47,7 @@
<attribute name="helperClass" type="string" use="required">
<annotation>
<documentation>
-
+ The class must implement org.eclipse.wst.validation.internal.IProjectValidationHelper.
</documentation>
</annotation>
</attribute>
diff --git a/plugins/org.eclipse.wst.validation/xsds/validationSelectionHandler.exsd b/plugins/org.eclipse.wst.validation/xsds/validationSelectionHandler.exsd
index 9e20f4a..acffbfa 100644
--- a/plugins/org.eclipse.wst.validation/xsds/validationSelectionHandler.exsd
+++ b/plugins/org.eclipse.wst.validation/xsds/validationSelectionHandler.exsd
@@ -51,7 +51,7 @@
<attribute name="handlerClass" type="string" use="required">
<annotation>
<documentation>
-
+ The class must implement the IValidationSelectionHandler interface.
</documentation>
</annotation>
</attribute>
diff --git a/plugins/org.eclipse.wst.validation/xsds/validator.exsd b/plugins/org.eclipse.wst.validation/xsds/validator.exsd
new file mode 100644
index 0000000..fcb4818
--- /dev/null
+++ b/plugins/org.eclipse.wst.validation/xsds/validator.exsd
@@ -0,0 +1,420 @@
+<?xml version='1.0' encoding='UTF-8'?>
+<!-- Schema file written by PDE -->
+<schema targetNamespace="org.eclipse.wst.validation" xmlns="http://www.w3.org/2001/XMLSchema">
+<annotation>
+ <appinfo>
+ <meta.schema plugin="org.eclipse.wst.validation" id="validator-v2" name="Validator V2"/>
+ </appinfo>
+ <documentation>
+ This is used to register a validator to the validation framework (version 2). In addition to specifying the validator to invoke, it registers a set of default filter rules, to control which resources are passsed to the validator.
+ </documentation>
+ </annotation>
+
+ <element name="extension">
+ <annotation>
+ <appinfo>
+ <meta.element />
+ </appinfo>
+ </annotation>
+ <complexType>
+ <sequence>
+ <element ref="validator"/>
+ </sequence>
+ <attribute name="point" type="string" use="required">
+ <annotation>
+ <documentation>
+
+ </documentation>
+ </annotation>
+ </attribute>
+ <attribute name="id" type="string" use="required">
+ <annotation>
+ <documentation>
+ A short id that is unique within the plug-in, so that this validator can be identified.
+ </documentation>
+ </annotation>
+ </attribute>
+ <attribute name="name" type="string" use="required">
+ <annotation>
+ <documentation>
+ The short user friendly name of the validator.
+ </documentation>
+ <appinfo>
+ <meta.attribute translatable="true"/>
+ </appinfo>
+ </annotation>
+ </attribute>
+ </complexType>
+ </element>
+
+ <element name="validator">
+ <annotation>
+ <documentation>
+ Defines a validator to the validation framework.
+ </documentation>
+ </annotation>
+ <complexType>
+ <sequence>
+ <element ref="include" minOccurs="0" maxOccurs="unbounded"/>
+ <element ref="exclude" minOccurs="0" maxOccurs="1"/>
+ <element ref="messageCategory" minOccurs="0" maxOccurs="unbounded"/>
+ <element ref="group" minOccurs="0" maxOccurs="unbounded"/>
+ </sequence>
+ <attribute name="class" type="string" use="required">
+ <annotation>
+ <documentation>
+ The class that implements the validator.
+ </documentation>
+ <appinfo>
+ <meta.attribute kind="java" basedOn="org.eclipse.wst.validation.AbstractValidator"/>
+ </appinfo>
+ </annotation>
+ </attribute>
+ <attribute name="build" type="boolean">
+ <annotation>
+ <documentation>
+ Is this validator enabled by default for build based validations? The default is true.
+ </documentation>
+ </annotation>
+ </attribute>
+ <attribute name="manual" type="boolean">
+ <annotation>
+ <documentation>
+ Is this validator enabled by default for manual based validations? The default is true.
+ </documentation>
+ </annotation>
+ </attribute>
+ <attribute name="version" type="string">
+ <annotation>
+ <documentation>
+ The version of the definition. It is a simple integer. If not specified the version is assumed to be 1.
+ </documentation>
+ </annotation>
+ </attribute>
+ <attribute name="sourceid" type="string">
+ <annotation>
+ <documentation>
+ If this validator also serves as an as-you-type validator (also know as an ISourceValidator) then it's source id is specified here, so that the two validators can be associated with one another.
+By source id, we mean the id that is used in the org.eclipse.wst.sse.ui.sourceValidation extension point
+ </documentation>
+ </annotation>
+ </attribute>
+ <attribute name="markerId" type="string">
+ <annotation>
+ <documentation>
+ If your validator wishes to use it's own marker, it can do so by supplying that marker id here.
+ </documentation>
+ </annotation>
+ </attribute>
+ </complexType>
+ </element>
+
+ <element name="include">
+ <annotation>
+ <documentation>
+ This contains a set of inclusion rules, which are used in filtering which resources get validated. At least one of these rules must be satisfied in order for the validator to be called on the particular resource.
+ </documentation>
+ </annotation>
+ <complexType>
+ <sequence>
+ <element ref="rules"/>
+ </sequence>
+ </complexType>
+ </element>
+
+ <element name="exclude">
+ <annotation>
+ <documentation>
+ This contains a set of exclusion rules, used in filtering which resources get validated. If any of these rules are matched, then the validator is not called on this resource.
+ </documentation>
+ </annotation>
+ <complexType>
+ <sequence>
+ <element ref="rules"/>
+ </sequence>
+ </complexType>
+ </element>
+
+ <element name="fileext">
+ <annotation>
+ <documentation>
+ A file extension, for example html.
+ </documentation>
+ </annotation>
+ <complexType>
+ <attribute name="ext" type="string" use="required">
+ <annotation>
+ <documentation>
+ The file extension, for example html.
+ </documentation>
+ </annotation>
+ </attribute>
+ <attribute name="caseSensitive" type="boolean">
+ <annotation>
+ <documentation>
+ If the file extension is case sensitive, then this needs to be set to true.
+ </documentation>
+ </annotation>
+ </attribute>
+ </complexType>
+ </element>
+
+ <element name="projectNature">
+ <annotation>
+ <documentation>
+ Used to filter on project natures.
+ </documentation>
+ </annotation>
+ <complexType>
+ <attribute name="id" type="string" use="required">
+ <annotation>
+ <documentation>
+ The fully qualified project nature id, for example "org.eclipse.jdt.core.javanature".
+ </documentation>
+ </annotation>
+ </attribute>
+ </complexType>
+ </element>
+
+ <element name="file">
+ <complexType>
+ <attribute name="name" type="string" use="required">
+ <annotation>
+ <documentation>
+ The file or folder name. The file name can be fully qualified, that is it starts with a leading slash ("/"), or it can be a relative name. Folder names are separated with the forward slash ("/") character.
+ </documentation>
+ </annotation>
+ </attribute>
+ <attribute name="caseSensitive" type="boolean">
+ <annotation>
+ <documentation>
+ If the file name is not case senstitive, then this needs to be set to false.
+ </documentation>
+ </annotation>
+ </attribute>
+ <attribute name="type" use="required">
+ <annotation>
+ <documentation>
+ Type of name, there are three choices. <ul><li>folder - specifies a project relative folder name.</li><li>file - a simple file name (i.e. no path information).</li><li>full - a fully qualified (project relative) file name.</li></ul>
+ </documentation>
+ </annotation>
+ <simpleType>
+ <restriction base="string">
+ <enumeration value="folder">
+ </enumeration>
+ <enumeration value="file">
+ </enumeration>
+ <enumeration value="full">
+ </enumeration>
+ </restriction>
+ </simpleType>
+ </attribute>
+ </complexType>
+ </element>
+
+ <element name="rules">
+ <annotation>
+ <documentation>
+ A set of rules for determining if a resource is passed to this validator or not. The rules are OR'ed together.
+ </documentation>
+ </annotation>
+ <complexType>
+ <sequence>
+ <element ref="fileext" minOccurs="0" maxOccurs="unbounded"/>
+ <element ref="file" minOccurs="0" maxOccurs="unbounded"/>
+ <element ref="projectNature" minOccurs="0" maxOccurs="unbounded"/>
+ <element ref="facet" minOccurs="0" maxOccurs="unbounded"/>
+ <element ref="contentType" minOccurs="0" maxOccurs="unbounded"/>
+ <element ref="pattern" minOccurs="0" maxOccurs="unbounded"/>
+ </sequence>
+ </complexType>
+ </element>
+
+ <element name="facet">
+ <complexType>
+ <attribute name="id" type="string" use="required">
+ <annotation>
+ <documentation>
+ The facet id.
+ </documentation>
+ </annotation>
+ </attribute>
+ <attribute name="version" type="string">
+ <annotation>
+ <documentation>
+ A version expression that can be used to futher qualify the match. If not specifed, then versions are not used as a criteria for selecting the facet. The syntax of this expression, is the same syntax that is used by the facet framework.
+ </documentation>
+ </annotation>
+ </attribute>
+ </complexType>
+ </element>
+
+ <element name="group">
+ <annotation>
+ <documentation>
+ Declares that this validator belongs to this validation group.
+ </documentation>
+ </annotation>
+ <complexType>
+ <attribute name="id" type="string" use="required">
+ <annotation>
+ <documentation>
+ The fully qualified ID of the validation group to which this validator belongs.
+ </documentation>
+ <appinfo>
+ <meta.attribute kind="identifier"/>
+ </appinfo>
+ </annotation>
+ </attribute>
+ </complexType>
+ </element>
+
+ <element name="contentType">
+ <annotation>
+ <documentation>
+ Used to filter based on content types.
+ </documentation>
+ </annotation>
+ <complexType>
+ <attribute name="id" type="string" use="required">
+ <annotation>
+ <documentation>
+ The content type id.
+ </documentation>
+ </annotation>
+ </attribute>
+ <attribute name="exactMatch" type="boolean">
+ <annotation>
+ <documentation>
+ Set to true if the content type needs to match exactly. Set to false if sub types are considered matches as well.
+ </documentation>
+ </annotation>
+ </attribute>
+ </complexType>
+ </element>
+
+ <element name="messageCategory">
+ <annotation>
+ <documentation>
+ Used to group together a set of messages, where the user can change the message severity of all the messages in the group. This is similar to the support in the JDT, where for example a user can specify whether used methods should be errors, warnings or ignored.
+ </documentation>
+ </annotation>
+ <complexType>
+ <attribute name="id" type="string" use="required">
+ <annotation>
+ <documentation>
+ A simple id that is unique within the scope of this validator.
+ </documentation>
+ </annotation>
+ </attribute>
+ <attribute name="label" type="string" use="required">
+ <annotation>
+ <documentation>
+ A short, one line label that is displayed to the end user, that describes the message category.
+ </documentation>
+ <appinfo>
+ <meta.attribute translatable="true"/>
+ </appinfo>
+ </annotation>
+ </attribute>
+ <attribute name="severity">
+ <annotation>
+ <documentation>
+ The default severity for this category.
+ </documentation>
+ </annotation>
+ <simpleType>
+ <restriction base="string">
+ <enumeration value="error">
+ </enumeration>
+ <enumeration value="warning">
+ </enumeration>
+ <enumeration value="ignore">
+ </enumeration>
+ </restriction>
+ </simpleType>
+ </attribute>
+ </complexType>
+ </element>
+
+ <element name="pattern">
+ <annotation>
+ <documentation>
+ Holds a regualr expression, that matches the resource's project relative name.
+ </documentation>
+ </annotation>
+ <complexType>
+ <attribute name="regex" type="string" use="required">
+ <annotation>
+ <documentation>
+ Holds a Java regular expression. See the class java.util.regex.Pattern for more details. This regular expression is matched against a resource's project relative path, after that path has been converted into a portable path.
+<p>The path will always start with a forward slash (/) so that folder names can be more easily matched.
+ </documentation>
+ </annotation>
+ </attribute>
+ <attribute name="caseSensitive" type="boolean">
+ <annotation>
+ <documentation>
+ If the file name is not case senstitive, then this needs to be set to false.
+ </documentation>
+ </annotation>
+ </attribute>
+ </complexType>
+ </element>
+
+ <annotation>
+ <appinfo>
+ <meta.section type="apiInfo"/>
+ </appinfo>
+ <documentation>
+ Provisional API.
+ </documentation>
+ </annotation>
+
+ <annotation>
+ <appinfo>
+ <meta.section type="since"/>
+ </appinfo>
+ <documentation>
+ WebTools 3.0.
+ </documentation>
+ </annotation>
+
+ <annotation>
+ <appinfo>
+ <meta.section type="examples"/>
+ </appinfo>
+ <documentation>
+ An example of a validator that will be called on resources that have html or htm file extensions.
+<pre>
+ <extension
+ point="org.eclipse.wst.validation.validator"
+ id="Test" name="%Validator.Name">
+ <validator class="org.eclipse.wst.validation.test.TestValidator">
+ <include>
+ <rules>
+ <fileext ext="html"/>
+ <fileext ext="htm"/>
+ </rules>
+ </include>
+ </validator>
+ </extension>
+</pre>
+ </documentation>
+ </annotation>
+
+
+ <annotation>
+ <appinfo>
+ <meta.section type="copyright"/>
+ </appinfo>
+ <documentation>
+ Copyright (c) 2007,2008 IBM Corporation and others.<br>
+All rights reserved. This program and the accompanying materials are made
+available under the terms of the Eclipse Public License v1.0 which accompanies
+this distribution, and is available at <a
+href="http://www.eclipse.org/legal/epl-v10.html">http://www.eclipse.org/legal/epl-v10.html</a>
+ </documentation>
+ </annotation>
+
+</schema>
diff --git a/plugins/org.eclipse.wst.validation/xsds/validatorExtSchema.exsd b/plugins/org.eclipse.wst.validation/xsds/validatorExtSchema.exsd
index d97b916..25d2602 100644
--- a/plugins/org.eclipse.wst.validation/xsds/validatorExtSchema.exsd
+++ b/plugins/org.eclipse.wst.validation/xsds/validatorExtSchema.exsd
@@ -20,22 +20,25 @@
<attribute name="point" type="string" use="required">
<annotation>
<documentation>
- a fully qualified identifier of the target extension point
+ A fully qualified identifier of the target extension point
</documentation>
</annotation>
</attribute>
<attribute name="id" type="string" use="required">
<annotation>
<documentation>
- an optional identifier of the extension instance
+ An optional identifier of the extension instance
</documentation>
</annotation>
</attribute>
<attribute name="name" type="string" use="required">
<annotation>
<documentation>
- an optional name of the extension instance
+ An optional name of the extension instance
</documentation>
+ <appInfo>
+ <meta.attribute translatable="true"/>
+ </appInfo>
</annotation>
</attribute>
</complexType>
@@ -44,15 +47,15 @@
<element name="validator">
<complexType>
<sequence>
- <element ref="projectNature" minOccurs="1" maxOccurs="unbounded"/>
- <element ref="filter" minOccurs="1" maxOccurs="unbounded"/>
- <element ref="enablement"/>
+ <element ref="projectNature" minOccurs="0" maxOccurs="unbounded"/>
+ <element ref="filter" minOccurs="0" maxOccurs="unbounded"/>
+ <element ref="enablement" minOccurs="0" maxOccurs="unbounded"/>/>
<element ref="helper"/>
<element ref="dependentValidator" minOccurs="0" maxOccurs="1"/>
<element ref="run"/>
<element ref="markerId" minOccurs="0" maxOccurs="1"/>
<element ref="facet" minOccurs="0" maxOccurs="unbounded"/>
-
+ <element ref="contentTypeBinding" minOccurs="0" maxOccurs="unbounded"/>
</sequence>
<attribute name="to" type="string">
<annotation>
@@ -91,6 +94,30 @@
</attribute>
</complexType>
</element>
+
+
+ <element name="contentTypeBinding">
+ <annotation>
+ <appInfo>
+ <meta.element labelAttribute="contentTypeId"/>
+ </appInfo>
+ <documentation>
+ Associates a particular content type with the current validator, and enables the validator to be run on resources of the specified content type.
+ </documentation>
+ </annotation>
+ <complexType>
+ <attribute name="contentTypeId" type="string" use="required">
+ <annotation>
+ <documentation>
+ The content type identifier. This is an ID defined by the 'org.eclipse.core.runtime.contentTypes' extension point.
+ </documentation>
+ </annotation>
+ </attribute>
+ </complexType>
+ </element>
+
+
+
<element name="filter">
<complexType>
diff --git a/plugins/org.eclipse.wst.validation/xsds/validatorgroup.exsd b/plugins/org.eclipse.wst.validation/xsds/validatorgroup.exsd
new file mode 100644
index 0000000..df05cb1
--- /dev/null
+++ b/plugins/org.eclipse.wst.validation/xsds/validatorgroup.exsd
@@ -0,0 +1,161 @@
+<?xml version='1.0' encoding='UTF-8'?>
+<!-- Schema file written by PDE -->
+<schema targetNamespace="org.eclipse.wst.validation" xmlns="http://www.w3.org/2001/XMLSchema">
+<annotation>
+ <appinfo>
+ <meta.schema plugin="org.eclipse.wst.validation" id="validatorGroup" name="Validator Group"/>
+ </appinfo>
+ <documentation>
+ Defines a grouping for validators with listeners notified of group members' activites. Useful for pre-caching common information used by multiple validators and disposing of that information when they're all done.
+ </documentation>
+ </annotation>
+
+ <element name="extension">
+ <annotation>
+ <appinfo>
+ <meta.element />
+ </appinfo>
+ </annotation>
+ <complexType>
+ <sequence>
+ <element ref="group" minOccurs="1" maxOccurs="unbounded"/>
+ </sequence>
+ <attribute name="point" type="string" use="required">
+ <annotation>
+ <documentation>
+
+ </documentation>
+ </annotation>
+ </attribute>
+ <attribute name="id" type="identifier">
+ <annotation>
+ <documentation>
+ A unique identifier for this extension
+ </documentation>
+ </annotation>
+ </attribute>
+ <attribute name="name" type="string">
+ <annotation>
+ <documentation>
+ A name for this extension
+ </documentation>
+ <appinfo>
+ <meta.attribute translatable="true"/>
+ </appinfo>
+ </annotation>
+ </attribute>
+ </complexType>
+ </element>
+
+ <element name="listener">
+ <annotation>
+ <documentation>
+ A listener for activities in this group.
+ </documentation>
+ </annotation>
+ <complexType>
+ <attribute name="class" type="string" use="required">
+ <annotation>
+ <documentation>
+ The listener's class.
+ </documentation>
+ <appinfo>
+ <meta.attribute kind="java" basedOn=":org.eclipse.wst.validation.IValidatorGroupListener"/>
+ </appinfo>
+ </annotation>
+ </attribute>
+ </complexType>
+ </element>
+
+ <element name="group">
+ <annotation>
+ <documentation>
+ Declares a validator group. A group may have multiple listeners.
+ </documentation>
+ </annotation>
+ <complexType>
+ <choice>
+ <element ref="listener" minOccurs="1" maxOccurs="unbounded"/>
+ </choice>
+ <attribute name="id" type="string" use="required">
+ <annotation>
+ <documentation>
+
+ </documentation>
+ <appinfo>
+ <meta.attribute kind="identifier"/>
+ </appinfo>
+ </annotation>
+ </attribute>
+ </complexType>
+ </element>
+
+ <annotation>
+ <appinfo>
+ <meta.section type="since"/>
+ </appinfo>
+ <documentation>
+ WebTools 3.0
+ </documentation>
+ </annotation>
+
+ <annotation>
+ <appinfo>
+ <meta.section type="examples"/>
+ </appinfo>
+ <documentation>
+ Define a listener that simply prints that it has been called.
+<pre>
+<extension point="org.eclipse.wst.validation.validatorGroup">
+ <group id="validatorGroup">
+ <listener class="org.eclipse.wst.validation.example.ValidatorGroupListener"/>
+ </group>
+</extension>
+
+public class org.eclipse.wst.validation.example.ValidatorGroupListener implements IValidatorGroupListener {
+
+ public ValidatorGroupListener() {
+ }
+
+ public void validationFinishing(IResource resource, IProgressMonitor monitor, ValType valType, ValOperation operation) {
+ System.out.println("Finishing:" + resource.getFullPath());
+ }
+
+ public void validationStarting(IResource resource, IProgressMonitor monitor, ValType valType, ValOperation operation) {
+ System.out.println("Starting:" + resource.getFullPath());
+ }
+}
+
+<extension id="id" name="name" point="org.eclipse.wst.validation.validatorV2">
+ <validator class="org.eclipse.wst.validation.example.Validator">
+ <group id="org.eclipse.wst.validation.example.validatorGroup"/>
+ </validator>
+</extension>
+</pre>
+ </documentation>
+ </annotation>
+
+ <annotation>
+ <appinfo>
+ <meta.section type="apiinfo"/>
+ </appinfo>
+ <documentation>
+ Provisional API.
+ </documentation>
+ </annotation>
+
+
+ <annotation>
+ <appinfo>
+ <meta.section type="copyright"/>
+ </appinfo>
+ <documentation>
+ Copyright (c) 2008 IBM Corporation and others.<br>
+All rights reserved. This program and the accompanying materials are made
+available under the terms of the Eclipse Public License v1.0 which accompanies
+this distribution, and is available at <a
+href="http://www.eclipse.org/legal/epl-v10.html">http://www.eclipse.org/legal/epl-v10.html</a>
+ </documentation>
+ </annotation>
+
+</schema>