Example usage for javax.persistence.spi PersistenceUnitTransactionType RESOURCE_LOCAL

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

Introduction

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

Prototype

PersistenceUnitTransactionType RESOURCE_LOCAL

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

Click Source Link

Document

Resource-local 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)
 *///from ww w  .j  a va  2 s  .  c o  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.EntityManagerFactoryBuilder.java

/**
 * Find persistence metadatas.//w  w  w.  ja  v  a2  s  . c o m
 * 
 * @return the list
 */
private List<PersistenceMetadata> findPersistenceMetadatas() {
    try {
        Enumeration<URL> xmls = Thread.currentThread().getContextClassLoader()
                .getResources("META-INF/persistence.xml");

        if (!xmls.hasMoreElements()) {
            log.info("Could not find any META-INF/persistence.xml " + "file in the classpath");
        }

        Set<String> persistenceUnitNames = new HashSet<String>();
        List<PersistenceMetadata> persistenceUnits = new ArrayList<PersistenceMetadata>();

        while (xmls.hasMoreElements()) {
            URL url = xmls.nextElement();
            log.trace("Analyse of persistence.xml: " + url);
            List<PersistenceMetadata> metadataFiles = PersistenceXmlLoader.findPersistenceUnits(url,
                    PersistenceUnitTransactionType.RESOURCE_LOCAL);

            // Pick only those that have Kundera Provider
            for (PersistenceMetadata metadata : metadataFiles) {
                // check for provider
                if (metadata.getProvider() == null
                        || PROVIDER_IMPLEMENTATION_NAME.equalsIgnoreCase(metadata.getProvider())) {
                    persistenceUnits.add(metadata);
                }

                // check for unique names
                if (persistenceUnitNames.contains(metadata.getName())) {
                    throw new PersistenceException(
                            "Duplicate persistence-units for name: " + metadata.getName());
                }
                persistenceUnitNames.add(metadata.getName());
            }
        }

        return persistenceUnits;
    } catch (Exception e) {
        if (e instanceof PersistenceException) {
            throw (PersistenceException) e;
        } else {
            throw new PersistenceException(e);
        }
    }
}

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

/**
 * Gets the transaction type.// w w  w.  ja v a 2 s. c  om
 * 
 * @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

/**
 * Parses the persistence unit./*from   www. j  av a2  s .  co  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:name.livitski.tools.persista.StorageBootstrap.java

/**
 * Returns the list of entity classes configured for this
 * object's {@link #getPersistenceUnit() persistence unit}
 * or an empty list if no classes have been configured.
 * Persistence unit's XML descriptor is expected to list
 * all its persistent classes explicitly.
 * @throws StorageConfigurationException if there is a problem
 * reading persistence unit configuration
 * @throws IllegalStateException if a persistent class cannot
 * be loaded//from   w  w  w. j av a2s  .  com
 */
public List<Class<?>> getEntityClasses() throws StorageConfigurationException {
    if (null == entities) {
        final ClassLoader loader = Thread.currentThread().getContextClassLoader();
        final URL resource = loader.getResource(PERSISTENCE_RESOURCE);
        if (null == resource)
            throw new IllegalStateException("Persistence metadata is not deployed in " + PERSISTENCE_RESOURCE);
        try {
            final String persistenceUnit = getPersistenceUnit();
            final List<PersistenceMetadata> descriptor = PersistenceXmlLoader.deploy(resource,
                    Collections.emptyMap(), new EntityResolverStub(log()),
                    PersistenceUnitTransactionType.RESOURCE_LOCAL);
            PersistenceMetadata source = null;
            for (PersistenceMetadata candidate : descriptor)
                if (candidate.getName().equals(persistenceUnit)) {
                    source = candidate;
                    break;
                }
            if (null == source)
                throw new ConfigurationException(
                        "Persistence unit '" + persistenceUnit + "' is not defined in " + resource + ". ");
            entities = new ArrayList<Class<?>>();
            for (String qName : source.getClasses())
                entities.add(Class.forName(qName, false, loader));
        } catch (ClassNotFoundException noclass) {
            throw new IllegalStateException("Could not load persistent class. " + noclass.getMessage(),
                    noclass);
        } catch (ConfigurationException e) {
            throw new StorageConfigurationException(this, e);
        } catch (Exception e) {
            throw new StorageConfigurationException(this,
                    "Error parsing persistence metadata at " + resource + ". " + e.getMessage(), e);
        }
    }
    return Collections.unmodifiableList(entities);
}

From source file:org.apache.shindig.social.opensocial.jpa.eclipselink.Bootstrap.java

public void init(String unitName) {

    Map<String, String> properties = Maps.newHashMap();

    // Ensure RESOURCE_LOCAL transactions is used.
    properties.put(TRANSACTION_TYPE, PersistenceUnitTransactionType.RESOURCE_LOCAL.name());

    // Configure the internal EclipseLink connection pool
    properties.put(JDBC_DRIVER, dbDriver);
    properties.put(JDBC_URL, dbUrl);
    properties.put(JDBC_USER, dbUser);/*  w  w  w. ja  va2  s .c  o  m*/
    properties.put(JDBC_PASSWORD, dbPassword);
    properties.put(JDBC_READ_CONNECTIONS_MIN, minRead);
    properties.put(JDBC_WRITE_CONNECTIONS_MIN, minWrite);

    // Configure logging. FINE ensures all SQL is shown
    properties.put(LOGGING_LEVEL, "FINE");
    properties.put(LOGGING_TIMESTAMP, "true");
    properties.put(LOGGING_THREAD, "false");
    properties.put(LOGGING_SESSION, "false");

    // Ensure that no server-platform is configured
    properties.put(TARGET_SERVER, TargetServer.None);

    properties.put(PersistenceUnitProperties.DDL_GENERATION, PersistenceUnitProperties.CREATE_ONLY);
    properties.put(PersistenceUnitProperties.DROP_JDBC_DDL_FILE, "drop.sql");
    properties.put(PersistenceUnitProperties.CREATE_JDBC_DDL_FILE, "create.sql");
    properties.put(PersistenceUnitProperties.DDL_GENERATION_MODE,
            PersistenceUnitProperties.DDL_BOTH_GENERATION);

    // properties.put(PersistenceUnitProperties.SESSION_CUSTOMIZER,
    // EnableIntegrityChecker.class.getName());

    LOG.info("Starting connection manager with properties " + properties);

    EntityManagerFactory emFactory = Persistence.createEntityManagerFactory(unitName, properties);
    entityManager = emFactory.createEntityManager();
}

From source file:org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.java

private void applyTransactionProperties() {
    PersistenceUnitTransactionType txnType = PersistenceUnitTransactionTypeHelper
            .interpretTransactionType(configurationValues.get(AvailableSettings.TRANSACTION_TYPE));
    if (txnType == null) {
        txnType = persistenceUnit.getTransactionType();
    }// w  w w.  j av  a2  s.  c  o  m
    if (txnType == null) {
        // is it more appropriate to have this be based on bootstrap entry
        // point (EE vs SE)?
        txnType = PersistenceUnitTransactionType.RESOURCE_LOCAL;
    }
    settings.setTransactionType(txnType);
    boolean hasTxStrategy = configurationValues.containsKey(Environment.TRANSACTION_STRATEGY);
    if (hasTxStrategy) {
        LOG.overridingTransactionStrategyDangerous(Environment.TRANSACTION_STRATEGY);
    } else {
        if (txnType == PersistenceUnitTransactionType.JTA) {
            serviceRegistryBuilder.applySetting(Environment.TRANSACTION_STRATEGY, CMTTransactionFactory.class);
        } else if (txnType == PersistenceUnitTransactionType.RESOURCE_LOCAL) {
            serviceRegistryBuilder.applySetting(Environment.TRANSACTION_STRATEGY, JdbcTransactionFactory.class);
        }
    }
}

From source file:org.jboss.ejb3.entity.PersistenceXmlLoader.java

public static List<PersistenceMetadata> deploy(URL url, Map overrides, EntityResolver resolver)
        throws Exception {
    return deploy(url, overrides, resolver, PersistenceUnitTransactionType.RESOURCE_LOCAL);
}

From source file:org.jboss.ejb3.entity.PersistenceXmlLoader.java

public static PersistenceUnitTransactionType getTransactionType(String elementContent) {
    if (StringHelper.isEmpty(elementContent)) {
        return null; //PersistenceUnitTransactionType.JTA;
    } else if (elementContent.equalsIgnoreCase("JTA")) {
        return PersistenceUnitTransactionType.JTA;
    } else if (elementContent.equalsIgnoreCase("RESOURCE_LOCAL")) {
        return PersistenceUnitTransactionType.RESOURCE_LOCAL;
    } else {//w w w .jav a2 s.co  m
        throw new PersistenceException("Unknown TransactionType: " + elementContent);
    }
}

From source file:org.sakaiproject.kernel.persistence.eclipselink.EntityManagerFactoryProvider.java

/**
 * Construct an EclipseLink entity manager provider.
 *
 * @param minRead/*from w w w. j  a  v  a  2s  .  c  om*/
 * @param minWrite
 * @param dataSourceService
 * @param unitName
 */
@Inject
@SuppressWarnings(value = {
        "DP_CREATE_CLASSLOADER_INSIDE_DO_PRIVILEGED" }, justification = "Expected to only ever be executed from a privalaged environment")
public EntityManagerFactoryProvider(DataSourceService dataSourceService,
        @Named(KernelConstants.DB_MIN_NUM_READ) String minRead,
        @Named(KernelConstants.DB_MIN_WRITE) String minWrite,
        @Named(KernelConstants.DB_UNITNAME) String unitName,
        @Named(KernelConstants.JDBC_DRIVER_NAME) String driverClassName,
        @Named(KernelConstants.JDBC_URL) String url, @Named(KernelConstants.JDBC_USERNAME) String username,
        @Named(KernelConstants.JDBC_PASSWORD) String password) {

    Map<String, Object> properties = new HashMap<String, Object>();

    // Ensure RESOURCE_LOCAL transactions is used.
    properties.put(TRANSACTION_TYPE, PersistenceUnitTransactionType.RESOURCE_LOCAL.name());

    LOG.info("Using provided data source");
    properties.put(dataSourceService.getType(), dataSourceService.getDataSource());

    // Configure the internal EclipseLink connection pool
    // LOG.info("Creating internal data source");
    // properties.put(PersistenceUnitProperties.JDBC_DRIVER, driverClassName);
    // properties.put(PersistenceUnitProperties.JDBC_URL, url);
    // properties.put(PersistenceUnitProperties.JDBC_USER, username);
    // properties.put(PersistenceUnitProperties.JDBC_PASSWORD, password);
    // properties
    // .put(PersistenceUnitProperties.JDBC_READ_CONNECTIONS_MIN, minRead);
    // properties.put(PersistenceUnitProperties.JDBC_WRITE_CONNECTIONS_MIN,
    // minWrite);

    // Configure logging. FINE ensures all SQL is shown
    properties.put(LOGGING_LEVEL, (debug ? "FINE" : "INFO"));
    properties.put(LOGGING_TIMESTAMP, "true");
    properties.put(LOGGING_THREAD, "true");
    properties.put(LOGGING_SESSION, "true");

    // Ensure that no server-platform is configured
    properties.put(TARGET_SERVER, TargetServer.None);

    properties.put(PersistenceUnitProperties.DDL_GENERATION, PersistenceUnitProperties.CREATE_ONLY);
    properties.put(PersistenceUnitProperties.DROP_JDBC_DDL_FILE, "drop.sql");
    properties.put(PersistenceUnitProperties.CREATE_JDBC_DDL_FILE, "create.sql");
    properties.put(PersistenceUnitProperties.DDL_GENERATION_MODE,
            PersistenceUnitProperties.DDL_BOTH_GENERATION);

    // properties.put(PersistenceUnitProperties.SESSION_CUSTOMIZER,
    // EnableIntegrityChecker.class.getName());

    LOG.info("Starting connection manager with properties " + properties);
    final Thread currentThread = Thread.currentThread();
    final ClassLoader saveClassLoader = currentThread.getContextClassLoader();

    PersistenceUnitClassLoader persistenceCL = new PersistenceUnitClassLoader(this.getClass().getClassLoader());
    currentThread.setContextClassLoader(persistenceCL);
    entityManagerFactory = Persistence.createEntityManagerFactory(unitName, properties);
    currentThread.setContextClassLoader(saveClassLoader);

}