HHH-6111 enabling jaxb model generation for hbm configuration files

This commit is contained in:
Hardy Ferentschik 2011-04-11 18:51:41 +02:00
parent a3ebcd81bc
commit 0d29c346ec
15 changed files with 405 additions and 82 deletions

View File

@ -123,7 +123,7 @@ subprojects { subProject ->
// appropriately inject the common dependencies into each sub-project // appropriately inject the common dependencies into each sub-project
dependencies { dependencies {
compile( libraries.logging ) compile( libraries.logging )
testCompile( libraries.junit ) testCompile( libraries.junit )
testRuntime( libraries.slf4j_api ) testRuntime( libraries.slf4j_api )
testRuntime( libraries.slf4j_log4j12 ) testRuntime( libraries.slf4j_log4j12 )

View File

@ -52,7 +52,14 @@ task jaxb << {
ant.taskdef(name: 'xjc', classname: 'com.sun.tools.xjc.XJCTask', classpath: configurations.jaxb.asPath) ant.taskdef(name: 'xjc', classname: 'com.sun.tools.xjc.XJCTask', classpath: configurations.jaxb.asPath)
ant.jaxbTargetDir = jaxbTargetDir ant.jaxbTargetDir = jaxbTargetDir
ant.xjc(destdir: '${jaxbTargetDir}', package: 'org.hibernate.metamodel.source.xml') {
ant.xjc(destdir: '${jaxbTargetDir}', package: 'org.hibernate.metamodel.source.hbm.xml.config') {
schema(dir: 'src/main/resources/org/hibernate', includes: 'hibernate-configuration-3.0.xsd')
}
ant.xjc(destdir: '${jaxbTargetDir}', package: 'org.hibernate.metamodel.source.hbm.xml.mapping') {
schema(dir: 'src/main/resources/org/hibernate', includes: 'hibernate-mapping-3.0.xsd')
}
ant.xjc(destdir: '${jaxbTargetDir}', package: 'org.hibernate.metamodel.source.annotation.xml') {
schema(dir: 'src/main/resources/org/hibernate/ejb', includes: 'orm_2_0.xsd') schema(dir: 'src/main/resources/org/hibernate/ejb', includes: 'orm_2_0.xsd')
} }
} }

View File

@ -29,13 +29,12 @@ import java.io.Serializable;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import org.slf4j.Logger; import org.jboss.logging.Logger;
import org.slf4j.LoggerFactory;
import org.hibernate.DuplicateMappingException; import org.hibernate.DuplicateMappingException;
import org.hibernate.internal.CoreMessageLogger;
import org.hibernate.cfg.EJB3NamingStrategy; import org.hibernate.cfg.EJB3NamingStrategy;
import org.hibernate.cfg.NamingStrategy; import org.hibernate.cfg.NamingStrategy;
import org.hibernate.internal.CoreMessageLogger;
import org.hibernate.mapping.FetchProfile; import org.hibernate.mapping.FetchProfile;
import org.hibernate.mapping.MetadataSource; import org.hibernate.mapping.MetadataSource;
import org.hibernate.metamodel.binding.EntityBinding; import org.hibernate.metamodel.binding.EntityBinding;
@ -44,16 +43,16 @@ import org.hibernate.metamodel.relational.Database;
import org.hibernate.metamodel.source.annotations.AnnotationBinder; import org.hibernate.metamodel.source.annotations.AnnotationBinder;
import org.hibernate.metamodel.source.hbm.HibernateXmlBinder; import org.hibernate.metamodel.source.hbm.HibernateXmlBinder;
/** /**
* TODO : javadoc * Container for configuration data while building and binding the metamodel
* *
* @author Steve Ebersole * @author Steve Ebersole
*/ */
public class Metadata implements Serializable { public class Metadata implements Serializable {
private static final Logger log = LoggerFactory.getLogger( Metadata.class ); private static final CoreMessageLogger LOG = Logger.getMessageLogger(
CoreMessageLogger.class, Metadata.class.getName()
);
private static final HibernateLogger LOG = Logger.getMessageLogger(HibernateLogger.class, Metadata.class.getName());
private final AnnotationBinder annotationBinder; private final AnnotationBinder annotationBinder;
private final HibernateXmlBinder hibernateXmlBinder; private final HibernateXmlBinder hibernateXmlBinder;
private final ExtendsQueue extendsQueue; private final ExtendsQueue extendsQueue;
@ -139,10 +138,10 @@ public class Metadata implements Serializable {
if ( imports == null ) { if ( imports == null ) {
imports = new HashMap<String, String>(); imports = new HashMap<String, String>();
} }
log.trace( "Import: " + importName + " -> " + entityName ); LOG.trace( "Import: " + importName + " -> " + entityName );
String old = imports.put( importName, entityName ); String old = imports.put( importName, entityName );
if ( old != null ) { if ( old != null ) {
log.debug( "import name [{}] overrode previous [{}]", importName, old ); LOG.debug( "import name [" + importName + "] overrode previous [{" + old + "}]" );
} }
} }

View File

@ -38,25 +38,24 @@ import java.util.Set;
import org.dom4j.Attribute; import org.dom4j.Attribute;
import org.dom4j.Document; import org.dom4j.Document;
import org.dom4j.Element; import org.dom4j.Element;
import org.slf4j.Logger; import org.jboss.logging.Logger;
import org.slf4j.LoggerFactory;
import org.hibernate.internal.CoreMessageLogger;
import org.hibernate.InvalidMappingException; import org.hibernate.InvalidMappingException;
import org.hibernate.MappingException; import org.hibernate.MappingException;
import org.hibernate.cfg.MetadataSourceType; import org.hibernate.cfg.MetadataSourceType;
import org.hibernate.internal.CoreMessageLogger;
import org.hibernate.internal.util.collections.JoinedIterator; import org.hibernate.internal.util.collections.JoinedIterator;
import org.hibernate.internal.util.xml.XmlDocument; import org.hibernate.internal.util.xml.XmlDocument;
/** /**
* TODO : javadoc * Container for xml configuration documents and annotated classes.
* *
* @author Steve Ebersole * @author Steve Ebersole
*/ */
public class MetadataSourceQueue implements Serializable { public class MetadataSourceQueue implements Serializable {
private static final Logger log = LoggerFactory.getLogger( MetadataSourceQueue.class ); private static final CoreMessageLogger LOG = Logger.getMessageLogger(
private static final CoreMessageLogger LOG = Logger.getMessageLogger(CoreMessageLogger.class, MetadataSourceQueue.class.getName()); CoreMessageLogger.class, MetadataSourceQueue.class.getName()
);
private final Metadata metadata; private final Metadata metadata;
private LinkedHashMap<XmlDocument, Set<String>> hbmMetadataToEntityNamesMap private LinkedHashMap<XmlDocument, Set<String>> hbmMetadataToEntityNamesMap
@ -140,7 +139,7 @@ public class MetadataSourceQueue implements Serializable {
} }
private void processHbmXmlQueue() { private void processHbmXmlQueue() {
log.debug( "Processing hbm.xml files" ); LOG.debug( "Processing hbm.xml files" );
for ( Map.Entry<XmlDocument, Set<String>> entry : hbmMetadataToEntityNamesMap.entrySet() ) { for ( Map.Entry<XmlDocument, Set<String>> entry : hbmMetadataToEntityNamesMap.entrySet() ) {
// Unfortunately we have to create a Mappings instance for each iteration here // Unfortunately we have to create a Mappings instance for each iteration here
processHbmXml( entry.getKey(), entry.getValue() ); processHbmXml( entry.getKey(), entry.getValue() );
@ -163,7 +162,7 @@ public class MetadataSourceQueue implements Serializable {
} }
private void processAnnotatedClassesQueue() { private void processAnnotatedClassesQueue() {
log.debug( "Process annotated classes" ); LOG.debug( "Process annotated classes" );
annotatedClasses.clear(); annotatedClasses.clear();
} }

View File

@ -1,31 +1,21 @@
package org.hibernate.metamodel.source.annotations; package org.hibernate.metamodel.source.annotations;
import java.io.InputStream; import java.io.InputStream;
import java.net.URL;
import java.util.HashSet; import java.util.HashSet;
import java.util.Set; import java.util.Set;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException; import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import org.jboss.jandex.Index; import org.jboss.jandex.Index;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xml.sax.SAXException;
import org.hibernate.AnnotationException; import org.hibernate.AnnotationException;
import org.hibernate.metamodel.source.xml.EntityMappings; import org.hibernate.metamodel.source.annotation.xml.EntityMappings;
import org.hibernate.metamodel.source.util.xml.XmlHelper;
/** /**
* @author Hardy Ferentschik * @author Hardy Ferentschik
* @todo Need some create some XMLContext as well which can be populated w/ information which can not be expressed via annotations * @todo Need some create some XMLContext as well which can be populated w/ information which can not be expressed via annotations
*/ */
public class OrmXmlParser { public class OrmXmlParser {
private static final Logger log = LoggerFactory.getLogger( OrmXmlParser.class );
private static final String ORM1_MAPPING_XSD = "org/hibernate/ejb/orm_1_0.xsd"; private static final String ORM1_MAPPING_XSD = "org/hibernate/ejb/orm_1_0.xsd";
private static final String ORM2_MAPPING_XSD = "org/hibernate/ejb/orm_2_0.xsd"; private static final String ORM2_MAPPING_XSD = "org/hibernate/ejb/orm_2_0.xsd";
@ -42,65 +32,25 @@ public class OrmXmlParser {
Set<InputStream> mappingStreams = new HashSet<InputStream>(); Set<InputStream> mappingStreams = new HashSet<InputStream>();
for ( String fileName : mappingFileNames ) { for ( String fileName : mappingFileNames ) {
Schema schema = getMappingSchema( ORM2_MAPPING_XSD );
InputStream in = getInputStreamForPath( fileName );
EntityMappings entityMappings; EntityMappings entityMappings;
try { try {
entityMappings = unmarshallXml( in, schema ); entityMappings = XmlHelper.unmarshallXml( fileName, ORM2_MAPPING_XSD, EntityMappings.class ).getRoot();
} }
catch ( JAXBException orm2Exception ) { catch ( JAXBException orm2Exception ) {
// if we cannot parse against orm_2_0.xsd we try orm_1_0.xsd for backwards compatibility // if we cannot parse against orm_2_0.xsd we try orm_1_0.xsd for backwards compatibility
try { try {
schema = getMappingSchema( ORM1_MAPPING_XSD ); entityMappings = XmlHelper.unmarshallXml( fileName, ORM1_MAPPING_XSD, EntityMappings.class ).getRoot();
in = getInputStreamForPath( fileName );
entityMappings = unmarshallXml( in, schema );
} }
catch ( JAXBException orm1Exception ) { catch ( JAXBException orm1Exception ) {
throw new AnnotationException( "Unable to parse xml configuration.", orm1Exception ); throw new AnnotationException( "Unable to parse xml configuration.", orm1Exception );
} }
} }
// .. entityMappings.toString();
} }
return null; return null;
} }
private InputStream getInputStreamForPath(String path) {
// try the context class loader first
InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream( path );
// try the current class loader
if ( inputStream == null ) {
inputStream = OrmXmlParser.class.getResourceAsStream( path );
}
return inputStream;
}
private EntityMappings unmarshallXml(InputStream in, Schema schema) throws JAXBException {
EntityMappings entityMappings;
JAXBContext jc = JAXBContext.newInstance( EntityMappings.class );
Unmarshaller unmarshaller = jc.createUnmarshaller();
unmarshaller.setSchema( schema );
StreamSource stream = new StreamSource( in );
JAXBElement<EntityMappings> root = unmarshaller.unmarshal( stream, EntityMappings.class );
entityMappings = root.getValue();
return entityMappings;
}
private Schema getMappingSchema(String schemaVersion) {
ClassLoader loader = OrmXmlParser.class.getClassLoader();
URL schemaUrl = loader.getResource( schemaVersion );
SchemaFactory sf = SchemaFactory.newInstance( javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI );
Schema schema = null;
try {
schema = sf.newSchema( schemaUrl );
}
catch ( SAXException e ) {
log.debug( "Unable to create schema for {}: {}", ORM2_MAPPING_XSD, e.getMessage() );
}
return schema;
}
} }

View File

@ -32,6 +32,8 @@ import java.util.Map;
import java.util.Set; import java.util.Set;
import org.dom4j.Element; import org.dom4j.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.hibernate.cfg.ExtendsQueueEntry; import org.hibernate.cfg.ExtendsQueueEntry;
import org.hibernate.internal.util.StringHelper; import org.hibernate.internal.util.StringHelper;
@ -39,6 +41,7 @@ import org.hibernate.internal.util.collections.JoinedIterator;
import org.hibernate.internal.util.xml.XmlDocument; import org.hibernate.internal.util.xml.XmlDocument;
import org.hibernate.mapping.MetaAttribute; import org.hibernate.mapping.MetaAttribute;
import org.hibernate.metamodel.source.Metadata; import org.hibernate.metamodel.source.Metadata;
import org.hibernate.metamodel.source.hbm.xml.mapping.HibernateMapping;
/** /**
* Binder for {@code hbm.xml} files * Binder for {@code hbm.xml} files
@ -46,6 +49,8 @@ import org.hibernate.metamodel.source.Metadata;
* @author Steve Ebersole * @author Steve Ebersole
*/ */
public class HibernateXmlBinder { public class HibernateXmlBinder {
private static final Logger log = LoggerFactory.getLogger( HibernateXmlBinder.class );
private final Metadata metadata; private final Metadata metadata;
private final Map<String, MetaAttribute> globalMetas; private final Map<String, MetaAttribute> globalMetas;
@ -62,6 +67,11 @@ public class HibernateXmlBinder {
bindRoot( metadataXml, Collections.<String>emptySet() ); bindRoot( metadataXml, Collections.<String>emptySet() );
} }
public void bindRoot(HibernateMapping mapping) {
// todo - process the mapping
log.debug( mapping.toString() );
}
public void bindRoot(XmlDocument metadataXml, Set<String> entityNames) { public void bindRoot(XmlDocument metadataXml, Set<String> entityNames) {
final HibernateMappingBinder mappingBinder = new HibernateMappingBinder( this, metadataXml ); final HibernateMappingBinder mappingBinder = new HibernateMappingBinder( this, metadataXml );
@ -69,7 +79,8 @@ public class HibernateXmlBinder {
if ( !names.isEmpty() ) { if ( !names.isEmpty() ) {
// classes mentioned in extends not available - so put it in queue // classes mentioned in extends not available - so put it in queue
for ( String name : names ) { for ( String name : names ) {
metadata.getExtendsQueue().add( new ExtendsQueueEntry( name, mappingBinder.getPackageName(), metadataXml, entityNames ) ); metadata.getExtendsQueue()
.add( new ExtendsQueueEntry( name, mappingBinder.getPackageName(), metadataXml, entityNames ) );
} }
return; return;
} }
@ -106,7 +117,11 @@ public class HibernateXmlBinder {
// mappings might contain either the "raw" extends name (in the case of // mappings might contain either the "raw" extends name (in the case of
// an entity-name mapping) or a FQN (in the case of a POJO mapping). // an entity-name mapping) or a FQN (in the case of a POJO mapping).
if ( getMetadata().getEntityBinding( extendsName ) == null if ( getMetadata().getEntityBinding( extendsName ) == null
&& getMetadata().getEntityBinding( HbmHelper.getClassName( extendsName, unqualifiedPackageName ) ) == null ) { && getMetadata().getEntityBinding(
HbmHelper.getClassName(
extendsName, unqualifiedPackageName
)
) == null ) {
awaitingExtends.add( extendsName ); awaitingExtends.add( extendsName );
} }
} }
@ -160,7 +175,7 @@ public class HibernateXmlBinder {
Element element = (Element) classIterator.next(); Element element = (Element) classIterator.next();
handler.handleEntity( handler.handleEntity(
element.attributeValue( "entity-name" ), element.attributeValue( "entity-name" ),
element.attributeValue( "name" ) element.attributeValue( "name" )
); );
recognizeEntities( element, handler ); recognizeEntities( element, handler );
} }

View File

@ -1,7 +1,7 @@
/* /*
* Hibernate, Relational Persistence for Idiomatic Java * Hibernate, Relational Persistence for Idiomatic Java
* *
* Copyright (c) 2010, Red Hat Inc. or third-party contributors as * Copyright (c) 2011, Red Hat Inc. or third-party contributors as
* indicated by the @author tags or express copyright attribution * indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are * statements applied by the authors. All third-party contributions are
* distributed under license by Red Hat Inc. * distributed under license by Red Hat Inc.
@ -27,11 +27,14 @@ import org.dom4j.Attribute;
import org.dom4j.Element; import org.dom4j.Element;
/** /**
* TODO : javadoc * Helper class for working with DOM documents.
* *
* @author Steve Ebersole * @author Steve Ebersole
*/ */
public class DomHelper { public class DomHelper {
private DomHelper() {
}
public static String extractAttributeValue(Element element, String attributeName) { public static String extractAttributeValue(Element element, String attributeName) {
return extractAttributeValue( element, attributeName, null ); return extractAttributeValue( element, attributeName, null );
} }

View File

@ -0,0 +1,45 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2011, Red Hat Inc. or third-party contributors as
* indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are
* distributed under license by Red Hat Inc.
*
* This copyrighted material is made available to anyone wishing to use, modify,
* copy, or redistribute it subject to the terms and conditions of the GNU
* Lesser General Public License, as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this distribution; if not, write to:
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
package org.hibernate.metamodel.source.util.xml;
/**
* Describes a parsed xml document.
*
* @author Hardy Ferentschik
*/
public interface JaxbRoot<T> {
/**
* Retrieve the jaxb root
*
* @return the jaxb root object
*/
public T getRoot();
/**
* Retrieve the document's origin.
*
* @return The origin
*/
public Origin getOrigin();
}

View File

@ -0,0 +1,53 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2011, Red Hat Inc. or third-party contributors as
* indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are
* distributed under license by Red Hat Inc.
*
* This copyrighted material is made available to anyone wishing to use, modify,
* copy, or redistribute it subject to the terms and conditions of the GNU
* Lesser General Public License, as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this distribution; if not, write to:
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
package org.hibernate.metamodel.source.util.xml;
/**
* Basic implementation of {@link JaxbRoot}.
*
* @author Hardy Ferentschik
*/
public class JaxbRootImpl<T> implements JaxbRoot<T> {
private final T root;
private final Origin origin;
public JaxbRootImpl(T root, Origin origin) {
this.root = root;
this.origin = origin;
}
/**
* {@inheritDoc}
*/
public T getRoot() {
return root;
}
/**
* {@inheritDoc}
*/
public Origin getOrigin() {
return origin;
}
}

View File

@ -0,0 +1,49 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2011, Red Hat Inc. or third-party contributors as
* indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are
* distributed under license by Red Hat Inc.
*
* This copyrighted material is made available to anyone wishing to use, modify,
* copy, or redistribute it subject to the terms and conditions of the GNU
* Lesser General Public License, as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this distribution; if not, write to:
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
package org.hibernate.metamodel.source.util.xml;
import java.io.Serializable;
/**
* Describes the origin of an xml document
*
* @author Steve Ebersole
*/
public interface Origin extends Serializable {
/**
* Retrieve the type of origin. This is not a discrete set, but might be somethign like
* {@code file} for file protocol URLs, or {@code resource} for classpath resource lookups.
*
* @return The origin type.
*/
public String getType();
/**
* The name of the document origin. Interpretation is relative to the type, but might be the
* resource name or file URL.
*
* @return The name.
*/
public String getName();
}

View File

@ -0,0 +1,53 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2011, Red Hat Inc. or third-party contributors as
* indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are
* distributed under license by Red Hat Inc.
*
* This copyrighted material is made available to anyone wishing to use, modify,
* copy, or redistribute it subject to the terms and conditions of the GNU
* Lesser General Public License, as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this distribution; if not, write to:
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
package org.hibernate.metamodel.source.util.xml;
/**
* Basic implementation of {@link org.hibernate.internal.util.xml.Origin}
*
* @author Steve Ebersole
*/
public class OriginImpl implements Origin {
private final String type;
private final String name;
public OriginImpl(String type, String name) {
this.type = type;
this.name = name;
}
/**
* {@inheritDoc}
*/
public String getType() {
return type;
}
/**
* {@inheritDoc}
*/
public String getName() {
return name;
}
}

View File

@ -0,0 +1,89 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2011, Red Hat Inc. or third-party contributors as
* indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are
* distributed under license by Red Hat Inc.
*
* This copyrighted material is made available to anyone wishing to use, modify,
* copy, or redistribute it subject to the terms and conditions of the GNU
* Lesser General Public License, as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this distribution; if not, write to:
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
package org.hibernate.metamodel.source.util.xml;
import java.io.InputStream;
import java.net.URL;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xml.sax.SAXException;
/**
* @author Hardy Ferentschik
*/
public class XmlHelper {
private static final Logger log = LoggerFactory.getLogger( XmlHelper.class );
private XmlHelper() {
}
public static <T> JaxbRoot<T> unmarshallXml(String fileName, String schemaName, Class<T> clazz)
throws JAXBException {
Schema schema = getMappingSchema( schemaName );
InputStream in = getInputStreamForPath( fileName );
JAXBContext jc = JAXBContext.newInstance( clazz );
Unmarshaller unmarshaller = jc.createUnmarshaller();
unmarshaller.setSchema( schema );
StreamSource stream = new StreamSource( in );
JAXBElement<T> elem = unmarshaller.unmarshal( stream, clazz );
Origin origin = new OriginImpl( "", fileName );
return new JaxbRootImpl<T>( elem.getValue(), origin );
}
private static Schema getMappingSchema(String schemaVersion) {
// todo - think about class loading. does this have to go via the class loader service?
ClassLoader loader = XmlHelper.class.getClassLoader();
URL schemaUrl = loader.getResource( schemaVersion );
SchemaFactory sf = SchemaFactory.newInstance( javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI );
Schema schema = null;
try {
schema = sf.newSchema( schemaUrl );
}
catch ( SAXException e ) {
log.debug( "Unable to create schema for {}: {}", schemaVersion, e.getMessage() );
}
return schema;
}
private static InputStream getInputStreamForPath(String path) {
// try the context class loader first
InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream( path );
// try the current class loader
if ( inputStream == null ) {
inputStream = XmlHelper.class.getResourceAsStream( path );
}
return inputStream;
}
}

View File

@ -23,6 +23,10 @@
*/ */
package org.hibernate.metamodel.binding; package org.hibernate.metamodel.binding;
import javax.xml.bind.JAXBException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xml.sax.InputSource; import org.xml.sax.InputSource;
import org.hibernate.internal.util.ConfigHelper; import org.hibernate.internal.util.ConfigHelper;
@ -31,6 +35,10 @@ import org.hibernate.internal.util.xml.Origin;
import org.hibernate.internal.util.xml.XMLHelper; import org.hibernate.internal.util.xml.XMLHelper;
import org.hibernate.internal.util.xml.XmlDocument; import org.hibernate.internal.util.xml.XmlDocument;
import org.hibernate.metamodel.source.Metadata; import org.hibernate.metamodel.source.Metadata;
import org.hibernate.metamodel.source.hbm.xml.mapping.HibernateMapping;
import org.hibernate.metamodel.source.util.xml.XmlHelper;
import static org.junit.Assert.fail;
/** /**
* Basic tests of {@code hbm.xml} binding code * Basic tests of {@code hbm.xml} binding code
@ -38,6 +46,7 @@ import org.hibernate.metamodel.source.Metadata;
* @author Steve Ebersole * @author Steve Ebersole
*/ */
public class BasicHbmBindingTests extends AbstractBasicBindingTests { public class BasicHbmBindingTests extends AbstractBasicBindingTests {
private static final Logger log = LoggerFactory.getLogger( BasicHbmBindingTests.class );
public EntityBinding buildSimpleEntityBinding() { public EntityBinding buildSimpleEntityBinding() {
Metadata metadata = new Metadata(); Metadata metadata = new Metadata();
@ -50,8 +59,23 @@ public class BasicHbmBindingTests extends AbstractBasicBindingTests {
public EntityBinding buildSimpleVersionedEntityBinding() { public EntityBinding buildSimpleVersionedEntityBinding() {
Metadata metadata = new Metadata(); Metadata metadata = new Metadata();
XmlDocument xmlDocument = readResource( "/org/hibernate/metamodel/binding/SimpleVersionedEntity.hbm.xml" ); String fileName = "/org/hibernate/metamodel/binding/SimpleVersionedEntity.hbm.xml";
XmlDocument xmlDocument = readResource( fileName );
metadata.getHibernateXmlBinder().bindRoot( xmlDocument ); metadata.getHibernateXmlBinder().bindRoot( xmlDocument );
// todo - just temporary to show how things would look like with JAXB
fileName = "/org/hibernate/metamodel/binding/SimpleVersionedEntity.xml";
final String HIBERNATE_MAPPING_XSD = "org/hibernate/hibernate-mapping-3.0.xsd";
HibernateMapping mapping = null;
try {
mapping = XmlHelper.unmarshallXml( fileName, HIBERNATE_MAPPING_XSD, HibernateMapping.class ).getRoot();
}
catch ( JAXBException e ) {
log.debug( e.getMessage() );
fail( "Unable to load xml " + fileName );
}
metadata.getHibernateXmlBinder().bindRoot( mapping );
return metadata.getEntityBinding( SimpleVersionedEntity.class.getName() ); return metadata.getEntityBinding( SimpleVersionedEntity.class.getName() );
} }

View File

@ -0,0 +1,38 @@
<?xml version="1.0"?>
<!--
~ Hibernate, Relational Persistence for Idiomatic Java
~
~ Copyright (c) 2010, Red Hat Inc. or third-party contributors as
~ indicated by the @author tags or express copyright attribution
~ statements applied by the authors. All third-party contributions are
~ distributed under license by Red Hat Inc.
~
~ This copyrighted material is made available to anyone wishing to use, modify,
~ copy, or redistribute it subject to the terms and conditions of the GNU
~ Lesser General Public License, as published by the Free Software Foundation.
~
~ This program is distributed in the hope that it will be useful,
~ but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
~ or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
~ for more details.
~
~ You should have received a copy of the GNU Lesser General Public License
~ along with this distribution; if not, write to:
~ Free Software Foundation, Inc.
~ 51 Franklin Street, Fifth Floor
~ Boston, MA 02110-1301 USA
-->
<hibernate-mapping package="org.hibernate.metamodel.binding" xmlns="http://www.hibernate.org/xsd/hibernate-mapping"
xsi:schemaLocation="http://www.hibernate.org/xsd/hibernate-mapping hibernate-mapping-3.0.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<class name="SimpleVersionedEntity">
<id name="id">
<generator class="increment"/>
</id>
<version name="version"/>
<property name="name"/>
</class>
</hibernate-mapping>

View File

@ -75,7 +75,6 @@ public class ConfiguredClassHierarchyBuilderTest extends BaseUnitTestCase {
assertEquals( "wrong class", DotName.createSimple( MappedSuperClass.class.getName() ), info.name() ); assertEquals( "wrong class", DotName.createSimple( MappedSuperClass.class.getName() ), info.name() );
info = iter.next().getClassInfo(); info = iter.next().getClassInfo();
assertEquals( "wrong class", DotName.createSimple( UnmappedSubClass.class.getName() ), info.name() ); assertEquals( "wrong class", DotName.createSimple( UnmappedSubClass.class.getName() ), info.name() );
assertFalse( iter.hasNext() );
info = iter.next().getClassInfo(); info = iter.next().getClassInfo();
assertEquals( "wrong class", DotName.createSimple( MappedSubClass.class.getName() ), info.name() ); assertEquals( "wrong class", DotName.createSimple( MappedSubClass.class.getName() ), info.name() );
assertFalse( iter.hasNext() ); assertFalse( iter.hasNext() );