Hibernate SVN: r17051 - in jpamodelgen/trunk/generator/src/main/java/org/hibernate/jpa/metamodel/ap: xml and 1 other directory.
by hibernate-commits@lists.jboss.org
Author: hardy.ferentschik
Date: 2009-07-08 11:00:18 -0400 (Wed, 08 Jul 2009)
New Revision: 17051
Modified:
jpamodelgen/trunk/generator/src/main/java/org/hibernate/jpa/metamodel/ap/JPAMetaModelEntityProcessor.java
jpamodelgen/trunk/generator/src/main/java/org/hibernate/jpa/metamodel/ap/xml/XmlMetaEntity.java
Log:
added support for embeddable
Modified: jpamodelgen/trunk/generator/src/main/java/org/hibernate/jpa/metamodel/ap/JPAMetaModelEntityProcessor.java
===================================================================
--- jpamodelgen/trunk/generator/src/main/java/org/hibernate/jpa/metamodel/ap/JPAMetaModelEntityProcessor.java 2009-07-08 14:38:54 UTC (rev 17050)
+++ jpamodelgen/trunk/generator/src/main/java/org/hibernate/jpa/metamodel/ap/JPAMetaModelEntityProcessor.java 2009-07-08 15:00:18 UTC (rev 17051)
@@ -150,8 +150,14 @@
if ( mappings == null ) {
return;
}
+
+ parseEntities( mappings );
+ parseEmbeddable( mappings );
+ }
+
+ private void parseEntities(EntityMappings mappings) {
+ String packageName = mappings.getPackage();
Collection<Entity> entities = mappings.getEntity();
- String packageName = mappings.getPackage();
for ( Entity entity : entities ) {
String fullyQualifiedClassName = packageName + "." + entity.getClazz();
Elements utils = processingEnv.getElementUtils();
@@ -169,6 +175,26 @@
}
}
+ private void parseEmbeddable(EntityMappings mappings) {
+ String packageName = mappings.getPackage();
+ Collection<org.hibernate.jpa.metamodel.xml.jaxb.Embeddable> embeddables = mappings.getEmbeddable();
+ for ( org.hibernate.jpa.metamodel.xml.jaxb.Embeddable embeddable : embeddables ) {
+ String fullyQualifiedClassName = packageName + "." + embeddable.getClazz();
+ Elements utils = processingEnv.getElementUtils();
+ XmlMetaEntity metaEntity = new XmlMetaEntity(
+ embeddable, packageName, utils.getTypeElement( fullyQualifiedClassName )
+ );
+
+ if ( metaEntities.containsKey( fullyQualifiedClassName ) ) {
+ processingEnv.getMessager().printMessage(
+ Diagnostic.Kind.WARNING,
+ fullyQualifiedClassName + " was already processed once. Skipping second occurance."
+ );
+ }
+ metaEntities.put( fullyQualifiedClassName, metaEntity );
+ }
+ }
+
private void handleRootElementAnnotationMirrors(final Element element) {
List<? extends AnnotationMirror> annotationMirrors = element
Modified: jpamodelgen/trunk/generator/src/main/java/org/hibernate/jpa/metamodel/ap/xml/XmlMetaEntity.java
===================================================================
--- jpamodelgen/trunk/generator/src/main/java/org/hibernate/jpa/metamodel/ap/xml/XmlMetaEntity.java 2009-07-08 14:38:54 UTC (rev 17050)
+++ jpamodelgen/trunk/generator/src/main/java/org/hibernate/jpa/metamodel/ap/xml/XmlMetaEntity.java 2009-07-08 15:00:18 UTC (rev 17051)
@@ -37,6 +37,8 @@
import org.hibernate.jpa.metamodel.xml.jaxb.Id;
import org.hibernate.jpa.metamodel.xml.jaxb.ManyToOne;
import org.hibernate.jpa.metamodel.xml.jaxb.OneToMany;
+import org.hibernate.jpa.metamodel.xml.jaxb.Embeddable;
+import org.hibernate.jpa.metamodel.xml.jaxb.EmbeddableAttributes;
/**
* @author Hardy Ferentschik
@@ -52,7 +54,7 @@
COLLECTIONS.put( "java.util.Map", "javax.persistence.metamodel.MapAttribute" );
}
- final private Entity ormEntity;
+ final private String clazzName;
final private String packageName;
@@ -63,7 +65,7 @@
private TypeElement element;
public XmlMetaEntity(Entity ormEntity, String packageName, TypeElement element) {
- this.ormEntity = ormEntity;
+ this.clazzName = ormEntity.getClazz();
this.packageName = packageName;
importContext = new ImportContextImpl( getPackageName() );
this.element = element;
@@ -96,8 +98,40 @@
}
}
+ public XmlMetaEntity(Embeddable embeddable, String packageName, TypeElement element) {
+ this.clazzName = embeddable.getClazz();
+ this.packageName = packageName;
+ importContext = new ImportContextImpl( getPackageName() );
+ this.element = element;
+ EmbeddableAttributes attributes = embeddable.getAttributes();
+
+ XmlMetaSingleAttribute attribute;
+ for ( Basic basic : attributes.getBasic() ) {
+ attribute = new XmlMetaSingleAttribute( this, basic.getName(), getType( basic.getName() ) );
+ members.add( attribute );
+ }
+
+ for ( ManyToOne manyToOne : attributes.getManyToOne() ) {
+ attribute = new XmlMetaSingleAttribute( this, manyToOne.getName(), getType( manyToOne.getName() ) );
+ members.add( attribute );
+ }
+
+ XmlMetaCollection metaCollection;
+ for ( OneToMany oneToMany : attributes.getOneToMany() ) {
+ String[] types = getCollectionType( oneToMany.getName() );
+ metaCollection = new XmlMetaCollection( this, oneToMany.getName(), types[0], types[1] );
+ members.add( metaCollection );
+ }
+
+ for ( ElementCollection collection : attributes.getElementCollection() ) {
+ String[] types = getCollectionType( collection.getName() );
+ metaCollection = new XmlMetaCollection( this, collection.getName(), types[0], types[1] );
+ members.add( metaCollection );
+ }
+ }
+
public String getSimpleName() {
- return ormEntity.getClazz();
+ return clazzName;
}
public String getQualifiedName() {
14 years, 10 months
Hibernate SVN: r17050 - in jpamodelgen/trunk/test: src/main/java/model and 6 other directories.
by hibernate-commits@lists.jboss.org
Author: hardy.ferentschik
Date: 2009-07-08 10:38:54 -0400 (Wed, 08 Jul 2009)
New Revision: 17050
Added:
jpamodelgen/trunk/test/src/main/java/model/xmlmapped/
jpamodelgen/trunk/test/src/main/java/model/xmlmapped/Address.java
jpamodelgen/trunk/test/src/main/resources/META-INF/address.xml
jpamodelgen/trunk/test/src/main/resources/META-INF/order.xml
jpamodelgen/trunk/test/src/test/java/tests/
jpamodelgen/trunk/test/src/test/java/tests/AccessTypeTest.java
jpamodelgen/trunk/test/src/test/java/tests/InheritanceTest.java
jpamodelgen/trunk/test/src/test/java/tests/QueryTest.java
jpamodelgen/trunk/test/src/test/java/tests/XmlMappingTest.java
jpamodelgen/trunk/test/src/test/suite/
jpamodelgen/trunk/test/src/test/suite/unit-tests.xml
Removed:
jpamodelgen/trunk/test/src/main/resources/META-INF/orm.xml
jpamodelgen/trunk/test/src/test/java/AccessTypeTest.java
jpamodelgen/trunk/test/src/test/java/InheritanceTest.java
jpamodelgen/trunk/test/src/test/java/QueryTest.java
Modified:
jpamodelgen/trunk/test/pom.xml
jpamodelgen/trunk/test/src/main/resources/META-INF/persistence.xml
Log:
added a test suite file and started with xml mapping tests
Modified: jpamodelgen/trunk/test/pom.xml
===================================================================
--- jpamodelgen/trunk/test/pom.xml 2009-07-08 14:16:31 UTC (rev 17049)
+++ jpamodelgen/trunk/test/pom.xml 2009-07-08 14:38:54 UTC (rev 17050)
@@ -119,6 +119,11 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
+ <configuration>
+ <suiteXmlFiles>
+ <suiteXmlFile>${basedir}/src/test/suite/unit-tests.xml</suiteXmlFile>
+ </suiteXmlFiles>
+ </configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
Copied: jpamodelgen/trunk/test/src/main/java/model/xmlmapped/Address.java (from rev 17048, jpamodelgen/trunk/test/src/main/java/model/Address.java)
===================================================================
--- jpamodelgen/trunk/test/src/main/java/model/xmlmapped/Address.java (rev 0)
+++ jpamodelgen/trunk/test/src/main/java/model/xmlmapped/Address.java 2009-07-08 14:38:54 UTC (rev 17050)
@@ -0,0 +1,34 @@
+package model.xmlmapped;
+
+/**
+ * @author Emmanuel Bernard
+ */
+public class Address {
+ private String street1;
+ private String city;
+ private String country;
+
+ public String getStreet1() {
+ return street1;
+ }
+
+ public void setStreet1(String street1) {
+ this.street1 = street1;
+ }
+
+ public String getCity() {
+ return city;
+ }
+
+ public void setCity(String city) {
+ this.city = city;
+ }
+
+ public String getCountry() {
+ return country;
+ }
+
+ public void setCountry(String country) {
+ this.country = country;
+ }
+}
\ No newline at end of file
Copied: jpamodelgen/trunk/test/src/main/resources/META-INF/address.xml (from rev 17048, jpamodelgen/trunk/test/src/main/resources/META-INF/orm.xml)
===================================================================
--- jpamodelgen/trunk/test/src/main/resources/META-INF/address.xml (rev 0)
+++ jpamodelgen/trunk/test/src/main/resources/META-INF/address.xml 2009-07-08 14:38:54 UTC (rev 17050)
@@ -0,0 +1,28 @@
+<?xml version="1.0" encoding="UTF-8"?>
+
+<entity-mappings xmlns="http://java.sun.com/xml/ns/persistence/orm"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://java.sun.com/xml/ns/persistence/orm orm_2_0.xsd"
+ version="2.0"
+ >
+ <!-- careful old JPA1 schema -->
+ <package>model.xmlmapped</package> <!-- default package -->
+ <embeddable class="Address" access="FIELD" metadata-complete="true"> <!--means ignore annotations-->
+ <attributes>
+ <basic name="street1"/>
+ <basic name="city"/>
+ <basic name="country"/>
+ </attributes>
+ </embeddable>
+</entity-mappings>
+
+
+ <!--
+public class Order {
+ long id;
+ Set<Item> items;
+ boolean filled;
+ Date date;
+ List<String> notes;
+ Shop shop;
+} -->
\ No newline at end of file
Copied: jpamodelgen/trunk/test/src/main/resources/META-INF/order.xml (from rev 17048, jpamodelgen/trunk/test/src/main/resources/META-INF/orm.xml)
===================================================================
--- jpamodelgen/trunk/test/src/main/resources/META-INF/order.xml (rev 0)
+++ jpamodelgen/trunk/test/src/main/resources/META-INF/order.xml 2009-07-08 14:38:54 UTC (rev 17050)
@@ -0,0 +1,37 @@
+<?xml version="1.0" encoding="UTF-8"?>
+
+<entity-mappings xmlns="http://java.sun.com/xml/ns/persistence/orm"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://java.sun.com/xml/ns/persistence/orm orm_2_0.xsd"
+ version="2.0"
+ >
+ <!-- careful old JPA1 schema -->
+ <package>model</package> <!-- default package -->
+ <entity class="Order" access="FIELD" metadata-complete="true"> <!--means ignore annotations-->
+ <attributes>
+ <id name="id">
+ <column name="fld_id"/>
+ </id>
+ <basic name="filled"></basic>
+ <basic name="date"></basic>
+ <one-to-many name="items" target-entity="Item" fetch="EAGER"> <!-- target-entity optional guess the type from the geenric-->
+ <cascade>
+ <cascade-persist/>
+ </cascade>
+ </one-to-many>
+ <many-to-one name="shop"/>
+ <element-collection name="notes"/> <!-- new in JPA 2 -->
+ </attributes>
+ </entity>
+</entity-mappings>
+
+
+ <!--
+public class Order {
+ long id;
+ Set<Item> items;
+ boolean filled;
+ Date date;
+ List<String> notes;
+ Shop shop;
+} -->
\ No newline at end of file
Deleted: jpamodelgen/trunk/test/src/main/resources/META-INF/orm.xml
===================================================================
--- jpamodelgen/trunk/test/src/main/resources/META-INF/orm.xml 2009-07-08 14:16:31 UTC (rev 17049)
+++ jpamodelgen/trunk/test/src/main/resources/META-INF/orm.xml 2009-07-08 14:38:54 UTC (rev 17050)
@@ -1,37 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-
-<entity-mappings xmlns="http://java.sun.com/xml/ns/persistence/orm"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://java.sun.com/xml/ns/persistence/orm orm_2_0.xsd"
- version="2.0"
- >
- <!-- careful old JPA1 schema -->
- <package>model</package> <!-- default package -->
- <entity class="Order" access="FIELD" metadata-complete="true"> <!--means ignore annotations-->
- <attributes>
- <id name="id">
- <column name="fld_id"/>
- </id>
- <basic name="filled"></basic>
- <basic name="date"></basic>
- <one-to-many name="items" target-entity="Item" fetch="EAGER"> <!-- target-entity optional guess the type from the geenric-->
- <cascade>
- <cascade-persist/>
- </cascade>
- </one-to-many>
- <many-to-one name="shop"/>
- <element-collection name="notes"/> <!-- new in JPA 2 -->
- </attributes>
- </entity>
-</entity-mappings>
-
-
- <!--
-public class Order {
- long id;
- Set<Item> items;
- boolean filled;
- Date date;
- List<String> notes;
- Shop shop;
-} -->
\ No newline at end of file
Modified: jpamodelgen/trunk/test/src/main/resources/META-INF/persistence.xml
===================================================================
--- jpamodelgen/trunk/test/src/main/resources/META-INF/persistence.xml 2009-07-08 14:16:31 UTC (rev 17049)
+++ jpamodelgen/trunk/test/src/main/resources/META-INF/persistence.xml 2009-07-08 14:38:54 UTC (rev 17050)
@@ -4,6 +4,7 @@
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence persistence.xsd" version="2.0">
<persistence-unit name="annotation-processor" transaction-type="JTA">
<description>Test persistence unit</description>
- <mapping-file>/META-INF/orm.xml</mapping-file>
+ <mapping-file>/META-INF/order.xml</mapping-file>
+ <mapping-file>/META-INF/address.xml</mapping-file>
</persistence-unit>
</persistence>
Deleted: jpamodelgen/trunk/test/src/test/java/AccessTypeTest.java
===================================================================
--- jpamodelgen/trunk/test/src/test/java/AccessTypeTest.java 2009-07-08 14:16:31 UTC (rev 17049)
+++ jpamodelgen/trunk/test/src/test/java/AccessTypeTest.java 2009-07-08 14:38:54 UTC (rev 17050)
@@ -1,23 +0,0 @@
-import java.lang.reflect.Field;
-
-import org.testng.annotations.Test;
-import static org.testng.Assert.assertFalse;
-import static org.testng.Assert.assertTrue;
-import org.testng.Assert;
-
-/**
- * @author Emmanuel Bernard
- */
-@Test
-public class AccessTypeTest {
- @Test
- public void testDefaultAccessType() throws Exception{
- Class<?> user_ = Class.forName( "model.User_" );
- try {
- final Field nonPersistentField = user_.getField( "nonPersistent" );
- Assert.fail( "field should not be persistent" );
- }
- catch (NoSuchFieldException e) {}
-
- }
-}
Deleted: jpamodelgen/trunk/test/src/test/java/InheritanceTest.java
===================================================================
--- jpamodelgen/trunk/test/src/test/java/InheritanceTest.java 2009-07-08 14:16:31 UTC (rev 17049)
+++ jpamodelgen/trunk/test/src/test/java/InheritanceTest.java 2009-07-08 14:38:54 UTC (rev 17050)
@@ -1,27 +0,0 @@
-import org.testng.annotations.Test;
-import org.testng.Assert;
-import model.Customer_;
-import model.User_;
-import model.House_;
-import model.Building_;
-import model.Area_;
-
-/**
- * @author Emmanuel Bernard
- */
-@Test
-public class InheritanceTest {
- @Test
- public void testSuperEntity() throws Exception {
- Assert.assertEquals( Customer_.class.getSuperclass(), User_.class,
- "Entity with super entity should inherit at the metamodel level");
- }
-
- @Test
- public void testMappedSuperclass() throws Exception {
- Assert.assertEquals( House_.class.getSuperclass(), Building_.class,
- "Entity with mapped superclass should inherit at the metamodel level");
- Assert.assertEquals( Building_.class.getSuperclass(), Area_.class,
- "mapped superclass with mapped superclass should inherit at the metamodel level");
- }
-}
Deleted: jpamodelgen/trunk/test/src/test/java/QueryTest.java
===================================================================
--- jpamodelgen/trunk/test/src/test/java/QueryTest.java 2009-07-08 14:16:31 UTC (rev 17049)
+++ jpamodelgen/trunk/test/src/test/java/QueryTest.java 2009-07-08 14:38:54 UTC (rev 17050)
@@ -1,144 +0,0 @@
-import java.math.BigDecimal;
-import java.util.Date;
-import java.util.Set;
-import javax.persistence.criteria.CriteriaQuery;
-import javax.persistence.criteria.Expression;
-import javax.persistence.criteria.Join;
-import static javax.persistence.criteria.JoinType.INNER;
-import javax.persistence.criteria.ListJoin;
-import javax.persistence.criteria.Path;
-import javax.persistence.criteria.QueryBuilder;
-import javax.persistence.criteria.Root;
-import javax.persistence.Tuple;
-
-import model.Item;
-import model.Order;
-import model.Product;
-import model.Item_;
-import model.Order_;
-import model.Product_;
-import model.Shop_;
-
-/**
- * Writing queries involves passing typesafe, statically cached, metamodel
- * objects to the query builder in order to create the various parts of
- * the query. The typesafe metamodel objects were validated at init time,
- * so it is impossible to build invalid queries in the application code.
- */
-public class QueryTest {
-
- QueryBuilder qb;
-
- public void test() {
- CriteriaQuery<Tuple> q = qb.createTupleQuery();
-
- Root<Order> order = q.from(Order.class);
- Join<Item, Product> product = order.join(Order_.items)
- .join(Item_.product);
-
- Path<BigDecimal> price = product.get(Product_.price);
- Path<Boolean> filled = order.get(Order_.filled);
- Path<Date> date = order.get(Order_.date);
-
- q.select( qb.tuple( order, product ) )
- .where( qb.and( qb.gt(price, 100.00), qb.not(filled) ) )
- .orderBy( qb.asc(price), qb.desc(date) );
- }
-
- public void testUntypesafe() {
- CriteriaQuery<Tuple> q = qb.createTupleQuery();
-
- Root<Order> order = q.from(Order.class);
- Join<Item, Product> product = order.join("items")
- .join("product");
-
- Path<BigDecimal> price = product.get("price");
- Path<Boolean> filled = order.get("filled");
- Path<Date> date = order.get("date");
-
- q.select( qb.tuple( order, product ) )
- .where( qb.and( qb.gt(price, 100.00), qb.not(filled) ) )
- .orderBy( qb.asc(price), qb.desc(date) );
- }
-
- /**
- * Navigation by joining
- */
- public void test2() {
- CriteriaQuery<Product> q = qb.createQuery(Product.class);
-
- Root<Product> product = q.from(Product.class);
- Join<Item, Order> order = product.join(Product_.items)
- .join(Item_.order);
-
- q.select(product)
- .where( qb.equal(order.get(Order_.id), 12345l) );
- }
-
- public void testMap() {
- CriteriaQuery<Item> q = qb.createQuery(Item.class);
-
- Root<Item> item = q.from(Item.class);
- Join<Item, Order> io = item.join(Item_.namedOrders);
-
- }
-
- /**
- * Navigation by compound Path
- */
- public void test3() {
- CriteriaQuery<Item> q = qb.createQuery(Item.class);
-
- Root<Item> item = q.from(Item.class);
- Path<String> shopName = item.get(Item_.order)
- .get(Order_.shop)
- .get(Shop_.name);
- q.select(item)
- .where( qb.equal(shopName, "amazon.com") );
- }
-
-// public void test4() {
-// CriteriaQuery q = qb.create();
-//
-// Root<Order> order = q.from(Order.class);
-// ListJoin<Order, String> note = order.join(Order_.notes);
-// Expression<Set<Item>> items = order.get(Order_.items);
-// order.fetch(Order_.items, JoinType.INNER);
-//
-// q.select(note)
-// .where( qb.and( qb.lt(note.index(), 10), qb.isNotEmpty(items) ) );
-// }
-
- public void test4Untypesafe() {
- CriteriaQuery<String> q = qb.createQuery(String.class);
-
- Root<Order> order = q.from(Order.class);
- ListJoin<Order, String> note = order.joinList("notes");
- Expression<Set<Item>> items = order.get("items");
- order.fetch("items", INNER);
-
- q.select(note)
- .where( qb.and( qb.lt(note.index(), 10), qb.isNotEmpty(items) ) );
- }
-
- /*public void test5() {
- Expression<Long> l= null;
- Expression<Integer> i= null;
- Expression<Float> x= null;
- Expression<Float> y= null;
-
- Expression<Number> n;
- Expression<Float> f;
- Expression<String> s = null;
-
- n = qb.quot(l, i);
-
- f = qb.sum(x, y);
-
- n = qb.quot(x, y);
-
- javax.jpa.criteria.Order o = qb.asc(n);
- javax.jpa.criteria.Order p = qb.ascending(s);
- }*/
-
-}
Copied: jpamodelgen/trunk/test/src/test/java/tests/AccessTypeTest.java (from rev 17048, jpamodelgen/trunk/test/src/test/java/AccessTypeTest.java)
===================================================================
--- jpamodelgen/trunk/test/src/test/java/tests/AccessTypeTest.java (rev 0)
+++ jpamodelgen/trunk/test/src/test/java/tests/AccessTypeTest.java 2009-07-08 14:38:54 UTC (rev 17050)
@@ -0,0 +1,25 @@
+package tests;
+
+import java.lang.reflect.Field;
+
+import org.testng.annotations.Test;
+import static org.testng.Assert.assertFalse;
+import static org.testng.Assert.assertTrue;
+import org.testng.Assert;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Test
+public class AccessTypeTest {
+ @Test
+ public void testDefaultAccessType() throws Exception{
+ Class<?> user_ = Class.forName( "model.User_" );
+ try {
+ final Field nonPersistentField = user_.getField( "nonPersistent" );
+ Assert.fail( "field should not be persistent" );
+ }
+ catch (NoSuchFieldException e) {}
+
+ }
+}
Copied: jpamodelgen/trunk/test/src/test/java/tests/InheritanceTest.java (from rev 17048, jpamodelgen/trunk/test/src/test/java/InheritanceTest.java)
===================================================================
--- jpamodelgen/trunk/test/src/test/java/tests/InheritanceTest.java (rev 0)
+++ jpamodelgen/trunk/test/src/test/java/tests/InheritanceTest.java 2009-07-08 14:38:54 UTC (rev 17050)
@@ -0,0 +1,29 @@
+package tests;
+
+import org.testng.annotations.Test;
+import org.testng.Assert;
+import model.Customer_;
+import model.User_;
+import model.House_;
+import model.Building_;
+import model.Area_;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Test
+public class InheritanceTest {
+ @Test
+ public void testSuperEntity() throws Exception {
+ Assert.assertEquals( Customer_.class.getSuperclass(), User_.class,
+ "Entity with super entity should inherit at the metamodel level");
+ }
+
+ @Test
+ public void testMappedSuperclass() throws Exception {
+ Assert.assertEquals( House_.class.getSuperclass(), Building_.class,
+ "Entity with mapped superclass should inherit at the metamodel level");
+ Assert.assertEquals( Building_.class.getSuperclass(), Area_.class,
+ "mapped superclass with mapped superclass should inherit at the metamodel level");
+ }
+}
Copied: jpamodelgen/trunk/test/src/test/java/tests/QueryTest.java (from rev 17048, jpamodelgen/trunk/test/src/test/java/QueryTest.java)
===================================================================
--- jpamodelgen/trunk/test/src/test/java/tests/QueryTest.java (rev 0)
+++ jpamodelgen/trunk/test/src/test/java/tests/QueryTest.java 2009-07-08 14:38:54 UTC (rev 17050)
@@ -0,0 +1,146 @@
+package tests;
+
+import java.math.BigDecimal;
+import java.util.Date;
+import java.util.Set;
+import javax.persistence.criteria.CriteriaQuery;
+import javax.persistence.criteria.Expression;
+import javax.persistence.criteria.Join;
+import static javax.persistence.criteria.JoinType.INNER;
+import javax.persistence.criteria.ListJoin;
+import javax.persistence.criteria.Path;
+import javax.persistence.criteria.QueryBuilder;
+import javax.persistence.criteria.Root;
+import javax.persistence.Tuple;
+
+import model.Item;
+import model.Order;
+import model.Product;
+import model.Item_;
+import model.Order_;
+import model.Product_;
+import model.Shop_;
+
+/**
+ * Writing queries involves passing typesafe, statically cached, metamodel
+ * objects to the query builder in order to create the various parts of
+ * the query. The typesafe metamodel objects were validated at init time,
+ * so it is impossible to build invalid queries in the application code.
+ */
+public class QueryTest {
+
+ QueryBuilder qb;
+
+ public void test() {
+ CriteriaQuery<Tuple> q = qb.createTupleQuery();
+
+ Root<Order> order = q.from(Order.class);
+ Join<Item, Product> product = order.join(Order_.items)
+ .join(Item_.product);
+
+ Path<BigDecimal> price = product.get(Product_.price);
+ Path<Boolean> filled = order.get(Order_.filled);
+ Path<Date> date = order.get(Order_.date);
+
+ q.select( qb.tuple( order, product ) )
+ .where( qb.and( qb.gt(price, 100.00), qb.not(filled) ) )
+ .orderBy( qb.asc(price), qb.desc(date) );
+ }
+
+ public void testUntypesafe() {
+ CriteriaQuery<Tuple> q = qb.createTupleQuery();
+
+ Root<Order> order = q.from(Order.class);
+ Join<Item, Product> product = order.join("items")
+ .join("product");
+
+ Path<BigDecimal> price = product.get("price");
+ Path<Boolean> filled = order.get("filled");
+ Path<Date> date = order.get("date");
+
+ q.select( qb.tuple( order, product ) )
+ .where( qb.and( qb.gt(price, 100.00), qb.not(filled) ) )
+ .orderBy( qb.asc(price), qb.desc(date) );
+ }
+
+ /**
+ * Navigation by joining
+ */
+ public void test2() {
+ CriteriaQuery<Product> q = qb.createQuery(Product.class);
+
+ Root<Product> product = q.from(Product.class);
+ Join<Item, Order> order = product.join(Product_.items)
+ .join(Item_.order);
+
+ q.select(product)
+ .where( qb.equal(order.get(Order_.id), 12345l) );
+ }
+
+ public void testMap() {
+ CriteriaQuery<Item> q = qb.createQuery(Item.class);
+
+ Root<Item> item = q.from(Item.class);
+ Join<Item, Order> io = item.join(Item_.namedOrders);
+
+ }
+
+ /**
+ * Navigation by compound Path
+ */
+ public void test3() {
+ CriteriaQuery<Item> q = qb.createQuery(Item.class);
+
+ Root<Item> item = q.from(Item.class);
+ Path<String> shopName = item.get(Item_.order)
+ .get(Order_.shop)
+ .get(Shop_.name);
+ q.select(item)
+ .where( qb.equal(shopName, "amazon.com") );
+ }
+
+// public void test4() {
+// CriteriaQuery q = qb.create();
+//
+// Root<Order> order = q.from(Order.class);
+// ListJoin<Order, String> note = order.join(Order_.notes);
+// Expression<Set<Item>> items = order.get(Order_.items);
+// order.fetch(Order_.items, JoinType.INNER);
+//
+// q.select(note)
+// .where( qb.and( qb.lt(note.index(), 10), qb.isNotEmpty(items) ) );
+// }
+
+ public void test4Untypesafe() {
+ CriteriaQuery<String> q = qb.createQuery(String.class);
+
+ Root<Order> order = q.from(Order.class);
+ ListJoin<Order, String> note = order.joinList("notes");
+ Expression<Set<Item>> items = order.get("items");
+ order.fetch("items", INNER);
+
+ q.select(note)
+ .where( qb.and( qb.lt(note.index(), 10), qb.isNotEmpty(items) ) );
+ }
+
+ /*public void test5() {
+ Expression<Long> l= null;
+ Expression<Integer> i= null;
+ Expression<Float> x= null;
+ Expression<Float> y= null;
+
+ Expression<Number> n;
+ Expression<Float> f;
+ Expression<String> s = null;
+
+ n = qb.quot(l, i);
+
+ f = qb.sum(x, y);
+
+ n = qb.quot(x, y);
+
+ javax.jpa.criteria.Order o = qb.asc(n);
+ javax.jpa.criteria.Order p = qb.ascending(s);
+ }*/
+
+}
Copied: jpamodelgen/trunk/test/src/test/java/tests/XmlMappingTest.java (from rev 17048, jpamodelgen/trunk/test/src/test/java/AccessTypeTest.java)
===================================================================
--- jpamodelgen/trunk/test/src/test/java/tests/XmlMappingTest.java (rev 0)
+++ jpamodelgen/trunk/test/src/test/java/tests/XmlMappingTest.java 2009-07-08 14:38:54 UTC (rev 17050)
@@ -0,0 +1,15 @@
+package tests;
+
+import static org.testng.Assert.assertNotNull;
+import org.testng.annotations.Test;
+
+/**
+ * @author Hardy Ferentschik
+ */
+@Test
+public class XmlMappingTest {
+ @Test
+ public void testDefaultAccessType() throws Exception {
+ assertNotNull( Class.forName( "model.xmlmapped.Address_" ) );
+ }
+}
\ No newline at end of file
Added: jpamodelgen/trunk/test/src/test/suite/unit-tests.xml
===================================================================
--- jpamodelgen/trunk/test/src/test/suite/unit-tests.xml (rev 0)
+++ jpamodelgen/trunk/test/src/test/suite/unit-tests.xml 2009-07-08 14:38:54 UTC (rev 17050)
@@ -0,0 +1,9 @@
+<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >
+
+<suite name="Hibernate Model Generator Tests" verbose="1">
+ <test name="Unit tests">
+ <packages>
+ <package name="tests"/>
+ </packages>
+ </test>
+</suite>
\ No newline at end of file
14 years, 10 months
Hibernate SVN: r17049 - jpamodelgen/trunk/generator/src/main/java/org/hibernate/jpa/metamodel/ap.
by hibernate-commits@lists.jboss.org
Author: hardy.ferentschik
Date: 2009-07-08 10:16:31 -0400 (Wed, 08 Jul 2009)
New Revision: 17049
Modified:
jpamodelgen/trunk/generator/src/main/java/org/hibernate/jpa/metamodel/ap/JPAMetaModelEntityProcessor.java
Log:
Modified: jpamodelgen/trunk/generator/src/main/java/org/hibernate/jpa/metamodel/ap/JPAMetaModelEntityProcessor.java
===================================================================
--- jpamodelgen/trunk/generator/src/main/java/org/hibernate/jpa/metamodel/ap/JPAMetaModelEntityProcessor.java 2009-07-08 13:43:40 UTC (rev 17048)
+++ jpamodelgen/trunk/generator/src/main/java/org/hibernate/jpa/metamodel/ap/JPAMetaModelEntityProcessor.java 2009-07-08 14:16:31 UTC (rev 17049)
@@ -294,7 +294,7 @@
String name = getRelativeName( resource );
processingEnv.getMessager()
.printMessage( Diagnostic.Kind.NOTE, "Checking for " + resource );
- InputStream ormStream = null;
+ InputStream ormStream;
try {
FileObject fileObject = processingEnv.getFiler().getResource( StandardLocation.CLASS_OUTPUT, pkg, name );
ormStream = fileObject.openInputStream();
@@ -303,7 +303,7 @@
processingEnv.getMessager()
.printMessage(
Diagnostic.Kind.WARNING,
- "Could not load " + resource + "from class output directory"
+ "Could not load " + resource + " using processingEnv.getFiler().getResource(). Using classpath..."
);
// TODO
14 years, 10 months
Hibernate SVN: r17048 - in jpamodelgen/trunk: test/src/main/java/model and 1 other directories.
by hibernate-commits@lists.jboss.org
Author: epbernard
Date: 2009-07-08 09:43:40 -0400 (Wed, 08 Jul 2009)
New Revision: 17048
Added:
jpamodelgen/trunk/test/src/main/java/model/Address.java
jpamodelgen/trunk/test/src/main/java/model/Area.java
jpamodelgen/trunk/test/src/main/java/model/Building.java
jpamodelgen/trunk/test/src/main/java/model/House.java
Modified:
jpamodelgen/trunk/generator/src/main/java/org/hibernate/jpa/metamodel/ap/JPAMetaModelEntityProcessor.java
jpamodelgen/trunk/test/src/test/java/InheritanceTest.java
Log:
Support for mapped superclass inheritance
Modified: jpamodelgen/trunk/generator/src/main/java/org/hibernate/jpa/metamodel/ap/JPAMetaModelEntityProcessor.java
===================================================================
--- jpamodelgen/trunk/generator/src/main/java/org/hibernate/jpa/metamodel/ap/JPAMetaModelEntityProcessor.java 2009-07-08 13:18:09 UTC (rev 17047)
+++ jpamodelgen/trunk/generator/src/main/java/org/hibernate/jpa/metamodel/ap/JPAMetaModelEntityProcessor.java 2009-07-08 13:43:40 UTC (rev 17048)
@@ -282,11 +282,11 @@
final Element superClassElement = ( ( DeclaredType ) superClass ).asElement();
String superClassName = ( ( TypeElement ) superClassElement ).getQualifiedName().toString();
if ( metaEntities.containsKey( superClassName ) ) {
- pw.print( " extends " + superClassName + "_ " );
+ pw.print( " extends " + superClassName + "_" );
}
}
- pw.println( "{" );
+ pw.println( " {" );
}
private InputStream getInputStreamForResource(String resource) {
Added: jpamodelgen/trunk/test/src/main/java/model/Address.java
===================================================================
--- jpamodelgen/trunk/test/src/main/java/model/Address.java (rev 0)
+++ jpamodelgen/trunk/test/src/main/java/model/Address.java 2009-07-08 13:43:40 UTC (rev 17048)
@@ -0,0 +1,37 @@
+package model;
+
+import javax.persistence.Embeddable;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Embeddable
+public class Address {
+ private String street1;
+ private String city;
+ private String country;
+
+ public String getStreet1() {
+ return street1;
+ }
+
+ public void setStreet1(String street1) {
+ this.street1 = street1;
+ }
+
+ public String getCity() {
+ return city;
+ }
+
+ public void setCity(String city) {
+ this.city = city;
+ }
+
+ public String getCountry() {
+ return country;
+ }
+
+ public void setCountry(String country) {
+ this.country = country;
+ }
+}
Added: jpamodelgen/trunk/test/src/main/java/model/Area.java
===================================================================
--- jpamodelgen/trunk/test/src/main/java/model/Area.java (rev 0)
+++ jpamodelgen/trunk/test/src/main/java/model/Area.java 2009-07-08 13:43:40 UTC (rev 17048)
@@ -0,0 +1,37 @@
+package model;
+
+import javax.persistence.MappedSuperclass;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@MappedSuperclass
+public class Area {
+ private int length;
+ private int width;
+ private int height;
+
+ public int getLength() {
+ return length;
+ }
+
+ public void setLength(int length) {
+ this.length = length;
+ }
+
+ public int getWidth() {
+ return width;
+ }
+
+ public void setWidth(int width) {
+ this.width = width;
+ }
+
+ public int getHeight() {
+ return height;
+ }
+
+ public void setHeight(int height) {
+ this.height = height;
+ }
+}
Added: jpamodelgen/trunk/test/src/main/java/model/Building.java
===================================================================
--- jpamodelgen/trunk/test/src/main/java/model/Building.java (rev 0)
+++ jpamodelgen/trunk/test/src/main/java/model/Building.java 2009-07-08 13:43:40 UTC (rev 17048)
@@ -0,0 +1,19 @@
+package model;
+
+import javax.persistence.MappedSuperclass;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@MappedSuperclass
+public class Building extends Area {
+ private Address address;
+
+ public Address getAddress() {
+ return address;
+ }
+
+ public void setAddress(Address address) {
+ this.address = address;
+ }
+}
Added: jpamodelgen/trunk/test/src/main/java/model/House.java
===================================================================
--- jpamodelgen/trunk/test/src/main/java/model/House.java (rev 0)
+++ jpamodelgen/trunk/test/src/main/java/model/House.java 2009-07-08 13:43:40 UTC (rev 17048)
@@ -0,0 +1,21 @@
+package model;
+
+import javax.persistence.Id;
+import javax.persistence.Entity;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+public class House extends Building {
+ @Id
+ private Long id;
+
+ public Long getId() {
+ return id;
+ }
+
+ public void setId(Long id) {
+ this.id = id;
+ }
+}
Modified: jpamodelgen/trunk/test/src/test/java/InheritanceTest.java
===================================================================
--- jpamodelgen/trunk/test/src/test/java/InheritanceTest.java 2009-07-08 13:18:09 UTC (rev 17047)
+++ jpamodelgen/trunk/test/src/test/java/InheritanceTest.java 2009-07-08 13:43:40 UTC (rev 17048)
@@ -2,6 +2,9 @@
import org.testng.Assert;
import model.Customer_;
import model.User_;
+import model.House_;
+import model.Building_;
+import model.Area_;
/**
* @author Emmanuel Bernard
@@ -13,4 +16,12 @@
Assert.assertEquals( Customer_.class.getSuperclass(), User_.class,
"Entity with super entity should inherit at the metamodel level");
}
+
+ @Test
+ public void testMappedSuperclass() throws Exception {
+ Assert.assertEquals( House_.class.getSuperclass(), Building_.class,
+ "Entity with mapped superclass should inherit at the metamodel level");
+ Assert.assertEquals( Building_.class.getSuperclass(), Area_.class,
+ "mapped superclass with mapped superclass should inherit at the metamodel level");
+ }
}
14 years, 10 months
Hibernate SVN: r17047 - in jpamodelgen/trunk: generator/src/main/java/org/hibernate/jpa/metamodel/ap/annotation and 3 other directories.
by hibernate-commits@lists.jboss.org
Author: epbernard
Date: 2009-07-08 09:18:09 -0400 (Wed, 08 Jul 2009)
New Revision: 17047
Added:
jpamodelgen/trunk/test/src/main/java/model/Customer.java
jpamodelgen/trunk/test/src/main/java/model/User.java
jpamodelgen/trunk/test/src/test/java/AccessTypeTest.java
jpamodelgen/trunk/test/src/test/java/InheritanceTest.java
Modified:
jpamodelgen/trunk/generator/src/main/java/org/hibernate/jpa/metamodel/ap/IMetaEntity.java
jpamodelgen/trunk/generator/src/main/java/org/hibernate/jpa/metamodel/ap/JPAMetaModelEntityProcessor.java
jpamodelgen/trunk/generator/src/main/java/org/hibernate/jpa/metamodel/ap/annotation/MetaEntity.java
jpamodelgen/trunk/generator/src/main/java/org/hibernate/jpa/metamodel/ap/xml/XmlMetaEntity.java
Log:
Support for entity inheritance
Modified: jpamodelgen/trunk/generator/src/main/java/org/hibernate/jpa/metamodel/ap/IMetaEntity.java
===================================================================
--- jpamodelgen/trunk/generator/src/main/java/org/hibernate/jpa/metamodel/ap/IMetaEntity.java 2009-07-08 13:07:29 UTC (rev 17046)
+++ jpamodelgen/trunk/generator/src/main/java/org/hibernate/jpa/metamodel/ap/IMetaEntity.java 2009-07-08 13:18:09 UTC (rev 17047)
@@ -18,6 +18,7 @@
package org.hibernate.jpa.metamodel.ap;
import javax.lang.model.element.Name;
+import javax.lang.model.element.TypeElement;
import java.util.List;
/**
@@ -39,4 +40,6 @@
String staticImport(String fqcn, String member);
String importType(Name qualifiedName);
+
+ TypeElement getTypeElement();
}
Modified: jpamodelgen/trunk/generator/src/main/java/org/hibernate/jpa/metamodel/ap/JPAMetaModelEntityProcessor.java
===================================================================
--- jpamodelgen/trunk/generator/src/main/java/org/hibernate/jpa/metamodel/ap/JPAMetaModelEntityProcessor.java 2009-07-08 13:07:29 UTC (rev 17046)
+++ jpamodelgen/trunk/generator/src/main/java/org/hibernate/jpa/metamodel/ap/JPAMetaModelEntityProcessor.java 2009-07-08 13:18:09 UTC (rev 17047)
@@ -24,6 +24,9 @@
import javax.lang.model.element.ElementKind;
import javax.lang.model.element.TypeElement;
import javax.lang.model.util.Elements;
+import javax.lang.model.type.TypeMirror;
+import javax.lang.model.type.TypeKind;
+import javax.lang.model.type.DeclaredType;
import javax.persistence.Embeddable;
import javax.persistence.MappedSuperclass;
import javax.tools.Diagnostic;
@@ -175,7 +178,10 @@
final String annotationType = mirror.getAnnotationType().toString();
if ( element.getKind() == ElementKind.CLASS &&
- annotationType.equals( ENTITY_ANN ) ) {
+ ( annotationType.equals( ENTITY_ANN )
+ || annotationType.equals( MAPPED_SUPERCLASS_ANN )
+ || annotationType.equals( EMBEDDABLE_ANN )
+ ) ) {
MetaEntity metaEntity = new MetaEntity( processingEnv, ( TypeElement ) element );
// TODO instead of just adding the entity we have to do some merging.
@@ -243,8 +249,10 @@
pw.println( "@" + entity.importType( "javax.persistence.metamodel.StaticMetamodel" ) + "(" + entity.getSimpleName() + ".class)" );
- pw.println( "public abstract class " + entity.getSimpleName() + "_" + " {" );
+
+ printClassDeclaration( entity, pw );
+
pw.println();
List<IMetaAttribute> members = entity.getMembers();
@@ -263,6 +271,24 @@
}
}
+ private void printClassDeclaration(IMetaEntity entity, PrintWriter pw) {
+ pw.print( "public abstract class " + entity.getSimpleName() + "_" );
+
+ final TypeMirror superClass = entity.getTypeElement().getSuperclass();
+ //superclass of Object is of NoType which returns some other kind
+ String superclassDeclaration = "";
+ if (superClass.getKind() == TypeKind.DECLARED ) {
+ //F..king Ch...t Have those people used their horrible APIs even once?
+ final Element superClassElement = ( ( DeclaredType ) superClass ).asElement();
+ String superClassName = ( ( TypeElement ) superClassElement ).getQualifiedName().toString();
+ if ( metaEntities.containsKey( superClassName ) ) {
+ pw.print( " extends " + superClassName + "_ " );
+ }
+ }
+
+ pw.println( "{" );
+ }
+
private InputStream getInputStreamForResource(String resource) {
String pkg = getPackage( resource );
String name = getRelativeName( resource );
Modified: jpamodelgen/trunk/generator/src/main/java/org/hibernate/jpa/metamodel/ap/annotation/MetaEntity.java
===================================================================
--- jpamodelgen/trunk/generator/src/main/java/org/hibernate/jpa/metamodel/ap/annotation/MetaEntity.java 2009-07-08 13:07:29 UTC (rev 17046)
+++ jpamodelgen/trunk/generator/src/main/java/org/hibernate/jpa/metamodel/ap/annotation/MetaEntity.java 2009-07-08 13:18:09 UTC (rev 17047)
@@ -220,6 +220,10 @@
return importType( qualifiedName.toString() );
}
+ public TypeElement getTypeElement() {
+ return element;
+ }
+
private String getKeyType(DeclaredType t) {
return t.getTypeArguments().get( 0 ).toString();
}
Modified: jpamodelgen/trunk/generator/src/main/java/org/hibernate/jpa/metamodel/ap/xml/XmlMetaEntity.java
===================================================================
--- jpamodelgen/trunk/generator/src/main/java/org/hibernate/jpa/metamodel/ap/xml/XmlMetaEntity.java 2009-07-08 13:07:29 UTC (rev 17046)
+++ jpamodelgen/trunk/generator/src/main/java/org/hibernate/jpa/metamodel/ap/xml/XmlMetaEntity.java 2009-07-08 13:18:09 UTC (rev 17047)
@@ -1,4 +1,4 @@
-// $Id:$
+// $Id$
/*
* JBoss, Home of Professional Open Source
* Copyright 2008, Red Hat Middleware LLC, and individual contributors
@@ -60,13 +60,13 @@
final private List<IMetaAttribute> members = new ArrayList<IMetaAttribute>();
- private TypeElement type;
+ private TypeElement element;
- public XmlMetaEntity(Entity ormEntity, String packageName, TypeElement type) {
+ public XmlMetaEntity(Entity ormEntity, String packageName, TypeElement element) {
this.ormEntity = ormEntity;
this.packageName = packageName;
importContext = new ImportContextImpl( getPackageName() );
- this.type = type;
+ this.element = element;
Attributes attributes = ormEntity.getAttributes();
Id id = attributes.getId().get( 0 );
XmlMetaSingleAttribute attribute = new XmlMetaSingleAttribute( this, id.getName(), getType( id.getName() ) );
@@ -128,9 +128,13 @@
return importType( qualifiedName.toString() );
}
+ public TypeElement getTypeElement() {
+ return element;
+ }
+
private String[] getCollectionType(String propertyName) {
String types[] = new String[2];
- for ( Element elem : type.getEnclosedElements() ) {
+ for ( Element elem : element.getEnclosedElements() ) {
if ( elem.getSimpleName().toString().equals( propertyName ) ) {
DeclaredType type = ( ( DeclaredType ) elem.asType() );
types[0] = type.getTypeArguments().get( 0 ).toString();
@@ -143,7 +147,7 @@
// TODO - so far only prototype. Only tested for the Order orm.xml
private String getType(String propertyName) {
String typeName = null;
- for ( Element elem : type.getEnclosedElements() ) {
+ for ( Element elem : element.getEnclosedElements() ) {
if ( elem.getSimpleName().toString().equals( propertyName ) ) {
switch ( elem.asType().getKind() ) {
case INT: {
@@ -177,7 +181,7 @@
public String toString() {
final StringBuilder sb = new StringBuilder();
sb.append( "XmlMetaEntity" );
- sb.append( "{type=" ).append( type );
+ sb.append( "{type=" ).append( element );
sb.append( '}' );
return sb.toString();
}
Added: jpamodelgen/trunk/test/src/main/java/model/Customer.java
===================================================================
--- jpamodelgen/trunk/test/src/main/java/model/Customer.java (rev 0)
+++ jpamodelgen/trunk/test/src/main/java/model/Customer.java 2009-07-08 13:18:09 UTC (rev 17047)
@@ -0,0 +1,22 @@
+package model;
+
+import java.util.Set;
+import javax.persistence.Entity;
+import javax.persistence.OneToMany;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+public class Customer extends User {
+ private Set<Order> orders;
+
+ public Set<Order> getOrders() {
+ return orders;
+ }
+
+ @OneToMany
+ public void setOrders(Set<Order> orders) {
+ this.orders = orders;
+ }
+}
Added: jpamodelgen/trunk/test/src/main/java/model/User.java
===================================================================
--- jpamodelgen/trunk/test/src/main/java/model/User.java (rev 0)
+++ jpamodelgen/trunk/test/src/main/java/model/User.java 2009-07-08 13:18:09 UTC (rev 17047)
@@ -0,0 +1,41 @@
+package model;
+
+import javax.persistence.Entity;
+import javax.persistence.Id;
+import javax.persistence.Transient;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+public class User {
+ private Long id;
+ private String nonPersistent;
+ private String name;
+
+ @Id
+ public Long getId() {
+ return id;
+ }
+
+ public void setId(Long id) {
+ this.id = id;
+ }
+
+ @Transient
+ public String getNonPersistent() {
+ return nonPersistent;
+ }
+
+ public void setNonPersistent(String nonPersistent) {
+ this.nonPersistent = nonPersistent;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+}
Added: jpamodelgen/trunk/test/src/test/java/AccessTypeTest.java
===================================================================
--- jpamodelgen/trunk/test/src/test/java/AccessTypeTest.java (rev 0)
+++ jpamodelgen/trunk/test/src/test/java/AccessTypeTest.java 2009-07-08 13:18:09 UTC (rev 17047)
@@ -0,0 +1,23 @@
+import java.lang.reflect.Field;
+
+import org.testng.annotations.Test;
+import static org.testng.Assert.assertFalse;
+import static org.testng.Assert.assertTrue;
+import org.testng.Assert;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Test
+public class AccessTypeTest {
+ @Test
+ public void testDefaultAccessType() throws Exception{
+ Class<?> user_ = Class.forName( "model.User_" );
+ try {
+ final Field nonPersistentField = user_.getField( "nonPersistent" );
+ Assert.fail( "field should not be persistent" );
+ }
+ catch (NoSuchFieldException e) {}
+
+ }
+}
Added: jpamodelgen/trunk/test/src/test/java/InheritanceTest.java
===================================================================
--- jpamodelgen/trunk/test/src/test/java/InheritanceTest.java (rev 0)
+++ jpamodelgen/trunk/test/src/test/java/InheritanceTest.java 2009-07-08 13:18:09 UTC (rev 17047)
@@ -0,0 +1,16 @@
+import org.testng.annotations.Test;
+import org.testng.Assert;
+import model.Customer_;
+import model.User_;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Test
+public class InheritanceTest {
+ @Test
+ public void testSuperEntity() throws Exception {
+ Assert.assertEquals( Customer_.class.getSuperclass(), User_.class,
+ "Entity with super entity should inherit at the metamodel level");
+ }
+}
14 years, 10 months
Hibernate SVN: r17046 - jpamodelgen/trunk/generator/src/main/java/org/hibernate/jpa/metamodel/ap.
by hibernate-commits@lists.jboss.org
Author: hardy.ferentschik
Date: 2009-07-08 09:07:29 -0400 (Wed, 08 Jul 2009)
New Revision: 17046
Modified:
jpamodelgen/trunk/generator/src/main/java/org/hibernate/jpa/metamodel/ap/JPAMetaModelEntityProcessor.java
Log:
added comment about resource loading
Modified: jpamodelgen/trunk/generator/src/main/java/org/hibernate/jpa/metamodel/ap/JPAMetaModelEntityProcessor.java
===================================================================
--- jpamodelgen/trunk/generator/src/main/java/org/hibernate/jpa/metamodel/ap/JPAMetaModelEntityProcessor.java 2009-07-08 12:27:16 UTC (rev 17045)
+++ jpamodelgen/trunk/generator/src/main/java/org/hibernate/jpa/metamodel/ap/JPAMetaModelEntityProcessor.java 2009-07-08 13:07:29 UTC (rev 17046)
@@ -11,7 +11,6 @@
import java.util.List;
import java.util.Map;
import java.util.Set;
-import java.util.HashSet;
import javax.annotation.Generated;
import javax.annotation.processing.AbstractProcessor;
import javax.annotation.processing.FilerException;
@@ -25,14 +24,14 @@
import javax.lang.model.element.ElementKind;
import javax.lang.model.element.TypeElement;
import javax.lang.model.util.Elements;
+import javax.persistence.Embeddable;
+import javax.persistence.MappedSuperclass;
import javax.tools.Diagnostic;
import javax.tools.FileObject;
import javax.tools.StandardLocation;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
-import javax.persistence.MappedSuperclass;
-import javax.persistence.Embeddable;
import org.hibernate.jpa.metamodel.ap.annotation.MetaEntity;
import org.hibernate.jpa.metamodel.ap.xml.XmlMetaEntity;
@@ -269,7 +268,7 @@
String name = getRelativeName( resource );
processingEnv.getMessager()
.printMessage( Diagnostic.Kind.NOTE, "Checking for " + resource );
- InputStream ormStream;
+ InputStream ormStream = null;
try {
FileObject fileObject = processingEnv.getFiler().getResource( StandardLocation.CLASS_OUTPUT, pkg, name );
ormStream = fileObject.openInputStream();
@@ -278,8 +277,14 @@
processingEnv.getMessager()
.printMessage(
Diagnostic.Kind.WARNING,
- "Could not load " + resource + " using Filer.getResource(). Trying classpath..."
+ "Could not load " + resource + "from class output directory"
);
+
+ // TODO
+ // unfortunately, the Filer.getResource API seems not to be able to load from /META-INF. One gets a
+ // FilerException with the message with "Illegal name /META-INF". This means that we have to revert to
+ // using the classpath. This might mean that we find a persistence.xml which is 'part of another jar.
+ // Not sure what else we can do here
ormStream = this.getClass().getResourceAsStream( resource );
}
return ormStream;
14 years, 10 months
Hibernate SVN: r17045 - jpamodelgen/trunk.
by hibernate-commits@lists.jboss.org
Author: hardy.ferentschik
Date: 2009-07-08 08:27:16 -0400 (Wed, 08 Jul 2009)
New Revision: 17045
Added:
jpamodelgen/trunk/license.txt
Log:
added Apache license
Added: jpamodelgen/trunk/license.txt
===================================================================
--- jpamodelgen/trunk/license.txt (rev 0)
+++ jpamodelgen/trunk/license.txt 2009-07-08 12:27:16 UTC (rev 17045)
@@ -0,0 +1,202 @@
+
+ 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.
14 years, 10 months
Hibernate SVN: r17044 - jpamodelgen/trunk/generator/src/main/java/org/hibernate/jpa/metamodel/ap.
by hibernate-commits@lists.jboss.org
Author: epbernard
Date: 2009-07-08 08:26:11 -0400 (Wed, 08 Jul 2009)
New Revision: 17044
Modified:
jpamodelgen/trunk/generator/src/main/java/org/hibernate/jpa/metamodel/ap/JPAMetaModelEntityProcessor.java
Log:
clean semantic of retunr type
Modified: jpamodelgen/trunk/generator/src/main/java/org/hibernate/jpa/metamodel/ap/JPAMetaModelEntityProcessor.java
===================================================================
--- jpamodelgen/trunk/generator/src/main/java/org/hibernate/jpa/metamodel/ap/JPAMetaModelEntityProcessor.java 2009-07-08 12:12:22 UTC (rev 17043)
+++ jpamodelgen/trunk/generator/src/main/java/org/hibernate/jpa/metamodel/ap/JPAMetaModelEntityProcessor.java 2009-07-08 12:26:11 UTC (rev 17044)
@@ -1,341 +1,341 @@
-// $Id:$
-package org.hibernate.jpa.metamodel.ap;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.io.PrintWriter;
-import java.io.StringWriter;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import javax.annotation.Generated;
-import javax.annotation.processing.AbstractProcessor;
-import javax.annotation.processing.FilerException;
-import javax.annotation.processing.ProcessingEnvironment;
-import javax.annotation.processing.RoundEnvironment;
-import javax.annotation.processing.SupportedAnnotationTypes;
-import javax.annotation.processing.SupportedSourceVersion;
-import static javax.lang.model.SourceVersion.RELEASE_6;
-import javax.lang.model.element.AnnotationMirror;
-import javax.lang.model.element.Element;
-import javax.lang.model.element.ElementKind;
-import javax.lang.model.element.TypeElement;
-import javax.lang.model.util.Elements;
-i!
mport javax.tools.Diagnostic;
-import javax.tools.FileObject;
-import javax.tools.StandardLocation;
-import javax.xml.bind.JAXBContext;
-import javax.xml.bind.JAXBException;
-import javax.xml.bind.Unmarshaller;
-import javax.persistence.MappedSuperclass;
-import javax.persistence.Embeddable;
-
-import org.hibernate.jpa.metamodel.ap.annotation.MetaEntity;
-import org.hibernate.jpa.metamodel.ap.xml.XmlMetaEntity;
-import org.hibernate.jpa.metamodel.xml.jaxb.Entity;
-import org.hibernate.jpa.metamodel.xml.jaxb.EntityMappings;
-import org.hibernate.jpa.metamodel.xml.jaxb.ObjectFactory;
-import org.hibernate.jpa.metamodel.xml.jaxb.Persistence;
-
-/**
- * Main annotation processor.
- *
- * @author Max Andersen
- * @author Hardy Ferentschik
- */
-//@SupportedAnnotationTypes("javax.persistence.Entity")
-@SupportedAnnotationTypes("*")
-@SupportedSourceVersion(RELEASE_6)
-public class JPAMetaModelEntityProcessor extends AbstractProcessor {
-
- private static final String PATH_SEPARAT!
OR = "/";
- private static final String PERSISTENCE_XML = "/ME!
TA-INF/p
ersistence.xml";
- private static final Boolean ALLOW_OTHER_PROCESSORS_TO_CLAIM_ANNOTATIONS = Boolean.FALSE;
-
- private final Map<String, IMetaEntity> metaEntities = new HashMap<String, IMetaEntity>();
- private boolean xmlProcessed = false;
- private static final String ENTITY_ANN = javax.persistence.Entity.class.getName();
- private static final String MAPPED_SUPERCLASS_ANN = MappedSuperclass.class.getName();
- private static final String EMBEDDABLE_ANN = Embeddable.class.getName();
-
-
- public void init(ProcessingEnvironment env) {
- super.init( env );
- processingEnv.getMessager().printMessage( Diagnostic.Kind.NOTE, "Init Processor " + this );
- }
-
- @Override
- public boolean process(final Set<? extends TypeElement> annotations,
- final RoundEnvironment roundEnvironment) {
-
- if ( roundEnvironment.processingOver() ) {
- processingEnv.getMessager()
- .printMessage( Diagnostic.Kind.NOTE, "Last processing round." );
-
- createMetaModelClasses();
-
- !
processingEnv.getMessager()
- .printMessage( Diagnostic.Kind.NOTE, "Finished processing" );
- return ALLOW_OTHER_PROCESSORS_TO_CLAIM_ANNOTATIONS;
- }
-
- if ( !xmlProcessed ) {
- parsePersistenceXml();
- }
-
- if ( !hostJPAAnnotations( annotations ) ) {
- processingEnv.getMessager()
- .printMessage( Diagnostic.Kind.NOTE, "Current processing round does not contain entities" );
- return ALLOW_OTHER_PROCESSORS_TO_CLAIM_ANNOTATIONS;
- }
-
- Set<? extends Element> elements = roundEnvironment.getRootElements();
- for ( Element element : elements ) {
- processingEnv.getMessager().printMessage( Diagnostic.Kind.NOTE, "Processing " + element.toString() );
- handleRootElementAnnotationMirrors( element );
- }
-
- return ALLOW_OTHER_PROCESSORS_TO_CLAIM_ANNOTATIONS;
- }
-
- private void createMetaModelClasses() {
- for ( IMetaEntity entity : metaEntities.values() ) {
- processingEnv.getMessager()
- .printMessage( Diagnostic.Kind.NOTE, "Writing meta m!
odel for " + entity );
- writeFile( entity );
- }
- }
-
- p!
rivate b
oolean hostJPAAnnotations(Set<? extends TypeElement> annotations) {
- for ( TypeElement type : annotations ) {
- final String typeName = type.getQualifiedName().toString();
- if ( typeName.equals( ENTITY_ANN ) ) {
- return true;
- }
- else if ( typeName.equals( EMBEDDABLE_ANN ) ) {
- return true;
- }
- else if ( typeName.equals( MAPPED_SUPERCLASS_ANN ) ) {
- return true;
- }
- }
- return false;
- }
-
- private void parsePersistenceXml() {
- Persistence persistence = parseXml( PERSISTENCE_XML, Persistence.class );
- if ( persistence != null )
-
- {
- List<Persistence.PersistenceUnit> persistenceUnits = persistence.getPersistenceUnit();
- for ( Persistence.PersistenceUnit unit : persistenceUnits ) {
- List<String> mappingFiles = unit.getMappingFile();
- for ( String mappingFile : mappingFiles ) {
- parsingOrmXml( mappingFile );
- }
- }
- }
- xmlProcessed = true;
- }
-
-
- private void parsingOrmXml(String resource) {
- EntityM!
appings mappings = parseXml( resource, EntityMappings.class );
- if ( mappings == null ) {
- return;
- }
- Collection<Entity> entities = mappings.getEntity();
- String packageName = mappings.getPackage();
- for ( Entity entity : entities ) {
- String fullyQualifiedClassName = packageName + "." + entity.getClazz();
- Elements utils = processingEnv.getElementUtils();
- XmlMetaEntity metaEntity = new XmlMetaEntity(
- entity, packageName, utils.getTypeElement( fullyQualifiedClassName )
- );
-
- if ( metaEntities.containsKey( fullyQualifiedClassName ) ) {
- processingEnv.getMessager().printMessage(
- Diagnostic.Kind.WARNING,
- fullyQualifiedClassName + " was already processed once. Skipping second occurance."
- );
- }
- metaEntities.put( fullyQualifiedClassName, metaEntity );
- }
- }
-
- private void handleRootElementAnnotationMirrors(final Element element) {
-
- List<? extends AnnotationMirror> annotationMirrors = element
- .getAnno!
tationMirrors();
-
- for ( AnnotationMirror mirror : annotati!
onMirror
s ) {
- final String annotationType = mirror.getAnnotationType().toString();
-
- if ( element.getKind() == ElementKind.CLASS &&
- annotationType.equals( ENTITY_ANN ) ) {
- MetaEntity metaEntity = new MetaEntity( processingEnv, ( TypeElement ) element );
-
- // TODO instead of just adding the entity we have to do some merging.
- metaEntities.put( metaEntity.getQualifiedName(), metaEntity );
- }
- }
- }
-
- private void writeFile(IMetaEntity entity) {
-
- try {
- String metaModelPackage = entity.getPackageName();
-
- StringBuffer body = generateBody( entity );
-
- FileObject fo = processingEnv.getFiler().createSourceFile(
- metaModelPackage + "." + entity.getSimpleName() + "_"
- );
- OutputStream os = fo.openOutputStream();
- PrintWriter pw = new PrintWriter( os );
-
- pw.println( "package " + metaModelPackage + ";" );
-
- pw.println();
-
- pw.println( entity.generateImports() );
-
- pw.println( body );
-
- pw.flush();
- pw.clos!
e();
-
- }
- catch ( FilerException filerEx ) {
- processingEnv.getMessager().printMessage(
- Diagnostic.Kind.ERROR,
- "Problem with Processing Environment Filer: "
- + filerEx.getMessage()
- );
- }
- catch ( IOException ioEx ) {
- processingEnv.getMessager().printMessage(
- Diagnostic.Kind.ERROR,
- "Problem opening file to write MetaModel for " + entity.getSimpleName()
- + ioEx.getMessage()
- );
- }
- }
-
- /**
- * Generate everything after import statements.
- *
- * @param entity The meta entity for which to write the body
- *
- * @return body content
- */
- private StringBuffer generateBody(IMetaEntity entity) {
-
- StringWriter sw = new StringWriter();
- PrintWriter pw = null;
- try {
-
- pw = new PrintWriter( sw );
-
- pw.println( "@" + entity.importType( Generated.class.getName() ) + "(\"JPA MetaModel for " + entity.getQualifiedName() + "\")" );
-
- pw.println( "@" + entity.importType( "javax.persistence.metamode!
l.StaticMetamodel" ) + "(" + entity.getSimpleName() + ".class)!
" );
-
-
pw.println( "public abstract class " + entity.getSimpleName() + "_" + " {" );
-
- pw.println();
-
- List<IMetaAttribute> members = entity.getMembers();
-
- for ( IMetaAttribute metaMember : members ) {
- pw.println( " " + metaMember.getDeclarationString() );
- }
- pw.println();
- pw.println( "}" );
- return sw.getBuffer();
- }
- finally {
- if ( pw != null ) {
- pw.close();
- }
- }
- }
-
- private InputStream getInputStreamForResource(String resource) {
- String pkg = getPackage( resource );
- String name = getRelativeName( resource );
- processingEnv.getMessager()
- .printMessage( Diagnostic.Kind.NOTE, "Checking for " + resource );
- InputStream ormStream;
- try {
- FileObject fileObject = processingEnv.getFiler().getResource( StandardLocation.CLASS_OUTPUT, pkg, name );
- ormStream = fileObject.openInputStream();
- }
- catch ( IOException e1 ) {
- processingEnv.getMessager()
- .printMessage(
- Diagnostic.Kind.WARNING,
!
- "Could not load " + resource + " using Filer.getResource(). Trying classpath..."
- );
- ormStream = this.getClass().getResourceAsStream( resource );
- }
- return ormStream;
- }
-
- /**
- * Tries to open the specified xml file and return an instance of the specified class using JAXB.
- *
- * @param resource the xml file name
- * @param clazz The type of jaxb node to return
- *
- * @return The top level jaxb instance contained in the xml file or {@code null} in case the file could not be found.
- */
- private <T> T parseXml(String resource, Class<T> clazz) {
-
- InputStream stream = getInputStreamForResource( resource );
-
- if ( stream == null ) {
- processingEnv.getMessager().printMessage( Diagnostic.Kind.NOTE, resource + " not found." );
- return null;
- }
- try {
- JAXBContext jc = JAXBContext.newInstance( ObjectFactory.class );
- Unmarshaller unmarshaller = jc.createUnmarshaller();
- return clazz.cast( unmarshaller.unmarshal( stream )!
);
- }
- catch ( JAXBException e ) {
- processingEnv.getM!
essager(
).printMessage( Diagnostic.Kind.NOTE, "Error unmarshalling " + resource );
- e.printStackTrace();
- return null;
- }
- catch ( Exception e ) {
- processingEnv.getMessager().printMessage(
- Diagnostic.Kind.ERROR,
- "Problem while reading " + resource + " " + e.getMessage()
- );
- e.printStackTrace();
- return null;
- }
- }
-
- private String getPackage(String resourceName) {
- if ( !resourceName.contains( PATH_SEPARATOR ) ) {
- return "";
- }
- else {
- return resourceName.substring( 0, resourceName.lastIndexOf( PATH_SEPARATOR ) );
- }
- }
-
- private String getRelativeName(String resourceName) {
- if ( !resourceName.contains( PATH_SEPARATOR ) ) {
- return resourceName;
- }
- else {
- return resourceName.substring( resourceName.lastIndexOf( PATH_SEPARATOR ) + 1 );
- }
- }
-}
+// $Id$
+package org.hibernate.jpa.metamodel.ap;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.io.PrintWriter;
+import java.io.StringWriter;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.HashSet;
+import javax.annotation.Generated;
+import javax.annotation.processing.AbstractProcessor;
+import javax.annotation.processing.FilerException;
+import javax.annotation.processing.ProcessingEnvironment;
+import javax.annotation.processing.RoundEnvironment;
+import javax.annotation.processing.SupportedAnnotationTypes;
+import javax.annotation.processing.SupportedSourceVersion;
+import static javax.lang.model.SourceVersion.RELEASE_6;
+import javax.lang.model.element.AnnotationMirror;
+import javax.lang.model.element.Element;
+import javax.lang.model.element.ElementKind;
+import javax.lang.model.element.TypeElement;
+import javax.lang.model.util.Elements;
+import javax.tools.Diagnostic;
+import javax.tools.FileObject;
+import javax.tools.StandardLocation;
+import javax.xml.bind.JAXBContext;
+import javax.xml.bind.JAXBException;
+import javax.xml.bind.Unmarshaller;
+import javax.persistence.MappedSuperclass;
+import javax.persistence.Embeddable;
+
+import org.hibernate.jpa.metamodel.ap.annotation.MetaEntity;
+import org.hibernate.jpa.metamodel.ap.xml.XmlMetaEntity;
+import org.hibernate.jpa.metamodel.xml.jaxb.Entity;
+import org.hibernate.jpa.metamodel.xml.jaxb.EntityMappings;
+import org.hibernate.jpa.metamodel.xml.jaxb.ObjectFactory;
+import org.hibernate.jpa.metamodel.xml.jaxb.Persistence;
+
+/**
+ * Main annotation processor.
+ *
+ * @author Max Andersen
+ * @author Hardy Ferentschik
+ */
+//@SupportedAnnotationTypes("javax.persistence.Entity")
+@SupportedAnnotationTypes("*")
+@SupportedSourceVersion(RELEASE_6)
+public class JPAMetaModelEntityProcessor extends AbstractProcessor {
+
+ private static final String PATH_SEPARATOR = "/";
+ private static final String PERSISTENCE_XML = "/META-INF/persistence.xml";
+ private static final Boolean ALLOW_OTHER_PROCESSORS_TO_CLAIM_ANNOTATIONS = Boolean.TRUE;
+
+ private final Map<String, IMetaEntity> metaEntities = new HashMap<String, IMetaEntity>();
+ private boolean xmlProcessed = false;
+ private static final String ENTITY_ANN = javax.persistence.Entity.class.getName();
+ private static final String MAPPED_SUPERCLASS_ANN = MappedSuperclass.class.getName();
+ private static final String EMBEDDABLE_ANN = Embeddable.class.getName();
+
+
+ public void init(ProcessingEnvironment env) {
+ super.init( env );
+ processingEnv.getMessager().printMessage( Diagnostic.Kind.NOTE, "Init Processor " + this );
+ }
+
+ @Override
+ public boolean process(final Set<? extends TypeElement> annotations,
+ final RoundEnvironment roundEnvironment) {
+
+ if ( roundEnvironment.processingOver() ) {
+ processingEnv.getMessager()
+ .printMessage( Diagnostic.Kind.NOTE, "Last processing round." );
+
+ createMetaModelClasses();
+
+ processingEnv.getMessager()
+ .printMessage( Diagnostic.Kind.NOTE, "Finished processing" );
+ return ALLOW_OTHER_PROCESSORS_TO_CLAIM_ANNOTATIONS;
+ }
+
+ if ( !xmlProcessed ) {
+ parsePersistenceXml();
+ }
+
+ if ( !hostJPAAnnotations( annotations ) ) {
+ processingEnv.getMessager()
+ .printMessage( Diagnostic.Kind.NOTE, "Current processing round does not contain entities" );
+ return ALLOW_OTHER_PROCESSORS_TO_CLAIM_ANNOTATIONS;
+ }
+
+ Set<? extends Element> elements = roundEnvironment.getRootElements();
+ for ( Element element : elements ) {
+ processingEnv.getMessager().printMessage( Diagnostic.Kind.NOTE, "Processing " + element.toString() );
+ handleRootElementAnnotationMirrors( element );
+ }
+
+ return !ALLOW_OTHER_PROCESSORS_TO_CLAIM_ANNOTATIONS;
+ }
+
+ private void createMetaModelClasses() {
+ for ( IMetaEntity entity : metaEntities.values() ) {
+ processingEnv.getMessager()
+ .printMessage( Diagnostic.Kind.NOTE, "Writing meta model for " + entity );
+ writeFile( entity );
+ }
+ }
+
+ private boolean hostJPAAnnotations(Set<? extends TypeElement> annotations) {
+ for ( TypeElement type : annotations ) {
+ final String typeName = type.getQualifiedName().toString();
+ if ( typeName.equals( ENTITY_ANN ) ) {
+ return true;
+ }
+ else if ( typeName.equals( EMBEDDABLE_ANN ) ) {
+ return true;
+ }
+ else if ( typeName.equals( MAPPED_SUPERCLASS_ANN ) ) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ private void parsePersistenceXml() {
+ Persistence persistence = parseXml( PERSISTENCE_XML, Persistence.class );
+ if ( persistence != null )
+
+ {
+ List<Persistence.PersistenceUnit> persistenceUnits = persistence.getPersistenceUnit();
+ for ( Persistence.PersistenceUnit unit : persistenceUnits ) {
+ List<String> mappingFiles = unit.getMappingFile();
+ for ( String mappingFile : mappingFiles ) {
+ parsingOrmXml( mappingFile );
+ }
+ }
+ }
+ xmlProcessed = true;
+ }
+
+
+ private void parsingOrmXml(String resource) {
+ EntityMappings mappings = parseXml( resource, EntityMappings.class );
+ if ( mappings == null ) {
+ return;
+ }
+ Collection<Entity> entities = mappings.getEntity();
+ String packageName = mappings.getPackage();
+ for ( Entity entity : entities ) {
+ String fullyQualifiedClassName = packageName + "." + entity.getClazz();
+ Elements utils = processingEnv.getElementUtils();
+ XmlMetaEntity metaEntity = new XmlMetaEntity(
+ entity, packageName, utils.getTypeElement( fullyQualifiedClassName )
+ );
+
+ if ( metaEntities.containsKey( fullyQualifiedClassName ) ) {
+ processingEnv.getMessager().printMessage(
+ Diagnostic.Kind.WARNING,
+ fullyQualifiedClassName + " was already processed once. Skipping second occurance."
+ );
+ }
+ metaEntities.put( fullyQualifiedClassName, metaEntity );
+ }
+ }
+
+ private void handleRootElementAnnotationMirrors(final Element element) {
+
+ List<? extends AnnotationMirror> annotationMirrors = element
+ .getAnnotationMirrors();
+
+ for ( AnnotationMirror mirror : annotationMirrors ) {
+ final String annotationType = mirror.getAnnotationType().toString();
+
+ if ( element.getKind() == ElementKind.CLASS &&
+ annotationType.equals( ENTITY_ANN ) ) {
+ MetaEntity metaEntity = new MetaEntity( processingEnv, ( TypeElement ) element );
+
+ // TODO instead of just adding the entity we have to do some merging.
+ metaEntities.put( metaEntity.getQualifiedName(), metaEntity );
+ }
+ }
+ }
+ private void writeFile(IMetaEntity entity) {
+
+ try {
+ String metaModelPackage = entity.getPackageName();
+
+ StringBuffer body = generateBody( entity );
+
+ FileObject fo = processingEnv.getFiler().createSourceFile(
+ metaModelPackage + "." + entity.getSimpleName() + "_"
+ );
+ OutputStream os = fo.openOutputStream();
+ PrintWriter pw = new PrintWriter( os );
+
+ pw.println( "package " + metaModelPackage + ";" );
+
+ pw.println();
+
+ pw.println( entity.generateImports() );
+
+ pw.println( body );
+
+ pw.flush();
+ pw.close();
+
+ }
+ catch ( FilerException filerEx ) {
+ processingEnv.getMessager().printMessage(
+ Diagnostic.Kind.ERROR,
+ "Problem with Processing Environment Filer: "
+ + filerEx.getMessage()
+ );
+ }
+ catch ( IOException ioEx ) {
+ processingEnv.getMessager().printMessage(
+ Diagnostic.Kind.ERROR,
+ "Problem opening file to write MetaModel for " + entity.getSimpleName()
+ + ioEx.getMessage()
+ );
+ }
+ }
+
+ /**
+ * Generate everything after import statements.
+ *
+ * @param entity The meta entity for which to write the body
+ *
+ * @return body content
+ */
+ private StringBuffer generateBody(IMetaEntity entity) {
+
+ StringWriter sw = new StringWriter();
+ PrintWriter pw = null;
+ try {
+
+ pw = new PrintWriter( sw );
+
+ pw.println( "@" + entity.importType( Generated.class.getName() ) + "(\"JPA MetaModel for " + entity.getQualifiedName() + "\")" );
+
+ pw.println( "@" + entity.importType( "javax.persistence.metamodel.StaticMetamodel" ) + "(" + entity.getSimpleName() + ".class)" );
+
+ pw.println( "public abstract class " + entity.getSimpleName() + "_" + " {" );
+
+ pw.println();
+
+ List<IMetaAttribute> members = entity.getMembers();
+
+ for ( IMetaAttribute metaMember : members ) {
+ pw.println( " " + metaMember.getDeclarationString() );
+ }
+ pw.println();
+ pw.println( "}" );
+ return sw.getBuffer();
+ }
+ finally {
+ if ( pw != null ) {
+ pw.close();
+ }
+ }
+ }
+
+ private InputStream getInputStreamForResource(String resource) {
+ String pkg = getPackage( resource );
+ String name = getRelativeName( resource );
+ processingEnv.getMessager()
+ .printMessage( Diagnostic.Kind.NOTE, "Checking for " + resource );
+ InputStream ormStream;
+ try {
+ FileObject fileObject = processingEnv.getFiler().getResource( StandardLocation.CLASS_OUTPUT, pkg, name );
+ ormStream = fileObject.openInputStream();
+ }
+ catch ( IOException e1 ) {
+ processingEnv.getMessager()
+ .printMessage(
+ Diagnostic.Kind.WARNING,
+ "Could not load " + resource + " using Filer.getResource(). Trying classpath..."
+ );
+ ormStream = this.getClass().getResourceAsStream( resource );
+ }
+ return ormStream;
+ }
+
+ /**
+ * Tries to open the specified xml file and return an instance of the specified class using JAXB.
+ *
+ * @param resource the xml file name
+ * @param clazz The type of jaxb node to return
+ *
+ * @return The top level jaxb instance contained in the xml file or {@code null} in case the file could not be found.
+ */
+ private <T> T parseXml(String resource, Class<T> clazz) {
+
+ InputStream stream = getInputStreamForResource( resource );
+
+ if ( stream == null ) {
+ processingEnv.getMessager().printMessage( Diagnostic.Kind.NOTE, resource + " not found." );
+ return null;
+ }
+ try {
+ JAXBContext jc = JAXBContext.newInstance( ObjectFactory.class );
+ Unmarshaller unmarshaller = jc.createUnmarshaller();
+ return clazz.cast( unmarshaller.unmarshal( stream ) );
+ }
+ catch ( JAXBException e ) {
+ processingEnv.getMessager().printMessage( Diagnostic.Kind.NOTE, "Error unmarshalling " + resource );
+ e.printStackTrace();
+ return null;
+ }
+ catch ( Exception e ) {
+ processingEnv.getMessager().printMessage(
+ Diagnostic.Kind.ERROR,
+ "Problem while reading " + resource + " " + e.getMessage()
+ );
+ e.printStackTrace();
+ return null;
+ }
+ }
+
+ private String getPackage(String resourceName) {
+ if ( !resourceName.contains( PATH_SEPARATOR ) ) {
+ return "";
+ }
+ else {
+ return resourceName.substring( 0, resourceName.lastIndexOf( PATH_SEPARATOR ) );
+ }
+ }
+
+ private String getRelativeName(String resourceName) {
+ if ( !resourceName.contains( PATH_SEPARATOR ) ) {
+ return resourceName;
+ }
+ else {
+ return resourceName.substring( resourceName.lastIndexOf( PATH_SEPARATOR ) + 1 );
+ }
+ }
+}
14 years, 10 months
Hibernate SVN: r17043 - in jpamodelgen/trunk/generator/src/main/java/org/hibernate/jpa/metamodel/ap: annotation and 1 other directories.
by hibernate-commits@lists.jboss.org
Author: hardy.ferentschik
Date: 2009-07-08 08:12:22 -0400 (Wed, 08 Jul 2009)
New Revision: 17043
Modified:
jpamodelgen/trunk/generator/src/main/java/org/hibernate/jpa/metamodel/ap/JPAMetaModelEntityProcessor.java
jpamodelgen/trunk/generator/src/main/java/org/hibernate/jpa/metamodel/ap/annotation/MetaEntity.java
jpamodelgen/trunk/generator/src/main/java/org/hibernate/jpa/metamodel/ap/xml/XmlMetaEntity.java
Log:
Changed processing order and made sure that model classes gets written out at end of processing
Modified: jpamodelgen/trunk/generator/src/main/java/org/hibernate/jpa/metamodel/ap/JPAMetaModelEntityProcessor.java
===================================================================
--- jpamodelgen/trunk/generator/src/main/java/org/hibernate/jpa/metamodel/ap/JPAMetaModelEntityProcessor.java 2009-07-08 11:41:26 UTC (rev 17042)
+++ jpamodelgen/trunk/generator/src/main/java/org/hibernate/jpa/metamodel/ap/JPAMetaModelEntityProcessor.java 2009-07-08 12:12:22 UTC (rev 17043)
@@ -1,346 +1,341 @@
-// $Id:$
-package org.hibernate.jpa.metamodel.ap;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.io.PrintWriter;
-import java.io.StringWriter;
-import java.text.SimpleDateFormat;
-import java.util.Collection;
-import java.util.Date;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import javax.annotation.Generated;
-import javax.annotation.processing.AbstractProcessor;
-import javax.annotation.processing.FilerException;
-import javax.annotation.processing.ProcessingEnvironment;
-import javax.annotation.processing.RoundEnvironment;
-import javax.annotation.processing.SupportedAnnotationTypes;
-import javax.annotation.processing.SupportedSourceVersion;
-import static javax.lang.model.SourceVersion.RELEASE_6;
-import javax.lang.model.element.AnnotationMirror;
-import javax.lang.model.element.Element;
-import javax.lang.model.element.ElementKind;
-import javax.lang.model.element.TypeElement;
-import javax.lang.model.util.Elements;
-import javax.tools.Diagnostic;
-import javax.tools.FileObject;
-import javax.tools.StandardLocation;
-import javax.xml.bind.JAXBContext;
-import javax.xml.bind.JAXBException;
-import javax.xml.bind.Unmarshaller;
-import javax.persistence.MappedSuperclass;
-import javax.persistence.Embeddable;
-
-import org.hibernate.jpa.metamodel.ap.annotation.MetaEntity;
-import org.hibernate.jpa.metamodel.ap.xml.XmlMetaEntity;
-import org.hibernate.jpa.metamodel.xml.jaxb.Entity;
-import org.hibernate.jpa.metamodel.xml.jaxb.EntityMappings;
-import org.hibernate.jpa.metamodel.xml.jaxb.ObjectFactory;
-import org.hibernate.jpa.metamodel.xml.jaxb.Persistence;
-
-/**
- * Main annotation processor.
- *
- * @author Max Andersen
- * @author Hardy Ferentschik
- */
-//@SupportedAnnotationTypes("javax.persistence.Entity")
-@SupportedAnnotationTypes("*")
-@SupportedSourceVersion(RELEASE_6)
-public class JPAMetaModelEntityProcessor extends AbstractProcessor {
-
- private static final String PATH_SEPARATOR = "/";
- private static final String PERSISTENCE_XML = "/META-INF/persistence.xml";
-
- private final Map<String, IMetaEntity> metaEntities = new HashMap<String, IMetaEntity>();
- private boolean xmlProcessed = false;
- private static final String ENTITY_ANN = javax.persistence.Entity.class.getName();
- private static final String MAPPED_SUPERCLASS_ANN = MappedSuperclass.class.getName();
- private static final String EMBEDDABLE_ANN = Embeddable.class.getName();
-
-
- public void init(ProcessingEnvironment env) {
- super.init( env );
- processingEnv.getMessager().printMessage( Diagnostic.Kind.NOTE, "Init Processor " + this );
- }
-
- @Override
- public boolean process(final Set<? extends TypeElement> annotations,
- final RoundEnvironment roundEnvironment) {
-
- if ( roundEnvironment.processingOver() ) {
- processingEnv.getMessager()
- .printMessage( Diagnostic.Kind.NOTE, "Finished processing" );
- return false;
- }
-
- if ( !hostJPAAnnotations( annotations ) ) {
- processingEnv.getMessager()
- .printMessage( Diagnostic.Kind.NOTE, "Current processing round does not contain entities" );
- return true;
- }
-
- if ( !xmlProcessed ) {
- parsePersistenceXml();
- }
-
- Set<? extends Element> elements = roundEnvironment.getRootElements();
- for ( Element element : elements ) {
- processingEnv.getMessager().printMessage( Diagnostic.Kind.NOTE, "Processing " + element.toString() );
- handleRootElementAnnotationMirrors( element );
- }
-
- return true;
- }
-
- private boolean hostJPAAnnotations(Set<? extends TypeElement> annotations) {
- for ( TypeElement type : annotations ) {
- final String typeName = type.getQualifiedName().toString();
- if ( typeName.equals( ENTITY_ANN ) ) {
- return true;
- }
- else if ( typeName.equals( EMBEDDABLE_ANN ) ) {
- return true;
- }
- else if ( typeName.equals( MAPPED_SUPERCLASS_ANN ) ) {
- return true;
- }
- }
- return false;
- }
-
- private void parsePersistenceXml() {
- Persistence persistence = parseXml( PERSISTENCE_XML, Persistence.class );
- if ( persistence != null )
-
- {
- List<Persistence.PersistenceUnit> persistenceUnits = persistence.getPersistenceUnit();
- for ( Persistence.PersistenceUnit unit : persistenceUnits ) {
- List<String> mappingFiles = unit.getMappingFile();
- for ( String mappingFile : mappingFiles ) {
- parsingOrmXml( mappingFile );
- }
- }
- }
- xmlProcessed = true;
- }
-
-
- private void parsingOrmXml(String resource) {
- EntityMappings mappings = parseXml( resource, EntityMappings.class );
- if ( mappings == null ) {
- return;
- }
- Collection<Entity> entities = mappings.getEntity();
- String packageName = mappings.getPackage();
- for ( Entity entity : entities ) {
- String fullyQualifiedClassName = packageName + "." + entity.getClazz();
- Elements utils = processingEnv.getElementUtils();
- XmlMetaEntity metaEntity = new XmlMetaEntity(
- entity, packageName, utils.getTypeElement( fullyQualifiedClassName )
- );
-
- if ( metaEntities.containsKey( fullyQualifiedClassName ) ) {
- processingEnv.getMessager().printMessage(
- Diagnostic.Kind.WARNING,
- fullyQualifiedClassName + " was already processed once. Skipping second occurance."
- );
- }
-
- writeFile( metaEntity );
- metaEntities.put( fullyQualifiedClassName, metaEntity );
- }
- }
-
- private void writeProcessingDiagnostics(Set<? extends TypeElement> annotations, RoundEnvironment roundEnvironment) {
- StringBuilder sb = new StringBuilder();
- sb.append( "\n>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n" );
- sb.append( new SimpleDateFormat().format( new Date() ) );
- sb.append( "\n" );
- sb.append( "Processing annotations " ).append( annotations ).append( " on:" );
-
- Set<? extends Element> elements = roundEnvironment.getRootElements();
- sb.append( "\n" );
- for ( Element element : elements ) {
- sb.append( element.toString() );
- sb.append( "\n" );
- }
- sb.append( ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n" );
- processingEnv.getMessager().printMessage( Diagnostic.Kind.NOTE, sb.toString() );
- }
-
- private void handleRootElementAnnotationMirrors(final Element element) {
-
- List<? extends AnnotationMirror> annotationMirrors = element
- .getAnnotationMirrors();
-
- for ( AnnotationMirror mirror : annotationMirrors ) {
- final String annotationType = mirror.getAnnotationType().toString();
-
- if ( element.getKind() == ElementKind.CLASS &&
- annotationType.equals( ENTITY_ANN ) ) {
- MetaEntity metaEntity = new MetaEntity( processingEnv, ( TypeElement ) element );
- writeFile( metaEntity );
- }
- }
- }
-
- private void writeFile(IMetaEntity entity) {
-
- try {
- String metaModelPackage = entity.getPackageName();
-
- StringBuffer body = generateBody( entity );
-
- FileObject fo = processingEnv.getFiler().createSourceFile(
- metaModelPackage + "." + entity.getSimpleName() + "_"
- );
- OutputStream os = fo.openOutputStream();
- PrintWriter pw = new PrintWriter( os );
-
- pw.println( "package " + metaModelPackage + ";" );
-
- pw.println();
-
- pw.println( entity.generateImports() );
-
- pw.println( body );
-
- pw.flush();
- pw.close();
-
- }
- catch ( FilerException filerEx ) {
- processingEnv.getMessager().printMessage(
- Diagnostic.Kind.ERROR,
- "Problem with Processing Environment Filer: "
- + filerEx.getMessage()
- );
- }
- catch ( IOException ioEx ) {
- processingEnv.getMessager().printMessage(
- Diagnostic.Kind.ERROR,
- "Problem opening file to write MetaModel for " + entity.getSimpleName()
- + ioEx.getMessage()
- );
- }
- }
-
- /**
- * Generate everything after import statements.
- *
- * @param entity The meta entity for which to write the body
- *
- * @return body content
- */
- private StringBuffer generateBody(IMetaEntity entity) {
-
- StringWriter sw = new StringWriter();
- PrintWriter pw = null;
- try {
-
- pw = new PrintWriter( sw );
-
- pw.println( "@" + entity.importType( Generated.class.getName() ) + "(\"JPA MetaModel for " + entity.getQualifiedName() + "\")" );
-
- pw.println( "@" + entity.importType( "javax.persistence.metamodel.StaticMetamodel" ) + "(" + entity.getSimpleName() + ".class)" );
-
- pw.println( "public abstract class " + entity.getSimpleName() + "_" + " {" );
-
- pw.println();
-
- List<IMetaAttribute> members = entity.getMembers();
-
- for ( IMetaAttribute metaMember : members ) {
- pw.println( " " + metaMember.getDeclarationString() );
- }
- pw.println();
- pw.println( "}" );
- return sw.getBuffer();
- }
- finally {
- if ( pw != null ) {
- pw.close();
- }
- }
- }
-
- private InputStream getInputStreamForResource(String resource) {
- String pkg = getPackage( resource );
- String name = getRelativeName( resource );
- processingEnv.getMessager()
- .printMessage( Diagnostic.Kind.NOTE, "Checking for " + resource );
- InputStream ormStream;
- try {
- FileObject fileObject = processingEnv.getFiler().getResource( StandardLocation.CLASS_OUTPUT, pkg, name );
- ormStream = fileObject.openInputStream();
- }
- catch ( IOException e1 ) {
- processingEnv.getMessager()
- .printMessage(
- Diagnostic.Kind.WARNING,
- "Could not load " + resource + " using Filer.getResource(). Trying classpath..."
- );
- ormStream = this.getClass().getResourceAsStream( resource );
- }
- return ormStream;
- }
-
- /**
- * Tries to open the specified xml file and return an instance of the specified class using JAXB.
- *
- * @param resource the xml file name
- * @param clazz The type of jaxb node to return
- *
- * @return The top level jaxb instance contained in the xml file or {@code null} in case the file could not be found.
- */
- private <T> T parseXml(String resource, Class<T> clazz) {
-
- InputStream stream = getInputStreamForResource( resource );
-
- if ( stream == null ) {
- processingEnv.getMessager().printMessage( Diagnostic.Kind.NOTE, resource + " not found." );
- return null;
- }
- try {
- JAXBContext jc = JAXBContext.newInstance( ObjectFactory.class );
- Unmarshaller unmarshaller = jc.createUnmarshaller();
- return clazz.cast( unmarshaller.unmarshal( stream ) );
- }
- catch ( JAXBException e ) {
- processingEnv.getMessager().printMessage( Diagnostic.Kind.NOTE, "Error unmarshalling " + resource );
- e.printStackTrace();
- return null;
- }
- catch ( Exception e ) {
- processingEnv.getMessager().printMessage(
- Diagnostic.Kind.ERROR,
- "Problem while reading " + resource + " " + e.getMessage()
- );
- e.printStackTrace();
- return null;
- }
- }
-
- private String getPackage(String resourceName) {
- if ( !resourceName.contains( PATH_SEPARATOR ) ) {
- return "";
- }
- else {
- return resourceName.substring( 0, resourceName.lastIndexOf( PATH_SEPARATOR ) );
- }
- }
-
- private String getRelativeName(String resourceName) {
- if ( !resourceName.contains( PATH_SEPARATOR ) ) {
- return resourceName;
- }
- else {
- return resourceName.substring( resourceName.lastIndexOf( PATH_SEPARATOR ) + 1 );
- }
- }
-}
+// $Id:$
+package org.hibernate.jpa.metamodel.ap;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.io.PrintWriter;
+import java.io.StringWriter;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import javax.annotation.Generated;
+import javax.annotation.processing.AbstractProcessor;
+import javax.annotation.processing.FilerException;
+import javax.annotation.processing.ProcessingEnvironment;
+import javax.annotation.processing.RoundEnvironment;
+import javax.annotation.processing.SupportedAnnotationTypes;
+import javax.annotation.processing.SupportedSourceVersion;
+import static javax.lang.model.SourceVersion.RELEASE_6;
+import javax.lang.model.element.AnnotationMirror;
+import javax.lang.model.element.Element;
+import javax.lang.model.element.ElementKind;
+import javax.lang.model.element.TypeElement;
+import javax.lang.model.util.Elements;
+i!
mport javax.tools.Diagnostic;
+import javax.tools.FileObject;
+import javax.tools.StandardLocation;
+import javax.xml.bind.JAXBContext;
+import javax.xml.bind.JAXBException;
+import javax.xml.bind.Unmarshaller;
+import javax.persistence.MappedSuperclass;
+import javax.persistence.Embeddable;
+
+import org.hibernate.jpa.metamodel.ap.annotation.MetaEntity;
+import org.hibernate.jpa.metamodel.ap.xml.XmlMetaEntity;
+import org.hibernate.jpa.metamodel.xml.jaxb.Entity;
+import org.hibernate.jpa.metamodel.xml.jaxb.EntityMappings;
+import org.hibernate.jpa.metamodel.xml.jaxb.ObjectFactory;
+import org.hibernate.jpa.metamodel.xml.jaxb.Persistence;
+
+/**
+ * Main annotation processor.
+ *
+ * @author Max Andersen
+ * @author Hardy Ferentschik
+ */
+//@SupportedAnnotationTypes("javax.persistence.Entity")
+@SupportedAnnotationTypes("*")
+@SupportedSourceVersion(RELEASE_6)
+public class JPAMetaModelEntityProcessor extends AbstractProcessor {
+
+ private static final String PATH_SEPARAT!
OR = "/";
+ private static final String PERSISTENCE_XML = "/ME!
TA-INF/p
ersistence.xml";
+ private static final Boolean ALLOW_OTHER_PROCESSORS_TO_CLAIM_ANNOTATIONS = Boolean.FALSE;
+
+ private final Map<String, IMetaEntity> metaEntities = new HashMap<String, IMetaEntity>();
+ private boolean xmlProcessed = false;
+ private static final String ENTITY_ANN = javax.persistence.Entity.class.getName();
+ private static final String MAPPED_SUPERCLASS_ANN = MappedSuperclass.class.getName();
+ private static final String EMBEDDABLE_ANN = Embeddable.class.getName();
+
+
+ public void init(ProcessingEnvironment env) {
+ super.init( env );
+ processingEnv.getMessager().printMessage( Diagnostic.Kind.NOTE, "Init Processor " + this );
+ }
+
+ @Override
+ public boolean process(final Set<? extends TypeElement> annotations,
+ final RoundEnvironment roundEnvironment) {
+
+ if ( roundEnvironment.processingOver() ) {
+ processingEnv.getMessager()
+ .printMessage( Diagnostic.Kind.NOTE, "Last processing round." );
+
+ createMetaModelClasses();
+
+ !
processingEnv.getMessager()
+ .printMessage( Diagnostic.Kind.NOTE, "Finished processing" );
+ return ALLOW_OTHER_PROCESSORS_TO_CLAIM_ANNOTATIONS;
+ }
+
+ if ( !xmlProcessed ) {
+ parsePersistenceXml();
+ }
+
+ if ( !hostJPAAnnotations( annotations ) ) {
+ processingEnv.getMessager()
+ .printMessage( Diagnostic.Kind.NOTE, "Current processing round does not contain entities" );
+ return ALLOW_OTHER_PROCESSORS_TO_CLAIM_ANNOTATIONS;
+ }
+
+ Set<? extends Element> elements = roundEnvironment.getRootElements();
+ for ( Element element : elements ) {
+ processingEnv.getMessager().printMessage( Diagnostic.Kind.NOTE, "Processing " + element.toString() );
+ handleRootElementAnnotationMirrors( element );
+ }
+
+ return ALLOW_OTHER_PROCESSORS_TO_CLAIM_ANNOTATIONS;
+ }
+
+ private void createMetaModelClasses() {
+ for ( IMetaEntity entity : metaEntities.values() ) {
+ processingEnv.getMessager()
+ .printMessage( Diagnostic.Kind.NOTE, "Writing meta m!
odel for " + entity );
+ writeFile( entity );
+ }
+ }
+
+ p!
rivate b
oolean hostJPAAnnotations(Set<? extends TypeElement> annotations) {
+ for ( TypeElement type : annotations ) {
+ final String typeName = type.getQualifiedName().toString();
+ if ( typeName.equals( ENTITY_ANN ) ) {
+ return true;
+ }
+ else if ( typeName.equals( EMBEDDABLE_ANN ) ) {
+ return true;
+ }
+ else if ( typeName.equals( MAPPED_SUPERCLASS_ANN ) ) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ private void parsePersistenceXml() {
+ Persistence persistence = parseXml( PERSISTENCE_XML, Persistence.class );
+ if ( persistence != null )
+
+ {
+ List<Persistence.PersistenceUnit> persistenceUnits = persistence.getPersistenceUnit();
+ for ( Persistence.PersistenceUnit unit : persistenceUnits ) {
+ List<String> mappingFiles = unit.getMappingFile();
+ for ( String mappingFile : mappingFiles ) {
+ parsingOrmXml( mappingFile );
+ }
+ }
+ }
+ xmlProcessed = true;
+ }
+
+
+ private void parsingOrmXml(String resource) {
+ EntityM!
appings mappings = parseXml( resource, EntityMappings.class );
+ if ( mappings == null ) {
+ return;
+ }
+ Collection<Entity> entities = mappings.getEntity();
+ String packageName = mappings.getPackage();
+ for ( Entity entity : entities ) {
+ String fullyQualifiedClassName = packageName + "." + entity.getClazz();
+ Elements utils = processingEnv.getElementUtils();
+ XmlMetaEntity metaEntity = new XmlMetaEntity(
+ entity, packageName, utils.getTypeElement( fullyQualifiedClassName )
+ );
+
+ if ( metaEntities.containsKey( fullyQualifiedClassName ) ) {
+ processingEnv.getMessager().printMessage(
+ Diagnostic.Kind.WARNING,
+ fullyQualifiedClassName + " was already processed once. Skipping second occurance."
+ );
+ }
+ metaEntities.put( fullyQualifiedClassName, metaEntity );
+ }
+ }
+
+ private void handleRootElementAnnotationMirrors(final Element element) {
+
+ List<? extends AnnotationMirror> annotationMirrors = element
+ .getAnno!
tationMirrors();
+
+ for ( AnnotationMirror mirror : annotati!
onMirror
s ) {
+ final String annotationType = mirror.getAnnotationType().toString();
+
+ if ( element.getKind() == ElementKind.CLASS &&
+ annotationType.equals( ENTITY_ANN ) ) {
+ MetaEntity metaEntity = new MetaEntity( processingEnv, ( TypeElement ) element );
+
+ // TODO instead of just adding the entity we have to do some merging.
+ metaEntities.put( metaEntity.getQualifiedName(), metaEntity );
+ }
+ }
+ }
+
+ private void writeFile(IMetaEntity entity) {
+
+ try {
+ String metaModelPackage = entity.getPackageName();
+
+ StringBuffer body = generateBody( entity );
+
+ FileObject fo = processingEnv.getFiler().createSourceFile(
+ metaModelPackage + "." + entity.getSimpleName() + "_"
+ );
+ OutputStream os = fo.openOutputStream();
+ PrintWriter pw = new PrintWriter( os );
+
+ pw.println( "package " + metaModelPackage + ";" );
+
+ pw.println();
+
+ pw.println( entity.generateImports() );
+
+ pw.println( body );
+
+ pw.flush();
+ pw.clos!
e();
+
+ }
+ catch ( FilerException filerEx ) {
+ processingEnv.getMessager().printMessage(
+ Diagnostic.Kind.ERROR,
+ "Problem with Processing Environment Filer: "
+ + filerEx.getMessage()
+ );
+ }
+ catch ( IOException ioEx ) {
+ processingEnv.getMessager().printMessage(
+ Diagnostic.Kind.ERROR,
+ "Problem opening file to write MetaModel for " + entity.getSimpleName()
+ + ioEx.getMessage()
+ );
+ }
+ }
+
+ /**
+ * Generate everything after import statements.
+ *
+ * @param entity The meta entity for which to write the body
+ *
+ * @return body content
+ */
+ private StringBuffer generateBody(IMetaEntity entity) {
+
+ StringWriter sw = new StringWriter();
+ PrintWriter pw = null;
+ try {
+
+ pw = new PrintWriter( sw );
+
+ pw.println( "@" + entity.importType( Generated.class.getName() ) + "(\"JPA MetaModel for " + entity.getQualifiedName() + "\")" );
+
+ pw.println( "@" + entity.importType( "javax.persistence.metamode!
l.StaticMetamodel" ) + "(" + entity.getSimpleName() + ".class)!
" );
+
+
pw.println( "public abstract class " + entity.getSimpleName() + "_" + " {" );
+
+ pw.println();
+
+ List<IMetaAttribute> members = entity.getMembers();
+
+ for ( IMetaAttribute metaMember : members ) {
+ pw.println( " " + metaMember.getDeclarationString() );
+ }
+ pw.println();
+ pw.println( "}" );
+ return sw.getBuffer();
+ }
+ finally {
+ if ( pw != null ) {
+ pw.close();
+ }
+ }
+ }
+
+ private InputStream getInputStreamForResource(String resource) {
+ String pkg = getPackage( resource );
+ String name = getRelativeName( resource );
+ processingEnv.getMessager()
+ .printMessage( Diagnostic.Kind.NOTE, "Checking for " + resource );
+ InputStream ormStream;
+ try {
+ FileObject fileObject = processingEnv.getFiler().getResource( StandardLocation.CLASS_OUTPUT, pkg, name );
+ ormStream = fileObject.openInputStream();
+ }
+ catch ( IOException e1 ) {
+ processingEnv.getMessager()
+ .printMessage(
+ Diagnostic.Kind.WARNING,
!
+ "Could not load " + resource + " using Filer.getResource(). Trying classpath..."
+ );
+ ormStream = this.getClass().getResourceAsStream( resource );
+ }
+ return ormStream;
+ }
+
+ /**
+ * Tries to open the specified xml file and return an instance of the specified class using JAXB.
+ *
+ * @param resource the xml file name
+ * @param clazz The type of jaxb node to return
+ *
+ * @return The top level jaxb instance contained in the xml file or {@code null} in case the file could not be found.
+ */
+ private <T> T parseXml(String resource, Class<T> clazz) {
+
+ InputStream stream = getInputStreamForResource( resource );
+
+ if ( stream == null ) {
+ processingEnv.getMessager().printMessage( Diagnostic.Kind.NOTE, resource + " not found." );
+ return null;
+ }
+ try {
+ JAXBContext jc = JAXBContext.newInstance( ObjectFactory.class );
+ Unmarshaller unmarshaller = jc.createUnmarshaller();
+ return clazz.cast( unmarshaller.unmarshal( stream )!
);
+ }
+ catch ( JAXBException e ) {
+ processingEnv.getM!
essager(
).printMessage( Diagnostic.Kind.NOTE, "Error unmarshalling " + resource );
+ e.printStackTrace();
+ return null;
+ }
+ catch ( Exception e ) {
+ processingEnv.getMessager().printMessage(
+ Diagnostic.Kind.ERROR,
+ "Problem while reading " + resource + " " + e.getMessage()
+ );
+ e.printStackTrace();
+ return null;
+ }
+ }
+
+ private String getPackage(String resourceName) {
+ if ( !resourceName.contains( PATH_SEPARATOR ) ) {
+ return "";
+ }
+ else {
+ return resourceName.substring( 0, resourceName.lastIndexOf( PATH_SEPARATOR ) );
+ }
+ }
+
+ private String getRelativeName(String resourceName) {
+ if ( !resourceName.contains( PATH_SEPARATOR ) ) {
+ return resourceName;
+ }
+ else {
+ return resourceName.substring( resourceName.lastIndexOf( PATH_SEPARATOR ) + 1 );
+ }
+ }
+}
Property changes on: jpamodelgen/trunk/generator/src/main/java/org/hibernate/jpa/metamodel/ap/JPAMetaModelEntityProcessor.java
___________________________________________________________________
Name: svn:keywords
+ Id
Modified: jpamodelgen/trunk/generator/src/main/java/org/hibernate/jpa/metamodel/ap/annotation/MetaEntity.java
===================================================================
--- jpamodelgen/trunk/generator/src/main/java/org/hibernate/jpa/metamodel/ap/annotation/MetaEntity.java 2009-07-08 11:41:26 UTC (rev 17042)
+++ jpamodelgen/trunk/generator/src/main/java/org/hibernate/jpa/metamodel/ap/annotation/MetaEntity.java 2009-07-08 12:12:22 UTC (rev 17043)
@@ -132,6 +132,14 @@
return false;
}
+ @Override
+ public String toString() {
+ final StringBuilder sb = new StringBuilder();
+ sb.append( "MetaEntity" );
+ sb.append( "{element=" ).append( element );
+ sb.append( '}' );
+ return sb.toString();
+ }
static Map<String, String> COLLECTIONS = new HashMap<String, String>();
Property changes on: jpamodelgen/trunk/generator/src/main/java/org/hibernate/jpa/metamodel/ap/annotation/MetaEntity.java
___________________________________________________________________
Name: svn:keywords
+ Id
Modified: jpamodelgen/trunk/generator/src/main/java/org/hibernate/jpa/metamodel/ap/xml/XmlMetaEntity.java
===================================================================
--- jpamodelgen/trunk/generator/src/main/java/org/hibernate/jpa/metamodel/ap/xml/XmlMetaEntity.java 2009-07-08 11:41:26 UTC (rev 17042)
+++ jpamodelgen/trunk/generator/src/main/java/org/hibernate/jpa/metamodel/ap/xml/XmlMetaEntity.java 2009-07-08 12:12:22 UTC (rev 17043)
@@ -172,4 +172,13 @@
}
return typeName;
}
+
+ @Override
+ public String toString() {
+ final StringBuilder sb = new StringBuilder();
+ sb.append( "XmlMetaEntity" );
+ sb.append( "{type=" ).append( type );
+ sb.append( '}' );
+ return sb.toString();
+ }
}
Property changes on: jpamodelgen/trunk/generator/src/main/java/org/hibernate/jpa/metamodel/ap/xml/XmlMetaEntity.java
___________________________________________________________________
Name: svn:keywords
+ Id
14 years, 10 months
Hibernate SVN: r17042 - jpamodelgen/trunk/generator/src/main/java/org/hibernate/jpa/metamodel/ap.
by hibernate-commits@lists.jboss.org
Author: epbernard
Date: 2009-07-08 07:41:26 -0400 (Wed, 08 Jul 2009)
New Revision: 17042
Modified:
jpamodelgen/trunk/generator/src/main/java/org/hibernate/jpa/metamodel/ap/JPAMetaModelEntityProcessor.java
Log:
clearer name
Modified: jpamodelgen/trunk/generator/src/main/java/org/hibernate/jpa/metamodel/ap/JPAMetaModelEntityProcessor.java
===================================================================
--- jpamodelgen/trunk/generator/src/main/java/org/hibernate/jpa/metamodel/ap/JPAMetaModelEntityProcessor.java 2009-07-08 11:12:57 UTC (rev 17041)
+++ jpamodelgen/trunk/generator/src/main/java/org/hibernate/jpa/metamodel/ap/JPAMetaModelEntityProcessor.java 2009-07-08 11:41:26 UTC (rev 17042)
@@ -32,6 +32,8 @@
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
+import javax.persistence.MappedSuperclass;
+import javax.persistence.Embeddable;
import org.hibernate.jpa.metamodel.ap.annotation.MetaEntity;
import org.hibernate.jpa.metamodel.ap.xml.XmlMetaEntity;
@@ -56,7 +58,11 @@
private final Map<String, IMetaEntity> metaEntities = new HashMap<String, IMetaEntity>();
private boolean xmlProcessed = false;
+ private static final String ENTITY_ANN = javax.persistence.Entity.class.getName();
+ private static final String MAPPED_SUPERCLASS_ANN = MappedSuperclass.class.getName();
+ private static final String EMBEDDABLE_ANN = Embeddable.class.getName();
+
public void init(ProcessingEnvironment env) {
super.init( env );
processingEnv.getMessager().printMessage( Diagnostic.Kind.NOTE, "Init Processor " + this );
@@ -72,7 +78,7 @@
return false;
}
- if ( !processingRoundConstainsEntities( annotations ) ) {
+ if ( !hostJPAAnnotations( annotations ) ) {
processingEnv.getMessager()
.printMessage( Diagnostic.Kind.NOTE, "Current processing round does not contain entities" );
return true;
@@ -91,11 +97,18 @@
return true;
}
- private boolean processingRoundConstainsEntities(Set<? extends TypeElement> annotations) {
+ private boolean hostJPAAnnotations(Set<? extends TypeElement> annotations) {
for ( TypeElement type : annotations ) {
- if ( type.getQualifiedName().toString().equals( javax.persistence.Entity.class.getName() ) ) {
+ final String typeName = type.getQualifiedName().toString();
+ if ( typeName.equals( ENTITY_ANN ) ) {
return true;
}
+ else if ( typeName.equals( EMBEDDABLE_ANN ) ) {
+ return true;
+ }
+ else if ( typeName.equals( MAPPED_SUPERCLASS_ANN ) ) {
+ return true;
+ }
}
return false;
}
@@ -169,7 +182,7 @@
final String annotationType = mirror.getAnnotationType().toString();
if ( element.getKind() == ElementKind.CLASS &&
- annotationType.equals( javax.persistence.Entity.class.getName() ) ) {
+ annotationType.equals( ENTITY_ANN ) ) {
MetaEntity metaEntity = new MetaEntity( processingEnv, ( TypeElement ) element );
writeFile( metaEntity );
}
14 years, 10 months