Example usage for javax.persistence.spi PersistenceUnitInfo getClassLoader

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

Introduction

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

Prototype

public ClassLoader getClassLoader();

Source Link

Document

Returns ClassLoader that the provider may use to load any classes, resources, or open URLs.

Usage

From source file:org.batoo.jpa.parser.impl.acl.ClassloaderAnnotatedClassLocator.java

/**
 * {@inheritDoc}/* w ww . j  a  va  2s  .co  m*/
 * 
 */
@Override
public Set<Class<?>> locateClasses(PersistenceUnitInfo persistenceUnitInfo, URL url) {
    final String root = FilenameUtils.separatorsToUnix(FilenameUtils.normalize(url.getFile()));

    ClassloaderAnnotatedClassLocator.LOG.info("Checking persistence root {0} for persistence classes...", root);

    final HashSet<Class<?>> classes = Sets.newHashSet();
    try {
        return this.findClasses(persistenceUnitInfo.getClassLoader(), classes, root, root);
    } finally {
        ClassloaderAnnotatedClassLocator.LOG.info("Found persistent classes {0}", classes.toString());
    }
}

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 + "]");
    }/*ww w . ja v  a2 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");
    }
}

From source file:org.kuali.rice.krad.data.jpa.eclipselink.KradEclipseLinkEntityManagerFactoryBeanTest.java

@Test
public void testLoadTimeWeaving() throws Exception {
    loadContext(getClass().getSimpleName() + "_LoadTimeWeaving.xml");
    EntityManagerFactoryDelegate delegate = entityManagerFactory.unwrap(EntityManagerFactoryDelegate.class);
    PersistenceUnitInfo info = delegate.getSetupImpl().getPersistenceUnitInfo();
    assertTrue(info.getClassLoader() instanceof SimpleInstrumentableClassLoader);
}