Example usage for javax.persistence.spi PersistenceUnitInfo getProperties

List of usage examples for javax.persistence.spi PersistenceUnitInfo getProperties

Introduction

In this page you can find the example usage for javax.persistence.spi PersistenceUnitInfo getProperties.

Prototype

public Properties getProperties();

Source Link

Document

Returns a properties object.

Usage

From source file:com.brienwheeler.apps.schematool.SchemaToolBean.java

private Configuration determineHibernateConfiguration()
        throws MappingException, ClassNotFoundException, IOException {
    // Read in the bean definitions but don't go creating all the singletons,
    // because that causes creation of data sources and connections to database, etc.
    NonInitializingClassPathXmlApplicationContext context = new NonInitializingClassPathXmlApplicationContext(
            new String[] { emfContextLocation });
    try {/* ww  w .  j  a va 2  s .com*/
        context.loadBeanDefinitions();

        // Get well-known EntityManagerFactory bean definition by name
        BeanDefinition emfBeanDef = context.getBeanDefinition(emfContextBeanName);
        if (emfBeanDef == null) {
            throw new RuntimeException("no bean defined: " + emfContextBeanName);
        }

        // Get the name of the persistence unit for this EntityManagerFactory
        PropertyValue puNameProperty = emfBeanDef.getPropertyValues().getPropertyValue("persistenceUnitName");
        if (puNameProperty == null || !(puNameProperty.getValue() instanceof TypedStringValue)) {
            throw new RuntimeException(
                    "no property 'persistenceUnitName' defined on bean: " + emfContextBeanName);
        }
        String puName = ((TypedStringValue) puNameProperty.getValue()).getValue();

        // Get the name of the persistence unit for this EntityManagerFactory
        PropertyValue pumProperty = emfBeanDef.getPropertyValues().getPropertyValue("persistenceUnitManager");
        PersistenceUnitManager pum = null;
        if (pumProperty != null) {
            pum = createConfiguredPum(context, pumProperty);
        } else {
            pum = simulateDefaultPum(context, emfBeanDef);
        }

        // create the Hibernate configuration
        PersistenceUnitInfo pui = pum.obtainPersistenceUnitInfo(puName);
        Configuration configuration = new Configuration();
        configuration.setProperties(pui.getProperties());
        for (String className : pui.getManagedClassNames()) {
            configuration.addAnnotatedClass(Class.forName(className));
        }

        return configuration;
    } finally {
        context.close();
    }
}

From source file:org.compass.gps.device.jpa.embedded.eclipselink.CompassSessionCustomizer.java

public void customize(Session session) throws Exception {
    if (log.isInfoEnabled()) {
        log.info("Compass embedded EclipseLink support enabled, initializing for session [" + session + "]");
    }/*from  w  w  w .j a v a 2  s  .co m*/
    PersistenceUnitInfo persistenceUnitInfo = findPersistenceUnitInfo(session);
    if (persistenceUnitInfo == null) {
        throw new CompassException("Failed to find Persistence Unit Info");
    }

    Map<Object, Object> eclipselinkProps = new HashMap();
    eclipselinkProps.putAll(persistenceUnitInfo.getProperties());
    eclipselinkProps.putAll(session.getProperties());

    String sessionCustomizer = (String) eclipselinkProps.get(COMPASS_SESSION_CUSTOMIZER);
    if (sessionCustomizer != null) {
        ((SessionCustomizer) ClassUtils.forName(sessionCustomizer, persistenceUnitInfo.getClassLoader())
                .newInstance()).customize(session);
    }

    Properties compassProperties = new Properties();
    //noinspection unchecked
    for (Map.Entry entry : eclipselinkProps.entrySet()) {
        if (!(entry.getKey() instanceof String)) {
            continue;
        }
        String key = (String) entry.getKey();
        if (key.startsWith(COMPASS_PREFIX)) {
            compassProperties.put(entry.getKey(), entry.getValue());
        }
        if (key.startsWith(COMPASS_GPS_INDEX_PREFIX)) {
            compassProperties.put(entry.getKey(), entry.getValue());
        }
    }
    if (compassProperties.isEmpty()) {
        if (log.isDebugEnabled()) {
            log.debug("No Compass properties found in configuraiton, disabling Compass");
        }
        return;
    }
    if (compassProperties.getProperty(CompassEnvironment.CONNECTION) == null) {
        if (log.isDebugEnabled()) {
            log.debug("No Compass [" + CompassEnvironment.CONNECTION + "] property defined, disabling Compass");
        }
        return;
    }

    CompassConfiguration compassConfiguration = CompassConfigurationFactory.newConfiguration();
    // use the same class loader of the persistence info to load Compass classes
    compassConfiguration.setClassLoader(persistenceUnitInfo.getClassLoader());
    CompassSettings settings = compassConfiguration.getSettings();
    settings.addSettings(compassProperties);

    String configLocation = (String) compassProperties.get(COMPASS_CONFIG_LOCATION);
    if (configLocation != null) {
        compassConfiguration.configure(configLocation);
    }

    Map descriptors = session.getDescriptors();
    for (Object o : descriptors.values()) {
        ClassDescriptor classDescriptor = (ClassDescriptor) o;
        Class mappedClass = classDescriptor.getJavaClass();
        compassConfiguration.tryAddClass(mappedClass);
    }

    // create some default settings

    String transactionFactory = (String) compassProperties.get(CompassEnvironment.Transaction.FACTORY);
    boolean eclipselinkControlledTransaction;
    if (transactionFactory == null) {
        if (persistenceUnitInfo.getTransactionType() == PersistenceUnitTransactionType.JTA) {
            transactionFactory = JTASyncTransactionFactory.class.getName();
            eclipselinkControlledTransaction = false;
        } else {
            transactionFactory = LocalTransactionFactory.class.getName();
            eclipselinkControlledTransaction = true;
        }
        settings.setSetting(CompassEnvironment.Transaction.FACTORY, transactionFactory);
    } else {
        // JPA is not controlling the transaction (using JTA Sync or XA), don't commit/rollback
        // with EclipseLink transaction listeners
        eclipselinkControlledTransaction = false;
    }

    // if the settings is configured to use local transaciton, disable thread bound setting since
    // we are using EclipseLink to managed transaction scope (using user objects on the em) and not thread locals
    // will only be taken into account when using local transactions
    if (settings.getSetting(CompassEnvironment.Transaction.DISABLE_THREAD_BOUND_LOCAL_TRANSATION) == null) {
        // if no emf is defined
        settings.setBooleanSetting(CompassEnvironment.Transaction.DISABLE_THREAD_BOUND_LOCAL_TRANSATION, true);
    }

    Compass compass = compassConfiguration.buildCompass();

    boolean commitBeforeCompletion = settings
            .getSettingAsBoolean(CompassEnvironment.Transaction.COMMIT_BEFORE_COMPLETION, false);

    // extract index properties so they will be used
    Properties indexProps = new Properties();
    for (Map.Entry entry : compassProperties.entrySet()) {
        String key = (String) entry.getKey();
        if (key.startsWith(COMPASS_GPS_INDEX_PREFIX)) {
            indexProps.put(key.substring(COMPASS_GPS_INDEX_PREFIX.length()), entry.getValue());
        }
    }

    // start an internal JPA device and Gps for mirroring
    EntityManagerFactory emf = new EntityManagerFactoryImpl((ServerSession) session);

    JpaGpsDevice jpaGpsDevice = new JpaGpsDevice(DefaultJpaCompassGps.JPA_DEVICE_NAME, emf);
    jpaGpsDevice.setMirrorDataChanges(true);
    jpaGpsDevice.setInjectEntityLifecycleListener(true);
    for (Map.Entry entry : compassProperties.entrySet()) {
        String key = (String) entry.getKey();
        if (key.startsWith(INDEX_QUERY_PREFIX)) {
            String entityName = key.substring(INDEX_QUERY_PREFIX.length());
            String selectQuery = (String) entry.getValue();
            jpaGpsDevice.setIndexSelectQuery(entityName, selectQuery);
        }
    }

    EclipseLinkJpaEntityLifecycleInjector lifecycleInjector = new EclipseLinkJpaEntityLifecycleInjector();
    lifecycleInjector.setEventListener(new EclipseLinkEventListener(jpaGpsDevice));
    jpaGpsDevice.setLifecycleInjector(lifecycleInjector);

    // set explicitly the EntityManagerWrapper since EclipseLink rollback the transaction on EntityManager#getTransaction
    // which makes it useless when using DefaultEntityManagerWrapper
    if (persistenceUnitInfo.getTransactionType() == PersistenceUnitTransactionType.JTA) {
        jpaGpsDevice.setEntityManagerWrapper(new JtaEntityManagerWrapper());
    } else {
        jpaGpsDevice.setEntityManagerWrapper(new ResourceLocalEntityManagerWrapper());
    }

    DefaultJpaCompassGps jpaCompassGps = new DefaultJpaCompassGps();
    jpaCompassGps.setCompass(compass);
    jpaCompassGps.addGpsDevice(jpaGpsDevice);

    // before we start the Gps, open and close a broker
    emf.createEntityManager().close();

    jpaCompassGps.start();

    session.getEventManager().addListener(new CompassSessionEventListener(compass, jpaCompassGps,
            commitBeforeCompletion, eclipselinkControlledTransaction, indexProps));

    if (log.isDebugEnabled()) {
        log.debug("Compass embedded EclipseLink support active");
    }
}

From source file:org.compass.gps.device.jpa.embedded.toplink.CompassSessionCustomizer.java

public void customize(Session session) throws Exception {
    if (log.isInfoEnabled()) {
        log.info("Compass embedded TopLink Essentials support enabled, initializing for session [" + session
                + "]");
    }/* w  w  w.  j av  a 2  s . c  o  m*/
    PersistenceUnitInfo persistenceUnitInfo = findPersistenceUnitInfo(session);
    if (persistenceUnitInfo == null) {
        throw new CompassException("Failed to find Persistence Unit Info");
    }

    Map<Object, Object> toplinkProps = new HashMap();
    toplinkProps.putAll(persistenceUnitInfo.getProperties());
    toplinkProps.putAll(session.getProperties());

    String sessionCustomizer = (String) toplinkProps.get(COMPASS_SESSION_CUSTOMIZER);
    if (sessionCustomizer != null) {
        ((SessionCustomizer) ClassUtils.forName(sessionCustomizer, persistenceUnitInfo.getClassLoader())
                .newInstance()).customize(session);
    }

    Properties compassProperties = new Properties();
    //noinspection unchecked
    for (Map.Entry entry : toplinkProps.entrySet()) {
        if (!(entry.getKey() instanceof String)) {
            continue;
        }
        String key = (String) entry.getKey();
        if (key.startsWith(COMPASS_PREFIX)) {
            compassProperties.put(entry.getKey(), entry.getValue());
        }
        if (key.startsWith(COMPASS_GPS_INDEX_PREFIX)) {
            compassProperties.put(entry.getKey(), entry.getValue());
        }
    }
    if (compassProperties.isEmpty()) {
        if (log.isDebugEnabled()) {
            log.debug("No Compass properties found in configuraiton, disabling Compass");
        }
        return;
    }
    if (compassProperties.getProperty(CompassEnvironment.CONNECTION) == null) {
        if (log.isDebugEnabled()) {
            log.debug("No Compass [" + CompassEnvironment.CONNECTION + "] property defined, disabling Compass");
        }
        return;
    }

    CompassConfiguration compassConfiguration = CompassConfigurationFactory.newConfiguration();
    // use the same class loader of the persistence info to load Compass classes
    compassConfiguration.setClassLoader(persistenceUnitInfo.getClassLoader());
    CompassSettings settings = compassConfiguration.getSettings();
    settings.addSettings(compassProperties);

    String configLocation = (String) compassProperties.get(COMPASS_CONFIG_LOCATION);
    if (configLocation != null) {
        compassConfiguration.configure(configLocation);
    }

    Map descriptors = session.getDescriptors();
    for (Object o : descriptors.values()) {
        ClassDescriptor classDescriptor = (ClassDescriptor) o;
        Class mappedClass = classDescriptor.getJavaClass();
        compassConfiguration.tryAddClass(mappedClass);
    }

    // create some default settings

    String transactionFactory = (String) compassProperties.get(CompassEnvironment.Transaction.FACTORY);
    boolean toplinkControlledTransaction;
    if (transactionFactory == null) {
        if (persistenceUnitInfo.getTransactionType() == PersistenceUnitTransactionType.JTA) {
            transactionFactory = JTASyncTransactionFactory.class.getName();
            toplinkControlledTransaction = false;
        } else {
            transactionFactory = LocalTransactionFactory.class.getName();
            toplinkControlledTransaction = true;
        }
        settings.setSetting(CompassEnvironment.Transaction.FACTORY, transactionFactory);
    } else {
        // JPA is not controlling the transaction (using JTA Sync or XA), don't commit/rollback
        // with Toplink transaction listeners
        toplinkControlledTransaction = false;
    }

    // if the settings is configured to use local transaciton, disable thread bound setting since
    // we are using Toplink to managed transaction scope (using user objects on the em) and not thread locals
    // will only be taken into account when using local transactions
    if (settings.getSetting(CompassEnvironment.Transaction.DISABLE_THREAD_BOUND_LOCAL_TRANSATION) == null) {
        // if no emf is defined
        settings.setBooleanSetting(CompassEnvironment.Transaction.DISABLE_THREAD_BOUND_LOCAL_TRANSATION, true);
    }

    Compass compass = compassConfiguration.buildCompass();

    boolean commitBeforeCompletion = settings
            .getSettingAsBoolean(CompassEnvironment.Transaction.COMMIT_BEFORE_COMPLETION, false);

    // extract index properties so they will be used
    Properties indexProps = new Properties();
    for (Map.Entry entry : compassProperties.entrySet()) {
        String key = (String) entry.getKey();
        if (key.startsWith(COMPASS_GPS_INDEX_PREFIX)) {
            indexProps.put(key.substring(COMPASS_GPS_INDEX_PREFIX.length()), entry.getValue());
        }
    }

    // start an internal JPA device and Gps for mirroring
    EntityManagerFactory emf = new EntityManagerFactoryImpl((ServerSession) session);

    JpaGpsDevice jpaGpsDevice = new JpaGpsDevice(DefaultJpaCompassGps.JPA_DEVICE_NAME, emf);
    jpaGpsDevice.setMirrorDataChanges(true);
    jpaGpsDevice.setInjectEntityLifecycleListener(true);
    for (Map.Entry entry : compassProperties.entrySet()) {
        String key = (String) entry.getKey();
        if (key.startsWith(INDEX_QUERY_PREFIX)) {
            String entityName = key.substring(INDEX_QUERY_PREFIX.length());
            String selectQuery = (String) entry.getValue();
            jpaGpsDevice.setIndexSelectQuery(entityName, selectQuery);
        }
    }

    TopLinkEssentialsJpaEntityLifecycleInjector lifecycleInjector = new TopLinkEssentialsJpaEntityLifecycleInjector();
    lifecycleInjector.setEventListener(new EmbeddedToplinkEventListener(jpaGpsDevice));
    jpaGpsDevice.setLifecycleInjector(lifecycleInjector);

    // set explicitly the EntityManagerWrapper since Toplink rollback the transaction on EntityManager#getTransaction
    // which makes it useless when using DefaultEntityManagerWrapper
    if (persistenceUnitInfo.getTransactionType() == PersistenceUnitTransactionType.JTA) {
        jpaGpsDevice.setEntityManagerWrapper(new JtaEntityManagerWrapper());
    } else {
        jpaGpsDevice.setEntityManagerWrapper(new ResourceLocalEntityManagerWrapper());
    }

    DefaultJpaCompassGps jpaCompassGps = new DefaultJpaCompassGps();
    jpaCompassGps.setCompass(compass);
    jpaCompassGps.addGpsDevice(jpaGpsDevice);

    // before we start the Gps, open and close a broker
    emf.createEntityManager().close();

    jpaCompassGps.start();

    session.getEventManager().addListener(new CompassSessionEventListener(compass, jpaCompassGps,
            commitBeforeCompletion, toplinkControlledTransaction, indexProps));

    if (log.isDebugEnabled()) {
        log.debug("Compass embedded TopLink Essentials support active");
    }
}