Example usage for javax.persistence.spi PersistenceUnitTransactionType JTA

List of usage examples for javax.persistence.spi PersistenceUnitTransactionType JTA

Introduction

In this page you can find the example usage for javax.persistence.spi PersistenceUnitTransactionType JTA.

Prototype

PersistenceUnitTransactionType JTA

To view the source code for javax.persistence.spi PersistenceUnitTransactionType JTA.

Click Source Link

Document

JTA entity managers will be created.

Usage

From source file:com.hmed.config.JtaPersistenceUnitPostProcessor.java

/**
 * Enriches the PersistenceUnitInfo read from the <tt>persistence.xml</tt>
 * configuration file according to the <tt>jtaEnabled</tt> flag. Registers
 * the <tt>dataSource</tt> as a jta data source if it is <tt>true</tt> or
 * as a regular, non-jta data source otherwise.
 *
 * @see PersistenceUnitPostProcessor#postProcessPersistenceUnitInfo(org.springframework.orm.jpa.persistenceunit.MutablePersistenceUnitInfo)
 *//*w w w  . j  a v a  2 s  .  co m*/
public void postProcessPersistenceUnitInfo(MutablePersistenceUnitInfo mutablePersistenceUnitInfo) {
    if (jtaEnabled) {
        if (logger.isDebugEnabled()) {
            logger.debug("Enriching the persistence unit info with the jta aware data source.");
        }
        mutablePersistenceUnitInfo.setJtaDataSource(dataSource);
        mutablePersistenceUnitInfo.setTransactionType(PersistenceUnitTransactionType.JTA);
    } else {
        if (logger.isDebugEnabled()) {
            logger.debug("Enriching the persistence unit info with the non-jta aware data source.");

        }
        mutablePersistenceUnitInfo.setNonJtaDataSource(dataSource);
        mutablePersistenceUnitInfo.setTransactionType(PersistenceUnitTransactionType.RESOURCE_LOCAL);
    }
}

From source file:com.impetus.kundera.ejb.PersistenceXmlLoader.java

/**
 * Find persistence units.//from w  ww.  j av  a 2 s . c om
 * 
 * @param url
 *            the url
 * @return the list
 * @throws Exception
 *             the exception
 */
public static List<PersistenceMetadata> findPersistenceUnits(URL url) throws Exception {
    return findPersistenceUnits(url, PersistenceUnitTransactionType.JTA);
}

From source file:com.impetus.kundera.ejb.PersistenceXmlLoader.java

/**
 * Gets the transaction type./*from www . j a  va2 s.  c o  m*/
 * 
 * @param elementContent
 *            the element content
 * @return the transaction type
 */
public static PersistenceUnitTransactionType getTransactionType(String elementContent) {

    if (elementContent == null || elementContent.isEmpty()) {
        return null;
    } else if (elementContent.equalsIgnoreCase("JTA")) {
        return PersistenceUnitTransactionType.JTA;
    } else if (elementContent.equalsIgnoreCase("RESOURCE_LOCAL")) {
        return PersistenceUnitTransactionType.RESOURCE_LOCAL;
    } else {
        throw new PersistenceException("Unknown TransactionType: " + elementContent);
    }
}

From source file:com.impetus.kundera.loader.PersistenceXMLLoader.java

/**
 * Find persistence units.//from  w ww  . j a va 2  s. c  o  m
 * 
 * @param url
 *            the url
 * @return the list
 * @throws Exception
 *             the exception
 */
public static List<PersistenceUnitMetadata> findPersistenceUnits(URL url, final String[] persistenceUnits)
        throws Exception {
    return findPersistenceUnits(url, persistenceUnits, PersistenceUnitTransactionType.JTA);
}

From source file:com.impetus.kundera.loader.PersistenceXMLLoader.java

/**
 * Parses the persistence unit.//from  w  w w  .  j av  a2s . c  o m
 * 
 * @param top
 *            the top
 * @return the persistence metadata
 * @throws Exception
 *             the exception
 */
private static PersistenceUnitMetadata parsePersistenceUnit(final URL url, final String[] persistenceUnits,
        Element top, final String versionName) {
    PersistenceUnitMetadata metadata = new PersistenceUnitMetadata(versionName, getPersistenceRootUrl(url),
            url);

    String puName = top.getAttribute("name");

    if (!Arrays.asList(persistenceUnits).contains(puName)) {
        // Returning null because this persistence unit is not intended for
        // creating entity manager factory.
        return null;
    }

    if (!isEmpty(puName)) {
        log.trace("Persistent Unit name from persistence.xml: " + puName);
        metadata.setPersistenceUnitName(puName);
        String transactionType = top.getAttribute("transaction-type");
        if (StringUtils.isEmpty(transactionType)
                || PersistenceUnitTransactionType.RESOURCE_LOCAL.name().equals(transactionType)) {
            metadata.setTransactionType(PersistenceUnitTransactionType.RESOURCE_LOCAL);
        } else if (PersistenceUnitTransactionType.JTA.name().equals(transactionType)) {
            metadata.setTransactionType(PersistenceUnitTransactionType.JTA);
        }
    }

    NodeList children = top.getChildNodes();
    for (int i = 0; i < children.getLength(); i++) {
        if (children.item(i).getNodeType() == Node.ELEMENT_NODE) {
            Element element = (Element) children.item(i);
            String tag = element.getTagName();

            if (tag.equals("provider")) {
                metadata.setProvider(getElementContent(element));
            } else if (tag.equals("properties")) {
                NodeList props = element.getChildNodes();
                for (int j = 0; j < props.getLength(); j++) {
                    if (props.item(j).getNodeType() == Node.ELEMENT_NODE) {
                        Element propElement = (Element) props.item(j);
                        // if element is not "property" then skip
                        if (!"property".equals(propElement.getTagName())) {
                            continue;
                        }

                        String propName = propElement.getAttribute("name").trim();
                        String propValue = propElement.getAttribute("value").trim();
                        if (isEmpty(propValue)) {
                            propValue = getElementContent(propElement, "");
                        }
                        metadata.getProperties().put(propName, propValue);
                    }
                }
            } else if (tag.equals("class")) {
                metadata.getClasses().add(getElementContent(element));
            } else if (tag.equals("jar-file")) {
                metadata.addJarFile(getElementContent(element));
            } else if (tag.equals("exclude-unlisted-classes")) {
                String excludeUnlisted = getElementContent(element);
                metadata.setExcludeUnlistedClasses(Boolean.parseBoolean(excludeUnlisted));
            }
        }
    }
    PersistenceUnitTransactionType transactionType = getTransactionType(top.getAttribute("transaction-type"));
    if (transactionType != null) {
        metadata.setTransactionType(transactionType);
    }

    return metadata;
}

From source file:com.impetus.kundera.persistence.EntityManagerImpl.java

@Override
public final void clear() {
    checkClosed();/*from   w  ww.  ja  va  2 s.c  om*/

    // TODO Do we need a client and persistenceDelegator close here?
    if (!PersistenceUnitTransactionType.JTA.equals(this.transactionType)) {
        getPersistenceDelegator().clear();
    }
}

From source file:com.impetus.kundera.persistence.EntityManagerImpl.java

@Override
public final EntityTransaction getTransaction() {
    checkClosed();//from ww  w .  j a  v  a  2  s  . c om
    if (this.transactionType == PersistenceUnitTransactionType.JTA) {
        throw new IllegalStateException("A JTA EntityManager cannot use getTransaction()");
    }

    if (this.entityTransaction == null) {
        this.entityTransaction = new KunderaEntityTransaction(this);
    }
    return this.entityTransaction;
}

From source file:com.impetus.kundera.persistence.EntityManagerImpl.java

private void onLookUp(PersistenceUnitTransactionType transactionType) {
    // TODO transaction should not be null;
    if (transactionType != null && transactionType.equals(PersistenceUnitTransactionType.JTA)) {
        if (this.entityTransaction == null) {
            this.entityTransaction = new KunderaEntityTransaction(this);
        }/*from w  w w .java2 s .c  o  m*/
        Context ctx;
        try {
            ctx = new InitialContext();

            this.utx = (UserTransaction) ctx.lookup("java:comp/UserTransaction");

            if (this.utx == null) {
                throw new KunderaException(
                        "Lookup for UserTransaction returning null for :{java:comp/UserTransaction}");
            }
            // TODO what is need to check?
            if (!(this.utx instanceof KunderaJTAUserTransaction)) {
                throw new KunderaException("Please bind [" + KunderaJTAUserTransaction.class.getName()
                        + "] for :{java:comp/UserTransaction} lookup" + this.utx.getClass());
            }

            if (!this.entityTransaction.isActive()) {
                this.entityTransaction.begin();
                this.setFlushMode(FlushModeType.COMMIT);
                ((KunderaJTAUserTransaction) this.utx).setImplementor(this);
            }

        } catch (NamingException e) {
            logger.error("Error during initialization of entity manager, Caused by:", e);
            throw new KunderaException(e);
        }

    }
}

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  ww.  j a  v  a2  s .  c  om
    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
                + "]");
    }/*from w  w  w.jav a  2 s.c  om*/
    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");
    }
}