OPENJPA-1927:Add first few tests to try out the test environment

git-svn-id: https://svn.apache.org/repos/asf/openjpa/trunk@1061099 13f79535-47bb-0310-9956-ffa450edef68
This commit is contained in:
Pinaki Poddar 2011-01-20 01:57:42 +00:00
parent 6259f9a0bb
commit 40052c12ad
9 changed files with 702 additions and 1 deletions

View File

@ -55,6 +55,53 @@
<groupId>javax.servlet</groupId> <groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId> <artifactId>servlet-api</artifactId>
<version>2.4</version> <version>2.4</version>
<scope>provided</scope>
</dependency> </dependency>
<dependency>
<groupId>org.apache.openjpa</groupId>
<artifactId>openjpa-persistence-jdbc</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>httpunit</groupId>
<artifactId>httpunit</artifactId>
<version>1.7</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-jci-rhino</artifactId>
<version>1.0</version>
<scope>test</scope>
</dependency>
</dependencies> </dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-antrun-plugin</artifactId>
<executions>
<execution>
<phase>process-test-classes</phase>
<configuration>
<tasks>
<ant antfile="src/main/ant/enhancer.xml" target="enhance" inheritRefs="true">
<property name="maven.test.skip" value="${maven.test.skip}" />
<property name="test" value="${test}" />
<property name="outdir" value="${project.build.outputDirectory}" />
<property name="project.build.testOutputDirectory" value="${project.build.testOutputDirectory}" />
<property name="openjpa.Log" value="${openjpa.Log}" />
</ant>
</tasks>
</configuration>
<goals>
<goal>run</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project> </project>

View File

@ -0,0 +1,85 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you 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.
-->
<project name="enhance" basedir=".">
<!--
This build file executes the PCEnhancer on the test entities. It's in a
separate file instead of nested in pom.xml to make some conditional
processing easier.
Test classes will not be compiled if maven is invoked with
-Dmaven.test.skip=true.
-->
<condition property="maven.test.skip.istrue">
<istrue value="${maven.test.skip}" />
</condition>
<condition property="skip.enhance">
<or>
<equals arg1="${test}" arg2="false" />
<equals arg1="${build.enhance}" arg2="false" />
<istrue value="${maven.test.skip}" />
<istrue value="${skipTests}" />
</or>
</condition>
<!-- =================================
target: enhance
================================= -->
<target name="enhance"
description="--> run the enhancer unless test=false"
unless="skip.enhance">
<antcall target="enhance.all.entities"
inheritall="true"
inheritrefs="true" />
</target>
<!-- =================================
target: enhance.all.entities
================================= -->
<target name="enhance.all.entities"
description="--> enhance the test entities"
unless="skip.enhance">
<echo> running enhancer</echo>
<!--
Inherited references won't be present until the task is called.
Therefore the path definition needs to stay inside the task.
-->
<path id="cp">
<path refid="maven.test.classpath" />
</path>
<taskdef name="openjpac"
classname="org.apache.openjpa.ant.PCEnhancerTask">
<classpath refid="cp" />
</taskdef>
<fileset id="enhance.path.ref"
dir="${project.build.testOutputDirectory}">
<include name="**/*.class" />
<exclude name="**/Test*.class" />
</fileset>
<openjpac>
<classpath refid="cp" />
<fileset refid="enhance.path.ref" />
<config log="${openjpa.Log}" />
</openjpac>
</target>
</project>

View File

@ -115,7 +115,7 @@ public class JESTServlet extends HttpServlet {
protected void createPersistenceUnit() throws ServletException { protected void createPersistenceUnit() throws ServletException {
try { try {
System.err.println("Creating Standalone Persistent Unit " + _unit + ":" + _emf); System.err.println("Creating Standalone Persistent Unit " + _unit);
_emf = OpenJPAPersistence.cast(Persistence.createEntityManagerFactory(_unit)); _emf = OpenJPAPersistence.cast(Persistence.createEntityManagerFactory(_unit));
System.err.println("Created Standalone Persistent Unit " + _unit + ":" + _emf); System.err.println("Created Standalone Persistent Unit " + _unit + ":" + _emf);
} catch (Exception e) { } catch (Exception e) {

View File

@ -0,0 +1,110 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 demo;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import org.apache.openjpa.persistence.FetchAttribute;
import org.apache.openjpa.persistence.FetchGroup;
import org.apache.openjpa.persistence.FetchGroups;
/**
* A persistent entity with singular and plural association.
*
* @author Pinaki Poddar
*
*/
@Entity
@FetchGroups({
@FetchGroup(name="OnlyName", attributes={
@FetchAttribute(name="firstName"),
@FetchAttribute(name="lastName")
})
})
public class Actor {
public static enum Gender {Male, Female};
@Id
private String id;
private String firstName;
private String lastName;
private Gender gender;
private Date dob;
@OneToOne
private Actor partner;
@OneToMany
private Set<Movie> movies;
protected Actor() {
}
public Actor(String id, String firstName, String lastName, Gender gender, Date dob) {
super();
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
this.gender = gender;
this.dob = dob;
}
public String getId() {
return id;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public Gender getGender() {
return gender;
}
public Date getDob() {
return dob;
}
public Actor getPartner() {
return partner;
}
public void setPartner(Actor partner) {
this.partner = partner;
}
public Set<Movie> getMovies() {
return movies;
}
public void addMovie(Movie movie) {
if (movies == null)
movies = new HashSet<Movie>();
movies.add(movie);
}
}

View File

@ -0,0 +1,133 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 demo;
import java.util.Date;
import javax.persistence.EntityManager;
/**
* Loads some example Actor-Movie data.
*
* @author Pinaki Poddar
*
*/
public class DataLoader {
// Hand-tuned data for Testing
@SuppressWarnings("deprecation")
public static Object[][] ACTOR_DATA = {
new Object[] {"m1", "Robert", "Redford", Actor.Gender.Male, new Date(50, 1, 12)},
new Object[] {"m2", "Robert", "De Niro", Actor.Gender.Male, new Date(40, 4, 14)},
new Object[] {"m3", "Al", "Pacino", Actor.Gender.Male, new Date(50, 1, 12)},
new Object[] {"m4", "Jack", "Nichelson",Actor.Gender.Male, new Date(40, 4, 14)},
new Object[] {"m5", "Clint", "Eastwood", Actor.Gender.Male, new Date(50, 1, 12)},
new Object[] {"f1", "Meryl", "Streep", Actor.Gender.Female, new Date(40, 4, 14)},
new Object[] {"f2", "Fay", "Dunaway", Actor.Gender.Female, new Date(50, 1, 12)},
new Object[] {"f3", "Jodie", "Foster", Actor.Gender.Female, new Date(40, 4, 14)},
new Object[] {"f4", "Diane", "Keaton", Actor.Gender.Female, new Date(50, 1, 12)},
new Object[] {"f5", "Catherine", "Hepburn", Actor.Gender.Female, new Date(40, 4, 14)},
};
public static Object[][] MOVIE_DATA = {
new Object[] {"1", "China Town", 1980},
new Object[] {"2", "Taxi Driver", 1980},
new Object[] {"3", "Where Eagles Dare", 1980},
new Object[] {"4", "Godfather", 1980},
new Object[] {"5", "Horse Whisperer", 1980},
};
public static int[][] MOVIE_ACTORS = {
new int[] {3,6},
new int[] {1,7},
new int[] {4},
new int[] {2,3,8},
new int[] {0}
};
public static int[][] PARTNERS = {
new int[] {3,6},
new int[] {1,7},
new int[] {3,8},
};
public void populate(EntityManager em) throws Exception {
Long count = em.createQuery("select count(m) from Movie m", Long.class).getSingleResult();
if (count != null && count.longValue() > 0) {
System.err.println("Found " + count + " Movie records in the database");
return;
}
Actor[] actors = createActors();
Movie[] movies = createMovies();
linkActorAndMovie(movies, actors);
makePartner(actors);
em.getTransaction().begin();
for (Actor a : actors) {
em.persist(a);
}
for (Movie m : movies) {
em.persist(m);
}
em.getTransaction().commit();
}
Actor[] createActors() {
Actor[] actors = new Actor[ACTOR_DATA.length];
for (int i = 0; i < ACTOR_DATA.length; i++) {
Object[] a = ACTOR_DATA[i];
actors[i] = new Actor((String)a[0], (String)a[1], (String)a[2], (Actor.Gender)a[3], (Date)a[4]);
}
return actors;
}
Movie[] createMovies() {
Movie[] movies = new Movie[MOVIE_DATA.length];
for (int i = 0; i < MOVIE_DATA.length; i++) {
Object[] m = MOVIE_DATA[i];
movies[i] = new Movie((String)m[0], (String)m[1], (Integer)m[2]);
}
return movies;
}
void linkActorAndMovie(Movie[] movies, Actor[] actors) {
for (int i = 0; i < MOVIE_ACTORS.length; i++) {
int[] roles = MOVIE_ACTORS[i];
Movie m = movies[i];
for (int j = 0; j < roles.length; j++) {
Actor a = actors[roles[j]];
a.addMovie(m);
m.addActor(a);
}
}
}
void makePartner(Actor[] actors) {
for (int i = 0; i < PARTNERS.length; i++) {
int[] partners = PARTNERS[i];
Actor a1 = actors[partners[0]];
Actor a2 = actors[partners[1]];
a1.setPartner(a2);
a2.setPartner(a1);
}
}
}

View File

@ -0,0 +1,86 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 demo;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import org.apache.openjpa.persistence.FetchAttribute;
import org.apache.openjpa.persistence.FetchGroup;
import org.apache.openjpa.persistence.FetchGroups;
/**
* @author Pinaki Poddar
*
*/
@Entity
@FetchGroups({
@FetchGroup(name="OnlyTitle", attributes={
@FetchAttribute(name="title")
})
})
public class Movie {
@Id
private String id;
private String title;
private int year;
@OneToMany(fetch=FetchType.EAGER)
private Set<Actor> actors;
protected Movie() {
}
public Movie(String id, String title, int year) {
super();
this.id = id;
this.title = title;
this.year = year;
}
public String getId() {
return id;
}
public String getTitle() {
return title;
}
public void addActor(Actor a) {
if (actors == null)
actors = new HashSet<Actor>();
actors.add(a);
}
public Set<Actor> getActors() {
return actors;
}
public int getYear() {
return year;
}
}

View File

@ -0,0 +1,158 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.persistence.jest;
import java.io.InputStream;
import java.net.HttpURLConnection;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import junit.framework.TestCase;
import com.meterware.httpunit.HTMLElement;
import com.meterware.httpunit.HttpException;
import com.meterware.httpunit.HttpUnitOptions;
import com.meterware.httpunit.WebResponse;
import com.meterware.servletunit.ServletRunner;
import com.meterware.servletunit.ServletUnitClient;
/**
* Tests JEST Servlet using <A href="http://httpunit.sourceforge.net/doc/servletunit-intro.html">ServletUnit</A>.
*
* Sets up a class-level Servlet Runner (an in-process Servlet Engine).
*
* Recognizes following JVM system property
* <OL>
* <LI><tt>jest.web.xml</tt> : web descriptor resource name looked up as a resource in the current
* thread context. Defaults to <tt>WEB-INF/web.xml</tt>
* <LI><tt>jest.base.uri</tt> : base uri for all request. Defaults to <tt>http://localhost/jest</tt>
*
*
* @author Pinaki Poddar
*
*/
public class TestJEST extends TestCase {
private static ServletRunner container;
private static String baseURI;
private static String DEFAULT_WEB_XML = "WEB-INF/web.xml";
private static String DEFAULT_BASE_URI = "http://localhost/jest";
private static DocumentBuilder _xmlParser;
private static XPathFactory _xpathFactory;
/**
* Sets up a class-wide Servlet Engine.
*/
protected void setUp() throws Exception {
super.setUp();
if (container == null) {
String resource = System.getProperty("jest.web.xml", DEFAULT_WEB_XML);
System.err.println("Starting Servlet Container from " + resource);
InputStream wdesc = Thread.currentThread().getContextClassLoader().getResourceAsStream(resource);
assertNotNull(resource + " not loadable at thread context classpath", wdesc);
container = new ServletRunner(wdesc);
assertNotNull("Servlet engine could not be started", container);
baseURI = System.getProperty("jest.base.uri", DEFAULT_BASE_URI);
System.err.println("Base URI " + baseURI);
_xmlParser = DocumentBuilderFactory.newInstance().newDocumentBuilder();
_xpathFactory = XPathFactory.newInstance();
}
HttpUnitOptions.setExceptionsThrownOnErrorStatus(true);
HttpUnitOptions.setScriptingEnabled(false);
HttpUnitOptions.setExceptionsThrownOnScriptError(false);
}
public void testBadURL() throws Exception {
assertError(HttpURLConnection.HTTP_NOT_FOUND, uri("some+bad+url"));
}
public void testDomain() throws Exception {
WebResponse response = getResponse(uri("domain"));
assertNotNull(response);
System.err.println(response.getText());
assertEquals("text/xml", response.getContentType());
Document doc = _xmlParser.parse(response.getInputStream());
assertNotNull(doc);
Node metamodel = getNode(doc, "/metamodel");
assertNotNull(metamodel);
NodeList entities = getNodes(doc, "/metamodel/entity");
assertEquals(2, ((NodeList)entities).getLength());
}
/**
* Gets the response for the given URL.
*/
WebResponse getResponse(String url) {
try {
ServletUnitClient client = container.newClient();
return client.getResponse(url);
} catch (Exception e) {
e.printStackTrace();
fail("Failed to get response on " + url + ". Error: " + e.getMessage());
}
return null;
}
/**
* Create a URI string for the given path with the base URI prepended.
*/
protected String uri(String path) {
return baseURI + '/' + path;
}
/**
* Asserts that the given URL generates the given error code.
* @param error HTTP error code
* @param url URL string
*/
void assertError(int error, String url) throws Exception {
ServletUnitClient client = container.newClient();
try {
client.getResponse(url);
fail("expected HTTP error " + error + " on " + url);
} catch (HttpException e) {
assertEquals("Unexpected HTTP Error code for " + url, error, e.getResponseCode());
}
}
NodeList getNodes(Document doc, String path) throws Exception {
XPath xpath = _xpathFactory.newXPath();
Object nodes = xpath.compile(path).evaluate(doc, XPathConstants.NODESET);
assertTrue(nodes instanceof NodeList);
return (NodeList)nodes;
}
Node getNode(Document doc, String path) throws Exception {
XPath xpath = _xpathFactory.newXPath();
Object node = xpath.compile(path).evaluate(doc, XPathConstants.NODE);
assertTrue(node instanceof Node);
return (Node)node;
}
}

View File

@ -0,0 +1,39 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you 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.
-->
<persistence xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
version="1.0">
<persistence-unit name="test-jest">
<provider>org.apache.openjpa.persistence.PersistenceProviderImpl</provider>
<class>demo.Movie</class>
<class>demo.Actor</class>
<properties>
<property name="openjpa.Log" value="Tool=Trace,SQL=TRACE,JEST=TRACE"/>
<property name="openjpa.jdbc.SynchronizeMappings" value="buildSchema(ForeignKeys=true)"/>
<property name="openjpa.InitializeEagerly" value="true"/>
</properties>
</persistence-unit>
</persistence>

View File

@ -0,0 +1,43 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you 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.
-->
<web-app version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<!-- Deployment descriptor for JESTServlet. -->
<servlet>
<servlet-name>jest</servlet-name>
<servlet-class>org.apache.openjpa.persistence.jest.JESTServlet</servlet-class>
<init-param>
<param-name>persistence.unit</param-name>
<param-value>test-jest</param-value>
</init-param>
<init-param>
<param-name>standalone</param-name>
<param-value>true</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>jest</servlet-name>
<url-pattern>/jest/*</url-pattern>
</servlet-mapping>
</web-app>