OPENJPA-1412,979: Adding Eclipse Plugin with complete Maven/Tycho build script and tests. It is also the first instance of a non-committer contribution

git-svn-id: https://svn.apache.org/repos/asf/openjpa/trunk@889024 13f79535-47bb-0310-9956-ffa450edef68
This commit is contained in:
Pinaki Poddar 2009-12-10 00:00:07 +00:00
parent 61dc996dc9
commit 658f01ee38
55 changed files with 6220 additions and 0 deletions

View File

@ -0,0 +1,12 @@
package test;
public class NotToEnhance {
/**
* @param args
*/
public static void main(String[] args) {
System.out.println("Hello!");
}
}

View File

@ -0,0 +1,8 @@
package test;
import javax.persistence.Entity;
@Entity
public class SomeEntity {
}

View File

@ -0,0 +1,15 @@
package test.test;
import junit.framework.TestCase;
import org.apache.openjpa.enhance.PersistenceCapable;
import test.SomeEntity;
public class SomeEntityTest extends TestCase {
public void testEnhancement() {
SomeEntity o = new SomeEntity();
assertTrue("SomeEntity is not PersistenceCapable", o instanceof PersistenceCapable);
}
}

View File

@ -0,0 +1 @@
bin.includes = feature.xml

View File

@ -0,0 +1,34 @@
<?xml version="1.0" encoding="UTF-8"?>
<feature
id="org.apache.openjpa.eclipse.feature"
label="OpenJPA Eclipse Feature"
version="1.0.0.qualifier"
provider-name="Michael Vorburger &amp; others, for Apache.org">
<description url="http://www.example.com/description">
[Enter Feature Description here.]
</description>
<copyright url="http://www.example.com/copyright">
[Enter Copyright Description here.]
</copyright>
<license url="http://www.example.com/license">
[Enter License Description here.]
</license>
<plugin
id="org.apache.openjpa"
download-size="0"
install-size="0"
version="0.0.0"
unpack="false"/>
<plugin
id="org.apache.openjpa.eclipse"
download-size="0"
install-size="0"
version="0.0.0"
unpack="false"/>
</feature>

View File

@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<project>
<modelVersion>4.0.0</modelVersion>
<parent>
<artifactId>org.apache.openjpa.eclipse.all</artifactId>
<groupId>org.apache.openjpa.eclipse</groupId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<groupId>org.apache.openjpa.eclipse</groupId>
<artifactId>org.apache.openjpa.eclipse.feature</artifactId>
<version>1.0.0</version>
<packaging>eclipse-feature</packaging>
</project>

View File

@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<project>
<modelVersion>4.0.0</modelVersion>
<parent>
<artifactId>org.apache.openjpa.eclipse.all</artifactId>
<groupId>org.apache.openjpa.eclipse</groupId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<groupId>org.apache.openjpa.eclipse</groupId>
<artifactId>org.apache.openjpa.eclipse.site</artifactId>
<version>1.0.0-SNAPSHOT</version>
<packaging>eclipse-update-site</packaging>
</project>

View File

@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<site>
<feature url="features/org.apache.openjpa.eclipse.feature_1.0.0.qualifier.jar" id="org.apache.openjpa.eclipse.feature" version="1.0.0.qualifier">
<category name="org.apache.openjpa.eclipse"/>
</feature>
<category-def name="org.apache.openjpa.eclipse" label="OpenJPA Eclipse Tools"/>
</site>

View File

@ -0,0 +1,11 @@
Manifest-Version: 1.0
Bundle-ManifestVersion: 2
Bundle-Name: OpenJPA Eclipse Tools Test Fragment
Bundle-SymbolicName: org.apache.openjpa.eclipse.tests
Bundle-Version: 1.0.0.qualifier
Fragment-Host: org.apache.openjpa.eclipse;bundle-version="1.0.0"
Bundle-RequiredExecutionEnvironment: JavaSE-1.6
Require-Bundle: org.apache.openjpa,
org.junit;bundle-version="3.8.2"
Bundle-ClassPath: lib/commons-io-1.4.jar,
.

View File

@ -0,0 +1,5 @@
source.. = src/test/java/
output.. = target/test-classes/
bin.includes = META-INF/,\
.,\
lib/commons-io-1.4.jar

View File

@ -0,0 +1,16 @@
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<artifactId>org.apache.openjpa.eclipse.all</artifactId>
<groupId>org.apache.openjpa.eclipse</groupId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<groupId>org.apache.openjpa.eclipse</groupId>
<artifactId>org.apache.openjpa.eclipse.tests</artifactId>
<version>1.0.0</version>
<packaging>eclipse-test-plugin</packaging>
</project>

View File

@ -0,0 +1,150 @@
/*
* Copyright 2002-2009 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.openjpa.eclipse;
import java.io.File;
import java.io.IOException;
import junit.framework.Assert;
import junit.framework.TestCase;
import org.apache.commons.io.FileUtils;
import org.apache.openjpa.eclipse.util.ClassLoaderFromIProjectHelper;
import org.apache.openjpa.enhance.PersistenceCapable;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IMarker;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IProjectDescription;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.resources.IncrementalProjectBuilder;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.jdt.core.IClasspathEntry;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.IPackageFragmentRoot;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.JavaModelException;
/**
* PDE Test for OpenJPAEnhancerBuilder.
*
* Inspired by ClasspathHelperTest, thanks!
* Uses same classes and approach as PCEnhancerHelperTest, have a look at that one before this one to better understand.
*
* @author Michael Vorburger
*/
public class EnhancerBuilderTest extends TestCase {
/*
* TODO EnhancerBuilderTest does not yet work! FIXME!!!
* Somehow our Builder doesn't run after all with this test (it works tested standalone of course), why??
*/
private static final String PROJECT_NAME = "EnhancerBuilderTest";
private static final String TESTCLASS_PACKAGE = "org.apache.openjpa.eclipse";
private final static File SRC_PACKAGE_DIR = new File("src/test/notonclasspath/", TESTCLASS_PACKAGE.replace('.', '/'));
private IProject project;
protected void setUp() throws Exception {
IWorkspace workspace = null;
try {
workspace = ResourcesPlugin.getWorkspace();
}
catch (IllegalStateException e) {
fail("workspace is closed, you are most probably running this as a standalone JUnit Test instead of as an Eclipse PDE Plug-In Test?!");
}
// create project
project = workspace.getRoot().getProject(PROJECT_NAME);
project.create(null);
project.open(null);
// create source and output folders
IFolder srcFolder = project.getFolder("src");
srcFolder.create(true, true, null);
IFolder binFolder = project.getFolder("bin");
binFolder.create(true, true, null);
IProjectDescription desc = project.getDescription();
// Set the Java and OpenJPA natures on the project,
// so that the builders is added and initialized
desc.setNatureIds(new String[] { JavaCore.NATURE_ID, OpenJPANature.NATURE_ID });
project.setDescription(desc, null);
// Declare Java source and output folders
IJavaProject javaProject = JavaCore.create(project);
javaProject.setOutputLocation(binFolder.getFullPath(), null);
IClasspathEntry cpEntry = JavaCore.newSourceEntry(srcFolder.getFullPath());
javaProject.setRawClasspath(new IClasspathEntry[] { cpEntry }, null);
// create a Java package and a class
IPackageFragmentRoot pkgFragmentRoot = javaProject.getPackageFragmentRoot(srcFolder);
IPackageFragment pkgFragment = pkgFragmentRoot.createPackageFragment(TESTCLASS_PACKAGE, true, null);
// and copy the same classes already used in the PCEnhancerHelperTest
copyTestClassToPackage(pkgFragment, "TestEntity.java");
// copyTestClassToPackage(pkgFragment, "NotToEnhance.java");
javaProject.save(null, true);
}
private void copyTestClassToPackage(IPackageFragment pkgFragment, String classFileName) throws IOException, JavaModelException {
File testEntityFile = new File(SRC_PACKAGE_DIR, classFileName);
String contents = FileUtils.readFileToString(testEntityFile);
pkgFragment.createCompilationUnit(classFileName, contents, true, null);
}
protected void tearDown() throws Exception {
project.delete(true, null);
}
public void testNoop() {}
// NOTE: This currently fails, see TODO at the beginning of the class...
public void todotestBuilder() throws Exception {
project.build(IncrementalProjectBuilder.FULL_BUILD, null);
// TODO INCREMENTAL and FULL_BUILD
IMarker[] markers = project.findMarkers(null, true, IResource.DEPTH_INFINITE);
if (markers.length != 0) {
for (IMarker marker : markers) {
System.err.print(marker.getAttribute(IMarker.LOCATION) + " : ");
System.err.println(marker.getAttribute(IMarker.MESSAGE));
}
fail("Project Build unexpectedly lead to Markers (printed to stderr for debugging)");
}
String classFileName = "bin/" + TESTCLASS_PACKAGE.replace('.', '/') + "/TestEntity.class";
assertTrue(classFileName + " does not exist?!", project.getFile(classFileName).exists());
// assertTrue(project.getFile("bin/" + TESTCLASS_PACKAGE.replace('.', '/') + "NotToEnhance.class").exists());
ClassLoader cl = ClassLoaderFromIProjectHelper.createClassLoader(project);
assertNotNull(cl);
Class<?> testClass = cl.loadClass(TESTCLASS_PACKAGE + "." + "TestEntity");
Assert.assertNotNull(testClass);
assertEquals("TestEntity", testClass.getSimpleName());
Assert.assertEquals(1, testClass.getInterfaces().length);
Assert.assertTrue(testClass.getInterfaces()[0].equals(PersistenceCapable.class));
}
}

View File

@ -0,0 +1,110 @@
/*
* Copyright 2002-2009 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.openjpa.eclipse.util;
import java.io.InputStream;
import junit.framework.TestCase;
import org.apache.commons.io.IOUtils;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IProjectDescription;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.resources.IncrementalProjectBuilder;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.jdt.core.IClasspathEntry;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.IPackageFragmentRoot;
import org.eclipse.jdt.core.JavaCore;
/**
* PDE Test for ClasspathHelper.
*
* @author Kai Kreuzer
*/
public class ClasspathHelperTest extends TestCase {
private static final String PROJECT_NAME = "test";
private static final String TESTCLASS_PACKAGE = "com.odcgroup.test";
private static final String TESTCLASS_NAME = "TestClass";
private IProject project;
protected void setUp() throws Exception {
IWorkspace workspace = null;
try {
workspace = ResourcesPlugin.getWorkspace();
}
catch (IllegalStateException e) {
fail("workspace is closed, you are most probably running this as a standalone JUnit Test instead of as an Eclipse PDE Plug-In Test?!");
}
// create project
project = workspace.getRoot().getProject(PROJECT_NAME);
project.create(null);
project.open(null);
// create source and output folders
IFolder srcFolder = project.getFolder("src");
srcFolder.create(true, true, null);
IFolder binFolder = project.getFolder("bin");
binFolder.create(true, true, null);
// Set the Java nature on the project, so that the builder is added and initialized
IProjectDescription desc = workspace.newProjectDescription(PROJECT_NAME);
desc.setNatureIds(new String[] { JavaCore.NATURE_ID });
project.setDescription(desc, null);
// Declare Java source and output folders
IJavaProject javaProject = JavaCore.create(project);
javaProject.setOutputLocation(binFolder.getFullPath(), null);
IClasspathEntry cpEntry = JavaCore.newSourceEntry(srcFolder.getFullPath());
javaProject.setRawClasspath(new IClasspathEntry[] { cpEntry }, null);
// create a Java package and a class
IPackageFragmentRoot pkgFragmentRoot = javaProject.getPackageFragmentRoot(srcFolder);
IPackageFragment pkgFragment = pkgFragmentRoot.createPackageFragment(TESTCLASS_PACKAGE, true, null);
InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(
"/com/odcgroup/classpath/demo/tests/resources/testclasscontent.txt");
String contents = IOUtils.toString(is);
pkgFragment.createCompilationUnit(TESTCLASS_NAME + ".java", contents, true, null);
javaProject.save(null, true);
}
protected void tearDown() throws Exception {
project.delete(true, null);
}
public void testCreateClassLoader() throws Exception {
project.build(IncrementalProjectBuilder.INCREMENTAL_BUILD, null);
assertTrue("Class file has not been built", project.getFile("bin/com/odcgroup/test/TestClass.class").exists());
ClassLoader cl = ClassLoaderFromIProjectHelper.createClassLoader(project);
assertNotNull(cl);
try {
Class<?> clazz = cl.loadClass(TESTCLASS_PACKAGE + "." + TESTCLASS_NAME);
assertEquals(TESTCLASS_NAME, clazz.getSimpleName());
} catch (ClassNotFoundException e) {
fail("Cannot find test class through classloader");
}
}
}

View File

@ -0,0 +1,77 @@
/*
* Copyright 2002-2009 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.openjpa.eclipse.util;
import java.io.File;
import java.net.URL;
import java.net.URLClassLoader;
import junit.framework.Assert;
import junit.framework.TestCase;
import org.apache.commons.io.FileUtils;
import org.apache.openjpa.enhance.PersistenceCapable;
/**
* Test for PCEnhancerHelper implementations.
*
* @author Michael Vorburger
*/
public class PCEnhancerHelperTest extends TestCase {
private final static File srcDir = new File("src/test/notonclasspath/");
private final static File targetDir = new File("target/PCEnhancerHelperTest");
private final static String classPackage = "org.apache.openjpa.eclipse.";
public void todotestEnhanceFile() throws Exception {
String className = "TestEntity";
URL[] urls = new URL[] { targetDir.toURI().toURL() };
ClassLoader classLoader = new URLClassLoader(urls);
PCEnhancerHelper eh = new PCEnhancerHelperImpl(classLoader);
boolean r = checkEnhance(eh, className);
Assert.assertTrue(r); // was enhanced..
// Reset/re-initialize classLoader, to freshly load and check the enhanced class
classLoader = new URLClassLoader(urls);
Class<?> testClass = classLoader.loadClass(classPackage + className);
Assert.assertNotNull(testClass);
Assert.assertEquals(1, testClass.getInterfaces().length);
Assert.assertTrue(testClass.getInterfaces()[0].equals(PersistenceCapable.class));
}
public void testEnhancingAClassThatIsNotAnEntity() throws Exception {
String className = "NotToEnhance";
ClassLoader classLoader = new URLClassLoader(new URL[] { targetDir.toURI().toURL() });
PCEnhancerHelper eh = new PCEnhancerHelperImpl(classLoader);
boolean r = checkEnhance(eh, className);
Assert.assertFalse(r); // NOT enhanced!
}
private boolean checkEnhance(PCEnhancerHelper eh, String classNameToCheck) throws Exception {
String classFileName = classPackage.replace('.', '/') + classNameToCheck + ".class";
FileUtils.forceMkdir(targetDir);
FileUtils.cleanDirectory(targetDir);
FileUtils.copyFileToDirectory(new File(srcDir, classFileName), new File(targetDir, classPackage.replace('.', '/')));
File classFile = new File(targetDir, classFileName);
assertTrue(classFile.exists());
return eh.enhance(classFile);
}
}

View File

@ -0,0 +1,53 @@
/*
* Copyright 2002-2009 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.openjpa.eclipse.util;
import java.util.Properties;
import junit.framework.TestCase;
/**
* Test for PathMatcherUtil.
*
* @author Michael Vorburger (MVO)
*/
public class PathMatcherUtilTest extends TestCase {
/**
* Test method for {@link org.apache.openjpa.eclipse.util.PathMatcherUtil#match(java.lang.String)}.
*/
public void testPathMatcherUtil() {
Properties p = new Properties();
p.setProperty("include1", "**/*Entity.class");
p.setProperty("include2", "**/*EntityRef.class");
PathMatcherUtil o = new PathMatcherUtil(p);
assertTrue(o.match("asdjflaskdf/asdkfmasdlfk/asdklfmasdlf/SomeEntity.class"));
assertTrue(o.match("asdjflaskdf/asdkfmasdlfk/asdklfmasdlf/SomeEntityRef.class"));
assertFalse(o.match("asdjflaskdf/asdkfmasdlfk/asdklfmasdlf/ThisEntityIsNot.class"));
assertFalse(o.match("asdjflaskdf/asdkfmasdlfk/asdklfmasdlf/SomethingElse.class"));
}
public void testPathMatcherUtilWithNull() {
PathMatcherUtil o = new PathMatcherUtil(null);
assertTrue(o.match("asdjflaskdf/asdkfmasdlfk/asdklfmasdlf/SomeEntity.class"));
assertTrue(o.match("asdjflaskdf/asdkfmasdlfk/asdklfmasdlf/SomeEntity.Refclass"));
assertTrue(o.match("asdjflaskdf/asdkfmasdlfk/asdklfmasdlf/ThisEntityIsNot.class"));
assertTrue(o.match("asdjflaskdf/asdkfmasdlfk/asdklfmasdlf/SomethingElse.class"));
}
}

View File

@ -0,0 +1,9 @@
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="1.0" xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd">
<persistence-unit name="testpu">
<class>org.apache.openjpa.eclipse.TestEntity</class>
</persistence-unit>
</persistence>

View File

@ -0,0 +1,12 @@
package test;
public class NotToEnhance {
/**
* @param args
*/
public static void main(String[] args) {
System.out.println("Hello!");
}
}

View File

@ -0,0 +1,22 @@
package org.apache.openjpa.eclipse;
import javax.persistence.Entity;
import javax.persistence.Id;
/**
* Test JPA Entity.
*/
@Entity
public class TestEntity {
@Id
private long id;
private String name;
// ----------------------------------------------------------------------
public String getName() {
return name;
}
}

View File

@ -0,0 +1,8 @@
package com.odcgroup.test;
public class TestClass {
public String toString() {
return "This class is totally useless";
}
}

View File

@ -0,0 +1,380 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
======================================
LICENSES FOR INCLUDED DEPENDENCIES
======================================
All the source code for the OpenJPA project is released under the
license above. Additionally, the OpenJPA binary distribution
includes a number of third-party files that are required in
order to the software to function. Unless noted below, these jars
and resource files are also released under the ASF license above.
The exceptions are as follows:
===========================
orm-xsd.rsrc - included in the openjpa jar, taken from:
http://java.sun.com/xml/ns/persistence/orm_1_0.xsd)
persistence-xsd.rsrc - included in the openjpa jar, taken from:
http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd)
websphere-uow-api.jar - this jar file contains WebSphere proprietary
API code which is licensed for use when compiling OpenJPA. The
jar is not distributed with OpenJPA and is only included with the
source archive in order to resolve compilation dependencies.
===========================
COMMON DEVELOPMENT AND DISTRIBUTION LICENSE (CDDL) Version 1.0
1. Definitions.
1.1. Contributor means each individual or entity that creates or contributes to the creation of Modifications.
1.2. Contributor Version means the combination of the Original Software, prior Modifications used by a Contributor (if any), and the Modifications made by that particular Contributor.
1.3. Covered Software means (a) the Original Software, or (b) Modifications, or (c) the combination of files containing Original Software with files containing Modifications, in each case including portions thereof.
1.4. Executable means the Covered Software in any form other than Source Code.
1.5. Initial Developer means the individual or entity that first makes Original Software available under this License.
1.6. Larger Work means a work which combines Covered Software or portions thereof with code not governed by the terms of this License.
1.7. License means this document.
1.8. Licensable means having the right to grant, to the maximum extent possible, whether at the time of the initial grant or subsequently acquired, any and all of the rights conveyed herein.
1.9. Modifications means the Source Code and Executable form of any of the following:
A. Any file that results from an addition to, deletion from or modification of the contents of a file containing Original Software or previous Modifications;
B. Any new file that contains any part of the Original Software or previous Modification; or
C. Any new file that is contributed or otherwise made available under the terms of this License.
1.10. Original Software means the Source Code and Executable form of computer software code that is originally released under this License.
1.11. Patent Claims means any patent claim(s), now owned or hereafter acquired, including without limitation, method, process, and apparatus claims, in any patent Licensable by grantor.
1.12. Source Code means (a) the common form of computer software code in which modifications are made and (b) associated documentation included in or with such code.
1.13. You (or Your) means an individual or a legal entity exercising rights under, and complying with all of the terms of, this License. For legal entities, You includes any entity which controls, is controlled by, or is under common control with You. For purposes of this definition, control means (a)<29>the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (b)<29>ownership of more than fifty percent (50%) of the outstanding shares or beneficial ownership of such entity.
2. License Grants.
2.1. The Initial Developer Grant.
Conditioned upon Your compliance with Section 3.1 below and subject to third party intellectual property claims, the Initial Developer hereby grants You a world-wide, royalty-free, non-exclusive license:
(a) under intellectual property rights (other than patent or trademark) Licensable by Initial Developer, to use, reproduce, modify, display, perform, sublicense and distribute the Original Software (or portions thereof), with or without Modifications, and/or as part of a Larger Work; and
(b) under Patent Claims infringed by the making, using or selling of Original Software, to make, have made, use, practice, sell, and offer for sale, and/or otherwise dispose of the Original Software (or portions thereof).
(c) The licenses granted in Sections<6E>2.1(a) and (b) are effective on the date Initial Developer first distributes or otherwise makes the Original Software available to a third party under the terms of this License.
(d) Notwithstanding Section<6F>2.1(b) above, no patent license is granted: (1)<29>for code that You delete from the Original Software, or (2)<29>for infringements caused by: (i)<29>the modification of the Original Software, or (ii)<29>the combination of the Original Software with other software or devices.
2.2. Contributor Grant.
Conditioned upon Your compliance with Section 3.1 below and subject to third party intellectual property claims, each Contributor hereby grants You a world-wide, royalty-free, non-exclusive license:
(a) under intellectual property rights (other than patent or trademark) Licensable by Contributor to use, reproduce, modify, display, perform, sublicense and distribute the Modifications created by such Contributor (or portions thereof), either on an unmodified basis, with other Modifications, as Covered Software and/or as part of a Larger Work; and
(b) under Patent Claims infringed by the making, using, or selling of Modifications made by that Contributor either alone and/or in combination with its Contributor Version (or portions of such combination), to make, use, sell, offer for sale, have made, and/or otherwise dispose of: (1)<29>Modifications made by that Contributor (or portions thereof); and (2)<29>the combination of Modifications made by that Contributor with its Contributor Version (or portions of such combination).
(c) The licenses granted in Sections<6E>2.2(a) and 2.2(b) are effective on the date Contributor first distributes or otherwise makes the Modifications available to a third party.
(d) Notwithstanding Section<6F>2.2(b) above, no patent license is granted: (1)<29>for any code that Contributor has deleted from the Contributor Version; (2)<29>for infringements caused by: (i)<29>third party modifications of Contributor Version, or (ii)<29>the combination of Modifications made by that Contributor with other software (except as part of the Contributor Version) or other devices; or (3)<29>under Patent Claims infringed by Covered Software in the absence of Modifications made by that Contributor.
3. Distribution Obligations.
3.1. Availability of Source Code.
Any Covered Software that You distribute or otherwise make available in Executable form must also be made available in Source Code form and that Source Code form must be distributed only under the terms of this License. You must include a copy of this License with every copy of the Source Code form of the Covered Software You distribute or otherwise make available. You must inform recipients of any such Covered Software in Executable form as to how they can obtain such Covered Software in Source Code form in a reasonable manner on or through a medium customarily used for software exchange.
3.2. Modifications.
The Modifications that You create or to which You contribute are governed by the terms of this License. You represent that You believe Your Modifications are Your original creation(s) and/or You have sufficient rights to grant the rights conveyed by this License.
3.3. Required Notices.
You must include a notice in each of Your Modifications that identifies You as the Contributor of the Modification. You may not remove or alter any copyright, patent or trademark notices contained within the Covered Software, or any notices of licensing or any descriptive text giving attribution to any Contributor or the Initial Developer.
3.4. Application of Additional Terms.
You may not offer or impose any terms on any Covered Software in Source Code form that alters or restricts the applicable version of this License or the recipients rights hereunder. You may choose to offer, and to charge a fee for, warranty, support, indemnity or liability obligations to one or more recipients of Covered Software. However, you may do so only on Your own behalf, and not on behalf of the Initial Developer or any Contributor. You must make it absolutely clear that any such warranty, support, indemnity or liability obligation is offered by You alone, and You hereby agree to indemnify the Initial Developer and every Contributor for any liability incurred by the Initial Developer or such Contributor as a result of warranty, support, indemnity or liability terms You offer.
3.5. Distribution of Executable Versions.
You may distribute the Executable form of the Covered Software under the terms of this License or under the terms of a license of Your choice, which may contain terms different from this License, provided that You are in compliance with the terms of this License and that the license for the Executable form does not attempt to limit or alter the recipients rights in the Source Code form from the rights set forth in this License. If You distribute the Covered Software in Executable form under a different license, You must make it absolutely clear that any terms which differ from this License are offered by You alone, not by the Initial Developer or Contributor. You hereby agree to indemnify the Initial Developer and every Contributor for any liability incurred by the Initial Developer or such Contributor as a result of any such terms You offer.
3.6. Larger Works.
You may create a Larger Work by combining Covered Software with other code not governed by the terms of this License and distribute the Larger Work as a single product. In such a case, You must make sure the requirements of this License are fulfilled for the Covered Software.
4. Versions of the License.
4.1. New Versions.
Sun Microsystems, Inc. is the initial license steward and may publish revised and/or new versions of this License from time to time. Each version will be given a distinguishing version number. Except as provided in Section 4.3, no one other than the license steward has the right to modify this License.
4.2. Effect of New Versions.
You may always continue to use, distribute or otherwise make the Covered Software available under the terms of the version of the License under which You originally received the Covered Software. If the Initial Developer includes a notice in the Original Software prohibiting it from being distributed or otherwise made available under any subsequent version of the License, You must distribute and make the Covered Software available under the terms of the version of the License under which You originally received the Covered Software. Otherwise, You may also choose to use, distribute or otherwise make the Covered Software available under the terms of any subsequent version of the License published by the license steward.
4.3. Modified Versions.
When You are an Initial Developer and You want to create a new license for Your Original Software, You may create and use a modified version of this License if You: (a)<29>rename the license and remove any references to the name of the license steward (except to note that the license differs from this License); and (b)<29>otherwise make it clear that the license contains terms which differ from this License.
5. DISCLAIMER OF WARRANTY.
COVERED SOFTWARE IS PROVIDED UNDER THIS LICENSE ON AN AS IS BASIS, WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, WARRANTIES THAT THE COVERED SOFTWARE IS FREE OF DEFECTS, MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE OR NON-INFRINGING. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE COVERED SOFTWARE IS WITH YOU. SHOULD ANY COVERED SOFTWARE PROVE DEFECTIVE IN ANY RESPECT, YOU (NOT THE INITIAL DEVELOPER OR ANY OTHER CONTRIBUTOR) ASSUME THE COST OF ANY NECESSARY SERVICING, REPAIR OR CORRECTION. THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. NO USE OF ANY COVERED SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER THIS DISCLAIMER.
6. TERMINATION.
6.1. This License and the rights granted hereunder will terminate automatically if You fail to comply with terms herein and fail to cure such breach within 30 days of becoming aware of the breach. Provisions which, by their nature, must remain in effect beyond the termination of this License shall survive.
6.2. If You assert a patent infringement claim (excluding declaratory judgment actions) against Initial Developer or a Contributor (the Initial Developer or Contributor against whom You assert such claim is referred to as Participant) alleging that the Participant Software (meaning the Contributor Version where the Participant is a Contributor or the Original Software where the Participant is the Initial Developer) directly or indirectly infringes any patent, then any and all rights granted directly or indirectly to You by such Participant, the Initial Developer (if the Initial Developer is not the Participant) and all Contributors under Sections<6E>2.1 and/or 2.2 of this License shall, upon 60 days notice from Participant terminate prospectively and automatically at the expiration of such 60 day notice period, unless if within such 60 day period You withdraw Your claim with respect to the Participant Software against such Participant either unilaterally or pursuant to a written agreement with Participant.
6.3. In the event of termination under Sections<6E>6.1 or 6.2 above, all end user licenses that have been validly granted by You or any distributor hereunder prior to termination (excluding licenses granted to You by any distributor) shall survive termination.
7. LIMITATION OF LIABILITY.
UNDER NO CIRCUMSTANCES AND UNDER NO LEGAL THEORY, WHETHER TORT (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, SHALL YOU, THE INITIAL DEVELOPER, ANY OTHER CONTRIBUTOR, OR ANY DISTRIBUTOR OF COVERED SOFTWARE, OR ANY SUPPLIER OF ANY OF SUCH PARTIES, BE LIABLE TO ANY PERSON FOR ANY INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES OF ANY CHARACTER INCLUDING, WITHOUT LIMITATION, DAMAGES FOR LOST PROFITS, LOSS OF GOODWILL, WORK STOPPAGE, COMPUTER FAILURE OR MALFUNCTION, OR ANY AND ALL OTHER COMMERCIAL DAMAGES OR LOSSES, EVEN IF SUCH PARTY SHALL HAVE BEEN INFORMED OF THE POSSIBILITY OF SUCH DAMAGES. THIS LIMITATION OF LIABILITY SHALL NOT APPLY TO LIABILITY FOR DEATH OR PERSONAL INJURY RESULTING FROM SUCH PARTYS NEGLIGENCE TO THE EXTENT APPLICABLE LAW PROHIBITS SUCH LIMITATION. SOME JURISDICTIONS DO NOT ALLOW THE EXCLUSION OR LIMITATION OF INCIDENTAL OR CONSEQUENTIAL DAMAGES, SO THIS EXCLUSION AND LIMITATION MAY NOT APPLY TO YOU.
8. U.S. GOVERNMENT END USERS.
The Covered Software is a commercial item, as that term is defined in 48<34>C.F.R.<2E>2.101 (Oct. 1995), consisting of commercial computer software (as that term is defined at 48 C.F.R. <20>252.227-7014(a)(1)) and commercial computer software documentation as such terms are used in 48<34>C.F.R.<2E>12.212 (Sept. 1995). Consistent with 48 C.F.R. 12.212 and 48 C.F.R. 227.7202-1 through 227.7202-4 (June 1995), all U.S. Government End Users acquire Covered Software with only those rights set forth herein. This U.S. Government Rights clause is in lieu of, and supersedes, any other FAR, DFAR, or other clause or provision that addresses Government rights in computer software under this License.
9. MISCELLANEOUS.
This License represents the complete agreement concerning subject matter hereof. If any provision of this License is held to be unenforceable, such provision shall be reformed only to the extent necessary to make it enforceable. This License shall be governed by the law of the jurisdiction specified in a notice contained within the Original Software (except to the extent applicable law, if any, provides otherwise), excluding such jurisdictions conflict-of-law provisions. Any litigation relating to this License shall be subject to the jurisdiction of the courts located in the jurisdiction and venue specified in a notice contained within the Original Software, with the losing party responsible for costs, including, without limitation, court costs and reasonable attorneys fees and expenses. The application of the United Nations Convention on Contracts for the International Sale of Goods is expressly excluded. Any law or regulation which provides that the language of a contract shall be construed against the drafter shall not apply to this License. You agree that You alone are responsible for compliance with the United States export administration regulations (and the export control laws and regulation of any other countries) when You use, distribute or otherwise make available any Covered Software.
10. RESPONSIBILITY FOR CLAIMS.
As between Initial Developer and the Contributors, each party is responsible for claims and damages arising, directly or indirectly, out of its utilization of rights under this License and You agree to work with Initial Developer and Contributors to distribute such responsibility on an equitable basis. Nothing herein is intended or shall be deemed to constitute any admission of liability.
NOTICE PURSUANT TO SECTION 9 OF THE COMMON DEVELOPMENT AND DISTRIBUTION LICENSE (CDDL)
The GlassFish code released under the CDDL shall be governed by the laws of the State of California (excluding conflict-of-law provisions). Any litigation relating to this License shall be subject to the jurisdiction of the Federal Courts of the Northern District of California and the state courts of the State of California, with venue lying in Santa Clara County, California.
===================
serp-1.11.0.jar
===================
Copyright (c) 2002-2006, A. Abram White
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of 'serp' nor the names of its contributors may
be used to endorse or promote products derived from this software without
specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

View File

@ -0,0 +1,16 @@
Manifest-Version: 1.0
Bundle-ManifestVersion: 2
Bundle-Name: OpenJPA Eclipse Plug-in
Bundle-SymbolicName: org.apache.openjpa.eclipse; singleton:=true
Bundle-Version: 1.0.0.qualifier
Bundle-Activator: org.apache.openjpa.eclipse.Activator
Require-Bundle: org.eclipse.ui,
org.eclipse.core.runtime,
org.eclipse.core.resources,
org.apache.openjpa,
org.eclipse.jdt.core;bundle-version="3.3",
org.eclipse.jdt.launching;bundle-version="3.3"
Bundle-ClassPath: .
Eclipse-LazyStart: true
Bundle-RequiredExecutionEnvironment: JavaSE-1.6
Import-Package: org.apache.commons.lang

View File

@ -0,0 +1,21 @@
=========================================================================
== NOTICE file corresponding to the section 4 d of ==
== the Apache License, Version 2.0, ==
== in this case for the Apache OpenJPA distribution. ==
=========================================================================
This product includes software developed by
The Apache Software Foundation (http://www.apache.org/).
COPYRIGHT NOTICES
* OpenJPA includes software developed by the SERP project
Copyright (c) 2002-2006, A. Abram White. All rights reserved.
* OpenJPA is bundled with the binaries from the JPA specification, by
Sun Microsystems and licensed under the CDDL 1.0. The source code is
available at: https://glassfish.dev.java.net/source/browse/glassfish/
* OpenJPA includes software written by Miroslav Nachev
* OpenJPA uses test code written by Charles Tillman.

View File

@ -0,0 +1,50 @@
These are some rough notes on what kind of doc should be written up on some e.g. Wiki page once this is accepted and published:
* Installation
* Usage
* Configuration via .project:
<buildCommand>
<name>org.apache.openjpa.eclipse.OpenJPAEnhancerBuilder</name>
<arguments>
<dictionary>
<key>debugLogs</key>
<value>false</value>
</dictionary>
<dictionary>
<key>include1</key>
<value>**/*Entity.class</value>
</dictionary>
<dictionary>
<key>include2</key>
<value>**/*EntityRef.class</value>
</dictionary>
* debugLogs true causes stuff to show up in the Error Log view, but it
seems to slow things down and something goes wrong with the Progress view and the Monitor stuff,
it doesn't update correctly anymore, and keeps running. So only intended for investigating problems.
* DOC: No support for persistence.xml, only based on @Entity Annotations
* see http://people.apache.org/~ppoddar/eclipse/
* FAQ / Troubleshooting
* something like "-XX:PermSize=64m -XX:MaxPermSize=256m -Xms128m -Xmx512m" is typically needed...
* OpenJPA documentation chapter on enhancement should reference this plug-in/doc?
* Link from http://webspherepersistence.blogspot.com/2009/02/openjpa-enhancement.html
* Known Limitations / Ideas for Extensions
* persistence.xml instead annotations
* Builder must not run on / skip classes which are red / have other compilation issues.. (is there a .class file in these cases? apparently.. or is that a left-over?)
* Error Marker is on .class resource (normal..), how can we make it on the 'corresponding' (?) .java instead?
* Adding supported enhancement flags (e.g. -addDefaultConstructor etc.) in a preference page.
Michael Vorburger, 3.12.2009

View File

@ -0,0 +1,6 @@
source.. = src/main/java/
output.. = target/classes/
bin.includes = plugin.xml,\
META-INF/,\
.
src.includes = src/

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,39 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<launchConfiguration type="org.eclipse.pde.ui.JunitLaunchConfig">
<booleanAttribute key="append.args" value="true"/>
<booleanAttribute key="askclear" value="false"/>
<booleanAttribute key="automaticAdd" value="true"/>
<booleanAttribute key="automaticValidate" value="true"/>
<stringAttribute key="bootstrap" value=""/>
<stringAttribute key="checked" value="[NONE]"/>
<booleanAttribute key="clearConfig" value="true"/>
<booleanAttribute key="clearws" value="false"/>
<booleanAttribute key="clearwslog" value="false"/>
<stringAttribute key="configLocation" value="${workspace_loc}/.metadata/.plugins/org.eclipse.pde.core/pde-junit"/>
<booleanAttribute key="default" value="true"/>
<booleanAttribute key="includeOptional" value="true"/>
<stringAttribute key="location" value="${workspace_loc:openjpa-eclipse/src/test/junit-workspace}"/>
<listAttribute key="org.eclipse.debug.core.MAPPED_RESOURCE_PATHS">
<listEntry value="/openjpa-eclipse"/>
</listAttribute>
<listAttribute key="org.eclipse.debug.core.MAPPED_RESOURCE_TYPES">
<listEntry value="4"/>
</listAttribute>
<booleanAttribute key="org.eclipse.debug.core.appendEnvironmentVariables" value="true"/>
<stringAttribute key="org.eclipse.jdt.junit.CONTAINER" value="=openjpa-eclipse"/>
<booleanAttribute key="org.eclipse.jdt.junit.KEEPRUNNING_ATTR" value="false"/>
<stringAttribute key="org.eclipse.jdt.junit.TESTNAME" value=""/>
<stringAttribute key="org.eclipse.jdt.junit.TEST_KIND" value="org.eclipse.jdt.junit.loader.junit3"/>
<stringAttribute key="org.eclipse.jdt.launching.MAIN_TYPE" value=""/>
<stringAttribute key="org.eclipse.jdt.launching.PROGRAM_ARGUMENTS" value="-os ${target.os} -ws ${target.ws} -arch ${target.arch} -nl ${target.nl}"/>
<stringAttribute key="org.eclipse.jdt.launching.PROJECT_ATTR" value="openjpa-eclipse"/>
<stringAttribute key="org.eclipse.jdt.launching.SOURCE_PATH_PROVIDER" value="org.eclipse.pde.ui.workbenchClasspathProvider"/>
<stringAttribute key="org.eclipse.jdt.launching.VM_ARGUMENTS" value="-Xms128m -Xmx512m -XX:PermSize=64m -XX:MaxPermSize=256m"/>
<stringAttribute key="pde.version" value="3.3"/>
<stringAttribute key="product" value="org.eclipse.platform.ide"/>
<booleanAttribute key="show_selected_only" value="false"/>
<booleanAttribute key="tracing" value="false"/>
<booleanAttribute key="useDefaultConfig" value="true"/>
<booleanAttribute key="useDefaultConfigArea" value="false"/>
<booleanAttribute key="useProduct" value="true"/>
</launchConfiguration>

View File

@ -0,0 +1,57 @@
<?xml version="1.0" encoding="UTF-8"?>
<?eclipse version="3.2"?>
<plugin>
<extension
id="OpenJPAEnhancerBuilder"
name="OpenJPA PC-Enhancer Project Builder"
point="org.eclipse.core.resources.builders">
<builder
hasNature="true">
<run
class="org.apache.openjpa.eclipse.OpenJPAEnhancerBuilder">
</run>
</builder>
</extension>
<extension
id="OpenJPANature"
name="OpenJPA Project Nature"
point="org.eclipse.core.resources.natures">
<runtime>
<run
class="org.apache.openjpa.eclipse.OpenJPANature">
</run>
</runtime>
<builder
id="org.apache.openjpa.eclipse.OpenJPAEnhancerBuilder">
</builder>
</extension>
<extension
point="org.eclipse.ui.popupMenus">
<objectContribution
adaptable="true"
objectClass="org.eclipse.core.resources.IProject"
nameFilter="*"
id="org.apache.openjpa.eclipse.contribution1">
<action
label="Add/Remove OpenJPA Builder"
class="org.apache.openjpa.eclipse.ToggleNatureAction"
menubarPath="additions"
enablesFor="+"
id="org.apache.openjpa.eclipse.addRemoveNatureAction">
</action>
</objectContribution>
</extension>
<extension
id="openJPAEnhancementProblem"
name="OpenJPA Enhancement Problem"
point="org.eclipse.core.resources.markers">
<super
type="org.eclipse.core.resources.problemmarker">
</super>
<persistent
value="true">
</persistent>
</extension>
</plugin>

View File

@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<project>
<modelVersion>4.0.0</modelVersion>
<parent>
<artifactId>org.apache.openjpa.eclipse.all</artifactId>
<groupId>org.apache.openjpa.eclipse</groupId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<groupId>org.apache.openjpa.eclipse</groupId>
<artifactId>org.apache.openjpa.eclipse</artifactId>
<version>1.0.0</version>
<packaging>eclipse-plugin</packaging>
</project>

View File

@ -0,0 +1,80 @@
/*
* Copyright 2002-2009 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.openjpa.eclipse;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.ui.plugin.AbstractUIPlugin;
import org.osgi.framework.BundleContext;
/**
* The activator class controls the plug-in life cycle
*
* @author Eclipse PDE Example Wizard! ;-)
* @author Michael Vorburger (MVO)
*/
public class Activator extends AbstractUIPlugin {
// The plug-in ID
public static final String PLUGIN_ID = "org.apache.openjpa.eclipse";
// The shared instance
private static Activator plugin;
/**
* The constructor
*/
public Activator() {
}
/*
* (non-Javadoc)
* @see org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext)
*/
public void start(BundleContext context) throws Exception {
super.start(context);
plugin = this;
}
/*
* (non-Javadoc)
* @see org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext)
*/
public void stop(BundleContext context) throws Exception {
plugin = null;
super.stop(context);
}
/**
* Returns the shared instance
*
* @return the shared instance
*/
public static Activator getDefault() {
return plugin;
}
/**
* Returns an image descriptor for the image file at the given
* plug-in relative path
*
* @param path the path
* @return the image descriptor
*/
public static ImageDescriptor getImageDescriptor(String path) {
return imageDescriptorFromPlugin(PLUGIN_ID, path);
}
}

View File

@ -0,0 +1,31 @@
/*
* Copyright 2002-2009 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.openjpa.eclipse;
import org.apache.openjpa.eclipse.util.PathMatcherUtil;
/**
* Helper class to pass through "options" (read from the project.xml) in the builder.
*
* @author Michael Vorburger
*/
public class BuilderOptions {
public PathMatcherUtil pathMatcher;
public boolean isVerboseLoggingEnabled;
}

View File

@ -0,0 +1,295 @@
/*
* Copyright 2002-2009 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.openjpa.eclipse;
import java.io.File;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import org.apache.openjpa.eclipse.util.ClassLoaderFromIProjectHelper;
import org.apache.openjpa.eclipse.util.LogUtil;
import org.apache.openjpa.eclipse.util.PCEnhancerHelper;
import org.apache.openjpa.eclipse.util.PCEnhancerHelperImpl;
import org.apache.openjpa.eclipse.util.PathMatcherUtil;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IMarker;
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.IResourceVisitor;
import org.eclipse.core.resources.IncrementalProjectBuilder;
import org.eclipse.core.runtime.CoreException;
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.SubMonitor;
/**
* Builder for the OpenJPA PCEnhancer.
*
* @see org.apache.openjpa.enhance.PCEnhancer
*
* @author Eclipse PDE Example Wizard! ;-)
* @author Michael Vorburger (MVO)
*/
public class OpenJPAEnhancerBuilder extends IncrementalProjectBuilder {
public static final String BUILDER_ID = "org.apache.openjpa.eclipse.OpenJPAEnhancerBuilder";
private static final String MARKER_TYPE = "org.apache.openjpa.eclipse.openJPAEnhancementProblem";
private class MyIncrementalBuildResourceDeltaVisitor implements IResourceDeltaVisitor {
private final IProgressMonitor monitor;
private final PCEnhancerHelper enhancerHelper;
private final BuilderOptions opts;
public MyIncrementalBuildResourceDeltaVisitor(IProgressMonitor monitor, PCEnhancerHelper enhancerHelper, BuilderOptions opts) {
this.monitor = monitor;
this.enhancerHelper = enhancerHelper;
this.opts = opts;
}
public boolean visit(IResourceDelta delta) throws CoreException {
// better do NOT use monitor.worked() & monitor.subTask() here, as this is fast enough and any UI will only slow it down
IResource resource = delta.getResource();
switch (delta.getKind()) {
// If Added or Changed, handle changed resource:
case IResourceDelta.ADDED:
case IResourceDelta.CHANGED:
if (needsEnhancement(resource, opts)) {
if (enhance(resource, this.enhancerHelper, opts)) {
delta.getResource().refreshLocal(IResource.DEPTH_ZERO, monitor);
}
}
break;
// If Removed, nothing to do:
case IResourceDelta.REMOVED:
break;
}
// return true to continue visiting children
return true;
}
}
private class MyFullBuildResourceVisitor implements IResourceVisitor {
private final IProgressMonitor monitor;
private final List<IResource> list = new LinkedList<IResource>();
private final BuilderOptions opts;
public MyFullBuildResourceVisitor(IProgressMonitor monitor, BuilderOptions opts) {
this.monitor = monitor;
this.opts = opts;
}
public boolean visit(IResource resource) throws CoreException {
// NO monitor.worked(1);
if (needsEnhancement(resource, opts))
list.add(resource);
checkCancel(monitor);
// return true to continue visiting children
return true;
}
List<IResource> getResourcesPotentiallyNeedingEnhancement() {
return list;
}
}
@Override
@SuppressWarnings("unchecked")
protected IProject[] build(int kind, Map args, IProgressMonitor monitor) throws CoreException {
BuilderOptions opts = new BuilderOptions();
opts.pathMatcher = new PathMatcherUtil(args);
opts.isVerboseLoggingEnabled = isFullLoggingEnabled(args);
if (kind == FULL_BUILD) {
fullBuild(monitor, opts);
} else {
IResourceDelta delta = getDelta(getProject());
if (delta == null) {
fullBuild(monitor, opts);
} else {
incrementalBuild(delta, monitor, opts);
}
}
return null;
}
private void fullBuild(final IProgressMonitor monitor, BuilderOptions opts) throws CoreException {
long startTime = System.currentTimeMillis();
monitor.subTask("OpenJPA Enhancement... (Full Build, collecting resources)");
MyFullBuildResourceVisitor visitor = new MyFullBuildResourceVisitor(monitor, opts);
getProject().accept(visitor);
long duration = System.currentTimeMillis() - startTime;
if (opts.isVerboseLoggingEnabled)
LogUtil.logOK("OpenJPA Enhancement (Full Build, collecting resources) took "
+ duration + "ms, found " + visitor.getResourcesPotentiallyNeedingEnhancement().size()
+ " classes potentially needing enhancement");
List<IResource> resources = visitor.getResourcesPotentiallyNeedingEnhancement();
if (!resources.isEmpty()) {
SubMonitor subMonitor = SubMonitor.convert(monitor, "OpenJPA Enhancement... (Full Build, actual bytecode work)", resources.size());
try {
int actuallyEnhanced = 0;
startTime = System.currentTimeMillis();
ClassLoader classLoader = ClassLoaderFromIProjectHelper.createClassLoader(getProject());
PCEnhancerHelper enhancerHelper = new PCEnhancerHelperImpl(classLoader);
for (IResource resource : resources) {
subMonitor.subTask("OpenJPA Enhancement... (Full Build, enhancing " + resource.getName() + ")");
checkCancel(subMonitor);
if (enhance(resource, enhancerHelper, opts)) {
++actuallyEnhanced;
}
subMonitor.worked(1);
}
duration = System.currentTimeMillis() - startTime;
if (opts.isVerboseLoggingEnabled)
LogUtil.logOK("OpenJPA Enhancement (Full Build) took " + duration + "ms, for " + resources.size()
+ " potential classes, of which " + actuallyEnhanced + " were actually enhanced");
} finally {
// LogUtil.logInfo("OpenJPA Enhancement (Full Build) will now cause a full project refresh");
getProject().refreshLocal(IResource.DEPTH_INFINITE, subMonitor.newChild(1));
// LogUtil.logOK("OpenJPA Enhancement (Full Build) completely done (after refresh), good bye.");
monitor.done();
}
}
}
private void incrementalBuild(IResourceDelta delta, IProgressMonitor monitor, BuilderOptions opts) throws CoreException {
monitor.subTask("OpenJPA Enhancement... (Incremental Build)");
try {
ClassLoader classLoader = ClassLoaderFromIProjectHelper.createClassLoader(getProject());
PCEnhancerHelper enhancerHelper = new PCEnhancerHelperImpl(classLoader);
delta.accept(new MyIncrementalBuildResourceDeltaVisitor(monitor, enhancerHelper, opts));
} finally {
monitor.done();
}
}
/**
* Check if a resource needs enhancement.
* Needs to be very fast, should NOT e.g. actually analyze any class files (do that later only).
* @param opts
*/
private boolean needsEnhancement(IResource resource, BuilderOptions opts) throws CoreException {
if (resource instanceof IFile && resource.getName().endsWith(".class")) {
IFile iFile = (IFile) resource;
String fileNameForLog = iFile.getFullPath().toString();
deleteMarkers(iFile);
if (!opts.pathMatcher.match(iFile.getLocation().toString())) {
if (opts.isVerboseLoggingEnabled) {
LogUtil.logInfo("OpenJPA Enhancer skipped class because it did not match pattern " + fileNameForLog );
}
return false;
}
return true;
} else {
return false;
}
}
private boolean enhance(IResource resource, PCEnhancerHelper enhancerHelper, BuilderOptions opts) throws CoreException {
IFile iFile = (IFile) resource;
String fileNameForLog = iFile.getFullPath().toString();
try {
File file = iFile.getLocation().toFile();
boolean hasEnhanced = enhancerHelper.enhance(file);
if (opts.isVerboseLoggingEnabled) {
if (hasEnhanced)
LogUtil.logInfo("OpenJPA Enhancer ran on and actually bytecode enhanced " + fileNameForLog);
else
LogUtil.logInfo("OpenJPA Enhancer ran on but did not have to bytecode enhance " + fileNameForLog);
}
return hasEnhanced;
} catch (Throwable e) {
String msg = "OpenJPA Enhancement Builder failed with message '" + e.toString() + "' for class: " + iFile.getLocation();
addMarkerAndThrowNewCoreException(iFile, msg, e);
return false;
}
}
/**
* Note that if full/verbose logging is enabled, which writes to that Error
* Log view, then something in Eclipse (3.4 at least) goes wrong with the
* Progress view and the Monitor stuff - it doesn't update correctly, and
* keeps running!
*/
private boolean isFullLoggingEnabled(Map<String, String> args) {
if (args.containsKey("debugLogs")) {
return "true".equalsIgnoreCase((String) args.get("debugLogs"));
}
return false;
}
private void addMarkerAndThrowNewCoreException(IFile iFile, String msg, Throwable e) throws CoreException {
addMarker(iFile, msg, 0, IMarker.SEVERITY_ERROR);
logAndThrowNewCoreException(msg, e);
}
private void logAndThrowNewCoreException(String msg, Throwable e) throws CoreException {
LogUtil.logError(msg, e);
IStatus status;
if (e != null) {
status = new Status(IStatus.ERROR, Activator.PLUGIN_ID, msg, e);
} else {
status = new Status(IStatus.ERROR, Activator.PLUGIN_ID, msg);
}
throw new CoreException(status);
}
private void addMarker(IFile file, String message, int lineNumber, int severity) {
try {
IMarker marker = file.createMarker(MARKER_TYPE);
marker.setAttribute(IMarker.MESSAGE, message);
marker.setAttribute(IMarker.SEVERITY, severity);
if (lineNumber == -1) {
lineNumber = 1;
}
marker.setAttribute(IMarker.LINE_NUMBER, lineNumber);
} catch (CoreException e) {
}
}
private void deleteMarkers(IFile file) {
try {
file.deleteMarkers(MARKER_TYPE, false, IResource.DEPTH_ZERO);
} catch (CoreException ce) {
}
}
private void checkCancel(IProgressMonitor monitor) {
// @see http://www.eclipse.org/articles/Article-Builders/builders.html
if (monitor.isCanceled()) {
// No monitor.done(); in example
forgetLastBuiltState(); // not sure if this is really necessary for us, but probably doesn't hurt?
throw new OperationCanceledException();
}
}
}

View File

@ -0,0 +1,102 @@
/*
* Copyright 2002-2009 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.openjpa.eclipse;
import org.eclipse.core.resources.ICommand;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IProjectDescription;
import org.eclipse.core.resources.IProjectNature;
import org.eclipse.core.runtime.CoreException;
/**
* Eclipse Nature for a Project with OpenJPA Builder.
*
* @author Eclipse PDE Example Wizard! ;-)
* @author Michael Vorburger (MVO)
*/
public class OpenJPANature implements IProjectNature {
/**
* ID of this project nature
*/
public static final String NATURE_ID = "org.apache.openjpa.eclipse.OpenJPANature";
private IProject project;
/*
* (non-Javadoc)
*
* @see org.eclipse.core.resources.IProjectNature#configure()
*/
public void configure() throws CoreException {
IProjectDescription desc = project.getDescription();
ICommand[] commands = desc.getBuildSpec();
for (int i = 0; i < commands.length; ++i) {
if (commands[i].getBuilderName().equals(OpenJPAEnhancerBuilder.BUILDER_ID)) {
return;
}
}
ICommand[] newCommands = new ICommand[commands.length + 1];
System.arraycopy(commands, 0, newCommands, 0, commands.length);
ICommand command = desc.newCommand();
command.setBuilderName(OpenJPAEnhancerBuilder.BUILDER_ID);
newCommands[newCommands.length - 1] = command;
desc.setBuildSpec(newCommands);
project.setDescription(desc, null);
}
/*
* (non-Javadoc)
*
* @see org.eclipse.core.resources.IProjectNature#deconfigure()
*/
public void deconfigure() throws CoreException {
IProjectDescription description = getProject().getDescription();
ICommand[] commands = description.getBuildSpec();
for (int i = 0; i < commands.length; ++i) {
if (commands[i].getBuilderName().equals(OpenJPAEnhancerBuilder.BUILDER_ID)) {
ICommand[] newCommands = new ICommand[commands.length - 1];
System.arraycopy(commands, 0, newCommands, 0, i);
System.arraycopy(commands, i + 1, newCommands, i,
commands.length - i - 1);
description.setBuildSpec(newCommands);
return;
}
}
}
/*
* (non-Javadoc)
*
* @see org.eclipse.core.resources.IProjectNature#getProject()
*/
public IProject getProject() {
return project;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.core.resources.IProjectNature#setProject(org.eclipse.core.resources.IProject)
*/
public void setProject(IProject project) {
this.project = project;
}
}

View File

@ -0,0 +1,119 @@
/*
* Copyright 2002-2009 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.openjpa.eclipse;
import java.util.Iterator;
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.action.IAction;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.ui.IObjectActionDelegate;
import org.eclipse.ui.IWorkbenchPart;
/**
* Action to Add/Remove OpenJPA Project Nature.
*
* @author Eclipse PDE Example Wizard! ;-)
* @author Michael Vorburger (MVO)
*/
public class ToggleNatureAction implements IObjectActionDelegate {
private ISelection selection;
/*
* (non-Javadoc)
*
* @see org.eclipse.ui.IActionDelegate#run(org.eclipse.jface.action.IAction)
*/
@SuppressWarnings("unchecked")
public void run(IAction action) {
if (selection instanceof IStructuredSelection) {
for (Iterator it = ((IStructuredSelection) selection).iterator(); it
.hasNext();) {
Object element = it.next();
IProject project = null;
if (element instanceof IProject) {
project = (IProject) element;
} else if (element instanceof IAdaptable) {
project = (IProject) ((IAdaptable) element)
.getAdapter(IProject.class);
}
if (project != null) {
toggleNature(project);
}
}
}
}
/*
* (non-Javadoc)
*
* @see org.eclipse.ui.IActionDelegate#selectionChanged(org.eclipse.jface.action.IAction,
* org.eclipse.jface.viewers.ISelection)
*/
public void selectionChanged(IAction action, ISelection selection) {
this.selection = selection;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.ui.IObjectActionDelegate#setActivePart(org.eclipse.jface.action.IAction,
* org.eclipse.ui.IWorkbenchPart)
*/
public void setActivePart(IAction action, IWorkbenchPart targetPart) {
}
/**
* Toggles sample nature on a project
*
* @param project
* to have sample nature added or removed
*/
private void toggleNature(IProject project) {
try {
IProjectDescription description = project.getDescription();
String[] natures = description.getNatureIds();
for (int i = 0; i < natures.length; ++i) {
if (OpenJPANature.NATURE_ID.equals(natures[i])) {
// Remove the nature
String[] newNatures = new String[natures.length - 1];
System.arraycopy(natures, 0, newNatures, 0, i);
System.arraycopy(natures, i + 1, newNatures, i,
natures.length - i - 1);
description.setNatureIds(newNatures);
project.setDescription(description, null);
return;
}
}
// Add the nature
String[] newNatures = new String[natures.length + 1];
System.arraycopy(natures, 0, newNatures, 0, natures.length);
newNatures[natures.length] = OpenJPANature.NATURE_ID;
description.setNatureIds(newNatures);
project.setDescription(description, null);
} catch (CoreException e) {
}
}
}

View File

@ -0,0 +1,60 @@
/*
* Copyright 2002-2009 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.openjpa.eclipse.util;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import org.apache.openjpa.eclipse.Activator;
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.jdt.core.IJavaProject;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.launching.JavaRuntime;
/**
* Helper to get a ClassLoader from an Eclipse IProject.
*
* @author Kai Kreuzer
* @author Michael Vorburger
*/
public class ClassLoaderFromIProjectHelper {
public static ClassLoader createClassLoader(IProject project) throws CoreException {
IJavaProject javaProject = JavaCore.create(project);
String[] classPath = JavaRuntime.computeDefaultRuntimeClassPath(javaProject);
URL[] urls = new URL[classPath.length];
for(int i=0;i<classPath.length;i++) {
try {
String urlString = "file:///" + classPath[i].replace('\\', '/');
// make sure that directory URLs end with a slash as they are otherwise not
// treated as directories but as libraries by the URLClassLoader
if(!classPath[i].endsWith(".jar") && !classPath[i].endsWith("/")) urlString += "/";
urls[i] = new URL(urlString);
} catch (MalformedURLException e) {
throw new CoreException(new Status(IStatus.ERROR, Activator.PLUGIN_ID,
"Could not resolve classpath correctly.", e));
}
}
return URLClassLoader.newInstance(urls);
}
}

View File

@ -0,0 +1,59 @@
/*
* Copyright 2002-2009 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.openjpa.eclipse.util;
import org.apache.openjpa.lib.log.AbstractLog;
import org.apache.openjpa.lib.log.Log;
import org.apache.openjpa.lib.log.LogFactory;
/**
* An OpenJPA LogFactory which logs using the Eclipse logging stuff.
*
* @see LogFactory
* @see LogUtil
*
* @author Michael Vorburger
*/
public class EclipseLogFactory implements LogFactory {
/**
* @see http://openjpa.apache.org/builds/latest/docs/manual/ref_guide_logging_custom.html
*
* @see org.apache.openjpa.lib.log.LogFactory#getLog(java.lang.String)
*/
public Log getLog(String channel) {
return new AbstractLog() {
protected boolean isEnabled(short logLevel) {
// log all levels
return true;
}
protected void log(short type, String message, Throwable t) {
if (type == Log.ERROR || type == Log.FATAL)
LogUtil.logError("OpenJPA Error: " + message, t);
if (type == Log.WARN)
LogUtil.logWarn("OpenJPA Warning: " + message, t);
// Ignore other internal messages... could be made this configurable via Builder argument (like include pattern), if really needed
// else
// LogUtil.logInfo("OpenJPA Info: " + message, t);
}
};
}
}

View File

@ -0,0 +1,62 @@
/*
* Copyright 2002-2009 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.openjpa.eclipse.util;
import org.apache.openjpa.eclipse.Activator;
import org.eclipse.core.runtime.Status;
/**
* Helper for Logging.
*
* @author Michael Vorburger
*/
public final class LogUtil {
private LogUtil() { };
public static void logOK(String msg) {
log(Status.OK, msg);
}
public static void logInfo(String msg) {
log(Status.INFO, msg);
}
public static void logInfo(String msg, Throwable t) {
log(Status.INFO, msg, t);
}
public static void logWarn(String msg, Throwable t) {
log(Status.WARNING, msg, t);
}
public static void logError(Throwable t) {
log(Status.ERROR, t.getMessage(), t);
}
public static void logError(String msg, Throwable t) {
log(Status.ERROR, msg, t);
}
private static void log(int status, String msg) {
Activator.getDefault().getLog().log(new Status(status, Activator.PLUGIN_ID, msg));
}
private static void log(int status, String msg, Throwable t) {
Activator.getDefault().getLog().log(new Status(status, Activator.PLUGIN_ID, msg, t));
}
}

View File

@ -0,0 +1,33 @@
/*
* Copyright 2002-2009 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.openjpa.eclipse.util;
import java.io.File;
import java.io.IOException;
import org.eclipse.core.runtime.CoreException;
/**
* Interface to an OpenJPA Persistence Capable Enhancer Helper implementation.
*
* @author Michael Vorburger
*/
public interface PCEnhancerHelper {
boolean enhance(File resource) throws CoreException, IOException, ClassNotFoundException;
}

View File

@ -0,0 +1,91 @@
/*
* Copyright 2002-2009 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.openjpa.eclipse.util;
import java.io.File;
import java.io.IOException;
import org.eclipse.core.runtime.CoreException;
/**
* PCEnhancerHelper implementation wrapping around the original
* PCEnhancerHelperImpl, but delegating lookup of the actual OpenJPA classes to
* a passed-in classloader (the one of the project).
*
* The idea is to use the OpenJPA JARs from the projects under enhancement, and
* in the future no longer bundle them in the plug-in. This way the plug-in is
* independent of the OpenJPA version. This is important as the enhancer
* implementation can change between OpenJPA versions, and the enhancer of the
* same OpenJPA version than the project has on it's classpath should naturally
* be used, not some fixed arbitrary version that happens to come with the
* plug-in.
*
* @author Michael Vorburger
*/
public class PCEnhancerHelperClassLoadingWrapper implements PCEnhancerHelper {
/*
* TODO PCEnhancerHelperClassLoadingWrapper does not yet work! FIXME!!!
* Thread.currentThread().setContextClassLoader seems to have no effect, how the h%#§ ??? ;-)
*/
private final ClassLoader classLoader;
private final PCEnhancerHelper delegateHelper;
public PCEnhancerHelperClassLoadingWrapper(ClassLoader classLoader) {
this.classLoader = new FunkyClassLoader(classLoader, Thread.currentThread().getContextClassLoader());
ClassLoader currentCL = Thread.currentThread().getContextClassLoader();
Thread.currentThread().setContextClassLoader(this.classLoader);
try {
delegateHelper = new PCEnhancerHelperImpl(classLoader);
} finally {
Thread.currentThread().setContextClassLoader(currentCL);
}
}
public boolean enhance(File resource) throws CoreException, IOException, ClassNotFoundException {
ClassLoader currentCL = Thread.currentThread().getContextClassLoader();
Thread.currentThread().setContextClassLoader(this.classLoader);
try {
return delegateHelper.enhance(resource);
} finally {
Thread.currentThread().setContextClassLoader(currentCL);
}
}
private static class FunkyClassLoader extends ClassLoader {
final private ClassLoader delegate;
final private ClassLoader cl;
public FunkyClassLoader(ClassLoader cl, ClassLoader delegate) {
this.cl = cl;
this.delegate = delegate;
}
// TODO Is it loadClass() or rather findClass() that needs overriding?
@Override
public Class<?> loadClass(String name) throws ClassNotFoundException {
try {
return cl.loadClass(name);
} catch(ClassNotFoundException e) {
return delegate.loadClass(name);
}
}
}
}

View File

@ -0,0 +1,114 @@
/*
* Copyright 2002-2009 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.openjpa.eclipse.util;
import java.io.File;
import java.io.IOException;
import java.util.Properties;
import javax.persistence.Embeddable;
import javax.persistence.Entity;
import javax.persistence.MappedSuperclass;
import org.apache.openjpa.conf.OpenJPAConfiguration;
import org.apache.openjpa.conf.OpenJPAConfigurationImpl;
import org.apache.openjpa.enhance.PCEnhancer;
import org.apache.openjpa.meta.ClassMetaData;
import org.apache.openjpa.meta.MetaDataRepository;
import org.apache.openjpa.persistence.ManagedInterface;
import org.eclipse.core.runtime.CoreException;
import serp.bytecode.Annotations;
import serp.bytecode.BCClass;
import serp.bytecode.Project;
/**
* OpenJPA Enhancer helper, for efficient invocation from an Eclipse builder.
*
* @author Pinaki Poddar
* @author Michael Vorburger (refactoring and extensions)
*/
public class PCEnhancerHelperImpl implements PCEnhancerHelper {
private final OpenJPAConfiguration conf;
private final MetaDataRepository repos;
private final ClassLoader loader;
// TODO, needed? private final ClassArgParser cap;
public PCEnhancerHelperImpl(ClassLoader classLoader) {
this.loader = classLoader;
conf = new OpenJPAConfigurationImpl();
Properties prop = new Properties();
prop.setProperty("openjpa.MetaDataFactory", "jpa");
prop.setProperty("openjpa.Log", EclipseLogFactory.class.getName());
conf.fromProperties(prop);
repos = conf.getMetaDataRepositoryInstance();
repos.setSourceMode(MetaDataRepository.MODE_META);
// TODO, needed? cap = conf.getMetaDataRepositoryInstance().getMetaDataFactory().newClassArgParser();
// cap.setClassLoader(loader);
}
/* (non-Javadoc)
* @see org.apache.openjpa.eclipse.util.PCEnhancerHelper#enhance(java.io.File)
*/
public boolean enhance(File resource) throws CoreException, IOException, ClassNotFoundException {
// No try/catch here - let Exception propagate upwards
// Eclipse will catch them and abandon Build and show cause in the Error Log
// Build should stop; if caught here, big projects with some set-up problem will appear to "hang".
// TODO, needed? cap.parseTypes(resource.getAbsolutePath().toString())
Project serp = new Project();
BCClass bcls = serp.loadClass(resource, loader);
if (!needsEnhance(bcls))
return false;
// Intentionally setting initializeClass to false;
// we do NOT want static class initialization to be executed during the builder!
Class<?> cls = Class.forName(bcls.getName(), false, loader);
repos.removeMetaData(cls);
ClassMetaData meta = repos.addMetaData(cls);
PCEnhancer delegate = new PCEnhancer(repos, bcls, meta);
int result = delegate.run();
if ((result != PCEnhancer.ENHANCE_NONE)
&& (result != PCEnhancer.ENHANCE_INTERFACE))
{
delegate.record();
return true;
} else {
return false;
}
}
private boolean needsEnhance(BCClass bcls) {
Annotations annos = bcls.getDeclaredRuntimeAnnotations(false);
if (annos == null)
return false;
return (annos.getAnnotation(Entity.class) != null
|| annos.getAnnotation(MappedSuperclass.class) != null
|| annos.getAnnotation(Embeddable.class) != null
|| annos.getAnnotation(ManagedInterface.class) != null);
}
}

View File

@ -0,0 +1,59 @@
/*
* Copyright 2002-2009 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.openjpa.eclipse.util;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.openjpa.eclipse.util.pathmatch.AntPathMatcher;
/**
* Util to check matching of Ant-style path patterns.
*
* @author Michael Vorburger (MVO)
*/
public class PathMatcherUtil {
private static final AntPathMatcher antPathMatcher = new AntPathMatcher();
private final List<String> includePatterns = new LinkedList<String>();
@SuppressWarnings("unchecked")
public PathMatcherUtil(Map args) {
if (args != null) {
Set<String> keys = args.keySet();
for (String key : keys) {
if (key.toLowerCase().startsWith("include")) {
includePatterns.add((String) args.get(key));
}
}
}
}
public boolean match(String fileName) {
if (includePatterns.isEmpty())
return true;
for (String includePattern : includePatterns) {
if (antPathMatcher.match(includePattern, fileName))
return true;
}
return false;
}
}

View File

@ -0,0 +1,419 @@
/*
* Copyright 2002-2009 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.openjpa.eclipse.util.pathmatch;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* PathMatcher implementation for Ant-style path patterns. Examples are provided below.
*
* <p>Part of this mapping code has been kindly borrowed from <a href="http://ant.apache.org">Apache Ant</a>.
*
* <p>The mapping matches URLs using the following rules:<br> <ul> <li>? matches one character</li> <li>* matches zero
* or more characters</li> <li>** matches zero or more 'directories' in a path</li> </ul>
*
* <p>Some examples:<br> <ul> <li><code>com/t?st.jsp</code> - matches <code>com/test.jsp</code> but also
* <code>com/tast.jsp</code> or <code>com/txst.jsp</code></li> <li><code>com/*.jsp</code> - matches all
* <code>.jsp</code> files in the <code>com</code> directory</li> <li><code>com/&#42;&#42;/test.jsp</code> - matches all
* <code>test.jsp</code> files underneath the <code>com</code> path</li> <li><code>org/springframework/&#42;&#42;/*.jsp</code>
* - matches all <code>.jsp</code> files underneath the <code>org/springframework</code> path</li>
* <li><code>org/&#42;&#42;/servlet/bla.jsp</code> - matches <code>org/springframework/servlet/bla.jsp</code> but also
* <code>org/springframework/testing/servlet/bla.jsp</code> and <code>org/servlet/bla.jsp</code></li> </ul>
*
* @author Alef Arendsen
* @author Juergen Hoeller
* @author Rob Harrop
* @author Arjen Poutsma
* @since 16.07.2003
*/
public class AntPathMatcher implements PathMatcher {
/** Default path separator: "/" */
public static final String DEFAULT_PATH_SEPARATOR = "/";
private String pathSeparator = DEFAULT_PATH_SEPARATOR;
/** Set the path separator to use for pattern parsing. Default is "/", as in Ant. */
public void setPathSeparator(String pathSeparator) {
this.pathSeparator = (pathSeparator != null ? pathSeparator : DEFAULT_PATH_SEPARATOR);
}
public boolean isPattern(String path) {
return (path.indexOf('*') != -1 || path.indexOf('?') != -1);
}
public boolean match(String pattern, String path) {
return doMatch(pattern, path, true, null);
}
public boolean matchStart(String pattern, String path) {
return doMatch(pattern, path, false, null);
}
/**
* Actually match the given <code>path</code> against the given <code>pattern</code>.
*
* @param pattern the pattern to match against
* @param path the path String to test
* @param fullMatch whether a full pattern match is required (else a pattern match as far as the given base path goes
* is sufficient)
* @return <code>true</code> if the supplied <code>path</code> matched, <code>false</code> if it didn't
*/
protected boolean doMatch(String pattern,
String path,
boolean fullMatch,
Map<String, String> uriTemplateVariables) {
if (path.startsWith(this.pathSeparator) != pattern.startsWith(this.pathSeparator)) {
return false;
}
String[] pattDirs = StringUtils.tokenizeToStringArray(pattern, this.pathSeparator);
String[] pathDirs = StringUtils.tokenizeToStringArray(path, this.pathSeparator);
int pattIdxStart = 0;
int pattIdxEnd = pattDirs.length - 1;
int pathIdxStart = 0;
int pathIdxEnd = pathDirs.length - 1;
// Match all elements up to the first **
while (pattIdxStart <= pattIdxEnd && pathIdxStart <= pathIdxEnd) {
String patDir = pattDirs[pattIdxStart];
if ("**".equals(patDir)) {
break;
}
if (!matchStrings(patDir, pathDirs[pathIdxStart], uriTemplateVariables)) {
return false;
}
pattIdxStart++;
pathIdxStart++;
}
if (pathIdxStart > pathIdxEnd) {
// Path is exhausted, only match if rest of pattern is * or **'s
if (pattIdxStart > pattIdxEnd) {
return (pattern.endsWith(this.pathSeparator) ? path.endsWith(this.pathSeparator) :
!path.endsWith(this.pathSeparator));
}
if (!fullMatch) {
return true;
}
if (pattIdxStart == pattIdxEnd && pattDirs[pattIdxStart].equals("*") && path.endsWith(this.pathSeparator)) {
return true;
}
for (int i = pattIdxStart; i <= pattIdxEnd; i++) {
if (!pattDirs[i].equals("**")) {
return false;
}
}
return true;
}
else if (pattIdxStart > pattIdxEnd) {
// String not exhausted, but pattern is. Failure.
return false;
}
else if (!fullMatch && "**".equals(pattDirs[pattIdxStart])) {
// Path start definitely matches due to "**" part in pattern.
return true;
}
// up to last '**'
while (pattIdxStart <= pattIdxEnd && pathIdxStart <= pathIdxEnd) {
String patDir = pattDirs[pattIdxEnd];
if (patDir.equals("**")) {
break;
}
if (!matchStrings(patDir, pathDirs[pathIdxEnd], uriTemplateVariables)) {
return false;
}
pattIdxEnd--;
pathIdxEnd--;
}
if (pathIdxStart > pathIdxEnd) {
// String is exhausted
for (int i = pattIdxStart; i <= pattIdxEnd; i++) {
if (!pattDirs[i].equals("**")) {
return false;
}
}
return true;
}
while (pattIdxStart != pattIdxEnd && pathIdxStart <= pathIdxEnd) {
int patIdxTmp = -1;
for (int i = pattIdxStart + 1; i <= pattIdxEnd; i++) {
if (pattDirs[i].equals("**")) {
patIdxTmp = i;
break;
}
}
if (patIdxTmp == pattIdxStart + 1) {
// '**/**' situation, so skip one
pattIdxStart++;
continue;
}
// Find the pattern between padIdxStart & padIdxTmp in str between
// strIdxStart & strIdxEnd
int patLength = (patIdxTmp - pattIdxStart - 1);
int strLength = (pathIdxEnd - pathIdxStart + 1);
int foundIdx = -1;
strLoop:
for (int i = 0; i <= strLength - patLength; i++) {
for (int j = 0; j < patLength; j++) {
String subPat = pattDirs[pattIdxStart + j + 1];
String subStr = pathDirs[pathIdxStart + i + j];
if (!matchStrings(subPat, subStr, uriTemplateVariables)) {
continue strLoop;
}
}
foundIdx = pathIdxStart + i;
break;
}
if (foundIdx == -1) {
return false;
}
pattIdxStart = patIdxTmp;
pathIdxStart = foundIdx + patLength;
}
for (int i = pattIdxStart; i <= pattIdxEnd; i++) {
if (!pattDirs[i].equals("**")) {
return false;
}
}
return true;
}
/**
* Tests whether or not a string matches against a pattern. The pattern may contain two special characters:<br> '*'
* means zero or more characters<br> '?' means one and only one character
*
* @param pattern pattern to match against. Must not be <code>null</code>.
* @param str string which must be matched against the pattern. Must not be <code>null</code>.
* @return <code>true</code> if the string matches against the pattern, or <code>false</code> otherwise.
*/
private boolean matchStrings(String pattern, String str, Map<String, String> uriTemplateVariables) {
AntPathStringMatcher matcher = new AntPathStringMatcher(pattern, str, uriTemplateVariables);
return matcher.matchStrings();
}
/**
* Given a pattern and a full path, determine the pattern-mapped part. <p>For example: <ul>
* <li>'<code>/docs/cvs/commit.html</code>' and '<code>/docs/cvs/commit.html</code> -> ''</li>
* <li>'<code>/docs/*</code>' and '<code>/docs/cvs/commit</code> -> '<code>cvs/commit</code>'</li>
* <li>'<code>/docs/cvs/*.html</code>' and '<code>/docs/cvs/commit.html</code> -> '<code>commit.html</code>'</li>
* <li>'<code>/docs/**</code>' and '<code>/docs/cvs/commit</code> -> '<code>cvs/commit</code>'</li>
* <li>'<code>/docs/**\/*.html</code>' and '<code>/docs/cvs/commit.html</code> -> '<code>cvs/commit.html</code>'</li>
* <li>'<code>/*.html</code>' and '<code>/docs/cvs/commit.html</code> -> '<code>docs/cvs/commit.html</code>'</li>
* <li>'<code>*.html</code>' and '<code>/docs/cvs/commit.html</code> -> '<code>/docs/cvs/commit.html</code>'</li>
* <li>'<code>*</code>' and '<code>/docs/cvs/commit.html</code> -> '<code>/docs/cvs/commit.html</code>'</li> </ul>
* <p>Assumes that {@link #match} returns <code>true</code> for '<code>pattern</code>' and '<code>path</code>', but
* does <strong>not</strong> enforce this.
*/
public String extractPathWithinPattern(String pattern, String path) {
String[] patternParts = StringUtils.tokenizeToStringArray(pattern, this.pathSeparator);
String[] pathParts = StringUtils.tokenizeToStringArray(path, this.pathSeparator);
StringBuilder builder = new StringBuilder();
// Add any path parts that have a wildcarded pattern part.
int puts = 0;
for (int i = 0; i < patternParts.length; i++) {
String patternPart = patternParts[i];
if ((patternPart.indexOf('*') > -1 || patternPart.indexOf('?') > -1) && pathParts.length >= i + 1) {
if (puts > 0 || (i == 0 && !pattern.startsWith(this.pathSeparator))) {
builder.append(this.pathSeparator);
}
builder.append(pathParts[i]);
puts++;
}
}
// Append any trailing path parts.
for (int i = patternParts.length; i < pathParts.length; i++) {
if (puts > 0 || i > 0) {
builder.append(this.pathSeparator);
}
builder.append(pathParts[i]);
}
return builder.toString();
}
public Map<String, String> extractUriTemplateVariables(String pattern, String path) {
Map<String, String> variables = new LinkedHashMap<String, String>();
boolean result = doMatch(pattern, path, true, variables);
Assert.state(result, "Pattern \"" + pattern + "\" is not a match for \"" + path + "\"");
return variables;
}
/**
* Combines two patterns into a new pattern that is returned. <p>This implementation simply concatenates the two
* patterns, unless the first pattern contains a file extension match (such as {@code *.html}. In that case, the second
* pattern should be included in the first, or an {@code IllegalArgumentException} is thrown. <p>For example: <table>
* <tr><th>Pattern 1</th><th>Pattern 2</th><th>Result</th></tr> <tr><td>/hotels</td><td>{@code
* null}</td><td>/hotels</td></tr> <tr><td>{@code null}</td><td>/hotels</td><td>/hotels</td></tr>
* <tr><td>/hotels</td><td>/bookings</td><td>/hotels/bookings</td></tr> <tr><td>/hotels</td><td>bookings</td><td>/hotels/bookings</td></tr>
* <tr><td>/hotels/*</td><td>/bookings</td><td>/hotels/bookings</td></tr> <tr><td>/hotels/&#42;&#42;</td><td>/bookings</td><td>/hotels/&#42;&#42;/bookings</td></tr>
* <tr><td>/hotels</td><td>{hotel}</td><td>/hotels/{hotel}</td></tr> <tr><td>/hotels/*</td><td>{hotel}</td><td>/hotels/{hotel}</td></tr>
* <tr><td>/hotels/&#42;&#42;</td><td>{hotel}</td><td>/hotels/&#42;&#42;/{hotel}</td></tr>
* <tr><td>/*.html</td><td>/hotels.html</td><td>/hotels.html</td></tr> <tr><td>/*.html</td><td>/hotels</td><td>/hotels.html</td></tr>
* <tr><td>/*.html</td><td>/*.txt</td><td>IllegalArgumentException</td></tr> </table>
*
* @param pattern1 the first pattern
* @param pattern2 the second pattern
* @return the combination of the two patterns
* @throws IllegalArgumentException when the two patterns cannot be combined
*/
public String combine(String pattern1, String pattern2) {
if (!StringUtils.hasText(pattern1) && !StringUtils.hasText(pattern2)) {
return "";
}
else if (!StringUtils.hasText(pattern1)) {
return pattern2;
}
else if (!StringUtils.hasText(pattern2)) {
return pattern1;
}
else if (match(pattern1, pattern2)) {
return pattern2;
}
else if (pattern1.endsWith("/*")) {
if (pattern2.startsWith("/")) {
// /hotels/* + /booking -> /hotels/booking
return pattern1.substring(0, pattern1.length() - 1) + pattern2.substring(1);
}
else {
// /hotels/* + booking -> /hotels/booking
return pattern1.substring(0, pattern1.length() - 1) + pattern2;
}
}
else if (pattern1.endsWith("/**")) {
if (pattern2.startsWith("/")) {
// /hotels/** + /booking -> /hotels/**/booking
return pattern1 + pattern2;
}
else {
// /hotels/** + booking -> /hotels/**/booking
return pattern1 + "/" + pattern2;
}
}
else {
int dotPos1 = pattern1.indexOf('.');
if (dotPos1 == -1) {
// simply concatenate the two patterns
if (pattern1.endsWith("/") || pattern2.startsWith("/")) {
return pattern1 + pattern2;
}
else {
return pattern1 + "/" + pattern2;
}
}
String fileName1 = pattern1.substring(0, dotPos1);
String extension1 = pattern1.substring(dotPos1);
String fileName2;
String extension2;
int dotPos2 = pattern2.indexOf('.');
if (dotPos2 != -1) {
fileName2 = pattern2.substring(0, dotPos2);
extension2 = pattern2.substring(dotPos2);
}
else {
fileName2 = pattern2;
extension2 = "";
}
String fileName = fileName1.endsWith("*") ? fileName2 : fileName1;
String extension = extension1.startsWith("*") ? extension2 : extension1;
return fileName + extension;
}
}
/**
* Given a full path, returns a {@link Comparator} suitable for sorting patterns in order of explicitness.
*
* <p>The returned <code>Comparator</code> will {@linkplain java.util.Collections#sort(java.util.List,
* java.util.Comparator) sort} a list so that more specific patterns (without uri templates or wild cards) come before
* generic patterns. So given a list with the following patterns: <ol> <li><code>/hotels/new</code></li>
* <li><code>/hotels/{hotel}</code></li> <li><code>/hotels/*</code></li> </ol> the returned comparator will sort this
* list so that the order will be as indicated.
*
* <p>The full path given as parameter is used to test for exact matches. So when the given path is {@code /hotels/2},
* the pattern {@code /hotels/2} will be sorted before {@code /hotels/1}.
*
* @param path the full path to use for comparison
* @return a comparator capable of sorting patterns in order of explicitness
*/
public Comparator<String> getPatternComparator(String path) {
return new AntPatternComparator(path);
}
private static class AntPatternComparator implements Comparator<String> {
private final String path;
private AntPatternComparator(String path) {
this.path = path;
}
public int compare(String pattern1, String pattern2) {
if (pattern1 == null && pattern2 == null) {
return 0;
}
else if (pattern1 == null) {
return 1;
}
else if (pattern2 == null) {
return -1;
}
boolean pattern1EqualsPath = pattern1.equals(path);
boolean pattern2EqualsPath = pattern2.equals(path);
if (pattern1EqualsPath && pattern2EqualsPath) {
return 0;
}
else if (pattern1EqualsPath) {
return -1;
}
else if (pattern2EqualsPath) {
return 1;
}
int wildCardCount1 = StringUtils.countOccurrencesOf(pattern1, "*");
int wildCardCount2 = StringUtils.countOccurrencesOf(pattern2, "*");
if (wildCardCount1 < wildCardCount2) {
return -1;
}
else if (wildCardCount2 < wildCardCount1) {
return 1;
}
int bracketCount1 = StringUtils.countOccurrencesOf(pattern1, "{");
int bracketCount2 = StringUtils.countOccurrencesOf(pattern2, "{");
if (bracketCount1 < bracketCount2) {
return -1;
}
else if (bracketCount2 < bracketCount1) {
return 1;
}
return 0;
}
}
}

View File

@ -0,0 +1,119 @@
/*
* Copyright 2002-2009 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.openjpa.eclipse.util.pathmatch;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Package-protected helper class for {@link AntPathMatcher}. Tests whether or not a string matches against a pattern
* using a regular expression.
*
* <p>The pattern may contain special characters: '*' means zero or more characters; '?' means one and only one
* character; '{' and '}' indicate a URI template pattern.
*
* @author Arjen Poutsma
* @since 3.0
*/
class AntPathStringMatcher {
private static final Pattern GLOB_PATTERN = Pattern.compile("\\?|\\*|\\{([^/]+?)\\}");
private static final String DEFAULT_VARIABLE_PATTERN = "(.*)";
private final Pattern pattern;
private String str;
private final List<String> variableNames = new LinkedList<String>();
private final Map<String, String> uriTemplateVariables;
/** Construct a new instance of the <code>AntPatchStringMatcher</code>. */
AntPathStringMatcher(String pattern, String str, Map<String, String> uriTemplateVariables) {
this.str = str;
this.uriTemplateVariables = uriTemplateVariables;
this.pattern = createPattern(pattern);
}
private Pattern createPattern(String pattern) {
StringBuilder patternBuilder = new StringBuilder();
Matcher m = GLOB_PATTERN.matcher(pattern);
int end = 0;
while (m.find()) {
patternBuilder.append(quote(pattern, end, m.start()));
String match = m.group();
if ("?".equals(match)) {
patternBuilder.append('.');
}
else if ("*".equals(match)) {
patternBuilder.append(".*");
}
else if (match.startsWith("{") && match.endsWith("}")) {
int colonIdx = match.indexOf(':');
if (colonIdx == -1) {
patternBuilder.append(DEFAULT_VARIABLE_PATTERN);
variableNames.add(m.group(1));
}
else {
String variablePattern = match.substring(colonIdx + 1, match.length() - 1);
patternBuilder.append('(');
patternBuilder.append(variablePattern);
patternBuilder.append(')');
String variableName = match.substring(1, colonIdx);
variableNames.add(variableName);
}
}
end = m.end();
}
patternBuilder.append(quote(pattern, end, pattern.length()));
return Pattern.compile(patternBuilder.toString());
}
private String quote(String s, int start, int end) {
if (start == end) {
return "";
}
return Pattern.quote(s.substring(start, end));
}
/**
* Main entry point.
*
* @return <code>true</code> if the string matches against the pattern, or <code>false</code> otherwise.
*/
public boolean matchStrings() {
Matcher matcher = pattern.matcher(str);
if (matcher.matches()) {
if (uriTemplateVariables != null) {
for (int i = 1; i <= matcher.groupCount(); i++) {
String name = this.variableNames.get(i - 1);
String value = matcher.group(i);
uriTemplateVariables.put(name, value);
}
}
return true;
}
else {
return false;
}
}
}

View File

@ -0,0 +1,402 @@
/*
* Copyright 2002-2007 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.apache.openjpa.eclipse.util.pathmatch;
import java.util.Collection;
import java.util.Map;
/**
* Assertion utility class that assists in validating arguments.
* Useful for identifying programmer errors early and clearly at runtime.
*
* <p>For example, if the contract of a public method states it does not
* allow <code>null</code> arguments, Assert can be used to validate that
* contract. Doing this clearly indicates a contract violation when it
* occurs and protects the class's invariants.
*
* <p>Typically used to validate method arguments rather than configuration
* properties, to check for cases that are usually programmer errors rather than
* configuration errors. In contrast to config initialization code, there is
* usally no point in falling back to defaults in such methods.
*
* <p>This class is similar to JUnit's assertion library. If an argument value is
* deemed invalid, an {@link IllegalArgumentException} is thrown (typically).
* For example:
*
* <pre class="code">
* Assert.notNull(clazz, "The class must not be null");
* Assert.isTrue(i > 0, "The value must be greater than zero");</pre>
*
* Mainly for internal use within the framework; consider Jakarta's Commons Lang
* >= 2.0 for a more comprehensive suite of assertion utilities.
*
* @author Keith Donald
* @author Juergen Hoeller
* @author Colin Sampaleanu
* @author Rob Harrop
* @since 1.1.2
*/
@SuppressWarnings("unchecked")
public abstract class Assert {
/**
* Assert a boolean expression, throwing <code>IllegalArgumentException</code>
* if the test result is <code>false</code>.
* <pre class="code">Assert.isTrue(i &gt; 0, "The value must be greater than zero");</pre>
* @param expression a boolean expression
* @param message the exception message to use if the assertion fails
* @throws IllegalArgumentException if expression is <code>false</code>
*/
public static void isTrue(boolean expression, String message) {
if (!expression) {
throw new IllegalArgumentException(message);
}
}
/**
* Assert a boolean expression, throwing <code>IllegalArgumentException</code>
* if the test result is <code>false</code>.
* <pre class="code">Assert.isTrue(i &gt; 0);</pre>
* @param expression a boolean expression
* @throws IllegalArgumentException if expression is <code>false</code>
*/
public static void isTrue(boolean expression) {
isTrue(expression, "[Assertion failed] - this expression must be true");
}
/**
* Assert that an object is <code>null</code> .
* <pre class="code">Assert.isNull(value, "The value must be null");</pre>
* @param object the object to check
* @param message the exception message to use if the assertion fails
* @throws IllegalArgumentException if the object is not <code>null</code>
*/
public static void isNull(Object object, String message) {
if (object != null) {
throw new IllegalArgumentException(message);
}
}
/**
* Assert that an object is <code>null</code> .
* <pre class="code">Assert.isNull(value);</pre>
* @param object the object to check
* @throws IllegalArgumentException if the object is not <code>null</code>
*/
public static void isNull(Object object) {
isNull(object, "[Assertion failed] - the object argument must be null");
}
/**
* Assert that an object is not <code>null</code> .
* <pre class="code">Assert.notNull(clazz, "The class must not be null");</pre>
* @param object the object to check
* @param message the exception message to use if the assertion fails
* @throws IllegalArgumentException if the object is <code>null</code>
*/
public static void notNull(Object object, String message) {
if (object == null) {
throw new IllegalArgumentException(message);
}
}
/**
* Assert that an object is not <code>null</code> .
* <pre class="code">Assert.notNull(clazz);</pre>
* @param object the object to check
* @throws IllegalArgumentException if the object is <code>null</code>
*/
public static void notNull(Object object) {
notNull(object, "[Assertion failed] - this argument is required; it must not be null");
}
/**
* Assert that the given String is not empty; that is,
* it must not be <code>null</code> and not the empty String.
* <pre class="code">Assert.hasLength(name, "Name must not be empty");</pre>
* @param text the String to check
* @param message the exception message to use if the assertion fails
* @see StringUtils#hasLength
*/
public static void hasLength(String text, String message) {
if (!StringUtils.hasLength(text)) {
throw new IllegalArgumentException(message);
}
}
/**
* Assert that the given String is not empty; that is,
* it must not be <code>null</code> and not the empty String.
* <pre class="code">Assert.hasLength(name);</pre>
* @param text the String to check
* @see StringUtils#hasLength
*/
public static void hasLength(String text) {
hasLength(text,
"[Assertion failed] - this String argument must have length; it must not be null or empty");
}
/**
* Assert that the given String has valid text content; that is, it must not
* be <code>null</code> and must contain at least one non-whitespace character.
* <pre class="code">Assert.hasText(name, "'name' must not be empty");</pre>
* @param text the String to check
* @param message the exception message to use if the assertion fails
* @see StringUtils#hasText
*/
public static void hasText(String text, String message) {
if (!StringUtils.hasText(text)) {
throw new IllegalArgumentException(message);
}
}
/**
* Assert that the given String has valid text content; that is, it must not
* be <code>null</code> and must contain at least one non-whitespace character.
* <pre class="code">Assert.hasText(name, "'name' must not be empty");</pre>
* @param text the String to check
* @see StringUtils#hasText
*/
public static void hasText(String text) {
hasText(text,
"[Assertion failed] - this String argument must have text; it must not be null, empty, or blank");
}
/**
* Assert that the given text does not contain the given substring.
* <pre class="code">Assert.doesNotContain(name, "rod", "Name must not contain 'rod'");</pre>
* @param textToSearch the text to search
* @param substring the substring to find within the text
* @param message the exception message to use if the assertion fails
*/
public static void doesNotContain(String textToSearch, String substring, String message) {
if (StringUtils.hasLength(textToSearch) && StringUtils.hasLength(substring) &&
textToSearch.indexOf(substring) != -1) {
throw new IllegalArgumentException(message);
}
}
/**
* Assert that the given text does not contain the given substring.
* <pre class="code">Assert.doesNotContain(name, "rod");</pre>
* @param textToSearch the text to search
* @param substring the substring to find within the text
*/
public static void doesNotContain(String textToSearch, String substring) {
doesNotContain(textToSearch, substring,
"[Assertion failed] - this String argument must not contain the substring [" + substring + "]");
}
/**
* Assert that an array has elements; that is, it must not be
* <code>null</code> and must have at least one element.
* <pre class="code">Assert.notEmpty(array, "The array must have elements");</pre>
* @param array the array to check
* @param message the exception message to use if the assertion fails
* @throws IllegalArgumentException if the object array is <code>null</code> or has no elements
*/
public static void notEmpty(Object[] array, String message) {
if (ObjectUtils.isEmpty(array)) {
throw new IllegalArgumentException(message);
}
}
/**
* Assert that an array has elements; that is, it must not be
* <code>null</code> and must have at least one element.
* <pre class="code">Assert.notEmpty(array);</pre>
* @param array the array to check
* @throws IllegalArgumentException if the object array is <code>null</code> or has no elements
*/
public static void notEmpty(Object[] array) {
notEmpty(array, "[Assertion failed] - this array must not be empty: it must contain at least 1 element");
}
/**
* Assert that an array has no null elements.
* Note: Does not complain if the array is empty!
* <pre class="code">Assert.noNullElements(array, "The array must have non-null elements");</pre>
* @param array the array to check
* @param message the exception message to use if the assertion fails
* @throws IllegalArgumentException if the object array contains a <code>null</code> element
*/
public static void noNullElements(Object[] array, String message) {
if (array != null) {
for (int i = 0; i < array.length; i++) {
if (array[i] == null) {
throw new IllegalArgumentException(message);
}
}
}
}
/**
* Assert that an array has no null elements.
* Note: Does not complain if the array is empty!
* <pre class="code">Assert.noNullElements(array);</pre>
* @param array the array to check
* @throws IllegalArgumentException if the object array contains a <code>null</code> element
*/
public static void noNullElements(Object[] array) {
noNullElements(array, "[Assertion failed] - this array must not contain any null elements");
}
/**
* Assert that a collection has elements; that is, it must not be
* <code>null</code> and must have at least one element.
* <pre class="code">Assert.notEmpty(collection, "Collection must have elements");</pre>
* @param collection the collection to check
* @param message the exception message to use if the assertion fails
* @throws IllegalArgumentException if the collection is <code>null</code> or has no elements
*/
public static void notEmpty(Collection collection, String message) {
if (CollectionUtils.isEmpty(collection)) {
throw new IllegalArgumentException(message);
}
}
/**
* Assert that a collection has elements; that is, it must not be
* <code>null</code> and must have at least one element.
* <pre class="code">Assert.notEmpty(collection, "Collection must have elements");</pre>
* @param collection the collection to check
* @throws IllegalArgumentException if the collection is <code>null</code> or has no elements
*/
public static void notEmpty(Collection collection) {
notEmpty(collection,
"[Assertion failed] - this collection must not be empty: it must contain at least 1 element");
}
/**
* Assert that a Map has entries; that is, it must not be <code>null</code>
* and must have at least one entry.
* <pre class="code">Assert.notEmpty(map, "Map must have entries");</pre>
* @param map the map to check
* @param message the exception message to use if the assertion fails
* @throws IllegalArgumentException if the map is <code>null</code> or has no entries
*/
public static void notEmpty(Map map, String message) {
if (CollectionUtils.isEmpty(map)) {
throw new IllegalArgumentException(message);
}
}
/**
* Assert that a Map has entries; that is, it must not be <code>null</code>
* and must have at least one entry.
* <pre class="code">Assert.notEmpty(map);</pre>
* @param map the map to check
* @throws IllegalArgumentException if the map is <code>null</code> or has no entries
*/
public static void notEmpty(Map map) {
notEmpty(map, "[Assertion failed] - this map must not be empty; it must contain at least one entry");
}
/**
* Assert that the provided object is an instance of the provided class.
* <pre class="code">Assert.instanceOf(Foo.class, foo);</pre>
* @param clazz the required class
* @param obj the object to check
* @throws IllegalArgumentException if the object is not an instance of clazz
* @see Class#isInstance
*/
public static void isInstanceOf(Class clazz, Object obj) {
isInstanceOf(clazz, obj, "");
}
/**
* Assert that the provided object is an instance of the provided class.
* <pre class="code">Assert.instanceOf(Foo.class, foo);</pre>
* @param type the type to check against
* @param obj the object to check
* @param message a message which will be prepended to the message produced by
* the function itself, and which may be used to provide context. It should
* normally end in a ": " or ". " so that the function generate message looks
* ok when prepended to it.
* @throws IllegalArgumentException if the object is not an instance of clazz
* @see Class#isInstance
*/
public static void isInstanceOf(Class type, Object obj, String message) {
notNull(type, "Type to check against must not be null");
if (!type.isInstance(obj)) {
throw new IllegalArgumentException(message +
"Object of class [" + (obj != null ? obj.getClass().getName() : "null") +
"] must be an instance of " + type);
}
}
/**
* Assert that <code>superType.isAssignableFrom(subType)</code> is <code>true</code>.
* <pre class="code">Assert.isAssignable(Number.class, myClass);</pre>
* @param superType the super type to check
* @param subType the sub type to check
* @throws IllegalArgumentException if the classes are not assignable
*/
public static void isAssignable(Class superType, Class subType) {
isAssignable(superType, subType, "");
}
/**
* Assert that <code>superType.isAssignableFrom(subType)</code> is <code>true</code>.
* <pre class="code">Assert.isAssignable(Number.class, myClass);</pre>
* @param superType the super type to check against
* @param subType the sub type to check
* @param message a message which will be prepended to the message produced by
* the function itself, and which may be used to provide context. It should
* normally end in a ": " or ". " so that the function generate message looks
* ok when prepended to it.
* @throws IllegalArgumentException if the classes are not assignable
*/
public static void isAssignable(Class superType, Class subType, String message) {
notNull(superType, "Type to check against must not be null");
if (subType == null || !superType.isAssignableFrom(subType)) {
throw new IllegalArgumentException(message + subType + " is not assignable to " + superType);
}
}
/**
* Assert a boolean expression, throwing <code>IllegalStateException</code>
* if the test result is <code>false</code>. Call isTrue if you wish to
* throw IllegalArgumentException on an assertion failure.
* <pre class="code">Assert.state(id == null, "The id property must not already be initialized");</pre>
* @param expression a boolean expression
* @param message the exception message to use if the assertion fails
* @throws IllegalStateException if expression is <code>false</code>
*/
public static void state(boolean expression, String message) {
if (!expression) {
throw new IllegalStateException(message);
}
}
/**
* Assert a boolean expression, throwing {@link IllegalStateException}
* if the test result is <code>false</code>.
* <p>Call {@link #isTrue(boolean)} if you wish to
* throw {@link IllegalArgumentException} on an assertion failure.
* <pre class="code">Assert.state(id == null);</pre>
* @param expression a boolean expression
* @throws IllegalStateException if the supplied expression is <code>false</code>
*/
public static void state(boolean expression) {
state(expression, "[Assertion failed] - this state invariant must be true");
}
}

View File

@ -0,0 +1,310 @@
/*
* Copyright 2002-2009 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.openjpa.eclipse.util.pathmatch;
import java.util.Arrays;
import java.util.Collection;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
/**
* Miscellaneous collection utility methods.
* Mainly for internal use within the framework.
*
* @author Juergen Hoeller
* @author Rob Harrop
* @since 1.1.3
*/
@SuppressWarnings("unchecked")
public abstract class CollectionUtils {
/**
* Return <code>true</code> if the supplied Collection is <code>null</code>
* or empty. Otherwise, return <code>false</code>.
* @param collection the Collection to check
* @return whether the given Collection is empty
*/
public static boolean isEmpty(Collection collection) {
return (collection == null || collection.isEmpty());
}
/**
* Return <code>true</code> if the supplied Map is <code>null</code>
* or empty. Otherwise, return <code>false</code>.
* @param map the Map to check
* @return whether the given Map is empty
*/
public static boolean isEmpty(Map map) {
return (map == null || map.isEmpty());
}
/**
* Convert the supplied array into a List. A primitive array gets
* converted into a List of the appropriate wrapper type.
* <p>A <code>null</code> source value will be converted to an
* empty List.
* @param source the (potentially primitive) array
* @return the converted List result
* @see ObjectUtils#toObjectArray(Object)
*/
public static List arrayToList(Object source) {
return Arrays.asList(ObjectUtils.toObjectArray(source));
}
/**
* Merge the given array into the given Collection.
* @param array the array to merge (may be <code>null</code>)
* @param collection the target Collection to merge the array into
*/
public static void mergeArrayIntoCollection(Object array, Collection collection) {
if (collection == null) {
throw new IllegalArgumentException("Collection must not be null");
}
Object[] arr = ObjectUtils.toObjectArray(array);
for (Object elem : arr) {
collection.add(elem);
}
}
/**
* Merge the given Properties instance into the given Map,
* copying all properties (key-value pairs) over.
* <p>Uses <code>Properties.propertyNames()</code> to even catch
* default properties linked into the original Properties instance.
* @param props the Properties instance to merge (may be <code>null</code>)
* @param map the target Map to merge the properties into
*/
public static void mergePropertiesIntoMap(Properties props, Map map) {
if (map == null) {
throw new IllegalArgumentException("Map must not be null");
}
if (props != null) {
for (Enumeration en = props.propertyNames(); en.hasMoreElements();) {
String key = (String) en.nextElement();
Object value = props.getProperty(key);
if (value == null) {
// Potentially a non-String value...
value = props.get(key);
}
map.put(key, value);
}
}
}
/**
* Check whether the given Iterator contains the given element.
* @param iterator the Iterator to check
* @param element the element to look for
* @return <code>true</code> if found, <code>false</code> else
*/
public static boolean contains(Iterator iterator, Object element) {
if (iterator != null) {
while (iterator.hasNext()) {
Object candidate = iterator.next();
if (ObjectUtils.nullSafeEquals(candidate, element)) {
return true;
}
}
}
return false;
}
/**
* Check whether the given Enumeration contains the given element.
* @param enumeration the Enumeration to check
* @param element the element to look for
* @return <code>true</code> if found, <code>false</code> else
*/
public static boolean contains(Enumeration enumeration, Object element) {
if (enumeration != null) {
while (enumeration.hasMoreElements()) {
Object candidate = enumeration.nextElement();
if (ObjectUtils.nullSafeEquals(candidate, element)) {
return true;
}
}
}
return false;
}
/**
* Check whether the given Collection contains the given element instance.
* <p>Enforces the given instance to be present, rather than returning
* <code>true</code> for an equal element as well.
* @param collection the Collection to check
* @param element the element to look for
* @return <code>true</code> if found, <code>false</code> else
*/
public static boolean containsInstance(Collection collection, Object element) {
if (collection != null) {
for (Object candidate : collection) {
if (candidate == element) {
return true;
}
}
}
return false;
}
/**
* Return <code>true</code> if any element in '<code>candidates</code>' is
* contained in '<code>source</code>'; otherwise returns <code>false</code>.
* @param source the source Collection
* @param candidates the candidates to search for
* @return whether any of the candidates has been found
*/
public static boolean containsAny(Collection source, Collection candidates) {
if (isEmpty(source) || isEmpty(candidates)) {
return false;
}
for (Object candidate : candidates) {
if (source.contains(candidate)) {
return true;
}
}
return false;
}
/**
* Return the first element in '<code>candidates</code>' that is contained in
* '<code>source</code>'. If no element in '<code>candidates</code>' is present in
* '<code>source</code>' returns <code>null</code>. Iteration order is
* {@link Collection} implementation specific.
* @param source the source Collection
* @param candidates the candidates to search for
* @return the first present object, or <code>null</code> if not found
*/
public static Object findFirstMatch(Collection source, Collection candidates) {
if (isEmpty(source) || isEmpty(candidates)) {
return null;
}
for (Object candidate : candidates) {
if (source.contains(candidate)) {
return candidate;
}
}
return null;
}
/**
* Find a single value of the given type in the given Collection.
* @param collection the Collection to search
* @param type the type to look for
* @return a value of the given type found if there is a clear match,
* or <code>null</code> if none or more than one such value found
*/
public static <T> T findValueOfType(Collection collection, Class<T> type) {
if (isEmpty(collection)) {
return null;
}
T value = null;
for (Object element : collection) {
if (type == null || type.isInstance(element)) {
if (value != null) {
// More than one value found... no clear single value.
return null;
}
value = (T) element;
}
}
return value;
}
/**
* Find a single value of one of the given types in the given Collection:
* searching the Collection for a value of the first type, then
* searching for a value of the second type, etc.
* @param collection the collection to search
* @param types the types to look for, in prioritized order
* @return a value of one of the given types found if there is a clear match,
* or <code>null</code> if none or more than one such value found
*/
public static Object findValueOfType(Collection collection, Class[] types) {
if (isEmpty(collection) || ObjectUtils.isEmpty(types)) {
return null;
}
for (Class type : types) {
Object value = findValueOfType(collection, type);
if (value != null) {
return value;
}
}
return null;
}
/**
* Determine whether the given Collection only contains a single unique object.
* @param collection the Collection to check
* @return <code>true</code> if the collection contains a single reference or
* multiple references to the same instance, <code>false</code> else
*/
public static boolean hasUniqueObject(Collection collection) {
if (isEmpty(collection)) {
return false;
}
boolean hasCandidate = false;
Object candidate = null;
for (Iterator it = collection.iterator(); it.hasNext();) {
Object elem = it.next();
if (!hasCandidate) {
hasCandidate = true;
candidate = elem;
}
else if (candidate != elem) {
return false;
}
}
return true;
}
/**
* Adapts an enumeration to an iterator.
* @param enumeration the enumeration
* @return the iterator
*/
public static <E> Iterator<E> toIterator(Enumeration<E> enumeration) {
return new EnumerationIterator<E>(enumeration);
}
/**
* Iterator wrapping an Enumeration.
*/
private static class EnumerationIterator<E> implements Iterator<E> {
private Enumeration<E> enumeration;
public EnumerationIterator(Enumeration<E> enumeration) {
this.enumeration = enumeration;
}
public boolean hasNext() {
return enumeration.hasMoreElements();
}
public E next() {
return enumeration.nextElement();
}
public void remove() throws UnsupportedOperationException {
throw new UnsupportedOperationException("Not supported");
}
}
}

View File

@ -0,0 +1,847 @@
/*
* Copyright 2002-2009 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.openjpa.eclipse.util.pathmatch;
import java.lang.reflect.Array;
import java.util.Arrays;
/**
* Miscellaneous object utility methods.
*
* <p>Mainly for internal use within the framework; consider
* <a href="http://jakarta.apache.org/commons/lang/">Jakarta's Commons Lang</a>
* for a more comprehensive suite of object utilities.
*
* <p>Thanks to Alex Ruiz for contributing several enhancements to this class!
*
* @author Juergen Hoeller
* @author Keith Donald
* @author Rod Johnson
* @author Rob Harrop
* @since 19.03.2004
* @see org.apache.commons.lang.ObjectUtils
*/
@SuppressWarnings("unchecked")
public abstract class ObjectUtils {
private static final int INITIAL_HASH = 7;
private static final int MULTIPLIER = 31;
private static final String EMPTY_STRING = "";
private static final String NULL_STRING = "null";
private static final String ARRAY_START = "{";
private static final String ARRAY_END = "}";
private static final String EMPTY_ARRAY = ARRAY_START + ARRAY_END;
private static final String ARRAY_ELEMENT_SEPARATOR = ", ";
/**
* Return whether the given throwable is a checked exception:
* that is, neither a RuntimeException nor an Error.
* @param ex the throwable to check
* @return whether the throwable is a checked exception
* @see java.lang.Exception
* @see java.lang.RuntimeException
* @see java.lang.Error
*/
public static boolean isCheckedException(Throwable ex) {
return !(ex instanceof RuntimeException || ex instanceof Error);
}
/**
* Check whether the given exception is compatible with the exceptions
* declared in a throws clause.
* @param ex the exception to checked
* @param declaredExceptions the exceptions declared in the throws clause
* @return whether the given exception is compatible
*/
public static boolean isCompatibleWithThrowsClause(Throwable ex, Class[] declaredExceptions) {
if (!isCheckedException(ex)) {
return true;
}
if (declaredExceptions != null) {
int i = 0;
while (i < declaredExceptions.length) {
if (declaredExceptions[i].isAssignableFrom(ex.getClass())) {
return true;
}
i++;
}
}
return false;
}
/**
* Determine whether the given object is an array:
* either an Object array or a primitive array.
* @param obj the object to check
*/
public static boolean isArray(Object obj) {
return (obj != null && obj.getClass().isArray());
}
/**
* Determine whether the given array is empty:
* i.e. <code>null</code> or of zero length.
* @param array the array to check
*/
public static boolean isEmpty(Object[] array) {
return (array == null || array.length == 0);
}
/**
* Check whether the given array contains the given element.
* @param array the array to check (may be <code>null</code>,
* in which case the return value will always be <code>false</code>)
* @param element the element to check for
* @return whether the element has been found in the given array
*/
public static boolean containsElement(Object[] array, Object element) {
if (array == null) {
return false;
}
for (Object arrayEle : array) {
if (nullSafeEquals(arrayEle, element)) {
return true;
}
}
return false;
}
/**
* Append the given Object to the given array, returning a new array
* consisting of the input array contents plus the given Object.
* @param array the array to append to (can be <code>null</code>)
* @param obj the Object to append
* @return the new array (of the same component type; never <code>null</code>)
*/
public static Object[] addObjectToArray(Object[] array, Object obj) {
Class compType = Object.class;
if (array != null) {
compType = array.getClass().getComponentType();
}
else if (obj != null) {
compType = obj.getClass();
}
int newArrLength = (array != null ? array.length + 1 : 1);
Object[] newArr = (Object[]) Array.newInstance(compType, newArrLength);
if (array != null) {
System.arraycopy(array, 0, newArr, 0, array.length);
}
newArr[newArr.length - 1] = obj;
return newArr;
}
/**
* Convert the given array (which may be a primitive array) to an
* object array (if necessary of primitive wrapper objects).
* <p>A <code>null</code> source value will be converted to an
* empty Object array.
* @param source the (potentially primitive) array
* @return the corresponding object array (never <code>null</code>)
* @throws IllegalArgumentException if the parameter is not an array
*/
public static Object[] toObjectArray(Object source) {
if (source instanceof Object[]) {
return (Object[]) source;
}
if (source == null) {
return new Object[0];
}
if (!source.getClass().isArray()) {
throw new IllegalArgumentException("Source is not an array: " + source);
}
int length = Array.getLength(source);
if (length == 0) {
return new Object[0];
}
Class wrapperType = Array.get(source, 0).getClass();
Object[] newArray = (Object[]) Array.newInstance(wrapperType, length);
for (int i = 0; i < length; i++) {
newArray[i] = Array.get(source, i);
}
return newArray;
}
//---------------------------------------------------------------------
// Convenience methods for content-based equality/hash-code handling
//---------------------------------------------------------------------
/**
* Determine if the given objects are equal, returning <code>true</code>
* if both are <code>null</code> or <code>false</code> if only one is
* <code>null</code>.
* <p>Compares arrays with <code>Arrays.equals</code>, performing an equality
* check based on the array elements rather than the array reference.
* @param o1 first Object to compare
* @param o2 second Object to compare
* @return whether the given objects are equal
* @see java.util.Arrays#equals
*/
public static boolean nullSafeEquals(Object o1, Object o2) {
if (o1 == o2) {
return true;
}
if (o1 == null || o2 == null) {
return false;
}
if (o1.equals(o2)) {
return true;
}
if (o1.getClass().isArray() && o2.getClass().isArray()) {
if (o1 instanceof Object[] && o2 instanceof Object[]) {
return Arrays.equals((Object[]) o1, (Object[]) o2);
}
if (o1 instanceof boolean[] && o2 instanceof boolean[]) {
return Arrays.equals((boolean[]) o1, (boolean[]) o2);
}
if (o1 instanceof byte[] && o2 instanceof byte[]) {
return Arrays.equals((byte[]) o1, (byte[]) o2);
}
if (o1 instanceof char[] && o2 instanceof char[]) {
return Arrays.equals((char[]) o1, (char[]) o2);
}
if (o1 instanceof double[] && o2 instanceof double[]) {
return Arrays.equals((double[]) o1, (double[]) o2);
}
if (o1 instanceof float[] && o2 instanceof float[]) {
return Arrays.equals((float[]) o1, (float[]) o2);
}
if (o1 instanceof int[] && o2 instanceof int[]) {
return Arrays.equals((int[]) o1, (int[]) o2);
}
if (o1 instanceof long[] && o2 instanceof long[]) {
return Arrays.equals((long[]) o1, (long[]) o2);
}
if (o1 instanceof short[] && o2 instanceof short[]) {
return Arrays.equals((short[]) o1, (short[]) o2);
}
}
return false;
}
/**
* Return as hash code for the given object; typically the value of
* <code>{@link Object#hashCode()}</code>. If the object is an array,
* this method will delegate to any of the <code>nullSafeHashCode</code>
* methods for arrays in this class. If the object is <code>null</code>,
* this method returns 0.
* @see #nullSafeHashCode(Object[])
* @see #nullSafeHashCode(boolean[])
* @see #nullSafeHashCode(byte[])
* @see #nullSafeHashCode(char[])
* @see #nullSafeHashCode(double[])
* @see #nullSafeHashCode(float[])
* @see #nullSafeHashCode(int[])
* @see #nullSafeHashCode(long[])
* @see #nullSafeHashCode(short[])
*/
public static int nullSafeHashCode(Object obj) {
if (obj == null) {
return 0;
}
if (obj.getClass().isArray()) {
if (obj instanceof Object[]) {
return nullSafeHashCode((Object[]) obj);
}
if (obj instanceof boolean[]) {
return nullSafeHashCode((boolean[]) obj);
}
if (obj instanceof byte[]) {
return nullSafeHashCode((byte[]) obj);
}
if (obj instanceof char[]) {
return nullSafeHashCode((char[]) obj);
}
if (obj instanceof double[]) {
return nullSafeHashCode((double[]) obj);
}
if (obj instanceof float[]) {
return nullSafeHashCode((float[]) obj);
}
if (obj instanceof int[]) {
return nullSafeHashCode((int[]) obj);
}
if (obj instanceof long[]) {
return nullSafeHashCode((long[]) obj);
}
if (obj instanceof short[]) {
return nullSafeHashCode((short[]) obj);
}
}
return obj.hashCode();
}
/**
* Return a hash code based on the contents of the specified array.
* If <code>array</code> is <code>null</code>, this method returns 0.
*/
public static int nullSafeHashCode(Object[] array) {
if (array == null) {
return 0;
}
int hash = INITIAL_HASH;
int arraySize = array.length;
for (int i = 0; i < arraySize; i++) {
hash = MULTIPLIER * hash + nullSafeHashCode(array[i]);
}
return hash;
}
/**
* Return a hash code based on the contents of the specified array.
* If <code>array</code> is <code>null</code>, this method returns 0.
*/
public static int nullSafeHashCode(boolean[] array) {
if (array == null) {
return 0;
}
int hash = INITIAL_HASH;
int arraySize = array.length;
for (int i = 0; i < arraySize; i++) {
hash = MULTIPLIER * hash + hashCode(array[i]);
}
return hash;
}
/**
* Return a hash code based on the contents of the specified array.
* If <code>array</code> is <code>null</code>, this method returns 0.
*/
public static int nullSafeHashCode(byte[] array) {
if (array == null) {
return 0;
}
int hash = INITIAL_HASH;
int arraySize = array.length;
for (int i = 0; i < arraySize; i++) {
hash = MULTIPLIER * hash + array[i];
}
return hash;
}
/**
* Return a hash code based on the contents of the specified array.
* If <code>array</code> is <code>null</code>, this method returns 0.
*/
public static int nullSafeHashCode(char[] array) {
if (array == null) {
return 0;
}
int hash = INITIAL_HASH;
int arraySize = array.length;
for (int i = 0; i < arraySize; i++) {
hash = MULTIPLIER * hash + array[i];
}
return hash;
}
/**
* Return a hash code based on the contents of the specified array.
* If <code>array</code> is <code>null</code>, this method returns 0.
*/
public static int nullSafeHashCode(double[] array) {
if (array == null) {
return 0;
}
int hash = INITIAL_HASH;
int arraySize = array.length;
for (int i = 0; i < arraySize; i++) {
hash = MULTIPLIER * hash + hashCode(array[i]);
}
return hash;
}
/**
* Return a hash code based on the contents of the specified array.
* If <code>array</code> is <code>null</code>, this method returns 0.
*/
public static int nullSafeHashCode(float[] array) {
if (array == null) {
return 0;
}
int hash = INITIAL_HASH;
int arraySize = array.length;
for (int i = 0; i < arraySize; i++) {
hash = MULTIPLIER * hash + hashCode(array[i]);
}
return hash;
}
/**
* Return a hash code based on the contents of the specified array.
* If <code>array</code> is <code>null</code>, this method returns 0.
*/
public static int nullSafeHashCode(int[] array) {
if (array == null) {
return 0;
}
int hash = INITIAL_HASH;
int arraySize = array.length;
for (int i = 0; i < arraySize; i++) {
hash = MULTIPLIER * hash + array[i];
}
return hash;
}
/**
* Return a hash code based on the contents of the specified array.
* If <code>array</code> is <code>null</code>, this method returns 0.
*/
public static int nullSafeHashCode(long[] array) {
if (array == null) {
return 0;
}
int hash = INITIAL_HASH;
int arraySize = array.length;
for (int i = 0; i < arraySize; i++) {
hash = MULTIPLIER * hash + hashCode(array[i]);
}
return hash;
}
/**
* Return a hash code based on the contents of the specified array.
* If <code>array</code> is <code>null</code>, this method returns 0.
*/
public static int nullSafeHashCode(short[] array) {
if (array == null) {
return 0;
}
int hash = INITIAL_HASH;
int arraySize = array.length;
for (int i = 0; i < arraySize; i++) {
hash = MULTIPLIER * hash + array[i];
}
return hash;
}
/**
* Return the same value as <code>{@link Boolean#hashCode()}</code>.
* @see Boolean#hashCode()
*/
public static int hashCode(boolean bool) {
return bool ? 1231 : 1237;
}
/**
* Return the same value as <code>{@link Double#hashCode()}</code>.
* @see Double#hashCode()
*/
public static int hashCode(double dbl) {
long bits = Double.doubleToLongBits(dbl);
return hashCode(bits);
}
/**
* Return the same value as <code>{@link Float#hashCode()}</code>.
* @see Float#hashCode()
*/
public static int hashCode(float flt) {
return Float.floatToIntBits(flt);
}
/**
* Return the same value as <code>{@link Long#hashCode()}</code>.
* @see Long#hashCode()
*/
public static int hashCode(long lng) {
return (int) (lng ^ (lng >>> 32));
}
//---------------------------------------------------------------------
// Convenience methods for toString output
//---------------------------------------------------------------------
/**
* Return a String representation of an object's overall identity.
* @param obj the object (may be <code>null</code>)
* @return the object's identity as String representation,
* or an empty String if the object was <code>null</code>
*/
public static String identityToString(Object obj) {
if (obj == null) {
return EMPTY_STRING;
}
return obj.getClass().getName() + "@" + getIdentityHexString(obj);
}
/**
* Return a hex String form of an object's identity hash code.
* @param obj the object
* @return the object's identity code in hex notation
*/
public static String getIdentityHexString(Object obj) {
return Integer.toHexString(System.identityHashCode(obj));
}
/**
* Return a content-based String representation if <code>obj</code> is
* not <code>null</code>; otherwise returns an empty String.
* <p>Differs from {@link #nullSafeToString(Object)} in that it returns
* an empty String rather than "null" for a <code>null</code> value.
* @param obj the object to build a display String for
* @return a display String representation of <code>obj</code>
* @see #nullSafeToString(Object)
*/
public static String getDisplayString(Object obj) {
if (obj == null) {
return EMPTY_STRING;
}
return nullSafeToString(obj);
}
/**
* Determine the class name for the given object.
* <p>Returns <code>"null"</code> if <code>obj</code> is <code>null</code>.
* @param obj the object to introspect (may be <code>null</code>)
* @return the corresponding class name
*/
public static String nullSafeClassName(Object obj) {
return (obj != null ? obj.getClass().getName() : NULL_STRING);
}
/**
* Return a String representation of the specified Object.
* <p>Builds a String representation of the contents in case of an array.
* Returns <code>"null"</code> if <code>obj</code> is <code>null</code>.
* @param obj the object to build a String representation for
* @return a String representation of <code>obj</code>
*/
public static String nullSafeToString(Object obj) {
if (obj == null) {
return NULL_STRING;
}
if (obj instanceof String) {
return (String) obj;
}
if (obj instanceof Object[]) {
return nullSafeToString((Object[]) obj);
}
if (obj instanceof boolean[]) {
return nullSafeToString((boolean[]) obj);
}
if (obj instanceof byte[]) {
return nullSafeToString((byte[]) obj);
}
if (obj instanceof char[]) {
return nullSafeToString((char[]) obj);
}
if (obj instanceof double[]) {
return nullSafeToString((double[]) obj);
}
if (obj instanceof float[]) {
return nullSafeToString((float[]) obj);
}
if (obj instanceof int[]) {
return nullSafeToString((int[]) obj);
}
if (obj instanceof long[]) {
return nullSafeToString((long[]) obj);
}
if (obj instanceof short[]) {
return nullSafeToString((short[]) obj);
}
String str = obj.toString();
return (str != null ? str : EMPTY_STRING);
}
/**
* Return a String representation of the contents of the specified array.
* <p>The String representation consists of a list of the array's elements,
* enclosed in curly braces (<code>"{}"</code>). Adjacent elements are separated
* by the characters <code>", "</code> (a comma followed by a space). Returns
* <code>"null"</code> if <code>array</code> is <code>null</code>.
* @param array the array to build a String representation for
* @return a String representation of <code>array</code>
*/
public static String nullSafeToString(Object[] array) {
if (array == null) {
return NULL_STRING;
}
int length = array.length;
if (length == 0) {
return EMPTY_ARRAY;
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < length; i++) {
if (i == 0) {
sb.append(ARRAY_START);
}
else {
sb.append(ARRAY_ELEMENT_SEPARATOR);
}
sb.append(String.valueOf(array[i]));
}
sb.append(ARRAY_END);
return sb.toString();
}
/**
* Return a String representation of the contents of the specified array.
* <p>The String representation consists of a list of the array's elements,
* enclosed in curly braces (<code>"{}"</code>). Adjacent elements are separated
* by the characters <code>", "</code> (a comma followed by a space). Returns
* <code>"null"</code> if <code>array</code> is <code>null</code>.
* @param array the array to build a String representation for
* @return a String representation of <code>array</code>
*/
public static String nullSafeToString(boolean[] array) {
if (array == null) {
return NULL_STRING;
}
int length = array.length;
if (length == 0) {
return EMPTY_ARRAY;
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < length; i++) {
if (i == 0) {
sb.append(ARRAY_START);
}
else {
sb.append(ARRAY_ELEMENT_SEPARATOR);
}
sb.append(array[i]);
}
sb.append(ARRAY_END);
return sb.toString();
}
/**
* Return a String representation of the contents of the specified array.
* <p>The String representation consists of a list of the array's elements,
* enclosed in curly braces (<code>"{}"</code>). Adjacent elements are separated
* by the characters <code>", "</code> (a comma followed by a space). Returns
* <code>"null"</code> if <code>array</code> is <code>null</code>.
* @param array the array to build a String representation for
* @return a String representation of <code>array</code>
*/
public static String nullSafeToString(byte[] array) {
if (array == null) {
return NULL_STRING;
}
int length = array.length;
if (length == 0) {
return EMPTY_ARRAY;
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < length; i++) {
if (i == 0) {
sb.append(ARRAY_START);
}
else {
sb.append(ARRAY_ELEMENT_SEPARATOR);
}
sb.append(array[i]);
}
sb.append(ARRAY_END);
return sb.toString();
}
/**
* Return a String representation of the contents of the specified array.
* <p>The String representation consists of a list of the array's elements,
* enclosed in curly braces (<code>"{}"</code>). Adjacent elements are separated
* by the characters <code>", "</code> (a comma followed by a space). Returns
* <code>"null"</code> if <code>array</code> is <code>null</code>.
* @param array the array to build a String representation for
* @return a String representation of <code>array</code>
*/
public static String nullSafeToString(char[] array) {
if (array == null) {
return NULL_STRING;
}
int length = array.length;
if (length == 0) {
return EMPTY_ARRAY;
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < length; i++) {
if (i == 0) {
sb.append(ARRAY_START);
}
else {
sb.append(ARRAY_ELEMENT_SEPARATOR);
}
sb.append("'").append(array[i]).append("'");
}
sb.append(ARRAY_END);
return sb.toString();
}
/**
* Return a String representation of the contents of the specified array.
* <p>The String representation consists of a list of the array's elements,
* enclosed in curly braces (<code>"{}"</code>). Adjacent elements are separated
* by the characters <code>", "</code> (a comma followed by a space). Returns
* <code>"null"</code> if <code>array</code> is <code>null</code>.
* @param array the array to build a String representation for
* @return a String representation of <code>array</code>
*/
public static String nullSafeToString(double[] array) {
if (array == null) {
return NULL_STRING;
}
int length = array.length;
if (length == 0) {
return EMPTY_ARRAY;
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < length; i++) {
if (i == 0) {
sb.append(ARRAY_START);
}
else {
sb.append(ARRAY_ELEMENT_SEPARATOR);
}
sb.append(array[i]);
}
sb.append(ARRAY_END);
return sb.toString();
}
/**
* Return a String representation of the contents of the specified array.
* <p>The String representation consists of a list of the array's elements,
* enclosed in curly braces (<code>"{}"</code>). Adjacent elements are separated
* by the characters <code>", "</code> (a comma followed by a space). Returns
* <code>"null"</code> if <code>array</code> is <code>null</code>.
* @param array the array to build a String representation for
* @return a String representation of <code>array</code>
*/
public static String nullSafeToString(float[] array) {
if (array == null) {
return NULL_STRING;
}
int length = array.length;
if (length == 0) {
return EMPTY_ARRAY;
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < length; i++) {
if (i == 0) {
sb.append(ARRAY_START);
}
else {
sb.append(ARRAY_ELEMENT_SEPARATOR);
}
sb.append(array[i]);
}
sb.append(ARRAY_END);
return sb.toString();
}
/**
* Return a String representation of the contents of the specified array.
* <p>The String representation consists of a list of the array's elements,
* enclosed in curly braces (<code>"{}"</code>). Adjacent elements are separated
* by the characters <code>", "</code> (a comma followed by a space). Returns
* <code>"null"</code> if <code>array</code> is <code>null</code>.
* @param array the array to build a String representation for
* @return a String representation of <code>array</code>
*/
public static String nullSafeToString(int[] array) {
if (array == null) {
return NULL_STRING;
}
int length = array.length;
if (length == 0) {
return EMPTY_ARRAY;
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < length; i++) {
if (i == 0) {
sb.append(ARRAY_START);
}
else {
sb.append(ARRAY_ELEMENT_SEPARATOR);
}
sb.append(array[i]);
}
sb.append(ARRAY_END);
return sb.toString();
}
/**
* Return a String representation of the contents of the specified array.
* <p>The String representation consists of a list of the array's elements,
* enclosed in curly braces (<code>"{}"</code>). Adjacent elements are separated
* by the characters <code>", "</code> (a comma followed by a space). Returns
* <code>"null"</code> if <code>array</code> is <code>null</code>.
* @param array the array to build a String representation for
* @return a String representation of <code>array</code>
*/
public static String nullSafeToString(long[] array) {
if (array == null) {
return NULL_STRING;
}
int length = array.length;
if (length == 0) {
return EMPTY_ARRAY;
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < length; i++) {
if (i == 0) {
sb.append(ARRAY_START);
}
else {
sb.append(ARRAY_ELEMENT_SEPARATOR);
}
sb.append(array[i]);
}
sb.append(ARRAY_END);
return sb.toString();
}
/**
* Return a String representation of the contents of the specified array.
* <p>The String representation consists of a list of the array's elements,
* enclosed in curly braces (<code>"{}"</code>). Adjacent elements are separated
* by the characters <code>", "</code> (a comma followed by a space). Returns
* <code>"null"</code> if <code>array</code> is <code>null</code>.
* @param array the array to build a String representation for
* @return a String representation of <code>array</code>
*/
public static String nullSafeToString(short[] array) {
if (array == null) {
return NULL_STRING;
}
int length = array.length;
if (length == 0) {
return EMPTY_ARRAY;
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < length; i++) {
if (i == 0) {
sb.append(ARRAY_START);
}
else {
sb.append(ARRAY_ELEMENT_SEPARATOR);
}
sb.append(array[i]);
}
sb.append(ARRAY_END);
return sb.toString();
}
}

View File

@ -0,0 +1,127 @@
/*
* Copyright 2002-2009 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.openjpa.eclipse.util.pathmatch;
import java.util.Comparator;
import java.util.Map;
/**
* Strategy interface for <code>String</code>-based path matching.
*
* <p>Used by {@link org.springframework.core.io.support.PathMatchingResourcePatternResolver},
* {@link org.springframework.web.servlet.handler.AbstractUrlHandlerMapping},
* {@link org.springframework.web.servlet.mvc.multiaction.PropertiesMethodNameResolver},
* and {@link org.springframework.web.servlet.mvc.WebContentInterceptor}.
*
* <p>The default implementation is {@link AntPathMatcher}, supporting the
* Ant-style pattern syntax.
*
* @author Juergen Hoeller
* @since 1.2
* @see AntPathMatcher
*/
public interface PathMatcher {
/**
* Does the given <code>path</code> represent a pattern that can be matched
* by an implementation of this interface?
* <p>If the return value is <code>false</code>, then the {@link #match}
* method does not have to be used because direct equality comparisons
* on the static path Strings will lead to the same result.
* @param path the path String to check
* @return <code>true</code> if the given <code>path</code> represents a pattern
*/
boolean isPattern(String path);
/**
* Match the given <code>path</code> against the given <code>pattern</code>,
* according to this PathMatcher's matching strategy.
* @param pattern the pattern to match against
* @param path the path String to test
* @return <code>true</code> if the supplied <code>path</code> matched,
* <code>false</code> if it didn't
*/
boolean match(String pattern, String path);
/**
* Match the given <code>path</code> against the corresponding part of the given
* <code>pattern</code>, according to this PathMatcher's matching strategy.
* <p>Determines whether the pattern at least matches as far as the given base
* path goes, assuming that a full path may then match as well.
* @param pattern the pattern to match against
* @param path the path String to test
* @return <code>true</code> if the supplied <code>path</code> matched,
* <code>false</code> if it didn't
*/
boolean matchStart(String pattern, String path);
/**
* Given a pattern and a full path, determine the pattern-mapped part.
* <p>This method is supposed to find out which part of the path is matched
* dynamically through an actual pattern, that is, it strips off a statically
* defined leading path from the given full path, returning only the actually
* pattern-matched part of the path.
* <p>For example: For "myroot/*.html" as pattern and "myroot/myfile.html"
* as full path, this method should return "myfile.html". The detailed
* determination rules are specified to this PathMatcher's matching strategy.
* <p>A simple implementation may return the given full path as-is in case
* of an actual pattern, and the empty String in case of the pattern not
* containing any dynamic parts (i.e. the <code>pattern</code> parameter being
* a static path that wouldn't qualify as an actual {@link #isPattern pattern}).
* A sophisticated implementation will differentiate between the static parts
* and the dynamic parts of the given path pattern.
* @param pattern the path pattern
* @param path the full path to introspect
* @return the pattern-mapped part of the given <code>path</code>
* (never <code>null</code>)
*/
String extractPathWithinPattern(String pattern, String path);
/**
* Given a pattern and a full path, extract the URI template variables. URI template
* variables are expressed through curly brackets ('{' and '}').
* <p>For example: For pattern "/hotels/{hotel}" and path "/hotels/1", this method will
* return a map containing "hotel"->"1".
*
* @param pattern the path pattern, possibly containing URI templates
* @param path the full path to extract template variables from
* @return a map, containing variable names as keys; variables values as values
*/
Map<String, String> extractUriTemplateVariables(String pattern, String path);
/**
* Given a full path, returns a {@link Comparator} suitable for sorting patterns in order of explicitness for that path.
* <p>The full algorithm used depends on the underlying implementation, but generally, the returned
* <code>Comparator</code> will {@linkplain java.util.Collections#sort(java.util.List, java.util.Comparator) sort} a
* list so that more specific patterns (for that come before generic patterns.
*
* @param path the full path to use for comparison
* @return a comparator capable of sorting patterns in order of explicitness
*/
Comparator<String> getPatternComparator(String path);
/**
* Combines two patterns into a new pattern that is returned.
* <p>The full algorithm used for combining the two pattern depends on the underlying implementation.
*
* @param pattern1 the first pattern
* @param pattern2 the second pattern
* @return the combination of the two patterns
* @throws IllegalArgumentException when the two patterns cannot be combined
*/
String combine(String pattern1, String pattern2);
}

View File

@ -0,0 +1,380 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
======================================
LICENSES FOR INCLUDED DEPENDENCIES
======================================
All the source code for the OpenJPA project is released under the
license above. Additionally, the OpenJPA binary distribution
includes a number of third-party files that are required in
order to the software to function. Unless noted below, these jars
and resource files are also released under the ASF license above.
The exceptions are as follows:
===========================
orm-xsd.rsrc - included in the openjpa jar, taken from:
http://java.sun.com/xml/ns/persistence/orm_1_0.xsd)
persistence-xsd.rsrc - included in the openjpa jar, taken from:
http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd)
websphere-uow-api.jar - this jar file contains WebSphere proprietary
API code which is licensed for use when compiling OpenJPA. The
jar is not distributed with OpenJPA and is only included with the
source archive in order to resolve compilation dependencies.
===========================
COMMON DEVELOPMENT AND DISTRIBUTION LICENSE (CDDL) Version 1.0
1. Definitions.
1.1. Contributor means each individual or entity that creates or contributes to the creation of Modifications.
1.2. Contributor Version means the combination of the Original Software, prior Modifications used by a Contributor (if any), and the Modifications made by that particular Contributor.
1.3. Covered Software means (a) the Original Software, or (b) Modifications, or (c) the combination of files containing Original Software with files containing Modifications, in each case including portions thereof.
1.4. Executable means the Covered Software in any form other than Source Code.
1.5. Initial Developer means the individual or entity that first makes Original Software available under this License.
1.6. Larger Work means a work which combines Covered Software or portions thereof with code not governed by the terms of this License.
1.7. License means this document.
1.8. Licensable means having the right to grant, to the maximum extent possible, whether at the time of the initial grant or subsequently acquired, any and all of the rights conveyed herein.
1.9. Modifications means the Source Code and Executable form of any of the following:
A. Any file that results from an addition to, deletion from or modification of the contents of a file containing Original Software or previous Modifications;
B. Any new file that contains any part of the Original Software or previous Modification; or
C. Any new file that is contributed or otherwise made available under the terms of this License.
1.10. Original Software means the Source Code and Executable form of computer software code that is originally released under this License.
1.11. Patent Claims means any patent claim(s), now owned or hereafter acquired, including without limitation, method, process, and apparatus claims, in any patent Licensable by grantor.
1.12. Source Code means (a) the common form of computer software code in which modifications are made and (b) associated documentation included in or with such code.
1.13. You (or Your) means an individual or a legal entity exercising rights under, and complying with all of the terms of, this License. For legal entities, You includes any entity which controls, is controlled by, or is under common control with You. For purposes of this definition, control means (a)<29>the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (b)<29>ownership of more than fifty percent (50%) of the outstanding shares or beneficial ownership of such entity.
2. License Grants.
2.1. The Initial Developer Grant.
Conditioned upon Your compliance with Section 3.1 below and subject to third party intellectual property claims, the Initial Developer hereby grants You a world-wide, royalty-free, non-exclusive license:
(a) under intellectual property rights (other than patent or trademark) Licensable by Initial Developer, to use, reproduce, modify, display, perform, sublicense and distribute the Original Software (or portions thereof), with or without Modifications, and/or as part of a Larger Work; and
(b) under Patent Claims infringed by the making, using or selling of Original Software, to make, have made, use, practice, sell, and offer for sale, and/or otherwise dispose of the Original Software (or portions thereof).
(c) The licenses granted in Sections<6E>2.1(a) and (b) are effective on the date Initial Developer first distributes or otherwise makes the Original Software available to a third party under the terms of this License.
(d) Notwithstanding Section<6F>2.1(b) above, no patent license is granted: (1)<29>for code that You delete from the Original Software, or (2)<29>for infringements caused by: (i)<29>the modification of the Original Software, or (ii)<29>the combination of the Original Software with other software or devices.
2.2. Contributor Grant.
Conditioned upon Your compliance with Section 3.1 below and subject to third party intellectual property claims, each Contributor hereby grants You a world-wide, royalty-free, non-exclusive license:
(a) under intellectual property rights (other than patent or trademark) Licensable by Contributor to use, reproduce, modify, display, perform, sublicense and distribute the Modifications created by such Contributor (or portions thereof), either on an unmodified basis, with other Modifications, as Covered Software and/or as part of a Larger Work; and
(b) under Patent Claims infringed by the making, using, or selling of Modifications made by that Contributor either alone and/or in combination with its Contributor Version (or portions of such combination), to make, use, sell, offer for sale, have made, and/or otherwise dispose of: (1)<29>Modifications made by that Contributor (or portions thereof); and (2)<29>the combination of Modifications made by that Contributor with its Contributor Version (or portions of such combination).
(c) The licenses granted in Sections<6E>2.2(a) and 2.2(b) are effective on the date Contributor first distributes or otherwise makes the Modifications available to a third party.
(d) Notwithstanding Section<6F>2.2(b) above, no patent license is granted: (1)<29>for any code that Contributor has deleted from the Contributor Version; (2)<29>for infringements caused by: (i)<29>third party modifications of Contributor Version, or (ii)<29>the combination of Modifications made by that Contributor with other software (except as part of the Contributor Version) or other devices; or (3)<29>under Patent Claims infringed by Covered Software in the absence of Modifications made by that Contributor.
3. Distribution Obligations.
3.1. Availability of Source Code.
Any Covered Software that You distribute or otherwise make available in Executable form must also be made available in Source Code form and that Source Code form must be distributed only under the terms of this License. You must include a copy of this License with every copy of the Source Code form of the Covered Software You distribute or otherwise make available. You must inform recipients of any such Covered Software in Executable form as to how they can obtain such Covered Software in Source Code form in a reasonable manner on or through a medium customarily used for software exchange.
3.2. Modifications.
The Modifications that You create or to which You contribute are governed by the terms of this License. You represent that You believe Your Modifications are Your original creation(s) and/or You have sufficient rights to grant the rights conveyed by this License.
3.3. Required Notices.
You must include a notice in each of Your Modifications that identifies You as the Contributor of the Modification. You may not remove or alter any copyright, patent or trademark notices contained within the Covered Software, or any notices of licensing or any descriptive text giving attribution to any Contributor or the Initial Developer.
3.4. Application of Additional Terms.
You may not offer or impose any terms on any Covered Software in Source Code form that alters or restricts the applicable version of this License or the recipients rights hereunder. You may choose to offer, and to charge a fee for, warranty, support, indemnity or liability obligations to one or more recipients of Covered Software. However, you may do so only on Your own behalf, and not on behalf of the Initial Developer or any Contributor. You must make it absolutely clear that any such warranty, support, indemnity or liability obligation is offered by You alone, and You hereby agree to indemnify the Initial Developer and every Contributor for any liability incurred by the Initial Developer or such Contributor as a result of warranty, support, indemnity or liability terms You offer.
3.5. Distribution of Executable Versions.
You may distribute the Executable form of the Covered Software under the terms of this License or under the terms of a license of Your choice, which may contain terms different from this License, provided that You are in compliance with the terms of this License and that the license for the Executable form does not attempt to limit or alter the recipients rights in the Source Code form from the rights set forth in this License. If You distribute the Covered Software in Executable form under a different license, You must make it absolutely clear that any terms which differ from this License are offered by You alone, not by the Initial Developer or Contributor. You hereby agree to indemnify the Initial Developer and every Contributor for any liability incurred by the Initial Developer or such Contributor as a result of any such terms You offer.
3.6. Larger Works.
You may create a Larger Work by combining Covered Software with other code not governed by the terms of this License and distribute the Larger Work as a single product. In such a case, You must make sure the requirements of this License are fulfilled for the Covered Software.
4. Versions of the License.
4.1. New Versions.
Sun Microsystems, Inc. is the initial license steward and may publish revised and/or new versions of this License from time to time. Each version will be given a distinguishing version number. Except as provided in Section 4.3, no one other than the license steward has the right to modify this License.
4.2. Effect of New Versions.
You may always continue to use, distribute or otherwise make the Covered Software available under the terms of the version of the License under which You originally received the Covered Software. If the Initial Developer includes a notice in the Original Software prohibiting it from being distributed or otherwise made available under any subsequent version of the License, You must distribute and make the Covered Software available under the terms of the version of the License under which You originally received the Covered Software. Otherwise, You may also choose to use, distribute or otherwise make the Covered Software available under the terms of any subsequent version of the License published by the license steward.
4.3. Modified Versions.
When You are an Initial Developer and You want to create a new license for Your Original Software, You may create and use a modified version of this License if You: (a)<29>rename the license and remove any references to the name of the license steward (except to note that the license differs from this License); and (b)<29>otherwise make it clear that the license contains terms which differ from this License.
5. DISCLAIMER OF WARRANTY.
COVERED SOFTWARE IS PROVIDED UNDER THIS LICENSE ON AN AS IS BASIS, WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, WARRANTIES THAT THE COVERED SOFTWARE IS FREE OF DEFECTS, MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE OR NON-INFRINGING. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE COVERED SOFTWARE IS WITH YOU. SHOULD ANY COVERED SOFTWARE PROVE DEFECTIVE IN ANY RESPECT, YOU (NOT THE INITIAL DEVELOPER OR ANY OTHER CONTRIBUTOR) ASSUME THE COST OF ANY NECESSARY SERVICING, REPAIR OR CORRECTION. THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. NO USE OF ANY COVERED SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER THIS DISCLAIMER.
6. TERMINATION.
6.1. This License and the rights granted hereunder will terminate automatically if You fail to comply with terms herein and fail to cure such breach within 30 days of becoming aware of the breach. Provisions which, by their nature, must remain in effect beyond the termination of this License shall survive.
6.2. If You assert a patent infringement claim (excluding declaratory judgment actions) against Initial Developer or a Contributor (the Initial Developer or Contributor against whom You assert such claim is referred to as Participant) alleging that the Participant Software (meaning the Contributor Version where the Participant is a Contributor or the Original Software where the Participant is the Initial Developer) directly or indirectly infringes any patent, then any and all rights granted directly or indirectly to You by such Participant, the Initial Developer (if the Initial Developer is not the Participant) and all Contributors under Sections<6E>2.1 and/or 2.2 of this License shall, upon 60 days notice from Participant terminate prospectively and automatically at the expiration of such 60 day notice period, unless if within such 60 day period You withdraw Your claim with respect to the Participant Software against such Participant either unilaterally or pursuant to a written agreement with Participant.
6.3. In the event of termination under Sections<6E>6.1 or 6.2 above, all end user licenses that have been validly granted by You or any distributor hereunder prior to termination (excluding licenses granted to You by any distributor) shall survive termination.
7. LIMITATION OF LIABILITY.
UNDER NO CIRCUMSTANCES AND UNDER NO LEGAL THEORY, WHETHER TORT (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, SHALL YOU, THE INITIAL DEVELOPER, ANY OTHER CONTRIBUTOR, OR ANY DISTRIBUTOR OF COVERED SOFTWARE, OR ANY SUPPLIER OF ANY OF SUCH PARTIES, BE LIABLE TO ANY PERSON FOR ANY INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES OF ANY CHARACTER INCLUDING, WITHOUT LIMITATION, DAMAGES FOR LOST PROFITS, LOSS OF GOODWILL, WORK STOPPAGE, COMPUTER FAILURE OR MALFUNCTION, OR ANY AND ALL OTHER COMMERCIAL DAMAGES OR LOSSES, EVEN IF SUCH PARTY SHALL HAVE BEEN INFORMED OF THE POSSIBILITY OF SUCH DAMAGES. THIS LIMITATION OF LIABILITY SHALL NOT APPLY TO LIABILITY FOR DEATH OR PERSONAL INJURY RESULTING FROM SUCH PARTYS NEGLIGENCE TO THE EXTENT APPLICABLE LAW PROHIBITS SUCH LIMITATION. SOME JURISDICTIONS DO NOT ALLOW THE EXCLUSION OR LIMITATION OF INCIDENTAL OR CONSEQUENTIAL DAMAGES, SO THIS EXCLUSION AND LIMITATION MAY NOT APPLY TO YOU.
8. U.S. GOVERNMENT END USERS.
The Covered Software is a commercial item, as that term is defined in 48<34>C.F.R.<2E>2.101 (Oct. 1995), consisting of commercial computer software (as that term is defined at 48 C.F.R. <20>252.227-7014(a)(1)) and commercial computer software documentation as such terms are used in 48<34>C.F.R.<2E>12.212 (Sept. 1995). Consistent with 48 C.F.R. 12.212 and 48 C.F.R. 227.7202-1 through 227.7202-4 (June 1995), all U.S. Government End Users acquire Covered Software with only those rights set forth herein. This U.S. Government Rights clause is in lieu of, and supersedes, any other FAR, DFAR, or other clause or provision that addresses Government rights in computer software under this License.
9. MISCELLANEOUS.
This License represents the complete agreement concerning subject matter hereof. If any provision of this License is held to be unenforceable, such provision shall be reformed only to the extent necessary to make it enforceable. This License shall be governed by the law of the jurisdiction specified in a notice contained within the Original Software (except to the extent applicable law, if any, provides otherwise), excluding such jurisdictions conflict-of-law provisions. Any litigation relating to this License shall be subject to the jurisdiction of the courts located in the jurisdiction and venue specified in a notice contained within the Original Software, with the losing party responsible for costs, including, without limitation, court costs and reasonable attorneys fees and expenses. The application of the United Nations Convention on Contracts for the International Sale of Goods is expressly excluded. Any law or regulation which provides that the language of a contract shall be construed against the drafter shall not apply to this License. You agree that You alone are responsible for compliance with the United States export administration regulations (and the export control laws and regulation of any other countries) when You use, distribute or otherwise make available any Covered Software.
10. RESPONSIBILITY FOR CLAIMS.
As between Initial Developer and the Contributors, each party is responsible for claims and damages arising, directly or indirectly, out of its utilization of rights under this License and You agree to work with Initial Developer and Contributors to distribute such responsibility on an equitable basis. Nothing herein is intended or shall be deemed to constitute any admission of liability.
NOTICE PURSUANT TO SECTION 9 OF THE COMMON DEVELOPMENT AND DISTRIBUTION LICENSE (CDDL)
The GlassFish code released under the CDDL shall be governed by the laws of the State of California (excluding conflict-of-law provisions). Any litigation relating to this License shall be subject to the jurisdiction of the Federal Courts of the Northern District of California and the state courts of the State of California, with venue lying in Santa Clara County, California.
===================
serp-1.11.0.jar
===================
Copyright (c) 2002-2006, A. Abram White
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of 'serp' nor the names of its contributors may
be used to endorse or promote products derived from this software without
specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

View File

@ -0,0 +1,51 @@
Manifest-Version: 1.0
Bundle-ManifestVersion: 2
Bundle-Name: OpenJPA Plug-in
Bundle-SymbolicName: org.apache.openjpa
Bundle-Version: 1.2.1.qualifier
Require-Bundle: org.apache.commons.logging
Eclipse-BuddyPolicy: dependent
Bundle-ClassPath: lib/geronimo-jms_1.1_spec-1.0.1.jar,
lib/geronimo-jpa_3.0_spec-1.0.jar,
lib/geronimo-jta_1.1_spec-1.1.jar,
lib/commons-collections-3.2.jar,
lib/commons-lang-2.1.jar,
lib/openjpa-1.2.1.jar,
lib/serp-1.13.1.jar,
.
Export-Package: javax.persistence,
javax.persistence.spi,
org.apache.openjpa.abstractstore,
org.apache.openjpa.ant,
org.apache.openjpa.conf,
org.apache.openjpa.datacache,
org.apache.openjpa.ee,
org.apache.openjpa.enhance,
org.apache.openjpa.event,
org.apache.openjpa.jdbc.ant,
org.apache.openjpa.jdbc.conf,
org.apache.openjpa.jdbc.kernel,
org.apache.openjpa.jdbc.kernel.exps,
org.apache.openjpa.jdbc.meta,
org.apache.openjpa.jdbc.meta.strats,
org.apache.openjpa.jdbc.schema,
org.apache.openjpa.jdbc.sql,
org.apache.openjpa.kernel,
org.apache.openjpa.kernel.exps,
org.apache.openjpa.kernel.jpql,
org.apache.openjpa.lib.ant,
org.apache.openjpa.lib.conf,
org.apache.openjpa.lib.graph,
org.apache.openjpa.lib.jdbc,
org.apache.openjpa.lib.log,
org.apache.openjpa.lib.meta,
org.apache.openjpa.lib.rop,
org.apache.openjpa.lib.util,
org.apache.openjpa.lib.util.concurrent,
org.apache.openjpa.lib.xml,
org.apache.openjpa.meta,
org.apache.openjpa.persistence,
org.apache.openjpa.persistence.jdbc,
org.apache.openjpa.util,
serp.bytecode
Bundle-RequiredExecutionEnvironment: JavaSE-1.6

View File

@ -0,0 +1,6 @@
This is OpenJPA, packaged as OSGi / Eclipse plug-in.
Other Eclipse plug-ins requiring OpenJPA will depend on this one.
Michael Vorburger, 9.12.2008

View File

@ -0,0 +1,11 @@
source.. = src/main/java/
output.. = target/
bin.includes = META-INF/,\
.,\
lib/commons-collections-3.2.jar,\
lib/commons-lang-2.1.jar,\
lib/geronimo-jms_1.1_spec-1.0.1.jar,\
lib/geronimo-jpa_3.0_spec-1.0.jar,\
lib/geronimo-jta_1.1_spec-1.1.jar,\
lib/openjpa-1.2.1.jar,\
lib/serp-1.13.1.jar

View File

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<launchConfiguration type="org.eclipse.ui.externaltools.ProgramLaunchConfigurationType">
<stringAttribute key="org.eclipse.debug.core.ATTR_REFRESH_SCOPE" value="${project}"/>
<stringAttribute key="org.eclipse.ui.externaltools.ATTR_LOCATION" value="${workspace_loc:/openjpa-openjpa/get-dependencies.bat}"/>
<stringAttribute key="org.eclipse.ui.externaltools.ATTR_WORKING_DIRECTORY" value="${workspace_loc:/openjpa-openjpa}"/>
</launchConfiguration>

View File

@ -0,0 +1,70 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<artifactId>org.apache.openjpa.eclipse.all</artifactId>
<groupId>org.apache.openjpa.eclipse</groupId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<groupId>org.apache.openjpa.eclipse</groupId>
<artifactId>org.apache.openjpa</artifactId>
<version>1.2.1</version>
<packaging>eclipse-plugin</packaging>
<name>OpenJPA packaged as OSGi/Eclipse plug-in</name>
<description>
OpenJPA packaged as OSGi/Eclipse plug-in
Currently this module only fetches dependencies, actual build to be added later.
</description>
<dependencies>
<dependency>
<groupId>org.apache.openjpa</groupId>
<artifactId>openjpa</artifactId>
<version>1.2.1</version>
<exclusions>
<exclusion>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
</exclusion>
<exclusion>
<groupId>commons-pool</groupId>
<artifactId>commons-pool</artifactId>
</exclusion>
<exclusion>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<executions>
<execution>
<id>copy-dependencies</id>
<phase>process-resources</phase>
<goals>
<goal>copy-dependencies</goal>
</goals>
<configuration>
<outputDirectory>lib</outputDirectory>
<overWriteReleases>true</overWriteReleases>
<overWriteSnapshots>true</overWriteSnapshots>
<overWriteIfNewer>true</overWriteIfNewer>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

63
contrib/devtools/pom.xml Normal file
View File

@ -0,0 +1,63 @@
<?xml version="1.0" encoding="UTF-8"?>
<project>
<modelVersion>4.0.0</modelVersion>
<groupId>org.apache.openjpa.eclipse</groupId>
<artifactId>org.apache.openjpa.eclipse.all</artifactId>
<version>1.0.0-SNAPSHOT</version>
<packaging>pom</packaging>
<properties>
<!-- <tycho-version>0.6.0-SNAPSHOT</tycho-version> -->
<tycho-version>0.5.0</tycho-version>
</properties>
<repositories>
<repository>
<id>galileo</id>
<layout>p2</layout>
<url>http://download.eclipse.org/releases/galileo</url>
</repository>
<repository>
<id>eclipse-3.5</id>
<layout>p2</layout>
<url>http://download.eclipse.org/eclipse/updates/3.5</url>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>sonatype-forge</id>
<url>http://repository.sonatype.org/content/groups/forge</url>
<releases>
<enabled>true</enabled>
</releases>
<snapshots>
<enabled>true</enabled>
</snapshots>
</pluginRepository>
</pluginRepositories>
<modules>
<module>org.apache.openjpa</module>
<module>org.apache.openjpa.eclipse</module>
<module>org.apache.openjpa.eclipse.tests</module>
<module>org.apache.openjpa.eclipse.feature</module>
<module>org.apache.openjpa.eclipse.site</module>
</modules>
<build>
<plugins>
<plugin>
<groupId>org.codehaus.tycho</groupId>
<artifactId>tycho-maven-plugin</artifactId>
<version>${tycho-version}</version>
<extensions>true</extensions>
</plugin>
<plugin>
<groupId>org.codehaus.tycho</groupId>
<artifactId>target-platform-configuration</artifactId>
<version>${tycho-version}</version>
<configuration>
<resolver>p2</resolver>
</configuration>
</plugin>
</plugins>
</build>
</project>