Search in sources :

Example 6 with ServiceRegistry

use of org.hibernate.service.ServiceRegistry in project hibernate-orm by hibernate.

the class AuditReaderFactory method get.

/**
	 * Create an audit reader associated with an open session.
	 *
	 * @param session An open session.
	 *
	 * @return An audit reader associated with the given sesison. It shouldn't be used
	 *         afterQuery the session is closed.
	 *
	 * @throws AuditException When the given required listeners aren't installed.
	 */
public static AuditReader get(Session session) throws AuditException {
    SessionImplementor sessionImpl;
    if (!(session instanceof SessionImplementor)) {
        sessionImpl = (SessionImplementor) session.getSessionFactory().getCurrentSession();
    } else {
        sessionImpl = (SessionImplementor) session;
    }
    final ServiceRegistry serviceRegistry = sessionImpl.getFactory().getServiceRegistry();
    final EnversService enversService = serviceRegistry.getService(EnversService.class);
    return new AuditReaderImpl(enversService, session, sessionImpl);
}
Also used : AuditReaderImpl(org.hibernate.envers.internal.reader.AuditReaderImpl) SessionImplementor(org.hibernate.engine.spi.SessionImplementor) EnversService(org.hibernate.envers.boot.internal.EnversService) ServiceRegistry(org.hibernate.service.ServiceRegistry)

Example 7 with ServiceRegistry

use of org.hibernate.service.ServiceRegistry in project hibernate-orm by hibernate.

the class AdditionalJaxbMappingProducerImpl method produceAdditionalMappings.

@Override
public Collection<MappingDocument> produceAdditionalMappings(final MetadataImplementor metadata, IndexView jandexIndex, final MappingBinder mappingBinder, final MetadataBuildingContext buildingContext) {
    final ServiceRegistry serviceRegistry = metadata.getMetadataBuildingOptions().getServiceRegistry();
    final EnversService enversService = serviceRegistry.getService(EnversService.class);
    if (!enversService.isEnabled()) {
        // short-circuit if envers integration has been disabled.
        return Collections.emptyList();
    }
    final ArrayList<MappingDocument> additionalMappingDocuments = new ArrayList<>();
    // atm we do not have distinct origin info for envers
    final Origin origin = new Origin(SourceType.OTHER, "envers");
    //		final DOMWriter writer = new DOMWriter();
    final MappingCollector mappingCollector = new MappingCollector() {

        @Override
        public void addDocument(Document document) throws DocumentException {
            dump(document);
            // while the commented-out code here is more efficient (well, understanding that
            // this whole process is un-efficient)  it leads to un-decipherable messages when
            // we get mapping mapping errors from envers output.
            //				final DOMSource domSource = new DOMSource( writer.write( document ) );
            //				domSource.setSystemId( "envers" );
            //				final Binding jaxbBinding = mappingBinder.bind( domSource, origin );
            // this form at least allows us to get better error messages
            final ByteArrayOutputStream baos = new ByteArrayOutputStream();
            try {
                final Writer w = new BufferedWriter(new OutputStreamWriter(baos, "UTF-8"));
                final XMLWriter xw = new XMLWriter(w, new OutputFormat(" ", true));
                xw.write(document);
                w.flush();
            } catch (IOException e) {
                throw new HibernateException("Unable to bind Envers-generated XML", e);
            }
            ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
            BufferedInputStream bis = new BufferedInputStream(bais);
            final Binding jaxbBinding = mappingBinder.bind(bis, origin);
            final JaxbHbmHibernateMapping jaxbRoot = (JaxbHbmHibernateMapping) jaxbBinding.getRoot();
            additionalMappingDocuments.add(new MappingDocument(jaxbRoot, origin, buildingContext));
        }
    };
    enversService.initialize(metadata, mappingCollector);
    return additionalMappingDocuments;
}
Also used : Origin(org.hibernate.boot.jaxb.Origin) Binding(org.hibernate.boot.jaxb.spi.Binding) HibernateException(org.hibernate.HibernateException) MappingDocument(org.hibernate.boot.model.source.internal.hbm.MappingDocument) ArrayList(java.util.ArrayList) OutputFormat(org.dom4j.io.OutputFormat) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) Document(org.dom4j.Document) MappingDocument(org.hibernate.boot.model.source.internal.hbm.MappingDocument) XMLWriter(org.dom4j.io.XMLWriter) BufferedWriter(java.io.BufferedWriter) ByteArrayInputStream(java.io.ByteArrayInputStream) BufferedInputStream(java.io.BufferedInputStream) OutputStreamWriter(java.io.OutputStreamWriter) ServiceRegistry(org.hibernate.service.ServiceRegistry) MappingCollector(org.hibernate.envers.configuration.internal.MappingCollector) XMLWriter(org.dom4j.io.XMLWriter) OutputStreamWriter(java.io.OutputStreamWriter) PrintWriter(java.io.PrintWriter) BufferedWriter(java.io.BufferedWriter) Writer(java.io.Writer) JaxbHbmHibernateMapping(org.hibernate.boot.jaxb.hbm.spi.JaxbHbmHibernateMapping)

Example 8 with ServiceRegistry

use of org.hibernate.service.ServiceRegistry in project querydsl by querydsl.

the class HibernateTestRunner method start.

private void start() throws Exception {
    Configuration cfg = new Configuration();
    for (Class<?> cl : Domain.classes) {
        cfg.addAnnotatedClass(cl);
    }
    String mode = Mode.mode.get() + ".properties";
    isDerby = mode.contains("derby");
    if (isDerby) {
        Class.forName("org.apache.derby.jdbc.EmbeddedDriver").newInstance();
    }
    Properties props = new Properties();
    InputStream is = HibernateTestRunner.class.getResourceAsStream(mode);
    if (is == null) {
        throw new IllegalArgumentException("No configuration available at classpath:" + mode);
    }
    props.load(is);
    ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(props).build();
    cfg.setProperties(props);
    sessionFactory = cfg.buildSessionFactory(serviceRegistry);
    session = sessionFactory.openSession();
    session.beginTransaction();
}
Also used : Configuration(org.hibernate.cfg.Configuration) StandardServiceRegistryBuilder(org.hibernate.boot.registry.StandardServiceRegistryBuilder) InputStream(java.io.InputStream) ServiceRegistry(org.hibernate.service.ServiceRegistry) Properties(java.util.Properties)

Example 9 with ServiceRegistry

use of org.hibernate.service.ServiceRegistry in project hibernate-orm by hibernate.

the class BootstrapTest method test_basic_custom_type_register_UserType_example.

@Test
public void test_basic_custom_type_register_UserType_example() {
    try {
        //tag::basic-custom-type-register-UserType-example[]
        ServiceRegistry standardRegistry = new StandardServiceRegistryBuilder().build();
        MetadataSources sources = new MetadataSources(standardRegistry);
        MetadataBuilder metadataBuilder = sources.getMetadataBuilder();
        metadataBuilder.applyBasicType(BitSetUserType.INSTANCE, "bitset");
    //end::basic-custom-type-register-UserType-example[]
    } catch (Exception ignore) {
    }
}
Also used : StandardServiceRegistryBuilder(org.hibernate.boot.registry.StandardServiceRegistryBuilder) MetadataBuilder(org.hibernate.boot.MetadataBuilder) MetadataSources(org.hibernate.boot.MetadataSources) SessionFactoryServiceRegistry(org.hibernate.service.spi.SessionFactoryServiceRegistry) StandardServiceRegistry(org.hibernate.boot.registry.StandardServiceRegistry) BootstrapServiceRegistry(org.hibernate.boot.registry.BootstrapServiceRegistry) ServiceRegistry(org.hibernate.service.ServiceRegistry) Test(org.junit.Test)

Example 10 with ServiceRegistry

use of org.hibernate.service.ServiceRegistry in project hibernate-orm by hibernate.

the class ScanningCoordinator method applyScanResultsToManagedResources.

public void applyScanResultsToManagedResources(ManagedResourcesImpl managedResources, ScanResult scanResult, MetadataBuildingOptions options, XmlMappingBinderAccess xmlMappingBinderAccess) {
    final ScanEnvironment scanEnvironment = options.getScanEnvironment();
    final ServiceRegistry serviceRegistry = options.getServiceRegistry();
    final ClassLoaderService classLoaderService = serviceRegistry.getService(ClassLoaderService.class);
    // mapping files ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    final Set<String> nonLocatedMappingFileNames = new HashSet<String>();
    final List<String> explicitMappingFileNames = scanEnvironment.getExplicitlyListedMappingFiles();
    if (explicitMappingFileNames != null) {
        nonLocatedMappingFileNames.addAll(explicitMappingFileNames);
    }
    for (MappingFileDescriptor mappingFileDescriptor : scanResult.getLocatedMappingFiles()) {
        managedResources.addXmlBinding(xmlMappingBinderAccess.bind(mappingFileDescriptor.getStreamAccess()));
        nonLocatedMappingFileNames.remove(mappingFileDescriptor.getName());
    }
    for (String name : nonLocatedMappingFileNames) {
        final URL url = classLoaderService.locateResource(name);
        if (url == null) {
            throw new MappingException("Unable to resolve explicitly named mapping-file : " + name, new Origin(SourceType.RESOURCE, name));
        }
        final UrlInputStreamAccess inputStreamAccess = new UrlInputStreamAccess(url);
        managedResources.addXmlBinding(xmlMappingBinderAccess.bind(inputStreamAccess));
    }
    // classes and packages ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    final List<String> unresolvedListedClassNames = scanEnvironment.getExplicitlyListedClassNames() == null ? new ArrayList<String>() : new ArrayList<String>(scanEnvironment.getExplicitlyListedClassNames());
    for (ClassDescriptor classDescriptor : scanResult.getLocatedClasses()) {
        if (classDescriptor.getCategorization() == ClassDescriptor.Categorization.CONVERTER) {
            // converter classes are safe to load because we never enhance them,
            // and notice we use the ClassLoaderService specifically, not the temp ClassLoader (if any)
            managedResources.addAttributeConverterDefinition(AttributeConverterDefinition.from(classLoaderService.<AttributeConverter>classForName(classDescriptor.getName())));
        } else if (classDescriptor.getCategorization() == ClassDescriptor.Categorization.MODEL) {
            managedResources.addAnnotatedClassName(classDescriptor.getName());
        }
        unresolvedListedClassNames.remove(classDescriptor.getName());
    }
    // IMPL NOTE : "explicitlyListedClassNames" can contain class or package names...
    for (PackageDescriptor packageDescriptor : scanResult.getLocatedPackages()) {
        managedResources.addAnnotatedPackageName(packageDescriptor.getName());
        unresolvedListedClassNames.remove(packageDescriptor.getName());
    }
    for (String unresolvedListedClassName : unresolvedListedClassNames) {
        // because the explicit list can contain either class names or package names
        // we need to check for both here...
        // First, try it as a class name
        final String classFileName = unresolvedListedClassName.replace('.', '/') + ".class";
        final URL classFileUrl = classLoaderService.locateResource(classFileName);
        if (classFileUrl != null) {
            managedResources.addAnnotatedClassName(unresolvedListedClassName);
            continue;
        }
        // Then, try it as a package name
        final String packageInfoFileName = unresolvedListedClassName.replace('.', '/') + "/package-info.class";
        final URL packageInfoFileUrl = classLoaderService.locateResource(packageInfoFileName);
        if (packageInfoFileUrl != null) {
            managedResources.addAnnotatedPackageName(unresolvedListedClassName);
            continue;
        }
        log.debugf("Unable to resolve class [%s] named in persistence unit [%s]", unresolvedListedClassName, scanEnvironment.getRootUrl());
    }
}
Also used : Origin(org.hibernate.boot.jaxb.Origin) MappingFileDescriptor(org.hibernate.boot.archive.scan.spi.MappingFileDescriptor) ClassDescriptor(org.hibernate.boot.archive.scan.spi.ClassDescriptor) UrlInputStreamAccess(org.hibernate.boot.archive.internal.UrlInputStreamAccess) PackageDescriptor(org.hibernate.boot.archive.scan.spi.PackageDescriptor) URL(java.net.URL) MappingException(org.hibernate.boot.MappingException) AttributeConverter(javax.persistence.AttributeConverter) ScanEnvironment(org.hibernate.boot.archive.scan.spi.ScanEnvironment) ServiceRegistry(org.hibernate.service.ServiceRegistry) ClassLoaderService(org.hibernate.boot.registry.classloading.spi.ClassLoaderService) HashSet(java.util.HashSet)

Aggregations

ServiceRegistry (org.hibernate.service.ServiceRegistry)48 Test (org.junit.Test)27 MetadataSources (org.hibernate.boot.MetadataSources)18 BootstrapServiceRegistry (org.hibernate.boot.registry.BootstrapServiceRegistry)17 Configuration (org.hibernate.cfg.Configuration)14 StandardServiceRegistryBuilder (org.hibernate.boot.registry.StandardServiceRegistryBuilder)11 AnnotationException (org.hibernate.AnnotationException)6 MappingException (org.hibernate.MappingException)6 SessionFactory (org.hibernate.SessionFactory)6 Metadata (org.hibernate.boot.Metadata)6 TestForIssue (org.hibernate.testing.TestForIssue)5 Map (java.util.Map)4 StandardServiceRegistry (org.hibernate.boot.registry.StandardServiceRegistry)4 HibernateException (org.hibernate.HibernateException)3 ClassLoaderService (org.hibernate.boot.registry.classloading.spi.ClassLoaderService)3 ConfigurationService (org.hibernate.engine.config.spi.ConfigurationService)3 JdbcEnvironment (org.hibernate.engine.jdbc.env.spi.JdbcEnvironment)3 ByteArrayInputStream (java.io.ByteArrayInputStream)2 ByteArrayOutputStream (java.io.ByteArrayOutputStream)2 File (java.io.File)2